blob: debfdb4838d8ad2ed63fc74e34f052e82bfbfbd1 [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]5889bfb2014-03-19 00:26:4818#include "base/strings/string_util.h"
[email protected]135cb802013-06-09 16:44:2019#include "base/strings/utf_string_conversions.h"
[email protected]ea3b9a502011-04-04 14:19:3720#include "chrome/browser/autocomplete/autocomplete_classifier.h"
[email protected]810ffba2012-06-12 01:07:4821#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
[email protected]5af9bc82012-06-29 00:53:4822#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
[email protected]73c2b1632012-07-02 22:51:3823#include "chrome/browser/autocomplete/autocomplete_result.h"
[email protected]2c812ba02011-07-14 00:23:1524#include "chrome/browser/autocomplete/keyword_provider.h"
[email protected]371dab12012-06-01 03:23:5525#include "chrome/browser/autocomplete/url_prefix.h"
[email protected]9b9fa672013-11-07 06:04:5226#include "chrome/browser/google/google_util.h"
[email protected]6a2c09f2013-01-25 04:50:0727#include "chrome/browser/history/history_service.h"
[email protected]9d2db762012-06-19 00:01:1028#include "chrome/browser/history/history_service_factory.h"
[email protected]10c2d692012-05-11 05:32:2329#include "chrome/browser/history/in_memory_database.h"
[email protected]ab7780792013-01-10 01:26:0930#include "chrome/browser/metrics/variations/variations_http_header_provider.h"
[email protected]684fcc12013-03-08 22:50:0231#include "chrome/browser/omnibox/omnibox_field_trial.h"
[email protected]8ecad5e2010-12-02 21:18:3332#include "chrome/browser/profiles/profile.h"
[email protected]a7b8e43d2013-03-18 18:52:4333#include "chrome/browser/search/search.h"
[email protected]9899a612012-08-21 23:50:0434#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
[email protected]8e5c89a2011-06-07 18:13:3335#include "chrome/browser/search_engines/template_url_service.h"
36#include "chrome/browser/search_engines/template_url_service_factory.h"
[email protected]c4a9d4c2013-08-10 07:06:2737#include "chrome/browser/ui/search/instant_controller.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]d1f0a7f2012-06-05 10:26:4296} // namespace
[email protected]51124552011-07-16 01:37:1097
[email protected]3954c3a2012-04-10 20:17:5598// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:5899
[email protected]85b8d6f2012-05-08 20:53:47100SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
[email protected]02346202014-02-05 05:18:30101 : template_url_service_(template_url_service) {}
[email protected]85b8d6f2012-05-08 20:53:47102
103const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
104 return default_provider_.empty() ? NULL :
105 template_url_service_->GetTemplateURLForKeyword(default_provider_);
106}
107
108const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
109 return keyword_provider_.empty() ? NULL :
110 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24111}
112
[email protected]3954c3a2012-04-10 20:17:55113
[email protected]bc8bb0cd2013-06-24 21:50:23114// SearchProvider::CompareScoredResults ---------------------------------------
115
116class SearchProvider::CompareScoredResults {
117 public:
118 bool operator()(const Result& a, const Result& b) {
119 // Sort in descending relevance order.
120 return a.relevance() > b.relevance();
121 }
122};
123
124
[email protected]3954c3a2012-04-10 20:17:55125// SearchProvider -------------------------------------------------------------
126
127// static
[email protected]24dbf2302013-04-05 16:59:25128int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]3954c3a2012-04-10 20:17:55129
[email protected]bc8bb0cd2013-06-24 21:50:23130SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
131 Profile* profile)
[email protected]02346202014-02-05 05:18:30132 : BaseSearchProvider(listener, profile, AutocompleteProvider::TYPE_SEARCH),
[email protected]bc8bb0cd2013-06-24 21:50:23133 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
[email protected]fd4e6a592014-02-07 02:41:38134 suggest_results_pending_(0) {
[email protected]bc8bb0cd2013-06-24 21:50:23135}
136
[email protected]cb86ee6f2013-04-28 16:58:15137// static
[email protected]987fad782013-08-28 06:23:18138std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
139 return match.GetAdditionalInfo(kSuggestMetadataKey);
140}
141
[email protected]bc8bb0cd2013-06-24 21:50:23142void SearchProvider::ResetSession() {
143 field_trial_triggered_in_session_ = false;
[email protected]4ab4c7c2010-11-24 04:49:34144}
145
[email protected]bc8bb0cd2013-06-24 21:50:23146SearchProvider::~SearchProvider() {
147}
148
149// static
[email protected]0085863a2013-12-06 21:19:03150void SearchProvider::RemoveStaleResults(const base::string16& input,
[email protected]bc8bb0cd2013-06-24 21:50:23151 int verbatim_relevance,
152 SuggestResults* suggest_results,
153 NavigationResults* navigation_results) {
154 DCHECK_GE(verbatim_relevance, 0);
155 // Keep pointers to the head of (the highest scoring elements of)
156 // |suggest_results| and |navigation_results|. Iterate down the lists
157 // removing non-inlineable results in order of decreasing relevance
158 // scores. Stop when the highest scoring element among those remaining
159 // is inlineable or the element is less than |verbatim_relevance|.
160 // This allows non-inlineable lower-scoring results to remain
161 // because (i) they are guaranteed to not be inlined and (ii)
162 // letting them remain reduces visual jank. For instance, as the
163 // user types the mis-spelled query "fpobar" (for foobar), the
164 // suggestion "foobar" will be suggested on every keystroke. If the
165 // SearchProvider always removes all non-inlineable results, the user will
166 // see visual jitter/jank as the result disappears and re-appears moments
167 // later as the suggest server returns results.
168 SuggestResults::iterator sug_it = suggest_results->begin();
169 NavigationResults::iterator nav_it = navigation_results->begin();
170 while ((sug_it != suggest_results->end()) ||
171 (nav_it != navigation_results->end())) {
172 const int sug_rel =
173 (sug_it != suggest_results->end()) ? sug_it->relevance() : -1;
174 const int nav_rel =
175 (nav_it != navigation_results->end()) ? nav_it->relevance() : -1;
176 if (std::max(sug_rel, nav_rel) < verbatim_relevance)
177 break;
178 if (sug_rel > nav_rel) {
179 // The current top result is a search suggestion.
180 if (sug_it->IsInlineable(input))
181 break;
182 sug_it = suggest_results->erase(sug_it);
183 } else if (sug_rel == nav_rel) {
184 // Have both results and they're tied.
185 const bool sug_inlineable = sug_it->IsInlineable(input);
186 const bool nav_inlineable = nav_it->IsInlineable(input);
187 if (!sug_inlineable)
188 sug_it = suggest_results->erase(sug_it);
189 if (!nav_inlineable)
190 nav_it = navigation_results->erase(nav_it);
191 if (sug_inlineable || nav_inlineable)
192 break;
193 } else {
194 // The current top result is a navigational suggestion.
195 if (nav_it->IsInlineable(input))
196 break;
197 nav_it = navigation_results->erase(nav_it);
198 }
199 }
200}
201
[email protected]ee6110b2014-01-09 22:26:31202void SearchProvider::UpdateMatchContentsClass(const base::string16& input_text,
[email protected]23db6492014-01-16 02:35:30203 Results* results) {
204 for (SuggestResults::iterator sug_it = results->suggest_results.begin();
205 sug_it != results->suggest_results.end(); ++sug_it) {
[email protected]ee6110b2014-01-09 22:26:31206 sug_it->ClassifyMatchContents(false, input_text);
207 }
[email protected]23db6492014-01-16 02:35:30208 const std::string languages(
209 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
210 for (NavigationResults::iterator nav_it = results->navigation_results.begin();
211 nav_it != results->navigation_results.end(); ++nav_it) {
212 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
213 }
[email protected]ee6110b2014-01-09 22:26:31214}
215
216// static
[email protected]bc8bb0cd2013-06-24 21:50:23217int SearchProvider::CalculateRelevanceForKeywordVerbatim(
218 AutocompleteInput::Type type,
219 bool prefer_keyword) {
220 // This function is responsible for scoring verbatim query matches
221 // for non-extension keywords. KeywordProvider::CalculateRelevance()
222 // scores verbatim query matches for extension keywords, as well as
223 // for keyword matches (i.e., suggestions of a keyword itself, not a
224 // suggestion of a query on a keyword search engine). These two
225 // functions are currently in sync, but there's no reason we
226 // couldn't decide in the future to score verbatim matches
227 // differently for extension and non-extension keywords. If you
228 // make such a change, however, you should update this comment to
229 // describe it, so it's clear why the functions diverge.
230 if (prefer_keyword)
231 return 1500;
232 return (type == AutocompleteInput::QUERY) ? 1450 : 1100;
233}
234
initial.commit09911bf2008-07-26 23:55:29235void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27236 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55237 // Do our best to load the model as early as possible. This will reduce
238 // odds of having the model not ready when really needed (a non-empty input).
239 TemplateURLService* model = providers_.template_url_service();
240 DCHECK(model);
241 model->Load();
242
initial.commit09911bf2008-07-26 23:55:29243 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57244 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29245
[email protected]6c85aa02009-02-27 12:08:09246 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29247 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]9950e5d52014-02-25 23:34:19248 Stop(true);
initial.commit09911bf2008-07-26 23:55:29249 return;
250 }
251
[email protected]14710852013-02-05 23:45:41252 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24253 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41254 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
255 &keyword_input_);
256 if (keyword_provider == NULL)
257 keyword_input_.Clear();
258 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24259 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24260
[email protected]85b8d6f2012-05-08 20:53:47261 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07262 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24263 default_provider = NULL;
264
265 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18266 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24267
268 if (!default_provider && !keyword_provider) {
269 // No valid providers.
[email protected]9950e5d52014-02-25 23:34:19270 Stop(true);
initial.commit09911bf2008-07-26 23:55:29271 return;
272 }
273
274 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24275 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03276 base::string16 default_provider_keyword(default_provider ?
277 default_provider->keyword() : base::string16());
278 base::string16 keyword_provider_keyword(keyword_provider ?
279 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32280 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47281 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29282 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15283 if (!done_)
[email protected]e29249dc52012-07-19 17:33:50284 Stop(false);
[email protected]257ab712009-04-14 17:16:24285 }
initial.commit09911bf2008-07-26 23:55:29286
[email protected]85b8d6f2012-05-08 20:53:47287 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29288
289 if (input.text().empty()) {
290 // User typed "?" alone. Give them a placeholder result indicating what
291 // this syntax does.
[email protected]257ab712009-04-14 17:16:24292 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00293 AutocompleteMatch match;
294 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36295 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24296 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35297 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47298 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36299 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24300 matches_.push_back(match);
301 }
[email protected]9950e5d52014-02-25 23:34:19302 Stop(true);
initial.commit09911bf2008-07-26 23:55:29303 return;
304 }
305
306 input_ = input;
307
[email protected]e1290ee62013-06-26 18:31:15308 DoHistoryQuery(minimal_changes);
309 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42310 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29311}
312
[email protected]10c2d692012-05-11 05:32:23313void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29314 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24315 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25316 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15317 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06318
[email protected]d7ad4772012-06-01 03:12:54319 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]f2916ea2013-01-26 02:20:14320 // Ensure the request succeeded and that the provider used is still available.
321 // A verbatim match cannot be generated without this provider, causing errors.
[email protected]013e9a02012-05-18 20:27:10322 const bool request_succeeded =
[email protected]bc8bb0cd2013-06-24 21:50:23323 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
324 (is_keyword ?
325 providers_.GetKeywordProviderURL() :
326 providers_.GetDefaultProviderURL());
[email protected]a0ad93ea2012-05-07 22:11:53327
328 // Record response time for suggest requests sent to Google. We care
329 // only about the common case: the Google default provider used in
330 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47331 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08332 if (!is_keyword && default_url &&
[email protected]628392f2013-08-16 00:34:45333 (TemplateURLPrepopulateData::GetEngineType(*default_url) ==
[email protected]9899a612012-08-21 23:50:04334 SEARCH_ENGINE_GOOGLE)) {
[email protected]bc8bb0cd2013-06-24 21:50:23335 const base::TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10336 base::TimeTicks::Now() - time_suggest_request_sent_;
337 if (request_succeeded) {
338 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
339 elapsed_time);
340 } else {
341 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
342 elapsed_time);
343 }
[email protected]b4cebf82008-12-29 19:59:08344 }
345
[email protected]d7ad4772012-06-01 03:12:54346 bool results_updated = false;
347 if (request_succeeded) {
[email protected]ed9b1802013-10-31 04:09:48348 const net::HttpResponseHeaders* const response_headers =
349 source->GetResponseHeaders();
350 std::string json_data;
351 source->GetResponseAsString(&json_data);
[email protected]7267ff82013-12-03 17:20:30352
[email protected]ed9b1802013-10-31 04:09:48353 // JSON is supposed to be UTF-8, but some suggest service providers send
354 // JSON files in non-UTF-8 encodings. The actual encoding is usually
355 // specified in the Content-Type header field.
356 if (response_headers) {
357 std::string charset;
358 if (response_headers->GetCharset(&charset)) {
[email protected]0085863a2013-12-06 21:19:03359 base::string16 data_16;
[email protected]ed9b1802013-10-31 04:09:48360 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
361 if (base::CodepageToUTF16(json_data, charset.c_str(),
362 base::OnStringConversionError::FAIL,
363 &data_16))
[email protected]670d3232013-12-24 17:58:58364 json_data = base::UTF16ToUTF8(data_16);
[email protected]ed9b1802013-10-31 04:09:48365 }
366 }
367
[email protected]5bcdd99d2013-12-23 18:28:30368 scoped_ptr<base::Value> data(DeserializeJsonData(json_data));
[email protected]d4a94b92014-03-04 01:35:22369 results_updated = data.get() && ParseSuggestResults(
370 *data.get(), is_keyword,
371 is_keyword ? &keyword_results_ : &default_results_);
[email protected]d7ad4772012-06-01 03:12:54372 }
373
[email protected]344946a12012-12-20 12:03:42374 UpdateMatches();
[email protected]d7ad4772012-06-01 03:12:54375 if (done_ || results_updated)
376 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29377}
378
[email protected]d4a94b92014-03-04 01:35:22379void SearchProvider::SortResults(bool is_keyword,
380 const base::ListValue* relevances,
381 Results* results) {
382 // Ignore suggested scores for non-keyword matches in keyword mode; if the
383 // server is allowed to score these, it could interfere with the user's
384 // ability to get good keyword results.
385 const bool abandon_suggested_scores =
386 !is_keyword && !providers_.keyword_provider().empty();
387 // Apply calculated relevance scores to suggestions if a valid list was
388 // not provided or we're abandoning suggested scores entirely.
389 if ((relevances == NULL) || abandon_suggested_scores) {
390 ApplyCalculatedSuggestRelevance(&results->suggest_results);
391 ApplyCalculatedNavigationRelevance(&results->navigation_results);
392 // If abandoning scores entirely, also abandon the verbatim score.
393 if (abandon_suggested_scores)
394 results->verbatim_relevance = -1;
395 }
396
397 // Keep the result lists sorted.
398 const CompareScoredResults comparator = CompareScoredResults();
399 std::stable_sort(results->suggest_results.begin(),
400 results->suggest_results.end(),
401 comparator);
402 std::stable_sort(results->navigation_results.begin(),
403 results->navigation_results.end(),
404 comparator);
405}
406
[email protected]9487b392014-02-14 02:48:18407const TemplateURL* SearchProvider::GetTemplateURL(
408 const SuggestResult& result) const {
409 return result.from_keyword_provider() ? providers_.GetKeywordProviderURL()
410 : providers_.GetDefaultProviderURL();
411}
412
[email protected]d4a94b92014-03-04 01:35:22413const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
414 return is_keyword ? keyword_input_ : input_;
[email protected]9487b392014-02-14 02:48:18415}
416
417bool SearchProvider::ShouldAppendExtraParams(
418 const SuggestResult& result) const {
419 return !result.from_keyword_provider() ||
420 providers_.default_provider().empty();
421}
422
[email protected]ef6866f2014-02-18 08:26:34423void SearchProvider::StopSuggest() {
424 // Increment the appropriate field in the histogram by the number of
425 // pending requests that were invalidated.
426 for (int i = 0; i < suggest_results_pending_; ++i)
427 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
428 suggest_results_pending_ = 0;
429 timer_.Stop();
430 // Stop any in-progress URL fetches.
431 keyword_fetcher_.reset();
432 default_fetcher_.reset();
433}
434
435void SearchProvider::ClearAllResults() {
436 keyword_results_.Clear();
437 default_results_.Clear();
438}
439
[email protected]d4a94b92014-03-04 01:35:22440int SearchProvider::GetDefaultResultRelevance() const {
441 return -1;
442}
443
[email protected]7267ff82013-12-03 17:20:30444void SearchProvider::RecordDeletionResult(bool success) {
445 if (success) {
446 content::RecordAction(
[email protected]e6e30ac2014-01-13 21:24:39447 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
[email protected]7267ff82013-12-03 17:20:30448 } else {
449 content::RecordAction(
[email protected]e6e30ac2014-01-13 21:24:39450 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
[email protected]7267ff82013-12-03 17:20:30451 }
452}
453
[email protected]bc8bb0cd2013-06-24 21:50:23454void SearchProvider::Run() {
455 // Start a new request with the current input.
456 suggest_results_pending_ = 0;
457 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05458
[email protected]bc8bb0cd2013-06-24 21:50:23459 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
460 providers_.GetDefaultProviderURL(), input_));
461 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
462 providers_.GetKeywordProviderURL(), keyword_input_));
463
464 // Both the above can fail if the providers have been modified or deleted
465 // since the query began.
466 if (suggest_results_pending_ == 0) {
467 UpdateDone();
468 // We only need to update the listener if we're actually done.
469 if (done_)
470 listener_->OnProviderUpdate(false);
471 }
[email protected]601858c02010-09-01 17:08:20472}
473
[email protected]8d457132010-11-04 18:13:40474void SearchProvider::DoHistoryQuery(bool minimal_changes) {
475 // The history query results are synchronous, so if minimal_changes is true,
476 // we still have the last results and don't need to do anything.
477 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29478 return;
479
[email protected]31afdf72013-09-26 04:29:36480 base::TimeTicks do_history_query_start_time(base::TimeTicks::Now());
481
[email protected]8d457132010-11-04 18:13:40482 keyword_history_results_.clear();
483 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29484
[email protected]78e5e432013-08-03 02:10:10485 if (OmniboxFieldTrial::SearchHistoryDisable(
486 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16487 return;
488
[email protected]31afdf72013-09-26 04:29:36489 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]8d457132010-11-04 18:13:40490 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10491 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]31afdf72013-09-26 04:29:36492 base::TimeTicks now(base::TimeTicks::Now());
493 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.GetHistoryServiceTime",
494 now - start_time);
495 start_time = now;
[email protected]8d457132010-11-04 18:13:40496 history::URLDatabase* url_db = history_service ?
497 history_service->InMemoryDatabase() : NULL;
[email protected]31afdf72013-09-26 04:29:36498 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.InMemoryDatabaseTime",
499 base::TimeTicks::Now() - start_time);
[email protected]8d457132010-11-04 18:13:40500 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29501 return;
502
[email protected]51124552011-07-16 01:37:10503 // Request history for both the keyword and default provider. We grab many
504 // more matches than we'll ultimately clamp to so that if there are several
505 // recent multi-word matches who scores are lowered (see
506 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
507 // matches. Note that this doesn't fix the problem entirely, but merely
508 // limits it to cases with a very large number of such multi-word matches; for
509 // now, this seems OK compared with the complexity of a real fix, which would
510 // require multiple searches and tracking of "single- vs. multi-word" in the
511 // database.
512 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47513 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
514 if (default_url) {
[email protected]31afdf72013-09-26 04:29:36515 start_time = base::TimeTicks::Now();
[email protected]85b8d6f2012-05-08 20:53:47516 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
517 num_matches, &default_history_results_);
[email protected]31afdf72013-09-26 04:29:36518 UMA_HISTOGRAM_TIMES(
519 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
520 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24521 }
[email protected]85b8d6f2012-05-08 20:53:47522 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
523 if (keyword_url) {
524 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41525 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55526 }
[email protected]31afdf72013-09-26 04:29:36527 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.DoHistoryQueryTime",
528 base::TimeTicks::Now() - do_history_query_start_time);
initial.commit09911bf2008-07-26 23:55:29529}
530
[email protected]6dc950f2012-07-16 19:49:08531void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34532 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29533 StopSuggest();
[email protected]71b46152013-05-03 16:39:20534 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29535 return;
536 }
537
538 // For the minimal_changes case, if we finished the previous query and still
539 // have its results, or are allowed to keep running it, just do that, rather
540 // than starting a new query.
541 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24542 (!default_results_.suggest_results.empty() ||
543 !default_results_.navigation_results.empty() ||
544 !keyword_results_.suggest_results.empty() ||
545 !keyword_results_.navigation_results.empty() ||
[email protected]ea3b9a502011-04-04 14:19:37546 (!done_ &&
547 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29548 return;
549
550 // We can't keep running any previous query, so halt it.
551 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42552
553 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20554 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29555
[email protected]ee6110b2014-01-09 22:26:31556 // Update the content classifications of remaining results so they look good
557 // against the current input.
[email protected]23db6492014-01-16 02:35:30558 UpdateMatchContentsClass(input_.text(), &default_results_);
559 if (!keyword_input_.text().empty())
560 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31561
initial.commit09911bf2008-07-26 23:55:29562 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37563 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29564 return;
565
[email protected]24dbf2302013-04-05 16:59:25566 // To avoid flooding the suggest server, don't send a query until at
567 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24568 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
[email protected]bc8bb0cd2013-06-24 21:50:23569 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
[email protected]515ffa942012-11-27 20:18:24570 base::TimeTicks now(base::TimeTicks::Now());
571 if (now >= next_suggest_time) {
572 Run();
573 return;
574 }
575 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29576}
577
[email protected]83c726482008-09-10 06:36:34578bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55579 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
580 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47581 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
582 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34583 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47584 ((!default_url || default_url->suggestions_url().empty()) &&
585 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34586 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
587 return false;
588
[email protected]cac59d32010-08-09 23:23:14589 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34590 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34591
[email protected]cac59d32010-08-09 23:23:14592 // FORCED_QUERY means the user is explicitly asking us to search for this, so
593 // we assume it isn't a URL and/or there isn't private data.
594 if (input_.type() == AutocompleteInput::FORCED_QUERY)
595 return true;
[email protected]83c726482008-09-10 06:36:34596
[email protected]f608ea102013-03-18 15:08:09597 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
598 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
599 // is both a waste of time and a disclosure of potentially private, local
600 // data. Other "schemes" may actually be usernames, and we don't want to send
601 // passwords. If the scheme is OK, we still need to check other cases below.
602 // If this is QUERY, then the presence of these schemes means the user
603 // explicitly typed one, and thus this is probably a URL that's being entered
604 // and happens to currently be invalid -- in which case we again want to run
605 // our checks below. Other QUERY cases are less likely to be URLs and thus we
606 // assume we're OK.
[email protected]e9a82042013-09-15 03:38:29607 if (!LowerCaseEqualsASCII(input_.scheme(), content::kHttpScheme) &&
[email protected]4654bfe2013-08-26 03:36:58608 !LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]72aa4c22013-12-01 15:09:35609 !LowerCaseEqualsASCII(input_.scheme(), content::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14610 return (input_.type() == AutocompleteInput::QUERY);
611
612 // Don't send URLs with usernames, queries or refs. Some of these are
613 // private, and the Suggest server is unlikely to have any useful results
614 // for any of them. Also don't send URLs with ports, as we may initially
615 // think that a username + password is a host + port (and we don't want to
616 // send usernames/passwords), and even if the port really is a port, the
617 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58618 // Note that we only block based on refs if the input is URL-typed, as search
619 // queries can legitimately have #s in them which the URL parser
620 // overaggressively categorizes as a url with a ref.
[email protected]cac59d32010-08-09 23:23:14621 const url_parse::Parsed& parts = input_.parts();
622 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58623 parts.query.is_nonempty() ||
624 (parts.ref.is_nonempty() && (input_.type() == AutocompleteInput::URL)))
[email protected]cac59d32010-08-09 23:23:14625 return false;
626
627 // Don't send anything for https except the hostname. Hostnames are OK
628 // because they are visible when the TCP connection is established, but the
629 // specific path may reveal private information.
[email protected]4654bfe2013-08-26 03:36:58630 if (LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36631 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14632 return false;
[email protected]83c726482008-09-10 06:36:34633
634 return true;
635}
636
[email protected]71b46152013-05-03 16:39:20637void SearchProvider::RemoveAllStaleResults() {
[email protected]dc735c02013-11-12 23:23:41638 // We only need to remove stale results (which ensures the top-scoring
639 // match is inlineable) if the user is not in reorder mode. In reorder
640 // mode, the autocomplete system will reorder results to make sure the
641 // top result is inlineable.
642 const bool omnibox_will_reorder_for_legal_default_match =
643 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
644 input_.current_page_classification());
[email protected]1e1550e2013-05-02 17:37:51645 // In theory it would be better to run an algorithm like that in
646 // RemoveStaleResults(...) below that uses all four results lists
647 // and both verbatim scores at once. However, that will be much
648 // more complicated for little obvious gain. For code simplicity
649 // and ease in reasoning about the invariants involved, this code
650 // removes stales results from the keyword provider and default
651 // provider independently.
[email protected]dc735c02013-11-12 23:23:41652 if (!omnibox_will_reorder_for_legal_default_match) {
653 RemoveStaleResults(input_.text(), GetVerbatimRelevance(NULL),
654 &default_results_.suggest_results,
655 &default_results_.navigation_results);
656 if (!keyword_input_.text().empty()) {
657 RemoveStaleResults(keyword_input_.text(),
658 GetKeywordVerbatimRelevance(NULL),
659 &keyword_results_.suggest_results,
660 &keyword_results_.navigation_results);
661 }
662 }
663 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51664 // User is either in keyword mode with a blank input or out of
665 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24666 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51667 }
[email protected]d1f0a7f2012-06-05 10:26:42668}
669
[email protected]d1f0a7f2012-06-05 10:26:42670void SearchProvider::ApplyCalculatedRelevance() {
[email protected]cc1526e2013-05-17 04:04:24671 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
672 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
673 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
674 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
[email protected]cc1526e2013-05-17 04:04:24675 default_results_.verbatim_relevance = -1;
676 keyword_results_.verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42677}
678
[email protected]188b50c2013-03-28 07:19:42679void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42680 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42681 SuggestResult& result = (*list)[i];
682 result.set_relevance(
683 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
684 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07685 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42686 }
687}
688
[email protected]188b50c2013-03-28 07:19:42689void SearchProvider::ApplyCalculatedNavigationRelevance(
690 NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42691 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42692 NavigationResult& result = (*list)[i];
693 result.set_relevance(
694 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
695 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07696 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42697 }
698}
699
[email protected]15fb2aa2012-05-22 22:52:59700net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12701 int id,
[email protected]9ff91722012-09-07 05:29:12702 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41703 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12704 if (!template_url || template_url->suggestions_url().empty())
705 return NULL;
706
707 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41708 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
709 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18710 search_term_args.page_classification = input.current_page_classification();
[email protected]9ff91722012-09-07 05:29:12711 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:16712 search_term_args));
[email protected]9ff91722012-09-07 05:29:12713 if (!suggest_url.is_valid())
714 return NULL;
[email protected]9b9fa672013-11-07 06:04:52715 // Send the current page URL if user setting and URL requirements are met and
716 // the user is in the field trial.
717 if (CanSendURL(current_page_url_, suggest_url, template_url,
718 input.current_page_classification(), profile_) &&
719 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
720 search_term_args.current_page_url = current_page_url_.spec();
721 // Create the suggest URL again with the current page URL.
722 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
723 search_term_args));
724 }
[email protected]9ff91722012-09-07 05:29:12725
726 suggest_results_pending_++;
727 LogOmniboxSuggestRequest(REQUEST_SENT);
728
729 net::URLFetcher* fetcher =
730 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12731 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34732 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30733 // Add Chrome experiment state to the request headers.
734 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:09735 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30736 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
737 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24738 fetcher->Start();
739 return fetcher;
740}
741
[email protected]344946a12012-12-20 12:03:42742void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29743 // Convert all the results to matches and add them to a map, so we can keep
744 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36745 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29746 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23747 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24748 int did_not_accept_keyword_suggestion =
749 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29750 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
751 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29752
[email protected]d30268a2013-06-25 22:31:07753 bool relevance_from_server;
754 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24755 int did_not_accept_default_suggestion =
756 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08757 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
758 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:42759 if (verbatim_relevance > 0) {
[email protected]2c03c06b2013-12-11 20:45:02760 SuggestResult verbatim(
761 input_.text(), AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]61f99082014-02-24 02:17:49762 input_.text(), base::string16(), base::string16(), std::string(),
763 std::string(), false, verbatim_relevance, relevance_from_server, false,
764 input_.text());
[email protected]57482a72014-03-14 22:27:37765 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
766 false, &map);
[email protected]d1f0a7f2012-06-05 10:26:42767 }
[email protected]5423e562013-02-07 03:58:45768 if (!keyword_input_.text().empty()) {
769 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
770 // We only create the verbatim search query match for a keyword
771 // if it's not an extension keyword. Extension keywords are handled
772 // in KeywordProvider::Start(). (Extensions are complicated...)
773 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
774 // to the keyword verbatim search query. Do not create other matches
775 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:25776 if (keyword_url &&
777 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:07778 bool keyword_relevance_from_server;
779 const int keyword_verbatim_relevance =
780 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:28781 if (keyword_verbatim_relevance > 0) {
[email protected]2c03c06b2013-12-11 20:45:02782 SuggestResult verbatim(
783 keyword_input_.text(), AutocompleteMatchType::SEARCH_OTHER_ENGINE,
[email protected]61f99082014-02-24 02:17:49784 keyword_input_.text(), base::string16(), base::string16(),
785 std::string(), std::string(), true, keyword_verbatim_relevance,
[email protected]ee6110b2014-01-09 22:26:31786 keyword_relevance_from_server, false, keyword_input_.text());
[email protected]57482a72014-03-14 22:27:37787 AddMatchToMap(verbatim, std::string(),
788 did_not_accept_keyword_suggestion, false, &map);
[email protected]dab8d52d2013-03-05 07:35:28789 }
[email protected]5423e562013-02-07 03:58:45790 }
791 }
[email protected]257ab712009-04-14 17:16:24792 AddHistoryResultsToMap(keyword_history_results_, true,
793 did_not_accept_keyword_suggestion, &map);
794 AddHistoryResultsToMap(default_history_results_, false,
795 did_not_accept_default_suggestion, &map);
796
[email protected]d1cb6a822013-09-18 19:43:00797 AddSuggestResultsToMap(keyword_results_.suggest_results,
798 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:18799 AddSuggestResultsToMap(default_results_.suggest_results,
800 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:29801
[email protected]d30268a2013-06-25 22:31:07802 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:29803 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:07804 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:29805
[email protected]d30268a2013-06-25 22:31:07806 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
807 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:29808
[email protected]d30268a2013-06-25 22:31:07809 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
810 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
811 // enabled and we have server-provided (and thus hopefully more accurate)
812 // scores for some suggestions, we allow more of those, until we reach
813 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
814 // whole popup).
815 //
816 // We will always return any verbatim matches, no matter how we obtained their
817 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
818 // higher-scoring matches under the conditions above.
[email protected]31afdf72013-09-26 04:29:36819 UMA_HISTOGRAM_CUSTOM_COUNTS(
820 "Omnibox.SearchProvider.NumMatchesToSort", matches.size(), 1, 50, 20);
[email protected]d30268a2013-06-25 22:31:07821 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
822 matches_.clear();
[email protected]3723e6e2012-06-11 21:06:56823
[email protected]d30268a2013-06-25 22:31:07824 size_t num_suggestions = 0;
825 for (ACMatches::const_iterator i(matches.begin());
826 (i != matches.end()) &&
827 (matches_.size() < AutocompleteResult::kMaxMatches);
828 ++i) {
829 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
830 // verbatim result, so this condition basically means "if this match is a
831 // suggestion of some sort".
832 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
833 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
834 // If we've already hit the limit on non-server-scored suggestions, and
835 // this isn't a server-scored suggestion we can add, skip it.
836 if ((num_suggestions >= kMaxMatches) &&
837 (!chrome::IsInstantExtendedAPIEnabled() ||
838 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
839 continue;
840 }
841
842 ++num_suggestions;
843 }
844
845 matches_.push_back(*i);
846 }
[email protected]31afdf72013-09-26 04:29:36847 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
848 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:42849}
850
[email protected]0a8718b12013-11-13 18:41:31851ACMatches::const_iterator SearchProvider::FindTopMatch(
852 bool autocomplete_result_will_reorder_for_default_match) const {
853 if (!autocomplete_result_will_reorder_for_default_match)
854 return matches_.begin();
855 ACMatches::const_iterator it = matches_.begin();
856 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
857 ++it;
858 return it;
[email protected]9dfb4d362013-04-05 02:15:12859}
860
[email protected]0a8718b12013-11-13 18:41:31861bool SearchProvider::IsTopMatchNavigationInKeywordMode(
862 bool autocomplete_result_will_reorder_for_default_match) const {
863 ACMatches::const_iterator first_match =
864 FindTopMatch(autocomplete_result_will_reorder_for_default_match);
865 return !providers_.keyword_provider().empty() &&
866 (first_match != matches_.end()) &&
867 (first_match->type == AutocompleteMatchType::NAVSUGGEST);
868}
869
[email protected]1c1e7842013-11-22 16:28:16870bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const {
871 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
872 // If the user is not in keyword mode, return true to say that this
873 // constraint is not violated.
874 if (keyword_url == NULL)
875 return true;
876 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
877 ++it) {
878 if ((it->keyword == keyword_url->keyword()) &&
879 it->allowed_to_be_default_match)
880 return true;
881 }
882 return false;
883}
884
[email protected]0a8718b12013-11-13 18:41:31885bool SearchProvider::IsTopMatchScoreTooLow(
886 bool autocomplete_result_will_reorder_for_default_match) const {
887 // In reorder mode, there's no such thing as a score that's too low.
888 if (autocomplete_result_will_reorder_for_default_match)
889 return false;
890
[email protected]dab8d52d2013-03-05 07:35:28891 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
892 // rather than CalculateRelevanceForVerbatim() because the latter returns
893 // a very low score (250) if keyword mode is active. This is because
894 // when keyword mode is active the user probably wants the keyword matches,
895 // not matches from the default provider. Hence, we use the version of
896 // the function that ignores whether keyword mode is active. This allows
897 // SearchProvider to maintain its contract with the AutocompleteController
898 // that it will always provide an inlineable match with a reasonable
899 // score.
900 return matches_.front().relevance <
901 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
[email protected]344946a12012-12-20 12:03:42902}
903
[email protected]0a8718b12013-11-13 18:41:31904bool SearchProvider::IsTopMatchSearchWithURLInput(
905 bool autocomplete_result_will_reorder_for_default_match) const {
906 ACMatches::const_iterator first_match =
907 FindTopMatch(autocomplete_result_will_reorder_for_default_match);
908 return (input_.type() == AutocompleteInput::URL) &&
909 (first_match != matches_.end()) &&
910 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
911 (first_match->type != AutocompleteMatchType::NAVSUGGEST);
[email protected]344946a12012-12-20 12:03:42912}
913
[email protected]45f89a92013-08-12 13:41:36914bool SearchProvider::HasValidDefaultMatch(
915 bool autocomplete_result_will_reorder_for_default_match) const {
916 // One of the SearchProvider matches may need to be the overall default. If
917 // AutocompleteResult is allowed to reorder matches, this means we simply
918 // need at least one match in the list to be |allowed_to_be_default_match|.
919 // If no reordering is possible, however, then our first match needs to have
920 // this flag.
921 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
922 ++it) {
923 if (it->allowed_to_be_default_match)
924 return true;
925 if (!autocomplete_result_will_reorder_for_default_match)
926 return false;
927 }
928 return false;
[email protected]344946a12012-12-20 12:03:42929}
930
931void SearchProvider::UpdateMatches() {
[email protected]31afdf72013-09-26 04:29:36932 base::TimeTicks update_matches_start_time(base::TimeTicks::Now());
[email protected]344946a12012-12-20 12:03:42933 ConvertResultsToAutocompleteMatches();
initial.commit09911bf2008-07-26 23:55:29934
[email protected]382a0642012-06-06 06:13:52935 // Check constraints that may be violated by suggested relevances.
[email protected]344946a12012-12-20 12:03:42936 if (!matches_.empty() &&
[email protected]bc8bb0cd2013-06-24 21:50:23937 (default_results_.HasServerProvidedScores() ||
938 keyword_results_.HasServerProvidedScores())) {
[email protected]9dfb4d362013-04-05 02:15:12939 // These blocks attempt to repair undesirable behavior by suggested
[email protected]344946a12012-12-20 12:03:42940 // relevances with minimal impact, preserving other suggested relevances.
[email protected]0a8718b12013-11-13 18:41:31941
942 // True if the omnibox will reorder matches as necessary to make the first
943 // one something that is allowed to be the default match.
944 const bool omnibox_will_reorder_for_legal_default_match =
945 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
946 input_.current_page_classification());
947 if (IsTopMatchNavigationInKeywordMode(
948 omnibox_will_reorder_for_legal_default_match)) {
[email protected]9dfb4d362013-04-05 02:15:12949 // Correct the suggested relevance scores if the top match is a
950 // navigation in keyword mode, since inlining a navigation match
[email protected]1c1e7842013-11-22 16:28:16951 // would break the user out of keyword mode. This will only be
952 // triggered in regular (non-reorder) mode; in reorder mode,
953 // navigation matches are marked as not allowed to be the default
954 // match and hence IsTopMatchNavigation() will always return false.
955 DCHECK(!omnibox_will_reorder_for_legal_default_match);
[email protected]9dfb4d362013-04-05 02:15:12956 DemoteKeywordNavigationMatchesPastTopQuery();
957 ConvertResultsToAutocompleteMatches();
[email protected]0a8718b12013-11-13 18:41:31958 DCHECK(!IsTopMatchNavigationInKeywordMode(
959 omnibox_will_reorder_for_legal_default_match));
[email protected]9dfb4d362013-04-05 02:15:12960 }
[email protected]1c1e7842013-11-22 16:28:16961 if (!HasKeywordDefaultMatchInKeywordMode()) {
962 // In keyword mode, disregard the keyword verbatim suggested relevance
963 // if necessary so there at least one keyword match that's allowed to
964 // be the default match.
965 keyword_results_.verbatim_relevance = -1;
966 ConvertResultsToAutocompleteMatches();
967 }
[email protected]0a8718b12013-11-13 18:41:31968 if (IsTopMatchScoreTooLow(omnibox_will_reorder_for_legal_default_match)) {
[email protected]1beee342012-06-19 22:22:28969 // Disregard the suggested verbatim relevance if the top score is below
970 // the usual verbatim value. For example, a BarProvider may rely on
[email protected]45f89a92013-08-12 13:41:36971 // SearchProvider's verbatim or inlineable matches for input "foo" (all
972 // allowed to be default match) to always outrank its own lowly-ranked
[email protected]0a8718b12013-11-13 18:41:31973 // "bar" matches that shouldn't be the default match.
[email protected]cc1526e2013-05-17 04:04:24974 default_results_.verbatim_relevance = -1;
975 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:42976 ConvertResultsToAutocompleteMatches();
[email protected]e6acd002012-06-16 22:27:47977 }
[email protected]0a8718b12013-11-13 18:41:31978 if (IsTopMatchSearchWithURLInput(
979 omnibox_will_reorder_for_legal_default_match)) {
[email protected]e6acd002012-06-16 22:27:47980 // Disregard the suggested search and verbatim relevances if the input
981 // type is URL and the top match is a highly-ranked search suggestion.
982 // For example, prevent a search for "foo.com" from outranking another
983 // provider's navigation for "foo.com" or "foo.com/url_from_history".
[email protected]cc1526e2013-05-17 04:04:24984 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
985 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
986 default_results_.verbatim_relevance = -1;
987 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:42988 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:52989 }
[email protected]45f89a92013-08-12 13:41:36990 if (!HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match)) {
991 // If the omnibox is not going to reorder results to put a legal default
992 // match at the top, then this provider needs to guarantee that its top
993 // scoring result is a legal default match (i.e., it's either a verbatim
994 // match or inlinable). For example, input "foo" should not invoke a
995 // search for "bar", which would happen if the "bar" search match
996 // outranked all other matches. On the other hand, if the omnibox will
997 // reorder matches as necessary to put a legal default match at the top,
998 // all we need to guarantee is that SearchProvider returns a legal
999 // default match. (The omnibox always needs at least one legal default
1000 // match, and it relies on SearchProvider to always return one.)
[email protected]344946a12012-12-20 12:03:421001 ApplyCalculatedRelevance();
1002 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521003 }
[email protected]0a8718b12013-11-13 18:41:311004 DCHECK(!IsTopMatchNavigationInKeywordMode(
1005 omnibox_will_reorder_for_legal_default_match));
[email protected]1c1e7842013-11-22 16:28:161006 DCHECK(HasKeywordDefaultMatchInKeywordMode());
[email protected]0a8718b12013-11-13 18:41:311007 DCHECK(!IsTopMatchScoreTooLow(
1008 omnibox_will_reorder_for_legal_default_match));
1009 DCHECK(!IsTopMatchSearchWithURLInput(
1010 omnibox_will_reorder_for_legal_default_match));
[email protected]45f89a92013-08-12 13:41:361011 DCHECK(HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match));
[email protected]d1f0a7f2012-06-05 10:26:421012 }
[email protected]3972aba2014-02-05 21:28:101013 UMA_HISTOGRAM_CUSTOM_COUNTS(
1014 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
[email protected]d1f0a7f2012-06-05 10:26:421015
[email protected]1c1e7842013-11-22 16:28:161016 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1017 if ((keyword_url != NULL) && HasKeywordDefaultMatchInKeywordMode()) {
1018 // If there is a keyword match that is allowed to be the default match,
1019 // then prohibit default provider matches from being the default match lest
1020 // such matches cause the user to break out of keyword mode.
1021 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
1022 ++it) {
1023 if (it->keyword != keyword_url->keyword())
1024 it->allowed_to_be_default_match = false;
1025 }
1026 }
1027
[email protected]31afdf72013-09-26 04:29:361028 base::TimeTicks update_starred_start_time(base::TimeTicks::Now());
[email protected]cc63dea2008-08-21 20:56:311029 UpdateStarredStateOfMatches();
[email protected]31afdf72013-09-26 04:29:361030 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateStarredTime",
1031 base::TimeTicks::Now() - update_starred_start_time);
[email protected]4ab4c7c2010-11-24 04:49:341032 UpdateDone();
[email protected]31afdf72013-09-26 04:29:361033 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateMatchesTime",
1034 base::TimeTicks::Now() - update_matches_start_time);
[email protected]257ab712009-04-14 17:16:241035}
1036
1037void SearchProvider::AddNavigationResultsToMatches(
[email protected]d30268a2013-06-25 22:31:071038 const NavigationResults& navigation_results,
1039 ACMatches* matches) {
[email protected]bc8bb0cd2013-06-24 21:50:231040 for (NavigationResults::const_iterator it = navigation_results.begin();
1041 it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:071042 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:231043 // In the absence of suggested relevance scores, use only the single
1044 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:071045 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:231046 return;
[email protected]257ab712009-04-14 17:16:241047 }
1048}
1049
1050void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
1051 bool is_keyword,
1052 int did_not_accept_suggestion,
1053 MatchMap* map) {
[email protected]51124552011-07-16 01:37:101054 if (results.empty())
1055 return;
1056
[email protected]31afdf72013-09-26 04:29:361057 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]d7ad4772012-06-01 03:12:541058 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1059 (input_.type() == AutocompleteInput::URL);
[email protected]0085863a2013-12-06 21:19:031060 const base::string16& input_text =
[email protected]14710852013-02-05 23:45:411061 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:101062 bool input_multiple_words = HasMultipleWords(input_text);
1063
[email protected]55ce8f12012-05-09 04:44:081064 SuggestResults scored_results;
1065 if (!prevent_inline_autocomplete && input_multiple_words) {
1066 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1067 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:101068 // autocompleting a multi-word, multi-visit query, and the current input is
1069 // still a prefix of it, then changing the autocompletion suddenly feels
1070 // wrong. To detect this case, first score as if only one word has been
1071 // typed, then check for a best result that is an autocompleted, multi-word
1072 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:081073 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1074 false, input_text, is_keyword);
[email protected]9dfb4d362013-04-05 02:15:121075 if ((scored_results.front().relevance() <
[email protected]55ce8f12012-05-09 04:44:081076 AutocompleteResult::kLowestDefaultScore) ||
[email protected]9dfb4d362013-04-05 02:15:121077 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:081078 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:101079 }
[email protected]55ce8f12012-05-09 04:44:081080 if (scored_results.empty())
1081 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1082 input_multiple_words, input_text,
1083 is_keyword);
1084 for (SuggestResults::const_iterator i(scored_results.begin());
1085 i != scored_results.end(); ++i) {
[email protected]57482a72014-03-14 22:27:371086 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true, map);
[email protected]51124552011-07-16 01:37:101087 }
[email protected]31afdf72013-09-26 04:29:361088 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1089 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:101090}
1091
[email protected]55ce8f12012-05-09 04:44:081092SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:101093 const HistoryResults& results,
1094 bool base_prevent_inline_autocomplete,
1095 bool input_multiple_words,
[email protected]0085863a2013-12-06 21:19:031096 const base::string16& input_text,
[email protected]51124552011-07-16 01:37:101097 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:481098 AutocompleteClassifier* classifier =
1099 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:081100 SuggestResults scored_results;
[email protected]78e5e432013-08-03 02:10:101101 const bool prevent_search_history_inlining =
1102 OmniboxFieldTrial::SearchHistoryPreventInlining(
1103 input_.current_page_classification());
[email protected]257ab712009-04-14 17:16:241104 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1105 ++i) {
[email protected]51124552011-07-16 01:37:101106 // Don't autocomplete multi-word queries that have only been seen once
1107 // unless the user has typed more than one word.
1108 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1109 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
1110
[email protected]ea3b9a502011-04-04 14:19:371111 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:101112 // when typed. For example, if the user searched for "google.com" and types
1113 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1114 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:481115 // NOTE: We don't check this in the following cases:
1116 // * When inline autocomplete is disabled, we won't be inline
1117 // autocompleting this term, so we don't need to worry about confusion as
1118 // much. This also prevents calling Classify() again from inside the
1119 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:101120 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:481121 // * When the user has typed the whole term, the "what you typed" history
1122 // match will outrank us for URL-like inputs anyway, so we need not do
1123 // anything special.
[email protected]51124552011-07-16 01:37:101124 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:371125 AutocompleteMatch match;
[email protected]51abb7b2014-02-09 23:00:081126 classifier->Classify(i->term, false, false,
1127 input_.current_page_classification(), &match, NULL);
[email protected]2905f742011-10-13 03:51:581128 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:461129 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:371130 }
[email protected]51124552011-07-16 01:37:101131
[email protected]78e5e432013-08-03 02:10:101132 int relevance = CalculateRelevanceForHistory(
1133 i->time, is_keyword, !prevent_inline_autocomplete,
1134 prevent_search_history_inlining);
[email protected]2c03c06b2013-12-11 20:45:021135 scored_results.push_back(SuggestResult(
1136 i->term, AutocompleteMatchType::SEARCH_HISTORY, i->term,
[email protected]61f99082014-02-24 02:17:491137 base::string16(), base::string16(), std::string(), std::string(),
1138 is_keyword, relevance, false, false, input_text));
[email protected]257ab712009-04-14 17:16:241139 }
[email protected]51124552011-07-16 01:37:101140
1141 // History returns results sorted for us. However, we may have docked some
1142 // results' scores, so things are no longer in order. Do a stable sort to get
1143 // things back in order without otherwise disturbing results with equal
1144 // scores, then force the scores to be unique, so that the order in which
1145 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081146 std::stable_sort(scored_results.begin(), scored_results.end(),
1147 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101148 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081149 for (SuggestResults::iterator i(scored_results.begin());
1150 i != scored_results.end(); ++i) {
1151 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1152 i->set_relevance(last_relevance - 1);
1153 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101154 }
1155
[email protected]55ce8f12012-05-09 04:44:081156 return scored_results;
[email protected]257ab712009-04-14 17:16:241157}
1158
[email protected]55ce8f12012-05-09 04:44:081159void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
[email protected]987fad782013-08-28 06:23:181160 const std::string& metadata,
[email protected]55ce8f12012-05-09 04:44:081161 MatchMap* map) {
[email protected]9487b392014-02-14 02:48:181162 for (size_t i = 0; i < results.size(); ++i)
[email protected]57482a72014-03-14 22:27:371163 AddMatchToMap(results[i], metadata, i, false, map);
initial.commit09911bf2008-07-26 23:55:291164}
1165
[email protected]d30268a2013-06-25 22:31:071166int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561167 // Use the suggested verbatim relevance score if it is non-negative (valid),
1168 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281169 // and if it won't suppress verbatim, leaving no default provider matches.
1170 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561171 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281172 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561173 // Check for results on each verbatim calculation, as results from older
1174 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231175 bool use_server_relevance =
1176 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281177 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231178 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241179 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231180 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071181 if (relevance_from_server)
1182 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231183 return use_server_relevance ?
1184 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521185}
[email protected]d1f0a7f2012-06-05 10:26:421186
[email protected]382a0642012-06-06 06:13:521187int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471188 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361189 return 250;
[email protected]dab8d52d2013-03-05 07:35:281190 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1191}
[email protected]52d08b12009-10-19 18:42:361192
[email protected]dab8d52d2013-03-05 07:35:281193int SearchProvider::
1194 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291195 switch (input_.type()) {
1196 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361197 case AutocompleteInput::QUERY:
1198 case AutocompleteInput::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131199 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291200
initial.commit09911bf2008-07-26 23:55:291201 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361202 return 850;
initial.commit09911bf2008-07-26 23:55:291203
1204 default:
1205 NOTREACHED();
1206 return 0;
1207 }
1208}
1209
[email protected]d30268a2013-06-25 22:31:071210int SearchProvider::GetKeywordVerbatimRelevance(
1211 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281212 // Use the suggested verbatim relevance score if it is non-negative (valid),
1213 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1214 // and if it won't suppress verbatim, leaving no keyword provider matches.
1215 // Otherwise, if the keyword provider returned no matches and was still able
1216 // to suppress verbatim, the user would have no search/nav matches and may be
1217 // left unable to search using their keyword provider from the omnibox.
1218 // Check for results on each verbatim calculation, as results from older
1219 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231220 bool use_server_relevance =
1221 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281222 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231223 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241224 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231225 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071226 if (relevance_from_server)
1227 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231228 return use_server_relevance ?
1229 keyword_results_.verbatim_relevance :
1230 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1231 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451232}
1233
[email protected]51124552011-07-16 01:37:101234int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231235 const base::Time& time,
[email protected]51124552011-07-16 01:37:101236 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101237 bool use_aggressive_method,
1238 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181239 // The relevance of past searches falls off over time. There are two distinct
1240 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101241 // provider that we want to score aggressively), the score is in the range
1242 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161243 // it's in the range 1200-1299). If the second equation is used the
1244 // relevance of a search 15 minutes ago is discounted 50 points, while the
1245 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231246 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421247 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101248 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181249 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101250 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181251 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161252 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101253 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161254 max_score = 1299;
1255 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181256 std::pow(elapsed_time / autocomplete_time, 2.5));
1257 }
1258 elapsed_time -= autocomplete_time;
1259 }
1260
[email protected]c3a4bd992010-08-18 20:25:011261 const int score_discount =
1262 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291263
[email protected]6c85aa02009-02-27 12:08:091264 // Don't let scores go below 0. Negative relevance scores are meaningful in
1265 // a different way.
initial.commit09911bf2008-07-26 23:55:291266 int base_score;
[email protected]51124552011-07-16 01:37:101267 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361268 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101269 else
1270 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291271 return std::max(0, base_score - score_discount);
1272}
1273
initial.commit09911bf2008-07-26 23:55:291274AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421275 const NavigationResult& navigation) {
[email protected]5889bfb2014-03-19 00:26:481276 base::string16 input;
1277 const bool trimmed_whitespace = base::TrimWhitespace(
1278 navigation.from_keyword_provider() ?
1279 keyword_input_.text() : input_.text(),
1280 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
[email protected]55ce8f12012-05-09 04:44:081281 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]b7f64d742013-05-21 04:04:041282 AutocompleteMatchType::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081283 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551284
[email protected]23db6492014-01-16 02:35:301285 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551286 // without trimming the scheme, so we can find matches at the beginning of the
1287 // scheme.
[email protected]371dab12012-06-01 03:23:551288 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301289 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551290 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301291 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351292 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1293 (!prefix || (match_start != 0));
[email protected]23db6492014-01-16 02:35:301294 const net::FormatUrlTypes format_types =
1295 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551296
[email protected]371dab12012-06-01 03:23:551297 const std::string languages(
1298 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
[email protected]23db6492014-01-16 02:35:301299 size_t inline_autocomplete_offset = (prefix == NULL) ?
1300 base::string16::npos : (match_start + input.length());
[email protected]371dab12012-06-01 03:23:551301 match.fill_into_edit +=
1302 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1303 net::FormatUrl(navigation.url(), languages, format_types,
1304 net::UnescapeRule::SPACES, NULL, NULL,
1305 &inline_autocomplete_offset));
[email protected]14119032013-11-07 08:14:261306 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1307 // Otherwise, user edits to a suggestion would show non-Search results.
1308 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581309 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031310 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261311 ++inline_autocomplete_offset;
1312 }
[email protected]6c94a1022014-02-21 03:48:041313 if (inline_autocomplete_offset != base::string16::npos) {
[email protected]518024c2013-07-19 23:40:251314 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1315 match.inline_autocompletion =
1316 match.fill_into_edit.substr(inline_autocomplete_offset);
1317 }
[email protected]6c94a1022014-02-21 03:48:041318 // An inlineable navsuggestion can only be the default match when there
1319 // is no keyword provider active, lest it appear first and break the user
[email protected]5889bfb2014-03-19 00:26:481320 // out of keyword mode. It can also only be default if either the inline
1321 // autocompletion is empty or we're not preventing inline autocompletion.
1322 // Finally, if we have an inlineable navsuggestion with an inline completion
1323 // that we're not preventing, make sure we didn't trim any whitespace.
1324 // We don't want to claim http://foo.com/bar is inlineable against the
1325 // input "foo.com/b ".
[email protected]6c94a1022014-02-21 03:48:041326 match.allowed_to_be_default_match = navigation.IsInlineable(input) &&
1327 (providers_.GetKeywordProviderURL() == NULL) &&
[email protected]5889bfb2014-03-19 00:26:481328 (match.inline_autocompletion.empty() ||
1329 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
[email protected]371dab12012-06-01 03:23:551330
[email protected]23db6492014-01-16 02:35:301331 match.contents = navigation.match_contents();
1332 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081333 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551334 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1335 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071336
1337 match.RecordAdditionalInfo(
1338 kRelevanceFromServerKey,
1339 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181340 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071341
initial.commit09911bf2008-07-26 23:55:291342 return match;
1343}
[email protected]4ab4c7c2010-11-24 04:49:341344
[email protected]9dfb4d362013-04-05 02:15:121345void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
[email protected]d519d392013-03-27 09:24:461346 // First, determine the maximum score of any keyword query match (verbatim or
1347 // query suggestion).
[email protected]d30268a2013-06-25 22:31:071348 bool relevance_from_server;
1349 int max_query_relevance = GetKeywordVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:241350 if (!keyword_results_.suggest_results.empty()) {
[email protected]d30268a2013-06-25 22:31:071351 const SuggestResult& top_keyword = keyword_results_.suggest_results.front();
1352 const int suggest_relevance = top_keyword.relevance();
1353 if (suggest_relevance > max_query_relevance) {
1354 max_query_relevance = suggest_relevance;
1355 relevance_from_server = top_keyword.relevance_from_server();
1356 } else if (suggest_relevance == max_query_relevance) {
1357 relevance_from_server |= top_keyword.relevance_from_server();
1358 }
[email protected]d519d392013-03-27 09:24:461359 }
1360 // If no query is supposed to appear, then navigational matches cannot
[email protected]9dfb4d362013-04-05 02:15:121361 // be demoted past it. Get rid of suggested relevance scores for
1362 // navsuggestions and introduce the verbatim results again. The keyword
1363 // verbatim match will outscore the navsuggest matches.
1364 if (max_query_relevance == 0) {
[email protected]cc1526e2013-05-17 04:04:241365 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
1366 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
1367 keyword_results_.verbatim_relevance = -1;
1368 default_results_.verbatim_relevance = -1;
[email protected]9dfb4d362013-04-05 02:15:121369 return;
1370 }
[email protected]d519d392013-03-27 09:24:461371 // Now we know we can enforce the minimum score constraint even after
1372 // the navigation matches are demoted. Proceed to demote the navigation
1373 // matches to enforce the query-must-come-first constraint.
[email protected]d519d392013-03-27 09:24:461374 // Cap the relevance score of all results.
[email protected]cc1526e2013-05-17 04:04:241375 for (NavigationResults::iterator it =
1376 keyword_results_.navigation_results.begin();
1377 it != keyword_results_.navigation_results.end(); ++it) {
[email protected]9dfb4d362013-04-05 02:15:121378 if (it->relevance() < max_query_relevance)
1379 return;
1380 max_query_relevance = std::max(max_query_relevance - 1, 0);
1381 it->set_relevance(max_query_relevance);
[email protected]d30268a2013-06-25 22:31:071382 it->set_relevance_from_server(relevance_from_server);
[email protected]d519d392013-03-27 09:24:461383 }
[email protected]d519d392013-03-27 09:24:461384}
1385
[email protected]4ab4c7c2010-11-24 04:49:341386void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331387 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311388 // pending, and we're not waiting on Instant.
[email protected]e1290ee62013-06-26 18:31:151389 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
[email protected]4ab4c7c2010-11-24 04:49:341390}