blob: 173e6051159ab3538498adf6faf804722610b8c4 [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]a7b8e43d2013-03-18 18:52:4332#include "chrome/browser/search/search.h"
[email protected]9899a612012-08-21 23:50:0433#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
[email protected]8e5c89a2011-06-07 18:13:3334#include "chrome/browser/search_engines/template_url_service.h"
35#include "chrome/browser/search_engines/template_url_service_factory.h"
[email protected]c4a9d4c2013-08-10 07:06:2736#include "chrome/browser/ui/search/instant_controller.h"
[email protected]4f3b4462013-07-27 19:20:1837#include "chrome/common/net/url_fixer_upper.h"
initial.commit09911bf2008-07-26 23:55:2938#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0239#include "chrome/common/url_constants.h"
[email protected]7267ff82013-12-03 17:20:3040#include "content/public/browser/user_metrics.h"
[email protected]34ac8f32009-02-22 23:03:2741#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2942#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3443#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5544#include "net/base/net_util.h"
[email protected]bd3b4712012-12-18 17:01:3045#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2146#include "net/http/http_response_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5347#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2148#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1749#include "ui/base/l10n/l10n_util.h"
[email protected]761fa4702013-07-02 15:25:1550#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2951
[email protected]bc8bb0cd2013-06-24 21:50:2352
53// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3354
[email protected]51124552011-07-16 01:37:1055namespace {
56
[email protected]7706a522012-08-16 17:42:2557// We keep track in a histogram how many suggest requests we send, how
58// many suggest requests we invalidate (e.g., due to a user typing
59// another character), and how many replies we receive.
60// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
61// (excluding the end-of-list enum value)
62// We do not want values of existing enums to change or else it screws
63// up the statistics.
64enum SuggestRequestsHistogramValue {
65 REQUEST_SENT = 1,
66 REQUEST_INVALIDATED,
67 REPLY_RECEIVED,
68 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
69};
70
[email protected]90fe2bb2013-01-15 03:42:1371// The verbatim score for an input which is not an URL.
72const int kNonURLVerbatimRelevance = 1300;
73
[email protected]7706a522012-08-16 17:42:2574// Increments the appropriate value in the histogram by one.
75void LogOmniboxSuggestRequest(
76 SuggestRequestsHistogramValue request_value) {
77 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
78 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
79}
80
[email protected]0085863a2013-12-06 21:19:0381bool HasMultipleWords(const base::string16& text) {
[email protected]51124552011-07-16 01:37:1082 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
83 bool found_word = false;
84 if (i.Init()) {
85 while (i.Advance()) {
86 if (i.IsWord()) {
87 if (found_word)
88 return true;
89 found_word = true;
90 }
91 }
92 }
93 return false;
94}
95
[email protected]2c03c06b2013-12-11 20:45:0296AutocompleteMatchType::Type GetAutocompleteMatchType(const std::string& type) {
97 if (type == "ENTITY")
98 return AutocompleteMatchType::SEARCH_SUGGEST_ENTITY;
99 if (type == "INFINITE")
100 return AutocompleteMatchType::SEARCH_SUGGEST_INFINITE;
101 if (type == "PERSONALIZED")
102 return AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED;
103 if (type == "PROFILE")
104 return AutocompleteMatchType::SEARCH_SUGGEST_PROFILE;
105 return AutocompleteMatchType::SEARCH_SUGGEST;
[email protected]621ade062013-10-28 06:27:43106}
107
[email protected]d1f0a7f2012-06-05 10:26:42108} // namespace
[email protected]51124552011-07-16 01:37:10109
[email protected]033f3422012-03-13 21:24:18110
[email protected]7267ff82013-12-03 17:20:30111// SuggestionDeletionHandler -------------------------------------------------
112
113// This class handles making requests to the server in order to delete
114// personalized suggestions.
115class SuggestionDeletionHandler : public net::URLFetcherDelegate {
116 public:
117 typedef base::Callback<void(bool, SuggestionDeletionHandler*)>
118 DeletionCompletedCallback;
119
120 SuggestionDeletionHandler(
121 const std::string& deletion_url,
122 Profile* profile,
123 const DeletionCompletedCallback& callback);
124
125 virtual ~SuggestionDeletionHandler();
126
127 private:
128 // net::URLFetcherDelegate:
129 virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE;
130
131 scoped_ptr<net::URLFetcher> deletion_fetcher_;
132 DeletionCompletedCallback callback_;
133
134 DISALLOW_COPY_AND_ASSIGN(SuggestionDeletionHandler);
135};
136
137
138SuggestionDeletionHandler::SuggestionDeletionHandler(
139 const std::string& deletion_url,
140 Profile* profile,
141 const DeletionCompletedCallback& callback) : callback_(callback) {
142 GURL url(deletion_url);
143 DCHECK(url.is_valid());
144
145 deletion_fetcher_.reset(net::URLFetcher::Create(
146 SearchProvider::kDeletionURLFetcherID,
147 url,
148 net::URLFetcher::GET,
149 this));
150 deletion_fetcher_->SetRequestContext(profile->GetRequestContext());
151 deletion_fetcher_->Start();
152};
153
154SuggestionDeletionHandler::~SuggestionDeletionHandler() {
155};
156
157void SuggestionDeletionHandler::OnURLFetchComplete(
158 const net::URLFetcher* source) {
159 DCHECK(source == deletion_fetcher_.get());
160 callback_.Run(
161 source->GetStatus().is_success() && (source->GetResponseCode() == 200),
162 this);
163};
164
165
[email protected]3954c3a2012-04-10 20:17:55166// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:58167
[email protected]85b8d6f2012-05-08 20:53:47168SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
[email protected]02346202014-02-05 05:18:30169 : template_url_service_(template_url_service) {}
[email protected]85b8d6f2012-05-08 20:53:47170
171const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
172 return default_provider_.empty() ? NULL :
173 template_url_service_->GetTemplateURLForKeyword(default_provider_);
174}
175
176const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
177 return keyword_provider_.empty() ? NULL :
178 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24179}
180
[email protected]3954c3a2012-04-10 20:17:55181
[email protected]bc8bb0cd2013-06-24 21:50:23182// SearchProvider::CompareScoredResults ---------------------------------------
183
184class SearchProvider::CompareScoredResults {
185 public:
186 bool operator()(const Result& a, const Result& b) {
187 // Sort in descending relevance order.
188 return a.relevance() > b.relevance();
189 }
190};
191
192
[email protected]3954c3a2012-04-10 20:17:55193// SearchProvider -------------------------------------------------------------
194
195// static
196const int SearchProvider::kDefaultProviderURLFetcherID = 1;
[email protected]3954c3a2012-04-10 20:17:55197const int SearchProvider::kKeywordProviderURLFetcherID = 2;
[email protected]7267ff82013-12-03 17:20:30198const int SearchProvider::kDeletionURLFetcherID = 3;
[email protected]24dbf2302013-04-05 16:59:25199int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]3954c3a2012-04-10 20:17:55200
[email protected]bc8bb0cd2013-06-24 21:50:23201SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
202 Profile* profile)
[email protected]02346202014-02-05 05:18:30203 : BaseSearchProvider(listener, profile, AutocompleteProvider::TYPE_SEARCH),
[email protected]bc8bb0cd2013-06-24 21:50:23204 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
[email protected]fd4e6a592014-02-07 02:41:38205 suggest_results_pending_(0) {
[email protected]bc8bb0cd2013-06-24 21:50:23206}
207
[email protected]cb86ee6f2013-04-28 16:58:15208// static
[email protected]987fad782013-08-28 06:23:18209std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
210 return match.GetAdditionalInfo(kSuggestMetadataKey);
211}
212
[email protected]7267ff82013-12-03 17:20:30213void SearchProvider::DeleteMatch(const AutocompleteMatch& match) {
[email protected]7267ff82013-12-03 17:20:30214 DCHECK(match.deletable);
215
216 deletion_handlers_.push_back(new SuggestionDeletionHandler(
217 match.GetAdditionalInfo(SearchProvider::kDeletionUrlKey),
218 profile_,
219 base::Bind(&SearchProvider::OnDeletionComplete, base::Unretained(this))));
220
[email protected]fba587fc2013-12-16 15:51:24221 HistoryService* const history_service =
222 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
223 TemplateURL* template_url = match.GetTemplateURL(profile_, false);
224 // This may be NULL if the template corresponding to the keyword has been
225 // deleted or there is no keyword set.
226 if (template_url != NULL) {
227 history_service->DeleteMatchingURLsForKeyword(template_url->id(),
228 match.contents);
229 }
230
[email protected]7267ff82013-12-03 17:20:30231 // Immediately update the list of matches to show the match was deleted,
232 // regardless of whether the server request actually succeeds.
233 DeleteMatchFromMatches(match);
234}
235
[email protected]bc8bb0cd2013-06-24 21:50:23236void SearchProvider::ResetSession() {
237 field_trial_triggered_in_session_ = false;
[email protected]4ab4c7c2010-11-24 04:49:34238}
239
[email protected]bc8bb0cd2013-06-24 21:50:23240SearchProvider::~SearchProvider() {
241}
242
243// static
[email protected]0085863a2013-12-06 21:19:03244void SearchProvider::RemoveStaleResults(const base::string16& input,
[email protected]bc8bb0cd2013-06-24 21:50:23245 int verbatim_relevance,
246 SuggestResults* suggest_results,
247 NavigationResults* navigation_results) {
248 DCHECK_GE(verbatim_relevance, 0);
249 // Keep pointers to the head of (the highest scoring elements of)
250 // |suggest_results| and |navigation_results|. Iterate down the lists
251 // removing non-inlineable results in order of decreasing relevance
252 // scores. Stop when the highest scoring element among those remaining
253 // is inlineable or the element is less than |verbatim_relevance|.
254 // This allows non-inlineable lower-scoring results to remain
255 // because (i) they are guaranteed to not be inlined and (ii)
256 // letting them remain reduces visual jank. For instance, as the
257 // user types the mis-spelled query "fpobar" (for foobar), the
258 // suggestion "foobar" will be suggested on every keystroke. If the
259 // SearchProvider always removes all non-inlineable results, the user will
260 // see visual jitter/jank as the result disappears and re-appears moments
261 // later as the suggest server returns results.
262 SuggestResults::iterator sug_it = suggest_results->begin();
263 NavigationResults::iterator nav_it = navigation_results->begin();
264 while ((sug_it != suggest_results->end()) ||
265 (nav_it != navigation_results->end())) {
266 const int sug_rel =
267 (sug_it != suggest_results->end()) ? sug_it->relevance() : -1;
268 const int nav_rel =
269 (nav_it != navigation_results->end()) ? nav_it->relevance() : -1;
270 if (std::max(sug_rel, nav_rel) < verbatim_relevance)
271 break;
272 if (sug_rel > nav_rel) {
273 // The current top result is a search suggestion.
274 if (sug_it->IsInlineable(input))
275 break;
276 sug_it = suggest_results->erase(sug_it);
277 } else if (sug_rel == nav_rel) {
278 // Have both results and they're tied.
279 const bool sug_inlineable = sug_it->IsInlineable(input);
280 const bool nav_inlineable = nav_it->IsInlineable(input);
281 if (!sug_inlineable)
282 sug_it = suggest_results->erase(sug_it);
283 if (!nav_inlineable)
284 nav_it = navigation_results->erase(nav_it);
285 if (sug_inlineable || nav_inlineable)
286 break;
287 } else {
288 // The current top result is a navigational suggestion.
289 if (nav_it->IsInlineable(input))
290 break;
291 nav_it = navigation_results->erase(nav_it);
292 }
293 }
294}
295
[email protected]ee6110b2014-01-09 22:26:31296void SearchProvider::UpdateMatchContentsClass(const base::string16& input_text,
[email protected]23db6492014-01-16 02:35:30297 Results* results) {
298 for (SuggestResults::iterator sug_it = results->suggest_results.begin();
299 sug_it != results->suggest_results.end(); ++sug_it) {
[email protected]ee6110b2014-01-09 22:26:31300 sug_it->ClassifyMatchContents(false, input_text);
301 }
[email protected]23db6492014-01-16 02:35:30302 const std::string languages(
303 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
304 for (NavigationResults::iterator nav_it = results->navigation_results.begin();
305 nav_it != results->navigation_results.end(); ++nav_it) {
306 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
307 }
[email protected]ee6110b2014-01-09 22:26:31308}
309
310// static
[email protected]bc8bb0cd2013-06-24 21:50:23311int SearchProvider::CalculateRelevanceForKeywordVerbatim(
312 AutocompleteInput::Type type,
313 bool prefer_keyword) {
314 // This function is responsible for scoring verbatim query matches
315 // for non-extension keywords. KeywordProvider::CalculateRelevance()
316 // scores verbatim query matches for extension keywords, as well as
317 // for keyword matches (i.e., suggestions of a keyword itself, not a
318 // suggestion of a query on a keyword search engine). These two
319 // functions are currently in sync, but there's no reason we
320 // couldn't decide in the future to score verbatim matches
321 // differently for extension and non-extension keywords. If you
322 // make such a change, however, you should update this comment to
323 // describe it, so it's clear why the functions diverge.
324 if (prefer_keyword)
325 return 1500;
326 return (type == AutocompleteInput::QUERY) ? 1450 : 1100;
327}
328
initial.commit09911bf2008-07-26 23:55:29329void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27330 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55331 // Do our best to load the model as early as possible. This will reduce
332 // odds of having the model not ready when really needed (a non-empty input).
333 TemplateURLService* model = providers_.template_url_service();
334 DCHECK(model);
335 model->Load();
336
initial.commit09911bf2008-07-26 23:55:29337 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57338 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29339
[email protected]6c85aa02009-02-27 12:08:09340 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29341 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]9950e5d52014-02-25 23:34:19342 Stop(true);
initial.commit09911bf2008-07-26 23:55:29343 return;
344 }
345
[email protected]14710852013-02-05 23:45:41346 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24347 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41348 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
349 &keyword_input_);
350 if (keyword_provider == NULL)
351 keyword_input_.Clear();
352 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24353 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24354
[email protected]85b8d6f2012-05-08 20:53:47355 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07356 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24357 default_provider = NULL;
358
359 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18360 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24361
362 if (!default_provider && !keyword_provider) {
363 // No valid providers.
[email protected]9950e5d52014-02-25 23:34:19364 Stop(true);
initial.commit09911bf2008-07-26 23:55:29365 return;
366 }
367
368 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24369 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03370 base::string16 default_provider_keyword(default_provider ?
371 default_provider->keyword() : base::string16());
372 base::string16 keyword_provider_keyword(keyword_provider ?
373 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32374 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47375 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29376 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15377 if (!done_)
[email protected]e29249dc52012-07-19 17:33:50378 Stop(false);
[email protected]257ab712009-04-14 17:16:24379 }
initial.commit09911bf2008-07-26 23:55:29380
[email protected]85b8d6f2012-05-08 20:53:47381 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29382
383 if (input.text().empty()) {
384 // User typed "?" alone. Give them a placeholder result indicating what
385 // this syntax does.
[email protected]257ab712009-04-14 17:16:24386 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00387 AutocompleteMatch match;
388 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36389 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24390 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35391 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47392 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36393 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24394 matches_.push_back(match);
395 }
[email protected]9950e5d52014-02-25 23:34:19396 Stop(true);
initial.commit09911bf2008-07-26 23:55:29397 return;
398 }
399
400 input_ = input;
401
[email protected]e1290ee62013-06-26 18:31:15402 DoHistoryQuery(minimal_changes);
403 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42404 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29405}
406
[email protected]10c2d692012-05-11 05:32:23407void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29408 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24409 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25410 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15411 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06412
[email protected]d7ad4772012-06-01 03:12:54413 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]f2916ea2013-01-26 02:20:14414 // Ensure the request succeeded and that the provider used is still available.
415 // A verbatim match cannot be generated without this provider, causing errors.
[email protected]013e9a02012-05-18 20:27:10416 const bool request_succeeded =
[email protected]bc8bb0cd2013-06-24 21:50:23417 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
418 (is_keyword ?
419 providers_.GetKeywordProviderURL() :
420 providers_.GetDefaultProviderURL());
[email protected]a0ad93ea2012-05-07 22:11:53421
422 // Record response time for suggest requests sent to Google. We care
423 // only about the common case: the Google default provider used in
424 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47425 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08426 if (!is_keyword && default_url &&
[email protected]628392f2013-08-16 00:34:45427 (TemplateURLPrepopulateData::GetEngineType(*default_url) ==
[email protected]9899a612012-08-21 23:50:04428 SEARCH_ENGINE_GOOGLE)) {
[email protected]bc8bb0cd2013-06-24 21:50:23429 const base::TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10430 base::TimeTicks::Now() - time_suggest_request_sent_;
431 if (request_succeeded) {
432 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
433 elapsed_time);
434 } else {
435 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
436 elapsed_time);
437 }
[email protected]b4cebf82008-12-29 19:59:08438 }
439
[email protected]d7ad4772012-06-01 03:12:54440 bool results_updated = false;
441 if (request_succeeded) {
[email protected]ed9b1802013-10-31 04:09:48442 const net::HttpResponseHeaders* const response_headers =
443 source->GetResponseHeaders();
444 std::string json_data;
445 source->GetResponseAsString(&json_data);
[email protected]7267ff82013-12-03 17:20:30446
[email protected]ed9b1802013-10-31 04:09:48447 // JSON is supposed to be UTF-8, but some suggest service providers send
448 // JSON files in non-UTF-8 encodings. The actual encoding is usually
449 // specified in the Content-Type header field.
450 if (response_headers) {
451 std::string charset;
452 if (response_headers->GetCharset(&charset)) {
[email protected]0085863a2013-12-06 21:19:03453 base::string16 data_16;
[email protected]ed9b1802013-10-31 04:09:48454 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
455 if (base::CodepageToUTF16(json_data, charset.c_str(),
456 base::OnStringConversionError::FAIL,
457 &data_16))
[email protected]670d3232013-12-24 17:58:58458 json_data = base::UTF16ToUTF8(data_16);
[email protected]ed9b1802013-10-31 04:09:48459 }
460 }
461
[email protected]5bcdd99d2013-12-23 18:28:30462 scoped_ptr<base::Value> data(DeserializeJsonData(json_data));
[email protected]2e8c6012013-12-03 12:00:01463 results_updated = data.get() && ParseSuggestResults(data.get(), is_keyword);
[email protected]d7ad4772012-06-01 03:12:54464 }
465
[email protected]344946a12012-12-20 12:03:42466 UpdateMatches();
[email protected]d7ad4772012-06-01 03:12:54467 if (done_ || results_updated)
468 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29469}
470
[email protected]9487b392014-02-14 02:48:18471const TemplateURL* SearchProvider::GetTemplateURL(
472 const SuggestResult& result) const {
473 return result.from_keyword_provider() ? providers_.GetKeywordProviderURL()
474 : providers_.GetDefaultProviderURL();
475}
476
477const AutocompleteInput SearchProvider::GetInput(
478 const SuggestResult& result) const {
479 return result.from_keyword_provider() ? keyword_input_ : input_;
480}
481
482bool SearchProvider::ShouldAppendExtraParams(
483 const SuggestResult& result) const {
484 return !result.from_keyword_provider() ||
485 providers_.default_provider().empty();
486}
487
[email protected]ef6866f2014-02-18 08:26:34488void SearchProvider::StopSuggest() {
489 // Increment the appropriate field in the histogram by the number of
490 // pending requests that were invalidated.
491 for (int i = 0; i < suggest_results_pending_; ++i)
492 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
493 suggest_results_pending_ = 0;
494 timer_.Stop();
495 // Stop any in-progress URL fetches.
496 keyword_fetcher_.reset();
497 default_fetcher_.reset();
498}
499
500void SearchProvider::ClearAllResults() {
501 keyword_results_.Clear();
502 default_results_.Clear();
503}
504
[email protected]7267ff82013-12-03 17:20:30505void SearchProvider::OnDeletionComplete(bool success,
506 SuggestionDeletionHandler* handler) {
507 RecordDeletionResult(success);
508 SuggestionDeletionHandlers::iterator it = std::find(
509 deletion_handlers_.begin(), deletion_handlers_.end(), handler);
510 DCHECK(it != deletion_handlers_.end());
511 deletion_handlers_.erase(it);
512}
513
514
515void SearchProvider::RecordDeletionResult(bool success) {
516 if (success) {
517 content::RecordAction(
[email protected]e6e30ac2014-01-13 21:24:39518 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
[email protected]7267ff82013-12-03 17:20:30519 } else {
520 content::RecordAction(
[email protected]e6e30ac2014-01-13 21:24:39521 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
[email protected]7267ff82013-12-03 17:20:30522 }
523}
524
525void SearchProvider::DeleteMatchFromMatches(const AutocompleteMatch& match) {
526 for (ACMatches::iterator i(matches_.begin()); i != matches_.end(); ++i) {
527 // Find the desired match to delete by checking the type and contents.
528 // We can't check the destination URL, because the autocomplete controller
529 // may have reformulated that. Not that while checking for matching
530 // contents works for personalized suggestions, if more match types gain
531 // deletion support, this algorithm may need to be re-examined.
532 if (i->contents == match.contents && i->type == match.type) {
533 matches_.erase(i);
534 break;
535 }
536 }
537 listener_->OnProviderUpdate(true);
538}
539
[email protected]bc8bb0cd2013-06-24 21:50:23540void SearchProvider::Run() {
541 // Start a new request with the current input.
542 suggest_results_pending_ = 0;
543 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05544
[email protected]bc8bb0cd2013-06-24 21:50:23545 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
546 providers_.GetDefaultProviderURL(), input_));
547 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
548 providers_.GetKeywordProviderURL(), keyword_input_));
549
550 // Both the above can fail if the providers have been modified or deleted
551 // since the query began.
552 if (suggest_results_pending_ == 0) {
553 UpdateDone();
554 // We only need to update the listener if we're actually done.
555 if (done_)
556 listener_->OnProviderUpdate(false);
557 }
[email protected]601858c02010-09-01 17:08:20558}
559
[email protected]8d457132010-11-04 18:13:40560void SearchProvider::DoHistoryQuery(bool minimal_changes) {
561 // The history query results are synchronous, so if minimal_changes is true,
562 // we still have the last results and don't need to do anything.
563 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29564 return;
565
[email protected]31afdf72013-09-26 04:29:36566 base::TimeTicks do_history_query_start_time(base::TimeTicks::Now());
567
[email protected]8d457132010-11-04 18:13:40568 keyword_history_results_.clear();
569 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29570
[email protected]78e5e432013-08-03 02:10:10571 if (OmniboxFieldTrial::SearchHistoryDisable(
572 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16573 return;
574
[email protected]31afdf72013-09-26 04:29:36575 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]8d457132010-11-04 18:13:40576 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10577 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]31afdf72013-09-26 04:29:36578 base::TimeTicks now(base::TimeTicks::Now());
579 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.GetHistoryServiceTime",
580 now - start_time);
581 start_time = now;
[email protected]8d457132010-11-04 18:13:40582 history::URLDatabase* url_db = history_service ?
583 history_service->InMemoryDatabase() : NULL;
[email protected]31afdf72013-09-26 04:29:36584 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.InMemoryDatabaseTime",
585 base::TimeTicks::Now() - start_time);
[email protected]8d457132010-11-04 18:13:40586 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29587 return;
588
[email protected]51124552011-07-16 01:37:10589 // Request history for both the keyword and default provider. We grab many
590 // more matches than we'll ultimately clamp to so that if there are several
591 // recent multi-word matches who scores are lowered (see
592 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
593 // matches. Note that this doesn't fix the problem entirely, but merely
594 // limits it to cases with a very large number of such multi-word matches; for
595 // now, this seems OK compared with the complexity of a real fix, which would
596 // require multiple searches and tracking of "single- vs. multi-word" in the
597 // database.
598 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47599 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
600 if (default_url) {
[email protected]31afdf72013-09-26 04:29:36601 start_time = base::TimeTicks::Now();
[email protected]85b8d6f2012-05-08 20:53:47602 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
603 num_matches, &default_history_results_);
[email protected]31afdf72013-09-26 04:29:36604 UMA_HISTOGRAM_TIMES(
605 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
606 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24607 }
[email protected]85b8d6f2012-05-08 20:53:47608 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
609 if (keyword_url) {
610 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41611 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55612 }
[email protected]31afdf72013-09-26 04:29:36613 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.DoHistoryQueryTime",
614 base::TimeTicks::Now() - do_history_query_start_time);
initial.commit09911bf2008-07-26 23:55:29615}
616
[email protected]6dc950f2012-07-16 19:49:08617void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34618 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29619 StopSuggest();
[email protected]71b46152013-05-03 16:39:20620 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29621 return;
622 }
623
624 // For the minimal_changes case, if we finished the previous query and still
625 // have its results, or are allowed to keep running it, just do that, rather
626 // than starting a new query.
627 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24628 (!default_results_.suggest_results.empty() ||
629 !default_results_.navigation_results.empty() ||
630 !keyword_results_.suggest_results.empty() ||
631 !keyword_results_.navigation_results.empty() ||
[email protected]ea3b9a502011-04-04 14:19:37632 (!done_ &&
633 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29634 return;
635
636 // We can't keep running any previous query, so halt it.
637 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42638
639 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20640 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29641
[email protected]ee6110b2014-01-09 22:26:31642 // Update the content classifications of remaining results so they look good
643 // against the current input.
[email protected]23db6492014-01-16 02:35:30644 UpdateMatchContentsClass(input_.text(), &default_results_);
645 if (!keyword_input_.text().empty())
646 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31647
initial.commit09911bf2008-07-26 23:55:29648 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37649 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29650 return;
651
[email protected]24dbf2302013-04-05 16:59:25652 // To avoid flooding the suggest server, don't send a query until at
653 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24654 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
[email protected]bc8bb0cd2013-06-24 21:50:23655 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
[email protected]515ffa942012-11-27 20:18:24656 base::TimeTicks now(base::TimeTicks::Now());
657 if (now >= next_suggest_time) {
658 Run();
659 return;
660 }
661 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29662}
663
[email protected]83c726482008-09-10 06:36:34664bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55665 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
666 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47667 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
668 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34669 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47670 ((!default_url || default_url->suggestions_url().empty()) &&
671 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34672 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
673 return false;
674
[email protected]cac59d32010-08-09 23:23:14675 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34676 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34677
[email protected]cac59d32010-08-09 23:23:14678 // FORCED_QUERY means the user is explicitly asking us to search for this, so
679 // we assume it isn't a URL and/or there isn't private data.
680 if (input_.type() == AutocompleteInput::FORCED_QUERY)
681 return true;
[email protected]83c726482008-09-10 06:36:34682
[email protected]f608ea102013-03-18 15:08:09683 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
684 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
685 // is both a waste of time and a disclosure of potentially private, local
686 // data. Other "schemes" may actually be usernames, and we don't want to send
687 // passwords. If the scheme is OK, we still need to check other cases below.
688 // If this is QUERY, then the presence of these schemes means the user
689 // explicitly typed one, and thus this is probably a URL that's being entered
690 // and happens to currently be invalid -- in which case we again want to run
691 // our checks below. Other QUERY cases are less likely to be URLs and thus we
692 // assume we're OK.
[email protected]e9a82042013-09-15 03:38:29693 if (!LowerCaseEqualsASCII(input_.scheme(), content::kHttpScheme) &&
[email protected]4654bfe2013-08-26 03:36:58694 !LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]72aa4c22013-12-01 15:09:35695 !LowerCaseEqualsASCII(input_.scheme(), content::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14696 return (input_.type() == AutocompleteInput::QUERY);
697
698 // Don't send URLs with usernames, queries or refs. Some of these are
699 // private, and the Suggest server is unlikely to have any useful results
700 // for any of them. Also don't send URLs with ports, as we may initially
701 // think that a username + password is a host + port (and we don't want to
702 // send usernames/passwords), and even if the port really is a port, the
703 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58704 // Note that we only block based on refs if the input is URL-typed, as search
705 // queries can legitimately have #s in them which the URL parser
706 // overaggressively categorizes as a url with a ref.
[email protected]cac59d32010-08-09 23:23:14707 const url_parse::Parsed& parts = input_.parts();
708 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58709 parts.query.is_nonempty() ||
710 (parts.ref.is_nonempty() && (input_.type() == AutocompleteInput::URL)))
[email protected]cac59d32010-08-09 23:23:14711 return false;
712
713 // Don't send anything for https except the hostname. Hostnames are OK
714 // because they are visible when the TCP connection is established, but the
715 // specific path may reveal private information.
[email protected]4654bfe2013-08-26 03:36:58716 if (LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36717 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14718 return false;
[email protected]83c726482008-09-10 06:36:34719
720 return true;
721}
722
[email protected]71b46152013-05-03 16:39:20723void SearchProvider::RemoveAllStaleResults() {
[email protected]dc735c02013-11-12 23:23:41724 // We only need to remove stale results (which ensures the top-scoring
725 // match is inlineable) if the user is not in reorder mode. In reorder
726 // mode, the autocomplete system will reorder results to make sure the
727 // top result is inlineable.
728 const bool omnibox_will_reorder_for_legal_default_match =
729 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
730 input_.current_page_classification());
[email protected]1e1550e2013-05-02 17:37:51731 // In theory it would be better to run an algorithm like that in
732 // RemoveStaleResults(...) below that uses all four results lists
733 // and both verbatim scores at once. However, that will be much
734 // more complicated for little obvious gain. For code simplicity
735 // and ease in reasoning about the invariants involved, this code
736 // removes stales results from the keyword provider and default
737 // provider independently.
[email protected]dc735c02013-11-12 23:23:41738 if (!omnibox_will_reorder_for_legal_default_match) {
739 RemoveStaleResults(input_.text(), GetVerbatimRelevance(NULL),
740 &default_results_.suggest_results,
741 &default_results_.navigation_results);
742 if (!keyword_input_.text().empty()) {
743 RemoveStaleResults(keyword_input_.text(),
744 GetKeywordVerbatimRelevance(NULL),
745 &keyword_results_.suggest_results,
746 &keyword_results_.navigation_results);
747 }
748 }
749 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51750 // User is either in keyword mode with a blank input or out of
751 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24752 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51753 }
[email protected]d1f0a7f2012-06-05 10:26:42754}
755
[email protected]d1f0a7f2012-06-05 10:26:42756void SearchProvider::ApplyCalculatedRelevance() {
[email protected]cc1526e2013-05-17 04:04:24757 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
758 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
759 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
760 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
[email protected]cc1526e2013-05-17 04:04:24761 default_results_.verbatim_relevance = -1;
762 keyword_results_.verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42763}
764
[email protected]188b50c2013-03-28 07:19:42765void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42766 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42767 SuggestResult& result = (*list)[i];
768 result.set_relevance(
769 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
770 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07771 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42772 }
773}
774
[email protected]188b50c2013-03-28 07:19:42775void SearchProvider::ApplyCalculatedNavigationRelevance(
776 NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42777 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42778 NavigationResult& result = (*list)[i];
779 result.set_relevance(
780 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
781 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07782 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42783 }
784}
785
[email protected]15fb2aa2012-05-22 22:52:59786net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12787 int id,
[email protected]9ff91722012-09-07 05:29:12788 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41789 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12790 if (!template_url || template_url->suggestions_url().empty())
791 return NULL;
792
793 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41794 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
795 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18796 search_term_args.page_classification = input.current_page_classification();
[email protected]9ff91722012-09-07 05:29:12797 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:16798 search_term_args));
[email protected]9ff91722012-09-07 05:29:12799 if (!suggest_url.is_valid())
800 return NULL;
[email protected]9b9fa672013-11-07 06:04:52801 // Send the current page URL if user setting and URL requirements are met and
802 // the user is in the field trial.
803 if (CanSendURL(current_page_url_, suggest_url, template_url,
804 input.current_page_classification(), profile_) &&
805 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
806 search_term_args.current_page_url = current_page_url_.spec();
807 // Create the suggest URL again with the current page URL.
808 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
809 search_term_args));
810 }
[email protected]9ff91722012-09-07 05:29:12811
812 suggest_results_pending_++;
813 LogOmniboxSuggestRequest(REQUEST_SENT);
814
815 net::URLFetcher* fetcher =
816 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12817 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34818 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30819 // Add Chrome experiment state to the request headers.
820 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:09821 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30822 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
823 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24824 fetcher->Start();
825 return fetcher;
826}
827
[email protected]5bcdd99d2013-12-23 18:28:30828bool SearchProvider::ParseSuggestResults(base::Value* root_val,
829 bool is_keyword) {
[email protected]0085863a2013-12-06 21:19:03830 base::string16 query;
[email protected]5bcdd99d2013-12-23 18:28:30831 base::ListValue* root_list = NULL;
832 base::ListValue* results_list = NULL;
[email protected]0085863a2013-12-06 21:19:03833 const base::string16& input_text =
[email protected]14710852013-02-05 23:45:41834 is_keyword ? keyword_input_.text() : input_.text();
[email protected]d7ad4772012-06-01 03:12:54835 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
[email protected]cc1526e2013-05-17 04:04:24836 (query != input_text) || !root_list->GetList(1, &results_list))
initial.commit09911bf2008-07-26 23:55:29837 return false;
838
[email protected]55ce8f12012-05-09 04:44:08839 // 3rd element: Description list.
[email protected]5bcdd99d2013-12-23 18:28:30840 base::ListValue* descriptions = NULL;
[email protected]d7ad4772012-06-01 03:12:54841 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:29842
[email protected]55ce8f12012-05-09 04:44:08843 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:29844
[email protected]d1f0a7f2012-06-05 10:26:42845 // Reset suggested relevance information from the default provider.
[email protected]cc1526e2013-05-17 04:04:24846 Results* results = is_keyword ? &keyword_results_ : &default_results_;
[email protected]cc1526e2013-05-17 04:04:24847 results->verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42848
[email protected]55ce8f12012-05-09 04:44:08849 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]5bcdd99d2013-12-23 18:28:30850 base::ListValue* types = NULL;
851 base::ListValue* relevances = NULL;
852 base::ListValue* suggestion_details = NULL;
853 base::DictionaryValue* extras = NULL;
[email protected]987fad782013-08-28 06:23:18854 int prefetch_index = -1;
[email protected]d1f0a7f2012-06-05 10:26:42855 if (root_list->GetDictionary(4, &extras)) {
856 extras->GetList("google:suggesttype", &types);
857
[email protected]eb8330d2013-06-15 00:55:08858 // Discard this list if its size does not match that of the suggestions.
859 if (extras->GetList("google:suggestrelevance", &relevances) &&
[email protected]621ade062013-10-28 06:27:43860 (relevances->GetSize() != results_list->GetSize()))
[email protected]eb8330d2013-06-15 00:55:08861 relevances = NULL;
862 extras->GetInteger("google:verbatimrelevance",
863 &results->verbatim_relevance);
[email protected]618d6e62012-12-16 05:55:57864
865 // Check if the active suggest field trial (if any) has triggered either
866 // for the default provider or keyword provider.
867 bool triggered = false;
868 extras->GetBoolean("google:fieldtrialtriggered", &triggered);
869 field_trial_triggered_ |= triggered;
870 field_trial_triggered_in_session_ |= triggered;
[email protected]987fad782013-08-28 06:23:18871
[email protected]5bcdd99d2013-12-23 18:28:30872 base::DictionaryValue* client_data = NULL;
[email protected]987fad782013-08-28 06:23:18873 if (extras->GetDictionary("google:clientdata", &client_data) && client_data)
874 client_data->GetInteger("phi", &prefetch_index);
875
[email protected]621ade062013-10-28 06:27:43876 if (extras->GetList("google:suggestdetail", &suggestion_details) &&
877 suggestion_details->GetSize() != results_list->GetSize())
878 suggestion_details = NULL;
879
[email protected]987fad782013-08-28 06:23:18880 // Store the metadata that came with the response in case we need to pass it
881 // along with the prefetch query to Instant.
882 JSONStringValueSerializer json_serializer(&results->metadata);
883 json_serializer.Serialize(*extras);
initial.commit09911bf2008-07-26 23:55:29884 }
885
[email protected]d1f0a7f2012-06-05 10:26:42886 // Clear the previous results now that new results are available.
[email protected]cc1526e2013-05-17 04:04:24887 results->suggest_results.clear();
888 results->navigation_results.clear();
[email protected]d1f0a7f2012-06-05 10:26:42889
[email protected]0085863a2013-12-06 21:19:03890 base::string16 suggestion;
[email protected]d1f0a7f2012-06-05 10:26:42891 std::string type;
892 int relevance = -1;
[email protected]3f381592013-11-05 20:43:51893 // Prohibit navsuggest in FORCED_QUERY mode. Users wants queries, not URLs.
894 const bool allow_navsuggest =
895 (is_keyword ? keyword_input_.type() : input_.type()) !=
896 AutocompleteInput::FORCED_QUERY;
[email protected]23db6492014-01-16 02:35:30897 const std::string languages(
898 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
[email protected]621ade062013-10-28 06:27:43899 for (size_t index = 0; results_list->GetString(index, &suggestion); ++index) {
[email protected]8e81f5092010-09-29 23:19:40900 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:08901 // they make no sense at all and can cause problems in our code.
[email protected]621ade062013-10-28 06:27:43902 if (suggestion.empty())
[email protected]8e81f5092010-09-29 23:19:40903 continue;
904
[email protected]d1f0a7f2012-06-05 10:26:42905 // Apply valid suggested relevance scores; discard invalid lists.
906 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
907 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:54908 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:42909 // Do not blindly trust the URL coming from the server to be valid.
[email protected]670d3232013-12-24 17:58:58910 GURL url(URLFixerUpper::FixupURL(
911 base::UTF16ToUTF8(suggestion), std::string()));
[email protected]3f381592013-11-05 20:43:51912 if (url.is_valid() && allow_navsuggest) {
[email protected]0085863a2013-12-06 21:19:03913 base::string16 title;
[email protected]d1f0a7f2012-06-05 10:26:42914 if (descriptions != NULL)
915 descriptions->GetString(index, &title);
[email protected]d30268a2013-06-25 22:31:07916 results->navigation_results.push_back(NavigationResult(
[email protected]23db6492014-01-16 02:35:30917 *this, url, title, is_keyword, relevance, true, input_text,
918 languages));
initial.commit09911bf2008-07-26 23:55:29919 }
920 } else {
[email protected]2c03c06b2013-12-11 20:45:02921 AutocompleteMatchType::Type match_type = GetAutocompleteMatchType(type);
[email protected]987fad782013-08-28 06:23:18922 bool should_prefetch = static_cast<int>(index) == prefetch_index;
[email protected]5bcdd99d2013-12-23 18:28:30923 base::DictionaryValue* suggestion_detail = NULL;
[email protected]0085863a2013-12-06 21:19:03924 base::string16 match_contents = suggestion;
[email protected]61f99082014-02-24 02:17:49925 base::string16 match_contents_prefix;
[email protected]0085863a2013-12-06 21:19:03926 base::string16 annotation;
[email protected]621ade062013-10-28 06:27:43927 std::string suggest_query_params;
[email protected]7267ff82013-12-03 17:20:30928 std::string deletion_url;
929
930 if (suggestion_details) {
931 suggestion_details->GetDictionary(index, &suggestion_detail);
932 if (suggestion_detail) {
933 suggestion_detail->GetString("du", &deletion_url);
[email protected]61f99082014-02-24 02:17:49934 suggestion_detail->GetString("t", &match_contents);
935 suggestion_detail->GetString("mp", &match_contents_prefix);
[email protected]ee6110b2014-01-09 22:26:31936 // Error correction for bad data from server.
937 if (match_contents.empty())
938 match_contents = suggestion;
[email protected]61f99082014-02-24 02:17:49939 suggestion_detail->GetString("a", &annotation);
940 suggestion_detail->GetString("q", &suggest_query_params);
[email protected]7267ff82013-12-03 17:20:30941 }
[email protected]621ade062013-10-28 06:27:43942 }
[email protected]7267ff82013-12-03 17:20:30943
[email protected]621ade062013-10-28 06:27:43944 // TODO(kochi): Improve calculator suggestion presentation.
945 results->suggest_results.push_back(SuggestResult(
[email protected]61f99082014-02-24 02:17:49946 suggestion, match_type, match_contents, match_contents_prefix,
947 annotation, suggest_query_params, deletion_url, is_keyword, relevance,
948 true, should_prefetch, input_text));
initial.commit09911bf2008-07-26 23:55:29949 }
950 }
951
[email protected]43126b7192013-11-14 18:10:34952 // Ignore suggested scores for non-keyword matches in keyword mode; if the
953 // server is allowed to score these, it could interfere with the user's
954 // ability to get good keyword results.
955 const bool abandon_suggested_scores =
956 !is_keyword && !providers_.keyword_provider().empty();
957 // Apply calculated relevance scores to suggestions if a valid list was
958 // not provided or we're abandoning suggested scores entirely.
959 if ((relevances == NULL) || abandon_suggested_scores) {
[email protected]cc1526e2013-05-17 04:04:24960 ApplyCalculatedSuggestRelevance(&results->suggest_results);
961 ApplyCalculatedNavigationRelevance(&results->navigation_results);
[email protected]43126b7192013-11-14 18:10:34962 // If abandoning scores entirely, also abandon the verbatim score.
963 if (abandon_suggested_scores)
964 results->verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42965 }
[email protected]43126b7192013-11-14 18:10:34966
[email protected]9dfb4d362013-04-05 02:15:12967 // Keep the result lists sorted.
968 const CompareScoredResults comparator = CompareScoredResults();
[email protected]cc1526e2013-05-17 04:04:24969 std::stable_sort(results->suggest_results.begin(),
970 results->suggest_results.end(),
[email protected]9dfb4d362013-04-05 02:15:12971 comparator);
[email protected]cc1526e2013-05-17 04:04:24972 std::stable_sort(results->navigation_results.begin(),
973 results->navigation_results.end(),
[email protected]9dfb4d362013-04-05 02:15:12974 comparator);
[email protected]d1f0a7f2012-06-05 10:26:42975 return true;
initial.commit09911bf2008-07-26 23:55:29976}
977
[email protected]344946a12012-12-20 12:03:42978void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29979 // Convert all the results to matches and add them to a map, so we can keep
980 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36981 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29982 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23983 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24984 int did_not_accept_keyword_suggestion =
985 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29986 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
987 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29988
[email protected]d30268a2013-06-25 22:31:07989 bool relevance_from_server;
990 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24991 int did_not_accept_default_suggestion =
992 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08993 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
994 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:42995 if (verbatim_relevance > 0) {
[email protected]2c03c06b2013-12-11 20:45:02996 SuggestResult verbatim(
997 input_.text(), AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]61f99082014-02-24 02:17:49998 input_.text(), base::string16(), base::string16(), std::string(),
999 std::string(), false, verbatim_relevance, relevance_from_server, false,
1000 input_.text());
[email protected]9487b392014-02-14 02:48:181001 AddMatchToMap(
1002 verbatim, std::string(), did_not_accept_default_suggestion, &map);
[email protected]d1f0a7f2012-06-05 10:26:421003 }
[email protected]5423e562013-02-07 03:58:451004 if (!keyword_input_.text().empty()) {
1005 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1006 // We only create the verbatim search query match for a keyword
1007 // if it's not an extension keyword. Extension keywords are handled
1008 // in KeywordProvider::Start(). (Extensions are complicated...)
1009 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
1010 // to the keyword verbatim search query. Do not create other matches
1011 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:251012 if (keyword_url &&
1013 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:071014 bool keyword_relevance_from_server;
1015 const int keyword_verbatim_relevance =
1016 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:281017 if (keyword_verbatim_relevance > 0) {
[email protected]2c03c06b2013-12-11 20:45:021018 SuggestResult verbatim(
1019 keyword_input_.text(), AutocompleteMatchType::SEARCH_OTHER_ENGINE,
[email protected]61f99082014-02-24 02:17:491020 keyword_input_.text(), base::string16(), base::string16(),
1021 std::string(), std::string(), true, keyword_verbatim_relevance,
[email protected]ee6110b2014-01-09 22:26:311022 keyword_relevance_from_server, false, keyword_input_.text());
[email protected]9487b392014-02-14 02:48:181023 AddMatchToMap(
1024 verbatim, std::string(), did_not_accept_keyword_suggestion, &map);
[email protected]dab8d52d2013-03-05 07:35:281025 }
[email protected]5423e562013-02-07 03:58:451026 }
1027 }
[email protected]257ab712009-04-14 17:16:241028 AddHistoryResultsToMap(keyword_history_results_, true,
1029 did_not_accept_keyword_suggestion, &map);
1030 AddHistoryResultsToMap(default_history_results_, false,
1031 did_not_accept_default_suggestion, &map);
1032
[email protected]d1cb6a822013-09-18 19:43:001033 AddSuggestResultsToMap(keyword_results_.suggest_results,
1034 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:181035 AddSuggestResultsToMap(default_results_.suggest_results,
1036 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:291037
[email protected]d30268a2013-06-25 22:31:071038 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:291039 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:071040 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:291041
[email protected]d30268a2013-06-25 22:31:071042 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
1043 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:291044
[email protected]d30268a2013-06-25 22:31:071045 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
1046 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
1047 // enabled and we have server-provided (and thus hopefully more accurate)
1048 // scores for some suggestions, we allow more of those, until we reach
1049 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
1050 // whole popup).
1051 //
1052 // We will always return any verbatim matches, no matter how we obtained their
1053 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
1054 // higher-scoring matches under the conditions above.
[email protected]31afdf72013-09-26 04:29:361055 UMA_HISTOGRAM_CUSTOM_COUNTS(
1056 "Omnibox.SearchProvider.NumMatchesToSort", matches.size(), 1, 50, 20);
[email protected]d30268a2013-06-25 22:31:071057 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
1058 matches_.clear();
[email protected]3723e6e2012-06-11 21:06:561059
[email protected]d30268a2013-06-25 22:31:071060 size_t num_suggestions = 0;
1061 for (ACMatches::const_iterator i(matches.begin());
1062 (i != matches.end()) &&
1063 (matches_.size() < AutocompleteResult::kMaxMatches);
1064 ++i) {
1065 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
1066 // verbatim result, so this condition basically means "if this match is a
1067 // suggestion of some sort".
1068 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
1069 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
1070 // If we've already hit the limit on non-server-scored suggestions, and
1071 // this isn't a server-scored suggestion we can add, skip it.
1072 if ((num_suggestions >= kMaxMatches) &&
1073 (!chrome::IsInstantExtendedAPIEnabled() ||
1074 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
1075 continue;
1076 }
1077
1078 ++num_suggestions;
1079 }
1080
1081 matches_.push_back(*i);
1082 }
[email protected]31afdf72013-09-26 04:29:361083 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
1084 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:421085}
1086
[email protected]0a8718b12013-11-13 18:41:311087ACMatches::const_iterator SearchProvider::FindTopMatch(
1088 bool autocomplete_result_will_reorder_for_default_match) const {
1089 if (!autocomplete_result_will_reorder_for_default_match)
1090 return matches_.begin();
1091 ACMatches::const_iterator it = matches_.begin();
1092 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
1093 ++it;
1094 return it;
[email protected]9dfb4d362013-04-05 02:15:121095}
1096
[email protected]0a8718b12013-11-13 18:41:311097bool SearchProvider::IsTopMatchNavigationInKeywordMode(
1098 bool autocomplete_result_will_reorder_for_default_match) const {
1099 ACMatches::const_iterator first_match =
1100 FindTopMatch(autocomplete_result_will_reorder_for_default_match);
1101 return !providers_.keyword_provider().empty() &&
1102 (first_match != matches_.end()) &&
1103 (first_match->type == AutocompleteMatchType::NAVSUGGEST);
1104}
1105
[email protected]1c1e7842013-11-22 16:28:161106bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const {
1107 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1108 // If the user is not in keyword mode, return true to say that this
1109 // constraint is not violated.
1110 if (keyword_url == NULL)
1111 return true;
1112 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
1113 ++it) {
1114 if ((it->keyword == keyword_url->keyword()) &&
1115 it->allowed_to_be_default_match)
1116 return true;
1117 }
1118 return false;
1119}
1120
[email protected]0a8718b12013-11-13 18:41:311121bool SearchProvider::IsTopMatchScoreTooLow(
1122 bool autocomplete_result_will_reorder_for_default_match) const {
1123 // In reorder mode, there's no such thing as a score that's too low.
1124 if (autocomplete_result_will_reorder_for_default_match)
1125 return false;
1126
[email protected]dab8d52d2013-03-05 07:35:281127 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
1128 // rather than CalculateRelevanceForVerbatim() because the latter returns
1129 // a very low score (250) if keyword mode is active. This is because
1130 // when keyword mode is active the user probably wants the keyword matches,
1131 // not matches from the default provider. Hence, we use the version of
1132 // the function that ignores whether keyword mode is active. This allows
1133 // SearchProvider to maintain its contract with the AutocompleteController
1134 // that it will always provide an inlineable match with a reasonable
1135 // score.
1136 return matches_.front().relevance <
1137 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
[email protected]344946a12012-12-20 12:03:421138}
1139
[email protected]0a8718b12013-11-13 18:41:311140bool SearchProvider::IsTopMatchSearchWithURLInput(
1141 bool autocomplete_result_will_reorder_for_default_match) const {
1142 ACMatches::const_iterator first_match =
1143 FindTopMatch(autocomplete_result_will_reorder_for_default_match);
1144 return (input_.type() == AutocompleteInput::URL) &&
1145 (first_match != matches_.end()) &&
1146 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
1147 (first_match->type != AutocompleteMatchType::NAVSUGGEST);
[email protected]344946a12012-12-20 12:03:421148}
1149
[email protected]45f89a92013-08-12 13:41:361150bool SearchProvider::HasValidDefaultMatch(
1151 bool autocomplete_result_will_reorder_for_default_match) const {
1152 // One of the SearchProvider matches may need to be the overall default. If
1153 // AutocompleteResult is allowed to reorder matches, this means we simply
1154 // need at least one match in the list to be |allowed_to_be_default_match|.
1155 // If no reordering is possible, however, then our first match needs to have
1156 // this flag.
1157 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
1158 ++it) {
1159 if (it->allowed_to_be_default_match)
1160 return true;
1161 if (!autocomplete_result_will_reorder_for_default_match)
1162 return false;
1163 }
1164 return false;
[email protected]344946a12012-12-20 12:03:421165}
1166
1167void SearchProvider::UpdateMatches() {
[email protected]31afdf72013-09-26 04:29:361168 base::TimeTicks update_matches_start_time(base::TimeTicks::Now());
[email protected]344946a12012-12-20 12:03:421169 ConvertResultsToAutocompleteMatches();
initial.commit09911bf2008-07-26 23:55:291170
[email protected]382a0642012-06-06 06:13:521171 // Check constraints that may be violated by suggested relevances.
[email protected]344946a12012-12-20 12:03:421172 if (!matches_.empty() &&
[email protected]bc8bb0cd2013-06-24 21:50:231173 (default_results_.HasServerProvidedScores() ||
1174 keyword_results_.HasServerProvidedScores())) {
[email protected]9dfb4d362013-04-05 02:15:121175 // These blocks attempt to repair undesirable behavior by suggested
[email protected]344946a12012-12-20 12:03:421176 // relevances with minimal impact, preserving other suggested relevances.
[email protected]0a8718b12013-11-13 18:41:311177
1178 // True if the omnibox will reorder matches as necessary to make the first
1179 // one something that is allowed to be the default match.
1180 const bool omnibox_will_reorder_for_legal_default_match =
1181 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
1182 input_.current_page_classification());
1183 if (IsTopMatchNavigationInKeywordMode(
1184 omnibox_will_reorder_for_legal_default_match)) {
[email protected]9dfb4d362013-04-05 02:15:121185 // Correct the suggested relevance scores if the top match is a
1186 // navigation in keyword mode, since inlining a navigation match
[email protected]1c1e7842013-11-22 16:28:161187 // would break the user out of keyword mode. This will only be
1188 // triggered in regular (non-reorder) mode; in reorder mode,
1189 // navigation matches are marked as not allowed to be the default
1190 // match and hence IsTopMatchNavigation() will always return false.
1191 DCHECK(!omnibox_will_reorder_for_legal_default_match);
[email protected]9dfb4d362013-04-05 02:15:121192 DemoteKeywordNavigationMatchesPastTopQuery();
1193 ConvertResultsToAutocompleteMatches();
[email protected]0a8718b12013-11-13 18:41:311194 DCHECK(!IsTopMatchNavigationInKeywordMode(
1195 omnibox_will_reorder_for_legal_default_match));
[email protected]9dfb4d362013-04-05 02:15:121196 }
[email protected]1c1e7842013-11-22 16:28:161197 if (!HasKeywordDefaultMatchInKeywordMode()) {
1198 // In keyword mode, disregard the keyword verbatim suggested relevance
1199 // if necessary so there at least one keyword match that's allowed to
1200 // be the default match.
1201 keyword_results_.verbatim_relevance = -1;
1202 ConvertResultsToAutocompleteMatches();
1203 }
[email protected]0a8718b12013-11-13 18:41:311204 if (IsTopMatchScoreTooLow(omnibox_will_reorder_for_legal_default_match)) {
[email protected]1beee342012-06-19 22:22:281205 // Disregard the suggested verbatim relevance if the top score is below
1206 // the usual verbatim value. For example, a BarProvider may rely on
[email protected]45f89a92013-08-12 13:41:361207 // SearchProvider's verbatim or inlineable matches for input "foo" (all
1208 // allowed to be default match) to always outrank its own lowly-ranked
[email protected]0a8718b12013-11-13 18:41:311209 // "bar" matches that shouldn't be the default match.
[email protected]cc1526e2013-05-17 04:04:241210 default_results_.verbatim_relevance = -1;
1211 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421212 ConvertResultsToAutocompleteMatches();
[email protected]e6acd002012-06-16 22:27:471213 }
[email protected]0a8718b12013-11-13 18:41:311214 if (IsTopMatchSearchWithURLInput(
1215 omnibox_will_reorder_for_legal_default_match)) {
[email protected]e6acd002012-06-16 22:27:471216 // Disregard the suggested search and verbatim relevances if the input
1217 // type is URL and the top match is a highly-ranked search suggestion.
1218 // For example, prevent a search for "foo.com" from outranking another
1219 // provider's navigation for "foo.com" or "foo.com/url_from_history".
[email protected]cc1526e2013-05-17 04:04:241220 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
1221 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
1222 default_results_.verbatim_relevance = -1;
1223 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421224 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521225 }
[email protected]45f89a92013-08-12 13:41:361226 if (!HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match)) {
1227 // If the omnibox is not going to reorder results to put a legal default
1228 // match at the top, then this provider needs to guarantee that its top
1229 // scoring result is a legal default match (i.e., it's either a verbatim
1230 // match or inlinable). For example, input "foo" should not invoke a
1231 // search for "bar", which would happen if the "bar" search match
1232 // outranked all other matches. On the other hand, if the omnibox will
1233 // reorder matches as necessary to put a legal default match at the top,
1234 // all we need to guarantee is that SearchProvider returns a legal
1235 // default match. (The omnibox always needs at least one legal default
1236 // match, and it relies on SearchProvider to always return one.)
[email protected]344946a12012-12-20 12:03:421237 ApplyCalculatedRelevance();
1238 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521239 }
[email protected]0a8718b12013-11-13 18:41:311240 DCHECK(!IsTopMatchNavigationInKeywordMode(
1241 omnibox_will_reorder_for_legal_default_match));
[email protected]1c1e7842013-11-22 16:28:161242 DCHECK(HasKeywordDefaultMatchInKeywordMode());
[email protected]0a8718b12013-11-13 18:41:311243 DCHECK(!IsTopMatchScoreTooLow(
1244 omnibox_will_reorder_for_legal_default_match));
1245 DCHECK(!IsTopMatchSearchWithURLInput(
1246 omnibox_will_reorder_for_legal_default_match));
[email protected]45f89a92013-08-12 13:41:361247 DCHECK(HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match));
[email protected]d1f0a7f2012-06-05 10:26:421248 }
[email protected]3972aba2014-02-05 21:28:101249 UMA_HISTOGRAM_CUSTOM_COUNTS(
1250 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
[email protected]d1f0a7f2012-06-05 10:26:421251
[email protected]1c1e7842013-11-22 16:28:161252 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1253 if ((keyword_url != NULL) && HasKeywordDefaultMatchInKeywordMode()) {
1254 // If there is a keyword match that is allowed to be the default match,
1255 // then prohibit default provider matches from being the default match lest
1256 // such matches cause the user to break out of keyword mode.
1257 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
1258 ++it) {
1259 if (it->keyword != keyword_url->keyword())
1260 it->allowed_to_be_default_match = false;
1261 }
1262 }
1263
[email protected]31afdf72013-09-26 04:29:361264 base::TimeTicks update_starred_start_time(base::TimeTicks::Now());
[email protected]cc63dea2008-08-21 20:56:311265 UpdateStarredStateOfMatches();
[email protected]31afdf72013-09-26 04:29:361266 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateStarredTime",
1267 base::TimeTicks::Now() - update_starred_start_time);
[email protected]4ab4c7c2010-11-24 04:49:341268 UpdateDone();
[email protected]31afdf72013-09-26 04:29:361269 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateMatchesTime",
1270 base::TimeTicks::Now() - update_matches_start_time);
[email protected]257ab712009-04-14 17:16:241271}
1272
1273void SearchProvider::AddNavigationResultsToMatches(
[email protected]d30268a2013-06-25 22:31:071274 const NavigationResults& navigation_results,
1275 ACMatches* matches) {
[email protected]bc8bb0cd2013-06-24 21:50:231276 for (NavigationResults::const_iterator it = navigation_results.begin();
1277 it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:071278 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:231279 // In the absence of suggested relevance scores, use only the single
1280 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:071281 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:231282 return;
[email protected]257ab712009-04-14 17:16:241283 }
1284}
1285
1286void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
1287 bool is_keyword,
1288 int did_not_accept_suggestion,
1289 MatchMap* map) {
[email protected]51124552011-07-16 01:37:101290 if (results.empty())
1291 return;
1292
[email protected]31afdf72013-09-26 04:29:361293 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]d7ad4772012-06-01 03:12:541294 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1295 (input_.type() == AutocompleteInput::URL);
[email protected]0085863a2013-12-06 21:19:031296 const base::string16& input_text =
[email protected]14710852013-02-05 23:45:411297 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:101298 bool input_multiple_words = HasMultipleWords(input_text);
1299
[email protected]55ce8f12012-05-09 04:44:081300 SuggestResults scored_results;
1301 if (!prevent_inline_autocomplete && input_multiple_words) {
1302 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1303 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:101304 // autocompleting a multi-word, multi-visit query, and the current input is
1305 // still a prefix of it, then changing the autocompletion suddenly feels
1306 // wrong. To detect this case, first score as if only one word has been
1307 // typed, then check for a best result that is an autocompleted, multi-word
1308 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:081309 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1310 false, input_text, is_keyword);
[email protected]9dfb4d362013-04-05 02:15:121311 if ((scored_results.front().relevance() <
[email protected]55ce8f12012-05-09 04:44:081312 AutocompleteResult::kLowestDefaultScore) ||
[email protected]9dfb4d362013-04-05 02:15:121313 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:081314 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:101315 }
[email protected]55ce8f12012-05-09 04:44:081316 if (scored_results.empty())
1317 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1318 input_multiple_words, input_text,
1319 is_keyword);
1320 for (SuggestResults::const_iterator i(scored_results.begin());
1321 i != scored_results.end(); ++i) {
[email protected]9487b392014-02-14 02:48:181322 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, map);
[email protected]51124552011-07-16 01:37:101323 }
[email protected]31afdf72013-09-26 04:29:361324 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1325 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:101326}
1327
[email protected]55ce8f12012-05-09 04:44:081328SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:101329 const HistoryResults& results,
1330 bool base_prevent_inline_autocomplete,
1331 bool input_multiple_words,
[email protected]0085863a2013-12-06 21:19:031332 const base::string16& input_text,
[email protected]51124552011-07-16 01:37:101333 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:481334 AutocompleteClassifier* classifier =
1335 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:081336 SuggestResults scored_results;
[email protected]78e5e432013-08-03 02:10:101337 const bool prevent_search_history_inlining =
1338 OmniboxFieldTrial::SearchHistoryPreventInlining(
1339 input_.current_page_classification());
[email protected]257ab712009-04-14 17:16:241340 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1341 ++i) {
[email protected]51124552011-07-16 01:37:101342 // Don't autocomplete multi-word queries that have only been seen once
1343 // unless the user has typed more than one word.
1344 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1345 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
1346
[email protected]ea3b9a502011-04-04 14:19:371347 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:101348 // when typed. For example, if the user searched for "google.com" and types
1349 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1350 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:481351 // NOTE: We don't check this in the following cases:
1352 // * When inline autocomplete is disabled, we won't be inline
1353 // autocompleting this term, so we don't need to worry about confusion as
1354 // much. This also prevents calling Classify() again from inside the
1355 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:101356 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:481357 // * When the user has typed the whole term, the "what you typed" history
1358 // match will outrank us for URL-like inputs anyway, so we need not do
1359 // anything special.
[email protected]51124552011-07-16 01:37:101360 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:371361 AutocompleteMatch match;
[email protected]51abb7b2014-02-09 23:00:081362 classifier->Classify(i->term, false, false,
1363 input_.current_page_classification(), &match, NULL);
[email protected]2905f742011-10-13 03:51:581364 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:461365 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:371366 }
[email protected]51124552011-07-16 01:37:101367
[email protected]78e5e432013-08-03 02:10:101368 int relevance = CalculateRelevanceForHistory(
1369 i->time, is_keyword, !prevent_inline_autocomplete,
1370 prevent_search_history_inlining);
[email protected]2c03c06b2013-12-11 20:45:021371 scored_results.push_back(SuggestResult(
1372 i->term, AutocompleteMatchType::SEARCH_HISTORY, i->term,
[email protected]61f99082014-02-24 02:17:491373 base::string16(), base::string16(), std::string(), std::string(),
1374 is_keyword, relevance, false, false, input_text));
[email protected]257ab712009-04-14 17:16:241375 }
[email protected]51124552011-07-16 01:37:101376
1377 // History returns results sorted for us. However, we may have docked some
1378 // results' scores, so things are no longer in order. Do a stable sort to get
1379 // things back in order without otherwise disturbing results with equal
1380 // scores, then force the scores to be unique, so that the order in which
1381 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081382 std::stable_sort(scored_results.begin(), scored_results.end(),
1383 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101384 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081385 for (SuggestResults::iterator i(scored_results.begin());
1386 i != scored_results.end(); ++i) {
1387 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1388 i->set_relevance(last_relevance - 1);
1389 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101390 }
1391
[email protected]55ce8f12012-05-09 04:44:081392 return scored_results;
[email protected]257ab712009-04-14 17:16:241393}
1394
[email protected]55ce8f12012-05-09 04:44:081395void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
[email protected]987fad782013-08-28 06:23:181396 const std::string& metadata,
[email protected]55ce8f12012-05-09 04:44:081397 MatchMap* map) {
[email protected]9487b392014-02-14 02:48:181398 for (size_t i = 0; i < results.size(); ++i)
1399 AddMatchToMap(results[i], metadata, i, map);
initial.commit09911bf2008-07-26 23:55:291400}
1401
[email protected]d30268a2013-06-25 22:31:071402int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561403 // Use the suggested verbatim relevance score if it is non-negative (valid),
1404 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281405 // and if it won't suppress verbatim, leaving no default provider matches.
1406 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561407 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281408 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561409 // Check for results on each verbatim calculation, as results from older
1410 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231411 bool use_server_relevance =
1412 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281413 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231414 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241415 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231416 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071417 if (relevance_from_server)
1418 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231419 return use_server_relevance ?
1420 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521421}
[email protected]d1f0a7f2012-06-05 10:26:421422
[email protected]382a0642012-06-06 06:13:521423int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471424 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361425 return 250;
[email protected]dab8d52d2013-03-05 07:35:281426 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1427}
[email protected]52d08b12009-10-19 18:42:361428
[email protected]dab8d52d2013-03-05 07:35:281429int SearchProvider::
1430 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291431 switch (input_.type()) {
1432 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361433 case AutocompleteInput::QUERY:
1434 case AutocompleteInput::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131435 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291436
initial.commit09911bf2008-07-26 23:55:291437 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361438 return 850;
initial.commit09911bf2008-07-26 23:55:291439
1440 default:
1441 NOTREACHED();
1442 return 0;
1443 }
1444}
1445
[email protected]d30268a2013-06-25 22:31:071446int SearchProvider::GetKeywordVerbatimRelevance(
1447 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281448 // Use the suggested verbatim relevance score if it is non-negative (valid),
1449 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1450 // and if it won't suppress verbatim, leaving no keyword provider matches.
1451 // Otherwise, if the keyword provider returned no matches and was still able
1452 // to suppress verbatim, the user would have no search/nav matches and may be
1453 // left unable to search using their keyword provider from the omnibox.
1454 // Check for results on each verbatim calculation, as results from older
1455 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231456 bool use_server_relevance =
1457 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281458 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231459 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241460 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231461 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071462 if (relevance_from_server)
1463 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231464 return use_server_relevance ?
1465 keyword_results_.verbatim_relevance :
1466 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1467 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451468}
1469
[email protected]51124552011-07-16 01:37:101470int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231471 const base::Time& time,
[email protected]51124552011-07-16 01:37:101472 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101473 bool use_aggressive_method,
1474 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181475 // The relevance of past searches falls off over time. There are two distinct
1476 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101477 // provider that we want to score aggressively), the score is in the range
1478 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161479 // it's in the range 1200-1299). If the second equation is used the
1480 // relevance of a search 15 minutes ago is discounted 50 points, while the
1481 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231482 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421483 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101484 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181485 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101486 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181487 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161488 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101489 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161490 max_score = 1299;
1491 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181492 std::pow(elapsed_time / autocomplete_time, 2.5));
1493 }
1494 elapsed_time -= autocomplete_time;
1495 }
1496
[email protected]c3a4bd992010-08-18 20:25:011497 const int score_discount =
1498 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291499
[email protected]6c85aa02009-02-27 12:08:091500 // Don't let scores go below 0. Negative relevance scores are meaningful in
1501 // a different way.
initial.commit09911bf2008-07-26 23:55:291502 int base_score;
[email protected]51124552011-07-16 01:37:101503 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361504 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101505 else
1506 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291507 return std::max(0, base_score - score_discount);
1508}
1509
initial.commit09911bf2008-07-26 23:55:291510AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421511 const NavigationResult& navigation) {
[email protected]0085863a2013-12-06 21:19:031512 const base::string16& input = navigation.from_keyword_provider() ?
[email protected]188b50c2013-03-28 07:19:421513 keyword_input_.text() : input_.text();
[email protected]55ce8f12012-05-09 04:44:081514 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]b7f64d742013-05-21 04:04:041515 AutocompleteMatchType::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081516 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551517
[email protected]23db6492014-01-16 02:35:301518 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551519 // without trimming the scheme, so we can find matches at the beginning of the
1520 // scheme.
[email protected]371dab12012-06-01 03:23:551521 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301522 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551523 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301524 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351525 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1526 (!prefix || (match_start != 0));
[email protected]23db6492014-01-16 02:35:301527 const net::FormatUrlTypes format_types =
1528 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551529
[email protected]371dab12012-06-01 03:23:551530 const std::string languages(
1531 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
[email protected]23db6492014-01-16 02:35:301532 size_t inline_autocomplete_offset = (prefix == NULL) ?
1533 base::string16::npos : (match_start + input.length());
[email protected]371dab12012-06-01 03:23:551534 match.fill_into_edit +=
1535 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1536 net::FormatUrl(navigation.url(), languages, format_types,
1537 net::UnescapeRule::SPACES, NULL, NULL,
1538 &inline_autocomplete_offset));
[email protected]14119032013-11-07 08:14:261539 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1540 // Otherwise, user edits to a suggestion would show non-Search results.
1541 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581542 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031543 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261544 ++inline_autocomplete_offset;
1545 }
[email protected]6c94a1022014-02-21 03:48:041546 if (inline_autocomplete_offset != base::string16::npos) {
[email protected]518024c2013-07-19 23:40:251547 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
[email protected]518024c2013-07-19 23:40:251548 match.inline_autocompletion =
1549 match.fill_into_edit.substr(inline_autocomplete_offset);
1550 }
[email protected]6c94a1022014-02-21 03:48:041551 // An inlineable navsuggestion can only be the default match when there
1552 // is no keyword provider active, lest it appear first and break the user
1553 // out of keyword mode. It can also only be default when we're not
1554 // preventing inline autocompletion (unless the inline autocompletion
1555 // would be empty).
1556 match.allowed_to_be_default_match = navigation.IsInlineable(input) &&
1557 (providers_.GetKeywordProviderURL() == NULL) &&
1558 (!input_.prevent_inline_autocomplete() ||
1559 match.inline_autocompletion.empty());
[email protected]371dab12012-06-01 03:23:551560
[email protected]23db6492014-01-16 02:35:301561 match.contents = navigation.match_contents();
1562 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081563 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551564 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1565 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071566
1567 match.RecordAdditionalInfo(
1568 kRelevanceFromServerKey,
1569 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181570 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071571
initial.commit09911bf2008-07-26 23:55:291572 return match;
1573}
[email protected]4ab4c7c2010-11-24 04:49:341574
[email protected]9dfb4d362013-04-05 02:15:121575void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
[email protected]d519d392013-03-27 09:24:461576 // First, determine the maximum score of any keyword query match (verbatim or
1577 // query suggestion).
[email protected]d30268a2013-06-25 22:31:071578 bool relevance_from_server;
1579 int max_query_relevance = GetKeywordVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:241580 if (!keyword_results_.suggest_results.empty()) {
[email protected]d30268a2013-06-25 22:31:071581 const SuggestResult& top_keyword = keyword_results_.suggest_results.front();
1582 const int suggest_relevance = top_keyword.relevance();
1583 if (suggest_relevance > max_query_relevance) {
1584 max_query_relevance = suggest_relevance;
1585 relevance_from_server = top_keyword.relevance_from_server();
1586 } else if (suggest_relevance == max_query_relevance) {
1587 relevance_from_server |= top_keyword.relevance_from_server();
1588 }
[email protected]d519d392013-03-27 09:24:461589 }
1590 // If no query is supposed to appear, then navigational matches cannot
[email protected]9dfb4d362013-04-05 02:15:121591 // be demoted past it. Get rid of suggested relevance scores for
1592 // navsuggestions and introduce the verbatim results again. The keyword
1593 // verbatim match will outscore the navsuggest matches.
1594 if (max_query_relevance == 0) {
[email protected]cc1526e2013-05-17 04:04:241595 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
1596 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
1597 keyword_results_.verbatim_relevance = -1;
1598 default_results_.verbatim_relevance = -1;
[email protected]9dfb4d362013-04-05 02:15:121599 return;
1600 }
[email protected]d519d392013-03-27 09:24:461601 // Now we know we can enforce the minimum score constraint even after
1602 // the navigation matches are demoted. Proceed to demote the navigation
1603 // matches to enforce the query-must-come-first constraint.
[email protected]d519d392013-03-27 09:24:461604 // Cap the relevance score of all results.
[email protected]cc1526e2013-05-17 04:04:241605 for (NavigationResults::iterator it =
1606 keyword_results_.navigation_results.begin();
1607 it != keyword_results_.navigation_results.end(); ++it) {
[email protected]9dfb4d362013-04-05 02:15:121608 if (it->relevance() < max_query_relevance)
1609 return;
1610 max_query_relevance = std::max(max_query_relevance - 1, 0);
1611 it->set_relevance(max_query_relevance);
[email protected]d30268a2013-06-25 22:31:071612 it->set_relevance_from_server(relevance_from_server);
[email protected]d519d392013-03-27 09:24:461613 }
[email protected]d519d392013-03-27 09:24:461614}
1615
[email protected]4ab4c7c2010-11-24 04:49:341616void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331617 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311618 // pending, and we're not waiting on Instant.
[email protected]e1290ee62013-06-26 18:31:151619 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
[email protected]4ab4c7c2010-11-24 04:49:341620}