blob: 2fc267bda96f3d031d21de8b9a4dc3fec05cd7df [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]9b9fa672013-11-07 06:04:5228#include "chrome/browser/google/google_util.h"
[email protected]6a2c09f2013-01-25 04:50:0729#include "chrome/browser/history/history_service.h"
[email protected]9d2db762012-06-19 00:01:1030#include "chrome/browser/history/history_service_factory.h"
[email protected]10c2d692012-05-11 05:32:2331#include "chrome/browser/history/in_memory_database.h"
[email protected]ab7780792013-01-10 01:26:0932#include "chrome/browser/metrics/variations/variations_http_header_provider.h"
[email protected]684fcc12013-03-08 22:50:0233#include "chrome/browser/omnibox/omnibox_field_trial.h"
[email protected]8ecad5e2010-12-02 21:18:3334#include "chrome/browser/profiles/profile.h"
[email protected]a7b8e43d2013-03-18 18:52:4335#include "chrome/browser/search/search.h"
[email protected]9899a612012-08-21 23:50:0436#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
[email protected]8e5c89a2011-06-07 18:13:3337#include "chrome/browser/search_engines/template_url_service.h"
38#include "chrome/browser/search_engines/template_url_service_factory.h"
[email protected]9b9fa672013-11-07 06:04:5239#include "chrome/browser/sync/profile_sync_service.h"
40#include "chrome/browser/sync/profile_sync_service_factory.h"
[email protected]c4a9d4c2013-08-10 07:06:2741#include "chrome/browser/ui/browser.h"
42#include "chrome/browser/ui/browser_finder.h"
43#include "chrome/browser/ui/browser_instant_controller.h"
44#include "chrome/browser/ui/search/instant_controller.h"
[email protected]4f3b4462013-07-27 19:20:1845#include "chrome/common/net/url_fixer_upper.h"
initial.commit09911bf2008-07-26 23:55:2946#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0247#include "chrome/common/url_constants.h"
[email protected]34ac8f32009-02-22 23:03:2748#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2949#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3450#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5551#include "net/base/net_util.h"
[email protected]9b9fa672013-11-07 06:04:5252#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
[email protected]bd3b4712012-12-18 17:01:3053#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2154#include "net/http/http_response_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5355#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2156#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1757#include "ui/base/l10n/l10n_util.h"
[email protected]761fa4702013-07-02 15:25:1558#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2959
[email protected]bc8bb0cd2013-06-24 21:50:2360
61// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3362
[email protected]51124552011-07-16 01:37:1063namespace {
64
[email protected]7706a522012-08-16 17:42:2565// We keep track in a histogram how many suggest requests we send, how
66// many suggest requests we invalidate (e.g., due to a user typing
67// another character), and how many replies we receive.
68// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
69// (excluding the end-of-list enum value)
70// We do not want values of existing enums to change or else it screws
71// up the statistics.
72enum SuggestRequestsHistogramValue {
73 REQUEST_SENT = 1,
74 REQUEST_INVALIDATED,
75 REPLY_RECEIVED,
76 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
77};
78
[email protected]90fe2bb2013-01-15 03:42:1379// The verbatim score for an input which is not an URL.
80const int kNonURLVerbatimRelevance = 1300;
81
[email protected]7706a522012-08-16 17:42:2582// Increments the appropriate value in the histogram by one.
83void LogOmniboxSuggestRequest(
84 SuggestRequestsHistogramValue request_value) {
85 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
86 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
87}
88
[email protected]51124552011-07-16 01:37:1089bool HasMultipleWords(const string16& text) {
90 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
91 bool found_word = false;
92 if (i.Init()) {
93 while (i.Advance()) {
94 if (i.IsWord()) {
95 if (found_word)
96 return true;
97 found_word = true;
98 }
99 }
100 }
101 return false;
102}
103
[email protected]621ade062013-10-28 06:27:43104// Builds the match contents and classification for the contents, and updates
105// the given |AutocompleteMatch|.
106void SetAndClassifyMatchContents(const string16& query_string,
107 const string16& input_text,
108 const string16& match_contents,
109 const string16& annotation,
110 AutocompleteMatch* match) {
111 size_t match_contents_start = 0;
112 size_t annotation_start = match_contents.size();
113 // Append annotation if present.
114 if (annotation.empty()) {
115 match->contents = match_contents;
116 } else {
117 std::vector<size_t> positions;
118 match->contents = l10n_util::GetStringFUTF16(
119 IDS_ANNOTATED_SUGGESTION, match_contents, annotation, &positions);
120 match_contents_start = positions[0];
121 annotation_start = positions[1];
122 }
123 size_t match_contents_end = match_contents_start + match_contents.size();
124
125 if (!annotation.empty() && (annotation_start < match_contents_start))
126 match->contents_class.push_back(ACMatchClassification(
127 annotation_start, ACMatchClassification::DIM));
128
129 // We do intra-string highlighting for suggestions - the suggested segment
130 // will be highlighted, e.g. for input_text = "you" the suggestion may be
131 // "youtube", so we'll bold the "tube" section: you*tube*.
132 if (input_text != match_contents) {
133 size_t input_position = match->contents.substr(
134 match_contents_start, match_contents.length()).find(input_text);
135 if (input_position == string16::npos) {
136 // The input text is not a substring of the query string, e.g. input
137 // text is "slasdot" and the query string is "slashdot", so we bold the
138 // whole thing.
139 match->contents_class.push_back(ACMatchClassification(
140 match_contents_start, ACMatchClassification::MATCH));
141 } else {
142 input_position += match_contents_start;
143
144 // TODO(beng): ACMatchClassification::MATCH now seems to just mean
145 // "bold" this. Consider modifying the terminology.
146 // We don't iterate over the string here annotating all matches because
147 // it looks odd to have every occurrence of a substring that may be as
148 // short as a single character highlighted in a query suggestion result,
149 // e.g. for input text "s" and query string "southwest airlines", it
150 // looks odd if both the first and last s are highlighted.
151 if (input_position != match_contents_start) {
152 match->contents_class.push_back(ACMatchClassification(
153 match_contents_start, ACMatchClassification::MATCH));
154 }
155 match->contents_class.push_back(
156 ACMatchClassification(input_position, ACMatchClassification::NONE));
157 size_t next_fragment_position = input_position + input_text.length();
158 if (next_fragment_position < query_string.length()) {
159 match->contents_class.push_back(ACMatchClassification(
160 next_fragment_position, ACMatchClassification::MATCH));
161 }
162 }
163 } else {
164 // Otherwise, |match| is a verbatim (what-you-typed) match, either for the
165 // default provider or a keyword search provider.
166 match->contents_class.push_back(ACMatchClassification(
167 match_contents_start, ACMatchClassification::NONE));
168 }
169
170 if (!annotation.empty() && (annotation_start >= match_contents_start))
171 match->contents_class.push_back(ACMatchClassification(
172 match_contents_end, ACMatchClassification::DIM));
173}
174
[email protected]d1f0a7f2012-06-05 10:26:42175} // namespace
[email protected]51124552011-07-16 01:37:10176
[email protected]033f3422012-03-13 21:24:18177
[email protected]3954c3a2012-04-10 20:17:55178// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:58179
[email protected]85b8d6f2012-05-08 20:53:47180SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
181 : template_url_service_(template_url_service) {
182}
183
184const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
185 return default_provider_.empty() ? NULL :
186 template_url_service_->GetTemplateURLForKeyword(default_provider_);
187}
188
189const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
190 return keyword_provider_.empty() ? NULL :
191 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24192}
193
[email protected]3954c3a2012-04-10 20:17:55194
[email protected]bc8bb0cd2013-06-24 21:50:23195// SearchProvider::Result -----------------------------------------------------
196
197SearchProvider::Result::Result(bool from_keyword_provider,
[email protected]d30268a2013-06-25 22:31:07198 int relevance,
199 bool relevance_from_server)
[email protected]bc8bb0cd2013-06-24 21:50:23200 : from_keyword_provider_(from_keyword_provider),
[email protected]d30268a2013-06-25 22:31:07201 relevance_(relevance),
202 relevance_from_server_(relevance_from_server) {
[email protected]bc8bb0cd2013-06-24 21:50:23203}
204
205SearchProvider::Result::~Result() {
206}
207
208
209// SearchProvider::SuggestResult ----------------------------------------------
210
[email protected]621ade062013-10-28 06:27:43211SearchProvider::SuggestResult::SuggestResult(
212 const string16& suggestion,
213 const string16& match_contents,
214 const string16& annotation,
215 const std::string& suggest_query_params,
216 bool from_keyword_provider,
217 int relevance,
218 bool relevance_from_server,
219 bool should_prefetch)
[email protected]d30268a2013-06-25 22:31:07220 : Result(from_keyword_provider, relevance, relevance_from_server),
[email protected]987fad782013-08-28 06:23:18221 suggestion_(suggestion),
[email protected]621ade062013-10-28 06:27:43222 match_contents_(match_contents),
223 annotation_(annotation),
224 suggest_query_params_(suggest_query_params),
[email protected]987fad782013-08-28 06:23:18225 should_prefetch_(should_prefetch) {
[email protected]bc8bb0cd2013-06-24 21:50:23226}
227
228SearchProvider::SuggestResult::~SuggestResult() {
229}
230
231bool SearchProvider::SuggestResult::IsInlineable(const string16& input) const {
232 return StartsWith(suggestion_, input, false);
233}
234
235int SearchProvider::SuggestResult::CalculateRelevance(
236 const AutocompleteInput& input,
237 bool keyword_provider_requested) const {
238 if (!from_keyword_provider_ && keyword_provider_requested)
239 return 100;
240 return ((input.type() == AutocompleteInput::URL) ? 300 : 600);
241}
242
243
244// SearchProvider::NavigationResult -------------------------------------------
245
246SearchProvider::NavigationResult::NavigationResult(
247 const AutocompleteProvider& provider,
248 const GURL& url,
249 const string16& description,
250 bool from_keyword_provider,
[email protected]d30268a2013-06-25 22:31:07251 int relevance,
252 bool relevance_from_server)
253 : Result(from_keyword_provider, relevance, relevance_from_server),
[email protected]bc8bb0cd2013-06-24 21:50:23254 url_(url),
255 formatted_url_(AutocompleteInput::FormattedStringWithEquivalentMeaning(
256 url, provider.StringForURLDisplay(url, true, false))),
257 description_(description) {
258 DCHECK(url_.is_valid());
259}
260
261SearchProvider::NavigationResult::~NavigationResult() {
262}
263
264bool SearchProvider::NavigationResult::IsInlineable(
265 const string16& input) const {
266 return URLPrefix::BestURLPrefix(formatted_url_, input) != NULL;
267}
268
269int SearchProvider::NavigationResult::CalculateRelevance(
270 const AutocompleteInput& input,
271 bool keyword_provider_requested) const {
272 return (from_keyword_provider_ || !keyword_provider_requested) ? 800 : 150;
273}
274
275
276// SearchProvider::CompareScoredResults ---------------------------------------
277
278class SearchProvider::CompareScoredResults {
279 public:
280 bool operator()(const Result& a, const Result& b) {
281 // Sort in descending relevance order.
282 return a.relevance() > b.relevance();
283 }
284};
285
286
287// SearchProvider::Results ----------------------------------------------------
288
[email protected]d30268a2013-06-25 22:31:07289SearchProvider::Results::Results() : verbatim_relevance(-1) {
[email protected]bc8bb0cd2013-06-24 21:50:23290}
291
292SearchProvider::Results::~Results() {
293}
294
295void SearchProvider::Results::Clear() {
296 suggest_results.clear();
297 navigation_results.clear();
[email protected]bc8bb0cd2013-06-24 21:50:23298 verbatim_relevance = -1;
[email protected]987fad782013-08-28 06:23:18299 metadata.clear();
[email protected]bc8bb0cd2013-06-24 21:50:23300}
301
302bool SearchProvider::Results::HasServerProvidedScores() const {
303 if (verbatim_relevance >= 0)
304 return true;
305
[email protected]d30268a2013-06-25 22:31:07306 // Right now either all results of one type will be server-scored or they will
307 // all be locally scored, but in case we change this later, we'll just check
308 // them all.
309 for (SuggestResults::const_iterator i(suggest_results.begin());
310 i != suggest_results.end(); ++i) {
311 if (i->relevance_from_server())
312 return true;
313 }
314 for (NavigationResults::const_iterator i(navigation_results.begin());
315 i != navigation_results.end(); ++i) {
316 if (i->relevance_from_server())
317 return true;
318 }
319
320 return false;
[email protected]bc8bb0cd2013-06-24 21:50:23321}
[email protected]d30268a2013-06-25 22:31:07322
323
[email protected]3954c3a2012-04-10 20:17:55324// SearchProvider -------------------------------------------------------------
325
326// static
327const int SearchProvider::kDefaultProviderURLFetcherID = 1;
[email protected]3954c3a2012-04-10 20:17:55328const int SearchProvider::kKeywordProviderURLFetcherID = 2;
[email protected]24dbf2302013-04-05 16:59:25329int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]d30268a2013-06-25 22:31:07330const char SearchProvider::kRelevanceFromServerKey[] = "relevance_from_server";
[email protected]987fad782013-08-28 06:23:18331const char SearchProvider::kShouldPrefetchKey[] = "should_prefetch";
332const char SearchProvider::kSuggestMetadataKey[] = "suggest_metadata";
[email protected]d30268a2013-06-25 22:31:07333const char SearchProvider::kTrue[] = "true";
334const char SearchProvider::kFalse[] = "false";
[email protected]3954c3a2012-04-10 20:17:55335
[email protected]bc8bb0cd2013-06-24 21:50:23336SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
337 Profile* profile)
338 : AutocompleteProvider(listener, profile,
339 AutocompleteProvider::TYPE_SEARCH),
340 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
341 suggest_results_pending_(0),
[email protected]bc8bb0cd2013-06-24 21:50:23342 field_trial_triggered_(false),
[email protected]c4a9d4c2013-08-10 07:06:27343 field_trial_triggered_in_session_(false) {
[email protected]bc8bb0cd2013-06-24 21:50:23344}
345
[email protected]cb86ee6f2013-04-28 16:58:15346// static
347AutocompleteMatch SearchProvider::CreateSearchSuggestion(
[email protected]cb86ee6f2013-04-28 16:58:15348 AutocompleteProvider* autocomplete_provider,
[email protected]621ade062013-10-28 06:27:43349 const AutocompleteInput& input,
350 const string16& input_text,
[email protected]cb86ee6f2013-04-28 16:58:15351 int relevance,
352 AutocompleteMatch::Type type,
[email protected]621ade062013-10-28 06:27:43353 bool is_keyword,
354 const string16& match_contents,
355 const string16& annotation,
[email protected]bba9e632013-06-28 22:52:19356 const TemplateURL* template_url,
357 const string16& query_string,
[email protected]621ade062013-10-28 06:27:43358 const std::string& suggest_query_params,
[email protected]bba9e632013-06-28 22:52:19359 int accepted_suggestion,
[email protected]56fa29592013-07-02 20:25:53360 int omnibox_start_margin,
361 bool append_extra_query_params) {
[email protected]cb86ee6f2013-04-28 16:58:15362 AutocompleteMatch match(autocomplete_provider, relevance, false, type);
363
[email protected]bba9e632013-06-28 22:52:19364 if (!template_url)
[email protected]cb86ee6f2013-04-28 16:58:15365 return match;
[email protected]bba9e632013-06-28 22:52:19366 match.keyword = template_url->keyword();
[email protected]cb86ee6f2013-04-28 16:58:15367
[email protected]621ade062013-10-28 06:27:43368 SetAndClassifyMatchContents(
369 query_string, input_text, match_contents, annotation, &match);
370
371 match.allowed_to_be_default_match = (input_text == match_contents);
[email protected]cb86ee6f2013-04-28 16:58:15372
373 // When the user forced a query, we need to make sure all the fill_into_edit
374 // values preserve that property. Otherwise, if the user starts editing a
375 // suggestion, non-Search results will suddenly appear.
376 if (input.type() == AutocompleteInput::FORCED_QUERY)
377 match.fill_into_edit.assign(ASCIIToUTF16("?"));
378 if (is_keyword)
379 match.fill_into_edit.append(match.keyword + char16(' '));
380 if (!input.prevent_inline_autocomplete() &&
381 StartsWith(query_string, input_text, false)) {
[email protected]518024c2013-07-19 23:40:25382 match.inline_autocompletion = query_string.substr(input_text.length());
[email protected]45f89a92013-08-12 13:41:36383 match.allowed_to_be_default_match = true;
[email protected]cb86ee6f2013-04-28 16:58:15384 }
385 match.fill_into_edit.append(query_string);
386
[email protected]bba9e632013-06-28 22:52:19387 const TemplateURLRef& search_url = template_url->url_ref();
[email protected]cb86ee6f2013-04-28 16:58:15388 DCHECK(search_url.SupportsReplacement());
389 match.search_terms_args.reset(
390 new TemplateURLRef::SearchTermsArgs(query_string));
391 match.search_terms_args->original_query = input_text;
392 match.search_terms_args->accepted_suggestion = accepted_suggestion;
[email protected]f3e46eec2013-06-11 14:46:28393 match.search_terms_args->omnibox_start_margin = omnibox_start_margin;
[email protected]621ade062013-10-28 06:27:43394 match.search_terms_args->suggest_query_params = suggest_query_params;
[email protected]56fa29592013-07-02 20:25:53395 match.search_terms_args->append_extra_query_params =
396 append_extra_query_params;
[email protected]cb86ee6f2013-04-28 16:58:15397 // This is the destination URL sans assisted query stats. This must be set
398 // so the AutocompleteController can properly de-dupe; the controller will
399 // eventually overwrite it before it reaches the user.
400 match.destination_url =
401 GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get()));
402
403 // Search results don't look like URLs.
404 match.transition = is_keyword ?
405 content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED;
406
407 return match;
408}
409
[email protected]987fad782013-08-28 06:23:18410// static
411bool SearchProvider::ShouldPrefetch(const AutocompleteMatch& match) {
412 return match.GetAdditionalInfo(kShouldPrefetchKey) == kTrue;
413}
414
415// static
416std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
417 return match.GetAdditionalInfo(kSuggestMetadataKey);
418}
419
[email protected]bc8bb0cd2013-06-24 21:50:23420void SearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
421 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
422 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
423 new_entry.set_provider(AsOmniboxEventProviderType());
424 new_entry.set_provider_done(done_);
425 std::vector<uint32> field_trial_hashes;
426 OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(&field_trial_hashes);
427 for (size_t i = 0; i < field_trial_hashes.size(); ++i) {
428 if (field_trial_triggered_)
429 new_entry.mutable_field_trial_triggered()->Add(field_trial_hashes[i]);
430 if (field_trial_triggered_in_session_) {
431 new_entry.mutable_field_trial_triggered_in_session()->Add(
432 field_trial_hashes[i]);
433 }
434 }
435}
436
437void SearchProvider::ResetSession() {
438 field_trial_triggered_in_session_ = false;
[email protected]4ab4c7c2010-11-24 04:49:34439}
440
[email protected]bc8bb0cd2013-06-24 21:50:23441SearchProvider::~SearchProvider() {
442}
443
444// static
445void SearchProvider::RemoveStaleResults(const string16& input,
446 int verbatim_relevance,
447 SuggestResults* suggest_results,
448 NavigationResults* navigation_results) {
449 DCHECK_GE(verbatim_relevance, 0);
450 // Keep pointers to the head of (the highest scoring elements of)
451 // |suggest_results| and |navigation_results|. Iterate down the lists
452 // removing non-inlineable results in order of decreasing relevance
453 // scores. Stop when the highest scoring element among those remaining
454 // is inlineable or the element is less than |verbatim_relevance|.
455 // This allows non-inlineable lower-scoring results to remain
456 // because (i) they are guaranteed to not be inlined and (ii)
457 // letting them remain reduces visual jank. For instance, as the
458 // user types the mis-spelled query "fpobar" (for foobar), the
459 // suggestion "foobar" will be suggested on every keystroke. If the
460 // SearchProvider always removes all non-inlineable results, the user will
461 // see visual jitter/jank as the result disappears and re-appears moments
462 // later as the suggest server returns results.
463 SuggestResults::iterator sug_it = suggest_results->begin();
464 NavigationResults::iterator nav_it = navigation_results->begin();
465 while ((sug_it != suggest_results->end()) ||
466 (nav_it != navigation_results->end())) {
467 const int sug_rel =
468 (sug_it != suggest_results->end()) ? sug_it->relevance() : -1;
469 const int nav_rel =
470 (nav_it != navigation_results->end()) ? nav_it->relevance() : -1;
471 if (std::max(sug_rel, nav_rel) < verbatim_relevance)
472 break;
473 if (sug_rel > nav_rel) {
474 // The current top result is a search suggestion.
475 if (sug_it->IsInlineable(input))
476 break;
477 sug_it = suggest_results->erase(sug_it);
478 } else if (sug_rel == nav_rel) {
479 // Have both results and they're tied.
480 const bool sug_inlineable = sug_it->IsInlineable(input);
481 const bool nav_inlineable = nav_it->IsInlineable(input);
482 if (!sug_inlineable)
483 sug_it = suggest_results->erase(sug_it);
484 if (!nav_inlineable)
485 nav_it = navigation_results->erase(nav_it);
486 if (sug_inlineable || nav_inlineable)
487 break;
488 } else {
489 // The current top result is a navigational suggestion.
490 if (nav_it->IsInlineable(input))
491 break;
492 nav_it = navigation_results->erase(nav_it);
493 }
494 }
495}
496
497// static
498int SearchProvider::CalculateRelevanceForKeywordVerbatim(
499 AutocompleteInput::Type type,
500 bool prefer_keyword) {
501 // This function is responsible for scoring verbatim query matches
502 // for non-extension keywords. KeywordProvider::CalculateRelevance()
503 // scores verbatim query matches for extension keywords, as well as
504 // for keyword matches (i.e., suggestions of a keyword itself, not a
505 // suggestion of a query on a keyword search engine). These two
506 // functions are currently in sync, but there's no reason we
507 // couldn't decide in the future to score verbatim matches
508 // differently for extension and non-extension keywords. If you
509 // make such a change, however, you should update this comment to
510 // describe it, so it's clear why the functions diverge.
511 if (prefer_keyword)
512 return 1500;
513 return (type == AutocompleteInput::QUERY) ? 1450 : 1100;
514}
515
initial.commit09911bf2008-07-26 23:55:29516void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27517 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55518 // Do our best to load the model as early as possible. This will reduce
519 // odds of having the model not ready when really needed (a non-empty input).
520 TemplateURLService* model = providers_.template_url_service();
521 DCHECK(model);
522 model->Load();
523
initial.commit09911bf2008-07-26 23:55:29524 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57525 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29526
[email protected]6c85aa02009-02-27 12:08:09527 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29528 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]e29249dc52012-07-19 17:33:50529 Stop(false);
initial.commit09911bf2008-07-26 23:55:29530 return;
531 }
532
[email protected]14710852013-02-05 23:45:41533 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24534 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41535 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
536 &keyword_input_);
537 if (keyword_provider == NULL)
538 keyword_input_.Clear();
539 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24540 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24541
[email protected]85b8d6f2012-05-08 20:53:47542 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07543 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24544 default_provider = NULL;
545
546 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18547 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24548
549 if (!default_provider && !keyword_provider) {
550 // No valid providers.
[email protected]e29249dc52012-07-19 17:33:50551 Stop(false);
initial.commit09911bf2008-07-26 23:55:29552 return;
553 }
554
555 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24556 // or the providers, abort the query.
[email protected]85b8d6f2012-05-08 20:53:47557 string16 default_provider_keyword(default_provider ?
558 default_provider->keyword() : string16());
559 string16 keyword_provider_keyword(keyword_provider ?
560 keyword_provider->keyword() : string16());
[email protected]9e789742011-01-10 23:27:32561 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47562 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29563 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15564 if (!done_)
[email protected]e29249dc52012-07-19 17:33:50565 Stop(false);
[email protected]257ab712009-04-14 17:16:24566 }
initial.commit09911bf2008-07-26 23:55:29567
[email protected]85b8d6f2012-05-08 20:53:47568 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29569
570 if (input.text().empty()) {
571 // User typed "?" alone. Give them a placeholder result indicating what
572 // this syntax does.
[email protected]257ab712009-04-14 17:16:24573 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00574 AutocompleteMatch match;
575 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36576 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24577 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35578 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47579 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36580 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24581 matches_.push_back(match);
582 }
[email protected]e29249dc52012-07-19 17:33:50583 Stop(false);
initial.commit09911bf2008-07-26 23:55:29584 return;
585 }
586
587 input_ = input;
588
[email protected]e1290ee62013-06-26 18:31:15589 DoHistoryQuery(minimal_changes);
590 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42591 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29592}
593
[email protected]e29249dc52012-07-19 17:33:50594void SearchProvider::Stop(bool clear_cached_results) {
initial.commit09911bf2008-07-26 23:55:29595 StopSuggest();
596 done_ = true;
[email protected]e29249dc52012-07-19 17:33:50597
598 if (clear_cached_results)
[email protected]71b46152013-05-03 16:39:20599 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29600}
601
[email protected]10c2d692012-05-11 05:32:23602void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29603 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24604 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25605 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15606 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06607
[email protected]d7ad4772012-06-01 03:12:54608 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]f2916ea2013-01-26 02:20:14609 // Ensure the request succeeded and that the provider used is still available.
610 // A verbatim match cannot be generated without this provider, causing errors.
[email protected]013e9a02012-05-18 20:27:10611 const bool request_succeeded =
[email protected]bc8bb0cd2013-06-24 21:50:23612 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
613 (is_keyword ?
614 providers_.GetKeywordProviderURL() :
615 providers_.GetDefaultProviderURL());
[email protected]a0ad93ea2012-05-07 22:11:53616
617 // Record response time for suggest requests sent to Google. We care
618 // only about the common case: the Google default provider used in
619 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47620 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08621 if (!is_keyword && default_url &&
[email protected]628392f2013-08-16 00:34:45622 (TemplateURLPrepopulateData::GetEngineType(*default_url) ==
[email protected]9899a612012-08-21 23:50:04623 SEARCH_ENGINE_GOOGLE)) {
[email protected]bc8bb0cd2013-06-24 21:50:23624 const base::TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10625 base::TimeTicks::Now() - time_suggest_request_sent_;
626 if (request_succeeded) {
627 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
628 elapsed_time);
629 } else {
630 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
631 elapsed_time);
632 }
[email protected]b4cebf82008-12-29 19:59:08633 }
634
[email protected]d7ad4772012-06-01 03:12:54635 bool results_updated = false;
636 if (request_succeeded) {
[email protected]ed9b1802013-10-31 04:09:48637 const net::HttpResponseHeaders* const response_headers =
638 source->GetResponseHeaders();
639 std::string json_data;
640 source->GetResponseAsString(&json_data);
641 // JSON is supposed to be UTF-8, but some suggest service providers send
642 // JSON files in non-UTF-8 encodings. The actual encoding is usually
643 // specified in the Content-Type header field.
644 if (response_headers) {
645 std::string charset;
646 if (response_headers->GetCharset(&charset)) {
647 string16 data_16;
648 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
649 if (base::CodepageToUTF16(json_data, charset.c_str(),
650 base::OnStringConversionError::FAIL,
651 &data_16))
652 json_data = UTF16ToUTF8(data_16);
653 }
654 }
655
656 // The JSON response should be an array.
657 for (size_t response_start_index = json_data.find("["), i = 0;
658 response_start_index != std::string::npos && i < 5;
659 response_start_index = json_data.find("[", 1), i++) {
660 // Remove any XSSI guards to allow for JSON parsing.
661 if (response_start_index > 0)
662 json_data.erase(0, response_start_index);
663
664 JSONStringValueSerializer deserializer(json_data);
665 deserializer.set_allow_trailing_comma(true);
666 int error_code = 0;
667 scoped_ptr<Value> data(deserializer.Deserialize(&error_code, NULL));
668 if (error_code == 0) {
669 results_updated = data.get() &&
670 ParseSuggestResults(data.get(), is_keyword);
671 break;
672 }
673 }
[email protected]d7ad4772012-06-01 03:12:54674 }
675
[email protected]344946a12012-12-20 12:03:42676 UpdateMatches();
[email protected]d7ad4772012-06-01 03:12:54677 if (done_ || results_updated)
678 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29679}
680
[email protected]bc8bb0cd2013-06-24 21:50:23681void SearchProvider::Run() {
682 // Start a new request with the current input.
683 suggest_results_pending_ = 0;
684 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05685
[email protected]bc8bb0cd2013-06-24 21:50:23686 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
687 providers_.GetDefaultProviderURL(), input_));
688 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
689 providers_.GetKeywordProviderURL(), keyword_input_));
690
691 // Both the above can fail if the providers have been modified or deleted
692 // since the query began.
693 if (suggest_results_pending_ == 0) {
694 UpdateDone();
695 // We only need to update the listener if we're actually done.
696 if (done_)
697 listener_->OnProviderUpdate(false);
698 }
[email protected]601858c02010-09-01 17:08:20699}
700
[email protected]8d457132010-11-04 18:13:40701void SearchProvider::DoHistoryQuery(bool minimal_changes) {
702 // The history query results are synchronous, so if minimal_changes is true,
703 // we still have the last results and don't need to do anything.
704 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29705 return;
706
[email protected]31afdf72013-09-26 04:29:36707 base::TimeTicks do_history_query_start_time(base::TimeTicks::Now());
708
[email protected]8d457132010-11-04 18:13:40709 keyword_history_results_.clear();
710 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29711
[email protected]78e5e432013-08-03 02:10:10712 if (OmniboxFieldTrial::SearchHistoryDisable(
713 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16714 return;
715
[email protected]31afdf72013-09-26 04:29:36716 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]8d457132010-11-04 18:13:40717 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10718 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]31afdf72013-09-26 04:29:36719 base::TimeTicks now(base::TimeTicks::Now());
720 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.GetHistoryServiceTime",
721 now - start_time);
722 start_time = now;
[email protected]8d457132010-11-04 18:13:40723 history::URLDatabase* url_db = history_service ?
724 history_service->InMemoryDatabase() : NULL;
[email protected]31afdf72013-09-26 04:29:36725 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.InMemoryDatabaseTime",
726 base::TimeTicks::Now() - start_time);
[email protected]8d457132010-11-04 18:13:40727 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29728 return;
729
[email protected]51124552011-07-16 01:37:10730 // Request history for both the keyword and default provider. We grab many
731 // more matches than we'll ultimately clamp to so that if there are several
732 // recent multi-word matches who scores are lowered (see
733 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
734 // matches. Note that this doesn't fix the problem entirely, but merely
735 // limits it to cases with a very large number of such multi-word matches; for
736 // now, this seems OK compared with the complexity of a real fix, which would
737 // require multiple searches and tracking of "single- vs. multi-word" in the
738 // database.
739 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47740 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
741 if (default_url) {
[email protected]31afdf72013-09-26 04:29:36742 start_time = base::TimeTicks::Now();
[email protected]85b8d6f2012-05-08 20:53:47743 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
744 num_matches, &default_history_results_);
[email protected]31afdf72013-09-26 04:29:36745 UMA_HISTOGRAM_TIMES(
746 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
747 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24748 }
[email protected]85b8d6f2012-05-08 20:53:47749 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
750 if (keyword_url) {
751 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41752 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55753 }
[email protected]31afdf72013-09-26 04:29:36754 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.DoHistoryQueryTime",
755 base::TimeTicks::Now() - do_history_query_start_time);
initial.commit09911bf2008-07-26 23:55:29756}
757
[email protected]6dc950f2012-07-16 19:49:08758void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34759 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29760 StopSuggest();
[email protected]71b46152013-05-03 16:39:20761 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29762 return;
763 }
764
765 // For the minimal_changes case, if we finished the previous query and still
766 // have its results, or are allowed to keep running it, just do that, rather
767 // than starting a new query.
768 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24769 (!default_results_.suggest_results.empty() ||
770 !default_results_.navigation_results.empty() ||
771 !keyword_results_.suggest_results.empty() ||
772 !keyword_results_.navigation_results.empty() ||
[email protected]ea3b9a502011-04-04 14:19:37773 (!done_ &&
774 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29775 return;
776
777 // We can't keep running any previous query, so halt it.
778 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42779
780 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20781 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29782
783 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37784 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29785 return;
786
[email protected]24dbf2302013-04-05 16:59:25787 // To avoid flooding the suggest server, don't send a query until at
788 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24789 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
[email protected]bc8bb0cd2013-06-24 21:50:23790 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
[email protected]515ffa942012-11-27 20:18:24791 base::TimeTicks now(base::TimeTicks::Now());
792 if (now >= next_suggest_time) {
793 Run();
794 return;
795 }
796 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29797}
798
[email protected]83c726482008-09-10 06:36:34799bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55800 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
801 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47802 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
803 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34804 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47805 ((!default_url || default_url->suggestions_url().empty()) &&
806 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34807 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
808 return false;
809
[email protected]cac59d32010-08-09 23:23:14810 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34811 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34812
[email protected]cac59d32010-08-09 23:23:14813 // FORCED_QUERY means the user is explicitly asking us to search for this, so
814 // we assume it isn't a URL and/or there isn't private data.
815 if (input_.type() == AutocompleteInput::FORCED_QUERY)
816 return true;
[email protected]83c726482008-09-10 06:36:34817
[email protected]f608ea102013-03-18 15:08:09818 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
819 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
820 // is both a waste of time and a disclosure of potentially private, local
821 // data. Other "schemes" may actually be usernames, and we don't want to send
822 // passwords. If the scheme is OK, we still need to check other cases below.
823 // If this is QUERY, then the presence of these schemes means the user
824 // explicitly typed one, and thus this is probably a URL that's being entered
825 // and happens to currently be invalid -- in which case we again want to run
826 // our checks below. Other QUERY cases are less likely to be URLs and thus we
827 // assume we're OK.
[email protected]e9a82042013-09-15 03:38:29828 if (!LowerCaseEqualsASCII(input_.scheme(), content::kHttpScheme) &&
[email protected]4654bfe2013-08-26 03:36:58829 !LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36830 !LowerCaseEqualsASCII(input_.scheme(), chrome::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14831 return (input_.type() == AutocompleteInput::QUERY);
832
833 // Don't send URLs with usernames, queries or refs. Some of these are
834 // private, and the Suggest server is unlikely to have any useful results
835 // for any of them. Also don't send URLs with ports, as we may initially
836 // think that a username + password is a host + port (and we don't want to
837 // send usernames/passwords), and even if the port really is a port, the
838 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58839 // Note that we only block based on refs if the input is URL-typed, as search
840 // queries can legitimately have #s in them which the URL parser
841 // overaggressively categorizes as a url with a ref.
[email protected]cac59d32010-08-09 23:23:14842 const url_parse::Parsed& parts = input_.parts();
843 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58844 parts.query.is_nonempty() ||
845 (parts.ref.is_nonempty() && (input_.type() == AutocompleteInput::URL)))
[email protected]cac59d32010-08-09 23:23:14846 return false;
847
848 // Don't send anything for https except the hostname. Hostnames are OK
849 // because they are visible when the TCP connection is established, but the
850 // specific path may reveal private information.
[email protected]4654bfe2013-08-26 03:36:58851 if (LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36852 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14853 return false;
[email protected]83c726482008-09-10 06:36:34854
855 return true;
856}
857
initial.commit09911bf2008-07-26 23:55:29858void SearchProvider::StopSuggest() {
[email protected]7706a522012-08-16 17:42:25859 // Increment the appropriate field in the histogram by the number of
860 // pending requests that were invalidated.
861 for (int i = 0; i < suggest_results_pending_; i++)
862 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
[email protected]257ab712009-04-14 17:16:24863 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14864 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24865 // Stop any in-progress URL fetches.
866 keyword_fetcher_.reset();
867 default_fetcher_.reset();
[email protected]55ce8f12012-05-09 04:44:08868}
869
[email protected]71b46152013-05-03 16:39:20870void SearchProvider::ClearAllResults() {
[email protected]cc1526e2013-05-17 04:04:24871 keyword_results_.Clear();
872 default_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51873}
874
[email protected]71b46152013-05-03 16:39:20875void SearchProvider::RemoveAllStaleResults() {
[email protected]dc735c02013-11-12 23:23:41876 // We only need to remove stale results (which ensures the top-scoring
877 // match is inlineable) if the user is not in reorder mode. In reorder
878 // mode, the autocomplete system will reorder results to make sure the
879 // top result is inlineable.
880 const bool omnibox_will_reorder_for_legal_default_match =
881 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
882 input_.current_page_classification());
[email protected]1e1550e2013-05-02 17:37:51883 // In theory it would be better to run an algorithm like that in
884 // RemoveStaleResults(...) below that uses all four results lists
885 // and both verbatim scores at once. However, that will be much
886 // more complicated for little obvious gain. For code simplicity
887 // and ease in reasoning about the invariants involved, this code
888 // removes stales results from the keyword provider and default
889 // provider independently.
[email protected]dc735c02013-11-12 23:23:41890 if (!omnibox_will_reorder_for_legal_default_match) {
891 RemoveStaleResults(input_.text(), GetVerbatimRelevance(NULL),
892 &default_results_.suggest_results,
893 &default_results_.navigation_results);
894 if (!keyword_input_.text().empty()) {
895 RemoveStaleResults(keyword_input_.text(),
896 GetKeywordVerbatimRelevance(NULL),
897 &keyword_results_.suggest_results,
898 &keyword_results_.navigation_results);
899 }
900 }
901 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51902 // User is either in keyword mode with a blank input or out of
903 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24904 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51905 }
[email protected]d1f0a7f2012-06-05 10:26:42906}
907
[email protected]d1f0a7f2012-06-05 10:26:42908void SearchProvider::ApplyCalculatedRelevance() {
[email protected]cc1526e2013-05-17 04:04:24909 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
910 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
911 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
912 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
[email protected]cc1526e2013-05-17 04:04:24913 default_results_.verbatim_relevance = -1;
914 keyword_results_.verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42915}
916
[email protected]188b50c2013-03-28 07:19:42917void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42918 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42919 SuggestResult& result = (*list)[i];
920 result.set_relevance(
921 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
922 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07923 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42924 }
925}
926
[email protected]188b50c2013-03-28 07:19:42927void SearchProvider::ApplyCalculatedNavigationRelevance(
928 NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42929 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42930 NavigationResult& result = (*list)[i];
931 result.set_relevance(
932 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
933 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07934 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42935 }
936}
937
[email protected]9b9fa672013-11-07 06:04:52938bool SearchProvider::CanSendURL(
939 const GURL& current_page_url,
940 const GURL& suggest_url,
941 const TemplateURL* template_url,
942 AutocompleteInput::PageClassification page_classification,
943 Profile* profile){
944 if (!current_page_url.is_valid())
945 return false;
946
947 // TODO(hfung): Show Most Visited on NTP with appropriate verbatim
948 // description when the user actively focuses on the omnibox as discussed in
949 // crbug/305366 if Most Visited (or something similar) will launch.
[email protected]12b5cd052013-11-08 20:59:37950 if ((page_classification ==
951 AutocompleteInput::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS) ||
952 (page_classification ==
953 AutocompleteInput::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS))
[email protected]9b9fa672013-11-07 06:04:52954 return false;
955
956 // Only allow HTTP URLs or HTTPS URLs for the same domain as the search
957 // provider.
958 if ((current_page_url.scheme() != content::kHttpScheme) &&
959 ((current_page_url.scheme() != content::kHttpsScheme) ||
960 !net::registry_controlled_domains::SameDomainOrHost(
961 current_page_url, suggest_url,
962 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES)))
963 return false;
964
965 // Make sure we are sending the suggest request through HTTPS to prevent
966 // exposing the current page URL to networks before the search provider.
967 if (!suggest_url.SchemeIs(content::kHttpsScheme))
968 return false;
969
970 // Don't run if there's no profile or in incognito mode.
971 if (profile == NULL || profile->IsOffTheRecord())
972 return false;
973
974 // Don't run if we can't get preferences or search suggest is not enabled.
975 PrefService* prefs = profile->GetPrefs();
976 if (!prefs->GetBoolean(prefs::kSearchSuggestEnabled))
977 return false;
978
979 // Only make the request if we know that the provider supports zero suggest
980 // (currently only the prepopulated Google provider).
981 if (template_url == NULL || !template_url->SupportsReplacement() ||
982 TemplateURLPrepopulateData::GetEngineType(*template_url) !=
983 SEARCH_ENGINE_GOOGLE)
984 return false;
985
986 // Check field trials and settings allow sending the URL on suggest requests.
987 ProfileSyncService* service =
988 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile);
989 browser_sync::SyncPrefs sync_prefs(prefs);
990 if (!OmniboxFieldTrial::InZeroSuggestFieldTrial() ||
991 service == NULL ||
992 !service->IsSyncEnabledAndLoggedIn() ||
993 !sync_prefs.GetPreferredDataTypes(syncer::UserTypes()).Has(
994 syncer::PROXY_TABS) ||
995 service->GetEncryptedDataTypes().Has(syncer::SESSIONS))
996 return false;
997
998 return true;
999}
1000
[email protected]15fb2aa2012-05-22 22:52:591001net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:121002 int id,
[email protected]9ff91722012-09-07 05:29:121003 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:411004 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:121005 if (!template_url || template_url->suggestions_url().empty())
1006 return NULL;
1007
1008 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:411009 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
1010 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:181011 search_term_args.page_classification = input.current_page_classification();
[email protected]9ff91722012-09-07 05:29:121012 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:161013 search_term_args));
[email protected]9ff91722012-09-07 05:29:121014 if (!suggest_url.is_valid())
1015 return NULL;
[email protected]9b9fa672013-11-07 06:04:521016 // Send the current page URL if user setting and URL requirements are met and
1017 // the user is in the field trial.
1018 if (CanSendURL(current_page_url_, suggest_url, template_url,
1019 input.current_page_classification(), profile_) &&
1020 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
1021 search_term_args.current_page_url = current_page_url_.spec();
1022 // Create the suggest URL again with the current page URL.
1023 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
1024 search_term_args));
1025 }
[email protected]9ff91722012-09-07 05:29:121026
1027 suggest_results_pending_++;
1028 LogOmniboxSuggestRequest(REQUEST_SENT);
1029
1030 net::URLFetcher* fetcher =
1031 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:121032 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:341033 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:301034 // Add Chrome experiment state to the request headers.
1035 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:091036 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:301037 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
1038 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:241039 fetcher->Start();
1040 return fetcher;
1041}
1042
[email protected]d7ad4772012-06-01 03:12:541043bool SearchProvider::ParseSuggestResults(Value* root_val, bool is_keyword) {
[email protected]d7ad4772012-06-01 03:12:541044 string16 query;
1045 ListValue* root_list = NULL;
[email protected]cc1526e2013-05-17 04:04:241046 ListValue* results_list = NULL;
[email protected]14710852013-02-05 23:45:411047 const string16& input_text =
1048 is_keyword ? keyword_input_.text() : input_.text();
[email protected]d7ad4772012-06-01 03:12:541049 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
[email protected]cc1526e2013-05-17 04:04:241050 (query != input_text) || !root_list->GetList(1, &results_list))
initial.commit09911bf2008-07-26 23:55:291051 return false;
1052
[email protected]55ce8f12012-05-09 04:44:081053 // 3rd element: Description list.
[email protected]d7ad4772012-06-01 03:12:541054 ListValue* descriptions = NULL;
1055 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:291056
[email protected]55ce8f12012-05-09 04:44:081057 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:291058
[email protected]d1f0a7f2012-06-05 10:26:421059 // Reset suggested relevance information from the default provider.
[email protected]cc1526e2013-05-17 04:04:241060 Results* results = is_keyword ? &keyword_results_ : &default_results_;
[email protected]cc1526e2013-05-17 04:04:241061 results->verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:421062
[email protected]55ce8f12012-05-09 04:44:081063 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]d7ad4772012-06-01 03:12:541064 ListValue* types = NULL;
[email protected]d1f0a7f2012-06-05 10:26:421065 ListValue* relevances = NULL;
[email protected]621ade062013-10-28 06:27:431066 ListValue* suggestion_details = NULL;
[email protected]d1f0a7f2012-06-05 10:26:421067 DictionaryValue* extras = NULL;
[email protected]987fad782013-08-28 06:23:181068 int prefetch_index = -1;
[email protected]d1f0a7f2012-06-05 10:26:421069 if (root_list->GetDictionary(4, &extras)) {
1070 extras->GetList("google:suggesttype", &types);
1071
[email protected]eb8330d2013-06-15 00:55:081072 // Discard this list if its size does not match that of the suggestions.
1073 if (extras->GetList("google:suggestrelevance", &relevances) &&
[email protected]621ade062013-10-28 06:27:431074 (relevances->GetSize() != results_list->GetSize()))
[email protected]eb8330d2013-06-15 00:55:081075 relevances = NULL;
1076 extras->GetInteger("google:verbatimrelevance",
1077 &results->verbatim_relevance);
[email protected]618d6e62012-12-16 05:55:571078
1079 // Check if the active suggest field trial (if any) has triggered either
1080 // for the default provider or keyword provider.
1081 bool triggered = false;
1082 extras->GetBoolean("google:fieldtrialtriggered", &triggered);
1083 field_trial_triggered_ |= triggered;
1084 field_trial_triggered_in_session_ |= triggered;
[email protected]987fad782013-08-28 06:23:181085
[email protected]987fad782013-08-28 06:23:181086 DictionaryValue* client_data = NULL;
1087 if (extras->GetDictionary("google:clientdata", &client_data) && client_data)
1088 client_data->GetInteger("phi", &prefetch_index);
1089
[email protected]621ade062013-10-28 06:27:431090 if (extras->GetList("google:suggestdetail", &suggestion_details) &&
1091 suggestion_details->GetSize() != results_list->GetSize())
1092 suggestion_details = NULL;
1093
[email protected]987fad782013-08-28 06:23:181094 // Store the metadata that came with the response in case we need to pass it
1095 // along with the prefetch query to Instant.
1096 JSONStringValueSerializer json_serializer(&results->metadata);
1097 json_serializer.Serialize(*extras);
initial.commit09911bf2008-07-26 23:55:291098 }
1099
[email protected]d1f0a7f2012-06-05 10:26:421100 // Clear the previous results now that new results are available.
[email protected]cc1526e2013-05-17 04:04:241101 results->suggest_results.clear();
1102 results->navigation_results.clear();
[email protected]d1f0a7f2012-06-05 10:26:421103
[email protected]621ade062013-10-28 06:27:431104 string16 suggestion;
[email protected]d1f0a7f2012-06-05 10:26:421105 std::string type;
1106 int relevance = -1;
[email protected]3f381592013-11-05 20:43:511107 // Prohibit navsuggest in FORCED_QUERY mode. Users wants queries, not URLs.
1108 const bool allow_navsuggest =
1109 (is_keyword ? keyword_input_.type() : input_.type()) !=
1110 AutocompleteInput::FORCED_QUERY;
[email protected]621ade062013-10-28 06:27:431111 for (size_t index = 0; results_list->GetString(index, &suggestion); ++index) {
[email protected]8e81f5092010-09-29 23:19:401112 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:081113 // they make no sense at all and can cause problems in our code.
[email protected]621ade062013-10-28 06:27:431114 if (suggestion.empty())
[email protected]8e81f5092010-09-29 23:19:401115 continue;
1116
[email protected]d1f0a7f2012-06-05 10:26:421117 // Apply valid suggested relevance scores; discard invalid lists.
1118 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
1119 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:541120 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:421121 // Do not blindly trust the URL coming from the server to be valid.
[email protected]621ade062013-10-28 06:27:431122 GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(suggestion), std::string()));
[email protected]3f381592013-11-05 20:43:511123 if (url.is_valid() && allow_navsuggest) {
[email protected]621ade062013-10-28 06:27:431124 string16 title;
[email protected]d1f0a7f2012-06-05 10:26:421125 if (descriptions != NULL)
1126 descriptions->GetString(index, &title);
[email protected]d30268a2013-06-25 22:31:071127 results->navigation_results.push_back(NavigationResult(
1128 *this, url, title, is_keyword, relevance, true));
initial.commit09911bf2008-07-26 23:55:291129 }
1130 } else {
[email protected]987fad782013-08-28 06:23:181131 bool should_prefetch = static_cast<int>(index) == prefetch_index;
[email protected]621ade062013-10-28 06:27:431132 DictionaryValue* suggestion_detail = NULL;
1133 string16 match_contents = suggestion;
1134 string16 disambiguating_query;
1135 string16 annotation;
1136 std::string suggest_query_params;
1137 if (suggestion_details && (type == "ENTITY") &&
1138 suggestion_details->GetDictionary(index, &suggestion_detail) &&
1139 suggestion_detail) {
1140 suggestion_detail->GetString("a", &annotation);
1141 if (suggestion_detail->GetString("dq", &disambiguating_query) &&
1142 !disambiguating_query.empty())
1143 suggestion = disambiguating_query;
1144 suggestion_detail->GetString("q", &suggest_query_params);
1145 }
1146 // TODO(kochi): Improve calculator suggestion presentation.
1147 results->suggest_results.push_back(SuggestResult(
1148 suggestion, match_contents, annotation, suggest_query_params,
1149 is_keyword, relevance, true, should_prefetch));
initial.commit09911bf2008-07-26 23:55:291150 }
1151 }
1152
[email protected]d1f0a7f2012-06-05 10:26:421153 // Apply calculated relevance scores if a valid list was not provided.
1154 if (relevances == NULL) {
[email protected]cc1526e2013-05-17 04:04:241155 ApplyCalculatedSuggestRelevance(&results->suggest_results);
1156 ApplyCalculatedNavigationRelevance(&results->navigation_results);
[email protected]d1f0a7f2012-06-05 10:26:421157 }
[email protected]9dfb4d362013-04-05 02:15:121158 // Keep the result lists sorted.
1159 const CompareScoredResults comparator = CompareScoredResults();
[email protected]cc1526e2013-05-17 04:04:241160 std::stable_sort(results->suggest_results.begin(),
1161 results->suggest_results.end(),
[email protected]9dfb4d362013-04-05 02:15:121162 comparator);
[email protected]cc1526e2013-05-17 04:04:241163 std::stable_sort(results->navigation_results.begin(),
1164 results->navigation_results.end(),
[email protected]9dfb4d362013-04-05 02:15:121165 comparator);
[email protected]d1f0a7f2012-06-05 10:26:421166 return true;
initial.commit09911bf2008-07-26 23:55:291167}
1168
[email protected]344946a12012-12-20 12:03:421169void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:291170 // Convert all the results to matches and add them to a map, so we can keep
1171 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:361172 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:291173 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:231174 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:241175 int did_not_accept_keyword_suggestion =
1176 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:291177 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
1178 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:291179
[email protected]d30268a2013-06-25 22:31:071180 bool relevance_from_server;
1181 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:241182 int did_not_accept_default_suggestion =
1183 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:081184 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
1185 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:421186 if (verbatim_relevance > 0) {
[email protected]621ade062013-10-28 06:27:431187 AddMatchToMap(input_.text(),
1188 verbatim_relevance,
1189 relevance_from_server,
1190 false,
1191 std::string(),
[email protected]b7f64d742013-05-21 04:04:041192 AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]621ade062013-10-28 06:27:431193 false,
1194 input_.text(),
1195 string16(),
1196 input_.text(),
1197 did_not_accept_default_suggestion,
1198 std::string(),
1199 &map);
[email protected]d1f0a7f2012-06-05 10:26:421200 }
[email protected]5423e562013-02-07 03:58:451201 if (!keyword_input_.text().empty()) {
1202 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1203 // We only create the verbatim search query match for a keyword
1204 // if it's not an extension keyword. Extension keywords are handled
1205 // in KeywordProvider::Start(). (Extensions are complicated...)
1206 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
1207 // to the keyword verbatim search query. Do not create other matches
1208 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:251209 if (keyword_url &&
1210 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:071211 bool keyword_relevance_from_server;
1212 const int keyword_verbatim_relevance =
1213 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:281214 if (keyword_verbatim_relevance > 0) {
[email protected]621ade062013-10-28 06:27:431215 AddMatchToMap(keyword_input_.text(),
1216 keyword_verbatim_relevance,
1217 keyword_relevance_from_server,
1218 false,
1219 std::string(),
[email protected]b7f64d742013-05-21 04:04:041220 AutocompleteMatchType::SEARCH_OTHER_ENGINE,
[email protected]621ade062013-10-28 06:27:431221 true,
1222 keyword_input_.text(),
1223 string16(),
1224 keyword_input_.text(),
1225 did_not_accept_keyword_suggestion,
1226 std::string(),
1227 &map);
[email protected]dab8d52d2013-03-05 07:35:281228 }
[email protected]5423e562013-02-07 03:58:451229 }
1230 }
[email protected]257ab712009-04-14 17:16:241231 AddHistoryResultsToMap(keyword_history_results_, true,
1232 did_not_accept_keyword_suggestion, &map);
1233 AddHistoryResultsToMap(default_history_results_, false,
1234 did_not_accept_default_suggestion, &map);
1235
[email protected]d1cb6a822013-09-18 19:43:001236 AddSuggestResultsToMap(keyword_results_.suggest_results,
1237 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:181238 AddSuggestResultsToMap(default_results_.suggest_results,
1239 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:291240
[email protected]d30268a2013-06-25 22:31:071241 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:291242 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:071243 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:291244
[email protected]d30268a2013-06-25 22:31:071245 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
1246 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:291247
[email protected]d30268a2013-06-25 22:31:071248 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
1249 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
1250 // enabled and we have server-provided (and thus hopefully more accurate)
1251 // scores for some suggestions, we allow more of those, until we reach
1252 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
1253 // whole popup).
1254 //
1255 // We will always return any verbatim matches, no matter how we obtained their
1256 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
1257 // higher-scoring matches under the conditions above.
[email protected]31afdf72013-09-26 04:29:361258 UMA_HISTOGRAM_CUSTOM_COUNTS(
1259 "Omnibox.SearchProvider.NumMatchesToSort", matches.size(), 1, 50, 20);
[email protected]d30268a2013-06-25 22:31:071260 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
1261 matches_.clear();
[email protected]3723e6e2012-06-11 21:06:561262
[email protected]d30268a2013-06-25 22:31:071263 size_t num_suggestions = 0;
1264 for (ACMatches::const_iterator i(matches.begin());
1265 (i != matches.end()) &&
1266 (matches_.size() < AutocompleteResult::kMaxMatches);
1267 ++i) {
1268 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
1269 // verbatim result, so this condition basically means "if this match is a
1270 // suggestion of some sort".
1271 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
1272 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
1273 // If we've already hit the limit on non-server-scored suggestions, and
1274 // this isn't a server-scored suggestion we can add, skip it.
1275 if ((num_suggestions >= kMaxMatches) &&
1276 (!chrome::IsInstantExtendedAPIEnabled() ||
1277 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
1278 continue;
1279 }
1280
1281 ++num_suggestions;
1282 }
1283
1284 matches_.push_back(*i);
1285 }
[email protected]31afdf72013-09-26 04:29:361286 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
1287 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:421288}
1289
[email protected]9dfb4d362013-04-05 02:15:121290bool SearchProvider::IsTopMatchNavigationInKeywordMode() const {
1291 return (!providers_.keyword_provider().empty() &&
[email protected]b7f64d742013-05-21 04:04:041292 (matches_.front().type == AutocompleteMatchType::NAVSUGGEST));
[email protected]9dfb4d362013-04-05 02:15:121293}
1294
[email protected]344946a12012-12-20 12:03:421295bool SearchProvider::IsTopMatchScoreTooLow() const {
[email protected]dab8d52d2013-03-05 07:35:281296 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
1297 // rather than CalculateRelevanceForVerbatim() because the latter returns
1298 // a very low score (250) if keyword mode is active. This is because
1299 // when keyword mode is active the user probably wants the keyword matches,
1300 // not matches from the default provider. Hence, we use the version of
1301 // the function that ignores whether keyword mode is active. This allows
1302 // SearchProvider to maintain its contract with the AutocompleteController
1303 // that it will always provide an inlineable match with a reasonable
1304 // score.
1305 return matches_.front().relevance <
1306 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
[email protected]344946a12012-12-20 12:03:421307}
1308
[email protected]fb95251e2013-07-17 14:52:241309bool SearchProvider::IsTopMatchSearchWithURLInput() const {
[email protected]344946a12012-12-20 12:03:421310 return input_.type() == AutocompleteInput::URL &&
1311 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
[email protected]fb95251e2013-07-17 14:52:241312 matches_.front().type != AutocompleteMatchType::NAVSUGGEST;
[email protected]344946a12012-12-20 12:03:421313}
1314
[email protected]45f89a92013-08-12 13:41:361315bool SearchProvider::HasValidDefaultMatch(
1316 bool autocomplete_result_will_reorder_for_default_match) const {
1317 // One of the SearchProvider matches may need to be the overall default. If
1318 // AutocompleteResult is allowed to reorder matches, this means we simply
1319 // need at least one match in the list to be |allowed_to_be_default_match|.
1320 // If no reordering is possible, however, then our first match needs to have
1321 // this flag.
1322 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
1323 ++it) {
1324 if (it->allowed_to_be_default_match)
1325 return true;
1326 if (!autocomplete_result_will_reorder_for_default_match)
1327 return false;
1328 }
1329 return false;
[email protected]344946a12012-12-20 12:03:421330}
1331
1332void SearchProvider::UpdateMatches() {
[email protected]31afdf72013-09-26 04:29:361333 base::TimeTicks update_matches_start_time(base::TimeTicks::Now());
[email protected]344946a12012-12-20 12:03:421334 ConvertResultsToAutocompleteMatches();
initial.commit09911bf2008-07-26 23:55:291335
[email protected]382a0642012-06-06 06:13:521336 // Check constraints that may be violated by suggested relevances.
[email protected]344946a12012-12-20 12:03:421337 if (!matches_.empty() &&
[email protected]bc8bb0cd2013-06-24 21:50:231338 (default_results_.HasServerProvidedScores() ||
1339 keyword_results_.HasServerProvidedScores())) {
[email protected]9dfb4d362013-04-05 02:15:121340 // These blocks attempt to repair undesirable behavior by suggested
[email protected]344946a12012-12-20 12:03:421341 // relevances with minimal impact, preserving other suggested relevances.
[email protected]9dfb4d362013-04-05 02:15:121342 if (IsTopMatchNavigationInKeywordMode()) {
1343 // Correct the suggested relevance scores if the top match is a
1344 // navigation in keyword mode, since inlining a navigation match
1345 // would break the user out of keyword mode. By the way, if the top
1346 // match is a non-keyword match (query or navsuggestion) in keyword
1347 // mode, the user would also break out of keyword mode. However,
1348 // that situation is impossible given the current scoring paradigm
1349 // and the fact that only one search engine (Google) provides suggested
1350 // relevance scores at this time.
1351 DemoteKeywordNavigationMatchesPastTopQuery();
1352 ConvertResultsToAutocompleteMatches();
1353 DCHECK(!IsTopMatchNavigationInKeywordMode());
1354 }
[email protected]45f89a92013-08-12 13:41:361355 // True if the omnibox will reorder matches as necessary to make the top
1356 // one something that is allowed to be the default match.
1357 const bool omnibox_will_reorder_for_legal_default_match =
1358 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
1359 input_.current_page_classification());
1360 if (!omnibox_will_reorder_for_legal_default_match &&
1361 IsTopMatchScoreTooLow()) {
[email protected]1beee342012-06-19 22:22:281362 // Disregard the suggested verbatim relevance if the top score is below
1363 // the usual verbatim value. For example, a BarProvider may rely on
[email protected]45f89a92013-08-12 13:41:361364 // SearchProvider's verbatim or inlineable matches for input "foo" (all
1365 // allowed to be default match) to always outrank its own lowly-ranked
1366 // "bar" matches that shouldn't be the default match. This only needs
1367 // to be enforced when the omnibox will not reorder results to make a
1368 // legal default match first.
[email protected]cc1526e2013-05-17 04:04:241369 default_results_.verbatim_relevance = -1;
1370 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421371 ConvertResultsToAutocompleteMatches();
[email protected]e6acd002012-06-16 22:27:471372 }
[email protected]fb95251e2013-07-17 14:52:241373 if (IsTopMatchSearchWithURLInput()) {
[email protected]e6acd002012-06-16 22:27:471374 // Disregard the suggested search and verbatim relevances if the input
1375 // type is URL and the top match is a highly-ranked search suggestion.
1376 // For example, prevent a search for "foo.com" from outranking another
1377 // provider's navigation for "foo.com" or "foo.com/url_from_history".
[email protected]cc1526e2013-05-17 04:04:241378 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
1379 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
1380 default_results_.verbatim_relevance = -1;
1381 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421382 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521383 }
[email protected]45f89a92013-08-12 13:41:361384 if (!HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match)) {
1385 // If the omnibox is not going to reorder results to put a legal default
1386 // match at the top, then this provider needs to guarantee that its top
1387 // scoring result is a legal default match (i.e., it's either a verbatim
1388 // match or inlinable). For example, input "foo" should not invoke a
1389 // search for "bar", which would happen if the "bar" search match
1390 // outranked all other matches. On the other hand, if the omnibox will
1391 // reorder matches as necessary to put a legal default match at the top,
1392 // all we need to guarantee is that SearchProvider returns a legal
1393 // default match. (The omnibox always needs at least one legal default
1394 // match, and it relies on SearchProvider to always return one.)
[email protected]344946a12012-12-20 12:03:421395 ApplyCalculatedRelevance();
1396 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521397 }
[email protected]9dfb4d362013-04-05 02:15:121398 DCHECK(!IsTopMatchNavigationInKeywordMode());
[email protected]45f89a92013-08-12 13:41:361399 DCHECK(omnibox_will_reorder_for_legal_default_match ||
1400 !IsTopMatchScoreTooLow());
[email protected]fb95251e2013-07-17 14:52:241401 DCHECK(!IsTopMatchSearchWithURLInput());
[email protected]45f89a92013-08-12 13:41:361402 DCHECK(HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match));
[email protected]d1f0a7f2012-06-05 10:26:421403 }
1404
[email protected]31afdf72013-09-26 04:29:361405 base::TimeTicks update_starred_start_time(base::TimeTicks::Now());
[email protected]cc63dea2008-08-21 20:56:311406 UpdateStarredStateOfMatches();
[email protected]31afdf72013-09-26 04:29:361407 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateStarredTime",
1408 base::TimeTicks::Now() - update_starred_start_time);
[email protected]4ab4c7c2010-11-24 04:49:341409 UpdateDone();
[email protected]31afdf72013-09-26 04:29:361410 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateMatchesTime",
1411 base::TimeTicks::Now() - update_matches_start_time);
[email protected]257ab712009-04-14 17:16:241412}
1413
1414void SearchProvider::AddNavigationResultsToMatches(
[email protected]d30268a2013-06-25 22:31:071415 const NavigationResults& navigation_results,
1416 ACMatches* matches) {
[email protected]bc8bb0cd2013-06-24 21:50:231417 for (NavigationResults::const_iterator it = navigation_results.begin();
1418 it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:071419 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:231420 // In the absence of suggested relevance scores, use only the single
1421 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:071422 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:231423 return;
[email protected]257ab712009-04-14 17:16:241424 }
1425}
1426
1427void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
1428 bool is_keyword,
1429 int did_not_accept_suggestion,
1430 MatchMap* map) {
[email protected]51124552011-07-16 01:37:101431 if (results.empty())
1432 return;
1433
[email protected]31afdf72013-09-26 04:29:361434 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]d7ad4772012-06-01 03:12:541435 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1436 (input_.type() == AutocompleteInput::URL);
[email protected]14710852013-02-05 23:45:411437 const string16& input_text =
1438 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:101439 bool input_multiple_words = HasMultipleWords(input_text);
1440
[email protected]55ce8f12012-05-09 04:44:081441 SuggestResults scored_results;
1442 if (!prevent_inline_autocomplete && input_multiple_words) {
1443 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1444 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:101445 // autocompleting a multi-word, multi-visit query, and the current input is
1446 // still a prefix of it, then changing the autocompletion suddenly feels
1447 // wrong. To detect this case, first score as if only one word has been
1448 // typed, then check for a best result that is an autocompleted, multi-word
1449 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:081450 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1451 false, input_text, is_keyword);
[email protected]9dfb4d362013-04-05 02:15:121452 if ((scored_results.front().relevance() <
[email protected]55ce8f12012-05-09 04:44:081453 AutocompleteResult::kLowestDefaultScore) ||
[email protected]9dfb4d362013-04-05 02:15:121454 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:081455 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:101456 }
[email protected]55ce8f12012-05-09 04:44:081457 if (scored_results.empty())
1458 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1459 input_multiple_words, input_text,
1460 is_keyword);
1461 for (SuggestResults::const_iterator i(scored_results.begin());
1462 i != scored_results.end(); ++i) {
[email protected]621ade062013-10-28 06:27:431463 AddMatchToMap(input_text,
1464 i->relevance(),
1465 false,
1466 false,
1467 std::string(),
1468 AutocompleteMatchType::SEARCH_HISTORY,
1469 is_keyword,
1470 i->suggestion(),
1471 string16(),
1472 i->suggestion(),
1473 did_not_accept_suggestion,
1474 std::string(),
1475 map);
[email protected]51124552011-07-16 01:37:101476 }
[email protected]31afdf72013-09-26 04:29:361477 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1478 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:101479}
1480
[email protected]55ce8f12012-05-09 04:44:081481SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:101482 const HistoryResults& results,
1483 bool base_prevent_inline_autocomplete,
1484 bool input_multiple_words,
1485 const string16& input_text,
1486 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:481487 AutocompleteClassifier* classifier =
1488 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:081489 SuggestResults scored_results;
[email protected]78e5e432013-08-03 02:10:101490 const bool prevent_search_history_inlining =
1491 OmniboxFieldTrial::SearchHistoryPreventInlining(
1492 input_.current_page_classification());
[email protected]257ab712009-04-14 17:16:241493 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1494 ++i) {
[email protected]51124552011-07-16 01:37:101495 // Don't autocomplete multi-word queries that have only been seen once
1496 // unless the user has typed more than one word.
1497 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1498 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
1499
[email protected]ea3b9a502011-04-04 14:19:371500 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:101501 // when typed. For example, if the user searched for "google.com" and types
1502 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1503 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:481504 // NOTE: We don't check this in the following cases:
1505 // * When inline autocomplete is disabled, we won't be inline
1506 // autocompleting this term, so we don't need to worry about confusion as
1507 // much. This also prevents calling Classify() again from inside the
1508 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:101509 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:481510 // * When the user has typed the whole term, the "what you typed" history
1511 // match will outrank us for URL-like inputs anyway, so we need not do
1512 // anything special.
[email protected]51124552011-07-16 01:37:101513 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:371514 AutocompleteMatch match;
[email protected]f608ea102013-03-18 15:08:091515 classifier->Classify(i->term, false, false, &match, NULL);
[email protected]2905f742011-10-13 03:51:581516 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:461517 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:371518 }
[email protected]51124552011-07-16 01:37:101519
[email protected]78e5e432013-08-03 02:10:101520 int relevance = CalculateRelevanceForHistory(
1521 i->time, is_keyword, !prevent_inline_autocomplete,
1522 prevent_search_history_inlining);
[email protected]d30268a2013-06-25 22:31:071523 scored_results.push_back(
[email protected]621ade062013-10-28 06:27:431524 SuggestResult(i->term, string16(), string16(), std::string(),
1525 is_keyword, relevance, false, false));
[email protected]257ab712009-04-14 17:16:241526 }
[email protected]51124552011-07-16 01:37:101527
1528 // History returns results sorted for us. However, we may have docked some
1529 // results' scores, so things are no longer in order. Do a stable sort to get
1530 // things back in order without otherwise disturbing results with equal
1531 // scores, then force the scores to be unique, so that the order in which
1532 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081533 std::stable_sort(scored_results.begin(), scored_results.end(),
1534 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101535 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081536 for (SuggestResults::iterator i(scored_results.begin());
1537 i != scored_results.end(); ++i) {
1538 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1539 i->set_relevance(last_relevance - 1);
1540 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101541 }
1542
[email protected]55ce8f12012-05-09 04:44:081543 return scored_results;
[email protected]257ab712009-04-14 17:16:241544}
1545
[email protected]55ce8f12012-05-09 04:44:081546void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
[email protected]987fad782013-08-28 06:23:181547 const std::string& metadata,
[email protected]55ce8f12012-05-09 04:44:081548 MatchMap* map) {
[email protected]55ce8f12012-05-09 04:44:081549 for (size_t i = 0; i < results.size(); ++i) {
[email protected]188b50c2013-03-28 07:19:421550 const bool is_keyword = results[i].from_keyword_provider();
1551 const string16& input = is_keyword ? keyword_input_.text() : input_.text();
[email protected]621ade062013-10-28 06:27:431552 AddMatchToMap(input,
1553 results[i].relevance(),
[email protected]d30268a2013-06-25 22:31:071554 results[i].relevance_from_server(),
[email protected]621ade062013-10-28 06:27:431555 results[i].should_prefetch(),
1556 metadata,
1557 AutocompleteMatchType::SEARCH_SUGGEST,
1558 is_keyword,
1559 results[i].match_contents(),
1560 results[i].annotation(),
1561 results[i].suggestion(),
1562 i,
1563 results[i].suggest_query_params(),
1564 map);
[email protected]257ab712009-04-14 17:16:241565 }
initial.commit09911bf2008-07-26 23:55:291566}
1567
[email protected]d30268a2013-06-25 22:31:071568int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561569 // Use the suggested verbatim relevance score if it is non-negative (valid),
1570 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281571 // and if it won't suppress verbatim, leaving no default provider matches.
1572 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561573 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281574 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561575 // Check for results on each verbatim calculation, as results from older
1576 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231577 bool use_server_relevance =
1578 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281579 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231580 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241581 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231582 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071583 if (relevance_from_server)
1584 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231585 return use_server_relevance ?
1586 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521587}
[email protected]d1f0a7f2012-06-05 10:26:421588
[email protected]382a0642012-06-06 06:13:521589int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471590 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361591 return 250;
[email protected]dab8d52d2013-03-05 07:35:281592 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1593}
[email protected]52d08b12009-10-19 18:42:361594
[email protected]dab8d52d2013-03-05 07:35:281595int SearchProvider::
1596 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291597 switch (input_.type()) {
1598 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361599 case AutocompleteInput::QUERY:
1600 case AutocompleteInput::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131601 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291602
initial.commit09911bf2008-07-26 23:55:291603 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361604 return 850;
initial.commit09911bf2008-07-26 23:55:291605
1606 default:
1607 NOTREACHED();
1608 return 0;
1609 }
1610}
1611
[email protected]d30268a2013-06-25 22:31:071612int SearchProvider::GetKeywordVerbatimRelevance(
1613 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281614 // Use the suggested verbatim relevance score if it is non-negative (valid),
1615 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1616 // and if it won't suppress verbatim, leaving no keyword provider matches.
1617 // Otherwise, if the keyword provider returned no matches and was still able
1618 // to suppress verbatim, the user would have no search/nav matches and may be
1619 // left unable to search using their keyword provider from the omnibox.
1620 // Check for results on each verbatim calculation, as results from older
1621 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231622 bool use_server_relevance =
1623 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281624 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231625 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241626 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231627 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071628 if (relevance_from_server)
1629 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231630 return use_server_relevance ?
1631 keyword_results_.verbatim_relevance :
1632 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1633 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451634}
1635
[email protected]51124552011-07-16 01:37:101636int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231637 const base::Time& time,
[email protected]51124552011-07-16 01:37:101638 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101639 bool use_aggressive_method,
1640 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181641 // The relevance of past searches falls off over time. There are two distinct
1642 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101643 // provider that we want to score aggressively), the score is in the range
1644 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161645 // it's in the range 1200-1299). If the second equation is used the
1646 // relevance of a search 15 minutes ago is discounted 50 points, while the
1647 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231648 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421649 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101650 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181651 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101652 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181653 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161654 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101655 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161656 max_score = 1299;
1657 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181658 std::pow(elapsed_time / autocomplete_time, 2.5));
1659 }
1660 elapsed_time -= autocomplete_time;
1661 }
1662
[email protected]c3a4bd992010-08-18 20:25:011663 const int score_discount =
1664 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291665
[email protected]6c85aa02009-02-27 12:08:091666 // Don't let scores go below 0. Negative relevance scores are meaningful in
1667 // a different way.
initial.commit09911bf2008-07-26 23:55:291668 int base_score;
[email protected]51124552011-07-16 01:37:101669 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361670 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101671 else
1672 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291673 return std::max(0, base_score - score_discount);
1674}
1675
[email protected]621ade062013-10-28 06:27:431676void SearchProvider::AddMatchToMap(const string16& input_text,
initial.commit09911bf2008-07-26 23:55:291677 int relevance,
[email protected]d30268a2013-06-25 22:31:071678 bool relevance_from_server,
[email protected]987fad782013-08-28 06:23:181679 bool should_prefetch,
1680 const std::string& metadata,
[email protected]4c1fb7ec2008-11-13 00:19:001681 AutocompleteMatch::Type type,
[email protected]257ab712009-04-14 17:16:241682 bool is_keyword,
[email protected]621ade062013-10-28 06:27:431683 const string16& match_contents,
1684 const string16& annotation,
1685 const string16& query_string,
1686 int accepted_suggestion,
1687 const std::string& suggest_query_params,
initial.commit09911bf2008-07-26 23:55:291688 MatchMap* map) {
[email protected]c4a9d4c2013-08-10 07:06:271689 // On non-mobile, ask the instant controller for the appropriate start margin.
1690 // On mobile the start margin is unused, so leave the value as default there.
1691 int omnibox_start_margin = chrome::kDisableStartMargin;
1692#if !defined(OS_ANDROID) && !defined(IOS)
1693 if (chrome::IsInstantExtendedAPIEnabled()) {
1694 Browser* browser =
1695 chrome::FindBrowserWithProfile(profile_, chrome::GetActiveDesktop());
1696 if (browser && browser->instant_controller() &&
1697 browser->instant_controller()->instant()) {
1698 omnibox_start_margin =
1699 browser->instant_controller()->instant()->omnibox_bounds().x();
1700 }
1701 }
1702#endif // !defined(OS_ANDROID) && !defined(IOS)
1703
[email protected]bba9e632013-06-28 22:52:191704 const TemplateURL* template_url = is_keyword ?
1705 providers_.GetKeywordProviderURL() : providers_.GetDefaultProviderURL();
[email protected]621ade062013-10-28 06:27:431706 AutocompleteMatch match = CreateSearchSuggestion(
1707 this, input_, input_text, relevance, type, is_keyword, match_contents,
1708 annotation, template_url, query_string, suggest_query_params,
[email protected]c4a9d4c2013-08-10 07:06:271709 accepted_suggestion, omnibox_start_margin,
[email protected]56fa29592013-07-02 20:25:531710 !is_keyword || providers_.default_provider().empty());
[email protected]cb86ee6f2013-04-28 16:58:151711 if (!match.destination_url.is_valid())
[email protected]85b8d6f2012-05-08 20:53:471712 return;
[email protected]a048de8a2013-10-02 18:30:061713 match.search_terms_args->bookmark_bar_pinned =
1714 profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
[email protected]d30268a2013-06-25 22:31:071715 match.RecordAdditionalInfo(kRelevanceFromServerKey,
1716 relevance_from_server ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181717 match.RecordAdditionalInfo(kShouldPrefetchKey,
1718 should_prefetch ? kTrue : kFalse);
1719
1720 // Metadata is needed only for prefetching queries.
1721 if (should_prefetch)
1722 match.RecordAdditionalInfo(kSuggestMetadataKey, metadata);
[email protected]85b8d6f2012-05-08 20:53:471723
initial.commit09911bf2008-07-26 23:55:291724 // Try to add |match| to |map|. If a match for |query_string| is already in
1725 // |map|, replace it if |match| is more relevant.
1726 // NOTE: Keep this ToLower() call in sync with url_database.cc.
[email protected]621ade062013-10-28 06:27:431727 MatchKey match_key(
1728 std::make_pair(base::i18n::ToLower(query_string),
1729 match.search_terms_args->suggest_query_params));
[email protected]bc8bb0cd2013-06-24 21:50:231730 const std::pair<MatchMap::iterator, bool> i(
[email protected]621ade062013-10-28 06:27:431731 map->insert(std::make_pair(match_key, match)));
[email protected]987fad782013-08-28 06:23:181732
1733 if (!i.second) {
1734 // NOTE: We purposefully do a direct relevance comparison here instead of
1735 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items
1736 // added first" rather than "items alphabetically first" when the scores are
1737 // equal. The only case this matters is when a user has results with the
1738 // same score that differ only by capitalization; because the history system
1739 // returns results sorted by recency, this means we'll pick the most
1740 // recent such result even if the precision of our relevance score is too
1741 // low to distinguish the two.
1742 if (match.relevance > i.first->second.relevance) {
1743 i.first->second = match;
1744 } else if (match.keyword == i.first->second.keyword) {
1745 // Old and new matches are from the same search provider. It is okay to
1746 // record one match's prefetch data onto a different match (for the same
1747 // query string) for the following reasons:
1748 // 1. Because the suggest server only sends down a query string from which
1749 // we construct a URL, rather than sending a full URL, and because we
1750 // construct URLs from query strings in the same way every time, the URLs
1751 // for the two matches will be the same. Therefore, we won't end up
1752 // prefetching something the server didn't intend.
1753 // 2. Presumably the server sets the prefetch bit on a match it things is
1754 // sufficiently relevant that the user is likely to choose it. Surely
1755 // setting the prefetch bit on a match of even higher relevance won't
1756 // violate this assumption.
1757 should_prefetch |= ShouldPrefetch(i.first->second);
1758 i.first->second.RecordAdditionalInfo(kShouldPrefetchKey,
1759 should_prefetch ? kTrue : kFalse);
1760 if (should_prefetch)
1761 i.first->second.RecordAdditionalInfo(kSuggestMetadataKey, metadata);
1762 }
1763 }
initial.commit09911bf2008-07-26 23:55:291764}
1765
1766AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421767 const NavigationResult& navigation) {
1768 const string16& input = navigation.from_keyword_provider() ?
1769 keyword_input_.text() : input_.text();
[email protected]55ce8f12012-05-09 04:44:081770 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]b7f64d742013-05-21 04:04:041771 AutocompleteMatchType::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081772 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551773
1774 // First look for the user's input inside the fill_into_edit as it would be
1775 // without trimming the scheme, so we can find matches at the beginning of the
1776 // scheme.
[email protected]a1b5e862013-03-29 06:38:441777 const string16& untrimmed_fill_into_edit = navigation.formatted_url();
[email protected]371dab12012-06-01 03:23:551778 const URLPrefix* prefix =
1779 URLPrefix::BestURLPrefix(untrimmed_fill_into_edit, input);
1780 size_t match_start = (prefix == NULL) ?
1781 untrimmed_fill_into_edit.find(input) : prefix->prefix.length();
1782 size_t inline_autocomplete_offset = (prefix == NULL) ?
1783 string16::npos : (match_start + input.length());
[email protected]d2445c82013-11-04 22:28:351784 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1785 (!prefix || (match_start != 0));
[email protected]371dab12012-06-01 03:23:551786
[email protected]371dab12012-06-01 03:23:551787 const std::string languages(
1788 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1789 const net::FormatUrlTypes format_types =
1790 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1791 match.fill_into_edit +=
1792 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1793 net::FormatUrl(navigation.url(), languages, format_types,
1794 net::UnescapeRule::SPACES, NULL, NULL,
1795 &inline_autocomplete_offset));
[email protected]14119032013-11-07 08:14:261796 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1797 // Otherwise, user edits to a suggestion would show non-Search results.
1798 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
1799 match.fill_into_edit.insert(0, ASCIIToUTF16("?"));
1800 if (inline_autocomplete_offset != string16::npos)
1801 ++inline_autocomplete_offset;
1802 }
[email protected]518024c2013-07-19 23:40:251803 if (!input_.prevent_inline_autocomplete() &&
1804 (inline_autocomplete_offset != string16::npos)) {
1805 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
[email protected]45f89a92013-08-12 13:41:361806 match.allowed_to_be_default_match = true;
[email protected]518024c2013-07-19 23:40:251807 match.inline_autocompletion =
1808 match.fill_into_edit.substr(inline_autocomplete_offset);
1809 }
[email protected]371dab12012-06-01 03:23:551810
1811 match.contents = net::FormatUrl(navigation.url(), languages,
1812 format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1813 // If the first match in the untrimmed string was inside a scheme that we
1814 // trimmed, look for a subsequent match.
1815 if (match_start == string16::npos)
1816 match_start = match.contents.find(input);
1817 // Safe if |match_start| is npos; also safe if the input is longer than the
1818 // remaining contents after |match_start|.
1819 AutocompleteMatch::ClassifyLocationInString(match_start, input.length(),
1820 match.contents.length(), ACMatchClassification::URL,
1821 &match.contents_class);
initial.commit09911bf2008-07-26 23:55:291822
[email protected]55ce8f12012-05-09 04:44:081823 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551824 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1825 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071826
1827 match.RecordAdditionalInfo(
1828 kRelevanceFromServerKey,
1829 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181830 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071831
initial.commit09911bf2008-07-26 23:55:291832 return match;
1833}
[email protected]4ab4c7c2010-11-24 04:49:341834
[email protected]9dfb4d362013-04-05 02:15:121835void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
[email protected]d519d392013-03-27 09:24:461836 // First, determine the maximum score of any keyword query match (verbatim or
1837 // query suggestion).
[email protected]d30268a2013-06-25 22:31:071838 bool relevance_from_server;
1839 int max_query_relevance = GetKeywordVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:241840 if (!keyword_results_.suggest_results.empty()) {
[email protected]d30268a2013-06-25 22:31:071841 const SuggestResult& top_keyword = keyword_results_.suggest_results.front();
1842 const int suggest_relevance = top_keyword.relevance();
1843 if (suggest_relevance > max_query_relevance) {
1844 max_query_relevance = suggest_relevance;
1845 relevance_from_server = top_keyword.relevance_from_server();
1846 } else if (suggest_relevance == max_query_relevance) {
1847 relevance_from_server |= top_keyword.relevance_from_server();
1848 }
[email protected]d519d392013-03-27 09:24:461849 }
1850 // If no query is supposed to appear, then navigational matches cannot
[email protected]9dfb4d362013-04-05 02:15:121851 // be demoted past it. Get rid of suggested relevance scores for
1852 // navsuggestions and introduce the verbatim results again. The keyword
1853 // verbatim match will outscore the navsuggest matches.
1854 if (max_query_relevance == 0) {
[email protected]cc1526e2013-05-17 04:04:241855 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
1856 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
1857 keyword_results_.verbatim_relevance = -1;
1858 default_results_.verbatim_relevance = -1;
[email protected]9dfb4d362013-04-05 02:15:121859 return;
1860 }
[email protected]d519d392013-03-27 09:24:461861 // Now we know we can enforce the minimum score constraint even after
1862 // the navigation matches are demoted. Proceed to demote the navigation
1863 // matches to enforce the query-must-come-first constraint.
[email protected]d519d392013-03-27 09:24:461864 // Cap the relevance score of all results.
[email protected]cc1526e2013-05-17 04:04:241865 for (NavigationResults::iterator it =
1866 keyword_results_.navigation_results.begin();
1867 it != keyword_results_.navigation_results.end(); ++it) {
[email protected]9dfb4d362013-04-05 02:15:121868 if (it->relevance() < max_query_relevance)
1869 return;
1870 max_query_relevance = std::max(max_query_relevance - 1, 0);
1871 it->set_relevance(max_query_relevance);
[email protected]d30268a2013-06-25 22:31:071872 it->set_relevance_from_server(relevance_from_server);
[email protected]d519d392013-03-27 09:24:461873 }
[email protected]d519d392013-03-27 09:24:461874}
1875
[email protected]4ab4c7c2010-11-24 04:49:341876void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331877 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311878 // pending, and we're not waiting on Instant.
[email protected]e1290ee62013-06-26 18:31:151879 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
[email protected]4ab4c7c2010-11-24 04:49:341880}