blob: 2b904b67bb3ce0155c2d13cfb70d675d7eb836d0 [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
hashimoto5f7db4b2014-08-27 02:46:205#include "components/omnibox/search_provider.h"
initial.commit09911bf2008-07-26 23:55:296
[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]20184242014-05-14 02:57:4210#include "base/base64.h"
mpearsond37de7c2015-03-11 01:56:2611#include "base/bind.h"
[email protected]2041cf342010-02-19 03:15:5912#include "base/callback.h"
[email protected]51124552011-07-16 01:37:1013#include "base/i18n/break_iterator.h"
[email protected]503d03872011-05-06 08:36:2614#include "base/i18n/case_conversion.h"
[email protected]ffbec692012-02-26 20:26:4215#include "base/json/json_string_value_serializer.h"
asvitkinea0f05db2015-06-16 21:45:4616#include "base/metrics/histogram_macros.h"
[email protected]f7f41c0e2014-08-11 04:22:2317#include "base/metrics/user_metrics.h"
[email protected]20184242014-05-14 02:57:4218#include "base/rand_util.h"
[email protected]5889bfb2014-03-19 00:26:4819#include "base/strings/string_util.h"
[email protected]135cb802013-06-09 16:44:2020#include "base/strings/utf_string_conversions.h"
[email protected]e3ce70ac2014-06-26 18:34:5621#include "components/history/core/browser/in_memory_database.h"
[email protected]73b2d1e72014-06-25 23:45:3622#include "components/history/core/browser/keyword_search_term.h"
[email protected]3dc75b12014-06-08 00:02:2223#include "components/metrics/proto/omnibox_input_type.pb.h"
Ryo Hashimoto884ad192014-08-28 05:54:3024#include "components/omnibox/autocomplete_provider_client.h"
[email protected]b1c5ab682014-08-07 11:53:1725#include "components/omnibox/autocomplete_provider_listener.h"
[email protected]4b56c602014-08-14 17:02:3126#include "components/omnibox/autocomplete_result.h"
[email protected]02f5e32d2014-08-22 07:44:4627#include "components/omnibox/keyword_provider.h"
[email protected]4c583b62014-08-08 10:37:2328#include "components/omnibox/omnibox_field_trial.h"
jdonnelly7393cee2014-10-31 01:52:5629#include "components/omnibox/suggestion_answer.h"
[email protected]b1c5ab682014-08-07 11:53:1730#include "components/omnibox/url_prefix.h"
[email protected]720b10492014-07-23 08:48:4031#include "components/search/search.h"
[email protected]0915b352014-06-25 19:58:1432#include "components/search_engines/template_url_prepopulate_data.h"
[email protected]bf5c532d2014-07-05 00:29:5333#include "components/search_engines/template_url_service.h"
isherman3be67db2014-10-24 05:57:4434#include "components/variations/net/variations_http_header_provider.h"
[email protected]53f0cab2014-08-18 09:52:2735#include "grit/components_strings.h"
initial.commit09911bf2008-07-26 23:55:2936#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3437#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5538#include "net/base/net_util.h"
[email protected]bd3b4712012-12-18 17:01:3039#include "net/http/http_request_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5340#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2141#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1742#include "ui/base/l10n/l10n_util.h"
[email protected]cca6f392014-05-28 21:32:2643#include "url/url_constants.h"
[email protected]761fa4702013-07-02 15:25:1544#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2945
[email protected]bc8bb0cd2013-06-24 21:50:2346// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3347
[email protected]51124552011-07-16 01:37:1048namespace {
49
[email protected]7706a522012-08-16 17:42:2550// We keep track in a histogram how many suggest requests we send, how
51// many suggest requests we invalidate (e.g., due to a user typing
52// another character), and how many replies we receive.
53// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
54// (excluding the end-of-list enum value)
55// We do not want values of existing enums to change or else it screws
56// up the statistics.
57enum SuggestRequestsHistogramValue {
58 REQUEST_SENT = 1,
59 REQUEST_INVALIDATED,
60 REPLY_RECEIVED,
61 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
62};
63
[email protected]90fe2bb2013-01-15 03:42:1364// The verbatim score for an input which is not an URL.
65const int kNonURLVerbatimRelevance = 1300;
66
[email protected]7706a522012-08-16 17:42:2567// Increments the appropriate value in the histogram by one.
68void LogOmniboxSuggestRequest(
69 SuggestRequestsHistogramValue request_value) {
70 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
71 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
72}
73
[email protected]0085863a2013-12-06 21:19:0374bool HasMultipleWords(const base::string16& text) {
[email protected]51124552011-07-16 01:37:1075 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
76 bool found_word = false;
77 if (i.Init()) {
78 while (i.Advance()) {
79 if (i.IsWord()) {
80 if (found_word)
81 return true;
82 found_word = true;
83 }
84 }
85 }
86 return false;
87}
88
[email protected]d1f0a7f2012-06-05 10:26:4289} // namespace
[email protected]51124552011-07-16 01:37:1090
[email protected]3954c3a2012-04-10 20:17:5591// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:5892
[email protected]85b8d6f2012-05-08 20:53:4793SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
[email protected]02346202014-02-05 05:18:3094 : template_url_service_(template_url_service) {}
[email protected]85b8d6f2012-05-08 20:53:4795
96const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
97 return default_provider_.empty() ? NULL :
98 template_url_service_->GetTemplateURLForKeyword(default_provider_);
99}
100
101const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
102 return keyword_provider_.empty() ? NULL :
103 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24104}
105
[email protected]3954c3a2012-04-10 20:17:55106
[email protected]bc8bb0cd2013-06-24 21:50:23107// SearchProvider::CompareScoredResults ---------------------------------------
108
109class SearchProvider::CompareScoredResults {
110 public:
[email protected]0b9575f2014-07-30 11:58:37111 bool operator()(const SearchSuggestionParser::Result& a,
112 const SearchSuggestionParser::Result& b) {
[email protected]bc8bb0cd2013-06-24 21:50:23113 // Sort in descending relevance order.
114 return a.relevance() > b.relevance();
115 }
116};
117
118
[email protected]3954c3a2012-04-10 20:17:55119// SearchProvider -------------------------------------------------------------
120
blundell55e35e82015-06-16 08:46:18121SearchProvider::SearchProvider(AutocompleteProviderClient* client,
blundelld130d592015-06-21 19:29:13122 AutocompleteProviderListener* listener)
123 : BaseSearchProvider(AutocompleteProvider::TYPE_SEARCH, client),
[email protected]776ee5902014-08-11 09:15:19124 listener_(listener),
blundelld130d592015-06-21 19:29:13125 providers_(client->GetTemplateURLService()),
groby1dbb8e22014-09-23 21:50:26126 answers_cache_(10) {
blundelld130d592015-06-21 19:29:13127 TemplateURLService* template_url_service = client->GetTemplateURLService();
128
129 // |template_url_service| can be null in tests.
130 if (template_url_service)
131 template_url_service->AddObserver(this);
[email protected]bc8bb0cd2013-06-24 21:50:23132}
133
[email protected]cb86ee6f2013-04-28 16:58:15134// static
[email protected]987fad782013-08-28 06:23:18135std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
136 return match.GetAdditionalInfo(kSuggestMetadataKey);
137}
138
[email protected]bc8bb0cd2013-06-24 21:50:23139void SearchProvider::ResetSession() {
blundelld130d592015-06-21 19:29:13140 set_field_trial_triggered_in_session(false);
[email protected]4ab4c7c2010-11-24 04:49:34141}
142
mpearson84f19a152015-03-12 19:42:21143void SearchProvider::OnTemplateURLServiceChanged() {
144 // Only update matches at this time if we haven't already claimed we're done
145 // processing the query.
146 if (done_)
147 return;
148
149 // Check that the engines we're using weren't renamed or deleted. (In short,
150 // require that an engine still exists with the keywords in use.) For each
151 // deleted engine, cancel the in-flight request if any, drop its suggestions,
152 // and, in the case when the default provider was affected, point the cached
153 // default provider keyword name at the new name for the default provider.
154
155 // Get...ProviderURL() looks up the provider using the cached keyword name
156 // stored in |providers_|.
157 const TemplateURL* template_url = providers_.GetDefaultProviderURL();
158 if (!template_url) {
159 CancelFetcher(&default_fetcher_);
160 default_results_.Clear();
blundelld130d592015-06-21 19:29:13161 providers_.set(client()
162 ->GetTemplateURLService()
163 ->GetDefaultSearchProvider()
164 ->keyword(),
mpearson84f19a152015-03-12 19:42:21165 providers_.keyword_provider());
166 }
167 template_url = providers_.GetKeywordProviderURL();
168 if (!providers_.keyword_provider().empty() && !template_url) {
169 CancelFetcher(&keyword_fetcher_);
170 keyword_results_.Clear();
171 providers_.set(providers_.default_provider(), base::string16());
172 }
173 // It's possible the template URL changed without changing associated keyword.
174 // Hence, it's always necessary to update matches to use the new template
175 // URL. (One could cache the template URL and only call UpdateMatches() and
176 // OnProviderUpdate() if a keyword was deleted/renamed or the template URL
177 // was changed. That would save extra calls to these functions. However,
178 // this is uncommon and not likely to be worth the extra work.)
179 UpdateMatches();
180 listener_->OnProviderUpdate(true); // always pretend something changed
181}
182
[email protected]bc8bb0cd2013-06-24 21:50:23183SearchProvider::~SearchProvider() {
blundelld130d592015-06-21 19:29:13184 TemplateURLService* template_url_service = client()->GetTemplateURLService();
185 if (template_url_service)
186 template_url_service->RemoveObserver(this);
[email protected]bc8bb0cd2013-06-24 21:50:23187}
188
[email protected]ee6110b2014-01-09 22:26:31189// static
[email protected]bc8bb0cd2013-06-24 21:50:23190int SearchProvider::CalculateRelevanceForKeywordVerbatim(
[email protected]332d17d22014-06-20 16:56:03191 metrics::OmniboxInputType::Type type,
[email protected]bc8bb0cd2013-06-24 21:50:23192 bool prefer_keyword) {
193 // This function is responsible for scoring verbatim query matches
194 // for non-extension keywords. KeywordProvider::CalculateRelevance()
195 // scores verbatim query matches for extension keywords, as well as
196 // for keyword matches (i.e., suggestions of a keyword itself, not a
197 // suggestion of a query on a keyword search engine). These two
198 // functions are currently in sync, but there's no reason we
199 // couldn't decide in the future to score verbatim matches
200 // differently for extension and non-extension keywords. If you
201 // make such a change, however, you should update this comment to
202 // describe it, so it's clear why the functions diverge.
203 if (prefer_keyword)
204 return 1500;
[email protected]3dc75b12014-06-08 00:02:22205 return (type == metrics::OmniboxInputType::QUERY) ? 1450 : 1100;
[email protected]bc8bb0cd2013-06-24 21:50:23206}
207
mpearson6c183672014-09-03 02:09:42208// static
209void SearchProvider::UpdateOldResults(
210 bool minimal_changes,
211 SearchSuggestionParser::Results* results) {
212 // When called without |minimal_changes|, it likely means the user has
213 // pressed a key. Revise the cached results appropriately.
214 if (!minimal_changes) {
215 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
216 results->suggest_results.begin();
217 sug_it != results->suggest_results.end(); ++sug_it) {
218 sug_it->set_received_after_last_keystroke(false);
219 }
220 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
221 results->navigation_results.begin();
222 nav_it != results->navigation_results.end(); ++nav_it) {
223 nav_it->set_received_after_last_keystroke(false);
224 }
225 }
226}
227
228// static
229ACMatches::iterator SearchProvider::FindTopMatch(ACMatches* matches) {
230 ACMatches::iterator it = matches->begin();
231 while ((it != matches->end()) && !it->allowed_to_be_default_match)
232 ++it;
233 return it;
234}
235
initial.commit09911bf2008-07-26 23:55:29236void SearchProvider::Start(const AutocompleteInput& input,
jifcf322cd2015-06-17 11:01:18237 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55238 // Do our best to load the model as early as possible. This will reduce
239 // odds of having the model not ready when really needed (a non-empty input).
blundelld130d592015-06-21 19:29:13240 TemplateURLService* model = client()->GetTemplateURLService();
[email protected]04504c242013-01-22 21:08:55241 DCHECK(model);
242 model->Load();
243
initial.commit09911bf2008-07-26 23:55:29244 matches_.clear();
blundelld130d592015-06-21 19:29:13245 set_field_trial_triggered(false);
initial.commit09911bf2008-07-26 23:55:29246
hashimoto663b9f42014-08-26 04:29:20247 // Can't return search/suggest results for bogus input.
jifcf322cd2015-06-17 11:01:18248 if (input.from_omnibox_focus() ||
mariakhomenko3ef531d72015-01-10 00:03:43249 input.type() == metrics::OmniboxInputType::INVALID) {
mpearson8a37c382015-03-07 05:58:57250 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29251 return;
252 }
253
[email protected]14710852013-02-05 23:45:41254 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24255 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41256 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
257 &keyword_input_);
258 if (keyword_provider == NULL)
259 keyword_input_.Clear();
260 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24261 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24262
[email protected]85b8d6f2012-05-08 20:53:47263 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]ce7ee5f2014-06-16 23:41:19264 if (default_provider &&
265 !default_provider->SupportsReplacement(model->search_terms_data()))
[email protected]257ab712009-04-14 17:16:24266 default_provider = NULL;
267
268 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18269 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24270
271 if (!default_provider && !keyword_provider) {
272 // No valid providers.
mpearson8a37c382015-03-07 05:58:57273 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29274 return;
275 }
276
277 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24278 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03279 base::string16 default_provider_keyword(default_provider ?
280 default_provider->keyword() : base::string16());
281 base::string16 keyword_provider_keyword(keyword_provider ?
282 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32283 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47284 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29285 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15286 if (!done_)
mpearson8a37c382015-03-07 05:58:57287 Stop(false, false);
[email protected]257ab712009-04-14 17:16:24288 }
initial.commit09911bf2008-07-26 23:55:29289
[email protected]85b8d6f2012-05-08 20:53:47290 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29291
292 if (input.text().empty()) {
293 // User typed "?" alone. Give them a placeholder result indicating what
294 // this syntax does.
[email protected]257ab712009-04-14 17:16:24295 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00296 AutocompleteMatch match;
297 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36298 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24299 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35300 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47301 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36302 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24303 matches_.push_back(match);
304 }
mpearson8a37c382015-03-07 05:58:57305 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29306 return;
307 }
308
309 input_ = input;
310
[email protected]e1290ee62013-06-26 18:31:15311 DoHistoryQuery(minimal_changes);
grobye5fcee42014-09-26 03:36:46312 // Answers needs scored history results before any suggest query has been
313 // started, since the query for answer-bearing results needs additional
314 // prefetch information based on the highest-scored local history result.
315 if (OmniboxFieldTrial::EnableAnswersInSuggest()) {
316 ScoreHistoryResults(raw_default_history_results_,
317 false,
318 &transformed_default_history_results_);
319 ScoreHistoryResults(raw_keyword_history_results_,
320 true,
321 &transformed_keyword_history_results_);
322 prefetch_data_ = FindAnswersPrefetchData();
323
324 // Raw results are not needed any more.
325 raw_default_history_results_.clear();
326 raw_keyword_history_results_.clear();
grobye5fcee42014-09-26 03:36:46327 }
328
[email protected]e1290ee62013-06-26 18:31:15329 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42330 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29331}
332
mpearson8a37c382015-03-07 05:58:57333void SearchProvider::Stop(bool clear_cached_results,
334 bool due_to_user_inactivity) {
[email protected]ec3f679b2014-08-18 07:45:13335 StopSuggest();
336 done_ = true;
337
338 if (clear_cached_results)
339 ClearAllResults();
340}
341
[email protected]776ee5902014-08-11 09:15:19342const TemplateURL* SearchProvider::GetTemplateURL(bool is_keyword) const {
343 return is_keyword ? providers_.GetKeywordProviderURL()
344 : providers_.GetDefaultProviderURL();
345}
346
347const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
348 return is_keyword ? keyword_input_ : input_;
349}
350
351bool SearchProvider::ShouldAppendExtraParams(
352 const SearchSuggestionParser::SuggestResult& result) const {
353 return !result.from_keyword_provider() ||
354 providers_.default_provider().empty();
355}
356
[email protected]776ee5902014-08-11 09:15:19357void SearchProvider::RecordDeletionResult(bool success) {
358 if (success) {
359 base::RecordAction(
360 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
361 } else {
362 base::RecordAction(
363 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
364 }
365}
366
367void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
368 DCHECK(!done_);
[email protected]776ee5902014-08-11 09:15:19369 const bool is_keyword = source == keyword_fetcher_.get();
370
371 // Ensure the request succeeded and that the provider used is still available.
372 // A verbatim match cannot be generated without this provider, causing errors.
373 const bool request_succeeded =
374 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
375 GetTemplateURL(is_keyword);
376
377 LogFetchComplete(request_succeeded, is_keyword);
378
379 bool results_updated = false;
380 if (request_succeeded) {
381 scoped_ptr<base::Value> data(SearchSuggestionParser::DeserializeJsonData(
382 SearchSuggestionParser::ExtractJsonData(source)));
383 if (data) {
384 SearchSuggestionParser::Results* results =
385 is_keyword ? &keyword_results_ : &default_results_;
386 results_updated = ParseSuggestResults(*data, -1, is_keyword, results);
387 if (results_updated)
388 SortResults(is_keyword, results);
389 }
390 }
mpearson84f19a152015-03-12 19:42:21391
392 // Delete the fetcher now that we're done with it.
393 if (is_keyword)
394 keyword_fetcher_.reset();
395 else
396 default_fetcher_.reset();
397
398 // Update matches, done status, etc., and send alerts if necessary.
[email protected]776ee5902014-08-11 09:15:19399 UpdateMatches();
400 if (done_ || results_updated)
401 listener_->OnProviderUpdate(results_updated);
402}
403
[email protected]ec3f679b2014-08-18 07:45:13404void SearchProvider::StopSuggest() {
mpearson84f19a152015-03-12 19:42:21405 CancelFetcher(&default_fetcher_);
406 CancelFetcher(&keyword_fetcher_);
[email protected]ec3f679b2014-08-18 07:45:13407 timer_.Stop();
[email protected]ec3f679b2014-08-18 07:45:13408}
409
410void SearchProvider::ClearAllResults() {
411 keyword_results_.Clear();
412 default_results_.Clear();
413}
414
[email protected]776ee5902014-08-11 09:15:19415void SearchProvider::UpdateMatchContentsClass(
416 const base::string16& input_text,
417 SearchSuggestionParser::Results* results) {
418 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
419 results->suggest_results.begin();
420 sug_it != results->suggest_results.end(); ++sug_it) {
421 sug_it->ClassifyMatchContents(false, input_text);
422 }
blundelld130d592015-06-21 19:29:13423 const std::string languages(client()->GetAcceptLanguages());
[email protected]776ee5902014-08-11 09:15:19424 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
425 results->navigation_results.begin();
426 nav_it != results->navigation_results.end(); ++nav_it) {
427 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
428 }
429}
430
[email protected]d4a94b92014-03-04 01:35:22431void SearchProvider::SortResults(bool is_keyword,
[email protected]0b9575f2014-07-30 11:58:37432 SearchSuggestionParser::Results* results) {
[email protected]d4a94b92014-03-04 01:35:22433 // Ignore suggested scores for non-keyword matches in keyword mode; if the
434 // server is allowed to score these, it could interfere with the user's
435 // ability to get good keyword results.
436 const bool abandon_suggested_scores =
437 !is_keyword && !providers_.keyword_provider().empty();
[email protected]0b9575f2014-07-30 11:58:37438 // Apply calculated relevance scores to suggestions if valid relevances were
[email protected]d4a94b92014-03-04 01:35:22439 // not provided or we're abandoning suggested scores entirely.
[email protected]2c802d12014-07-31 12:57:14440 if (!results->relevances_from_server || abandon_suggested_scores) {
[email protected]d4a94b92014-03-04 01:35:22441 ApplyCalculatedSuggestRelevance(&results->suggest_results);
442 ApplyCalculatedNavigationRelevance(&results->navigation_results);
443 // If abandoning scores entirely, also abandon the verbatim score.
444 if (abandon_suggested_scores)
445 results->verbatim_relevance = -1;
446 }
447
448 // Keep the result lists sorted.
449 const CompareScoredResults comparator = CompareScoredResults();
450 std::stable_sort(results->suggest_results.begin(),
451 results->suggest_results.end(),
452 comparator);
453 std::stable_sort(results->navigation_results.begin(),
454 results->navigation_results.end(),
455 comparator);
456}
457
[email protected]cfa164bf2014-03-19 11:51:15458void SearchProvider::LogFetchComplete(bool success, bool is_keyword) {
459 LogOmniboxSuggestRequest(REPLY_RECEIVED);
460 // Record response time for suggest requests sent to Google. We care
461 // only about the common case: the Google default provider used in
462 // non-keyword mode.
463 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
464 if (!is_keyword && default_url &&
[email protected]ce7ee5f2014-06-16 23:41:19465 (TemplateURLPrepopulateData::GetEngineType(
blundelld130d592015-06-21 19:29:13466 *default_url,
467 client()->GetTemplateURLService()->search_terms_data()) ==
[email protected]cfa164bf2014-03-19 11:51:15468 SEARCH_ENGINE_GOOGLE)) {
469 const base::TimeDelta elapsed_time =
470 base::TimeTicks::Now() - time_suggest_request_sent_;
471 if (success) {
472 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
473 elapsed_time);
474 } else {
475 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
476 elapsed_time);
477 }
478 }
479}
480
[email protected]cfa164bf2014-03-19 11:51:15481void SearchProvider::UpdateMatches() {
mpearson6c183672014-09-03 02:09:42482 PersistTopSuggestions(&default_results_);
483 PersistTopSuggestions(&keyword_results_);
[email protected]cfa164bf2014-03-19 11:51:15484 ConvertResultsToAutocompleteMatches();
485
486 // Check constraints that may be violated by suggested relevances.
487 if (!matches_.empty() &&
488 (default_results_.HasServerProvidedScores() ||
489 keyword_results_.HasServerProvidedScores())) {
490 // These blocks attempt to repair undesirable behavior by suggested
491 // relevances with minimal impact, preserving other suggested relevances.
[email protected]d0e4ad02014-08-22 18:58:33492 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
493 const bool is_extension_keyword = (keyword_url != NULL) &&
494 (keyword_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION);
495 if ((keyword_url != NULL) && !is_extension_keyword &&
[email protected]7bc5e162014-08-15 19:41:11496 (FindTopMatch() == matches_.end())) {
[email protected]d0e4ad02014-08-22 18:58:33497 // In non-extension keyword mode, disregard the keyword verbatim suggested
498 // relevance if necessary, so at least one match is allowed to be default.
499 // (In extension keyword mode this is not necessary because the extension
mpearson6c183672014-09-03 02:09:42500 // will return a default match.) Give keyword verbatim the lowest
501 // non-zero score to best reflect what the server desired.
502 DCHECK_EQ(0, keyword_results_.verbatim_relevance);
503 keyword_results_.verbatim_relevance = 1;
[email protected]cfa164bf2014-03-19 11:51:15504 ConvertResultsToAutocompleteMatches();
505 }
[email protected]89bd27d12014-04-12 17:36:23506 if (IsTopMatchSearchWithURLInput()) {
[email protected]cfa164bf2014-03-19 11:51:15507 // Disregard the suggested search and verbatim relevances if the input
508 // type is URL and the top match is a highly-ranked search suggestion.
509 // For example, prevent a search for "foo.com" from outranking another
510 // provider's navigation for "foo.com" or "foo.com/url_from_history".
511 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
512 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
513 default_results_.verbatim_relevance = -1;
514 keyword_results_.verbatim_relevance = -1;
515 ConvertResultsToAutocompleteMatches();
516 }
[email protected]d0e4ad02014-08-22 18:58:33517 if (!is_extension_keyword && (FindTopMatch() == matches_.end())) {
518 // Guarantee that SearchProvider returns a legal default match (except
519 // when in extension-based keyword mode). The omnibox always needs at
520 // least one legal default match, and it relies on SearchProvider in
521 // combination with KeywordProvider (for extension-based keywords) to
mpearson6c183672014-09-03 02:09:42522 // always return one. Give the verbatim suggestion the lowest non-zero
523 // scores to best reflect what the server desired.
524 DCHECK_EQ(0, default_results_.verbatim_relevance);
525 default_results_.verbatim_relevance = 1;
526 // We do not have to alter keyword_results_.verbatim_relevance here.
527 // If the user is in keyword mode, we already reverted (earlier in this
528 // function) the instructions to suppress keyword verbatim.
[email protected]cfa164bf2014-03-19 11:51:15529 ConvertResultsToAutocompleteMatches();
530 }
[email protected]89bd27d12014-04-12 17:36:23531 DCHECK(!IsTopMatchSearchWithURLInput());
[email protected]d0e4ad02014-08-22 18:58:33532 DCHECK(is_extension_keyword || (FindTopMatch() != matches_.end()));
[email protected]cfa164bf2014-03-19 11:51:15533 }
534 UMA_HISTOGRAM_CUSTOM_COUNTS(
535 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
mpearson6c183672014-09-03 02:09:42536
537 // Record the top suggestion (if any) for future use.
538 top_query_suggestion_match_contents_ = base::string16();
539 top_navigation_suggestion_ = GURL();
540 ACMatches::const_iterator first_match = FindTopMatch();
541 if ((first_match != matches_.end()) &&
542 !first_match->inline_autocompletion.empty()) {
543 // Identify if this match came from a query suggestion or a navsuggestion.
544 // In either case, extracts the identifying feature of the suggestion
545 // (query string or navigation url).
546 if (AutocompleteMatch::IsSearchType(first_match->type))
547 top_query_suggestion_match_contents_ = first_match->contents;
548 else
549 top_navigation_suggestion_ = first_match->destination_url;
550 }
551
[email protected]cfa164bf2014-03-19 11:51:15552 UpdateDone();
[email protected]cfa164bf2014-03-19 11:51:15553}
554
mpearsond37de7c2015-03-11 01:56:26555void SearchProvider::Run(bool query_is_private) {
[email protected]bc8bb0cd2013-06-24 21:50:23556 // Start a new request with the current input.
mpearson84f19a152015-03-12 19:42:21557 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05558
mpearsond37de7c2015-03-11 01:56:26559 if (!query_is_private) {
dtapuskadafcf892015-05-01 13:58:25560 default_fetcher_ =
561 CreateSuggestFetcher(kDefaultProviderURLFetcherID,
562 providers_.GetDefaultProviderURL(), input_);
mpearsond37de7c2015-03-11 01:56:26563 }
dtapuskadafcf892015-05-01 13:58:25564 keyword_fetcher_ =
565 CreateSuggestFetcher(kKeywordProviderURLFetcherID,
566 providers_.GetKeywordProviderURL(), keyword_input_);
[email protected]bc8bb0cd2013-06-24 21:50:23567
568 // Both the above can fail if the providers have been modified or deleted
569 // since the query began.
mpearson84f19a152015-03-12 19:42:21570 if (!default_fetcher_ && !keyword_fetcher_) {
[email protected]bc8bb0cd2013-06-24 21:50:23571 UpdateDone();
572 // We only need to update the listener if we're actually done.
573 if (done_)
574 listener_->OnProviderUpdate(false);
mpearsond37de7c2015-03-11 01:56:26575 } else {
576 // Sent at least one request.
577 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]bc8bb0cd2013-06-24 21:50:23578 }
[email protected]601858c02010-09-01 17:08:20579}
580
[email protected]8d457132010-11-04 18:13:40581void SearchProvider::DoHistoryQuery(bool minimal_changes) {
582 // The history query results are synchronous, so if minimal_changes is true,
583 // we still have the last results and don't need to do anything.
584 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29585 return;
586
grobye5fcee42014-09-26 03:36:46587 raw_keyword_history_results_.clear();
588 raw_default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29589
[email protected]78e5e432013-08-03 02:10:10590 if (OmniboxFieldTrial::SearchHistoryDisable(
591 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16592 return;
593
blundelld130d592015-06-21 19:29:13594 history::URLDatabase* url_db = client()->GetInMemoryDatabase();
[email protected]8d457132010-11-04 18:13:40595 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29596 return;
597
[email protected]51124552011-07-16 01:37:10598 // Request history for both the keyword and default provider. We grab many
599 // more matches than we'll ultimately clamp to so that if there are several
600 // recent multi-word matches who scores are lowered (see
grobye5fcee42014-09-26 03:36:46601 // ScoreHistoryResults()), they won't crowd out older, higher-scoring
[email protected]51124552011-07-16 01:37:10602 // matches. Note that this doesn't fix the problem entirely, but merely
603 // limits it to cases with a very large number of such multi-word matches; for
604 // now, this seems OK compared with the complexity of a real fix, which would
605 // require multiple searches and tracking of "single- vs. multi-word" in the
606 // database.
607 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47608 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
609 if (default_url) {
[email protected]b4bec972014-04-05 18:07:15610 const base::TimeTicks start_time = base::TimeTicks::Now();
grobye5fcee42014-09-26 03:36:46611 url_db->GetMostRecentKeywordSearchTerms(default_url->id(),
612 input_.text(),
613 num_matches,
614 &raw_default_history_results_);
[email protected]31afdf72013-09-26 04:29:36615 UMA_HISTOGRAM_TIMES(
616 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
617 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24618 }
[email protected]85b8d6f2012-05-08 20:53:47619 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
620 if (keyword_url) {
621 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
grobye5fcee42014-09-26 03:36:46622 keyword_input_.text(),
623 num_matches,
624 &raw_keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55625 }
initial.commit09911bf2008-07-26 23:55:29626}
627
bartn1c07e722014-10-27 19:34:24628base::TimeDelta SearchProvider::GetSuggestQueryDelay() const {
629 bool from_last_keystroke;
630 int polling_delay_ms;
631 OmniboxFieldTrial::GetSuggestPollingStrategy(&from_last_keystroke,
632 &polling_delay_ms);
633
634 base::TimeDelta delay(base::TimeDelta::FromMilliseconds(polling_delay_ms));
635 if (from_last_keystroke)
636 return delay;
637
638 base::TimeDelta time_since_last_suggest_request =
639 base::TimeTicks::Now() - time_suggest_request_sent_;
640 return std::max(base::TimeDelta(), delay - time_since_last_suggest_request);
641}
642
[email protected]6dc950f2012-07-16 19:49:08643void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
mpearsond37de7c2015-03-11 01:56:26644 bool query_is_private;
645 if (!IsQuerySuitableForSuggest(&query_is_private)) {
initial.commit09911bf2008-07-26 23:55:29646 StopSuggest();
[email protected]71b46152013-05-03 16:39:20647 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29648 return;
649 }
650
bartn1c07e722014-10-27 19:34:24651 if (OmniboxFieldTrial::DisableResultsCaching())
652 ClearAllResults();
653
initial.commit09911bf2008-07-26 23:55:29654 // For the minimal_changes case, if we finished the previous query and still
655 // have its results, or are allowed to keep running it, just do that, rather
656 // than starting a new query.
657 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24658 (!default_results_.suggest_results.empty() ||
659 !default_results_.navigation_results.empty() ||
660 !keyword_results_.suggest_results.empty() ||
661 !keyword_results_.navigation_results.empty() ||
[email protected]a2770a7d2014-04-22 19:33:35662 (!done_ && input_.want_asynchronous_matches())))
initial.commit09911bf2008-07-26 23:55:29663 return;
664
665 // We can't keep running any previous query, so halt it.
666 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42667
mpearson6c183672014-09-03 02:09:42668 UpdateAllOldResults(minimal_changes);
initial.commit09911bf2008-07-26 23:55:29669
[email protected]ee6110b2014-01-09 22:26:31670 // Update the content classifications of remaining results so they look good
671 // against the current input.
[email protected]23db6492014-01-16 02:35:30672 UpdateMatchContentsClass(input_.text(), &default_results_);
673 if (!keyword_input_.text().empty())
674 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31675
initial.commit09911bf2008-07-26 23:55:29676 // We can't start a new query if we're only allowed synchronous results.
[email protected]a2770a7d2014-04-22 19:33:35677 if (!input_.want_asynchronous_matches())
initial.commit09911bf2008-07-26 23:55:29678 return;
679
bartn1c07e722014-10-27 19:34:24680 // Kick off a timer that will start the URL fetch if it completes before
681 // the user types another character. Requests may be delayed to avoid
682 // flooding the server with requests that are likely to be thrown away later
683 // anyway.
684 const base::TimeDelta delay = GetSuggestQueryDelay();
685 if (delay <= base::TimeDelta()) {
mpearsond37de7c2015-03-11 01:56:26686 Run(query_is_private);
[email protected]515ffa942012-11-27 20:18:24687 return;
688 }
mpearsond37de7c2015-03-11 01:56:26689 timer_.Start(FROM_HERE,
690 delay,
691 base::Bind(&SearchProvider::Run,
692 base::Unretained(this),
693 query_is_private));
initial.commit09911bf2008-07-26 23:55:29694}
695
mpearson84f19a152015-03-12 19:42:21696void SearchProvider::CancelFetcher(scoped_ptr<net::URLFetcher>* fetcher) {
697 if (*fetcher) {
698 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
699 fetcher->reset();
700 }
701}
702
mpearsond37de7c2015-03-11 01:56:26703bool SearchProvider::IsQuerySuitableForSuggest(bool* query_is_private) const {
704 *query_is_private = IsQueryPotentionallyPrivate();
705
[email protected]3954c3a2012-04-10 20:17:55706 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
mpearsond37de7c2015-03-11 01:56:26707 // if the user has disabled it. Also don't send potentionally private data
708 // to the default search provider. (It's always okay to send explicit
709 // keyword input to a keyword suggest server, if any.)
[email protected]85b8d6f2012-05-08 20:53:47710 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
711 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
blundelld130d592015-06-21 19:29:13712 return !client()->IsOffTheRecord() && client()->SearchSuggestEnabled() &&
713 ((default_url && !default_url->suggestions_url().empty() &&
714 !*query_is_private) ||
715 (keyword_url && !keyword_url->suggestions_url().empty()));
mpearsond37de7c2015-03-11 01:56:26716}
[email protected]83c726482008-09-10 06:36:34717
mpearsond37de7c2015-03-11 01:56:26718bool SearchProvider::IsQueryPotentionallyPrivate() const {
[email protected]cac59d32010-08-09 23:23:14719 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34720 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34721
[email protected]cac59d32010-08-09 23:23:14722 // FORCED_QUERY means the user is explicitly asking us to search for this, so
723 // we assume it isn't a URL and/or there isn't private data.
[email protected]3dc75b12014-06-08 00:02:22724 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY)
mpearsond37de7c2015-03-11 01:56:26725 return false;
[email protected]83c726482008-09-10 06:36:34726
[email protected]f608ea102013-03-18 15:08:09727 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
728 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
729 // is both a waste of time and a disclosure of potentially private, local
730 // data. Other "schemes" may actually be usernames, and we don't want to send
731 // passwords. If the scheme is OK, we still need to check other cases below.
732 // If this is QUERY, then the presence of these schemes means the user
733 // explicitly typed one, and thus this is probably a URL that's being entered
734 // and happens to currently be invalid -- in which case we again want to run
735 // our checks below. Other QUERY cases are less likely to be URLs and thus we
736 // assume we're OK.
brettwbc17d2c82015-06-09 22:39:08737 if (!base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpScheme) &&
738 !base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
739 !base::LowerCaseEqualsASCII(input_.scheme(), url::kFtpScheme))
mpearsond37de7c2015-03-11 01:56:26740 return (input_.type() != metrics::OmniboxInputType::QUERY);
[email protected]cac59d32010-08-09 23:23:14741
742 // Don't send URLs with usernames, queries or refs. Some of these are
743 // private, and the Suggest server is unlikely to have any useful results
744 // for any of them. Also don't send URLs with ports, as we may initially
745 // think that a username + password is a host + port (and we don't want to
746 // send usernames/passwords), and even if the port really is a port, the
747 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58748 // Note that we only block based on refs if the input is URL-typed, as search
749 // queries can legitimately have #s in them which the URL parser
750 // overaggressively categorizes as a url with a ref.
[email protected]b45334502014-04-30 19:44:05751 const url::Parsed& parts = input_.parts();
[email protected]cac59d32010-08-09 23:23:14752 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58753 parts.query.is_nonempty() ||
[email protected]3dc75b12014-06-08 00:02:22754 (parts.ref.is_nonempty() &&
755 (input_.type() == metrics::OmniboxInputType::URL)))
mpearsond37de7c2015-03-11 01:56:26756 return true;
[email protected]cac59d32010-08-09 23:23:14757
758 // Don't send anything for https except the hostname. Hostnames are OK
759 // because they are visible when the TCP connection is established, but the
760 // specific path may reveal private information.
brettwbc17d2c82015-06-09 22:39:08761 if (base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36762 parts.path.is_nonempty())
mpearsond37de7c2015-03-11 01:56:26763 return true;
[email protected]83c726482008-09-10 06:36:34764
mpearsond37de7c2015-03-11 01:56:26765 return false;
[email protected]83c726482008-09-10 06:36:34766}
767
mpearson6c183672014-09-03 02:09:42768void SearchProvider::UpdateAllOldResults(bool minimal_changes) {
[email protected]dc735c02013-11-12 23:23:41769 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51770 // User is either in keyword mode with a blank input or out of
771 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24772 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51773 }
mpearson6c183672014-09-03 02:09:42774 UpdateOldResults(minimal_changes, &default_results_);
775 UpdateOldResults(minimal_changes, &keyword_results_);
[email protected]d1f0a7f2012-06-05 10:26:42776}
777
mpearson6c183672014-09-03 02:09:42778void SearchProvider::PersistTopSuggestions(
779 SearchSuggestionParser::Results* results) {
780 // Mark any results matching the current top results as having been received
781 // prior to the last keystroke. That prevents asynchronous updates from
782 // clobbering top results, which may be used for inline autocompletion.
783 // Other results don't need similar changes, because they shouldn't be
784 // displayed asynchronously anyway.
785 if (!top_query_suggestion_match_contents_.empty()) {
786 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
787 results->suggest_results.begin();
788 sug_it != results->suggest_results.end(); ++sug_it) {
789 if (sug_it->match_contents() == top_query_suggestion_match_contents_)
790 sug_it->set_received_after_last_keystroke(false);
791 }
792 }
793 if (top_navigation_suggestion_.is_valid()) {
794 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
795 results->navigation_results.begin();
796 nav_it != results->navigation_results.end(); ++nav_it) {
797 if (nav_it->url() == top_navigation_suggestion_)
798 nav_it->set_received_after_last_keystroke(false);
799 }
800 }
[email protected]d1f0a7f2012-06-05 10:26:42801}
802
[email protected]0b9575f2014-07-30 11:58:37803void SearchProvider::ApplyCalculatedSuggestRelevance(
804 SearchSuggestionParser::SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42805 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37806 SearchSuggestionParser::SuggestResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42807 result.set_relevance(
808 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
809 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07810 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42811 }
812}
813
[email protected]188b50c2013-03-28 07:19:42814void SearchProvider::ApplyCalculatedNavigationRelevance(
[email protected]0b9575f2014-07-30 11:58:37815 SearchSuggestionParser::NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42816 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37817 SearchSuggestionParser::NavigationResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42818 result.set_relevance(
819 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
820 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07821 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42822 }
823}
824
dtapuskadafcf892015-05-01 13:58:25825scoped_ptr<net::URLFetcher> SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12826 int id,
[email protected]9ff91722012-09-07 05:29:12827 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41828 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12829 if (!template_url || template_url->suggestions_url().empty())
830 return NULL;
831
832 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41833 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
[email protected]420472b22014-06-10 13:34:43834 search_term_args.input_type = input.type();
[email protected]14710852013-02-05 23:45:41835 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18836 search_term_args.page_classification = input.current_page_classification();
[email protected]2ef2a6642014-07-30 05:50:29837 if (OmniboxFieldTrial::EnableAnswersInSuggest()) {
[email protected]20184242014-05-14 02:57:42838 search_term_args.session_token = GetSessionToken();
[email protected]2ef2a6642014-07-30 05:50:29839 if (!prefetch_data_.full_query_text.empty()) {
840 search_term_args.prefetch_query =
[email protected]ebbac63e2014-08-22 01:43:06841 base::UTF16ToUTF8(prefetch_data_.full_query_text);
[email protected]2ef2a6642014-07-30 05:50:29842 search_term_args.prefetch_query_type =
[email protected]ebbac63e2014-08-22 01:43:06843 base::UTF16ToUTF8(prefetch_data_.query_type);
[email protected]2ef2a6642014-07-30 05:50:29844 }
845 }
[email protected]9ff91722012-09-07 05:29:12846 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19847 search_term_args,
blundelld130d592015-06-21 19:29:13848 client()->GetTemplateURLService()->search_terms_data()));
[email protected]9ff91722012-09-07 05:29:12849 if (!suggest_url.is_valid())
850 return NULL;
[email protected]9b9fa672013-11-07 06:04:52851 // Send the current page URL if user setting and URL requirements are met and
852 // the user is in the field trial.
blundelld130d592015-06-21 19:29:13853 TemplateURLService* template_url_service = client()->GetTemplateURLService();
mariakhomenko3ac684352015-06-18 20:01:17854 if (CanSendURL(input.current_url(), suggest_url, template_url,
[email protected]e6477f12014-08-05 07:59:54855 input.current_page_classification(),
blundelld130d592015-06-21 19:29:13856 template_url_service->search_terms_data(), client()) &&
[email protected]9b9fa672013-11-07 06:04:52857 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
mariakhomenko3ac684352015-06-18 20:01:17858 search_term_args.current_page_url = input.current_url().spec();
[email protected]9b9fa672013-11-07 06:04:52859 // Create the suggest URL again with the current page URL.
860 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
blundelld130d592015-06-21 19:29:13861 search_term_args, template_url_service->search_terms_data()));
[email protected]9b9fa672013-11-07 06:04:52862 }
[email protected]9ff91722012-09-07 05:29:12863
[email protected]9ff91722012-09-07 05:29:12864 LogOmniboxSuggestRequest(REQUEST_SENT);
865
dtapuskadafcf892015-05-01 13:58:25866 scoped_ptr<net::URLFetcher> fetcher =
[email protected]9ff91722012-09-07 05:29:12867 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
blundelld130d592015-06-21 19:29:13868 fetcher->SetRequestContext(client()->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34869 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30870 // Add Chrome experiment state to the request headers.
871 net::HttpRequestHeaders headers;
[email protected]71011c1682014-07-09 17:19:16872 variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
blundelld130d592015-06-21 19:29:13873 fetcher->GetOriginalURL(), client()->IsOffTheRecord(), false, &headers);
[email protected]bd3b4712012-12-18 17:01:30874 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24875 fetcher->Start();
876 return fetcher;
877}
878
[email protected]344946a12012-12-20 12:03:42879void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29880 // Convert all the results to matches and add them to a map, so we can keep
881 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36882 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29883 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23884 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24885 int did_not_accept_keyword_suggestion =
886 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29887 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
888 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29889
[email protected]d30268a2013-06-25 22:31:07890 bool relevance_from_server;
891 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24892 int did_not_accept_default_suggestion =
893 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08894 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
895 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]7bc5e162014-08-15 19:41:11896 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]d1f0a7f2012-06-05 10:26:42897 if (verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44898 const base::string16& trimmed_verbatim =
899 base::CollapseWhitespace(input_.text(), false);
[email protected]716cd372014-08-15 18:56:03900
901 // Verbatim results don't get suggestions and hence, answers.
902 // Scan previous matches if the last answer-bearing suggestion matches
903 // verbatim, and if so, copy over answer contents.
904 base::string16 answer_contents;
905 base::string16 answer_type;
jdonnelly7393cee2014-10-31 01:52:56906 scoped_ptr<SuggestionAnswer> answer;
[email protected]716cd372014-08-15 18:56:03907 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
908 ++it) {
jdonnelly7393cee2014-10-31 01:52:56909 if (it->answer && it->fill_into_edit == trimmed_verbatim) {
[email protected]716cd372014-08-15 18:56:03910 answer_contents = it->answer_contents;
911 answer_type = it->answer_type;
jdonnelly7393cee2014-10-31 01:52:56912 answer = SuggestionAnswer::copy(it->answer.get());
[email protected]716cd372014-08-15 18:56:03913 break;
914 }
915 }
916
[email protected]0b9575f2014-07-30 11:58:37917 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44918 trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]716cd372014-08-15 18:56:03919 trimmed_verbatim, base::string16(), base::string16(), answer_contents,
jdonnelly7393cee2014-10-31 01:52:56920 answer_type, answer.Pass(), std::string(), std::string(), false,
921 verbatim_relevance, relevance_from_server, false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37922 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
[email protected]7bc5e162014-08-15 19:41:11923 false, keyword_url != NULL, &map);
[email protected]d1f0a7f2012-06-05 10:26:42924 }
[email protected]5423e562013-02-07 03:58:45925 if (!keyword_input_.text().empty()) {
[email protected]5423e562013-02-07 03:58:45926 // We only create the verbatim search query match for a keyword
927 // if it's not an extension keyword. Extension keywords are handled
928 // in KeywordProvider::Start(). (Extensions are complicated...)
929 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
930 // to the keyword verbatim search query. Do not create other matches
931 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:25932 if (keyword_url &&
933 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:07934 bool keyword_relevance_from_server;
935 const int keyword_verbatim_relevance =
936 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:28937 if (keyword_verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44938 const base::string16& trimmed_verbatim =
939 base::CollapseWhitespace(keyword_input_.text(), false);
[email protected]0b9575f2014-07-30 11:58:37940 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44941 trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
942 trimmed_verbatim, base::string16(), base::string16(),
jdonnelly7393cee2014-10-31 01:52:56943 base::string16(), base::string16(), nullptr, std::string(),
944 std::string(), true, keyword_verbatim_relevance,
945 keyword_relevance_from_server, false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37946 AddMatchToMap(verbatim, std::string(),
[email protected]7bc5e162014-08-15 19:41:11947 did_not_accept_keyword_suggestion, false, true, &map);
[email protected]dab8d52d2013-03-05 07:35:28948 }
[email protected]5423e562013-02-07 03:58:45949 }
950 }
grobye5fcee42014-09-26 03:36:46951 AddRawHistoryResultsToMap(true, did_not_accept_keyword_suggestion, &map);
952 AddRawHistoryResultsToMap(false, did_not_accept_default_suggestion, &map);
[email protected]257ab712009-04-14 17:16:24953
[email protected]d1cb6a822013-09-18 19:43:00954 AddSuggestResultsToMap(keyword_results_.suggest_results,
955 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:18956 AddSuggestResultsToMap(default_results_.suggest_results,
957 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:29958
[email protected]d30268a2013-06-25 22:31:07959 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:29960 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:07961 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:29962
[email protected]d30268a2013-06-25 22:31:07963 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
964 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:29965
[email protected]d30268a2013-06-25 22:31:07966 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
mpearson6c183672014-09-03 02:09:42967 // suggest/navsuggest matches, regardless of origin. We always include in
968 // that set a legal default match if possible. If Instant Extended is enabled
969 // and we have server-provided (and thus hopefully more accurate) scores for
970 // some suggestions, we allow more of those, until we reach
[email protected]d30268a2013-06-25 22:31:07971 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
972 // whole popup).
973 //
974 // We will always return any verbatim matches, no matter how we obtained their
975 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
976 // higher-scoring matches under the conditions above.
977 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
jdonnelly55f66142014-09-25 23:08:11978
mpearson6c183672014-09-03 02:09:42979 // Guarantee that if there's a legal default match anywhere in the result
980 // set that it'll get returned. The rotate() call does this by moving the
981 // default match to the front of the list.
982 ACMatches::iterator default_match = FindTopMatch(&matches);
983 if (default_match != matches.end())
984 std::rotate(matches.begin(), default_match, default_match + 1);
[email protected]3723e6e2012-06-11 21:06:56985
jdonnelly55f66142014-09-25 23:08:11986 // It's possible to get a copy of an answer from previous matches and get the
987 // same or a different answer to another server-provided suggestion. In the
988 // future we may decide that we want to have answers attached to multiple
989 // suggestions, but the current assumption is that there should only ever be
990 // one suggestion with an answer. To maintain this assumption, remove any
991 // answers after the first.
992 RemoveExtraAnswers(&matches);
993
994 matches_.clear();
[email protected]d30268a2013-06-25 22:31:07995 size_t num_suggestions = 0;
996 for (ACMatches::const_iterator i(matches.begin());
997 (i != matches.end()) &&
998 (matches_.size() < AutocompleteResult::kMaxMatches);
999 ++i) {
1000 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
1001 // verbatim result, so this condition basically means "if this match is a
1002 // suggestion of some sort".
1003 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
1004 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
1005 // If we've already hit the limit on non-server-scored suggestions, and
1006 // this isn't a server-scored suggestion we can add, skip it.
1007 if ((num_suggestions >= kMaxMatches) &&
1008 (!chrome::IsInstantExtendedAPIEnabled() ||
1009 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
1010 continue;
1011 }
1012
1013 ++num_suggestions;
1014 }
1015
1016 matches_.push_back(*i);
1017 }
[email protected]31afdf72013-09-26 04:29:361018 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
1019 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:421020}
1021
jdonnelly55f66142014-09-25 23:08:111022void SearchProvider::RemoveExtraAnswers(ACMatches* matches) {
1023 bool answer_seen = false;
1024 for (ACMatches::iterator it = matches->begin(); it != matches->end(); ++it) {
jdonnelly7393cee2014-10-31 01:52:561025 if (it->answer) {
jdonnelly55f66142014-09-25 23:08:111026 if (!answer_seen) {
1027 answer_seen = true;
1028 } else {
1029 it->answer_contents.clear();
1030 it->answer_type.clear();
jdonnelly7393cee2014-10-31 01:52:561031 it->answer.reset();
jdonnelly55f66142014-09-25 23:08:111032 }
1033 }
1034 }
1035}
1036
[email protected]89bd27d12014-04-12 17:36:231037ACMatches::const_iterator SearchProvider::FindTopMatch() const {
[email protected]0a8718b12013-11-13 18:41:311038 ACMatches::const_iterator it = matches_.begin();
1039 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
1040 ++it;
1041 return it;
[email protected]9dfb4d362013-04-05 02:15:121042}
1043
[email protected]89bd27d12014-04-12 17:36:231044bool SearchProvider::IsTopMatchSearchWithURLInput() const {
1045 ACMatches::const_iterator first_match = FindTopMatch();
[email protected]3dc75b12014-06-08 00:02:221046 return (input_.type() == metrics::OmniboxInputType::URL) &&
[email protected]0a8718b12013-11-13 18:41:311047 (first_match != matches_.end()) &&
1048 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
[email protected]78981d8c2014-05-09 15:05:471049 (first_match->type != AutocompleteMatchType::NAVSUGGEST) &&
1050 (first_match->type != AutocompleteMatchType::NAVSUGGEST_PERSONALIZED);
[email protected]344946a12012-12-20 12:03:421051}
1052
[email protected]257ab712009-04-14 17:16:241053void SearchProvider::AddNavigationResultsToMatches(
[email protected]0b9575f2014-07-30 11:58:371054 const SearchSuggestionParser::NavigationResults& navigation_results,
[email protected]d30268a2013-06-25 22:31:071055 ACMatches* matches) {
[email protected]0b9575f2014-07-30 11:58:371056 for (SearchSuggestionParser::NavigationResults::const_iterator it =
1057 navigation_results.begin(); it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:071058 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:231059 // In the absence of suggested relevance scores, use only the single
1060 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:071061 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:231062 return;
[email protected]257ab712009-04-14 17:16:241063 }
1064}
1065
grobye5fcee42014-09-26 03:36:461066void SearchProvider::AddRawHistoryResultsToMap(bool is_keyword,
1067 int did_not_accept_suggestion,
1068 MatchMap* map) {
1069 const HistoryResults& raw_results =
1070 is_keyword ? raw_keyword_history_results_ : raw_default_history_results_;
1071 if (!OmniboxFieldTrial::EnableAnswersInSuggest() && raw_results.empty())
[email protected]51124552011-07-16 01:37:101072 return;
1073
[email protected]31afdf72013-09-26 04:29:361074 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]51124552011-07-16 01:37:101075
grobye5fcee42014-09-26 03:36:461076 // Until Answers becomes default, scoring of history results will still happen
1077 // here for non-Answers Chrome, to prevent scoring performance regressions
1078 // resulting from moving the scoring code before the suggest request is sent.
1079 // For users with Answers enabled, the history results have already been
1080 // scored earlier, right after calling DoHistoryQuery().
1081 SearchSuggestionParser::SuggestResults local_transformed_results;
1082 const SearchSuggestionParser::SuggestResults* transformed_results = NULL;
1083 if (!OmniboxFieldTrial::EnableAnswersInSuggest()) {
1084 ScoreHistoryResults(raw_results, is_keyword, &local_transformed_results);
1085 transformed_results = &local_transformed_results;
1086 } else {
1087 transformed_results = is_keyword ? &transformed_keyword_history_results_
1088 : &transformed_default_history_results_;
[email protected]51124552011-07-16 01:37:101089 }
grobye5fcee42014-09-26 03:36:461090 DCHECK(transformed_results);
1091 AddTransformedHistoryResultsToMap(
1092 *transformed_results, did_not_accept_suggestion, map);
[email protected]31afdf72013-09-26 04:29:361093 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1094 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:101095}
1096
grobye5fcee42014-09-26 03:36:461097void SearchProvider::AddTransformedHistoryResultsToMap(
1098 const SearchSuggestionParser::SuggestResults& transformed_results,
1099 int did_not_accept_suggestion,
1100 MatchMap* map) {
1101 for (SearchSuggestionParser::SuggestResults::const_iterator i(
1102 transformed_results.begin());
1103 i != transformed_results.end();
1104 ++i) {
1105 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true,
1106 providers_.GetKeywordProviderURL() != NULL, map);
1107 }
1108}
1109
1110SearchSuggestionParser::SuggestResults
1111SearchProvider::ScoreHistoryResultsHelper(const HistoryResults& results,
1112 bool base_prevent_inline_autocomplete,
1113 bool input_multiple_words,
1114 const base::string16& input_text,
1115 bool is_keyword) {
[email protected]0b9575f2014-07-30 11:58:371116 SearchSuggestionParser::SuggestResults scored_results;
[email protected]ab5fd2f2014-07-17 19:18:521117 // True if the user has asked this exact query previously.
1118 bool found_what_you_typed_match = false;
[email protected]78e5e432013-08-03 02:10:101119 const bool prevent_search_history_inlining =
1120 OmniboxFieldTrial::SearchHistoryPreventInlining(
1121 input_.current_page_classification());
[email protected]c2ca3fd2014-03-22 03:07:441122 const base::string16& trimmed_input =
1123 base::CollapseWhitespace(input_text, false);
[email protected]257ab712009-04-14 17:16:241124 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1125 ++i) {
[email protected]c2ca3fd2014-03-22 03:07:441126 const base::string16& trimmed_suggestion =
1127 base::CollapseWhitespace(i->term, false);
1128
[email protected]51124552011-07-16 01:37:101129 // Don't autocomplete multi-word queries that have only been seen once
1130 // unless the user has typed more than one word.
1131 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
[email protected]c2ca3fd2014-03-22 03:07:441132 (!input_multiple_words && (i->visits < 2) &&
1133 HasMultipleWords(trimmed_suggestion));
[email protected]51124552011-07-16 01:37:101134
[email protected]78e5e432013-08-03 02:10:101135 int relevance = CalculateRelevanceForHistory(
1136 i->time, is_keyword, !prevent_inline_autocomplete,
1137 prevent_search_history_inlining);
[email protected]ab5fd2f2014-07-17 19:18:521138 // Add the match to |scored_results| by putting the what-you-typed match
1139 // on the front and appending all other matches. We want the what-you-
1140 // typed match to always be first.
[email protected]0b9575f2014-07-30 11:58:371141 SearchSuggestionParser::SuggestResults::iterator insertion_position =
1142 scored_results.end();
[email protected]ab5fd2f2014-07-17 19:18:521143 if (trimmed_suggestion == trimmed_input) {
1144 found_what_you_typed_match = true;
1145 insertion_position = scored_results.begin();
1146 }
mpearson6c183672014-09-03 02:09:421147 SearchSuggestionParser::SuggestResult history_suggestion(
1148 trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
1149 trimmed_suggestion, base::string16(), base::string16(),
jdonnelly7393cee2014-10-31 01:52:561150 base::string16(), base::string16(), nullptr, std::string(),
1151 std::string(), is_keyword, relevance, false, false, trimmed_input);
mpearson6c183672014-09-03 02:09:421152 // History results are synchronous; they are received on the last keystroke.
1153 history_suggestion.set_received_after_last_keystroke(false);
1154 scored_results.insert(insertion_position, history_suggestion);
[email protected]257ab712009-04-14 17:16:241155 }
[email protected]51124552011-07-16 01:37:101156
1157 // History returns results sorted for us. However, we may have docked some
[email protected]ab5fd2f2014-07-17 19:18:521158 // results' scores, so things are no longer in order. While keeping the
1159 // what-you-typed match at the front (if it exists), do a stable sort to get
[email protected]51124552011-07-16 01:37:101160 // things back in order without otherwise disturbing results with equal
1161 // scores, then force the scores to be unique, so that the order in which
1162 // they're shown is deterministic.
[email protected]ab5fd2f2014-07-17 19:18:521163 std::stable_sort(scored_results.begin() +
1164 (found_what_you_typed_match ? 1 : 0),
1165 scored_results.end(),
[email protected]55ce8f12012-05-09 04:44:081166 CompareScoredResults());
[email protected]7e3b77f2014-07-25 02:29:441167
1168 // Don't autocomplete to search terms that would normally be treated as URLs
1169 // when typed. For example, if the user searched for "google.com" and types
1170 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1171 // the input will look like a URL but act like a search, which is confusing.
1172 // The 1200 relevance score threshold in the test below is the lowest
1173 // possible score in CalculateRelevanceForHistory()'s aggressive-scoring
1174 // curve. This is an appropriate threshold to use to decide if we're overly
1175 // aggressively inlining because, if we decide the answer is yes, the
1176 // way we resolve it it to not use the aggressive-scoring curve.
1177 // NOTE: We don't check for autocompleting to URLs in the following cases:
1178 // * When inline autocomplete is disabled, we won't be inline autocompleting
1179 // this term, so we don't need to worry about confusion as much. This
1180 // also prevents calling Classify() again from inside the classifier
1181 // (which will corrupt state and likely crash), since the classifier
1182 // always disables inline autocomplete.
1183 // * When the user has typed the whole string before as a query, then it's
1184 // likely the user has no expectation that term should be interpreted as
1185 // as a URL, so we need not do anything special to preserve user
1186 // expectation.
[email protected]51124552011-07-16 01:37:101187 int last_relevance = 0;
[email protected]7e3b77f2014-07-25 02:29:441188 if (!base_prevent_inline_autocomplete && !found_what_you_typed_match &&
hashimoto663b9f42014-08-26 04:29:201189 scored_results.front().relevance() >= 1200) {
[email protected]7e3b77f2014-07-25 02:29:441190 AutocompleteMatch match;
blundelld130d592015-06-21 19:29:131191 client()->Classify(scored_results.front().suggestion(), false, false,
1192 input_.current_page_classification(), &match, NULL);
[email protected]7e3b77f2014-07-25 02:29:441193 // Demote this match that would normally be interpreted as a URL to have
1194 // the highest score a previously-issued search query could have when
1195 // scoring with the non-aggressive method. A consequence of demoting
1196 // by revising |last_relevance| is that this match and all following
1197 // matches get demoted; the relative order of matches is preserved.
1198 // One could imagine demoting only those matches that might cause
1199 // confusion (which, by the way, might change the relative order of
1200 // matches. We have decided to go with the simple demote-all approach
1201 // because selective demotion requires multiple Classify() calls and
1202 // such calls can be expensive (as expensive as running the whole
1203 // autocomplete system).
1204 if (!AutocompleteMatch::IsSearchType(match.type)) {
1205 last_relevance = CalculateRelevanceForHistory(
1206 base::Time::Now(), is_keyword, false,
1207 prevent_search_history_inlining);
1208 }
1209 }
1210
[email protected]0b9575f2014-07-30 11:58:371211 for (SearchSuggestionParser::SuggestResults::iterator i(
1212 scored_results.begin()); i != scored_results.end(); ++i) {
[email protected]7e3b77f2014-07-25 02:29:441213 if ((last_relevance != 0) && (i->relevance() >= last_relevance))
[email protected]55ce8f12012-05-09 04:44:081214 i->set_relevance(last_relevance - 1);
1215 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101216 }
1217
[email protected]55ce8f12012-05-09 04:44:081218 return scored_results;
[email protected]257ab712009-04-14 17:16:241219}
1220
grobye5fcee42014-09-26 03:36:461221void SearchProvider::ScoreHistoryResults(
1222 const HistoryResults& results,
1223 bool is_keyword,
1224 SearchSuggestionParser::SuggestResults* scored_results) {
1225 DCHECK(scored_results);
jdonnellye5f055d92015-01-15 00:58:581226 scored_results->clear();
1227
grobye5fcee42014-09-26 03:36:461228 if (results.empty()) {
grobye5fcee42014-09-26 03:36:461229 return;
1230 }
1231
1232 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1233 (input_.type() == metrics::OmniboxInputType::URL);
1234 const base::string16 input_text = GetInput(is_keyword).text();
1235 bool input_multiple_words = HasMultipleWords(input_text);
1236
1237 if (!prevent_inline_autocomplete && input_multiple_words) {
1238 // ScoreHistoryResultsHelper() allows autocompletion of multi-word, 1-visit
1239 // queries if the input also has multiple words. But if we were already
1240 // scoring a multi-word, multi-visit query aggressively, and the current
1241 // input is still a prefix of it, then changing the suggestion suddenly
1242 // feels wrong. To detect this case, first score as if only one word has
1243 // been typed, then check if the best result came from aggressive search
1244 // history scoring. If it did, then just keep that score set. This
1245 // 1200 the lowest possible score in CalculateRelevanceForHistory()'s
1246 // aggressive-scoring curve.
1247 *scored_results = ScoreHistoryResultsHelper(
1248 results, prevent_inline_autocomplete, false, input_text, is_keyword);
1249 if ((scored_results->front().relevance() < 1200) ||
1250 !HasMultipleWords(scored_results->front().suggestion()))
1251 scored_results->clear(); // Didn't detect the case above, score normally.
1252 }
1253 if (scored_results->empty()) {
1254 *scored_results = ScoreHistoryResultsHelper(results,
1255 prevent_inline_autocomplete,
1256 input_multiple_words,
1257 input_text,
1258 is_keyword);
1259 }
1260}
1261
[email protected]0b9575f2014-07-30 11:58:371262void SearchProvider::AddSuggestResultsToMap(
1263 const SearchSuggestionParser::SuggestResults& results,
1264 const std::string& metadata,
1265 MatchMap* map) {
[email protected]7bc5e162014-08-15 19:41:111266 for (size_t i = 0; i < results.size(); ++i) {
1267 AddMatchToMap(results[i], metadata, i, false,
1268 providers_.GetKeywordProviderURL() != NULL, map);
1269 }
initial.commit09911bf2008-07-26 23:55:291270}
1271
[email protected]d30268a2013-06-25 22:31:071272int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561273 // Use the suggested verbatim relevance score if it is non-negative (valid),
1274 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281275 // and if it won't suppress verbatim, leaving no default provider matches.
1276 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561277 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281278 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561279 // Check for results on each verbatim calculation, as results from older
1280 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231281 bool use_server_relevance =
1282 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281283 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231284 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241285 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231286 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071287 if (relevance_from_server)
1288 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231289 return use_server_relevance ?
1290 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521291}
[email protected]d1f0a7f2012-06-05 10:26:421292
[email protected]382a0642012-06-06 06:13:521293int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471294 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361295 return 250;
[email protected]dab8d52d2013-03-05 07:35:281296 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1297}
[email protected]52d08b12009-10-19 18:42:361298
[email protected]dab8d52d2013-03-05 07:35:281299int SearchProvider::
1300 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291301 switch (input_.type()) {
[email protected]3dc75b12014-06-08 00:02:221302 case metrics::OmniboxInputType::UNKNOWN:
1303 case metrics::OmniboxInputType::QUERY:
1304 case metrics::OmniboxInputType::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131305 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291306
[email protected]3dc75b12014-06-08 00:02:221307 case metrics::OmniboxInputType::URL:
[email protected]52d08b12009-10-19 18:42:361308 return 850;
initial.commit09911bf2008-07-26 23:55:291309
1310 default:
1311 NOTREACHED();
1312 return 0;
1313 }
1314}
1315
[email protected]d30268a2013-06-25 22:31:071316int SearchProvider::GetKeywordVerbatimRelevance(
1317 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281318 // Use the suggested verbatim relevance score if it is non-negative (valid),
1319 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1320 // and if it won't suppress verbatim, leaving no keyword provider matches.
1321 // Otherwise, if the keyword provider returned no matches and was still able
1322 // to suppress verbatim, the user would have no search/nav matches and may be
1323 // left unable to search using their keyword provider from the omnibox.
1324 // Check for results on each verbatim calculation, as results from older
1325 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231326 bool use_server_relevance =
1327 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281328 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231329 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241330 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231331 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071332 if (relevance_from_server)
1333 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231334 return use_server_relevance ?
1335 keyword_results_.verbatim_relevance :
1336 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1337 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451338}
1339
[email protected]51124552011-07-16 01:37:101340int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231341 const base::Time& time,
[email protected]51124552011-07-16 01:37:101342 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101343 bool use_aggressive_method,
1344 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181345 // The relevance of past searches falls off over time. There are two distinct
1346 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101347 // provider that we want to score aggressively), the score is in the range
1348 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161349 // it's in the range 1200-1299). If the second equation is used the
1350 // relevance of a search 15 minutes ago is discounted 50 points, while the
1351 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231352 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421353 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101354 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181355 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101356 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181357 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161358 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101359 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161360 max_score = 1299;
1361 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181362 std::pow(elapsed_time / autocomplete_time, 2.5));
1363 }
1364 elapsed_time -= autocomplete_time;
1365 }
1366
[email protected]c3a4bd992010-08-18 20:25:011367 const int score_discount =
1368 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291369
[email protected]6c85aa02009-02-27 12:08:091370 // Don't let scores go below 0. Negative relevance scores are meaningful in
1371 // a different way.
initial.commit09911bf2008-07-26 23:55:291372 int base_score;
[email protected]51124552011-07-16 01:37:101373 if (is_primary_provider)
[email protected]3dc75b12014-06-08 00:02:221374 base_score = (input_.type() == metrics::OmniboxInputType::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101375 else
1376 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291377 return std::max(0, base_score - score_discount);
1378}
1379
initial.commit09911bf2008-07-26 23:55:291380AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]0b9575f2014-07-30 11:58:371381 const SearchSuggestionParser::NavigationResult& navigation) {
[email protected]5889bfb2014-03-19 00:26:481382 base::string16 input;
1383 const bool trimmed_whitespace = base::TrimWhitespace(
1384 navigation.from_keyword_provider() ?
1385 keyword_input_.text() : input_.text(),
1386 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
[email protected]55ce8f12012-05-09 04:44:081387 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]78981d8c2014-05-09 15:05:471388 navigation.type());
[email protected]55ce8f12012-05-09 04:44:081389 match.destination_url = navigation.url();
[email protected]78981d8c2014-05-09 15:05:471390 BaseSearchProvider::SetDeletionURL(navigation.deletion_url(), &match);
[email protected]23db6492014-01-16 02:35:301391 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551392 // without trimming the scheme, so we can find matches at the beginning of the
1393 // scheme.
[email protected]371dab12012-06-01 03:23:551394 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301395 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551396 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301397 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351398 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1399 (!prefix || (match_start != 0));
[email protected]23db6492014-01-16 02:35:301400 const net::FormatUrlTypes format_types =
1401 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551402
blundelld130d592015-06-21 19:29:131403 const std::string languages(client()->GetAcceptLanguages());
[email protected]23db6492014-01-16 02:35:301404 size_t inline_autocomplete_offset = (prefix == NULL) ?
1405 base::string16::npos : (match_start + input.length());
[email protected]371dab12012-06-01 03:23:551406 match.fill_into_edit +=
[email protected]5655ea32014-06-21 05:28:081407 AutocompleteInput::FormattedStringWithEquivalentMeaning(
1408 navigation.url(),
[email protected]371dab12012-06-01 03:23:551409 net::FormatUrl(navigation.url(), languages, format_types,
1410 net::UnescapeRule::SPACES, NULL, NULL,
[email protected]5655ea32014-06-21 05:28:081411 &inline_autocomplete_offset),
blundelld130d592015-06-21 19:29:131412 client()->GetSchemeClassifier());
[email protected]14119032013-11-07 08:14:261413 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1414 // Otherwise, user edits to a suggestion would show non-Search results.
[email protected]3dc75b12014-06-08 00:02:221415 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581416 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031417 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261418 ++inline_autocomplete_offset;
1419 }
[email protected]6c94a1022014-02-21 03:48:041420 if (inline_autocomplete_offset != base::string16::npos) {
[email protected]518024c2013-07-19 23:40:251421 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1422 match.inline_autocompletion =
1423 match.fill_into_edit.substr(inline_autocomplete_offset);
1424 }
[email protected]6c94a1022014-02-21 03:48:041425 // An inlineable navsuggestion can only be the default match when there
1426 // is no keyword provider active, lest it appear first and break the user
mpearson6c183672014-09-03 02:09:421427 // out of keyword mode. We also must have received the navsuggestion before
1428 // the last keystroke, to prevent asynchronous inline autocompletions changes.
1429 // The navsuggestion can also only be default if either the inline
[email protected]5889bfb2014-03-19 00:26:481430 // autocompletion is empty or we're not preventing inline autocompletion.
1431 // Finally, if we have an inlineable navsuggestion with an inline completion
1432 // that we're not preventing, make sure we didn't trim any whitespace.
1433 // We don't want to claim http://foo.com/bar is inlineable against the
1434 // input "foo.com/b ".
mpearson6c183672014-09-03 02:09:421435 match.allowed_to_be_default_match =
1436 (prefix != NULL) &&
[email protected]6c94a1022014-02-21 03:48:041437 (providers_.GetKeywordProviderURL() == NULL) &&
mpearson6c183672014-09-03 02:09:421438 !navigation.received_after_last_keystroke() &&
[email protected]5889bfb2014-03-19 00:26:481439 (match.inline_autocompletion.empty() ||
[email protected]78981d8c2014-05-09 15:05:471440 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
blundelld130d592015-06-21 19:29:131441 match.EnsureUWYTIsAllowedToBeDefault(input_.canonicalized_url(),
1442 client()->GetTemplateURLService());
[email protected]371dab12012-06-01 03:23:551443
[email protected]23db6492014-01-16 02:35:301444 match.contents = navigation.match_contents();
1445 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081446 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551447 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1448 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071449
1450 match.RecordAdditionalInfo(
1451 kRelevanceFromServerKey,
1452 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181453 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071454
initial.commit09911bf2008-07-26 23:55:291455 return match;
1456}
[email protected]4ab4c7c2010-11-24 04:49:341457
1458void SearchProvider::UpdateDone() {
mpearson84f19a152015-03-12 19:42:211459 // We're done when the timer isn't running and there are no suggest queries
1460 // pending.
1461 done_ = !timer_.IsRunning() && !default_fetcher_ && !keyword_fetcher_;
[email protected]4ab4c7c2010-11-24 04:49:341462}
[email protected]20184242014-05-14 02:57:421463
1464std::string SearchProvider::GetSessionToken() {
1465 base::TimeTicks current_time(base::TimeTicks::Now());
1466 // Renew token if it expired.
1467 if (current_time > token_expiration_time_) {
1468 const size_t kTokenBytes = 12;
1469 std::string raw_data;
1470 base::RandBytes(WriteInto(&raw_data, kTokenBytes + 1), kTokenBytes);
1471 base::Base64Encode(raw_data, &current_token_);
[email protected]ab2c31f72014-05-17 17:03:531472
1473 // Make the base64 encoded value URL and filename safe(see RFC 3548).
1474 std::replace(current_token_.begin(), current_token_.end(), '+', '-');
1475 std::replace(current_token_.begin(), current_token_.end(), '/', '_');
[email protected]20184242014-05-14 02:57:421476 }
1477
1478 // Extend expiration time another 60 seconds.
1479 token_expiration_time_ = current_time + base::TimeDelta::FromSeconds(60);
1480
1481 return current_token_;
1482}
[email protected]2ef2a6642014-07-30 05:50:291483
1484void SearchProvider::RegisterDisplayedAnswers(
1485 const AutocompleteResult& result) {
1486 if (result.empty())
1487 return;
1488
1489 // The answer must be in the first or second slot to be considered. It should
1490 // only be in the second slot if AutocompleteController ranked a local search
1491 // history or a verbatim item higher than the answer.
1492 AutocompleteResult::const_iterator match = result.begin();
1493 if (match->answer_contents.empty() && result.size() > 1)
1494 ++match;
1495 if (match->answer_contents.empty() || match->answer_type.empty() ||
1496 match->fill_into_edit.empty())
1497 return;
1498
1499 // Valid answer encountered, cache it for further queries.
[email protected]ebbac63e2014-08-22 01:43:061500 answers_cache_.UpdateRecentAnswers(match->fill_into_edit, match->answer_type);
[email protected]2ef2a6642014-07-30 05:50:291501}
1502
grobye5fcee42014-09-26 03:36:461503AnswersQueryData SearchProvider::FindAnswersPrefetchData() {
1504 // Retrieve the top entry from scored history results.
1505 MatchMap map;
1506 AddTransformedHistoryResultsToMap(transformed_keyword_history_results_,
1507 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
1508 &map);
1509 AddTransformedHistoryResultsToMap(transformed_default_history_results_,
1510 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
1511 &map);
1512
1513 ACMatches matches;
1514 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
1515 matches.push_back(i->second);
1516 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
1517
1518 // If there is a top scoring entry, find the corresponding answer.
1519 if (!matches.empty())
1520 return answers_cache_.GetTopAnswerEntry(matches[0].contents);
1521
1522 return AnswersQueryData();
[email protected]2ef2a6642014-07-30 05:50:291523}