blob: 882d988ec796a241721f6dbe4acde3d225a53233 [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"
[email protected]fa1e0e12013-07-18 00:10:1415#include "base/message_loop/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]684fcc12013-03-08 22:50:0232#include "chrome/browser/omnibox/omnibox_field_trial.h"
[email protected]8ecad5e2010-12-02 21:18:3333#include "chrome/browser/profiles/profile.h"
[email protected]a7b8e43d2013-03-18 18:52:4334#include "chrome/browser/search/search.h"
[email protected]9899a612012-08-21 23:50:0435#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
[email protected]8e5c89a2011-06-07 18:13:3336#include "chrome/browser/search_engines/template_url_service.h"
37#include "chrome/browser/search_engines/template_url_service_factory.h"
[email protected]c4a9d4c2013-08-10 07:06:2738#include "chrome/browser/ui/browser.h"
39#include "chrome/browser/ui/browser_finder.h"
40#include "chrome/browser/ui/browser_instant_controller.h"
41#include "chrome/browser/ui/search/instant_controller.h"
[email protected]4f3b4462013-07-27 19:20:1842#include "chrome/common/net/url_fixer_upper.h"
initial.commit09911bf2008-07-26 23:55:2943#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0244#include "chrome/common/url_constants.h"
[email protected]34ac8f32009-02-22 23:03:2745#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2946#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3447#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5548#include "net/base/net_util.h"
[email protected]bd3b4712012-12-18 17:01:3049#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2150#include "net/http/http_response_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5351#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2152#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1753#include "ui/base/l10n/l10n_util.h"
[email protected]761fa4702013-07-02 15:25:1554#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2955
[email protected]bc8bb0cd2013-06-24 21:50:2356
57// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3358
[email protected]51124552011-07-16 01:37:1059namespace {
60
[email protected]7706a522012-08-16 17:42:2561// We keep track in a histogram how many suggest requests we send, how
62// many suggest requests we invalidate (e.g., due to a user typing
63// another character), and how many replies we receive.
64// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
65// (excluding the end-of-list enum value)
66// We do not want values of existing enums to change or else it screws
67// up the statistics.
68enum SuggestRequestsHistogramValue {
69 REQUEST_SENT = 1,
70 REQUEST_INVALIDATED,
71 REPLY_RECEIVED,
72 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
73};
74
[email protected]90fe2bb2013-01-15 03:42:1375// The verbatim score for an input which is not an URL.
76const int kNonURLVerbatimRelevance = 1300;
77
[email protected]7706a522012-08-16 17:42:2578// Increments the appropriate value in the histogram by one.
79void LogOmniboxSuggestRequest(
80 SuggestRequestsHistogramValue request_value) {
81 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
82 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
83}
84
[email protected]51124552011-07-16 01:37:1085bool HasMultipleWords(const string16& text) {
86 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
87 bool found_word = false;
88 if (i.Init()) {
89 while (i.Advance()) {
90 if (i.IsWord()) {
91 if (found_word)
92 return true;
93 found_word = true;
94 }
95 }
96 }
97 return false;
98}
99
[email protected]621ade062013-10-28 06:27:43100// Builds the match contents and classification for the contents, and updates
101// the given |AutocompleteMatch|.
102void SetAndClassifyMatchContents(const string16& query_string,
103 const string16& input_text,
104 const string16& match_contents,
105 const string16& annotation,
106 AutocompleteMatch* match) {
107 size_t match_contents_start = 0;
108 size_t annotation_start = match_contents.size();
109 // Append annotation if present.
110 if (annotation.empty()) {
111 match->contents = match_contents;
112 } else {
113 std::vector<size_t> positions;
114 match->contents = l10n_util::GetStringFUTF16(
115 IDS_ANNOTATED_SUGGESTION, match_contents, annotation, &positions);
116 match_contents_start = positions[0];
117 annotation_start = positions[1];
118 }
119 size_t match_contents_end = match_contents_start + match_contents.size();
120
121 if (!annotation.empty() && (annotation_start < match_contents_start))
122 match->contents_class.push_back(ACMatchClassification(
123 annotation_start, ACMatchClassification::DIM));
124
125 // We do intra-string highlighting for suggestions - the suggested segment
126 // will be highlighted, e.g. for input_text = "you" the suggestion may be
127 // "youtube", so we'll bold the "tube" section: you*tube*.
128 if (input_text != match_contents) {
129 size_t input_position = match->contents.substr(
130 match_contents_start, match_contents.length()).find(input_text);
131 if (input_position == string16::npos) {
132 // The input text is not a substring of the query string, e.g. input
133 // text is "slasdot" and the query string is "slashdot", so we bold the
134 // whole thing.
135 match->contents_class.push_back(ACMatchClassification(
136 match_contents_start, ACMatchClassification::MATCH));
137 } else {
138 input_position += match_contents_start;
139
140 // TODO(beng): ACMatchClassification::MATCH now seems to just mean
141 // "bold" this. Consider modifying the terminology.
142 // We don't iterate over the string here annotating all matches because
143 // it looks odd to have every occurrence of a substring that may be as
144 // short as a single character highlighted in a query suggestion result,
145 // e.g. for input text "s" and query string "southwest airlines", it
146 // looks odd if both the first and last s are highlighted.
147 if (input_position != match_contents_start) {
148 match->contents_class.push_back(ACMatchClassification(
149 match_contents_start, ACMatchClassification::MATCH));
150 }
151 match->contents_class.push_back(
152 ACMatchClassification(input_position, ACMatchClassification::NONE));
153 size_t next_fragment_position = input_position + input_text.length();
154 if (next_fragment_position < query_string.length()) {
155 match->contents_class.push_back(ACMatchClassification(
156 next_fragment_position, ACMatchClassification::MATCH));
157 }
158 }
159 } else {
160 // Otherwise, |match| is a verbatim (what-you-typed) match, either for the
161 // default provider or a keyword search provider.
162 match->contents_class.push_back(ACMatchClassification(
163 match_contents_start, ACMatchClassification::NONE));
164 }
165
166 if (!annotation.empty() && (annotation_start >= match_contents_start))
167 match->contents_class.push_back(ACMatchClassification(
168 match_contents_end, ACMatchClassification::DIM));
169}
170
[email protected]d1f0a7f2012-06-05 10:26:42171} // namespace
[email protected]51124552011-07-16 01:37:10172
[email protected]033f3422012-03-13 21:24:18173
[email protected]3954c3a2012-04-10 20:17:55174// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:58175
[email protected]85b8d6f2012-05-08 20:53:47176SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
177 : template_url_service_(template_url_service) {
178}
179
180const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
181 return default_provider_.empty() ? NULL :
182 template_url_service_->GetTemplateURLForKeyword(default_provider_);
183}
184
185const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
186 return keyword_provider_.empty() ? NULL :
187 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24188}
189
[email protected]3954c3a2012-04-10 20:17:55190
[email protected]bc8bb0cd2013-06-24 21:50:23191// SearchProvider::Result -----------------------------------------------------
192
193SearchProvider::Result::Result(bool from_keyword_provider,
[email protected]d30268a2013-06-25 22:31:07194 int relevance,
195 bool relevance_from_server)
[email protected]bc8bb0cd2013-06-24 21:50:23196 : from_keyword_provider_(from_keyword_provider),
[email protected]d30268a2013-06-25 22:31:07197 relevance_(relevance),
198 relevance_from_server_(relevance_from_server) {
[email protected]bc8bb0cd2013-06-24 21:50:23199}
200
201SearchProvider::Result::~Result() {
202}
203
204
205// SearchProvider::SuggestResult ----------------------------------------------
206
[email protected]621ade062013-10-28 06:27:43207SearchProvider::SuggestResult::SuggestResult(
208 const string16& suggestion,
209 const string16& match_contents,
210 const string16& annotation,
211 const std::string& suggest_query_params,
212 bool from_keyword_provider,
213 int relevance,
214 bool relevance_from_server,
215 bool should_prefetch)
[email protected]d30268a2013-06-25 22:31:07216 : Result(from_keyword_provider, relevance, relevance_from_server),
[email protected]987fad782013-08-28 06:23:18217 suggestion_(suggestion),
[email protected]621ade062013-10-28 06:27:43218 match_contents_(match_contents),
219 annotation_(annotation),
220 suggest_query_params_(suggest_query_params),
[email protected]987fad782013-08-28 06:23:18221 should_prefetch_(should_prefetch) {
[email protected]bc8bb0cd2013-06-24 21:50:23222}
223
224SearchProvider::SuggestResult::~SuggestResult() {
225}
226
227bool SearchProvider::SuggestResult::IsInlineable(const string16& input) const {
228 return StartsWith(suggestion_, input, false);
229}
230
231int SearchProvider::SuggestResult::CalculateRelevance(
232 const AutocompleteInput& input,
233 bool keyword_provider_requested) const {
234 if (!from_keyword_provider_ && keyword_provider_requested)
235 return 100;
236 return ((input.type() == AutocompleteInput::URL) ? 300 : 600);
237}
238
239
240// SearchProvider::NavigationResult -------------------------------------------
241
242SearchProvider::NavigationResult::NavigationResult(
243 const AutocompleteProvider& provider,
244 const GURL& url,
245 const string16& description,
246 bool from_keyword_provider,
[email protected]d30268a2013-06-25 22:31:07247 int relevance,
248 bool relevance_from_server)
249 : Result(from_keyword_provider, relevance, relevance_from_server),
[email protected]bc8bb0cd2013-06-24 21:50:23250 url_(url),
251 formatted_url_(AutocompleteInput::FormattedStringWithEquivalentMeaning(
252 url, provider.StringForURLDisplay(url, true, false))),
253 description_(description) {
254 DCHECK(url_.is_valid());
255}
256
257SearchProvider::NavigationResult::~NavigationResult() {
258}
259
260bool SearchProvider::NavigationResult::IsInlineable(
261 const string16& input) const {
262 return URLPrefix::BestURLPrefix(formatted_url_, input) != NULL;
263}
264
265int SearchProvider::NavigationResult::CalculateRelevance(
266 const AutocompleteInput& input,
267 bool keyword_provider_requested) const {
268 return (from_keyword_provider_ || !keyword_provider_requested) ? 800 : 150;
269}
270
271
272// SearchProvider::CompareScoredResults ---------------------------------------
273
274class SearchProvider::CompareScoredResults {
275 public:
276 bool operator()(const Result& a, const Result& b) {
277 // Sort in descending relevance order.
278 return a.relevance() > b.relevance();
279 }
280};
281
282
283// SearchProvider::Results ----------------------------------------------------
284
[email protected]d30268a2013-06-25 22:31:07285SearchProvider::Results::Results() : verbatim_relevance(-1) {
[email protected]bc8bb0cd2013-06-24 21:50:23286}
287
288SearchProvider::Results::~Results() {
289}
290
291void SearchProvider::Results::Clear() {
292 suggest_results.clear();
293 navigation_results.clear();
[email protected]bc8bb0cd2013-06-24 21:50:23294 verbatim_relevance = -1;
[email protected]987fad782013-08-28 06:23:18295 metadata.clear();
[email protected]bc8bb0cd2013-06-24 21:50:23296}
297
298bool SearchProvider::Results::HasServerProvidedScores() const {
299 if (verbatim_relevance >= 0)
300 return true;
301
[email protected]d30268a2013-06-25 22:31:07302 // Right now either all results of one type will be server-scored or they will
303 // all be locally scored, but in case we change this later, we'll just check
304 // them all.
305 for (SuggestResults::const_iterator i(suggest_results.begin());
306 i != suggest_results.end(); ++i) {
307 if (i->relevance_from_server())
308 return true;
309 }
310 for (NavigationResults::const_iterator i(navigation_results.begin());
311 i != navigation_results.end(); ++i) {
312 if (i->relevance_from_server())
313 return true;
314 }
315
316 return false;
[email protected]bc8bb0cd2013-06-24 21:50:23317}
[email protected]d30268a2013-06-25 22:31:07318
319
[email protected]3954c3a2012-04-10 20:17:55320// SearchProvider -------------------------------------------------------------
321
322// static
323const int SearchProvider::kDefaultProviderURLFetcherID = 1;
[email protected]3954c3a2012-04-10 20:17:55324const int SearchProvider::kKeywordProviderURLFetcherID = 2;
[email protected]24dbf2302013-04-05 16:59:25325int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]d30268a2013-06-25 22:31:07326const char SearchProvider::kRelevanceFromServerKey[] = "relevance_from_server";
[email protected]987fad782013-08-28 06:23:18327const char SearchProvider::kShouldPrefetchKey[] = "should_prefetch";
328const char SearchProvider::kSuggestMetadataKey[] = "suggest_metadata";
[email protected]d30268a2013-06-25 22:31:07329const char SearchProvider::kTrue[] = "true";
330const char SearchProvider::kFalse[] = "false";
[email protected]3954c3a2012-04-10 20:17:55331
[email protected]bc8bb0cd2013-06-24 21:50:23332SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
333 Profile* profile)
334 : AutocompleteProvider(listener, profile,
335 AutocompleteProvider::TYPE_SEARCH),
336 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
337 suggest_results_pending_(0),
[email protected]bc8bb0cd2013-06-24 21:50:23338 field_trial_triggered_(false),
[email protected]c4a9d4c2013-08-10 07:06:27339 field_trial_triggered_in_session_(false) {
[email protected]bc8bb0cd2013-06-24 21:50:23340}
341
[email protected]cb86ee6f2013-04-28 16:58:15342// static
343AutocompleteMatch SearchProvider::CreateSearchSuggestion(
[email protected]cb86ee6f2013-04-28 16:58:15344 AutocompleteProvider* autocomplete_provider,
[email protected]621ade062013-10-28 06:27:43345 const AutocompleteInput& input,
346 const string16& input_text,
[email protected]cb86ee6f2013-04-28 16:58:15347 int relevance,
348 AutocompleteMatch::Type type,
[email protected]621ade062013-10-28 06:27:43349 bool is_keyword,
350 const string16& match_contents,
351 const string16& annotation,
[email protected]bba9e632013-06-28 22:52:19352 const TemplateURL* template_url,
353 const string16& query_string,
[email protected]621ade062013-10-28 06:27:43354 const std::string& suggest_query_params,
[email protected]bba9e632013-06-28 22:52:19355 int accepted_suggestion,
[email protected]56fa29592013-07-02 20:25:53356 int omnibox_start_margin,
357 bool append_extra_query_params) {
[email protected]cb86ee6f2013-04-28 16:58:15358 AutocompleteMatch match(autocomplete_provider, relevance, false, type);
359
[email protected]bba9e632013-06-28 22:52:19360 if (!template_url)
[email protected]cb86ee6f2013-04-28 16:58:15361 return match;
[email protected]bba9e632013-06-28 22:52:19362 match.keyword = template_url->keyword();
[email protected]cb86ee6f2013-04-28 16:58:15363
[email protected]621ade062013-10-28 06:27:43364 SetAndClassifyMatchContents(
365 query_string, input_text, match_contents, annotation, &match);
366
367 match.allowed_to_be_default_match = (input_text == match_contents);
[email protected]cb86ee6f2013-04-28 16:58:15368
369 // When the user forced a query, we need to make sure all the fill_into_edit
370 // values preserve that property. Otherwise, if the user starts editing a
371 // suggestion, non-Search results will suddenly appear.
372 if (input.type() == AutocompleteInput::FORCED_QUERY)
373 match.fill_into_edit.assign(ASCIIToUTF16("?"));
374 if (is_keyword)
375 match.fill_into_edit.append(match.keyword + char16(' '));
376 if (!input.prevent_inline_autocomplete() &&
377 StartsWith(query_string, input_text, false)) {
[email protected]518024c2013-07-19 23:40:25378 match.inline_autocompletion = query_string.substr(input_text.length());
[email protected]45f89a92013-08-12 13:41:36379 match.allowed_to_be_default_match = true;
[email protected]cb86ee6f2013-04-28 16:58:15380 }
381 match.fill_into_edit.append(query_string);
382
[email protected]bba9e632013-06-28 22:52:19383 const TemplateURLRef& search_url = template_url->url_ref();
[email protected]cb86ee6f2013-04-28 16:58:15384 DCHECK(search_url.SupportsReplacement());
385 match.search_terms_args.reset(
386 new TemplateURLRef::SearchTermsArgs(query_string));
387 match.search_terms_args->original_query = input_text;
388 match.search_terms_args->accepted_suggestion = accepted_suggestion;
[email protected]f3e46eec2013-06-11 14:46:28389 match.search_terms_args->omnibox_start_margin = omnibox_start_margin;
[email protected]621ade062013-10-28 06:27:43390 match.search_terms_args->suggest_query_params = suggest_query_params;
[email protected]56fa29592013-07-02 20:25:53391 match.search_terms_args->append_extra_query_params =
392 append_extra_query_params;
[email protected]cb86ee6f2013-04-28 16:58:15393 // This is the destination URL sans assisted query stats. This must be set
394 // so the AutocompleteController can properly de-dupe; the controller will
395 // eventually overwrite it before it reaches the user.
396 match.destination_url =
397 GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get()));
398
399 // Search results don't look like URLs.
400 match.transition = is_keyword ?
401 content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED;
402
403 return match;
404}
405
[email protected]987fad782013-08-28 06:23:18406// static
407bool SearchProvider::ShouldPrefetch(const AutocompleteMatch& match) {
408 return match.GetAdditionalInfo(kShouldPrefetchKey) == kTrue;
409}
410
411// static
412std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
413 return match.GetAdditionalInfo(kSuggestMetadataKey);
414}
415
[email protected]bc8bb0cd2013-06-24 21:50:23416void SearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
417 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
418 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
419 new_entry.set_provider(AsOmniboxEventProviderType());
420 new_entry.set_provider_done(done_);
421 std::vector<uint32> field_trial_hashes;
422 OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(&field_trial_hashes);
423 for (size_t i = 0; i < field_trial_hashes.size(); ++i) {
424 if (field_trial_triggered_)
425 new_entry.mutable_field_trial_triggered()->Add(field_trial_hashes[i]);
426 if (field_trial_triggered_in_session_) {
427 new_entry.mutable_field_trial_triggered_in_session()->Add(
428 field_trial_hashes[i]);
429 }
430 }
431}
432
433void SearchProvider::ResetSession() {
434 field_trial_triggered_in_session_ = false;
[email protected]4ab4c7c2010-11-24 04:49:34435}
436
[email protected]bc8bb0cd2013-06-24 21:50:23437SearchProvider::~SearchProvider() {
438}
439
440// static
441void SearchProvider::RemoveStaleResults(const string16& input,
442 int verbatim_relevance,
443 SuggestResults* suggest_results,
444 NavigationResults* navigation_results) {
445 DCHECK_GE(verbatim_relevance, 0);
446 // Keep pointers to the head of (the highest scoring elements of)
447 // |suggest_results| and |navigation_results|. Iterate down the lists
448 // removing non-inlineable results in order of decreasing relevance
449 // scores. Stop when the highest scoring element among those remaining
450 // is inlineable or the element is less than |verbatim_relevance|.
451 // This allows non-inlineable lower-scoring results to remain
452 // because (i) they are guaranteed to not be inlined and (ii)
453 // letting them remain reduces visual jank. For instance, as the
454 // user types the mis-spelled query "fpobar" (for foobar), the
455 // suggestion "foobar" will be suggested on every keystroke. If the
456 // SearchProvider always removes all non-inlineable results, the user will
457 // see visual jitter/jank as the result disappears and re-appears moments
458 // later as the suggest server returns results.
459 SuggestResults::iterator sug_it = suggest_results->begin();
460 NavigationResults::iterator nav_it = navigation_results->begin();
461 while ((sug_it != suggest_results->end()) ||
462 (nav_it != navigation_results->end())) {
463 const int sug_rel =
464 (sug_it != suggest_results->end()) ? sug_it->relevance() : -1;
465 const int nav_rel =
466 (nav_it != navigation_results->end()) ? nav_it->relevance() : -1;
467 if (std::max(sug_rel, nav_rel) < verbatim_relevance)
468 break;
469 if (sug_rel > nav_rel) {
470 // The current top result is a search suggestion.
471 if (sug_it->IsInlineable(input))
472 break;
473 sug_it = suggest_results->erase(sug_it);
474 } else if (sug_rel == nav_rel) {
475 // Have both results and they're tied.
476 const bool sug_inlineable = sug_it->IsInlineable(input);
477 const bool nav_inlineable = nav_it->IsInlineable(input);
478 if (!sug_inlineable)
479 sug_it = suggest_results->erase(sug_it);
480 if (!nav_inlineable)
481 nav_it = navigation_results->erase(nav_it);
482 if (sug_inlineable || nav_inlineable)
483 break;
484 } else {
485 // The current top result is a navigational suggestion.
486 if (nav_it->IsInlineable(input))
487 break;
488 nav_it = navigation_results->erase(nav_it);
489 }
490 }
491}
492
493// static
494int SearchProvider::CalculateRelevanceForKeywordVerbatim(
495 AutocompleteInput::Type type,
496 bool prefer_keyword) {
497 // This function is responsible for scoring verbatim query matches
498 // for non-extension keywords. KeywordProvider::CalculateRelevance()
499 // scores verbatim query matches for extension keywords, as well as
500 // for keyword matches (i.e., suggestions of a keyword itself, not a
501 // suggestion of a query on a keyword search engine). These two
502 // functions are currently in sync, but there's no reason we
503 // couldn't decide in the future to score verbatim matches
504 // differently for extension and non-extension keywords. If you
505 // make such a change, however, you should update this comment to
506 // describe it, so it's clear why the functions diverge.
507 if (prefer_keyword)
508 return 1500;
509 return (type == AutocompleteInput::QUERY) ? 1450 : 1100;
510}
511
initial.commit09911bf2008-07-26 23:55:29512void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27513 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55514 // Do our best to load the model as early as possible. This will reduce
515 // odds of having the model not ready when really needed (a non-empty input).
516 TemplateURLService* model = providers_.template_url_service();
517 DCHECK(model);
518 model->Load();
519
initial.commit09911bf2008-07-26 23:55:29520 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57521 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29522
[email protected]6c85aa02009-02-27 12:08:09523 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29524 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]e29249dc52012-07-19 17:33:50525 Stop(false);
initial.commit09911bf2008-07-26 23:55:29526 return;
527 }
528
[email protected]14710852013-02-05 23:45:41529 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24530 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41531 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
532 &keyword_input_);
533 if (keyword_provider == NULL)
534 keyword_input_.Clear();
535 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24536 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24537
[email protected]85b8d6f2012-05-08 20:53:47538 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07539 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24540 default_provider = NULL;
541
542 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18543 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24544
545 if (!default_provider && !keyword_provider) {
546 // No valid providers.
[email protected]e29249dc52012-07-19 17:33:50547 Stop(false);
initial.commit09911bf2008-07-26 23:55:29548 return;
549 }
550
551 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24552 // or the providers, abort the query.
[email protected]85b8d6f2012-05-08 20:53:47553 string16 default_provider_keyword(default_provider ?
554 default_provider->keyword() : string16());
555 string16 keyword_provider_keyword(keyword_provider ?
556 keyword_provider->keyword() : string16());
[email protected]9e789742011-01-10 23:27:32557 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47558 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29559 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15560 if (!done_)
[email protected]e29249dc52012-07-19 17:33:50561 Stop(false);
[email protected]257ab712009-04-14 17:16:24562 }
initial.commit09911bf2008-07-26 23:55:29563
[email protected]85b8d6f2012-05-08 20:53:47564 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29565
566 if (input.text().empty()) {
567 // User typed "?" alone. Give them a placeholder result indicating what
568 // this syntax does.
[email protected]257ab712009-04-14 17:16:24569 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00570 AutocompleteMatch match;
571 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36572 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24573 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35574 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47575 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36576 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24577 matches_.push_back(match);
578 }
[email protected]e29249dc52012-07-19 17:33:50579 Stop(false);
initial.commit09911bf2008-07-26 23:55:29580 return;
581 }
582
583 input_ = input;
584
[email protected]e1290ee62013-06-26 18:31:15585 DoHistoryQuery(minimal_changes);
586 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42587 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29588}
589
[email protected]e29249dc52012-07-19 17:33:50590void SearchProvider::Stop(bool clear_cached_results) {
initial.commit09911bf2008-07-26 23:55:29591 StopSuggest();
592 done_ = true;
[email protected]e29249dc52012-07-19 17:33:50593
594 if (clear_cached_results)
[email protected]71b46152013-05-03 16:39:20595 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29596}
597
[email protected]10c2d692012-05-11 05:32:23598void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29599 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24600 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25601 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15602 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06603
[email protected]d7ad4772012-06-01 03:12:54604 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]f2916ea2013-01-26 02:20:14605 // Ensure the request succeeded and that the provider used is still available.
606 // A verbatim match cannot be generated without this provider, causing errors.
[email protected]013e9a02012-05-18 20:27:10607 const bool request_succeeded =
[email protected]bc8bb0cd2013-06-24 21:50:23608 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
609 (is_keyword ?
610 providers_.GetKeywordProviderURL() :
611 providers_.GetDefaultProviderURL());
[email protected]a0ad93ea2012-05-07 22:11:53612
613 // Record response time for suggest requests sent to Google. We care
614 // only about the common case: the Google default provider used in
615 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47616 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08617 if (!is_keyword && default_url &&
[email protected]628392f2013-08-16 00:34:45618 (TemplateURLPrepopulateData::GetEngineType(*default_url) ==
[email protected]9899a612012-08-21 23:50:04619 SEARCH_ENGINE_GOOGLE)) {
[email protected]bc8bb0cd2013-06-24 21:50:23620 const base::TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10621 base::TimeTicks::Now() - time_suggest_request_sent_;
622 if (request_succeeded) {
623 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
624 elapsed_time);
625 } else {
626 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
627 elapsed_time);
628 }
[email protected]b4cebf82008-12-29 19:59:08629 }
630
[email protected]d7ad4772012-06-01 03:12:54631 bool results_updated = false;
632 if (request_succeeded) {
[email protected]ed9b1802013-10-31 04:09:48633 const net::HttpResponseHeaders* const response_headers =
634 source->GetResponseHeaders();
635 std::string json_data;
636 source->GetResponseAsString(&json_data);
637 // JSON is supposed to be UTF-8, but some suggest service providers send
638 // JSON files in non-UTF-8 encodings. The actual encoding is usually
639 // specified in the Content-Type header field.
640 if (response_headers) {
641 std::string charset;
642 if (response_headers->GetCharset(&charset)) {
643 string16 data_16;
644 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
645 if (base::CodepageToUTF16(json_data, charset.c_str(),
646 base::OnStringConversionError::FAIL,
647 &data_16))
648 json_data = UTF16ToUTF8(data_16);
649 }
650 }
651
652 // The JSON response should be an array.
653 for (size_t response_start_index = json_data.find("["), i = 0;
654 response_start_index != std::string::npos && i < 5;
655 response_start_index = json_data.find("[", 1), i++) {
656 // Remove any XSSI guards to allow for JSON parsing.
657 if (response_start_index > 0)
658 json_data.erase(0, response_start_index);
659
660 JSONStringValueSerializer deserializer(json_data);
661 deserializer.set_allow_trailing_comma(true);
662 int error_code = 0;
663 scoped_ptr<Value> data(deserializer.Deserialize(&error_code, NULL));
664 if (error_code == 0) {
665 results_updated = data.get() &&
666 ParseSuggestResults(data.get(), is_keyword);
667 break;
668 }
669 }
[email protected]d7ad4772012-06-01 03:12:54670 }
671
[email protected]344946a12012-12-20 12:03:42672 UpdateMatches();
[email protected]d7ad4772012-06-01 03:12:54673 if (done_ || results_updated)
674 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29675}
676
[email protected]bc8bb0cd2013-06-24 21:50:23677void SearchProvider::Run() {
678 // Start a new request with the current input.
679 suggest_results_pending_ = 0;
680 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05681
[email protected]bc8bb0cd2013-06-24 21:50:23682 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
683 providers_.GetDefaultProviderURL(), input_));
684 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
685 providers_.GetKeywordProviderURL(), keyword_input_));
686
687 // Both the above can fail if the providers have been modified or deleted
688 // since the query began.
689 if (suggest_results_pending_ == 0) {
690 UpdateDone();
691 // We only need to update the listener if we're actually done.
692 if (done_)
693 listener_->OnProviderUpdate(false);
694 }
[email protected]601858c02010-09-01 17:08:20695}
696
[email protected]8d457132010-11-04 18:13:40697void SearchProvider::DoHistoryQuery(bool minimal_changes) {
698 // The history query results are synchronous, so if minimal_changes is true,
699 // we still have the last results and don't need to do anything.
700 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29701 return;
702
[email protected]31afdf72013-09-26 04:29:36703 base::TimeTicks do_history_query_start_time(base::TimeTicks::Now());
704
[email protected]8d457132010-11-04 18:13:40705 keyword_history_results_.clear();
706 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29707
[email protected]78e5e432013-08-03 02:10:10708 if (OmniboxFieldTrial::SearchHistoryDisable(
709 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16710 return;
711
[email protected]31afdf72013-09-26 04:29:36712 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]8d457132010-11-04 18:13:40713 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10714 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]31afdf72013-09-26 04:29:36715 base::TimeTicks now(base::TimeTicks::Now());
716 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.GetHistoryServiceTime",
717 now - start_time);
718 start_time = now;
[email protected]8d457132010-11-04 18:13:40719 history::URLDatabase* url_db = history_service ?
720 history_service->InMemoryDatabase() : NULL;
[email protected]31afdf72013-09-26 04:29:36721 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.InMemoryDatabaseTime",
722 base::TimeTicks::Now() - start_time);
[email protected]8d457132010-11-04 18:13:40723 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29724 return;
725
[email protected]51124552011-07-16 01:37:10726 // Request history for both the keyword and default provider. We grab many
727 // more matches than we'll ultimately clamp to so that if there are several
728 // recent multi-word matches who scores are lowered (see
729 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
730 // matches. Note that this doesn't fix the problem entirely, but merely
731 // limits it to cases with a very large number of such multi-word matches; for
732 // now, this seems OK compared with the complexity of a real fix, which would
733 // require multiple searches and tracking of "single- vs. multi-word" in the
734 // database.
735 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47736 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
737 if (default_url) {
[email protected]31afdf72013-09-26 04:29:36738 start_time = base::TimeTicks::Now();
[email protected]85b8d6f2012-05-08 20:53:47739 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
740 num_matches, &default_history_results_);
[email protected]31afdf72013-09-26 04:29:36741 UMA_HISTOGRAM_TIMES(
742 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
743 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24744 }
[email protected]85b8d6f2012-05-08 20:53:47745 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
746 if (keyword_url) {
747 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41748 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55749 }
[email protected]31afdf72013-09-26 04:29:36750 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.DoHistoryQueryTime",
751 base::TimeTicks::Now() - do_history_query_start_time);
initial.commit09911bf2008-07-26 23:55:29752}
753
[email protected]6dc950f2012-07-16 19:49:08754void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34755 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29756 StopSuggest();
[email protected]71b46152013-05-03 16:39:20757 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29758 return;
759 }
760
761 // For the minimal_changes case, if we finished the previous query and still
762 // have its results, or are allowed to keep running it, just do that, rather
763 // than starting a new query.
764 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24765 (!default_results_.suggest_results.empty() ||
766 !default_results_.navigation_results.empty() ||
767 !keyword_results_.suggest_results.empty() ||
768 !keyword_results_.navigation_results.empty() ||
[email protected]ea3b9a502011-04-04 14:19:37769 (!done_ &&
770 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29771 return;
772
773 // We can't keep running any previous query, so halt it.
774 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42775
776 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20777 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29778
779 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37780 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29781 return;
782
[email protected]24dbf2302013-04-05 16:59:25783 // To avoid flooding the suggest server, don't send a query until at
784 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24785 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
[email protected]bc8bb0cd2013-06-24 21:50:23786 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
[email protected]515ffa942012-11-27 20:18:24787 base::TimeTicks now(base::TimeTicks::Now());
788 if (now >= next_suggest_time) {
789 Run();
790 return;
791 }
792 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29793}
794
[email protected]83c726482008-09-10 06:36:34795bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55796 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
797 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47798 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
799 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34800 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47801 ((!default_url || default_url->suggestions_url().empty()) &&
802 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34803 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
804 return false;
805
[email protected]cac59d32010-08-09 23:23:14806 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34807 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34808
[email protected]cac59d32010-08-09 23:23:14809 // FORCED_QUERY means the user is explicitly asking us to search for this, so
810 // we assume it isn't a URL and/or there isn't private data.
811 if (input_.type() == AutocompleteInput::FORCED_QUERY)
812 return true;
[email protected]83c726482008-09-10 06:36:34813
[email protected]f608ea102013-03-18 15:08:09814 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
815 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
816 // is both a waste of time and a disclosure of potentially private, local
817 // data. Other "schemes" may actually be usernames, and we don't want to send
818 // passwords. If the scheme is OK, we still need to check other cases below.
819 // If this is QUERY, then the presence of these schemes means the user
820 // explicitly typed one, and thus this is probably a URL that's being entered
821 // and happens to currently be invalid -- in which case we again want to run
822 // our checks below. Other QUERY cases are less likely to be URLs and thus we
823 // assume we're OK.
[email protected]e9a82042013-09-15 03:38:29824 if (!LowerCaseEqualsASCII(input_.scheme(), content::kHttpScheme) &&
[email protected]4654bfe2013-08-26 03:36:58825 !LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36826 !LowerCaseEqualsASCII(input_.scheme(), chrome::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14827 return (input_.type() == AutocompleteInput::QUERY);
828
829 // Don't send URLs with usernames, queries or refs. Some of these are
830 // private, and the Suggest server is unlikely to have any useful results
831 // for any of them. Also don't send URLs with ports, as we may initially
832 // think that a username + password is a host + port (and we don't want to
833 // send usernames/passwords), and even if the port really is a port, the
834 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58835 // Note that we only block based on refs if the input is URL-typed, as search
836 // queries can legitimately have #s in them which the URL parser
837 // overaggressively categorizes as a url with a ref.
[email protected]cac59d32010-08-09 23:23:14838 const url_parse::Parsed& parts = input_.parts();
839 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58840 parts.query.is_nonempty() ||
841 (parts.ref.is_nonempty() && (input_.type() == AutocompleteInput::URL)))
[email protected]cac59d32010-08-09 23:23:14842 return false;
843
844 // Don't send anything for https except the hostname. Hostnames are OK
845 // because they are visible when the TCP connection is established, but the
846 // specific path may reveal private information.
[email protected]4654bfe2013-08-26 03:36:58847 if (LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36848 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14849 return false;
[email protected]83c726482008-09-10 06:36:34850
851 return true;
852}
853
initial.commit09911bf2008-07-26 23:55:29854void SearchProvider::StopSuggest() {
[email protected]7706a522012-08-16 17:42:25855 // Increment the appropriate field in the histogram by the number of
856 // pending requests that were invalidated.
857 for (int i = 0; i < suggest_results_pending_; i++)
858 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
[email protected]257ab712009-04-14 17:16:24859 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14860 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24861 // Stop any in-progress URL fetches.
862 keyword_fetcher_.reset();
863 default_fetcher_.reset();
[email protected]55ce8f12012-05-09 04:44:08864}
865
[email protected]71b46152013-05-03 16:39:20866void SearchProvider::ClearAllResults() {
[email protected]cc1526e2013-05-17 04:04:24867 keyword_results_.Clear();
868 default_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51869}
870
[email protected]71b46152013-05-03 16:39:20871void SearchProvider::RemoveAllStaleResults() {
[email protected]1e1550e2013-05-02 17:37:51872 // In theory it would be better to run an algorithm like that in
873 // RemoveStaleResults(...) below that uses all four results lists
874 // and both verbatim scores at once. However, that will be much
875 // more complicated for little obvious gain. For code simplicity
876 // and ease in reasoning about the invariants involved, this code
877 // removes stales results from the keyword provider and default
878 // provider independently.
[email protected]d30268a2013-06-25 22:31:07879 RemoveStaleResults(input_.text(), GetVerbatimRelevance(NULL),
[email protected]cc1526e2013-05-17 04:04:24880 &default_results_.suggest_results,
881 &default_results_.navigation_results);
[email protected]1e1550e2013-05-02 17:37:51882 if (!keyword_input_.text().empty()) {
[email protected]d30268a2013-06-25 22:31:07883 RemoveStaleResults(keyword_input_.text(), GetKeywordVerbatimRelevance(NULL),
[email protected]cc1526e2013-05-17 04:04:24884 &keyword_results_.suggest_results,
885 &keyword_results_.navigation_results);
[email protected]1e1550e2013-05-02 17:37:51886 } else {
887 // User is either in keyword mode with a blank input or out of
888 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24889 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51890 }
[email protected]d1f0a7f2012-06-05 10:26:42891}
892
[email protected]d1f0a7f2012-06-05 10:26:42893void SearchProvider::ApplyCalculatedRelevance() {
[email protected]cc1526e2013-05-17 04:04:24894 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
895 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
896 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
897 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
[email protected]cc1526e2013-05-17 04:04:24898 default_results_.verbatim_relevance = -1;
899 keyword_results_.verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42900}
901
[email protected]188b50c2013-03-28 07:19:42902void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42903 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42904 SuggestResult& result = (*list)[i];
905 result.set_relevance(
906 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
907 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07908 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42909 }
910}
911
[email protected]188b50c2013-03-28 07:19:42912void SearchProvider::ApplyCalculatedNavigationRelevance(
913 NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42914 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42915 NavigationResult& result = (*list)[i];
916 result.set_relevance(
917 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
918 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07919 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42920 }
921}
922
[email protected]15fb2aa2012-05-22 22:52:59923net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12924 int id,
[email protected]9ff91722012-09-07 05:29:12925 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41926 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12927 if (!template_url || template_url->suggestions_url().empty())
928 return NULL;
929
930 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41931 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
932 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18933 search_term_args.page_classification = input.current_page_classification();
[email protected]9ff91722012-09-07 05:29:12934 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:16935 search_term_args));
[email protected]9ff91722012-09-07 05:29:12936 if (!suggest_url.is_valid())
937 return NULL;
938
939 suggest_results_pending_++;
940 LogOmniboxSuggestRequest(REQUEST_SENT);
941
942 net::URLFetcher* fetcher =
943 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12944 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34945 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30946 // Add Chrome experiment state to the request headers.
947 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:09948 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30949 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
950 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24951 fetcher->Start();
952 return fetcher;
953}
954
[email protected]d7ad4772012-06-01 03:12:54955bool SearchProvider::ParseSuggestResults(Value* root_val, bool is_keyword) {
[email protected]d7ad4772012-06-01 03:12:54956 string16 query;
957 ListValue* root_list = NULL;
[email protected]cc1526e2013-05-17 04:04:24958 ListValue* results_list = NULL;
[email protected]14710852013-02-05 23:45:41959 const string16& input_text =
960 is_keyword ? keyword_input_.text() : input_.text();
[email protected]d7ad4772012-06-01 03:12:54961 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
[email protected]cc1526e2013-05-17 04:04:24962 (query != input_text) || !root_list->GetList(1, &results_list))
initial.commit09911bf2008-07-26 23:55:29963 return false;
964
[email protected]55ce8f12012-05-09 04:44:08965 // 3rd element: Description list.
[email protected]d7ad4772012-06-01 03:12:54966 ListValue* descriptions = NULL;
967 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:29968
[email protected]55ce8f12012-05-09 04:44:08969 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:29970
[email protected]d1f0a7f2012-06-05 10:26:42971 // Reset suggested relevance information from the default provider.
[email protected]cc1526e2013-05-17 04:04:24972 Results* results = is_keyword ? &keyword_results_ : &default_results_;
[email protected]cc1526e2013-05-17 04:04:24973 results->verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42974
[email protected]55ce8f12012-05-09 04:44:08975 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]d7ad4772012-06-01 03:12:54976 ListValue* types = NULL;
[email protected]d1f0a7f2012-06-05 10:26:42977 ListValue* relevances = NULL;
[email protected]621ade062013-10-28 06:27:43978 ListValue* suggestion_details = NULL;
[email protected]d1f0a7f2012-06-05 10:26:42979 DictionaryValue* extras = NULL;
[email protected]987fad782013-08-28 06:23:18980 int prefetch_index = -1;
[email protected]d1f0a7f2012-06-05 10:26:42981 if (root_list->GetDictionary(4, &extras)) {
982 extras->GetList("google:suggesttype", &types);
983
[email protected]eb8330d2013-06-15 00:55:08984 // Discard this list if its size does not match that of the suggestions.
985 if (extras->GetList("google:suggestrelevance", &relevances) &&
[email protected]621ade062013-10-28 06:27:43986 (relevances->GetSize() != results_list->GetSize()))
[email protected]eb8330d2013-06-15 00:55:08987 relevances = NULL;
988 extras->GetInteger("google:verbatimrelevance",
989 &results->verbatim_relevance);
[email protected]618d6e62012-12-16 05:55:57990
991 // Check if the active suggest field trial (if any) has triggered either
992 // for the default provider or keyword provider.
993 bool triggered = false;
994 extras->GetBoolean("google:fieldtrialtriggered", &triggered);
995 field_trial_triggered_ |= triggered;
996 field_trial_triggered_in_session_ |= triggered;
[email protected]987fad782013-08-28 06:23:18997
[email protected]987fad782013-08-28 06:23:18998 DictionaryValue* client_data = NULL;
999 if (extras->GetDictionary("google:clientdata", &client_data) && client_data)
1000 client_data->GetInteger("phi", &prefetch_index);
1001
[email protected]621ade062013-10-28 06:27:431002 if (extras->GetList("google:suggestdetail", &suggestion_details) &&
1003 suggestion_details->GetSize() != results_list->GetSize())
1004 suggestion_details = NULL;
1005
[email protected]987fad782013-08-28 06:23:181006 // Store the metadata that came with the response in case we need to pass it
1007 // along with the prefetch query to Instant.
1008 JSONStringValueSerializer json_serializer(&results->metadata);
1009 json_serializer.Serialize(*extras);
initial.commit09911bf2008-07-26 23:55:291010 }
1011
[email protected]d1f0a7f2012-06-05 10:26:421012 // Clear the previous results now that new results are available.
[email protected]cc1526e2013-05-17 04:04:241013 results->suggest_results.clear();
1014 results->navigation_results.clear();
[email protected]d1f0a7f2012-06-05 10:26:421015
[email protected]621ade062013-10-28 06:27:431016 string16 suggestion;
[email protected]d1f0a7f2012-06-05 10:26:421017 std::string type;
1018 int relevance = -1;
[email protected]3f381592013-11-05 20:43:511019 // Prohibit navsuggest in FORCED_QUERY mode. Users wants queries, not URLs.
1020 const bool allow_navsuggest =
1021 (is_keyword ? keyword_input_.type() : input_.type()) !=
1022 AutocompleteInput::FORCED_QUERY;
[email protected]621ade062013-10-28 06:27:431023 for (size_t index = 0; results_list->GetString(index, &suggestion); ++index) {
[email protected]8e81f5092010-09-29 23:19:401024 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:081025 // they make no sense at all and can cause problems in our code.
[email protected]621ade062013-10-28 06:27:431026 if (suggestion.empty())
[email protected]8e81f5092010-09-29 23:19:401027 continue;
1028
[email protected]d1f0a7f2012-06-05 10:26:421029 // Apply valid suggested relevance scores; discard invalid lists.
1030 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
1031 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:541032 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:421033 // Do not blindly trust the URL coming from the server to be valid.
[email protected]621ade062013-10-28 06:27:431034 GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(suggestion), std::string()));
[email protected]3f381592013-11-05 20:43:511035 if (url.is_valid() && allow_navsuggest) {
[email protected]621ade062013-10-28 06:27:431036 string16 title;
[email protected]d1f0a7f2012-06-05 10:26:421037 if (descriptions != NULL)
1038 descriptions->GetString(index, &title);
[email protected]d30268a2013-06-25 22:31:071039 results->navigation_results.push_back(NavigationResult(
1040 *this, url, title, is_keyword, relevance, true));
initial.commit09911bf2008-07-26 23:55:291041 }
1042 } else {
[email protected]987fad782013-08-28 06:23:181043 bool should_prefetch = static_cast<int>(index) == prefetch_index;
[email protected]621ade062013-10-28 06:27:431044 DictionaryValue* suggestion_detail = NULL;
1045 string16 match_contents = suggestion;
1046 string16 disambiguating_query;
1047 string16 annotation;
1048 std::string suggest_query_params;
1049 if (suggestion_details && (type == "ENTITY") &&
1050 suggestion_details->GetDictionary(index, &suggestion_detail) &&
1051 suggestion_detail) {
1052 suggestion_detail->GetString("a", &annotation);
1053 if (suggestion_detail->GetString("dq", &disambiguating_query) &&
1054 !disambiguating_query.empty())
1055 suggestion = disambiguating_query;
1056 suggestion_detail->GetString("q", &suggest_query_params);
1057 }
1058 // TODO(kochi): Improve calculator suggestion presentation.
1059 results->suggest_results.push_back(SuggestResult(
1060 suggestion, match_contents, annotation, suggest_query_params,
1061 is_keyword, relevance, true, should_prefetch));
initial.commit09911bf2008-07-26 23:55:291062 }
1063 }
1064
[email protected]d1f0a7f2012-06-05 10:26:421065 // Apply calculated relevance scores if a valid list was not provided.
1066 if (relevances == NULL) {
[email protected]cc1526e2013-05-17 04:04:241067 ApplyCalculatedSuggestRelevance(&results->suggest_results);
1068 ApplyCalculatedNavigationRelevance(&results->navigation_results);
[email protected]d1f0a7f2012-06-05 10:26:421069 }
[email protected]9dfb4d362013-04-05 02:15:121070 // Keep the result lists sorted.
1071 const CompareScoredResults comparator = CompareScoredResults();
[email protected]cc1526e2013-05-17 04:04:241072 std::stable_sort(results->suggest_results.begin(),
1073 results->suggest_results.end(),
[email protected]9dfb4d362013-04-05 02:15:121074 comparator);
[email protected]cc1526e2013-05-17 04:04:241075 std::stable_sort(results->navigation_results.begin(),
1076 results->navigation_results.end(),
[email protected]9dfb4d362013-04-05 02:15:121077 comparator);
[email protected]d1f0a7f2012-06-05 10:26:421078 return true;
initial.commit09911bf2008-07-26 23:55:291079}
1080
[email protected]344946a12012-12-20 12:03:421081void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:291082 // Convert all the results to matches and add them to a map, so we can keep
1083 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:361084 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:291085 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:231086 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:241087 int did_not_accept_keyword_suggestion =
1088 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:291089 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
1090 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:291091
[email protected]d30268a2013-06-25 22:31:071092 bool relevance_from_server;
1093 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:241094 int did_not_accept_default_suggestion =
1095 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:081096 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
1097 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:421098 if (verbatim_relevance > 0) {
[email protected]621ade062013-10-28 06:27:431099 AddMatchToMap(input_.text(),
1100 verbatim_relevance,
1101 relevance_from_server,
1102 false,
1103 std::string(),
[email protected]b7f64d742013-05-21 04:04:041104 AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]621ade062013-10-28 06:27:431105 false,
1106 input_.text(),
1107 string16(),
1108 input_.text(),
1109 did_not_accept_default_suggestion,
1110 std::string(),
1111 &map);
[email protected]d1f0a7f2012-06-05 10:26:421112 }
[email protected]5423e562013-02-07 03:58:451113 if (!keyword_input_.text().empty()) {
1114 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1115 // We only create the verbatim search query match for a keyword
1116 // if it's not an extension keyword. Extension keywords are handled
1117 // in KeywordProvider::Start(). (Extensions are complicated...)
1118 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
1119 // to the keyword verbatim search query. Do not create other matches
1120 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:251121 if (keyword_url &&
1122 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:071123 bool keyword_relevance_from_server;
1124 const int keyword_verbatim_relevance =
1125 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:281126 if (keyword_verbatim_relevance > 0) {
[email protected]621ade062013-10-28 06:27:431127 AddMatchToMap(keyword_input_.text(),
1128 keyword_verbatim_relevance,
1129 keyword_relevance_from_server,
1130 false,
1131 std::string(),
[email protected]b7f64d742013-05-21 04:04:041132 AutocompleteMatchType::SEARCH_OTHER_ENGINE,
[email protected]621ade062013-10-28 06:27:431133 true,
1134 keyword_input_.text(),
1135 string16(),
1136 keyword_input_.text(),
1137 did_not_accept_keyword_suggestion,
1138 std::string(),
1139 &map);
[email protected]dab8d52d2013-03-05 07:35:281140 }
[email protected]5423e562013-02-07 03:58:451141 }
1142 }
[email protected]257ab712009-04-14 17:16:241143 AddHistoryResultsToMap(keyword_history_results_, true,
1144 did_not_accept_keyword_suggestion, &map);
1145 AddHistoryResultsToMap(default_history_results_, false,
1146 did_not_accept_default_suggestion, &map);
1147
[email protected]d1cb6a822013-09-18 19:43:001148 AddSuggestResultsToMap(keyword_results_.suggest_results,
1149 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:181150 AddSuggestResultsToMap(default_results_.suggest_results,
1151 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:291152
[email protected]d30268a2013-06-25 22:31:071153 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:291154 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:071155 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:291156
[email protected]d30268a2013-06-25 22:31:071157 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
1158 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:291159
[email protected]d30268a2013-06-25 22:31:071160 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
1161 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
1162 // enabled and we have server-provided (and thus hopefully more accurate)
1163 // scores for some suggestions, we allow more of those, until we reach
1164 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
1165 // whole popup).
1166 //
1167 // We will always return any verbatim matches, no matter how we obtained their
1168 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
1169 // higher-scoring matches under the conditions above.
[email protected]31afdf72013-09-26 04:29:361170 UMA_HISTOGRAM_CUSTOM_COUNTS(
1171 "Omnibox.SearchProvider.NumMatchesToSort", matches.size(), 1, 50, 20);
[email protected]d30268a2013-06-25 22:31:071172 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
1173 matches_.clear();
[email protected]3723e6e2012-06-11 21:06:561174
[email protected]d30268a2013-06-25 22:31:071175 size_t num_suggestions = 0;
1176 for (ACMatches::const_iterator i(matches.begin());
1177 (i != matches.end()) &&
1178 (matches_.size() < AutocompleteResult::kMaxMatches);
1179 ++i) {
1180 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
1181 // verbatim result, so this condition basically means "if this match is a
1182 // suggestion of some sort".
1183 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
1184 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
1185 // If we've already hit the limit on non-server-scored suggestions, and
1186 // this isn't a server-scored suggestion we can add, skip it.
1187 if ((num_suggestions >= kMaxMatches) &&
1188 (!chrome::IsInstantExtendedAPIEnabled() ||
1189 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
1190 continue;
1191 }
1192
1193 ++num_suggestions;
1194 }
1195
1196 matches_.push_back(*i);
1197 }
[email protected]31afdf72013-09-26 04:29:361198 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
1199 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:421200}
1201
[email protected]9dfb4d362013-04-05 02:15:121202bool SearchProvider::IsTopMatchNavigationInKeywordMode() const {
1203 return (!providers_.keyword_provider().empty() &&
[email protected]b7f64d742013-05-21 04:04:041204 (matches_.front().type == AutocompleteMatchType::NAVSUGGEST));
[email protected]9dfb4d362013-04-05 02:15:121205}
1206
[email protected]344946a12012-12-20 12:03:421207bool SearchProvider::IsTopMatchScoreTooLow() const {
[email protected]dab8d52d2013-03-05 07:35:281208 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
1209 // rather than CalculateRelevanceForVerbatim() because the latter returns
1210 // a very low score (250) if keyword mode is active. This is because
1211 // when keyword mode is active the user probably wants the keyword matches,
1212 // not matches from the default provider. Hence, we use the version of
1213 // the function that ignores whether keyword mode is active. This allows
1214 // SearchProvider to maintain its contract with the AutocompleteController
1215 // that it will always provide an inlineable match with a reasonable
1216 // score.
1217 return matches_.front().relevance <
1218 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
[email protected]344946a12012-12-20 12:03:421219}
1220
[email protected]fb95251e2013-07-17 14:52:241221bool SearchProvider::IsTopMatchSearchWithURLInput() const {
[email protected]344946a12012-12-20 12:03:421222 return input_.type() == AutocompleteInput::URL &&
1223 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
[email protected]fb95251e2013-07-17 14:52:241224 matches_.front().type != AutocompleteMatchType::NAVSUGGEST;
[email protected]344946a12012-12-20 12:03:421225}
1226
[email protected]45f89a92013-08-12 13:41:361227bool SearchProvider::HasValidDefaultMatch(
1228 bool autocomplete_result_will_reorder_for_default_match) const {
1229 // One of the SearchProvider matches may need to be the overall default. If
1230 // AutocompleteResult is allowed to reorder matches, this means we simply
1231 // need at least one match in the list to be |allowed_to_be_default_match|.
1232 // If no reordering is possible, however, then our first match needs to have
1233 // this flag.
1234 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
1235 ++it) {
1236 if (it->allowed_to_be_default_match)
1237 return true;
1238 if (!autocomplete_result_will_reorder_for_default_match)
1239 return false;
1240 }
1241 return false;
[email protected]344946a12012-12-20 12:03:421242}
1243
1244void SearchProvider::UpdateMatches() {
[email protected]31afdf72013-09-26 04:29:361245 base::TimeTicks update_matches_start_time(base::TimeTicks::Now());
[email protected]344946a12012-12-20 12:03:421246 ConvertResultsToAutocompleteMatches();
initial.commit09911bf2008-07-26 23:55:291247
[email protected]382a0642012-06-06 06:13:521248 // Check constraints that may be violated by suggested relevances.
[email protected]344946a12012-12-20 12:03:421249 if (!matches_.empty() &&
[email protected]bc8bb0cd2013-06-24 21:50:231250 (default_results_.HasServerProvidedScores() ||
1251 keyword_results_.HasServerProvidedScores())) {
[email protected]9dfb4d362013-04-05 02:15:121252 // These blocks attempt to repair undesirable behavior by suggested
[email protected]344946a12012-12-20 12:03:421253 // relevances with minimal impact, preserving other suggested relevances.
[email protected]9dfb4d362013-04-05 02:15:121254 if (IsTopMatchNavigationInKeywordMode()) {
1255 // Correct the suggested relevance scores if the top match is a
1256 // navigation in keyword mode, since inlining a navigation match
1257 // would break the user out of keyword mode. By the way, if the top
1258 // match is a non-keyword match (query or navsuggestion) in keyword
1259 // mode, the user would also break out of keyword mode. However,
1260 // that situation is impossible given the current scoring paradigm
1261 // and the fact that only one search engine (Google) provides suggested
1262 // relevance scores at this time.
1263 DemoteKeywordNavigationMatchesPastTopQuery();
1264 ConvertResultsToAutocompleteMatches();
1265 DCHECK(!IsTopMatchNavigationInKeywordMode());
1266 }
[email protected]45f89a92013-08-12 13:41:361267 // True if the omnibox will reorder matches as necessary to make the top
1268 // one something that is allowed to be the default match.
1269 const bool omnibox_will_reorder_for_legal_default_match =
1270 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
1271 input_.current_page_classification());
1272 if (!omnibox_will_reorder_for_legal_default_match &&
1273 IsTopMatchScoreTooLow()) {
[email protected]1beee342012-06-19 22:22:281274 // Disregard the suggested verbatim relevance if the top score is below
1275 // the usual verbatim value. For example, a BarProvider may rely on
[email protected]45f89a92013-08-12 13:41:361276 // SearchProvider's verbatim or inlineable matches for input "foo" (all
1277 // allowed to be default match) to always outrank its own lowly-ranked
1278 // "bar" matches that shouldn't be the default match. This only needs
1279 // to be enforced when the omnibox will not reorder results to make a
1280 // legal default match first.
[email protected]cc1526e2013-05-17 04:04:241281 default_results_.verbatim_relevance = -1;
1282 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421283 ConvertResultsToAutocompleteMatches();
[email protected]e6acd002012-06-16 22:27:471284 }
[email protected]fb95251e2013-07-17 14:52:241285 if (IsTopMatchSearchWithURLInput()) {
[email protected]e6acd002012-06-16 22:27:471286 // Disregard the suggested search and verbatim relevances if the input
1287 // type is URL and the top match is a highly-ranked search suggestion.
1288 // For example, prevent a search for "foo.com" from outranking another
1289 // provider's navigation for "foo.com" or "foo.com/url_from_history".
[email protected]cc1526e2013-05-17 04:04:241290 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
1291 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
1292 default_results_.verbatim_relevance = -1;
1293 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421294 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521295 }
[email protected]45f89a92013-08-12 13:41:361296 if (!HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match)) {
1297 // If the omnibox is not going to reorder results to put a legal default
1298 // match at the top, then this provider needs to guarantee that its top
1299 // scoring result is a legal default match (i.e., it's either a verbatim
1300 // match or inlinable). For example, input "foo" should not invoke a
1301 // search for "bar", which would happen if the "bar" search match
1302 // outranked all other matches. On the other hand, if the omnibox will
1303 // reorder matches as necessary to put a legal default match at the top,
1304 // all we need to guarantee is that SearchProvider returns a legal
1305 // default match. (The omnibox always needs at least one legal default
1306 // match, and it relies on SearchProvider to always return one.)
[email protected]344946a12012-12-20 12:03:421307 ApplyCalculatedRelevance();
1308 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521309 }
[email protected]9dfb4d362013-04-05 02:15:121310 DCHECK(!IsTopMatchNavigationInKeywordMode());
[email protected]45f89a92013-08-12 13:41:361311 DCHECK(omnibox_will_reorder_for_legal_default_match ||
1312 !IsTopMatchScoreTooLow());
[email protected]fb95251e2013-07-17 14:52:241313 DCHECK(!IsTopMatchSearchWithURLInput());
[email protected]45f89a92013-08-12 13:41:361314 DCHECK(HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match));
[email protected]d1f0a7f2012-06-05 10:26:421315 }
1316
[email protected]31afdf72013-09-26 04:29:361317 base::TimeTicks update_starred_start_time(base::TimeTicks::Now());
[email protected]cc63dea2008-08-21 20:56:311318 UpdateStarredStateOfMatches();
[email protected]31afdf72013-09-26 04:29:361319 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateStarredTime",
1320 base::TimeTicks::Now() - update_starred_start_time);
[email protected]4ab4c7c2010-11-24 04:49:341321 UpdateDone();
[email protected]31afdf72013-09-26 04:29:361322 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateMatchesTime",
1323 base::TimeTicks::Now() - update_matches_start_time);
[email protected]257ab712009-04-14 17:16:241324}
1325
1326void SearchProvider::AddNavigationResultsToMatches(
[email protected]d30268a2013-06-25 22:31:071327 const NavigationResults& navigation_results,
1328 ACMatches* matches) {
[email protected]bc8bb0cd2013-06-24 21:50:231329 for (NavigationResults::const_iterator it = navigation_results.begin();
1330 it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:071331 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:231332 // In the absence of suggested relevance scores, use only the single
1333 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:071334 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:231335 return;
[email protected]257ab712009-04-14 17:16:241336 }
1337}
1338
1339void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
1340 bool is_keyword,
1341 int did_not_accept_suggestion,
1342 MatchMap* map) {
[email protected]51124552011-07-16 01:37:101343 if (results.empty())
1344 return;
1345
[email protected]31afdf72013-09-26 04:29:361346 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]d7ad4772012-06-01 03:12:541347 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1348 (input_.type() == AutocompleteInput::URL);
[email protected]14710852013-02-05 23:45:411349 const string16& input_text =
1350 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:101351 bool input_multiple_words = HasMultipleWords(input_text);
1352
[email protected]55ce8f12012-05-09 04:44:081353 SuggestResults scored_results;
1354 if (!prevent_inline_autocomplete && input_multiple_words) {
1355 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1356 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:101357 // autocompleting a multi-word, multi-visit query, and the current input is
1358 // still a prefix of it, then changing the autocompletion suddenly feels
1359 // wrong. To detect this case, first score as if only one word has been
1360 // typed, then check for a best result that is an autocompleted, multi-word
1361 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:081362 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1363 false, input_text, is_keyword);
[email protected]9dfb4d362013-04-05 02:15:121364 if ((scored_results.front().relevance() <
[email protected]55ce8f12012-05-09 04:44:081365 AutocompleteResult::kLowestDefaultScore) ||
[email protected]9dfb4d362013-04-05 02:15:121366 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:081367 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:101368 }
[email protected]55ce8f12012-05-09 04:44:081369 if (scored_results.empty())
1370 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1371 input_multiple_words, input_text,
1372 is_keyword);
1373 for (SuggestResults::const_iterator i(scored_results.begin());
1374 i != scored_results.end(); ++i) {
[email protected]621ade062013-10-28 06:27:431375 AddMatchToMap(input_text,
1376 i->relevance(),
1377 false,
1378 false,
1379 std::string(),
1380 AutocompleteMatchType::SEARCH_HISTORY,
1381 is_keyword,
1382 i->suggestion(),
1383 string16(),
1384 i->suggestion(),
1385 did_not_accept_suggestion,
1386 std::string(),
1387 map);
[email protected]51124552011-07-16 01:37:101388 }
[email protected]31afdf72013-09-26 04:29:361389 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1390 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:101391}
1392
[email protected]55ce8f12012-05-09 04:44:081393SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:101394 const HistoryResults& results,
1395 bool base_prevent_inline_autocomplete,
1396 bool input_multiple_words,
1397 const string16& input_text,
1398 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:481399 AutocompleteClassifier* classifier =
1400 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:081401 SuggestResults scored_results;
[email protected]78e5e432013-08-03 02:10:101402 const bool prevent_search_history_inlining =
1403 OmniboxFieldTrial::SearchHistoryPreventInlining(
1404 input_.current_page_classification());
[email protected]257ab712009-04-14 17:16:241405 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1406 ++i) {
[email protected]51124552011-07-16 01:37:101407 // Don't autocomplete multi-word queries that have only been seen once
1408 // unless the user has typed more than one word.
1409 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1410 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
1411
[email protected]ea3b9a502011-04-04 14:19:371412 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:101413 // when typed. For example, if the user searched for "google.com" and types
1414 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1415 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:481416 // NOTE: We don't check this in the following cases:
1417 // * When inline autocomplete is disabled, we won't be inline
1418 // autocompleting this term, so we don't need to worry about confusion as
1419 // much. This also prevents calling Classify() again from inside the
1420 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:101421 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:481422 // * When the user has typed the whole term, the "what you typed" history
1423 // match will outrank us for URL-like inputs anyway, so we need not do
1424 // anything special.
[email protected]51124552011-07-16 01:37:101425 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:371426 AutocompleteMatch match;
[email protected]f608ea102013-03-18 15:08:091427 classifier->Classify(i->term, false, false, &match, NULL);
[email protected]2905f742011-10-13 03:51:581428 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:461429 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:371430 }
[email protected]51124552011-07-16 01:37:101431
[email protected]78e5e432013-08-03 02:10:101432 int relevance = CalculateRelevanceForHistory(
1433 i->time, is_keyword, !prevent_inline_autocomplete,
1434 prevent_search_history_inlining);
[email protected]d30268a2013-06-25 22:31:071435 scored_results.push_back(
[email protected]621ade062013-10-28 06:27:431436 SuggestResult(i->term, string16(), string16(), std::string(),
1437 is_keyword, relevance, false, false));
[email protected]257ab712009-04-14 17:16:241438 }
[email protected]51124552011-07-16 01:37:101439
1440 // History returns results sorted for us. However, we may have docked some
1441 // results' scores, so things are no longer in order. Do a stable sort to get
1442 // things back in order without otherwise disturbing results with equal
1443 // scores, then force the scores to be unique, so that the order in which
1444 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081445 std::stable_sort(scored_results.begin(), scored_results.end(),
1446 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101447 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081448 for (SuggestResults::iterator i(scored_results.begin());
1449 i != scored_results.end(); ++i) {
1450 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1451 i->set_relevance(last_relevance - 1);
1452 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101453 }
1454
[email protected]55ce8f12012-05-09 04:44:081455 return scored_results;
[email protected]257ab712009-04-14 17:16:241456}
1457
[email protected]55ce8f12012-05-09 04:44:081458void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
[email protected]987fad782013-08-28 06:23:181459 const std::string& metadata,
[email protected]55ce8f12012-05-09 04:44:081460 MatchMap* map) {
[email protected]55ce8f12012-05-09 04:44:081461 for (size_t i = 0; i < results.size(); ++i) {
[email protected]188b50c2013-03-28 07:19:421462 const bool is_keyword = results[i].from_keyword_provider();
1463 const string16& input = is_keyword ? keyword_input_.text() : input_.text();
[email protected]621ade062013-10-28 06:27:431464 AddMatchToMap(input,
1465 results[i].relevance(),
[email protected]d30268a2013-06-25 22:31:071466 results[i].relevance_from_server(),
[email protected]621ade062013-10-28 06:27:431467 results[i].should_prefetch(),
1468 metadata,
1469 AutocompleteMatchType::SEARCH_SUGGEST,
1470 is_keyword,
1471 results[i].match_contents(),
1472 results[i].annotation(),
1473 results[i].suggestion(),
1474 i,
1475 results[i].suggest_query_params(),
1476 map);
[email protected]257ab712009-04-14 17:16:241477 }
initial.commit09911bf2008-07-26 23:55:291478}
1479
[email protected]d30268a2013-06-25 22:31:071480int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561481 // Use the suggested verbatim relevance score if it is non-negative (valid),
1482 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281483 // and if it won't suppress verbatim, leaving no default provider matches.
1484 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561485 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281486 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561487 // Check for results on each verbatim calculation, as results from older
1488 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231489 bool use_server_relevance =
1490 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281491 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231492 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241493 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231494 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071495 if (relevance_from_server)
1496 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231497 return use_server_relevance ?
1498 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521499}
[email protected]d1f0a7f2012-06-05 10:26:421500
[email protected]382a0642012-06-06 06:13:521501int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471502 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361503 return 250;
[email protected]dab8d52d2013-03-05 07:35:281504 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1505}
[email protected]52d08b12009-10-19 18:42:361506
[email protected]dab8d52d2013-03-05 07:35:281507int SearchProvider::
1508 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291509 switch (input_.type()) {
1510 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361511 case AutocompleteInput::QUERY:
1512 case AutocompleteInput::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131513 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291514
initial.commit09911bf2008-07-26 23:55:291515 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361516 return 850;
initial.commit09911bf2008-07-26 23:55:291517
1518 default:
1519 NOTREACHED();
1520 return 0;
1521 }
1522}
1523
[email protected]d30268a2013-06-25 22:31:071524int SearchProvider::GetKeywordVerbatimRelevance(
1525 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281526 // Use the suggested verbatim relevance score if it is non-negative (valid),
1527 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1528 // and if it won't suppress verbatim, leaving no keyword provider matches.
1529 // Otherwise, if the keyword provider returned no matches and was still able
1530 // to suppress verbatim, the user would have no search/nav matches and may be
1531 // left unable to search using their keyword provider from the omnibox.
1532 // Check for results on each verbatim calculation, as results from older
1533 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231534 bool use_server_relevance =
1535 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281536 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231537 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241538 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231539 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071540 if (relevance_from_server)
1541 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231542 return use_server_relevance ?
1543 keyword_results_.verbatim_relevance :
1544 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1545 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451546}
1547
[email protected]51124552011-07-16 01:37:101548int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231549 const base::Time& time,
[email protected]51124552011-07-16 01:37:101550 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101551 bool use_aggressive_method,
1552 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181553 // The relevance of past searches falls off over time. There are two distinct
1554 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101555 // provider that we want to score aggressively), the score is in the range
1556 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161557 // it's in the range 1200-1299). If the second equation is used the
1558 // relevance of a search 15 minutes ago is discounted 50 points, while the
1559 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231560 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421561 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101562 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181563 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101564 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181565 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161566 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101567 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161568 max_score = 1299;
1569 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181570 std::pow(elapsed_time / autocomplete_time, 2.5));
1571 }
1572 elapsed_time -= autocomplete_time;
1573 }
1574
[email protected]c3a4bd992010-08-18 20:25:011575 const int score_discount =
1576 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291577
[email protected]6c85aa02009-02-27 12:08:091578 // Don't let scores go below 0. Negative relevance scores are meaningful in
1579 // a different way.
initial.commit09911bf2008-07-26 23:55:291580 int base_score;
[email protected]51124552011-07-16 01:37:101581 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361582 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101583 else
1584 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291585 return std::max(0, base_score - score_discount);
1586}
1587
[email protected]621ade062013-10-28 06:27:431588void SearchProvider::AddMatchToMap(const string16& input_text,
initial.commit09911bf2008-07-26 23:55:291589 int relevance,
[email protected]d30268a2013-06-25 22:31:071590 bool relevance_from_server,
[email protected]987fad782013-08-28 06:23:181591 bool should_prefetch,
1592 const std::string& metadata,
[email protected]4c1fb7ec2008-11-13 00:19:001593 AutocompleteMatch::Type type,
[email protected]257ab712009-04-14 17:16:241594 bool is_keyword,
[email protected]621ade062013-10-28 06:27:431595 const string16& match_contents,
1596 const string16& annotation,
1597 const string16& query_string,
1598 int accepted_suggestion,
1599 const std::string& suggest_query_params,
initial.commit09911bf2008-07-26 23:55:291600 MatchMap* map) {
[email protected]c4a9d4c2013-08-10 07:06:271601 // On non-mobile, ask the instant controller for the appropriate start margin.
1602 // On mobile the start margin is unused, so leave the value as default there.
1603 int omnibox_start_margin = chrome::kDisableStartMargin;
1604#if !defined(OS_ANDROID) && !defined(IOS)
1605 if (chrome::IsInstantExtendedAPIEnabled()) {
1606 Browser* browser =
1607 chrome::FindBrowserWithProfile(profile_, chrome::GetActiveDesktop());
1608 if (browser && browser->instant_controller() &&
1609 browser->instant_controller()->instant()) {
1610 omnibox_start_margin =
1611 browser->instant_controller()->instant()->omnibox_bounds().x();
1612 }
1613 }
1614#endif // !defined(OS_ANDROID) && !defined(IOS)
1615
[email protected]bba9e632013-06-28 22:52:191616 const TemplateURL* template_url = is_keyword ?
1617 providers_.GetKeywordProviderURL() : providers_.GetDefaultProviderURL();
[email protected]621ade062013-10-28 06:27:431618 AutocompleteMatch match = CreateSearchSuggestion(
1619 this, input_, input_text, relevance, type, is_keyword, match_contents,
1620 annotation, template_url, query_string, suggest_query_params,
[email protected]c4a9d4c2013-08-10 07:06:271621 accepted_suggestion, omnibox_start_margin,
[email protected]56fa29592013-07-02 20:25:531622 !is_keyword || providers_.default_provider().empty());
[email protected]cb86ee6f2013-04-28 16:58:151623 if (!match.destination_url.is_valid())
[email protected]85b8d6f2012-05-08 20:53:471624 return;
[email protected]a048de8a2013-10-02 18:30:061625 match.search_terms_args->bookmark_bar_pinned =
1626 profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
[email protected]d30268a2013-06-25 22:31:071627 match.RecordAdditionalInfo(kRelevanceFromServerKey,
1628 relevance_from_server ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181629 match.RecordAdditionalInfo(kShouldPrefetchKey,
1630 should_prefetch ? kTrue : kFalse);
1631
1632 // Metadata is needed only for prefetching queries.
1633 if (should_prefetch)
1634 match.RecordAdditionalInfo(kSuggestMetadataKey, metadata);
[email protected]85b8d6f2012-05-08 20:53:471635
initial.commit09911bf2008-07-26 23:55:291636 // Try to add |match| to |map|. If a match for |query_string| is already in
1637 // |map|, replace it if |match| is more relevant.
1638 // NOTE: Keep this ToLower() call in sync with url_database.cc.
[email protected]621ade062013-10-28 06:27:431639 MatchKey match_key(
1640 std::make_pair(base::i18n::ToLower(query_string),
1641 match.search_terms_args->suggest_query_params));
[email protected]bc8bb0cd2013-06-24 21:50:231642 const std::pair<MatchMap::iterator, bool> i(
[email protected]621ade062013-10-28 06:27:431643 map->insert(std::make_pair(match_key, match)));
[email protected]987fad782013-08-28 06:23:181644
1645 if (!i.second) {
1646 // NOTE: We purposefully do a direct relevance comparison here instead of
1647 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items
1648 // added first" rather than "items alphabetically first" when the scores are
1649 // equal. The only case this matters is when a user has results with the
1650 // same score that differ only by capitalization; because the history system
1651 // returns results sorted by recency, this means we'll pick the most
1652 // recent such result even if the precision of our relevance score is too
1653 // low to distinguish the two.
1654 if (match.relevance > i.first->second.relevance) {
1655 i.first->second = match;
1656 } else if (match.keyword == i.first->second.keyword) {
1657 // Old and new matches are from the same search provider. It is okay to
1658 // record one match's prefetch data onto a different match (for the same
1659 // query string) for the following reasons:
1660 // 1. Because the suggest server only sends down a query string from which
1661 // we construct a URL, rather than sending a full URL, and because we
1662 // construct URLs from query strings in the same way every time, the URLs
1663 // for the two matches will be the same. Therefore, we won't end up
1664 // prefetching something the server didn't intend.
1665 // 2. Presumably the server sets the prefetch bit on a match it things is
1666 // sufficiently relevant that the user is likely to choose it. Surely
1667 // setting the prefetch bit on a match of even higher relevance won't
1668 // violate this assumption.
1669 should_prefetch |= ShouldPrefetch(i.first->second);
1670 i.first->second.RecordAdditionalInfo(kShouldPrefetchKey,
1671 should_prefetch ? kTrue : kFalse);
1672 if (should_prefetch)
1673 i.first->second.RecordAdditionalInfo(kSuggestMetadataKey, metadata);
1674 }
1675 }
initial.commit09911bf2008-07-26 23:55:291676}
1677
1678AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421679 const NavigationResult& navigation) {
1680 const string16& input = navigation.from_keyword_provider() ?
1681 keyword_input_.text() : input_.text();
[email protected]55ce8f12012-05-09 04:44:081682 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]b7f64d742013-05-21 04:04:041683 AutocompleteMatchType::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081684 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551685
1686 // First look for the user's input inside the fill_into_edit as it would be
1687 // without trimming the scheme, so we can find matches at the beginning of the
1688 // scheme.
[email protected]a1b5e862013-03-29 06:38:441689 const string16& untrimmed_fill_into_edit = navigation.formatted_url();
[email protected]371dab12012-06-01 03:23:551690 const URLPrefix* prefix =
1691 URLPrefix::BestURLPrefix(untrimmed_fill_into_edit, input);
1692 size_t match_start = (prefix == NULL) ?
1693 untrimmed_fill_into_edit.find(input) : prefix->prefix.length();
1694 size_t inline_autocomplete_offset = (prefix == NULL) ?
1695 string16::npos : (match_start + input.length());
[email protected]d2445c82013-11-04 22:28:351696 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1697 (!prefix || (match_start != 0));
[email protected]371dab12012-06-01 03:23:551698
1699 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1700 // Otherwise, user edits to a suggestion would show non-Search results.
1701 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
1702 match.fill_into_edit = ASCIIToUTF16("?");
1703 if (inline_autocomplete_offset != string16::npos)
1704 ++inline_autocomplete_offset;
1705 }
1706
1707 const std::string languages(
1708 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1709 const net::FormatUrlTypes format_types =
1710 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1711 match.fill_into_edit +=
1712 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1713 net::FormatUrl(navigation.url(), languages, format_types,
1714 net::UnescapeRule::SPACES, NULL, NULL,
1715 &inline_autocomplete_offset));
[email protected]518024c2013-07-19 23:40:251716 if (!input_.prevent_inline_autocomplete() &&
1717 (inline_autocomplete_offset != string16::npos)) {
1718 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
[email protected]45f89a92013-08-12 13:41:361719 match.allowed_to_be_default_match = true;
[email protected]518024c2013-07-19 23:40:251720 match.inline_autocompletion =
1721 match.fill_into_edit.substr(inline_autocomplete_offset);
1722 }
[email protected]371dab12012-06-01 03:23:551723
1724 match.contents = net::FormatUrl(navigation.url(), languages,
1725 format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1726 // If the first match in the untrimmed string was inside a scheme that we
1727 // trimmed, look for a subsequent match.
1728 if (match_start == string16::npos)
1729 match_start = match.contents.find(input);
1730 // Safe if |match_start| is npos; also safe if the input is longer than the
1731 // remaining contents after |match_start|.
1732 AutocompleteMatch::ClassifyLocationInString(match_start, input.length(),
1733 match.contents.length(), ACMatchClassification::URL,
1734 &match.contents_class);
initial.commit09911bf2008-07-26 23:55:291735
[email protected]55ce8f12012-05-09 04:44:081736 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551737 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1738 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071739
1740 match.RecordAdditionalInfo(
1741 kRelevanceFromServerKey,
1742 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181743 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071744
initial.commit09911bf2008-07-26 23:55:291745 return match;
1746}
[email protected]4ab4c7c2010-11-24 04:49:341747
[email protected]9dfb4d362013-04-05 02:15:121748void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
[email protected]d519d392013-03-27 09:24:461749 // First, determine the maximum score of any keyword query match (verbatim or
1750 // query suggestion).
[email protected]d30268a2013-06-25 22:31:071751 bool relevance_from_server;
1752 int max_query_relevance = GetKeywordVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:241753 if (!keyword_results_.suggest_results.empty()) {
[email protected]d30268a2013-06-25 22:31:071754 const SuggestResult& top_keyword = keyword_results_.suggest_results.front();
1755 const int suggest_relevance = top_keyword.relevance();
1756 if (suggest_relevance > max_query_relevance) {
1757 max_query_relevance = suggest_relevance;
1758 relevance_from_server = top_keyword.relevance_from_server();
1759 } else if (suggest_relevance == max_query_relevance) {
1760 relevance_from_server |= top_keyword.relevance_from_server();
1761 }
[email protected]d519d392013-03-27 09:24:461762 }
1763 // If no query is supposed to appear, then navigational matches cannot
[email protected]9dfb4d362013-04-05 02:15:121764 // be demoted past it. Get rid of suggested relevance scores for
1765 // navsuggestions and introduce the verbatim results again. The keyword
1766 // verbatim match will outscore the navsuggest matches.
1767 if (max_query_relevance == 0) {
[email protected]cc1526e2013-05-17 04:04:241768 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
1769 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
1770 keyword_results_.verbatim_relevance = -1;
1771 default_results_.verbatim_relevance = -1;
[email protected]9dfb4d362013-04-05 02:15:121772 return;
1773 }
[email protected]d519d392013-03-27 09:24:461774 // Now we know we can enforce the minimum score constraint even after
1775 // the navigation matches are demoted. Proceed to demote the navigation
1776 // matches to enforce the query-must-come-first constraint.
[email protected]d519d392013-03-27 09:24:461777 // Cap the relevance score of all results.
[email protected]cc1526e2013-05-17 04:04:241778 for (NavigationResults::iterator it =
1779 keyword_results_.navigation_results.begin();
1780 it != keyword_results_.navigation_results.end(); ++it) {
[email protected]9dfb4d362013-04-05 02:15:121781 if (it->relevance() < max_query_relevance)
1782 return;
1783 max_query_relevance = std::max(max_query_relevance - 1, 0);
1784 it->set_relevance(max_query_relevance);
[email protected]d30268a2013-06-25 22:31:071785 it->set_relevance_from_server(relevance_from_server);
[email protected]d519d392013-03-27 09:24:461786 }
[email protected]d519d392013-03-27 09:24:461787}
1788
[email protected]4ab4c7c2010-11-24 04:49:341789void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331790 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311791 // pending, and we're not waiting on Instant.
[email protected]e1290ee62013-06-26 18:31:151792 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
[email protected]4ab4c7c2010-11-24 04:49:341793}