blob: b38ffbd7ea2b492a8ffb3a4983147ced516533a4 [file] [log] [blame]
[email protected]e41982a72012-11-20 07:16:511// Copyright 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
5#include "chrome/browser/autocomplete/search_provider.h"
6
[email protected]1cb2dac2010-03-08 21:49:157#include <algorithm>
[email protected]c3a4bd992010-08-18 20:25:018#include <cmath>
[email protected]1cb2dac2010-03-08 21:49:159
[email protected]bb900e02013-03-14 14:15:2910#include "base/auto_reset.h"
[email protected]2041cf342010-02-19 03:15:5911#include "base/callback.h"
[email protected]51124552011-07-16 01:37:1012#include "base/i18n/break_iterator.h"
[email protected]503d03872011-05-06 08:36:2613#include "base/i18n/case_conversion.h"
[email protected]d6e58c6e2009-10-10 20:40:5014#include "base/i18n/icu_string_conversions.h"
[email protected]ffbec692012-02-26 20:26:4215#include "base/json/json_string_value_serializer.h"
initial.commit09911bf2008-07-26 23:55:2916#include "base/message_loop.h"
[email protected]f5b95ba92012-03-27 14:05:1917#include "base/metrics/histogram.h"
[email protected]3853a4c2013-02-11 17:15:5718#include "base/prefs/pref_service.h"
[email protected]dc9a6762010-08-16 07:13:5319#include "base/string16.h"
[email protected]371dab12012-06-01 03:23:5520#include "base/string_util.h"
[email protected]1cb2dac2010-03-08 21:49:1521#include "base/utf_string_conversions.h"
[email protected]ea3b9a502011-04-04 14:19:3722#include "chrome/browser/autocomplete/autocomplete_classifier.h"
[email protected]810ffba2012-06-12 01:07:4823#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
[email protected]9ac40092010-10-27 23:05:2624#include "chrome/browser/autocomplete/autocomplete_match.h"
[email protected]5af9bc82012-06-29 00:53:4825#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
[email protected]73c2b1632012-07-02 22:51:3826#include "chrome/browser/autocomplete/autocomplete_result.h"
[email protected]2c812ba02011-07-14 00:23:1527#include "chrome/browser/autocomplete/keyword_provider.h"
[email protected]371dab12012-06-01 03:23:5528#include "chrome/browser/autocomplete/url_prefix.h"
[email protected]6a2c09f2013-01-25 04:50:0729#include "chrome/browser/history/history_service.h"
[email protected]9d2db762012-06-19 00:01:1030#include "chrome/browser/history/history_service_factory.h"
[email protected]10c2d692012-05-11 05:32:2331#include "chrome/browser/history/in_memory_database.h"
[email protected]ab7780792013-01-10 01:26:0932#include "chrome/browser/metrics/variations/variations_http_header_provider.h"
[email protected]f870a322009-01-16 21:47:2733#include "chrome/browser/net/url_fixer_upper.h"
[email protected]684fcc12013-03-08 22:50:0234#include "chrome/browser/omnibox/omnibox_field_trial.h"
[email protected]8ecad5e2010-12-02 21:18:3335#include "chrome/browser/profiles/profile.h"
[email protected]a7b8e43d2013-03-18 18:52:4336#include "chrome/browser/search/search.h"
[email protected]a0ad93ea2012-05-07 22:11:5337#include "chrome/browser/search_engines/search_engine_type.h"
[email protected]9899a612012-08-21 23:50:0438#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
[email protected]8e5c89a2011-06-07 18:13:3339#include "chrome/browser/search_engines/template_url_service.h"
40#include "chrome/browser/search_engines/template_url_service_factory.h"
initial.commit09911bf2008-07-26 23:55:2941#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0242#include "chrome/common/url_constants.h"
initial.commit09911bf2008-07-26 23:55:2943#include "googleurl/src/url_util.h"
[email protected]34ac8f32009-02-22 23:03:2744#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2945#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3446#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5547#include "net/base/net_util.h"
[email protected]bd3b4712012-12-18 17:01:3048#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2149#include "net/http/http_response_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5350#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2151#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1752#include "ui/base/l10n/l10n_util.h"
initial.commit09911bf2008-07-26 23:55:2953
[email protected]e1acf6f2008-10-27 20:43:3354using base::Time;
55using base::TimeDelta;
56
[email protected]51124552011-07-16 01:37:1057namespace {
58
[email protected]7706a522012-08-16 17:42:2559// We keep track in a histogram how many suggest requests we send, how
60// many suggest requests we invalidate (e.g., due to a user typing
61// another character), and how many replies we receive.
62// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
63// (excluding the end-of-list enum value)
64// We do not want values of existing enums to change or else it screws
65// up the statistics.
66enum SuggestRequestsHistogramValue {
67 REQUEST_SENT = 1,
68 REQUEST_INVALIDATED,
69 REPLY_RECEIVED,
70 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
71};
72
[email protected]90fe2bb2013-01-15 03:42:1373// The verbatim score for an input which is not an URL.
74const int kNonURLVerbatimRelevance = 1300;
75
[email protected]7706a522012-08-16 17:42:2576// Increments the appropriate value in the histogram by one.
77void LogOmniboxSuggestRequest(
78 SuggestRequestsHistogramValue request_value) {
79 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
80 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
81}
82
[email protected]51124552011-07-16 01:37:1083bool HasMultipleWords(const string16& text) {
84 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
85 bool found_word = false;
86 if (i.Init()) {
87 while (i.Advance()) {
88 if (i.IsWord()) {
89 if (found_word)
90 return true;
91 found_word = true;
92 }
93 }
94 }
95 return false;
96}
97
[email protected]d1f0a7f2012-06-05 10:26:4298} // namespace
[email protected]51124552011-07-16 01:37:1099
[email protected]033f3422012-03-13 21:24:18100
[email protected]3954c3a2012-04-10 20:17:55101// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:58102
[email protected]85b8d6f2012-05-08 20:53:47103SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
104 : template_url_service_(template_url_service) {
105}
106
107const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
108 return default_provider_.empty() ? NULL :
109 template_url_service_->GetTemplateURLForKeyword(default_provider_);
110}
111
112const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
113 return keyword_provider_.empty() ? NULL :
114 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24115}
116
[email protected]3954c3a2012-04-10 20:17:55117
118// SearchProvider -------------------------------------------------------------
119
120// static
121const int SearchProvider::kDefaultProviderURLFetcherID = 1;
122// static
123const int SearchProvider::kKeywordProviderURLFetcherID = 2;
[email protected]24dbf2302013-04-05 16:59:25124// static
125int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]3954c3a2012-04-10 20:17:55126
[email protected]cb86ee6f2013-04-28 16:58:15127// static
128AutocompleteMatch SearchProvider::CreateSearchSuggestion(
129 Profile* profile,
130 AutocompleteProvider* autocomplete_provider,
131 const AutocompleteInput& input,
132 const string16& query_string,
133 const string16& input_text,
134 int relevance,
135 AutocompleteMatch::Type type,
136 int accepted_suggestion,
137 bool is_keyword,
138 const string16& keyword) {
139 AutocompleteMatch match(autocomplete_provider, relevance, false, type);
140
141 // Bail out now if we don't actually have a valid provider.
142 match.keyword = keyword;
143 const TemplateURL* provider_url = match.GetTemplateURL(profile, false);
144 if (provider_url == NULL)
145 return match;
146
147 match.contents.assign(query_string);
148 // We do intra-string highlighting for suggestions - the suggested segment
149 // will be highlighted, e.g. for input_text = "you" the suggestion may be
150 // "youtube", so we'll bold the "tube" section: you*tube*.
151 if (input_text != query_string) {
152 size_t input_position = match.contents.find(input_text);
153 if (input_position == string16::npos) {
154 // The input text is not a substring of the query string, e.g. input
155 // text is "slasdot" and the query string is "slashdot", so we bold the
156 // whole thing.
157 match.contents_class.push_back(
158 ACMatchClassification(0, ACMatchClassification::MATCH));
159 } else {
160 // TODO(beng): ACMatchClassification::MATCH now seems to just mean
161 // "bold" this. Consider modifying the terminology.
162 // We don't iterate over the string here annotating all matches because
163 // it looks odd to have every occurrence of a substring that may be as
164 // short as a single character highlighted in a query suggestion result,
165 // e.g. for input text "s" and query string "southwest airlines", it
166 // looks odd if both the first and last s are highlighted.
167 if (input_position != 0) {
168 match.contents_class.push_back(
169 ACMatchClassification(0, ACMatchClassification::NONE));
170 }
171 match.contents_class.push_back(
172 ACMatchClassification(input_position, ACMatchClassification::DIM));
173 size_t next_fragment_position = input_position + input_text.length();
174 if (next_fragment_position < query_string.length()) {
175 match.contents_class.push_back(
176 ACMatchClassification(next_fragment_position,
177 ACMatchClassification::NONE));
178 }
179 }
180 } else {
181 // Otherwise, we're dealing with the "default search" result which has no
182 // completion.
183 match.contents_class.push_back(
184 ACMatchClassification(0, ACMatchClassification::NONE));
185 }
186
187 // When the user forced a query, we need to make sure all the fill_into_edit
188 // values preserve that property. Otherwise, if the user starts editing a
189 // suggestion, non-Search results will suddenly appear.
190 if (input.type() == AutocompleteInput::FORCED_QUERY)
191 match.fill_into_edit.assign(ASCIIToUTF16("?"));
192 if (is_keyword)
193 match.fill_into_edit.append(match.keyword + char16(' '));
194 if (!input.prevent_inline_autocomplete() &&
195 StartsWith(query_string, input_text, false)) {
196 match.inline_autocomplete_offset =
197 match.fill_into_edit.length() + input_text.length();
198 }
199 match.fill_into_edit.append(query_string);
200
201 const TemplateURLRef& search_url = provider_url->url_ref();
202 DCHECK(search_url.SupportsReplacement());
203 match.search_terms_args.reset(
204 new TemplateURLRef::SearchTermsArgs(query_string));
205 match.search_terms_args->original_query = input_text;
206 match.search_terms_args->accepted_suggestion = accepted_suggestion;
207 // This is the destination URL sans assisted query stats. This must be set
208 // so the AutocompleteController can properly de-dupe; the controller will
209 // eventually overwrite it before it reaches the user.
210 match.destination_url =
211 GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get()));
212
213 // Search results don't look like URLs.
214 match.transition = is_keyword ?
215 content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED;
216
217 return match;
218}
219
[email protected]30f5bc92012-06-26 04:14:55220SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
221 Profile* profile)
[email protected]35f1f4f02012-09-11 13:17:00222 : AutocompleteProvider(listener, profile,
223 AutocompleteProvider::TYPE_SEARCH),
[email protected]85b8d6f2012-05-08 20:53:47224 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
[email protected]601858c02010-09-01 17:08:20225 suggest_results_pending_(0),
[email protected]dab8d52d2013-03-05 07:35:28226 has_default_suggested_relevance_(false),
227 has_keyword_suggested_relevance_(false),
228 default_verbatim_relevance_(-1),
229 keyword_verbatim_relevance_(-1),
[email protected]8e5cc282010-12-05 18:11:39230 have_suggest_results_(false),
[email protected]618d6e62012-12-16 05:55:57231 instant_finalized_(false),
232 field_trial_triggered_(false),
233 field_trial_triggered_in_session_(false) {
[email protected]4ab4c7c2010-11-24 04:49:34234}
235
[email protected]a2fedb1e2011-01-25 15:23:36236void SearchProvider::FinalizeInstantQuery(const string16& input_text,
[email protected]93b73832012-10-18 20:18:38237 const InstantSuggestion& suggestion) {
[email protected]4ab4c7c2010-11-24 04:49:34238 if (done_ || instant_finalized_)
239 return;
240
241 instant_finalized_ = true;
242 UpdateDone();
243
[email protected]e918c112010-12-08 23:03:49244 if (input_text.empty()) {
[email protected]4ab4c7c2010-11-24 04:49:34245 // We only need to update the listener if we're actually done.
246 if (done_)
247 listener_->OnProviderUpdate(false);
248 return;
249 }
250
[email protected]93b73832012-10-18 20:18:38251 default_provider_suggestion_ = suggestion;
[email protected]9e789742011-01-10 23:27:32252
[email protected]a2fedb1e2011-01-25 15:23:36253 string16 adjusted_input_text(input_text);
[email protected]e918c112010-12-08 23:03:49254 AutocompleteInput::RemoveForcedQueryStringIfNecessary(input_.type(),
255 &adjusted_input_text);
256
[email protected]93b73832012-10-18 20:18:38257 const string16 text = adjusted_input_text + suggestion.text;
[email protected]9acdcdc02012-05-21 20:58:36258 bool results_updated = false;
[email protected]4ab4c7c2010-11-24 04:49:34259 // Remove any matches that are identical to |text|. We don't use the
260 // destination_url for comparison as it varies depending upon the index passed
261 // to TemplateURL::ReplaceSearchTerms.
262 for (ACMatches::iterator i = matches_.begin(); i != matches_.end();) {
263 if (((i->type == AutocompleteMatch::SEARCH_HISTORY) ||
264 (i->type == AutocompleteMatch::SEARCH_SUGGEST)) &&
265 (i->fill_into_edit == text)) {
[email protected]e030de62010-11-24 05:41:19266 i = matches_.erase(i);
[email protected]9acdcdc02012-05-21 20:58:36267 results_updated = true;
[email protected]4ab4c7c2010-11-24 04:49:34268 } else {
269 ++i;
270 }
271 }
272
[email protected]5fac3782013-03-06 09:32:31273 // Add the new Instant suggest result.
[email protected]93b73832012-10-18 20:18:38274 if (suggestion.type == INSTANT_SUGGESTION_SEARCH) {
[email protected]90fe2bb2013-01-15 03:42:13275 // Instant has a query suggestion. Rank it higher than SEARCH_WHAT_YOU_TYPED
276 // so that it gets autocompleted.
277 const int verbatim_relevance = GetVerbatimRelevance();
[email protected]93b73832012-10-18 20:18:38278 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
[email protected]4ab4c7c2010-11-24 04:49:34279 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
280 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]93b73832012-10-18 20:18:38281 MatchMap match_map;
282 AddMatchToMap(text, adjusted_input_text, verbatim_relevance + 1,
283 AutocompleteMatch::SEARCH_SUGGEST,
284 did_not_accept_default_suggestion, false, &match_map);
285 if (!match_map.empty()) {
286 matches_.push_back(match_map.begin()->second);
287 results_updated = true;
288 }
289 } else {
[email protected]c112f0fe72013-01-18 20:30:09290 // Instant has a URL suggestion. Rank it higher than URL_WHAT_YOU_TYPED so
[email protected]90fe2bb2013-01-15 03:42:13291 // it gets autocompleted; use kNonURLVerbatimRelevance rather than
292 // verbatim_relevance so that the score does not change if the user keeps
293 // typing and the input changes from type UNKNOWN to URL.
[email protected]93b73832012-10-18 20:18:38294 matches_.push_back(NavigationToMatch(
[email protected]a1b5e862013-03-29 06:38:44295 NavigationResult(*this,
296 GURL(UTF16ToUTF8(suggestion.text)),
[email protected]93b73832012-10-18 20:18:38297 string16(),
[email protected]188b50c2013-03-28 07:19:42298 false,
299 kNonURLVerbatimRelevance + 1)));
[email protected]9acdcdc02012-05-21 20:58:36300 results_updated = true;
301 }
[email protected]4ab4c7c2010-11-24 04:49:34302
[email protected]9acdcdc02012-05-21 20:58:36303 if (results_updated || done_)
304 listener_->OnProviderUpdate(results_updated);
[email protected]601858c02010-09-01 17:08:20305}
306
[email protected]0a633ba92013-03-26 09:13:47307void SearchProvider::ClearInstantSuggestion() {
308 default_provider_suggestion_ = InstantSuggestion();
309 if (done_ || instant_finalized_)
310 return;
311 instant_finalized_ = true;
312 UpdateMatches();
313 listener_->OnProviderUpdate(true);
314}
315
initial.commit09911bf2008-07-26 23:55:29316void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27317 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55318 // Do our best to load the model as early as possible. This will reduce
319 // odds of having the model not ready when really needed (a non-empty input).
320 TemplateURLService* model = providers_.template_url_service();
321 DCHECK(model);
322 model->Load();
323
initial.commit09911bf2008-07-26 23:55:29324 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57325 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29326
[email protected]ea3b9a502011-04-04 14:19:37327 instant_finalized_ =
328 (input.matches_requested() != AutocompleteInput::ALL_MATCHES);
[email protected]4ab4c7c2010-11-24 04:49:34329
[email protected]6c85aa02009-02-27 12:08:09330 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29331 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]e29249dc52012-07-19 17:33:50332 Stop(false);
initial.commit09911bf2008-07-26 23:55:29333 return;
334 }
335
[email protected]14710852013-02-05 23:45:41336 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24337 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41338 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
339 &keyword_input_);
340 if (keyword_provider == NULL)
341 keyword_input_.Clear();
342 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24343 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24344
[email protected]85b8d6f2012-05-08 20:53:47345 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07346 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24347 default_provider = NULL;
348
349 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18350 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24351
352 if (!default_provider && !keyword_provider) {
353 // No valid providers.
[email protected]e29249dc52012-07-19 17:33:50354 Stop(false);
initial.commit09911bf2008-07-26 23:55:29355 return;
356 }
357
358 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24359 // or the providers, abort the query.
[email protected]85b8d6f2012-05-08 20:53:47360 string16 default_provider_keyword(default_provider ?
361 default_provider->keyword() : string16());
362 string16 keyword_provider_keyword(keyword_provider ?
363 keyword_provider->keyword() : string16());
[email protected]9e789742011-01-10 23:27:32364 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47365 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29366 // If Instant has not come back with a suggestion, adjust the previous
367 // suggestion if possible. If |instant_finalized| is true, we are looking
368 // for synchronous matches only, so the suggestion is cleared.
369 if (instant_finalized_)
[email protected]93b73832012-10-18 20:18:38370 default_provider_suggestion_ = InstantSuggestion();
[email protected]9e789742011-01-10 23:27:32371 else
[email protected]bb900e02013-03-14 14:15:29372 AdjustDefaultProviderSuggestion(input_.text(), input.text());
373
374 // Cancel any in-flight suggest requests.
375 if (!done_) {
376 // The Stop(false) call below clears |default_provider_suggestion_|, but
377 // in this instance we do not want to clear cached results, so we
378 // restore it.
379 base::AutoReset<InstantSuggestion> reset(&default_provider_suggestion_,
380 InstantSuggestion());
[email protected]e29249dc52012-07-19 17:33:50381 Stop(false);
[email protected]bb900e02013-03-14 14:15:29382 }
[email protected]257ab712009-04-14 17:16:24383 }
initial.commit09911bf2008-07-26 23:55:29384
[email protected]85b8d6f2012-05-08 20:53:47385 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29386
387 if (input.text().empty()) {
388 // User typed "?" alone. Give them a placeholder result indicating what
389 // this syntax does.
[email protected]257ab712009-04-14 17:16:24390 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00391 AutocompleteMatch match;
392 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36393 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24394 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35395 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47396 match.keyword = providers_.default_provider();
[email protected]257ab712009-04-14 17:16:24397 matches_.push_back(match);
398 }
[email protected]e29249dc52012-07-19 17:33:50399 Stop(false);
initial.commit09911bf2008-07-26 23:55:29400 return;
401 }
402
403 input_ = input;
404
[email protected]5fac3782013-03-06 09:32:31405 // When Instant is enabled in the extended mode, the embedded page will handle
406 // all search suggestions itself, so don't run the normal provider flow.
407 // TODO(dcblack): Once we are done refactoring the omnibox so we don't need to
[email protected]5cd06c3e2012-09-20 03:25:20408 // use FinalizeInstantQuery anymore, we can take out this check and remove
409 // this provider from kInstantExtendedOmniboxProviders.
[email protected]165fe422013-03-27 06:34:03410 if (!chrome::IsInstantExtendedAPIEnabled() ||
411 !chrome::IsInstantEnabled(profile_)) {
[email protected]5cd06c3e2012-09-20 03:25:20412 DoHistoryQuery(minimal_changes);
413 StartOrStopSuggestQuery(minimal_changes);
414 }
[email protected]344946a12012-12-20 12:03:42415 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29416}
417
[email protected]188b50c2013-03-28 07:19:42418SearchProvider::Result::Result(bool from_keyword_provider, int relevance)
419 : from_keyword_provider_(from_keyword_provider),
420 relevance_(relevance) {
421}
422
[email protected]55ce8f12012-05-09 04:44:08423SearchProvider::Result::~Result() {}
424
425SearchProvider::SuggestResult::SuggestResult(const string16& suggestion,
[email protected]188b50c2013-03-28 07:19:42426 bool from_keyword_provider,
[email protected]55ce8f12012-05-09 04:44:08427 int relevance)
[email protected]188b50c2013-03-28 07:19:42428 : Result(from_keyword_provider, relevance),
[email protected]55ce8f12012-05-09 04:44:08429 suggestion_(suggestion) {
430}
431
432SearchProvider::SuggestResult::~SuggestResult() {}
433
[email protected]a1b5e862013-03-29 06:38:44434bool SearchProvider::SuggestResult::IsInlineable(const string16& input) const {
435 return StartsWith(suggestion_, input, false);
436}
437
[email protected]188b50c2013-03-28 07:19:42438int SearchProvider::SuggestResult::CalculateRelevance(
439 const AutocompleteInput& input,
440 bool keyword_provider_requested) const {
441 if (!from_keyword_provider_ && keyword_provider_requested)
442 return 100;
443 return ((input.type() == AutocompleteInput::URL) ? 300 : 600);
444}
445
446SearchProvider::NavigationResult::NavigationResult(
[email protected]a1b5e862013-03-29 06:38:44447 const AutocompleteProvider& provider,
[email protected]188b50c2013-03-28 07:19:42448 const GURL& url,
449 const string16& description,
450 bool from_keyword_provider,
451 int relevance)
452 : Result(from_keyword_provider, relevance),
[email protected]55ce8f12012-05-09 04:44:08453 url_(url),
[email protected]a1b5e862013-03-29 06:38:44454 formatted_url_(AutocompleteInput::FormattedStringWithEquivalentMeaning(
455 url, provider.StringForURLDisplay(url, true, false))),
[email protected]55ce8f12012-05-09 04:44:08456 description_(description) {
457 DCHECK(url_.is_valid());
458}
459
[email protected]a1b5e862013-03-29 06:38:44460SearchProvider::NavigationResult::~NavigationResult() {}
461
462bool SearchProvider::NavigationResult::IsInlineable(
463 const string16& input) const {
464 return URLPrefix::BestURLPrefix(formatted_url_, input) != NULL;
465}
466
[email protected]188b50c2013-03-28 07:19:42467int SearchProvider::NavigationResult::CalculateRelevance(
468 const AutocompleteInput& input,
469 bool keyword_provider_requested) const {
470 return (from_keyword_provider_ || !keyword_provider_requested) ? 800 : 150;
471}
472
[email protected]55ce8f12012-05-09 04:44:08473class SearchProvider::CompareScoredResults {
[email protected]51124552011-07-16 01:37:10474 public:
[email protected]55ce8f12012-05-09 04:44:08475 bool operator()(const Result& a, const Result& b) {
[email protected]51124552011-07-16 01:37:10476 // Sort in descending relevance order.
[email protected]55ce8f12012-05-09 04:44:08477 return a.relevance() > b.relevance();
[email protected]51124552011-07-16 01:37:10478 }
479};
480
initial.commit09911bf2008-07-26 23:55:29481void SearchProvider::Run() {
482 // Start a new request with the current input.
[email protected]257ab712009-04-14 17:16:24483 suggest_results_pending_ = 0;
[email protected]a0ad93ea2012-05-07 22:11:53484 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]9ff91722012-09-07 05:29:12485
486 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
[email protected]14710852013-02-05 23:45:41487 providers_.GetDefaultProviderURL(), input_));
[email protected]9ff91722012-09-07 05:29:12488 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
[email protected]14710852013-02-05 23:45:41489 providers_.GetKeywordProviderURL(), keyword_input_));
[email protected]85b8d6f2012-05-08 20:53:47490
491 // Both the above can fail if the providers have been modified or deleted
492 // since the query began.
493 if (suggest_results_pending_ == 0) {
494 UpdateDone();
495 // We only need to update the listener if we're actually done.
496 if (done_)
497 listener_->OnProviderUpdate(false);
498 }
initial.commit09911bf2008-07-26 23:55:29499}
500
[email protected]e29249dc52012-07-19 17:33:50501void SearchProvider::Stop(bool clear_cached_results) {
initial.commit09911bf2008-07-26 23:55:29502 StopSuggest();
503 done_ = true;
[email protected]93b73832012-10-18 20:18:38504 default_provider_suggestion_ = InstantSuggestion();
[email protected]e29249dc52012-07-19 17:33:50505
506 if (clear_cached_results)
[email protected]71b46152013-05-03 16:39:20507 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29508}
509
[email protected]0e9e8782012-05-15 23:01:51510void SearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
511 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
512 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
513 new_entry.set_provider(AsOmniboxEventProviderType());
514 new_entry.set_provider_done(done_);
[email protected]fea6d302013-04-13 02:04:06515 std::vector<uint32> field_trial_hashes;
516 OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(&field_trial_hashes);
517 for (size_t i = 0; i < field_trial_hashes.size(); ++i) {
[email protected]618d6e62012-12-16 05:55:57518 if (field_trial_triggered_)
[email protected]fea6d302013-04-13 02:04:06519 new_entry.mutable_field_trial_triggered()->Add(field_trial_hashes[i]);
[email protected]d78d7362012-12-19 18:43:28520 if (field_trial_triggered_in_session_) {
[email protected]618d6e62012-12-16 05:55:57521 new_entry.mutable_field_trial_triggered_in_session()->Add(
[email protected]fea6d302013-04-13 02:04:06522 field_trial_hashes[i]);
[email protected]d78d7362012-12-19 18:43:28523 }
[email protected]618d6e62012-12-16 05:55:57524 }
525}
526
527void SearchProvider::ResetSession() {
528 field_trial_triggered_in_session_ = false;
[email protected]0e9e8782012-05-15 23:01:51529}
530
[email protected]10c2d692012-05-11 05:32:23531void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29532 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24533 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25534 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15535 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06536 const net::HttpResponseHeaders* const response_headers =
[email protected]7cc6e5632011-10-25 17:56:12537 source->GetResponseHeaders();
[email protected]c530c852011-10-24 18:18:34538 std::string json_data;
539 source->GetResponseAsString(&json_data);
[email protected]6c85aa02009-02-27 12:08:09540 // JSON is supposed to be UTF-8, but some suggest service providers send JSON
541 // files in non-UTF-8 encodings. The actual encoding is usually specified in
542 // the Content-Type header field.
[email protected]ec9207d32008-09-26 00:51:06543 if (response_headers) {
544 std::string charset;
545 if (response_headers->GetCharset(&charset)) {
[email protected]a2fedb1e2011-01-25 15:23:36546 string16 data_16;
[email protected]ec9207d32008-09-26 00:51:06547 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
[email protected]c530c852011-10-24 18:18:34548 if (base::CodepageToUTF16(json_data, charset.c_str(),
[email protected]a2fedb1e2011-01-25 15:23:36549 base::OnStringConversionError::FAIL,
550 &data_16))
551 json_data = UTF16ToUTF8(data_16);
[email protected]ec9207d32008-09-26 00:51:06552 }
553 }
554
[email protected]d7ad4772012-06-01 03:12:54555 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]f2916ea2013-01-26 02:20:14556 // Ensure the request succeeded and that the provider used is still available.
557 // A verbatim match cannot be generated without this provider, causing errors.
[email protected]013e9a02012-05-18 20:27:10558 const bool request_succeeded =
[email protected]f2916ea2013-01-26 02:20:14559 source->GetStatus().is_success() && source->GetResponseCode() == 200 &&
560 ((is_keyword && providers_.GetKeywordProviderURL()) ||
561 (!is_keyword && providers_.GetDefaultProviderURL()));
[email protected]a0ad93ea2012-05-07 22:11:53562
563 // Record response time for suggest requests sent to Google. We care
564 // only about the common case: the Google default provider used in
565 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47566 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08567 if (!is_keyword && default_url &&
[email protected]9899a612012-08-21 23:50:04568 (TemplateURLPrepopulateData::GetEngineType(default_url->url()) ==
569 SEARCH_ENGINE_GOOGLE)) {
[email protected]6dc950f2012-07-16 19:49:08570 const TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10571 base::TimeTicks::Now() - time_suggest_request_sent_;
572 if (request_succeeded) {
573 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
574 elapsed_time);
575 } else {
576 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
577 elapsed_time);
578 }
[email protected]b4cebf82008-12-29 19:59:08579 }
580
[email protected]d7ad4772012-06-01 03:12:54581 bool results_updated = false;
582 if (request_succeeded) {
583 JSONStringValueSerializer deserializer(json_data);
584 deserializer.set_allow_trailing_comma(true);
585 scoped_ptr<Value> data(deserializer.Deserialize(NULL, NULL));
586 results_updated = data.get() && ParseSuggestResults(data.get(), is_keyword);
587 }
588
[email protected]344946a12012-12-20 12:03:42589 UpdateMatches();
[email protected]d7ad4772012-06-01 03:12:54590 if (done_ || results_updated)
591 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29592}
593
[email protected]601858c02010-09-01 17:08:20594SearchProvider::~SearchProvider() {
595}
596
[email protected]8d457132010-11-04 18:13:40597void SearchProvider::DoHistoryQuery(bool minimal_changes) {
598 // The history query results are synchronous, so if minimal_changes is true,
599 // we still have the last results and don't need to do anything.
600 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29601 return;
602
[email protected]8d457132010-11-04 18:13:40603 keyword_history_results_.clear();
604 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29605
[email protected]8d457132010-11-04 18:13:40606 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10607 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]8d457132010-11-04 18:13:40608 history::URLDatabase* url_db = history_service ?
609 history_service->InMemoryDatabase() : NULL;
610 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29611 return;
612
[email protected]51124552011-07-16 01:37:10613 // Request history for both the keyword and default provider. We grab many
614 // more matches than we'll ultimately clamp to so that if there are several
615 // recent multi-word matches who scores are lowered (see
616 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
617 // matches. Note that this doesn't fix the problem entirely, but merely
618 // limits it to cases with a very large number of such multi-word matches; for
619 // now, this seems OK compared with the complexity of a real fix, which would
620 // require multiple searches and tracking of "single- vs. multi-word" in the
621 // database.
622 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47623 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
624 if (default_url) {
625 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
626 num_matches, &default_history_results_);
[email protected]257ab712009-04-14 17:16:24627 }
[email protected]85b8d6f2012-05-08 20:53:47628 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
629 if (keyword_url) {
630 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41631 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55632 }
initial.commit09911bf2008-07-26 23:55:29633}
634
[email protected]6dc950f2012-07-16 19:49:08635void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34636 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29637 StopSuggest();
[email protected]71b46152013-05-03 16:39:20638 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29639 return;
640 }
641
642 // For the minimal_changes case, if we finished the previous query and still
643 // have its results, or are allowed to keep running it, just do that, rather
644 // than starting a new query.
645 if (minimal_changes &&
[email protected]ea3b9a502011-04-04 14:19:37646 (have_suggest_results_ ||
647 (!done_ &&
648 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29649 return;
650
651 // We can't keep running any previous query, so halt it.
652 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42653
654 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20655 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29656
657 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37658 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29659 return;
660
[email protected]24dbf2302013-04-05 16:59:25661 // To avoid flooding the suggest server, don't send a query until at
662 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24663 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
664 TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
665 base::TimeTicks now(base::TimeTicks::Now());
666 if (now >= next_suggest_time) {
667 Run();
668 return;
669 }
670 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29671}
672
[email protected]83c726482008-09-10 06:36:34673bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55674 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
675 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47676 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
677 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34678 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47679 ((!default_url || default_url->suggestions_url().empty()) &&
680 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34681 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
682 return false;
683
[email protected]cac59d32010-08-09 23:23:14684 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34685 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34686
[email protected]cac59d32010-08-09 23:23:14687 // FORCED_QUERY means the user is explicitly asking us to search for this, so
688 // we assume it isn't a URL and/or there isn't private data.
689 if (input_.type() == AutocompleteInput::FORCED_QUERY)
690 return true;
[email protected]83c726482008-09-10 06:36:34691
[email protected]f608ea102013-03-18 15:08:09692 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
693 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
694 // is both a waste of time and a disclosure of potentially private, local
695 // data. Other "schemes" may actually be usernames, and we don't want to send
696 // passwords. If the scheme is OK, we still need to check other cases below.
697 // If this is QUERY, then the presence of these schemes means the user
698 // explicitly typed one, and thus this is probably a URL that's being entered
699 // and happens to currently be invalid -- in which case we again want to run
700 // our checks below. Other QUERY cases are less likely to be URLs and thus we
701 // assume we're OK.
[email protected]a2fedb1e2011-01-25 15:23:36702 if (!LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpScheme) &&
703 !LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
704 !LowerCaseEqualsASCII(input_.scheme(), chrome::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14705 return (input_.type() == AutocompleteInput::QUERY);
706
707 // Don't send URLs with usernames, queries or refs. Some of these are
708 // private, and the Suggest server is unlikely to have any useful results
709 // for any of them. Also don't send URLs with ports, as we may initially
710 // think that a username + password is a host + port (and we don't want to
711 // send usernames/passwords), and even if the port really is a port, the
712 // server is once again unlikely to have and useful results.
713 const url_parse::Parsed& parts = input_.parts();
714 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
715 parts.query.is_nonempty() || parts.ref.is_nonempty())
716 return false;
717
718 // Don't send anything for https except the hostname. Hostnames are OK
719 // because they are visible when the TCP connection is established, but the
720 // specific path may reveal private information.
[email protected]a2fedb1e2011-01-25 15:23:36721 if (LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
722 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14723 return false;
[email protected]83c726482008-09-10 06:36:34724
725 return true;
726}
727
initial.commit09911bf2008-07-26 23:55:29728void SearchProvider::StopSuggest() {
[email protected]7706a522012-08-16 17:42:25729 // Increment the appropriate field in the histogram by the number of
730 // pending requests that were invalidated.
731 for (int i = 0; i < suggest_results_pending_; i++)
732 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
[email protected]257ab712009-04-14 17:16:24733 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14734 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24735 // Stop any in-progress URL fetches.
736 keyword_fetcher_.reset();
737 default_fetcher_.reset();
[email protected]55ce8f12012-05-09 04:44:08738}
739
[email protected]71b46152013-05-03 16:39:20740void SearchProvider::ClearAllResults() {
[email protected]1e1550e2013-05-02 17:37:51741 ClearResults(&keyword_suggest_results_, &keyword_navigation_results_,
742 &keyword_verbatim_relevance_, &has_keyword_suggested_relevance_);
743 ClearResults(&default_suggest_results_, &default_navigation_results_,
744 &default_verbatim_relevance_, &has_default_suggested_relevance_);
initial.commit09911bf2008-07-26 23:55:29745 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29746}
747
[email protected]1e1550e2013-05-02 17:37:51748// static
749void SearchProvider::ClearResults(SuggestResults* suggest_results,
750 NavigationResults* navigation_results,
751 int* verbatim_relevance,
752 bool* has_suggested_relevance) {
753 suggest_results->clear();
754 navigation_results->clear();
755 *verbatim_relevance = -1;
756 *has_suggested_relevance = false;
757}
758
[email protected]71b46152013-05-03 16:39:20759void SearchProvider::RemoveAllStaleResults() {
[email protected]1e1550e2013-05-02 17:37:51760 // In theory it would be better to run an algorithm like that in
761 // RemoveStaleResults(...) below that uses all four results lists
762 // and both verbatim scores at once. However, that will be much
763 // more complicated for little obvious gain. For code simplicity
764 // and ease in reasoning about the invariants involved, this code
765 // removes stales results from the keyword provider and default
766 // provider independently.
767 RemoveStaleResults(input_.text(), GetVerbatimRelevance(),
768 &default_suggest_results_, &default_navigation_results_);
769 if (!keyword_input_.text().empty()) {
770 RemoveStaleResults(keyword_input_.text(), GetKeywordVerbatimRelevance(),
771 &keyword_suggest_results_, &keyword_navigation_results_);
772 } else {
773 // User is either in keyword mode with a blank input or out of
774 // keyword mode entirely.
775 ClearResults(
776 &keyword_suggest_results_, &keyword_navigation_results_,
777 &keyword_verbatim_relevance_, &has_keyword_suggested_relevance_);
778 }
[email protected]d1f0a7f2012-06-05 10:26:42779}
780
[email protected]42cfd01d02013-01-23 02:40:02781// static
[email protected]1e1550e2013-05-02 17:37:51782void SearchProvider::RemoveStaleResults(const string16& input,
783 int verbatim_relevance,
784 SuggestResults* suggest_results,
785 NavigationResults* navigation_results) {
786 DCHECK_GE(verbatim_relevance, 0);
787 // Keep pointers to the head of (the highest scoring elements of)
788 // |suggest_results| and |navigation_results|. Iterate down the lists
789 // removing non-inlineable results in order of decreasing relevance
790 // scores. Stop when the highest scoring element among those remaining
791 // is inlineable or the element is less than |verbatim_relevance|.
792 // This allows non-inlineable lower-scoring results to remain
793 // because (i) they are guaranteed to not be inlined and (ii)
794 // letting them remain reduces visual jank. For instance, as the
795 // user types the mis-spelled query "fpobar" (for foobar), the
796 // suggestion "foobar" will be suggested on every keystroke. If the
797 // SearchProvider always removes all non-inlineable results, the user will
798 // see visual jitter/jank as the result disappears and re-appears moments
799 // later as the suggest server returns results.
800 SuggestResults::iterator sug_it = suggest_results->begin();
801 NavigationResults::iterator nav_it = navigation_results->begin();
802 while ((sug_it != suggest_results->end()) ||
803 (nav_it != navigation_results->end())) {
804 const int sug_rel =
805 (sug_it != suggest_results->end()) ? sug_it->relevance() : -1;
806 const int nav_rel =
807 (nav_it != navigation_results->end()) ? nav_it->relevance() : -1;
808 if (std::max(sug_rel, nav_rel) < verbatim_relevance)
809 break;
810 if (sug_rel > nav_rel) {
811 // The current top result is a search suggestion.
812 if (sug_it->IsInlineable(input))
813 break;
814 sug_it = suggest_results->erase(sug_it);
815 } else if (sug_rel == nav_rel) {
816 // Have both results and they're tied.
817 const bool sug_inlineable = sug_it->IsInlineable(input);
818 const bool nav_inlineable = nav_it->IsInlineable(input);
819 if (!sug_inlineable)
820 sug_it = suggest_results->erase(sug_it);
821 if (!nav_inlineable)
822 nav_it = navigation_results->erase(nav_it);
823 if (sug_inlineable || nav_inlineable)
824 break;
825 } else {
826 // The current top result is a navigational suggestion.
827 if (nav_it->IsInlineable(input))
828 break;
829 nav_it = navigation_results->erase(nav_it);
830 }
[email protected]d1f0a7f2012-06-05 10:26:42831 }
832}
833
[email protected]bb900e02013-03-14 14:15:29834void SearchProvider::AdjustDefaultProviderSuggestion(
835 const string16& previous_input,
836 const string16& current_input) {
837 if (default_provider_suggestion_.type == INSTANT_SUGGESTION_URL) {
[email protected]bb900e02013-03-14 14:15:29838 // Description and relevance do not matter in the check for staleness.
[email protected]a1b5e862013-03-29 06:38:44839 NavigationResult result(*this,
840 GURL(default_provider_suggestion_.text),
[email protected]188b50c2013-03-28 07:19:42841 string16(),
842 false,
843 100);
[email protected]bb900e02013-03-14 14:15:29844 // If navigation suggestion is stale, clear |default_provider_suggestion_|.
[email protected]1e1550e2013-05-02 17:37:51845 if (!result.IsInlineable(current_input))
[email protected]bb900e02013-03-14 14:15:29846 default_provider_suggestion_ = InstantSuggestion();
847 } else {
848 DCHECK(default_provider_suggestion_.type == INSTANT_SUGGESTION_SEARCH);
849 // InstantSuggestion of type SEARCH contain only the suggested text, and not
850 // the full text of the query. This looks at the current and previous input
851 // to determine if the user is typing forward, and if the new input is
852 // contained in |default_provider_suggestion_|. If so, the suggestion is
853 // adjusted and can be kept. Otherwise, it is reset.
854 if (!previous_input.empty() &&
855 StartsWith(current_input, previous_input, false)) {
856 // User is typing forward; verify if new input is part of the suggestion.
857 const string16 new_text = string16(current_input, previous_input.size());
858 if (StartsWith(default_provider_suggestion_.text, new_text, false)) {
859 // New input is a prefix to the previous suggestion, adjust the
860 // suggestion to strip the prefix.
861 default_provider_suggestion_.text.erase(0, new_text.size());
862 return;
863 }
864 }
865 // If we are here, the search suggestion is stale; reset it.
866 default_provider_suggestion_ = InstantSuggestion();
867 }
868}
869
[email protected]d1f0a7f2012-06-05 10:26:42870void SearchProvider::ApplyCalculatedRelevance() {
[email protected]188b50c2013-03-28 07:19:42871 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_);
872 ApplyCalculatedSuggestRelevance(&default_suggest_results_);
873 ApplyCalculatedNavigationRelevance(&keyword_navigation_results_);
874 ApplyCalculatedNavigationRelevance(&default_navigation_results_);
[email protected]dab8d52d2013-03-05 07:35:28875 has_default_suggested_relevance_ = false;
876 has_keyword_suggested_relevance_ = false;
877 default_verbatim_relevance_ = -1;
878 keyword_verbatim_relevance_ = -1;
[email protected]d1f0a7f2012-06-05 10:26:42879}
880
[email protected]188b50c2013-03-28 07:19:42881void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42882 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42883 SuggestResult& result = (*list)[i];
884 result.set_relevance(
885 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
886 (list->size() - i - 1));
[email protected]d1f0a7f2012-06-05 10:26:42887 }
888}
889
[email protected]188b50c2013-03-28 07:19:42890void SearchProvider::ApplyCalculatedNavigationRelevance(
891 NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42892 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42893 NavigationResult& result = (*list)[i];
894 result.set_relevance(
895 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
896 (list->size() - i - 1));
[email protected]d1f0a7f2012-06-05 10:26:42897 }
898}
899
[email protected]15fb2aa2012-05-22 22:52:59900net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12901 int id,
[email protected]9ff91722012-09-07 05:29:12902 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41903 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12904 if (!template_url || template_url->suggestions_url().empty())
905 return NULL;
906
907 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41908 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
909 search_term_args.cursor_position = input.cursor_position();
[email protected]9ff91722012-09-07 05:29:12910 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:16911 search_term_args));
[email protected]9ff91722012-09-07 05:29:12912 if (!suggest_url.is_valid())
913 return NULL;
914
915 suggest_results_pending_++;
916 LogOmniboxSuggestRequest(REQUEST_SENT);
917
918 net::URLFetcher* fetcher =
919 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12920 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34921 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30922 // Add Chrome experiment state to the request headers.
923 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:09924 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30925 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
926 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24927 fetcher->Start();
928 return fetcher;
929}
930
[email protected]d7ad4772012-06-01 03:12:54931bool SearchProvider::ParseSuggestResults(Value* root_val, bool is_keyword) {
932 // TODO(pkasting): Fix |have_suggest_results_|; see http://crbug.com/130631
933 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29934
[email protected]d7ad4772012-06-01 03:12:54935 string16 query;
936 ListValue* root_list = NULL;
937 ListValue* results = NULL;
[email protected]14710852013-02-05 23:45:41938 const string16& input_text =
939 is_keyword ? keyword_input_.text() : input_.text();
[email protected]d7ad4772012-06-01 03:12:54940 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
941 (query != input_text) || !root_list->GetList(1, &results))
initial.commit09911bf2008-07-26 23:55:29942 return false;
943
[email protected]55ce8f12012-05-09 04:44:08944 // 3rd element: Description list.
[email protected]d7ad4772012-06-01 03:12:54945 ListValue* descriptions = NULL;
946 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:29947
[email protected]55ce8f12012-05-09 04:44:08948 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:29949
[email protected]d1f0a7f2012-06-05 10:26:42950 // Reset suggested relevance information from the default provider.
[email protected]dab8d52d2013-03-05 07:35:28951 bool* has_suggested_relevance = is_keyword ?
952 &has_keyword_suggested_relevance_ : &has_default_suggested_relevance_;
953 *has_suggested_relevance = false;
954 int* verbatim_relevance = is_keyword ?
955 &keyword_verbatim_relevance_ : &default_verbatim_relevance_;
956 *verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42957
[email protected]55ce8f12012-05-09 04:44:08958 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]d7ad4772012-06-01 03:12:54959 ListValue* types = NULL;
[email protected]d1f0a7f2012-06-05 10:26:42960 ListValue* relevances = NULL;
961 DictionaryValue* extras = NULL;
962 if (root_list->GetDictionary(4, &extras)) {
963 extras->GetList("google:suggesttype", &types);
964
965 // Only accept relevance suggestions if Instant is disabled.
[email protected]165fe422013-03-27 06:34:03966 if (!chrome::IsInstantEnabled(profile_)) {
[email protected]d1f0a7f2012-06-05 10:26:42967 // Discard this list if its size does not match that of the suggestions.
968 if (extras->GetList("google:suggestrelevance", &relevances) &&
969 relevances->GetSize() != results->GetSize())
970 relevances = NULL;
[email protected]dab8d52d2013-03-05 07:35:28971 extras->GetInteger("google:verbatimrelevance", verbatim_relevance);
[email protected]d1f0a7f2012-06-05 10:26:42972 }
[email protected]618d6e62012-12-16 05:55:57973
974 // Check if the active suggest field trial (if any) has triggered either
975 // for the default provider or keyword provider.
976 bool triggered = false;
977 extras->GetBoolean("google:fieldtrialtriggered", &triggered);
978 field_trial_triggered_ |= triggered;
979 field_trial_triggered_in_session_ |= triggered;
initial.commit09911bf2008-07-26 23:55:29980 }
981
[email protected]d7ad4772012-06-01 03:12:54982 SuggestResults* suggest_results =
983 is_keyword ? &keyword_suggest_results_ : &default_suggest_results_;
984 NavigationResults* navigation_results =
985 is_keyword ? &keyword_navigation_results_ : &default_navigation_results_;
initial.commit09911bf2008-07-26 23:55:29986
[email protected]d1f0a7f2012-06-05 10:26:42987 // Clear the previous results now that new results are available.
988 suggest_results->clear();
989 navigation_results->clear();
990
991 string16 result, title;
992 std::string type;
993 int relevance = -1;
[email protected]d7ad4772012-06-01 03:12:54994 for (size_t index = 0; results->GetString(index, &result); ++index) {
[email protected]8e81f5092010-09-29 23:19:40995 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:08996 // they make no sense at all and can cause problems in our code.
[email protected]d7ad4772012-06-01 03:12:54997 if (result.empty())
[email protected]8e81f5092010-09-29 23:19:40998 continue;
999
[email protected]d1f0a7f2012-06-05 10:26:421000 // Apply valid suggested relevance scores; discard invalid lists.
1001 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
1002 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:541003 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:421004 // Do not blindly trust the URL coming from the server to be valid.
1005 GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(result), std::string()));
1006 if (url.is_valid()) {
1007 if (descriptions != NULL)
1008 descriptions->GetString(index, &title);
[email protected]188b50c2013-03-28 07:19:421009 navigation_results->push_back(NavigationResult(
[email protected]a1b5e862013-03-29 06:38:441010 *this, url, title, is_keyword, relevance));
initial.commit09911bf2008-07-26 23:55:291011 }
1012 } else {
[email protected]d1f0a7f2012-06-05 10:26:421013 // TODO(kochi): Improve calculator result presentation.
[email protected]188b50c2013-03-28 07:19:421014 suggest_results->push_back(SuggestResult(result, is_keyword, relevance));
initial.commit09911bf2008-07-26 23:55:291015 }
1016 }
1017
[email protected]d1f0a7f2012-06-05 10:26:421018 // Apply calculated relevance scores if a valid list was not provided.
1019 if (relevances == NULL) {
[email protected]188b50c2013-03-28 07:19:421020 ApplyCalculatedSuggestRelevance(suggest_results);
1021 ApplyCalculatedNavigationRelevance(navigation_results);
[email protected]dab8d52d2013-03-05 07:35:281022 } else {
1023 *has_suggested_relevance = true;
[email protected]d1f0a7f2012-06-05 10:26:421024 }
[email protected]9dfb4d362013-04-05 02:15:121025 // Keep the result lists sorted.
1026 const CompareScoredResults comparator = CompareScoredResults();
1027 std::stable_sort(suggest_results->begin(), suggest_results->end(),
1028 comparator);
1029 std::stable_sort(navigation_results->begin(), navigation_results->end(),
1030 comparator);
[email protected]d7ad4772012-06-01 03:12:541031 have_suggest_results_ = true;
[email protected]d1f0a7f2012-06-05 10:26:421032 return true;
initial.commit09911bf2008-07-26 23:55:291033}
1034
[email protected]344946a12012-12-20 12:03:421035void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:291036 // Convert all the results to matches and add them to a map, so we can keep
1037 // the most relevant match for each result.
1038 MatchMap map;
[email protected]257ab712009-04-14 17:16:241039 const Time no_time;
1040 int did_not_accept_keyword_suggestion = keyword_suggest_results_.empty() ?
initial.commit09911bf2008-07-26 23:55:291041 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
1042 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:291043
[email protected]382a0642012-06-06 06:13:521044 int verbatim_relevance = GetVerbatimRelevance();
[email protected]257ab712009-04-14 17:16:241045 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
[email protected]55ce8f12012-05-09 04:44:081046 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
1047 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:421048 if (verbatim_relevance > 0) {
1049 AddMatchToMap(input_.text(), input_.text(), verbatim_relevance,
1050 AutocompleteMatch::SEARCH_WHAT_YOU_TYPED,
1051 did_not_accept_default_suggestion, false, &map);
1052 }
[email protected]5423e562013-02-07 03:58:451053 if (!keyword_input_.text().empty()) {
1054 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1055 // We only create the verbatim search query match for a keyword
1056 // if it's not an extension keyword. Extension keywords are handled
1057 // in KeywordProvider::Start(). (Extensions are complicated...)
1058 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
1059 // to the keyword verbatim search query. Do not create other matches
1060 // of type SEARCH_OTHER_ENGINE.
1061 if (keyword_url && !keyword_url->IsExtensionKeyword()) {
[email protected]dab8d52d2013-03-05 07:35:281062 const int keyword_verbatim_relevance = GetKeywordVerbatimRelevance();
1063 if (keyword_verbatim_relevance > 0) {
1064 AddMatchToMap(keyword_input_.text(), keyword_input_.text(),
1065 keyword_verbatim_relevance,
1066 AutocompleteMatch::SEARCH_OTHER_ENGINE,
1067 did_not_accept_keyword_suggestion, true, &map);
1068 }
[email protected]5423e562013-02-07 03:58:451069 }
1070 }
1071 const size_t verbatim_matches_size = map.size();
[email protected]93b73832012-10-18 20:18:381072 if (!default_provider_suggestion_.text.empty() &&
[email protected]2ac15ba2013-01-14 22:38:591073 default_provider_suggestion_.type == INSTANT_SUGGESTION_SEARCH &&
1074 !input_.prevent_inline_autocomplete())
[email protected]93b73832012-10-18 20:18:381075 AddMatchToMap(input_.text() + default_provider_suggestion_.text,
[email protected]55ce8f12012-05-09 04:44:081076 input_.text(), verbatim_relevance + 1,
[email protected]85b8d6f2012-05-08 20:53:471077 AutocompleteMatch::SEARCH_SUGGEST,
[email protected]55ce8f12012-05-09 04:44:081078 did_not_accept_default_suggestion, false, &map);
initial.commit09911bf2008-07-26 23:55:291079
[email protected]257ab712009-04-14 17:16:241080 AddHistoryResultsToMap(keyword_history_results_, true,
1081 did_not_accept_keyword_suggestion, &map);
1082 AddHistoryResultsToMap(default_history_results_, false,
1083 did_not_accept_default_suggestion, &map);
1084
[email protected]188b50c2013-03-28 07:19:421085 AddSuggestResultsToMap(keyword_suggest_results_, &map);
1086 AddSuggestResultsToMap(default_suggest_results_, &map);
initial.commit09911bf2008-07-26 23:55:291087
1088 // Now add the most relevant matches from the map to |matches_|.
1089 matches_.clear();
1090 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
1091 matches_.push_back(i->second);
1092
[email protected]93b73832012-10-18 20:18:381093 if (!default_provider_suggestion_.text.empty() &&
[email protected]2ac15ba2013-01-14 22:38:591094 default_provider_suggestion_.type == INSTANT_SUGGESTION_URL &&
[email protected]90fe2bb2013-01-15 03:42:131095 !input_.prevent_inline_autocomplete()) {
1096 // See comment in FinalizeInstantQuery() for why we don't use
1097 // |verbatim_relevance| here.
[email protected]93b73832012-10-18 20:18:381098 matches_.push_back(NavigationToMatch(
[email protected]a1b5e862013-03-29 06:38:441099 NavigationResult(*this,
1100 GURL(UTF16ToUTF8(default_provider_suggestion_.text)),
[email protected]93b73832012-10-18 20:18:381101 string16(),
[email protected]188b50c2013-03-28 07:19:421102 false,
1103 kNonURLVerbatimRelevance + 1)));
[email protected]90fe2bb2013-01-15 03:42:131104 }
[email protected]257ab712009-04-14 17:16:241105 AddNavigationResultsToMatches(keyword_navigation_results_, true);
1106 AddNavigationResultsToMatches(default_navigation_results_, false);
initial.commit09911bf2008-07-26 23:55:291107
[email protected]5423e562013-02-07 03:58:451108 // Allow additional match(es) for verbatim results if present.
1109 const size_t max_total_matches = kMaxMatches + verbatim_matches_size;
initial.commit09911bf2008-07-26 23:55:291110 std::partial_sort(matches_.begin(),
1111 matches_.begin() + std::min(max_total_matches, matches_.size()),
1112 matches_.end(), &AutocompleteMatch::MoreRelevant);
[email protected]3723e6e2012-06-11 21:06:561113
initial.commit09911bf2008-07-26 23:55:291114 if (matches_.size() > max_total_matches)
[email protected]344946a12012-12-20 12:03:421115 matches_.resize(max_total_matches);
1116}
1117
[email protected]9dfb4d362013-04-05 02:15:121118bool SearchProvider::IsTopMatchNavigationInKeywordMode() const {
1119 return (!providers_.keyword_provider().empty() &&
1120 (matches_.front().type == AutocompleteMatch::NAVSUGGEST));
1121}
1122
[email protected]344946a12012-12-20 12:03:421123bool SearchProvider::IsTopMatchScoreTooLow() const {
[email protected]dab8d52d2013-03-05 07:35:281124 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
1125 // rather than CalculateRelevanceForVerbatim() because the latter returns
1126 // a very low score (250) if keyword mode is active. This is because
1127 // when keyword mode is active the user probably wants the keyword matches,
1128 // not matches from the default provider. Hence, we use the version of
1129 // the function that ignores whether keyword mode is active. This allows
1130 // SearchProvider to maintain its contract with the AutocompleteController
1131 // that it will always provide an inlineable match with a reasonable
1132 // score.
1133 return matches_.front().relevance <
1134 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
[email protected]344946a12012-12-20 12:03:421135}
1136
1137bool SearchProvider::IsTopMatchHighRankSearchForURL() const {
1138 return input_.type() == AutocompleteInput::URL &&
1139 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
1140 (matches_.front().type == AutocompleteMatch::SEARCH_SUGGEST ||
[email protected]5423e562013-02-07 03:58:451141 matches_.front().type == AutocompleteMatch::SEARCH_WHAT_YOU_TYPED ||
1142 matches_.front().type == AutocompleteMatch::SEARCH_OTHER_ENGINE);
[email protected]344946a12012-12-20 12:03:421143}
1144
1145bool SearchProvider::IsTopMatchNotInlinable() const {
[email protected]5423e562013-02-07 03:58:451146 // Note: this test assumes the SEARCH_OTHER_ENGINE match corresponds to
1147 // the verbatim search query on the keyword engine. SearchProvider should
1148 // not create any other match of type SEARCH_OTHER_ENGINE.
[email protected]344946a12012-12-20 12:03:421149 return matches_.front().type != AutocompleteMatch::SEARCH_WHAT_YOU_TYPED &&
1150 matches_.front().type != AutocompleteMatch::URL_WHAT_YOU_TYPED &&
[email protected]5423e562013-02-07 03:58:451151 matches_.front().type != AutocompleteMatch::SEARCH_OTHER_ENGINE &&
[email protected]344946a12012-12-20 12:03:421152 matches_.front().inline_autocomplete_offset == string16::npos &&
1153 matches_.front().fill_into_edit != input_.text();
1154}
1155
1156void SearchProvider::UpdateMatches() {
1157 ConvertResultsToAutocompleteMatches();
initial.commit09911bf2008-07-26 23:55:291158
[email protected]382a0642012-06-06 06:13:521159 // Check constraints that may be violated by suggested relevances.
[email protected]344946a12012-12-20 12:03:421160 if (!matches_.empty() &&
[email protected]dab8d52d2013-03-05 07:35:281161 (has_default_suggested_relevance_ || default_verbatim_relevance_ >= 0 ||
1162 has_keyword_suggested_relevance_ || keyword_verbatim_relevance_ >= 0)) {
[email protected]9dfb4d362013-04-05 02:15:121163 // These blocks attempt to repair undesirable behavior by suggested
[email protected]344946a12012-12-20 12:03:421164 // relevances with minimal impact, preserving other suggested relevances.
[email protected]9dfb4d362013-04-05 02:15:121165 if (IsTopMatchNavigationInKeywordMode()) {
1166 // Correct the suggested relevance scores if the top match is a
1167 // navigation in keyword mode, since inlining a navigation match
1168 // would break the user out of keyword mode. By the way, if the top
1169 // match is a non-keyword match (query or navsuggestion) in keyword
1170 // mode, the user would also break out of keyword mode. However,
1171 // that situation is impossible given the current scoring paradigm
1172 // and the fact that only one search engine (Google) provides suggested
1173 // relevance scores at this time.
1174 DemoteKeywordNavigationMatchesPastTopQuery();
1175 ConvertResultsToAutocompleteMatches();
1176 DCHECK(!IsTopMatchNavigationInKeywordMode());
1177 }
[email protected]344946a12012-12-20 12:03:421178 if (IsTopMatchScoreTooLow()) {
[email protected]1beee342012-06-19 22:22:281179 // Disregard the suggested verbatim relevance if the top score is below
1180 // the usual verbatim value. For example, a BarProvider may rely on
1181 // SearchProvider's verbatim or inlineable matches for input "foo" to
1182 // always outrank its own lowly-ranked non-inlineable "bar" match.
[email protected]dab8d52d2013-03-05 07:35:281183 default_verbatim_relevance_ = -1;
1184 keyword_verbatim_relevance_ = -1;
[email protected]344946a12012-12-20 12:03:421185 ConvertResultsToAutocompleteMatches();
[email protected]e6acd002012-06-16 22:27:471186 }
[email protected]344946a12012-12-20 12:03:421187 if (IsTopMatchHighRankSearchForURL()) {
[email protected]e6acd002012-06-16 22:27:471188 // Disregard the suggested search and verbatim relevances if the input
1189 // type is URL and the top match is a highly-ranked search suggestion.
1190 // For example, prevent a search for "foo.com" from outranking another
1191 // provider's navigation for "foo.com" or "foo.com/url_from_history".
[email protected]188b50c2013-03-28 07:19:421192 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_);
1193 ApplyCalculatedSuggestRelevance(&default_suggest_results_);
[email protected]dab8d52d2013-03-05 07:35:281194 default_verbatim_relevance_ = -1;
1195 keyword_verbatim_relevance_ = -1;
[email protected]344946a12012-12-20 12:03:421196 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521197 }
[email protected]344946a12012-12-20 12:03:421198 if (IsTopMatchNotInlinable()) {
[email protected]5423e562013-02-07 03:58:451199 // Disregard suggested relevances if the top match is not a verbatim
1200 // match, inlinable, or URL_WHAT_YOU_TYPED (which may be top match
1201 // regardless of inlining). For example, input "foo" should not
1202 // invoke a search for "bar", which would happen if the "bar" search
1203 // match outranked all other matches.
[email protected]344946a12012-12-20 12:03:421204 ApplyCalculatedRelevance();
1205 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521206 }
[email protected]9dfb4d362013-04-05 02:15:121207 DCHECK(!IsTopMatchNavigationInKeywordMode());
[email protected]344946a12012-12-20 12:03:421208 DCHECK(!IsTopMatchScoreTooLow());
1209 DCHECK(!IsTopMatchHighRankSearchForURL());
1210 DCHECK(!IsTopMatchNotInlinable());
[email protected]d1f0a7f2012-06-05 10:26:421211 }
1212
[email protected]cc63dea2008-08-21 20:56:311213 UpdateStarredStateOfMatches();
[email protected]4ab4c7c2010-11-24 04:49:341214 UpdateDone();
[email protected]257ab712009-04-14 17:16:241215}
1216
1217void SearchProvider::AddNavigationResultsToMatches(
1218 const NavigationResults& navigation_results,
1219 bool is_keyword) {
[email protected]c112f0fe72013-01-18 20:30:091220 if (navigation_results.empty())
1221 return;
1222
[email protected]dab8d52d2013-03-05 07:35:281223 if (is_keyword ?
1224 has_keyword_suggested_relevance_ : has_default_suggested_relevance_) {
[email protected]c112f0fe72013-01-18 20:30:091225 for (NavigationResults::const_iterator it = navigation_results.begin();
1226 it != navigation_results.end(); ++it)
[email protected]188b50c2013-03-28 07:19:421227 matches_.push_back(NavigationToMatch(*it));
[email protected]c112f0fe72013-01-18 20:30:091228 } else {
[email protected]9dfb4d362013-04-05 02:15:121229 // Pick the highest-scoring element only in absence of the
1230 // suggested relevance scores. (The results are already sorted.)
[email protected]6c535842012-05-15 05:20:551231 // TODO(kochi|msw): Add more navigational results if they get more
1232 // meaningful relevance values; see http://b/1170574.
[email protected]9dfb4d362013-04-05 02:15:121233 matches_.push_back(NavigationToMatch(navigation_results.front()));
[email protected]257ab712009-04-14 17:16:241234 }
1235}
1236
1237void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
1238 bool is_keyword,
1239 int did_not_accept_suggestion,
1240 MatchMap* map) {
[email protected]51124552011-07-16 01:37:101241 if (results.empty())
1242 return;
1243
[email protected]d7ad4772012-06-01 03:12:541244 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1245 (input_.type() == AutocompleteInput::URL);
[email protected]14710852013-02-05 23:45:411246 const string16& input_text =
1247 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:101248 bool input_multiple_words = HasMultipleWords(input_text);
1249
[email protected]55ce8f12012-05-09 04:44:081250 SuggestResults scored_results;
1251 if (!prevent_inline_autocomplete && input_multiple_words) {
1252 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1253 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:101254 // autocompleting a multi-word, multi-visit query, and the current input is
1255 // still a prefix of it, then changing the autocompletion suddenly feels
1256 // wrong. To detect this case, first score as if only one word has been
1257 // typed, then check for a best result that is an autocompleted, multi-word
1258 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:081259 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1260 false, input_text, is_keyword);
[email protected]9dfb4d362013-04-05 02:15:121261 if ((scored_results.front().relevance() <
[email protected]55ce8f12012-05-09 04:44:081262 AutocompleteResult::kLowestDefaultScore) ||
[email protected]9dfb4d362013-04-05 02:15:121263 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:081264 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:101265 }
[email protected]55ce8f12012-05-09 04:44:081266 if (scored_results.empty())
1267 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1268 input_multiple_words, input_text,
1269 is_keyword);
1270 for (SuggestResults::const_iterator i(scored_results.begin());
1271 i != scored_results.end(); ++i) {
1272 AddMatchToMap(i->suggestion(), input_text, i->relevance(),
[email protected]51124552011-07-16 01:37:101273 AutocompleteMatch::SEARCH_HISTORY, did_not_accept_suggestion,
[email protected]55ce8f12012-05-09 04:44:081274 is_keyword, map);
[email protected]51124552011-07-16 01:37:101275 }
1276}
1277
[email protected]55ce8f12012-05-09 04:44:081278SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:101279 const HistoryResults& results,
1280 bool base_prevent_inline_autocomplete,
1281 bool input_multiple_words,
1282 const string16& input_text,
1283 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:481284 AutocompleteClassifier* classifier =
1285 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:081286 SuggestResults scored_results;
[email protected]257ab712009-04-14 17:16:241287 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1288 ++i) {
[email protected]51124552011-07-16 01:37:101289 // Don't autocomplete multi-word queries that have only been seen once
1290 // unless the user has typed more than one word.
1291 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1292 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
1293
[email protected]ea3b9a502011-04-04 14:19:371294 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:101295 // when typed. For example, if the user searched for "google.com" and types
1296 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1297 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:481298 // NOTE: We don't check this in the following cases:
1299 // * When inline autocomplete is disabled, we won't be inline
1300 // autocompleting this term, so we don't need to worry about confusion as
1301 // much. This also prevents calling Classify() again from inside the
1302 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:101303 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:481304 // * When the user has typed the whole term, the "what you typed" history
1305 // match will outrank us for URL-like inputs anyway, so we need not do
1306 // anything special.
[email protected]51124552011-07-16 01:37:101307 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:371308 AutocompleteMatch match;
[email protected]f608ea102013-03-18 15:08:091309 classifier->Classify(i->term, false, false, &match, NULL);
[email protected]2905f742011-10-13 03:51:581310 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:461311 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:371312 }
[email protected]51124552011-07-16 01:37:101313
1314 int relevance = CalculateRelevanceForHistory(i->time, is_keyword,
1315 prevent_inline_autocomplete);
[email protected]188b50c2013-03-28 07:19:421316 scored_results.push_back(SuggestResult(i->term, is_keyword, relevance));
[email protected]257ab712009-04-14 17:16:241317 }
[email protected]51124552011-07-16 01:37:101318
1319 // History returns results sorted for us. However, we may have docked some
1320 // results' scores, so things are no longer in order. Do a stable sort to get
1321 // things back in order without otherwise disturbing results with equal
1322 // scores, then force the scores to be unique, so that the order in which
1323 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081324 std::stable_sort(scored_results.begin(), scored_results.end(),
1325 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101326 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081327 for (SuggestResults::iterator i(scored_results.begin());
1328 i != scored_results.end(); ++i) {
1329 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1330 i->set_relevance(last_relevance - 1);
1331 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101332 }
1333
[email protected]55ce8f12012-05-09 04:44:081334 return scored_results;
[email protected]257ab712009-04-14 17:16:241335}
1336
[email protected]55ce8f12012-05-09 04:44:081337void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
[email protected]55ce8f12012-05-09 04:44:081338 MatchMap* map) {
[email protected]55ce8f12012-05-09 04:44:081339 for (size_t i = 0; i < results.size(); ++i) {
[email protected]188b50c2013-03-28 07:19:421340 const bool is_keyword = results[i].from_keyword_provider();
1341 const string16& input = is_keyword ? keyword_input_.text() : input_.text();
1342 AddMatchToMap(results[i].suggestion(), input, results[i].relevance(),
[email protected]55ce8f12012-05-09 04:44:081343 AutocompleteMatch::SEARCH_SUGGEST, i, is_keyword, map);
[email protected]257ab712009-04-14 17:16:241344 }
initial.commit09911bf2008-07-26 23:55:291345}
1346
[email protected]382a0642012-06-06 06:13:521347int SearchProvider::GetVerbatimRelevance() const {
[email protected]dc6943b2012-06-19 06:39:561348 // Use the suggested verbatim relevance score if it is non-negative (valid),
1349 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281350 // and if it won't suppress verbatim, leaving no default provider matches.
1351 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561352 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281353 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561354 // Check for results on each verbatim calculation, as results from older
1355 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]dab8d52d2013-03-05 07:35:281356 if (default_verbatim_relevance_ >= 0 &&
1357 !input_.prevent_inline_autocomplete() &&
1358 (default_verbatim_relevance_ > 0 ||
[email protected]1beee342012-06-19 22:22:281359 !default_suggest_results_.empty() ||
[email protected]dc6943b2012-06-19 06:39:561360 !default_navigation_results_.empty())) {
[email protected]dab8d52d2013-03-05 07:35:281361 return default_verbatim_relevance_;
[email protected]dc6943b2012-06-19 06:39:561362 }
[email protected]382a0642012-06-06 06:13:521363 return CalculateRelevanceForVerbatim();
1364}
[email protected]d1f0a7f2012-06-05 10:26:421365
[email protected]382a0642012-06-06 06:13:521366int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471367 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361368 return 250;
[email protected]dab8d52d2013-03-05 07:35:281369 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1370}
[email protected]52d08b12009-10-19 18:42:361371
[email protected]dab8d52d2013-03-05 07:35:281372int SearchProvider::
1373 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291374 switch (input_.type()) {
1375 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361376 case AutocompleteInput::QUERY:
1377 case AutocompleteInput::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131378 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291379
initial.commit09911bf2008-07-26 23:55:291380 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361381 return 850;
initial.commit09911bf2008-07-26 23:55:291382
1383 default:
1384 NOTREACHED();
1385 return 0;
1386 }
1387}
1388
[email protected]dab8d52d2013-03-05 07:35:281389int SearchProvider::GetKeywordVerbatimRelevance() const {
1390 // Use the suggested verbatim relevance score if it is non-negative (valid),
1391 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1392 // and if it won't suppress verbatim, leaving no keyword provider matches.
1393 // Otherwise, if the keyword provider returned no matches and was still able
1394 // to suppress verbatim, the user would have no search/nav matches and may be
1395 // left unable to search using their keyword provider from the omnibox.
1396 // Check for results on each verbatim calculation, as results from older
1397 // queries (on previous input) may be trimmed for failing to inline new input.
1398 if (keyword_verbatim_relevance_ >= 0 &&
1399 !input_.prevent_inline_autocomplete() &&
1400 (keyword_verbatim_relevance_ > 0 ||
1401 !keyword_suggest_results_.empty() ||
1402 !keyword_navigation_results_.empty())) {
1403 return keyword_verbatim_relevance_;
1404 }
1405 return CalculateRelevanceForKeywordVerbatim(
1406 keyword_input_.type(), keyword_input_.prefer_keyword());
1407}
1408
[email protected]5423e562013-02-07 03:58:451409// static
1410int SearchProvider::CalculateRelevanceForKeywordVerbatim(
1411 AutocompleteInput::Type type,
1412 bool prefer_keyword) {
1413 // This function is responsible for scoring verbatim query matches
1414 // for non-extension keywords. KeywordProvider::CalculateRelevance()
1415 // scores verbatim query matches for extension keywords, as well as
1416 // for keyword matches (i.e., suggestions of a keyword itself, not a
1417 // suggestion of a query on a keyword search engine). These two
1418 // functions are currently in sync, but there's no reason we
1419 // couldn't decide in the future to score verbatim matches
1420 // differently for extension and non-extension keywords. If you
1421 // make such a change, however, you should update this comment to
1422 // describe it, so it's clear why the functions diverge.
1423 if (prefer_keyword)
1424 return 1500;
1425 return (type == AutocompleteInput::QUERY) ? 1450 : 1100;
1426}
1427
[email protected]51124552011-07-16 01:37:101428int SearchProvider::CalculateRelevanceForHistory(
1429 const Time& time,
1430 bool is_keyword,
1431 bool prevent_inline_autocomplete) const {
[email protected]aa613d62010-11-09 20:40:181432 // The relevance of past searches falls off over time. There are two distinct
1433 // equations used. If the first equation is used (searches to the primary
[email protected]51124552011-07-16 01:37:101434 // provider that we want to inline autocomplete), the score starts at 1399 and
1435 // falls to 1300. If the second equation is used the relevance of a search 15
1436 // minutes ago is discounted 50 points, while the relevance of a search two
1437 // weeks ago is discounted 450 points.
[email protected]aa613d62010-11-09 20:40:181438 double elapsed_time = std::max((Time::Now() - time).InSecondsF(), 0.);
[email protected]188b50c2013-03-28 07:19:421439 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]51124552011-07-16 01:37:101440 if (is_primary_provider && !prevent_inline_autocomplete) {
[email protected]aa613d62010-11-09 20:40:181441 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101442 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181443 if (elapsed_time < autocomplete_time) {
[email protected]e17511f2011-07-13 14:09:181444 return (is_keyword ? 1599 : 1399) - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181445 std::pow(elapsed_time / autocomplete_time, 2.5));
1446 }
1447 elapsed_time -= autocomplete_time;
1448 }
1449
[email protected]c3a4bd992010-08-18 20:25:011450 const int score_discount =
1451 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291452
[email protected]6c85aa02009-02-27 12:08:091453 // Don't let scores go below 0. Negative relevance scores are meaningful in
1454 // a different way.
initial.commit09911bf2008-07-26 23:55:291455 int base_score;
[email protected]51124552011-07-16 01:37:101456 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361457 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101458 else
1459 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291460 return std::max(0, base_score - score_discount);
1461}
1462
[email protected]a2fedb1e2011-01-25 15:23:361463void SearchProvider::AddMatchToMap(const string16& query_string,
1464 const string16& input_text,
initial.commit09911bf2008-07-26 23:55:291465 int relevance,
[email protected]4c1fb7ec2008-11-13 00:19:001466 AutocompleteMatch::Type type,
initial.commit09911bf2008-07-26 23:55:291467 int accepted_suggestion,
[email protected]257ab712009-04-14 17:16:241468 bool is_keyword,
initial.commit09911bf2008-07-26 23:55:291469 MatchMap* map) {
[email protected]4eeb54f92013-04-27 04:01:201470 // With Instant Extended, we never want to inline autocomplete search queries
1471 // -- they should always use grey text if they are to autocomplete at all. So
1472 // we clamp non-verbatim results to just below the verbatim score to ensure
1473 // that none of them are inline autocompleted.
1474 if ((type != AutocompleteMatch::SEARCH_WHAT_YOU_TYPED) &&
1475 chrome::IsInstantExtendedAPIEnabled()) {
1476 relevance = std::min(kNonURLVerbatimRelevance - 1, relevance);
1477 }
[email protected]cb86ee6f2013-04-28 16:58:151478
1479 const string16& keyword = is_keyword ?
[email protected]3954c3a2012-04-10 20:17:551480 providers_.keyword_provider() : providers_.default_provider();
[email protected]cb86ee6f2013-04-28 16:58:151481 AutocompleteMatch match = CreateSearchSuggestion(profile_, this, input_,
1482 query_string, input_text, relevance, type, accepted_suggestion,
1483 is_keyword, keyword);
1484 if (!match.destination_url.is_valid())
[email protected]85b8d6f2012-05-08 20:53:471485 return;
1486
initial.commit09911bf2008-07-26 23:55:291487 // Try to add |match| to |map|. If a match for |query_string| is already in
1488 // |map|, replace it if |match| is more relevant.
1489 // NOTE: Keep this ToLower() call in sync with url_database.cc.
1490 const std::pair<MatchMap::iterator, bool> i = map->insert(
[email protected]a2fedb1e2011-01-25 15:23:361491 std::pair<string16, AutocompleteMatch>(
[email protected]503d03872011-05-06 08:36:261492 base::i18n::ToLower(query_string), match));
initial.commit09911bf2008-07-26 23:55:291493 // NOTE: We purposefully do a direct relevance comparison here instead of
1494 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items added
1495 // first" rather than "items alphabetically first" when the scores are equal.
1496 // The only case this matters is when a user has results with the same score
1497 // that differ only by capitalization; because the history system returns
1498 // results sorted by recency, this means we'll pick the most recent such
1499 // result even if the precision of our relevance score is too low to
1500 // distinguish the two.
1501 if (!i.second && (match.relevance > i.first->second.relevance))
1502 i.first->second = match;
1503}
1504
1505AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421506 const NavigationResult& navigation) {
1507 const string16& input = navigation.from_keyword_provider() ?
1508 keyword_input_.text() : input_.text();
[email protected]55ce8f12012-05-09 04:44:081509 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]4c1fb7ec2008-11-13 00:19:001510 AutocompleteMatch::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081511 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551512
1513 // First look for the user's input inside the fill_into_edit as it would be
1514 // without trimming the scheme, so we can find matches at the beginning of the
1515 // scheme.
[email protected]a1b5e862013-03-29 06:38:441516 const string16& untrimmed_fill_into_edit = navigation.formatted_url();
[email protected]371dab12012-06-01 03:23:551517 const URLPrefix* prefix =
1518 URLPrefix::BestURLPrefix(untrimmed_fill_into_edit, input);
1519 size_t match_start = (prefix == NULL) ?
1520 untrimmed_fill_into_edit.find(input) : prefix->prefix.length();
1521 size_t inline_autocomplete_offset = (prefix == NULL) ?
1522 string16::npos : (match_start + input.length());
1523 bool trim_http = !HasHTTPScheme(input) && (!prefix || (match_start != 0));
1524
1525 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1526 // Otherwise, user edits to a suggestion would show non-Search results.
1527 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
1528 match.fill_into_edit = ASCIIToUTF16("?");
1529 if (inline_autocomplete_offset != string16::npos)
1530 ++inline_autocomplete_offset;
1531 }
1532
1533 const std::string languages(
1534 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1535 const net::FormatUrlTypes format_types =
1536 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1537 match.fill_into_edit +=
1538 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1539 net::FormatUrl(navigation.url(), languages, format_types,
1540 net::UnescapeRule::SPACES, NULL, NULL,
1541 &inline_autocomplete_offset));
1542 if (!input_.prevent_inline_autocomplete())
1543 match.inline_autocomplete_offset = inline_autocomplete_offset;
1544 DCHECK((match.inline_autocomplete_offset == string16::npos) ||
1545 (match.inline_autocomplete_offset <= match.fill_into_edit.length()));
1546
1547 match.contents = net::FormatUrl(navigation.url(), languages,
1548 format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1549 // If the first match in the untrimmed string was inside a scheme that we
1550 // trimmed, look for a subsequent match.
1551 if (match_start == string16::npos)
1552 match_start = match.contents.find(input);
1553 // Safe if |match_start| is npos; also safe if the input is longer than the
1554 // remaining contents after |match_start|.
1555 AutocompleteMatch::ClassifyLocationInString(match_start, input.length(),
1556 match.contents.length(), ACMatchClassification::URL,
1557 &match.contents_class);
initial.commit09911bf2008-07-26 23:55:291558
[email protected]55ce8f12012-05-09 04:44:081559 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551560 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1561 ACMatchClassification::NONE, &match.description_class);
initial.commit09911bf2008-07-26 23:55:291562 return match;
1563}
[email protected]4ab4c7c2010-11-24 04:49:341564
[email protected]9dfb4d362013-04-05 02:15:121565void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
[email protected]d519d392013-03-27 09:24:461566 // First, determine the maximum score of any keyword query match (verbatim or
1567 // query suggestion).
1568 int max_query_relevance = GetKeywordVerbatimRelevance();
1569 if (!keyword_suggest_results_.empty()) {
[email protected]d519d392013-03-27 09:24:461570 max_query_relevance =
[email protected]9dfb4d362013-04-05 02:15:121571 std::max(keyword_suggest_results_.front().relevance(),
1572 max_query_relevance);
[email protected]d519d392013-03-27 09:24:461573 }
1574 // If no query is supposed to appear, then navigational matches cannot
[email protected]9dfb4d362013-04-05 02:15:121575 // be demoted past it. Get rid of suggested relevance scores for
1576 // navsuggestions and introduce the verbatim results again. The keyword
1577 // verbatim match will outscore the navsuggest matches.
1578 if (max_query_relevance == 0) {
1579 ApplyCalculatedNavigationRelevance(&keyword_navigation_results_);
1580 ApplyCalculatedNavigationRelevance(&default_navigation_results_);
1581 keyword_verbatim_relevance_ = -1;
1582 default_verbatim_relevance_ = -1;
1583 return;
1584 }
[email protected]d519d392013-03-27 09:24:461585 // Now we know we can enforce the minimum score constraint even after
1586 // the navigation matches are demoted. Proceed to demote the navigation
1587 // matches to enforce the query-must-come-first constraint.
[email protected]d519d392013-03-27 09:24:461588 // Cap the relevance score of all results.
1589 for (NavigationResults::iterator it = keyword_navigation_results_.begin();
1590 it != keyword_navigation_results_.end(); ++it) {
[email protected]9dfb4d362013-04-05 02:15:121591 if (it->relevance() < max_query_relevance)
1592 return;
1593 max_query_relevance = std::max(max_query_relevance - 1, 0);
1594 it->set_relevance(max_query_relevance);
[email protected]d519d392013-03-27 09:24:461595 }
[email protected]d519d392013-03-27 09:24:461596}
1597
[email protected]4ab4c7c2010-11-24 04:49:341598void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331599 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311600 // pending, and we're not waiting on Instant.
[email protected]2cdf1172012-08-26 12:21:331601 done_ = (!timer_.IsRunning() && (suggest_results_pending_ == 0) &&
[email protected]165fe422013-03-27 06:34:031602 (instant_finalized_ || !chrome::IsInstantEnabled(profile_)));
[email protected]4ab4c7c2010-11-24 04:49:341603}