blob: a1ccb9a3be148ce63f74d728f8286b9fc316ecc4 [file] [log] [blame]
[email protected]e41982a72012-11-20 07:16:511// Copyright 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
5#include "chrome/browser/autocomplete/search_provider.h"
6
[email protected]1cb2dac2010-03-08 21:49:157#include <algorithm>
[email protected]c3a4bd992010-08-18 20:25:018#include <cmath>
[email protected]1cb2dac2010-03-08 21:49:159
[email protected]2041cf342010-02-19 03:15:5910#include "base/callback.h"
[email protected]51124552011-07-16 01:37:1011#include "base/i18n/break_iterator.h"
[email protected]503d03872011-05-06 08:36:2612#include "base/i18n/case_conversion.h"
[email protected]d6e58c6e2009-10-10 20:40:5013#include "base/i18n/icu_string_conversions.h"
[email protected]ffbec692012-02-26 20:26:4214#include "base/json/json_string_value_serializer.h"
[email protected]fa1e0e12013-07-18 00:10:1415#include "base/message_loop/message_loop.h"
[email protected]f5b95ba92012-03-27 14:05:1916#include "base/metrics/histogram.h"
[email protected]3853a4c2013-02-11 17:15:5717#include "base/prefs/pref_service.h"
[email protected]135cb802013-06-09 16:44:2018#include "base/strings/utf_string_conversions.h"
[email protected]ea3b9a502011-04-04 14:19:3719#include "chrome/browser/autocomplete/autocomplete_classifier.h"
[email protected]810ffba2012-06-12 01:07:4820#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
[email protected]5af9bc82012-06-29 00:53:4821#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
[email protected]73c2b1632012-07-02 22:51:3822#include "chrome/browser/autocomplete/autocomplete_result.h"
[email protected]2c812ba02011-07-14 00:23:1523#include "chrome/browser/autocomplete/keyword_provider.h"
[email protected]371dab12012-06-01 03:23:5524#include "chrome/browser/autocomplete/url_prefix.h"
[email protected]9b9fa672013-11-07 06:04:5225#include "chrome/browser/google/google_util.h"
[email protected]6a2c09f2013-01-25 04:50:0726#include "chrome/browser/history/history_service.h"
[email protected]9d2db762012-06-19 00:01:1027#include "chrome/browser/history/history_service_factory.h"
[email protected]10c2d692012-05-11 05:32:2328#include "chrome/browser/history/in_memory_database.h"
[email protected]ab7780792013-01-10 01:26:0929#include "chrome/browser/metrics/variations/variations_http_header_provider.h"
[email protected]684fcc12013-03-08 22:50:0230#include "chrome/browser/omnibox/omnibox_field_trial.h"
[email protected]8ecad5e2010-12-02 21:18:3331#include "chrome/browser/profiles/profile.h"
[email protected]553c7af2014-02-06 17:58:5832#include "chrome/browser/search/instant_service.h"
33#include "chrome/browser/search/instant_service_factory.h"
[email protected]a7b8e43d2013-03-18 18:52:4334#include "chrome/browser/search/search.h"
[email protected]9899a612012-08-21 23:50:0435#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
[email protected]8e5c89a2011-06-07 18:13:3336#include "chrome/browser/search_engines/template_url_service.h"
37#include "chrome/browser/search_engines/template_url_service_factory.h"
[email protected]c4a9d4c2013-08-10 07:06:2738#include "chrome/browser/ui/browser.h"
39#include "chrome/browser/ui/browser_finder.h"
40#include "chrome/browser/ui/browser_instant_controller.h"
41#include "chrome/browser/ui/search/instant_controller.h"
[email protected]4f3b4462013-07-27 19:20:1842#include "chrome/common/net/url_fixer_upper.h"
initial.commit09911bf2008-07-26 23:55:2943#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0244#include "chrome/common/url_constants.h"
[email protected]7267ff82013-12-03 17:20:3045#include "content/public/browser/user_metrics.h"
[email protected]34ac8f32009-02-22 23:03:2746#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2947#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3448#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5549#include "net/base/net_util.h"
[email protected]bd3b4712012-12-18 17:01:3050#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2151#include "net/http/http_response_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5352#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2153#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1754#include "ui/base/l10n/l10n_util.h"
[email protected]761fa4702013-07-02 15:25:1555#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2956
[email protected]bc8bb0cd2013-06-24 21:50:2357
58// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3359
[email protected]51124552011-07-16 01:37:1060namespace {
61
[email protected]7706a522012-08-16 17:42:2562// We keep track in a histogram how many suggest requests we send, how
63// many suggest requests we invalidate (e.g., due to a user typing
64// another character), and how many replies we receive.
65// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
66// (excluding the end-of-list enum value)
67// We do not want values of existing enums to change or else it screws
68// up the statistics.
69enum SuggestRequestsHistogramValue {
70 REQUEST_SENT = 1,
71 REQUEST_INVALIDATED,
72 REPLY_RECEIVED,
73 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
74};
75
[email protected]90fe2bb2013-01-15 03:42:1376// The verbatim score for an input which is not an URL.
77const int kNonURLVerbatimRelevance = 1300;
78
[email protected]7706a522012-08-16 17:42:2579// Increments the appropriate value in the histogram by one.
80void LogOmniboxSuggestRequest(
81 SuggestRequestsHistogramValue request_value) {
82 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
83 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
84}
85
[email protected]0085863a2013-12-06 21:19:0386bool HasMultipleWords(const base::string16& text) {
[email protected]51124552011-07-16 01:37:1087 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
88 bool found_word = false;
89 if (i.Init()) {
90 while (i.Advance()) {
91 if (i.IsWord()) {
92 if (found_word)
93 return true;
94 found_word = true;
95 }
96 }
97 }
98 return false;
99}
100
[email protected]2c03c06b2013-12-11 20:45:02101AutocompleteMatchType::Type GetAutocompleteMatchType(const std::string& type) {
102 if (type == "ENTITY")
103 return AutocompleteMatchType::SEARCH_SUGGEST_ENTITY;
104 if (type == "INFINITE")
105 return AutocompleteMatchType::SEARCH_SUGGEST_INFINITE;
106 if (type == "PERSONALIZED")
107 return AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED;
108 if (type == "PROFILE")
109 return AutocompleteMatchType::SEARCH_SUGGEST_PROFILE;
110 return AutocompleteMatchType::SEARCH_SUGGEST;
[email protected]621ade062013-10-28 06:27:43111}
112
[email protected]d1f0a7f2012-06-05 10:26:42113} // namespace
[email protected]51124552011-07-16 01:37:10114
[email protected]033f3422012-03-13 21:24:18115
[email protected]7267ff82013-12-03 17:20:30116// SuggestionDeletionHandler -------------------------------------------------
117
118// This class handles making requests to the server in order to delete
119// personalized suggestions.
120class SuggestionDeletionHandler : public net::URLFetcherDelegate {
121 public:
122 typedef base::Callback<void(bool, SuggestionDeletionHandler*)>
123 DeletionCompletedCallback;
124
125 SuggestionDeletionHandler(
126 const std::string& deletion_url,
127 Profile* profile,
128 const DeletionCompletedCallback& callback);
129
130 virtual ~SuggestionDeletionHandler();
131
132 private:
133 // net::URLFetcherDelegate:
134 virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE;
135
136 scoped_ptr<net::URLFetcher> deletion_fetcher_;
137 DeletionCompletedCallback callback_;
138
139 DISALLOW_COPY_AND_ASSIGN(SuggestionDeletionHandler);
140};
141
142
143SuggestionDeletionHandler::SuggestionDeletionHandler(
144 const std::string& deletion_url,
145 Profile* profile,
146 const DeletionCompletedCallback& callback) : callback_(callback) {
147 GURL url(deletion_url);
148 DCHECK(url.is_valid());
149
150 deletion_fetcher_.reset(net::URLFetcher::Create(
151 SearchProvider::kDeletionURLFetcherID,
152 url,
153 net::URLFetcher::GET,
154 this));
155 deletion_fetcher_->SetRequestContext(profile->GetRequestContext());
156 deletion_fetcher_->Start();
157};
158
159SuggestionDeletionHandler::~SuggestionDeletionHandler() {
160};
161
162void SuggestionDeletionHandler::OnURLFetchComplete(
163 const net::URLFetcher* source) {
164 DCHECK(source == deletion_fetcher_.get());
165 callback_.Run(
166 source->GetStatus().is_success() && (source->GetResponseCode() == 200),
167 this);
168};
169
170
[email protected]3954c3a2012-04-10 20:17:55171// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:58172
[email protected]85b8d6f2012-05-08 20:53:47173SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
[email protected]02346202014-02-05 05:18:30174 : template_url_service_(template_url_service) {}
[email protected]85b8d6f2012-05-08 20:53:47175
176const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
177 return default_provider_.empty() ? NULL :
178 template_url_service_->GetTemplateURLForKeyword(default_provider_);
179}
180
181const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
182 return keyword_provider_.empty() ? NULL :
183 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24184}
185
[email protected]3954c3a2012-04-10 20:17:55186
[email protected]bc8bb0cd2013-06-24 21:50:23187// SearchProvider::CompareScoredResults ---------------------------------------
188
189class SearchProvider::CompareScoredResults {
190 public:
191 bool operator()(const Result& a, const Result& b) {
192 // Sort in descending relevance order.
193 return a.relevance() > b.relevance();
194 }
195};
196
197
[email protected]3954c3a2012-04-10 20:17:55198// SearchProvider -------------------------------------------------------------
199
200// static
201const int SearchProvider::kDefaultProviderURLFetcherID = 1;
[email protected]3954c3a2012-04-10 20:17:55202const int SearchProvider::kKeywordProviderURLFetcherID = 2;
[email protected]7267ff82013-12-03 17:20:30203const int SearchProvider::kDeletionURLFetcherID = 3;
[email protected]24dbf2302013-04-05 16:59:25204int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]d30268a2013-06-25 22:31:07205const char SearchProvider::kRelevanceFromServerKey[] = "relevance_from_server";
[email protected]987fad782013-08-28 06:23:18206const char SearchProvider::kShouldPrefetchKey[] = "should_prefetch";
207const char SearchProvider::kSuggestMetadataKey[] = "suggest_metadata";
[email protected]7267ff82013-12-03 17:20:30208const char SearchProvider::kDeletionUrlKey[] = "deletion_url";
[email protected]d30268a2013-06-25 22:31:07209const char SearchProvider::kTrue[] = "true";
210const char SearchProvider::kFalse[] = "false";
[email protected]3954c3a2012-04-10 20:17:55211
[email protected]bc8bb0cd2013-06-24 21:50:23212SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
213 Profile* profile)
[email protected]02346202014-02-05 05:18:30214 : BaseSearchProvider(listener, profile, AutocompleteProvider::TYPE_SEARCH),
[email protected]bc8bb0cd2013-06-24 21:50:23215 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
[email protected]fd4e6a592014-02-07 02:41:38216 suggest_results_pending_(0) {
[email protected]bc8bb0cd2013-06-24 21:50:23217}
218
[email protected]cb86ee6f2013-04-28 16:58:15219// static
[email protected]987fad782013-08-28 06:23:18220bool SearchProvider::ShouldPrefetch(const AutocompleteMatch& match) {
221 return match.GetAdditionalInfo(kShouldPrefetchKey) == kTrue;
222}
223
224// static
225std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
226 return match.GetAdditionalInfo(kSuggestMetadataKey);
227}
228
[email protected]7267ff82013-12-03 17:20:30229void SearchProvider::DeleteMatch(const AutocompleteMatch& match) {
[email protected]7267ff82013-12-03 17:20:30230 DCHECK(match.deletable);
231
232 deletion_handlers_.push_back(new SuggestionDeletionHandler(
233 match.GetAdditionalInfo(SearchProvider::kDeletionUrlKey),
234 profile_,
235 base::Bind(&SearchProvider::OnDeletionComplete, base::Unretained(this))));
236
[email protected]fba587fc2013-12-16 15:51:24237 HistoryService* const history_service =
238 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
239 TemplateURL* template_url = match.GetTemplateURL(profile_, false);
240 // This may be NULL if the template corresponding to the keyword has been
241 // deleted or there is no keyword set.
242 if (template_url != NULL) {
243 history_service->DeleteMatchingURLsForKeyword(template_url->id(),
244 match.contents);
245 }
246
[email protected]7267ff82013-12-03 17:20:30247 // Immediately update the list of matches to show the match was deleted,
248 // regardless of whether the server request actually succeeds.
249 DeleteMatchFromMatches(match);
250}
251
[email protected]bc8bb0cd2013-06-24 21:50:23252void SearchProvider::ResetSession() {
253 field_trial_triggered_in_session_ = false;
[email protected]4ab4c7c2010-11-24 04:49:34254}
255
[email protected]bc8bb0cd2013-06-24 21:50:23256SearchProvider::~SearchProvider() {
257}
258
259// static
[email protected]0085863a2013-12-06 21:19:03260void SearchProvider::RemoveStaleResults(const base::string16& input,
[email protected]bc8bb0cd2013-06-24 21:50:23261 int verbatim_relevance,
262 SuggestResults* suggest_results,
263 NavigationResults* navigation_results) {
264 DCHECK_GE(verbatim_relevance, 0);
265 // Keep pointers to the head of (the highest scoring elements of)
266 // |suggest_results| and |navigation_results|. Iterate down the lists
267 // removing non-inlineable results in order of decreasing relevance
268 // scores. Stop when the highest scoring element among those remaining
269 // is inlineable or the element is less than |verbatim_relevance|.
270 // This allows non-inlineable lower-scoring results to remain
271 // because (i) they are guaranteed to not be inlined and (ii)
272 // letting them remain reduces visual jank. For instance, as the
273 // user types the mis-spelled query "fpobar" (for foobar), the
274 // suggestion "foobar" will be suggested on every keystroke. If the
275 // SearchProvider always removes all non-inlineable results, the user will
276 // see visual jitter/jank as the result disappears and re-appears moments
277 // later as the suggest server returns results.
278 SuggestResults::iterator sug_it = suggest_results->begin();
279 NavigationResults::iterator nav_it = navigation_results->begin();
280 while ((sug_it != suggest_results->end()) ||
281 (nav_it != navigation_results->end())) {
282 const int sug_rel =
283 (sug_it != suggest_results->end()) ? sug_it->relevance() : -1;
284 const int nav_rel =
285 (nav_it != navigation_results->end()) ? nav_it->relevance() : -1;
286 if (std::max(sug_rel, nav_rel) < verbatim_relevance)
287 break;
288 if (sug_rel > nav_rel) {
289 // The current top result is a search suggestion.
290 if (sug_it->IsInlineable(input))
291 break;
292 sug_it = suggest_results->erase(sug_it);
293 } else if (sug_rel == nav_rel) {
294 // Have both results and they're tied.
295 const bool sug_inlineable = sug_it->IsInlineable(input);
296 const bool nav_inlineable = nav_it->IsInlineable(input);
297 if (!sug_inlineable)
298 sug_it = suggest_results->erase(sug_it);
299 if (!nav_inlineable)
300 nav_it = navigation_results->erase(nav_it);
301 if (sug_inlineable || nav_inlineable)
302 break;
303 } else {
304 // The current top result is a navigational suggestion.
305 if (nav_it->IsInlineable(input))
306 break;
307 nav_it = navigation_results->erase(nav_it);
308 }
309 }
310}
311
[email protected]ee6110b2014-01-09 22:26:31312void SearchProvider::UpdateMatchContentsClass(const base::string16& input_text,
[email protected]23db6492014-01-16 02:35:30313 Results* results) {
314 for (SuggestResults::iterator sug_it = results->suggest_results.begin();
315 sug_it != results->suggest_results.end(); ++sug_it) {
[email protected]ee6110b2014-01-09 22:26:31316 sug_it->ClassifyMatchContents(false, input_text);
317 }
[email protected]23db6492014-01-16 02:35:30318 const std::string languages(
319 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
320 for (NavigationResults::iterator nav_it = results->navigation_results.begin();
321 nav_it != results->navigation_results.end(); ++nav_it) {
322 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
323 }
[email protected]ee6110b2014-01-09 22:26:31324}
325
326// static
[email protected]bc8bb0cd2013-06-24 21:50:23327int SearchProvider::CalculateRelevanceForKeywordVerbatim(
328 AutocompleteInput::Type type,
329 bool prefer_keyword) {
330 // This function is responsible for scoring verbatim query matches
331 // for non-extension keywords. KeywordProvider::CalculateRelevance()
332 // scores verbatim query matches for extension keywords, as well as
333 // for keyword matches (i.e., suggestions of a keyword itself, not a
334 // suggestion of a query on a keyword search engine). These two
335 // functions are currently in sync, but there's no reason we
336 // couldn't decide in the future to score verbatim matches
337 // differently for extension and non-extension keywords. If you
338 // make such a change, however, you should update this comment to
339 // describe it, so it's clear why the functions diverge.
340 if (prefer_keyword)
341 return 1500;
342 return (type == AutocompleteInput::QUERY) ? 1450 : 1100;
343}
344
initial.commit09911bf2008-07-26 23:55:29345void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27346 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55347 // Do our best to load the model as early as possible. This will reduce
348 // odds of having the model not ready when really needed (a non-empty input).
349 TemplateURLService* model = providers_.template_url_service();
350 DCHECK(model);
351 model->Load();
352
initial.commit09911bf2008-07-26 23:55:29353 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57354 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29355
[email protected]6c85aa02009-02-27 12:08:09356 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29357 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]e29249dc52012-07-19 17:33:50358 Stop(false);
initial.commit09911bf2008-07-26 23:55:29359 return;
360 }
361
[email protected]14710852013-02-05 23:45:41362 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24363 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41364 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
365 &keyword_input_);
366 if (keyword_provider == NULL)
367 keyword_input_.Clear();
368 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24369 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24370
[email protected]85b8d6f2012-05-08 20:53:47371 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07372 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24373 default_provider = NULL;
374
375 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18376 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24377
378 if (!default_provider && !keyword_provider) {
379 // No valid providers.
[email protected]e29249dc52012-07-19 17:33:50380 Stop(false);
initial.commit09911bf2008-07-26 23:55:29381 return;
382 }
383
384 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24385 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03386 base::string16 default_provider_keyword(default_provider ?
387 default_provider->keyword() : base::string16());
388 base::string16 keyword_provider_keyword(keyword_provider ?
389 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32390 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47391 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29392 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15393 if (!done_)
[email protected]e29249dc52012-07-19 17:33:50394 Stop(false);
[email protected]257ab712009-04-14 17:16:24395 }
initial.commit09911bf2008-07-26 23:55:29396
[email protected]85b8d6f2012-05-08 20:53:47397 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29398
399 if (input.text().empty()) {
400 // User typed "?" alone. Give them a placeholder result indicating what
401 // this syntax does.
[email protected]257ab712009-04-14 17:16:24402 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00403 AutocompleteMatch match;
404 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36405 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24406 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35407 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47408 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36409 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24410 matches_.push_back(match);
411 }
[email protected]e29249dc52012-07-19 17:33:50412 Stop(false);
initial.commit09911bf2008-07-26 23:55:29413 return;
414 }
415
416 input_ = input;
417
[email protected]e1290ee62013-06-26 18:31:15418 DoHistoryQuery(minimal_changes);
419 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42420 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29421}
422
[email protected]e29249dc52012-07-19 17:33:50423void SearchProvider::Stop(bool clear_cached_results) {
initial.commit09911bf2008-07-26 23:55:29424 StopSuggest();
425 done_ = true;
[email protected]e29249dc52012-07-19 17:33:50426
427 if (clear_cached_results)
[email protected]71b46152013-05-03 16:39:20428 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29429}
430
[email protected]10c2d692012-05-11 05:32:23431void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29432 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24433 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25434 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15435 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06436
[email protected]d7ad4772012-06-01 03:12:54437 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]f2916ea2013-01-26 02:20:14438 // Ensure the request succeeded and that the provider used is still available.
439 // A verbatim match cannot be generated without this provider, causing errors.
[email protected]013e9a02012-05-18 20:27:10440 const bool request_succeeded =
[email protected]bc8bb0cd2013-06-24 21:50:23441 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
442 (is_keyword ?
443 providers_.GetKeywordProviderURL() :
444 providers_.GetDefaultProviderURL());
[email protected]a0ad93ea2012-05-07 22:11:53445
446 // Record response time for suggest requests sent to Google. We care
447 // only about the common case: the Google default provider used in
448 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47449 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08450 if (!is_keyword && default_url &&
[email protected]628392f2013-08-16 00:34:45451 (TemplateURLPrepopulateData::GetEngineType(*default_url) ==
[email protected]9899a612012-08-21 23:50:04452 SEARCH_ENGINE_GOOGLE)) {
[email protected]bc8bb0cd2013-06-24 21:50:23453 const base::TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10454 base::TimeTicks::Now() - time_suggest_request_sent_;
455 if (request_succeeded) {
456 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
457 elapsed_time);
458 } else {
459 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
460 elapsed_time);
461 }
[email protected]b4cebf82008-12-29 19:59:08462 }
463
[email protected]d7ad4772012-06-01 03:12:54464 bool results_updated = false;
465 if (request_succeeded) {
[email protected]ed9b1802013-10-31 04:09:48466 const net::HttpResponseHeaders* const response_headers =
467 source->GetResponseHeaders();
468 std::string json_data;
469 source->GetResponseAsString(&json_data);
[email protected]7267ff82013-12-03 17:20:30470
[email protected]ed9b1802013-10-31 04:09:48471 // JSON is supposed to be UTF-8, but some suggest service providers send
472 // JSON files in non-UTF-8 encodings. The actual encoding is usually
473 // specified in the Content-Type header field.
474 if (response_headers) {
475 std::string charset;
476 if (response_headers->GetCharset(&charset)) {
[email protected]0085863a2013-12-06 21:19:03477 base::string16 data_16;
[email protected]ed9b1802013-10-31 04:09:48478 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
479 if (base::CodepageToUTF16(json_data, charset.c_str(),
480 base::OnStringConversionError::FAIL,
481 &data_16))
[email protected]670d3232013-12-24 17:58:58482 json_data = base::UTF16ToUTF8(data_16);
[email protected]ed9b1802013-10-31 04:09:48483 }
484 }
485
[email protected]5bcdd99d2013-12-23 18:28:30486 scoped_ptr<base::Value> data(DeserializeJsonData(json_data));
[email protected]2e8c6012013-12-03 12:00:01487 results_updated = data.get() && ParseSuggestResults(data.get(), is_keyword);
[email protected]d7ad4772012-06-01 03:12:54488 }
489
[email protected]344946a12012-12-20 12:03:42490 UpdateMatches();
[email protected]d7ad4772012-06-01 03:12:54491 if (done_ || results_updated)
492 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29493}
494
[email protected]7267ff82013-12-03 17:20:30495void SearchProvider::OnDeletionComplete(bool success,
496 SuggestionDeletionHandler* handler) {
497 RecordDeletionResult(success);
498 SuggestionDeletionHandlers::iterator it = std::find(
499 deletion_handlers_.begin(), deletion_handlers_.end(), handler);
500 DCHECK(it != deletion_handlers_.end());
501 deletion_handlers_.erase(it);
502}
503
504
505void SearchProvider::RecordDeletionResult(bool success) {
506 if (success) {
507 content::RecordAction(
[email protected]e6e30ac2014-01-13 21:24:39508 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
[email protected]7267ff82013-12-03 17:20:30509 } else {
510 content::RecordAction(
[email protected]e6e30ac2014-01-13 21:24:39511 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
[email protected]7267ff82013-12-03 17:20:30512 }
513}
514
515void SearchProvider::DeleteMatchFromMatches(const AutocompleteMatch& match) {
516 for (ACMatches::iterator i(matches_.begin()); i != matches_.end(); ++i) {
517 // Find the desired match to delete by checking the type and contents.
518 // We can't check the destination URL, because the autocomplete controller
519 // may have reformulated that. Not that while checking for matching
520 // contents works for personalized suggestions, if more match types gain
521 // deletion support, this algorithm may need to be re-examined.
522 if (i->contents == match.contents && i->type == match.type) {
523 matches_.erase(i);
524 break;
525 }
526 }
527 listener_->OnProviderUpdate(true);
528}
529
[email protected]bc8bb0cd2013-06-24 21:50:23530void SearchProvider::Run() {
531 // Start a new request with the current input.
532 suggest_results_pending_ = 0;
533 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05534
[email protected]bc8bb0cd2013-06-24 21:50:23535 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
536 providers_.GetDefaultProviderURL(), input_));
537 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
538 providers_.GetKeywordProviderURL(), keyword_input_));
539
540 // Both the above can fail if the providers have been modified or deleted
541 // since the query began.
542 if (suggest_results_pending_ == 0) {
543 UpdateDone();
544 // We only need to update the listener if we're actually done.
545 if (done_)
546 listener_->OnProviderUpdate(false);
547 }
[email protected]601858c02010-09-01 17:08:20548}
549
[email protected]8d457132010-11-04 18:13:40550void SearchProvider::DoHistoryQuery(bool minimal_changes) {
551 // The history query results are synchronous, so if minimal_changes is true,
552 // we still have the last results and don't need to do anything.
553 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29554 return;
555
[email protected]31afdf72013-09-26 04:29:36556 base::TimeTicks do_history_query_start_time(base::TimeTicks::Now());
557
[email protected]8d457132010-11-04 18:13:40558 keyword_history_results_.clear();
559 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29560
[email protected]78e5e432013-08-03 02:10:10561 if (OmniboxFieldTrial::SearchHistoryDisable(
562 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16563 return;
564
[email protected]31afdf72013-09-26 04:29:36565 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]8d457132010-11-04 18:13:40566 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10567 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]31afdf72013-09-26 04:29:36568 base::TimeTicks now(base::TimeTicks::Now());
569 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.GetHistoryServiceTime",
570 now - start_time);
571 start_time = now;
[email protected]8d457132010-11-04 18:13:40572 history::URLDatabase* url_db = history_service ?
573 history_service->InMemoryDatabase() : NULL;
[email protected]31afdf72013-09-26 04:29:36574 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.InMemoryDatabaseTime",
575 base::TimeTicks::Now() - start_time);
[email protected]8d457132010-11-04 18:13:40576 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29577 return;
578
[email protected]51124552011-07-16 01:37:10579 // Request history for both the keyword and default provider. We grab many
580 // more matches than we'll ultimately clamp to so that if there are several
581 // recent multi-word matches who scores are lowered (see
582 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
583 // matches. Note that this doesn't fix the problem entirely, but merely
584 // limits it to cases with a very large number of such multi-word matches; for
585 // now, this seems OK compared with the complexity of a real fix, which would
586 // require multiple searches and tracking of "single- vs. multi-word" in the
587 // database.
588 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47589 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
590 if (default_url) {
[email protected]31afdf72013-09-26 04:29:36591 start_time = base::TimeTicks::Now();
[email protected]85b8d6f2012-05-08 20:53:47592 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
593 num_matches, &default_history_results_);
[email protected]31afdf72013-09-26 04:29:36594 UMA_HISTOGRAM_TIMES(
595 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
596 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24597 }
[email protected]85b8d6f2012-05-08 20:53:47598 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
599 if (keyword_url) {
600 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41601 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55602 }
[email protected]31afdf72013-09-26 04:29:36603 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.DoHistoryQueryTime",
604 base::TimeTicks::Now() - do_history_query_start_time);
initial.commit09911bf2008-07-26 23:55:29605}
606
[email protected]6dc950f2012-07-16 19:49:08607void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34608 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29609 StopSuggest();
[email protected]71b46152013-05-03 16:39:20610 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29611 return;
612 }
613
614 // For the minimal_changes case, if we finished the previous query and still
615 // have its results, or are allowed to keep running it, just do that, rather
616 // than starting a new query.
617 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24618 (!default_results_.suggest_results.empty() ||
619 !default_results_.navigation_results.empty() ||
620 !keyword_results_.suggest_results.empty() ||
621 !keyword_results_.navigation_results.empty() ||
[email protected]ea3b9a502011-04-04 14:19:37622 (!done_ &&
623 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29624 return;
625
626 // We can't keep running any previous query, so halt it.
627 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42628
629 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20630 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29631
[email protected]ee6110b2014-01-09 22:26:31632 // Update the content classifications of remaining results so they look good
633 // against the current input.
[email protected]23db6492014-01-16 02:35:30634 UpdateMatchContentsClass(input_.text(), &default_results_);
635 if (!keyword_input_.text().empty())
636 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31637
initial.commit09911bf2008-07-26 23:55:29638 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37639 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29640 return;
641
[email protected]24dbf2302013-04-05 16:59:25642 // To avoid flooding the suggest server, don't send a query until at
643 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24644 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
[email protected]bc8bb0cd2013-06-24 21:50:23645 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
[email protected]515ffa942012-11-27 20:18:24646 base::TimeTicks now(base::TimeTicks::Now());
647 if (now >= next_suggest_time) {
648 Run();
649 return;
650 }
651 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29652}
653
[email protected]83c726482008-09-10 06:36:34654bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55655 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
656 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47657 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
658 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34659 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47660 ((!default_url || default_url->suggestions_url().empty()) &&
661 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34662 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
663 return false;
664
[email protected]cac59d32010-08-09 23:23:14665 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34666 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34667
[email protected]cac59d32010-08-09 23:23:14668 // FORCED_QUERY means the user is explicitly asking us to search for this, so
669 // we assume it isn't a URL and/or there isn't private data.
670 if (input_.type() == AutocompleteInput::FORCED_QUERY)
671 return true;
[email protected]83c726482008-09-10 06:36:34672
[email protected]f608ea102013-03-18 15:08:09673 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
674 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
675 // is both a waste of time and a disclosure of potentially private, local
676 // data. Other "schemes" may actually be usernames, and we don't want to send
677 // passwords. If the scheme is OK, we still need to check other cases below.
678 // If this is QUERY, then the presence of these schemes means the user
679 // explicitly typed one, and thus this is probably a URL that's being entered
680 // and happens to currently be invalid -- in which case we again want to run
681 // our checks below. Other QUERY cases are less likely to be URLs and thus we
682 // assume we're OK.
[email protected]e9a82042013-09-15 03:38:29683 if (!LowerCaseEqualsASCII(input_.scheme(), content::kHttpScheme) &&
[email protected]4654bfe2013-08-26 03:36:58684 !LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]72aa4c22013-12-01 15:09:35685 !LowerCaseEqualsASCII(input_.scheme(), content::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14686 return (input_.type() == AutocompleteInput::QUERY);
687
688 // Don't send URLs with usernames, queries or refs. Some of these are
689 // private, and the Suggest server is unlikely to have any useful results
690 // for any of them. Also don't send URLs with ports, as we may initially
691 // think that a username + password is a host + port (and we don't want to
692 // send usernames/passwords), and even if the port really is a port, the
693 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58694 // Note that we only block based on refs if the input is URL-typed, as search
695 // queries can legitimately have #s in them which the URL parser
696 // overaggressively categorizes as a url with a ref.
[email protected]cac59d32010-08-09 23:23:14697 const url_parse::Parsed& parts = input_.parts();
698 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58699 parts.query.is_nonempty() ||
700 (parts.ref.is_nonempty() && (input_.type() == AutocompleteInput::URL)))
[email protected]cac59d32010-08-09 23:23:14701 return false;
702
703 // Don't send anything for https except the hostname. Hostnames are OK
704 // because they are visible when the TCP connection is established, but the
705 // specific path may reveal private information.
[email protected]4654bfe2013-08-26 03:36:58706 if (LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36707 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14708 return false;
[email protected]83c726482008-09-10 06:36:34709
710 return true;
711}
712
initial.commit09911bf2008-07-26 23:55:29713void SearchProvider::StopSuggest() {
[email protected]7706a522012-08-16 17:42:25714 // Increment the appropriate field in the histogram by the number of
715 // pending requests that were invalidated.
716 for (int i = 0; i < suggest_results_pending_; i++)
717 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
[email protected]257ab712009-04-14 17:16:24718 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14719 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24720 // Stop any in-progress URL fetches.
721 keyword_fetcher_.reset();
722 default_fetcher_.reset();
[email protected]55ce8f12012-05-09 04:44:08723}
724
[email protected]71b46152013-05-03 16:39:20725void SearchProvider::ClearAllResults() {
[email protected]cc1526e2013-05-17 04:04:24726 keyword_results_.Clear();
727 default_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51728}
729
[email protected]71b46152013-05-03 16:39:20730void SearchProvider::RemoveAllStaleResults() {
[email protected]dc735c02013-11-12 23:23:41731 // We only need to remove stale results (which ensures the top-scoring
732 // match is inlineable) if the user is not in reorder mode. In reorder
733 // mode, the autocomplete system will reorder results to make sure the
734 // top result is inlineable.
735 const bool omnibox_will_reorder_for_legal_default_match =
736 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
737 input_.current_page_classification());
[email protected]1e1550e2013-05-02 17:37:51738 // In theory it would be better to run an algorithm like that in
739 // RemoveStaleResults(...) below that uses all four results lists
740 // and both verbatim scores at once. However, that will be much
741 // more complicated for little obvious gain. For code simplicity
742 // and ease in reasoning about the invariants involved, this code
743 // removes stales results from the keyword provider and default
744 // provider independently.
[email protected]dc735c02013-11-12 23:23:41745 if (!omnibox_will_reorder_for_legal_default_match) {
746 RemoveStaleResults(input_.text(), GetVerbatimRelevance(NULL),
747 &default_results_.suggest_results,
748 &default_results_.navigation_results);
749 if (!keyword_input_.text().empty()) {
750 RemoveStaleResults(keyword_input_.text(),
751 GetKeywordVerbatimRelevance(NULL),
752 &keyword_results_.suggest_results,
753 &keyword_results_.navigation_results);
754 }
755 }
756 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51757 // User is either in keyword mode with a blank input or out of
758 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24759 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51760 }
[email protected]d1f0a7f2012-06-05 10:26:42761}
762
[email protected]d1f0a7f2012-06-05 10:26:42763void SearchProvider::ApplyCalculatedRelevance() {
[email protected]cc1526e2013-05-17 04:04:24764 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
765 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
766 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
767 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
[email protected]cc1526e2013-05-17 04:04:24768 default_results_.verbatim_relevance = -1;
769 keyword_results_.verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42770}
771
[email protected]188b50c2013-03-28 07:19:42772void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42773 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42774 SuggestResult& result = (*list)[i];
775 result.set_relevance(
776 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
777 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07778 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42779 }
780}
781
[email protected]188b50c2013-03-28 07:19:42782void SearchProvider::ApplyCalculatedNavigationRelevance(
783 NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42784 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42785 NavigationResult& result = (*list)[i];
786 result.set_relevance(
787 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
788 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07789 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42790 }
791}
792
[email protected]15fb2aa2012-05-22 22:52:59793net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12794 int id,
[email protected]9ff91722012-09-07 05:29:12795 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41796 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12797 if (!template_url || template_url->suggestions_url().empty())
798 return NULL;
799
800 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41801 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
802 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18803 search_term_args.page_classification = input.current_page_classification();
[email protected]9ff91722012-09-07 05:29:12804 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:16805 search_term_args));
[email protected]9ff91722012-09-07 05:29:12806 if (!suggest_url.is_valid())
807 return NULL;
[email protected]9b9fa672013-11-07 06:04:52808 // Send the current page URL if user setting and URL requirements are met and
809 // the user is in the field trial.
810 if (CanSendURL(current_page_url_, suggest_url, template_url,
811 input.current_page_classification(), profile_) &&
812 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
813 search_term_args.current_page_url = current_page_url_.spec();
814 // Create the suggest URL again with the current page URL.
815 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
816 search_term_args));
817 }
[email protected]9ff91722012-09-07 05:29:12818
819 suggest_results_pending_++;
820 LogOmniboxSuggestRequest(REQUEST_SENT);
821
822 net::URLFetcher* fetcher =
823 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12824 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34825 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30826 // Add Chrome experiment state to the request headers.
827 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:09828 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30829 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
830 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24831 fetcher->Start();
832 return fetcher;
833}
834
[email protected]5bcdd99d2013-12-23 18:28:30835bool SearchProvider::ParseSuggestResults(base::Value* root_val,
836 bool is_keyword) {
[email protected]0085863a2013-12-06 21:19:03837 base::string16 query;
[email protected]5bcdd99d2013-12-23 18:28:30838 base::ListValue* root_list = NULL;
839 base::ListValue* results_list = NULL;
[email protected]0085863a2013-12-06 21:19:03840 const base::string16& input_text =
[email protected]14710852013-02-05 23:45:41841 is_keyword ? keyword_input_.text() : input_.text();
[email protected]d7ad4772012-06-01 03:12:54842 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
[email protected]cc1526e2013-05-17 04:04:24843 (query != input_text) || !root_list->GetList(1, &results_list))
initial.commit09911bf2008-07-26 23:55:29844 return false;
845
[email protected]55ce8f12012-05-09 04:44:08846 // 3rd element: Description list.
[email protected]5bcdd99d2013-12-23 18:28:30847 base::ListValue* descriptions = NULL;
[email protected]d7ad4772012-06-01 03:12:54848 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:29849
[email protected]55ce8f12012-05-09 04:44:08850 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:29851
[email protected]d1f0a7f2012-06-05 10:26:42852 // Reset suggested relevance information from the default provider.
[email protected]cc1526e2013-05-17 04:04:24853 Results* results = is_keyword ? &keyword_results_ : &default_results_;
[email protected]cc1526e2013-05-17 04:04:24854 results->verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42855
[email protected]55ce8f12012-05-09 04:44:08856 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]5bcdd99d2013-12-23 18:28:30857 base::ListValue* types = NULL;
858 base::ListValue* relevances = NULL;
859 base::ListValue* suggestion_details = NULL;
860 base::DictionaryValue* extras = NULL;
[email protected]987fad782013-08-28 06:23:18861 int prefetch_index = -1;
[email protected]d1f0a7f2012-06-05 10:26:42862 if (root_list->GetDictionary(4, &extras)) {
863 extras->GetList("google:suggesttype", &types);
864
[email protected]eb8330d2013-06-15 00:55:08865 // Discard this list if its size does not match that of the suggestions.
866 if (extras->GetList("google:suggestrelevance", &relevances) &&
[email protected]621ade062013-10-28 06:27:43867 (relevances->GetSize() != results_list->GetSize()))
[email protected]eb8330d2013-06-15 00:55:08868 relevances = NULL;
869 extras->GetInteger("google:verbatimrelevance",
870 &results->verbatim_relevance);
[email protected]618d6e62012-12-16 05:55:57871
872 // Check if the active suggest field trial (if any) has triggered either
873 // for the default provider or keyword provider.
874 bool triggered = false;
875 extras->GetBoolean("google:fieldtrialtriggered", &triggered);
876 field_trial_triggered_ |= triggered;
877 field_trial_triggered_in_session_ |= triggered;
[email protected]987fad782013-08-28 06:23:18878
[email protected]5bcdd99d2013-12-23 18:28:30879 base::DictionaryValue* client_data = NULL;
[email protected]987fad782013-08-28 06:23:18880 if (extras->GetDictionary("google:clientdata", &client_data) && client_data)
881 client_data->GetInteger("phi", &prefetch_index);
882
[email protected]621ade062013-10-28 06:27:43883 if (extras->GetList("google:suggestdetail", &suggestion_details) &&
884 suggestion_details->GetSize() != results_list->GetSize())
885 suggestion_details = NULL;
886
[email protected]987fad782013-08-28 06:23:18887 // Store the metadata that came with the response in case we need to pass it
888 // along with the prefetch query to Instant.
889 JSONStringValueSerializer json_serializer(&results->metadata);
890 json_serializer.Serialize(*extras);
initial.commit09911bf2008-07-26 23:55:29891 }
892
[email protected]d1f0a7f2012-06-05 10:26:42893 // Clear the previous results now that new results are available.
[email protected]cc1526e2013-05-17 04:04:24894 results->suggest_results.clear();
895 results->navigation_results.clear();
[email protected]d1f0a7f2012-06-05 10:26:42896
[email protected]0085863a2013-12-06 21:19:03897 base::string16 suggestion;
[email protected]d1f0a7f2012-06-05 10:26:42898 std::string type;
899 int relevance = -1;
[email protected]3f381592013-11-05 20:43:51900 // Prohibit navsuggest in FORCED_QUERY mode. Users wants queries, not URLs.
901 const bool allow_navsuggest =
902 (is_keyword ? keyword_input_.type() : input_.type()) !=
903 AutocompleteInput::FORCED_QUERY;
[email protected]23db6492014-01-16 02:35:30904 const std::string languages(
905 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
[email protected]621ade062013-10-28 06:27:43906 for (size_t index = 0; results_list->GetString(index, &suggestion); ++index) {
[email protected]8e81f5092010-09-29 23:19:40907 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:08908 // they make no sense at all and can cause problems in our code.
[email protected]621ade062013-10-28 06:27:43909 if (suggestion.empty())
[email protected]8e81f5092010-09-29 23:19:40910 continue;
911
[email protected]d1f0a7f2012-06-05 10:26:42912 // Apply valid suggested relevance scores; discard invalid lists.
913 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
914 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:54915 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:42916 // Do not blindly trust the URL coming from the server to be valid.
[email protected]670d3232013-12-24 17:58:58917 GURL url(URLFixerUpper::FixupURL(
918 base::UTF16ToUTF8(suggestion), std::string()));
[email protected]3f381592013-11-05 20:43:51919 if (url.is_valid() && allow_navsuggest) {
[email protected]0085863a2013-12-06 21:19:03920 base::string16 title;
[email protected]d1f0a7f2012-06-05 10:26:42921 if (descriptions != NULL)
922 descriptions->GetString(index, &title);
[email protected]d30268a2013-06-25 22:31:07923 results->navigation_results.push_back(NavigationResult(
[email protected]23db6492014-01-16 02:35:30924 *this, url, title, is_keyword, relevance, true, input_text,
925 languages));
initial.commit09911bf2008-07-26 23:55:29926 }
927 } else {
[email protected]2c03c06b2013-12-11 20:45:02928 AutocompleteMatchType::Type match_type = GetAutocompleteMatchType(type);
[email protected]987fad782013-08-28 06:23:18929 bool should_prefetch = static_cast<int>(index) == prefetch_index;
[email protected]5bcdd99d2013-12-23 18:28:30930 base::DictionaryValue* suggestion_detail = NULL;
[email protected]0085863a2013-12-06 21:19:03931 base::string16 match_contents = suggestion;
932 base::string16 annotation;
[email protected]621ade062013-10-28 06:27:43933 std::string suggest_query_params;
[email protected]7267ff82013-12-03 17:20:30934 std::string deletion_url;
935
936 if (suggestion_details) {
937 suggestion_details->GetDictionary(index, &suggestion_detail);
938 if (suggestion_detail) {
939 suggestion_detail->GetString("du", &deletion_url);
[email protected]2c03c06b2013-12-11 20:45:02940 suggestion_detail->GetString("title", &match_contents) ||
941 suggestion_detail->GetString("t", &match_contents);
[email protected]ee6110b2014-01-09 22:26:31942 // Error correction for bad data from server.
943 if (match_contents.empty())
944 match_contents = suggestion;
[email protected]2c03c06b2013-12-11 20:45:02945 suggestion_detail->GetString("annotation", &annotation) ||
946 suggestion_detail->GetString("a", &annotation);
947 suggestion_detail->GetString("query_params", &suggest_query_params) ||
948 suggestion_detail->GetString("q", &suggest_query_params);
[email protected]7267ff82013-12-03 17:20:30949 }
[email protected]621ade062013-10-28 06:27:43950 }
[email protected]7267ff82013-12-03 17:20:30951
[email protected]621ade062013-10-28 06:27:43952 // TODO(kochi): Improve calculator suggestion presentation.
953 results->suggest_results.push_back(SuggestResult(
[email protected]2c03c06b2013-12-11 20:45:02954 suggestion, match_type, match_contents, annotation,
955 suggest_query_params, deletion_url, is_keyword, relevance, true,
[email protected]ee6110b2014-01-09 22:26:31956 should_prefetch, input_text));
initial.commit09911bf2008-07-26 23:55:29957 }
958 }
959
[email protected]43126b7192013-11-14 18:10:34960 // Ignore suggested scores for non-keyword matches in keyword mode; if the
961 // server is allowed to score these, it could interfere with the user's
962 // ability to get good keyword results.
963 const bool abandon_suggested_scores =
964 !is_keyword && !providers_.keyword_provider().empty();
965 // Apply calculated relevance scores to suggestions if a valid list was
966 // not provided or we're abandoning suggested scores entirely.
967 if ((relevances == NULL) || abandon_suggested_scores) {
[email protected]cc1526e2013-05-17 04:04:24968 ApplyCalculatedSuggestRelevance(&results->suggest_results);
969 ApplyCalculatedNavigationRelevance(&results->navigation_results);
[email protected]43126b7192013-11-14 18:10:34970 // If abandoning scores entirely, also abandon the verbatim score.
971 if (abandon_suggested_scores)
972 results->verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42973 }
[email protected]43126b7192013-11-14 18:10:34974
[email protected]9dfb4d362013-04-05 02:15:12975 // Keep the result lists sorted.
976 const CompareScoredResults comparator = CompareScoredResults();
[email protected]cc1526e2013-05-17 04:04:24977 std::stable_sort(results->suggest_results.begin(),
978 results->suggest_results.end(),
[email protected]9dfb4d362013-04-05 02:15:12979 comparator);
[email protected]cc1526e2013-05-17 04:04:24980 std::stable_sort(results->navigation_results.begin(),
981 results->navigation_results.end(),
[email protected]9dfb4d362013-04-05 02:15:12982 comparator);
[email protected]d1f0a7f2012-06-05 10:26:42983 return true;
initial.commit09911bf2008-07-26 23:55:29984}
985
[email protected]344946a12012-12-20 12:03:42986void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29987 // Convert all the results to matches and add them to a map, so we can keep
988 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36989 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29990 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23991 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24992 int did_not_accept_keyword_suggestion =
993 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29994 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
995 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29996
[email protected]d30268a2013-06-25 22:31:07997 bool relevance_from_server;
998 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24999 int did_not_accept_default_suggestion =
1000 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:081001 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
1002 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:421003 if (verbatim_relevance > 0) {
[email protected]2c03c06b2013-12-11 20:45:021004 SuggestResult verbatim(
1005 input_.text(), AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]ee6110b2014-01-09 22:26:311006 input_.text(), base::string16(), std::string(), std::string(), false,
1007 verbatim_relevance, relevance_from_server, false, input_.text());
[email protected]866f02e2013-12-10 17:12:051008 AddMatchToMap(verbatim, input_.text(), std::string(),
[email protected]866f02e2013-12-10 17:12:051009 did_not_accept_default_suggestion, &map);
[email protected]d1f0a7f2012-06-05 10:26:421010 }
[email protected]5423e562013-02-07 03:58:451011 if (!keyword_input_.text().empty()) {
1012 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1013 // We only create the verbatim search query match for a keyword
1014 // if it's not an extension keyword. Extension keywords are handled
1015 // in KeywordProvider::Start(). (Extensions are complicated...)
1016 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
1017 // to the keyword verbatim search query. Do not create other matches
1018 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:251019 if (keyword_url &&
1020 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:071021 bool keyword_relevance_from_server;
1022 const int keyword_verbatim_relevance =
1023 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:281024 if (keyword_verbatim_relevance > 0) {
[email protected]2c03c06b2013-12-11 20:45:021025 SuggestResult verbatim(
1026 keyword_input_.text(), AutocompleteMatchType::SEARCH_OTHER_ENGINE,
1027 keyword_input_.text(), base::string16(), std::string(),
1028 std::string(), true, keyword_verbatim_relevance,
[email protected]ee6110b2014-01-09 22:26:311029 keyword_relevance_from_server, false, keyword_input_.text());
[email protected]866f02e2013-12-10 17:12:051030 AddMatchToMap(verbatim, keyword_input_.text(), std::string(),
[email protected]866f02e2013-12-10 17:12:051031 did_not_accept_keyword_suggestion, &map);
[email protected]dab8d52d2013-03-05 07:35:281032 }
[email protected]5423e562013-02-07 03:58:451033 }
1034 }
[email protected]257ab712009-04-14 17:16:241035 AddHistoryResultsToMap(keyword_history_results_, true,
1036 did_not_accept_keyword_suggestion, &map);
1037 AddHistoryResultsToMap(default_history_results_, false,
1038 did_not_accept_default_suggestion, &map);
1039
[email protected]d1cb6a822013-09-18 19:43:001040 AddSuggestResultsToMap(keyword_results_.suggest_results,
1041 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:181042 AddSuggestResultsToMap(default_results_.suggest_results,
1043 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:291044
[email protected]d30268a2013-06-25 22:31:071045 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:291046 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:071047 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:291048
[email protected]d30268a2013-06-25 22:31:071049 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
1050 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:291051
[email protected]d30268a2013-06-25 22:31:071052 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
1053 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
1054 // enabled and we have server-provided (and thus hopefully more accurate)
1055 // scores for some suggestions, we allow more of those, until we reach
1056 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
1057 // whole popup).
1058 //
1059 // We will always return any verbatim matches, no matter how we obtained their
1060 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
1061 // higher-scoring matches under the conditions above.
[email protected]31afdf72013-09-26 04:29:361062 UMA_HISTOGRAM_CUSTOM_COUNTS(
1063 "Omnibox.SearchProvider.NumMatchesToSort", matches.size(), 1, 50, 20);
[email protected]d30268a2013-06-25 22:31:071064 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
1065 matches_.clear();
[email protected]3723e6e2012-06-11 21:06:561066
[email protected]d30268a2013-06-25 22:31:071067 size_t num_suggestions = 0;
1068 for (ACMatches::const_iterator i(matches.begin());
1069 (i != matches.end()) &&
1070 (matches_.size() < AutocompleteResult::kMaxMatches);
1071 ++i) {
1072 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
1073 // verbatim result, so this condition basically means "if this match is a
1074 // suggestion of some sort".
1075 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
1076 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
1077 // If we've already hit the limit on non-server-scored suggestions, and
1078 // this isn't a server-scored suggestion we can add, skip it.
1079 if ((num_suggestions >= kMaxMatches) &&
1080 (!chrome::IsInstantExtendedAPIEnabled() ||
1081 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
1082 continue;
1083 }
1084
1085 ++num_suggestions;
1086 }
1087
1088 matches_.push_back(*i);
1089 }
[email protected]31afdf72013-09-26 04:29:361090 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
1091 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:421092}
1093
[email protected]0a8718b12013-11-13 18:41:311094ACMatches::const_iterator SearchProvider::FindTopMatch(
1095 bool autocomplete_result_will_reorder_for_default_match) const {
1096 if (!autocomplete_result_will_reorder_for_default_match)
1097 return matches_.begin();
1098 ACMatches::const_iterator it = matches_.begin();
1099 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
1100 ++it;
1101 return it;
[email protected]9dfb4d362013-04-05 02:15:121102}
1103
[email protected]0a8718b12013-11-13 18:41:311104bool SearchProvider::IsTopMatchNavigationInKeywordMode(
1105 bool autocomplete_result_will_reorder_for_default_match) const {
1106 ACMatches::const_iterator first_match =
1107 FindTopMatch(autocomplete_result_will_reorder_for_default_match);
1108 return !providers_.keyword_provider().empty() &&
1109 (first_match != matches_.end()) &&
1110 (first_match->type == AutocompleteMatchType::NAVSUGGEST);
1111}
1112
[email protected]1c1e7842013-11-22 16:28:161113bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const {
1114 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1115 // If the user is not in keyword mode, return true to say that this
1116 // constraint is not violated.
1117 if (keyword_url == NULL)
1118 return true;
1119 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
1120 ++it) {
1121 if ((it->keyword == keyword_url->keyword()) &&
1122 it->allowed_to_be_default_match)
1123 return true;
1124 }
1125 return false;
1126}
1127
[email protected]0a8718b12013-11-13 18:41:311128bool SearchProvider::IsTopMatchScoreTooLow(
1129 bool autocomplete_result_will_reorder_for_default_match) const {
1130 // In reorder mode, there's no such thing as a score that's too low.
1131 if (autocomplete_result_will_reorder_for_default_match)
1132 return false;
1133
[email protected]dab8d52d2013-03-05 07:35:281134 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
1135 // rather than CalculateRelevanceForVerbatim() because the latter returns
1136 // a very low score (250) if keyword mode is active. This is because
1137 // when keyword mode is active the user probably wants the keyword matches,
1138 // not matches from the default provider. Hence, we use the version of
1139 // the function that ignores whether keyword mode is active. This allows
1140 // SearchProvider to maintain its contract with the AutocompleteController
1141 // that it will always provide an inlineable match with a reasonable
1142 // score.
1143 return matches_.front().relevance <
1144 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
[email protected]344946a12012-12-20 12:03:421145}
1146
[email protected]0a8718b12013-11-13 18:41:311147bool SearchProvider::IsTopMatchSearchWithURLInput(
1148 bool autocomplete_result_will_reorder_for_default_match) const {
1149 ACMatches::const_iterator first_match =
1150 FindTopMatch(autocomplete_result_will_reorder_for_default_match);
1151 return (input_.type() == AutocompleteInput::URL) &&
1152 (first_match != matches_.end()) &&
1153 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
1154 (first_match->type != AutocompleteMatchType::NAVSUGGEST);
[email protected]344946a12012-12-20 12:03:421155}
1156
[email protected]45f89a92013-08-12 13:41:361157bool SearchProvider::HasValidDefaultMatch(
1158 bool autocomplete_result_will_reorder_for_default_match) const {
1159 // One of the SearchProvider matches may need to be the overall default. If
1160 // AutocompleteResult is allowed to reorder matches, this means we simply
1161 // need at least one match in the list to be |allowed_to_be_default_match|.
1162 // If no reordering is possible, however, then our first match needs to have
1163 // this flag.
1164 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
1165 ++it) {
1166 if (it->allowed_to_be_default_match)
1167 return true;
1168 if (!autocomplete_result_will_reorder_for_default_match)
1169 return false;
1170 }
1171 return false;
[email protected]344946a12012-12-20 12:03:421172}
1173
1174void SearchProvider::UpdateMatches() {
[email protected]31afdf72013-09-26 04:29:361175 base::TimeTicks update_matches_start_time(base::TimeTicks::Now());
[email protected]344946a12012-12-20 12:03:421176 ConvertResultsToAutocompleteMatches();
initial.commit09911bf2008-07-26 23:55:291177
[email protected]382a0642012-06-06 06:13:521178 // Check constraints that may be violated by suggested relevances.
[email protected]344946a12012-12-20 12:03:421179 if (!matches_.empty() &&
[email protected]bc8bb0cd2013-06-24 21:50:231180 (default_results_.HasServerProvidedScores() ||
1181 keyword_results_.HasServerProvidedScores())) {
[email protected]9dfb4d362013-04-05 02:15:121182 // These blocks attempt to repair undesirable behavior by suggested
[email protected]344946a12012-12-20 12:03:421183 // relevances with minimal impact, preserving other suggested relevances.
[email protected]0a8718b12013-11-13 18:41:311184
1185 // True if the omnibox will reorder matches as necessary to make the first
1186 // one something that is allowed to be the default match.
1187 const bool omnibox_will_reorder_for_legal_default_match =
1188 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
1189 input_.current_page_classification());
1190 if (IsTopMatchNavigationInKeywordMode(
1191 omnibox_will_reorder_for_legal_default_match)) {
[email protected]9dfb4d362013-04-05 02:15:121192 // Correct the suggested relevance scores if the top match is a
1193 // navigation in keyword mode, since inlining a navigation match
[email protected]1c1e7842013-11-22 16:28:161194 // would break the user out of keyword mode. This will only be
1195 // triggered in regular (non-reorder) mode; in reorder mode,
1196 // navigation matches are marked as not allowed to be the default
1197 // match and hence IsTopMatchNavigation() will always return false.
1198 DCHECK(!omnibox_will_reorder_for_legal_default_match);
[email protected]9dfb4d362013-04-05 02:15:121199 DemoteKeywordNavigationMatchesPastTopQuery();
1200 ConvertResultsToAutocompleteMatches();
[email protected]0a8718b12013-11-13 18:41:311201 DCHECK(!IsTopMatchNavigationInKeywordMode(
1202 omnibox_will_reorder_for_legal_default_match));
[email protected]9dfb4d362013-04-05 02:15:121203 }
[email protected]1c1e7842013-11-22 16:28:161204 if (!HasKeywordDefaultMatchInKeywordMode()) {
1205 // In keyword mode, disregard the keyword verbatim suggested relevance
1206 // if necessary so there at least one keyword match that's allowed to
1207 // be the default match.
1208 keyword_results_.verbatim_relevance = -1;
1209 ConvertResultsToAutocompleteMatches();
1210 }
[email protected]0a8718b12013-11-13 18:41:311211 if (IsTopMatchScoreTooLow(omnibox_will_reorder_for_legal_default_match)) {
[email protected]1beee342012-06-19 22:22:281212 // Disregard the suggested verbatim relevance if the top score is below
1213 // the usual verbatim value. For example, a BarProvider may rely on
[email protected]45f89a92013-08-12 13:41:361214 // SearchProvider's verbatim or inlineable matches for input "foo" (all
1215 // allowed to be default match) to always outrank its own lowly-ranked
[email protected]0a8718b12013-11-13 18:41:311216 // "bar" matches that shouldn't be the default match.
[email protected]cc1526e2013-05-17 04:04:241217 default_results_.verbatim_relevance = -1;
1218 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421219 ConvertResultsToAutocompleteMatches();
[email protected]e6acd002012-06-16 22:27:471220 }
[email protected]0a8718b12013-11-13 18:41:311221 if (IsTopMatchSearchWithURLInput(
1222 omnibox_will_reorder_for_legal_default_match)) {
[email protected]e6acd002012-06-16 22:27:471223 // Disregard the suggested search and verbatim relevances if the input
1224 // type is URL and the top match is a highly-ranked search suggestion.
1225 // For example, prevent a search for "foo.com" from outranking another
1226 // provider's navigation for "foo.com" or "foo.com/url_from_history".
[email protected]cc1526e2013-05-17 04:04:241227 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
1228 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
1229 default_results_.verbatim_relevance = -1;
1230 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421231 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521232 }
[email protected]45f89a92013-08-12 13:41:361233 if (!HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match)) {
1234 // If the omnibox is not going to reorder results to put a legal default
1235 // match at the top, then this provider needs to guarantee that its top
1236 // scoring result is a legal default match (i.e., it's either a verbatim
1237 // match or inlinable). For example, input "foo" should not invoke a
1238 // search for "bar", which would happen if the "bar" search match
1239 // outranked all other matches. On the other hand, if the omnibox will
1240 // reorder matches as necessary to put a legal default match at the top,
1241 // all we need to guarantee is that SearchProvider returns a legal
1242 // default match. (The omnibox always needs at least one legal default
1243 // match, and it relies on SearchProvider to always return one.)
[email protected]344946a12012-12-20 12:03:421244 ApplyCalculatedRelevance();
1245 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521246 }
[email protected]0a8718b12013-11-13 18:41:311247 DCHECK(!IsTopMatchNavigationInKeywordMode(
1248 omnibox_will_reorder_for_legal_default_match));
[email protected]1c1e7842013-11-22 16:28:161249 DCHECK(HasKeywordDefaultMatchInKeywordMode());
[email protected]0a8718b12013-11-13 18:41:311250 DCHECK(!IsTopMatchScoreTooLow(
1251 omnibox_will_reorder_for_legal_default_match));
1252 DCHECK(!IsTopMatchSearchWithURLInput(
1253 omnibox_will_reorder_for_legal_default_match));
[email protected]45f89a92013-08-12 13:41:361254 DCHECK(HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match));
[email protected]d1f0a7f2012-06-05 10:26:421255 }
[email protected]3972aba2014-02-05 21:28:101256 UMA_HISTOGRAM_CUSTOM_COUNTS(
1257 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
[email protected]d1f0a7f2012-06-05 10:26:421258
[email protected]1c1e7842013-11-22 16:28:161259 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1260 if ((keyword_url != NULL) && HasKeywordDefaultMatchInKeywordMode()) {
1261 // If there is a keyword match that is allowed to be the default match,
1262 // then prohibit default provider matches from being the default match lest
1263 // such matches cause the user to break out of keyword mode.
1264 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
1265 ++it) {
1266 if (it->keyword != keyword_url->keyword())
1267 it->allowed_to_be_default_match = false;
1268 }
1269 }
1270
[email protected]31afdf72013-09-26 04:29:361271 base::TimeTicks update_starred_start_time(base::TimeTicks::Now());
[email protected]cc63dea2008-08-21 20:56:311272 UpdateStarredStateOfMatches();
[email protected]31afdf72013-09-26 04:29:361273 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateStarredTime",
1274 base::TimeTicks::Now() - update_starred_start_time);
[email protected]4ab4c7c2010-11-24 04:49:341275 UpdateDone();
[email protected]31afdf72013-09-26 04:29:361276 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateMatchesTime",
1277 base::TimeTicks::Now() - update_matches_start_time);
[email protected]257ab712009-04-14 17:16:241278}
1279
1280void SearchProvider::AddNavigationResultsToMatches(
[email protected]d30268a2013-06-25 22:31:071281 const NavigationResults& navigation_results,
1282 ACMatches* matches) {
[email protected]bc8bb0cd2013-06-24 21:50:231283 for (NavigationResults::const_iterator it = navigation_results.begin();
1284 it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:071285 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:231286 // In the absence of suggested relevance scores, use only the single
1287 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:071288 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:231289 return;
[email protected]257ab712009-04-14 17:16:241290 }
1291}
1292
1293void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
1294 bool is_keyword,
1295 int did_not_accept_suggestion,
1296 MatchMap* map) {
[email protected]51124552011-07-16 01:37:101297 if (results.empty())
1298 return;
1299
[email protected]31afdf72013-09-26 04:29:361300 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]d7ad4772012-06-01 03:12:541301 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1302 (input_.type() == AutocompleteInput::URL);
[email protected]0085863a2013-12-06 21:19:031303 const base::string16& input_text =
[email protected]14710852013-02-05 23:45:411304 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:101305 bool input_multiple_words = HasMultipleWords(input_text);
1306
[email protected]55ce8f12012-05-09 04:44:081307 SuggestResults scored_results;
1308 if (!prevent_inline_autocomplete && input_multiple_words) {
1309 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1310 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:101311 // autocompleting a multi-word, multi-visit query, and the current input is
1312 // still a prefix of it, then changing the autocompletion suddenly feels
1313 // wrong. To detect this case, first score as if only one word has been
1314 // typed, then check for a best result that is an autocompleted, multi-word
1315 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:081316 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1317 false, input_text, is_keyword);
[email protected]9dfb4d362013-04-05 02:15:121318 if ((scored_results.front().relevance() <
[email protected]55ce8f12012-05-09 04:44:081319 AutocompleteResult::kLowestDefaultScore) ||
[email protected]9dfb4d362013-04-05 02:15:121320 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:081321 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:101322 }
[email protected]55ce8f12012-05-09 04:44:081323 if (scored_results.empty())
1324 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1325 input_multiple_words, input_text,
1326 is_keyword);
1327 for (SuggestResults::const_iterator i(scored_results.begin());
1328 i != scored_results.end(); ++i) {
[email protected]866f02e2013-12-10 17:12:051329 AddMatchToMap(*i, input_text, std::string(),
[email protected]866f02e2013-12-10 17:12:051330 did_not_accept_suggestion, map);
[email protected]51124552011-07-16 01:37:101331 }
[email protected]31afdf72013-09-26 04:29:361332 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1333 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:101334}
1335
[email protected]55ce8f12012-05-09 04:44:081336SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:101337 const HistoryResults& results,
1338 bool base_prevent_inline_autocomplete,
1339 bool input_multiple_words,
[email protected]0085863a2013-12-06 21:19:031340 const base::string16& input_text,
[email protected]51124552011-07-16 01:37:101341 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:481342 AutocompleteClassifier* classifier =
1343 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:081344 SuggestResults scored_results;
[email protected]78e5e432013-08-03 02:10:101345 const bool prevent_search_history_inlining =
1346 OmniboxFieldTrial::SearchHistoryPreventInlining(
1347 input_.current_page_classification());
[email protected]257ab712009-04-14 17:16:241348 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1349 ++i) {
[email protected]51124552011-07-16 01:37:101350 // Don't autocomplete multi-word queries that have only been seen once
1351 // unless the user has typed more than one word.
1352 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1353 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
1354
[email protected]ea3b9a502011-04-04 14:19:371355 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:101356 // when typed. For example, if the user searched for "google.com" and types
1357 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1358 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:481359 // NOTE: We don't check this in the following cases:
1360 // * When inline autocomplete is disabled, we won't be inline
1361 // autocompleting this term, so we don't need to worry about confusion as
1362 // much. This also prevents calling Classify() again from inside the
1363 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:101364 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:481365 // * When the user has typed the whole term, the "what you typed" history
1366 // match will outrank us for URL-like inputs anyway, so we need not do
1367 // anything special.
[email protected]51124552011-07-16 01:37:101368 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:371369 AutocompleteMatch match;
[email protected]51abb7b2014-02-09 23:00:081370 classifier->Classify(i->term, false, false,
1371 input_.current_page_classification(), &match, NULL);
[email protected]2905f742011-10-13 03:51:581372 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:461373 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:371374 }
[email protected]51124552011-07-16 01:37:101375
[email protected]78e5e432013-08-03 02:10:101376 int relevance = CalculateRelevanceForHistory(
1377 i->time, is_keyword, !prevent_inline_autocomplete,
1378 prevent_search_history_inlining);
[email protected]2c03c06b2013-12-11 20:45:021379 scored_results.push_back(SuggestResult(
1380 i->term, AutocompleteMatchType::SEARCH_HISTORY, i->term,
1381 base::string16(), std::string(), std::string(), is_keyword, relevance,
[email protected]ee6110b2014-01-09 22:26:311382 false, false, input_text));
[email protected]257ab712009-04-14 17:16:241383 }
[email protected]51124552011-07-16 01:37:101384
1385 // History returns results sorted for us. However, we may have docked some
1386 // results' scores, so things are no longer in order. Do a stable sort to get
1387 // things back in order without otherwise disturbing results with equal
1388 // scores, then force the scores to be unique, so that the order in which
1389 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081390 std::stable_sort(scored_results.begin(), scored_results.end(),
1391 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101392 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081393 for (SuggestResults::iterator i(scored_results.begin());
1394 i != scored_results.end(); ++i) {
1395 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1396 i->set_relevance(last_relevance - 1);
1397 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101398 }
1399
[email protected]55ce8f12012-05-09 04:44:081400 return scored_results;
[email protected]257ab712009-04-14 17:16:241401}
1402
[email protected]55ce8f12012-05-09 04:44:081403void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
[email protected]987fad782013-08-28 06:23:181404 const std::string& metadata,
[email protected]55ce8f12012-05-09 04:44:081405 MatchMap* map) {
[email protected]55ce8f12012-05-09 04:44:081406 for (size_t i = 0; i < results.size(); ++i) {
[email protected]188b50c2013-03-28 07:19:421407 const bool is_keyword = results[i].from_keyword_provider();
[email protected]0085863a2013-12-06 21:19:031408 const base::string16& input = is_keyword ? keyword_input_.text()
1409 : input_.text();
[email protected]2c03c06b2013-12-11 20:45:021410 AddMatchToMap(results[i], input, metadata, i, map);
[email protected]257ab712009-04-14 17:16:241411 }
initial.commit09911bf2008-07-26 23:55:291412}
1413
[email protected]d30268a2013-06-25 22:31:071414int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561415 // Use the suggested verbatim relevance score if it is non-negative (valid),
1416 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281417 // and if it won't suppress verbatim, leaving no default provider matches.
1418 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561419 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281420 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561421 // Check for results on each verbatim calculation, as results from older
1422 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231423 bool use_server_relevance =
1424 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281425 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231426 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241427 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231428 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071429 if (relevance_from_server)
1430 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231431 return use_server_relevance ?
1432 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521433}
[email protected]d1f0a7f2012-06-05 10:26:421434
[email protected]382a0642012-06-06 06:13:521435int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471436 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361437 return 250;
[email protected]dab8d52d2013-03-05 07:35:281438 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1439}
[email protected]52d08b12009-10-19 18:42:361440
[email protected]dab8d52d2013-03-05 07:35:281441int SearchProvider::
1442 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291443 switch (input_.type()) {
1444 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361445 case AutocompleteInput::QUERY:
1446 case AutocompleteInput::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131447 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291448
initial.commit09911bf2008-07-26 23:55:291449 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361450 return 850;
initial.commit09911bf2008-07-26 23:55:291451
1452 default:
1453 NOTREACHED();
1454 return 0;
1455 }
1456}
1457
[email protected]d30268a2013-06-25 22:31:071458int SearchProvider::GetKeywordVerbatimRelevance(
1459 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281460 // Use the suggested verbatim relevance score if it is non-negative (valid),
1461 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1462 // and if it won't suppress verbatim, leaving no keyword provider matches.
1463 // Otherwise, if the keyword provider returned no matches and was still able
1464 // to suppress verbatim, the user would have no search/nav matches and may be
1465 // left unable to search using their keyword provider from the omnibox.
1466 // Check for results on each verbatim calculation, as results from older
1467 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231468 bool use_server_relevance =
1469 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281470 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231471 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241472 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231473 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071474 if (relevance_from_server)
1475 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231476 return use_server_relevance ?
1477 keyword_results_.verbatim_relevance :
1478 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1479 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451480}
1481
[email protected]51124552011-07-16 01:37:101482int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231483 const base::Time& time,
[email protected]51124552011-07-16 01:37:101484 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101485 bool use_aggressive_method,
1486 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181487 // The relevance of past searches falls off over time. There are two distinct
1488 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101489 // provider that we want to score aggressively), the score is in the range
1490 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161491 // it's in the range 1200-1299). If the second equation is used the
1492 // relevance of a search 15 minutes ago is discounted 50 points, while the
1493 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231494 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421495 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101496 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181497 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101498 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181499 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161500 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101501 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161502 max_score = 1299;
1503 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181504 std::pow(elapsed_time / autocomplete_time, 2.5));
1505 }
1506 elapsed_time -= autocomplete_time;
1507 }
1508
[email protected]c3a4bd992010-08-18 20:25:011509 const int score_discount =
1510 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291511
[email protected]6c85aa02009-02-27 12:08:091512 // Don't let scores go below 0. Negative relevance scores are meaningful in
1513 // a different way.
initial.commit09911bf2008-07-26 23:55:291514 int base_score;
[email protected]51124552011-07-16 01:37:101515 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361516 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101517 else
1518 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291519 return std::max(0, base_score - score_discount);
1520}
1521
[email protected]866f02e2013-12-10 17:12:051522void SearchProvider::AddMatchToMap(const SuggestResult& result,
1523 const base::string16& input_text,
[email protected]987fad782013-08-28 06:23:181524 const std::string& metadata,
[email protected]621ade062013-10-28 06:27:431525 int accepted_suggestion,
initial.commit09911bf2008-07-26 23:55:291526 MatchMap* map) {
[email protected]553c7af2014-02-06 17:58:581527 InstantService* instant_service =
1528 InstantServiceFactory::GetForProfile(profile_);
1529 // Android and iOS have no InstantService.
1530 const int omnibox_start_margin = instant_service ?
1531 instant_service->omnibox_start_margin() : chrome::kDisableStartMargin;
[email protected]c4a9d4c2013-08-10 07:06:271532
[email protected]866f02e2013-12-10 17:12:051533 const TemplateURL* template_url = result.from_keyword_provider() ?
[email protected]bba9e632013-06-28 22:52:191534 providers_.GetKeywordProviderURL() : providers_.GetDefaultProviderURL();
[email protected]621ade062013-10-28 06:27:431535 AutocompleteMatch match = CreateSearchSuggestion(
[email protected]575b2122014-01-03 20:35:331536 this, input_, input_text, result, template_url, accepted_suggestion,
1537 omnibox_start_margin,
[email protected]866f02e2013-12-10 17:12:051538 !result.from_keyword_provider() || providers_.default_provider().empty());
[email protected]cb86ee6f2013-04-28 16:58:151539 if (!match.destination_url.is_valid())
[email protected]85b8d6f2012-05-08 20:53:471540 return;
[email protected]a048de8a2013-10-02 18:30:061541 match.search_terms_args->bookmark_bar_pinned =
1542 profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
[email protected]d30268a2013-06-25 22:31:071543 match.RecordAdditionalInfo(kRelevanceFromServerKey,
[email protected]866f02e2013-12-10 17:12:051544 result.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181545 match.RecordAdditionalInfo(kShouldPrefetchKey,
[email protected]866f02e2013-12-10 17:12:051546 result.should_prefetch() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181547
[email protected]866f02e2013-12-10 17:12:051548 if (!result.deletion_url().empty()) {
1549 GURL url(match.destination_url.GetOrigin().Resolve(result.deletion_url()));
[email protected]f8c43e82013-12-06 12:46:231550 if (url.is_valid()) {
1551 match.RecordAdditionalInfo(kDeletionUrlKey, url.spec());
1552 match.deletable = true;
1553 }
[email protected]7267ff82013-12-03 17:20:301554 }
1555
[email protected]987fad782013-08-28 06:23:181556 // Metadata is needed only for prefetching queries.
[email protected]866f02e2013-12-10 17:12:051557 if (result.should_prefetch())
[email protected]987fad782013-08-28 06:23:181558 match.RecordAdditionalInfo(kSuggestMetadataKey, metadata);
[email protected]85b8d6f2012-05-08 20:53:471559
initial.commit09911bf2008-07-26 23:55:291560 // Try to add |match| to |map|. If a match for |query_string| is already in
1561 // |map|, replace it if |match| is more relevant.
1562 // NOTE: Keep this ToLower() call in sync with url_database.cc.
[email protected]621ade062013-10-28 06:27:431563 MatchKey match_key(
[email protected]866f02e2013-12-10 17:12:051564 std::make_pair(base::i18n::ToLower(result.suggestion()),
[email protected]621ade062013-10-28 06:27:431565 match.search_terms_args->suggest_query_params));
[email protected]bc8bb0cd2013-06-24 21:50:231566 const std::pair<MatchMap::iterator, bool> i(
[email protected]621ade062013-10-28 06:27:431567 map->insert(std::make_pair(match_key, match)));
[email protected]987fad782013-08-28 06:23:181568
[email protected]866f02e2013-12-10 17:12:051569 bool should_prefetch = result.should_prefetch();
[email protected]987fad782013-08-28 06:23:181570 if (!i.second) {
1571 // NOTE: We purposefully do a direct relevance comparison here instead of
1572 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items
1573 // added first" rather than "items alphabetically first" when the scores are
1574 // equal. The only case this matters is when a user has results with the
1575 // same score that differ only by capitalization; because the history system
1576 // returns results sorted by recency, this means we'll pick the most
1577 // recent such result even if the precision of our relevance score is too
1578 // low to distinguish the two.
1579 if (match.relevance > i.first->second.relevance) {
1580 i.first->second = match;
1581 } else if (match.keyword == i.first->second.keyword) {
1582 // Old and new matches are from the same search provider. It is okay to
1583 // record one match's prefetch data onto a different match (for the same
1584 // query string) for the following reasons:
1585 // 1. Because the suggest server only sends down a query string from which
1586 // we construct a URL, rather than sending a full URL, and because we
1587 // construct URLs from query strings in the same way every time, the URLs
1588 // for the two matches will be the same. Therefore, we won't end up
1589 // prefetching something the server didn't intend.
1590 // 2. Presumably the server sets the prefetch bit on a match it things is
1591 // sufficiently relevant that the user is likely to choose it. Surely
1592 // setting the prefetch bit on a match of even higher relevance won't
1593 // violate this assumption.
1594 should_prefetch |= ShouldPrefetch(i.first->second);
1595 i.first->second.RecordAdditionalInfo(kShouldPrefetchKey,
1596 should_prefetch ? kTrue : kFalse);
1597 if (should_prefetch)
1598 i.first->second.RecordAdditionalInfo(kSuggestMetadataKey, metadata);
1599 }
1600 }
initial.commit09911bf2008-07-26 23:55:291601}
1602
1603AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421604 const NavigationResult& navigation) {
[email protected]0085863a2013-12-06 21:19:031605 const base::string16& input = navigation.from_keyword_provider() ?
[email protected]188b50c2013-03-28 07:19:421606 keyword_input_.text() : input_.text();
[email protected]55ce8f12012-05-09 04:44:081607 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]b7f64d742013-05-21 04:04:041608 AutocompleteMatchType::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081609 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551610
[email protected]23db6492014-01-16 02:35:301611 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551612 // without trimming the scheme, so we can find matches at the beginning of the
1613 // scheme.
[email protected]371dab12012-06-01 03:23:551614 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301615 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551616 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301617 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351618 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1619 (!prefix || (match_start != 0));
[email protected]23db6492014-01-16 02:35:301620 const net::FormatUrlTypes format_types =
1621 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551622
[email protected]371dab12012-06-01 03:23:551623 const std::string languages(
1624 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
[email protected]23db6492014-01-16 02:35:301625 size_t inline_autocomplete_offset = (prefix == NULL) ?
1626 base::string16::npos : (match_start + input.length());
[email protected]371dab12012-06-01 03:23:551627 match.fill_into_edit +=
1628 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1629 net::FormatUrl(navigation.url(), languages, format_types,
1630 net::UnescapeRule::SPACES, NULL, NULL,
1631 &inline_autocomplete_offset));
[email protected]14119032013-11-07 08:14:261632 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1633 // Otherwise, user edits to a suggestion would show non-Search results.
1634 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581635 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031636 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261637 ++inline_autocomplete_offset;
1638 }
[email protected]518024c2013-07-19 23:40:251639 if (!input_.prevent_inline_autocomplete() &&
[email protected]0085863a2013-12-06 21:19:031640 (inline_autocomplete_offset != base::string16::npos)) {
[email protected]518024c2013-07-19 23:40:251641 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
[email protected]1c1e7842013-11-22 16:28:161642 // A navsuggestion can only be the default match when there is no
1643 // keyword provider active, lest it appear first and break the user
1644 // out of keyword mode.
1645 match.allowed_to_be_default_match =
1646 (providers_.GetKeywordProviderURL() == NULL);
[email protected]518024c2013-07-19 23:40:251647 match.inline_autocompletion =
1648 match.fill_into_edit.substr(inline_autocomplete_offset);
1649 }
[email protected]371dab12012-06-01 03:23:551650
[email protected]23db6492014-01-16 02:35:301651 match.contents = navigation.match_contents();
1652 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081653 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551654 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1655 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071656
1657 match.RecordAdditionalInfo(
1658 kRelevanceFromServerKey,
1659 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181660 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071661
initial.commit09911bf2008-07-26 23:55:291662 return match;
1663}
[email protected]4ab4c7c2010-11-24 04:49:341664
[email protected]9dfb4d362013-04-05 02:15:121665void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
[email protected]d519d392013-03-27 09:24:461666 // First, determine the maximum score of any keyword query match (verbatim or
1667 // query suggestion).
[email protected]d30268a2013-06-25 22:31:071668 bool relevance_from_server;
1669 int max_query_relevance = GetKeywordVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:241670 if (!keyword_results_.suggest_results.empty()) {
[email protected]d30268a2013-06-25 22:31:071671 const SuggestResult& top_keyword = keyword_results_.suggest_results.front();
1672 const int suggest_relevance = top_keyword.relevance();
1673 if (suggest_relevance > max_query_relevance) {
1674 max_query_relevance = suggest_relevance;
1675 relevance_from_server = top_keyword.relevance_from_server();
1676 } else if (suggest_relevance == max_query_relevance) {
1677 relevance_from_server |= top_keyword.relevance_from_server();
1678 }
[email protected]d519d392013-03-27 09:24:461679 }
1680 // If no query is supposed to appear, then navigational matches cannot
[email protected]9dfb4d362013-04-05 02:15:121681 // be demoted past it. Get rid of suggested relevance scores for
1682 // navsuggestions and introduce the verbatim results again. The keyword
1683 // verbatim match will outscore the navsuggest matches.
1684 if (max_query_relevance == 0) {
[email protected]cc1526e2013-05-17 04:04:241685 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
1686 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
1687 keyword_results_.verbatim_relevance = -1;
1688 default_results_.verbatim_relevance = -1;
[email protected]9dfb4d362013-04-05 02:15:121689 return;
1690 }
[email protected]d519d392013-03-27 09:24:461691 // Now we know we can enforce the minimum score constraint even after
1692 // the navigation matches are demoted. Proceed to demote the navigation
1693 // matches to enforce the query-must-come-first constraint.
[email protected]d519d392013-03-27 09:24:461694 // Cap the relevance score of all results.
[email protected]cc1526e2013-05-17 04:04:241695 for (NavigationResults::iterator it =
1696 keyword_results_.navigation_results.begin();
1697 it != keyword_results_.navigation_results.end(); ++it) {
[email protected]9dfb4d362013-04-05 02:15:121698 if (it->relevance() < max_query_relevance)
1699 return;
1700 max_query_relevance = std::max(max_query_relevance - 1, 0);
1701 it->set_relevance(max_query_relevance);
[email protected]d30268a2013-06-25 22:31:071702 it->set_relevance_from_server(relevance_from_server);
[email protected]d519d392013-03-27 09:24:461703 }
[email protected]d519d392013-03-27 09:24:461704}
1705
[email protected]4ab4c7c2010-11-24 04:49:341706void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331707 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311708 // pending, and we're not waiting on Instant.
[email protected]e1290ee62013-06-26 18:31:151709 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
[email protected]4ab4c7c2010-11-24 04:49:341710}