blob: b26910c402d44f768d003376794b125ea66adc2e [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
blundell2102f7c2015-07-09 10:00:535#include "components/omnibox/browser/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"
amohammadkhanf76ae112015-09-14 17:34:4321#include "components/data_use_measurement/core/data_use_user_data.h"
[email protected]e3ce70ac2014-06-26 18:34:5622#include "components/history/core/browser/in_memory_database.h"
[email protected]73b2d1e72014-06-25 23:45:3623#include "components/history/core/browser/keyword_search_term.h"
[email protected]3dc75b12014-06-08 00:02:2224#include "components/metrics/proto/omnibox_input_type.pb.h"
blundell2102f7c2015-07-09 10:00:5325#include "components/omnibox/browser/autocomplete_provider_client.h"
26#include "components/omnibox/browser/autocomplete_provider_listener.h"
27#include "components/omnibox/browser/autocomplete_result.h"
28#include "components/omnibox/browser/keyword_provider.h"
29#include "components/omnibox/browser/omnibox_field_trial.h"
30#include "components/omnibox/browser/suggestion_answer.h"
31#include "components/omnibox/browser/url_prefix.h"
[email protected]720b10492014-07-23 08:48:4032#include "components/search/search.h"
[email protected]0915b352014-06-25 19:58:1433#include "components/search_engines/template_url_prepopulate_data.h"
[email protected]bf5c532d2014-07-05 00:29:5334#include "components/search_engines/template_url_service.h"
rsleevi24f64dc22015-08-07 21:39:2135#include "components/url_formatter/url_formatter.h"
asvitkine9a279832015-12-18 02:35:5036#include "components/variations/net/variations_http_headers.h"
[email protected]53f0cab2014-08-18 09:52:2737#include "grit/components_strings.h"
initial.commit09911bf2008-07-26 23:55:2938#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3439#include "net/base/load_flags.h"
[email protected]bd3b4712012-12-18 17:01:3040#include "net/http/http_request_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5341#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2142#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1743#include "ui/base/l10n/l10n_util.h"
[email protected]cca6f392014-05-28 21:32:2644#include "url/url_constants.h"
[email protected]761fa4702013-07-02 15:25:1545#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2946
[email protected]bc8bb0cd2013-06-24 21:50:2347// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3348
[email protected]51124552011-07-16 01:37:1049namespace {
50
[email protected]7706a522012-08-16 17:42:2551// We keep track in a histogram how many suggest requests we send, how
52// many suggest requests we invalidate (e.g., due to a user typing
53// another character), and how many replies we receive.
54// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
55// (excluding the end-of-list enum value)
56// We do not want values of existing enums to change or else it screws
57// up the statistics.
58enum SuggestRequestsHistogramValue {
59 REQUEST_SENT = 1,
60 REQUEST_INVALIDATED,
61 REPLY_RECEIVED,
62 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
63};
64
[email protected]90fe2bb2013-01-15 03:42:1365// The verbatim score for an input which is not an URL.
66const int kNonURLVerbatimRelevance = 1300;
67
[email protected]7706a522012-08-16 17:42:2568// Increments the appropriate value in the histogram by one.
69void LogOmniboxSuggestRequest(
70 SuggestRequestsHistogramValue request_value) {
71 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
72 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
73}
74
[email protected]0085863a2013-12-06 21:19:0375bool HasMultipleWords(const base::string16& text) {
[email protected]51124552011-07-16 01:37:1076 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
77 bool found_word = false;
78 if (i.Init()) {
79 while (i.Advance()) {
80 if (i.IsWord()) {
81 if (found_word)
82 return true;
83 found_word = true;
84 }
85 }
86 }
87 return false;
88}
89
[email protected]d1f0a7f2012-06-05 10:26:4290} // namespace
[email protected]51124552011-07-16 01:37:1091
[email protected]3954c3a2012-04-10 20:17:5592// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:5893
[email protected]85b8d6f2012-05-08 20:53:4794SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
[email protected]02346202014-02-05 05:18:3095 : template_url_service_(template_url_service) {}
[email protected]85b8d6f2012-05-08 20:53:4796
97const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
98 return default_provider_.empty() ? NULL :
99 template_url_service_->GetTemplateURLForKeyword(default_provider_);
100}
101
102const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
103 return keyword_provider_.empty() ? NULL :
104 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24105}
106
[email protected]3954c3a2012-04-10 20:17:55107
[email protected]bc8bb0cd2013-06-24 21:50:23108// SearchProvider::CompareScoredResults ---------------------------------------
109
110class SearchProvider::CompareScoredResults {
111 public:
[email protected]0b9575f2014-07-30 11:58:37112 bool operator()(const SearchSuggestionParser::Result& a,
113 const SearchSuggestionParser::Result& b) {
[email protected]bc8bb0cd2013-06-24 21:50:23114 // Sort in descending relevance order.
115 return a.relevance() > b.relevance();
116 }
117};
118
119
[email protected]3954c3a2012-04-10 20:17:55120// SearchProvider -------------------------------------------------------------
121
blundell55e35e82015-06-16 08:46:18122SearchProvider::SearchProvider(AutocompleteProviderClient* client,
blundelld130d592015-06-21 19:29:13123 AutocompleteProviderListener* listener)
124 : BaseSearchProvider(AutocompleteProvider::TYPE_SEARCH, client),
[email protected]776ee5902014-08-11 09:15:19125 listener_(listener),
blundelld130d592015-06-21 19:29:13126 providers_(client->GetTemplateURLService()),
groby1dbb8e22014-09-23 21:50:26127 answers_cache_(10) {
blundelld130d592015-06-21 19:29:13128 TemplateURLService* template_url_service = client->GetTemplateURLService();
129
130 // |template_url_service| can be null in tests.
131 if (template_url_service)
132 template_url_service->AddObserver(this);
[email protected]bc8bb0cd2013-06-24 21:50:23133}
134
[email protected]cb86ee6f2013-04-28 16:58:15135// static
[email protected]987fad782013-08-28 06:23:18136std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
137 return match.GetAdditionalInfo(kSuggestMetadataKey);
138}
139
mpearson6456fb62015-11-13 06:44:28140void SearchProvider::RegisterDisplayedAnswers(
141 const AutocompleteResult& result) {
142 if (result.empty())
mpearson84f19a152015-03-12 19:42:21143 return;
144
mpearson6456fb62015-11-13 06:44:28145 // The answer must be in the first or second slot to be considered. It should
146 // only be in the second slot if AutocompleteController ranked a local search
147 // history or a verbatim item higher than the answer.
148 AutocompleteResult::const_iterator match = result.begin();
149 if (match->answer_contents.empty() && result.size() > 1)
150 ++match;
151 if (match->answer_contents.empty() || match->answer_type.empty() ||
152 match->fill_into_edit.empty())
153 return;
mpearson84f19a152015-03-12 19:42:21154
mpearson6456fb62015-11-13 06:44:28155 // Valid answer encountered, cache it for further queries.
156 answers_cache_.UpdateRecentAnswers(match->fill_into_edit, match->answer_type);
157}
158
159// static
160int SearchProvider::CalculateRelevanceForKeywordVerbatim(
161 metrics::OmniboxInputType::Type type,
162 bool allow_exact_keyword_match,
163 bool prefer_keyword) {
164 // This function is responsible for scoring verbatim query matches
165 // for non-extension substituting keywords.
166 // KeywordProvider::CalculateRelevance() scores all other types of
167 // keyword verbatim matches.
168 if (allow_exact_keyword_match && prefer_keyword)
169 return 1500;
170 return (allow_exact_keyword_match &&
171 (type == metrics::OmniboxInputType::QUERY)) ?
172 1450 : 1100;
173}
174
175void SearchProvider::ResetSession() {
176 set_field_trial_triggered_in_session(false);
mpearson84f19a152015-03-12 19:42:21177}
178
[email protected]bc8bb0cd2013-06-24 21:50:23179SearchProvider::~SearchProvider() {
blundelld130d592015-06-21 19:29:13180 TemplateURLService* template_url_service = client()->GetTemplateURLService();
181 if (template_url_service)
182 template_url_service->RemoveObserver(this);
[email protected]bc8bb0cd2013-06-24 21:50:23183}
184
[email protected]ee6110b2014-01-09 22:26:31185// static
mpearson6c183672014-09-03 02:09:42186void SearchProvider::UpdateOldResults(
187 bool minimal_changes,
188 SearchSuggestionParser::Results* results) {
189 // When called without |minimal_changes|, it likely means the user has
190 // pressed a key. Revise the cached results appropriately.
191 if (!minimal_changes) {
192 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
193 results->suggest_results.begin();
mpearsonf080b342015-11-11 00:52:44194 sug_it != results->suggest_results.end(); ) {
195 if (sug_it->type() == AutocompleteMatchType::CALCULATOR) {
196 sug_it = results->suggest_results.erase(sug_it);
197 } else {
198 sug_it->set_received_after_last_keystroke(false);
199 ++sug_it;
200 }
mpearson6c183672014-09-03 02:09:42201 }
202 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
203 results->navigation_results.begin();
204 nav_it != results->navigation_results.end(); ++nav_it) {
205 nav_it->set_received_after_last_keystroke(false);
206 }
207 }
208}
209
210// static
211ACMatches::iterator SearchProvider::FindTopMatch(ACMatches* matches) {
212 ACMatches::iterator it = matches->begin();
213 while ((it != matches->end()) && !it->allowed_to_be_default_match)
214 ++it;
215 return it;
216}
217
initial.commit09911bf2008-07-26 23:55:29218void SearchProvider::Start(const AutocompleteInput& input,
jifcf322cd2015-06-17 11:01:18219 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55220 // Do our best to load the model as early as possible. This will reduce
221 // odds of having the model not ready when really needed (a non-empty input).
blundelld130d592015-06-21 19:29:13222 TemplateURLService* model = client()->GetTemplateURLService();
[email protected]04504c242013-01-22 21:08:55223 DCHECK(model);
224 model->Load();
225
initial.commit09911bf2008-07-26 23:55:29226 matches_.clear();
blundelld130d592015-06-21 19:29:13227 set_field_trial_triggered(false);
initial.commit09911bf2008-07-26 23:55:29228
hashimoto663b9f42014-08-26 04:29:20229 // Can't return search/suggest results for bogus input.
jifcf322cd2015-06-17 11:01:18230 if (input.from_omnibox_focus() ||
mariakhomenko3ef531d72015-01-10 00:03:43231 input.type() == metrics::OmniboxInputType::INVALID) {
mpearson8a37c382015-03-07 05:58:57232 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29233 return;
234 }
235
[email protected]14710852013-02-05 23:45:41236 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24237 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41238 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
239 &keyword_input_);
240 if (keyword_provider == NULL)
241 keyword_input_.Clear();
242 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24243 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24244
[email protected]85b8d6f2012-05-08 20:53:47245 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]ce7ee5f2014-06-16 23:41:19246 if (default_provider &&
247 !default_provider->SupportsReplacement(model->search_terms_data()))
[email protected]257ab712009-04-14 17:16:24248 default_provider = NULL;
249
250 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18251 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24252
253 if (!default_provider && !keyword_provider) {
254 // No valid providers.
mpearson8a37c382015-03-07 05:58:57255 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29256 return;
257 }
258
259 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24260 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03261 base::string16 default_provider_keyword(default_provider ?
262 default_provider->keyword() : base::string16());
263 base::string16 keyword_provider_keyword(keyword_provider ?
264 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32265 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47266 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29267 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15268 if (!done_)
mpearson8a37c382015-03-07 05:58:57269 Stop(false, false);
[email protected]257ab712009-04-14 17:16:24270 }
initial.commit09911bf2008-07-26 23:55:29271
[email protected]85b8d6f2012-05-08 20:53:47272 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29273
274 if (input.text().empty()) {
275 // User typed "?" alone. Give them a placeholder result indicating what
276 // this syntax does.
[email protected]257ab712009-04-14 17:16:24277 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00278 AutocompleteMatch match;
279 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36280 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24281 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35282 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47283 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36284 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24285 matches_.push_back(match);
286 }
mpearson8a37c382015-03-07 05:58:57287 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29288 return;
289 }
290
291 input_ = input;
292
[email protected]e1290ee62013-06-26 18:31:15293 DoHistoryQuery(minimal_changes);
grobye5fcee42014-09-26 03:36:46294 // Answers needs scored history results before any suggest query has been
295 // started, since the query for answer-bearing results needs additional
296 // prefetch information based on the highest-scored local history result.
jdonnelly41c5b46a2015-07-10 21:24:38297 ScoreHistoryResults(raw_default_history_results_,
298 false,
299 &transformed_default_history_results_);
300 ScoreHistoryResults(raw_keyword_history_results_,
301 true,
302 &transformed_keyword_history_results_);
303 prefetch_data_ = FindAnswersPrefetchData();
grobye5fcee42014-09-26 03:36:46304
jdonnelly41c5b46a2015-07-10 21:24:38305 // Raw results are not needed any more.
306 raw_default_history_results_.clear();
307 raw_keyword_history_results_.clear();
grobye5fcee42014-09-26 03:36:46308
[email protected]e1290ee62013-06-26 18:31:15309 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42310 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29311}
312
mpearson8a37c382015-03-07 05:58:57313void SearchProvider::Stop(bool clear_cached_results,
314 bool due_to_user_inactivity) {
[email protected]ec3f679b2014-08-18 07:45:13315 StopSuggest();
316 done_ = true;
317
318 if (clear_cached_results)
319 ClearAllResults();
320}
321
[email protected]776ee5902014-08-11 09:15:19322const TemplateURL* SearchProvider::GetTemplateURL(bool is_keyword) const {
323 return is_keyword ? providers_.GetKeywordProviderURL()
324 : providers_.GetDefaultProviderURL();
325}
326
327const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
328 return is_keyword ? keyword_input_ : input_;
329}
330
331bool SearchProvider::ShouldAppendExtraParams(
332 const SearchSuggestionParser::SuggestResult& result) const {
333 return !result.from_keyword_provider() ||
334 providers_.default_provider().empty();
335}
336
[email protected]776ee5902014-08-11 09:15:19337void SearchProvider::RecordDeletionResult(bool success) {
338 if (success) {
339 base::RecordAction(
340 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
341 } else {
342 base::RecordAction(
343 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
344 }
345}
346
mpearson6456fb62015-11-13 06:44:28347void SearchProvider::OnTemplateURLServiceChanged() {
348 // Only update matches at this time if we haven't already claimed we're done
349 // processing the query.
350 if (done_)
351 return;
352
353 // Check that the engines we're using weren't renamed or deleted. (In short,
354 // require that an engine still exists with the keywords in use.) For each
355 // deleted engine, cancel the in-flight request if any, drop its suggestions,
356 // and, in the case when the default provider was affected, point the cached
357 // default provider keyword name at the new name for the default provider.
358
359 // Get...ProviderURL() looks up the provider using the cached keyword name
360 // stored in |providers_|.
361 const TemplateURL* template_url = providers_.GetDefaultProviderURL();
362 if (!template_url) {
363 CancelFetcher(&default_fetcher_);
364 default_results_.Clear();
365 providers_.set(client()
366 ->GetTemplateURLService()
367 ->GetDefaultSearchProvider()
368 ->keyword(),
369 providers_.keyword_provider());
370 }
371 template_url = providers_.GetKeywordProviderURL();
372 if (!providers_.keyword_provider().empty() && !template_url) {
373 CancelFetcher(&keyword_fetcher_);
374 keyword_results_.Clear();
375 providers_.set(providers_.default_provider(), base::string16());
376 }
377 // It's possible the template URL changed without changing associated keyword.
378 // Hence, it's always necessary to update matches to use the new template
379 // URL. (One could cache the template URL and only call UpdateMatches() and
380 // OnProviderUpdate() if a keyword was deleted/renamed or the template URL
381 // was changed. That would save extra calls to these functions. However,
382 // this is uncommon and not likely to be worth the extra work.)
383 UpdateMatches();
384 listener_->OnProviderUpdate(true); // always pretend something changed
385}
386
[email protected]776ee5902014-08-11 09:15:19387void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
388 DCHECK(!done_);
[email protected]776ee5902014-08-11 09:15:19389 const bool is_keyword = source == keyword_fetcher_.get();
390
391 // Ensure the request succeeded and that the provider used is still available.
392 // A verbatim match cannot be generated without this provider, causing errors.
393 const bool request_succeeded =
394 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
395 GetTemplateURL(is_keyword);
396
397 LogFetchComplete(request_succeeded, is_keyword);
398
399 bool results_updated = false;
400 if (request_succeeded) {
401 scoped_ptr<base::Value> data(SearchSuggestionParser::DeserializeJsonData(
402 SearchSuggestionParser::ExtractJsonData(source)));
403 if (data) {
404 SearchSuggestionParser::Results* results =
405 is_keyword ? &keyword_results_ : &default_results_;
406 results_updated = ParseSuggestResults(*data, -1, is_keyword, results);
407 if (results_updated)
408 SortResults(is_keyword, results);
409 }
410 }
mpearson84f19a152015-03-12 19:42:21411
412 // Delete the fetcher now that we're done with it.
413 if (is_keyword)
414 keyword_fetcher_.reset();
415 else
416 default_fetcher_.reset();
417
418 // Update matches, done status, etc., and send alerts if necessary.
[email protected]776ee5902014-08-11 09:15:19419 UpdateMatches();
420 if (done_ || results_updated)
421 listener_->OnProviderUpdate(results_updated);
422}
423
[email protected]ec3f679b2014-08-18 07:45:13424void SearchProvider::StopSuggest() {
mpearson84f19a152015-03-12 19:42:21425 CancelFetcher(&default_fetcher_);
426 CancelFetcher(&keyword_fetcher_);
[email protected]ec3f679b2014-08-18 07:45:13427 timer_.Stop();
[email protected]ec3f679b2014-08-18 07:45:13428}
429
430void SearchProvider::ClearAllResults() {
431 keyword_results_.Clear();
432 default_results_.Clear();
433}
434
[email protected]776ee5902014-08-11 09:15:19435void SearchProvider::UpdateMatchContentsClass(
436 const base::string16& input_text,
437 SearchSuggestionParser::Results* results) {
438 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
439 results->suggest_results.begin();
440 sug_it != results->suggest_results.end(); ++sug_it) {
441 sug_it->ClassifyMatchContents(false, input_text);
442 }
blundelld130d592015-06-21 19:29:13443 const std::string languages(client()->GetAcceptLanguages());
[email protected]776ee5902014-08-11 09:15:19444 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
445 results->navigation_results.begin();
446 nav_it != results->navigation_results.end(); ++nav_it) {
447 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
448 }
449}
450
[email protected]d4a94b92014-03-04 01:35:22451void SearchProvider::SortResults(bool is_keyword,
[email protected]0b9575f2014-07-30 11:58:37452 SearchSuggestionParser::Results* results) {
[email protected]d4a94b92014-03-04 01:35:22453 // Ignore suggested scores for non-keyword matches in keyword mode; if the
454 // server is allowed to score these, it could interfere with the user's
455 // ability to get good keyword results.
456 const bool abandon_suggested_scores =
457 !is_keyword && !providers_.keyword_provider().empty();
[email protected]0b9575f2014-07-30 11:58:37458 // Apply calculated relevance scores to suggestions if valid relevances were
[email protected]d4a94b92014-03-04 01:35:22459 // not provided or we're abandoning suggested scores entirely.
[email protected]2c802d12014-07-31 12:57:14460 if (!results->relevances_from_server || abandon_suggested_scores) {
[email protected]d4a94b92014-03-04 01:35:22461 ApplyCalculatedSuggestRelevance(&results->suggest_results);
462 ApplyCalculatedNavigationRelevance(&results->navigation_results);
463 // If abandoning scores entirely, also abandon the verbatim score.
464 if (abandon_suggested_scores)
465 results->verbatim_relevance = -1;
466 }
467
468 // Keep the result lists sorted.
469 const CompareScoredResults comparator = CompareScoredResults();
470 std::stable_sort(results->suggest_results.begin(),
471 results->suggest_results.end(),
472 comparator);
473 std::stable_sort(results->navigation_results.begin(),
474 results->navigation_results.end(),
475 comparator);
476}
477
[email protected]cfa164bf2014-03-19 11:51:15478void SearchProvider::LogFetchComplete(bool success, bool is_keyword) {
479 LogOmniboxSuggestRequest(REPLY_RECEIVED);
480 // Record response time for suggest requests sent to Google. We care
481 // only about the common case: the Google default provider used in
482 // non-keyword mode.
483 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
484 if (!is_keyword && default_url &&
[email protected]ce7ee5f2014-06-16 23:41:19485 (TemplateURLPrepopulateData::GetEngineType(
blundelld130d592015-06-21 19:29:13486 *default_url,
487 client()->GetTemplateURLService()->search_terms_data()) ==
[email protected]cfa164bf2014-03-19 11:51:15488 SEARCH_ENGINE_GOOGLE)) {
489 const base::TimeDelta elapsed_time =
490 base::TimeTicks::Now() - time_suggest_request_sent_;
491 if (success) {
492 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
493 elapsed_time);
494 } else {
495 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
496 elapsed_time);
497 }
498 }
499}
500
[email protected]cfa164bf2014-03-19 11:51:15501void SearchProvider::UpdateMatches() {
mpearson6c183672014-09-03 02:09:42502 PersistTopSuggestions(&default_results_);
503 PersistTopSuggestions(&keyword_results_);
[email protected]cfa164bf2014-03-19 11:51:15504 ConvertResultsToAutocompleteMatches();
505
506 // Check constraints that may be violated by suggested relevances.
507 if (!matches_.empty() &&
508 (default_results_.HasServerProvidedScores() ||
509 keyword_results_.HasServerProvidedScores())) {
510 // These blocks attempt to repair undesirable behavior by suggested
511 // relevances with minimal impact, preserving other suggested relevances.
[email protected]d0e4ad02014-08-22 18:58:33512 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
513 const bool is_extension_keyword = (keyword_url != NULL) &&
514 (keyword_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION);
515 if ((keyword_url != NULL) && !is_extension_keyword &&
[email protected]7bc5e162014-08-15 19:41:11516 (FindTopMatch() == matches_.end())) {
[email protected]d0e4ad02014-08-22 18:58:33517 // In non-extension keyword mode, disregard the keyword verbatim suggested
518 // relevance if necessary, so at least one match is allowed to be default.
519 // (In extension keyword mode this is not necessary because the extension
mpearson6c183672014-09-03 02:09:42520 // will return a default match.) Give keyword verbatim the lowest
521 // non-zero score to best reflect what the server desired.
522 DCHECK_EQ(0, keyword_results_.verbatim_relevance);
523 keyword_results_.verbatim_relevance = 1;
[email protected]cfa164bf2014-03-19 11:51:15524 ConvertResultsToAutocompleteMatches();
525 }
[email protected]89bd27d12014-04-12 17:36:23526 if (IsTopMatchSearchWithURLInput()) {
[email protected]cfa164bf2014-03-19 11:51:15527 // Disregard the suggested search and verbatim relevances if the input
528 // type is URL and the top match is a highly-ranked search suggestion.
529 // For example, prevent a search for "foo.com" from outranking another
530 // provider's navigation for "foo.com" or "foo.com/url_from_history".
531 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
532 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
533 default_results_.verbatim_relevance = -1;
534 keyword_results_.verbatim_relevance = -1;
535 ConvertResultsToAutocompleteMatches();
536 }
[email protected]d0e4ad02014-08-22 18:58:33537 if (!is_extension_keyword && (FindTopMatch() == matches_.end())) {
538 // Guarantee that SearchProvider returns a legal default match (except
539 // when in extension-based keyword mode). The omnibox always needs at
540 // least one legal default match, and it relies on SearchProvider in
541 // combination with KeywordProvider (for extension-based keywords) to
mpearson6c183672014-09-03 02:09:42542 // always return one. Give the verbatim suggestion the lowest non-zero
543 // scores to best reflect what the server desired.
544 DCHECK_EQ(0, default_results_.verbatim_relevance);
545 default_results_.verbatim_relevance = 1;
546 // We do not have to alter keyword_results_.verbatim_relevance here.
547 // If the user is in keyword mode, we already reverted (earlier in this
548 // function) the instructions to suppress keyword verbatim.
[email protected]cfa164bf2014-03-19 11:51:15549 ConvertResultsToAutocompleteMatches();
550 }
[email protected]89bd27d12014-04-12 17:36:23551 DCHECK(!IsTopMatchSearchWithURLInput());
[email protected]d0e4ad02014-08-22 18:58:33552 DCHECK(is_extension_keyword || (FindTopMatch() != matches_.end()));
[email protected]cfa164bf2014-03-19 11:51:15553 }
554 UMA_HISTOGRAM_CUSTOM_COUNTS(
555 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
mpearson6c183672014-09-03 02:09:42556
557 // Record the top suggestion (if any) for future use.
558 top_query_suggestion_match_contents_ = base::string16();
559 top_navigation_suggestion_ = GURL();
560 ACMatches::const_iterator first_match = FindTopMatch();
561 if ((first_match != matches_.end()) &&
562 !first_match->inline_autocompletion.empty()) {
563 // Identify if this match came from a query suggestion or a navsuggestion.
564 // In either case, extracts the identifying feature of the suggestion
565 // (query string or navigation url).
566 if (AutocompleteMatch::IsSearchType(first_match->type))
567 top_query_suggestion_match_contents_ = first_match->contents;
568 else
569 top_navigation_suggestion_ = first_match->destination_url;
570 }
571
[email protected]cfa164bf2014-03-19 11:51:15572 UpdateDone();
[email protected]cfa164bf2014-03-19 11:51:15573}
574
mpearsond37de7c2015-03-11 01:56:26575void SearchProvider::Run(bool query_is_private) {
[email protected]bc8bb0cd2013-06-24 21:50:23576 // Start a new request with the current input.
mpearson84f19a152015-03-12 19:42:21577 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05578
mpearsond37de7c2015-03-11 01:56:26579 if (!query_is_private) {
dtapuskadafcf892015-05-01 13:58:25580 default_fetcher_ =
581 CreateSuggestFetcher(kDefaultProviderURLFetcherID,
582 providers_.GetDefaultProviderURL(), input_);
mpearsond37de7c2015-03-11 01:56:26583 }
dtapuskadafcf892015-05-01 13:58:25584 keyword_fetcher_ =
585 CreateSuggestFetcher(kKeywordProviderURLFetcherID,
586 providers_.GetKeywordProviderURL(), keyword_input_);
[email protected]bc8bb0cd2013-06-24 21:50:23587
588 // Both the above can fail if the providers have been modified or deleted
589 // since the query began.
mpearson84f19a152015-03-12 19:42:21590 if (!default_fetcher_ && !keyword_fetcher_) {
[email protected]bc8bb0cd2013-06-24 21:50:23591 UpdateDone();
592 // We only need to update the listener if we're actually done.
593 if (done_)
594 listener_->OnProviderUpdate(false);
mpearsond37de7c2015-03-11 01:56:26595 } else {
596 // Sent at least one request.
597 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]bc8bb0cd2013-06-24 21:50:23598 }
[email protected]601858c02010-09-01 17:08:20599}
600
[email protected]8d457132010-11-04 18:13:40601void SearchProvider::DoHistoryQuery(bool minimal_changes) {
602 // The history query results are synchronous, so if minimal_changes is true,
603 // we still have the last results and don't need to do anything.
604 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29605 return;
606
grobye5fcee42014-09-26 03:36:46607 raw_keyword_history_results_.clear();
608 raw_default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29609
[email protected]78e5e432013-08-03 02:10:10610 if (OmniboxFieldTrial::SearchHistoryDisable(
611 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16612 return;
613
blundelld130d592015-06-21 19:29:13614 history::URLDatabase* url_db = client()->GetInMemoryDatabase();
[email protected]8d457132010-11-04 18:13:40615 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29616 return;
617
[email protected]51124552011-07-16 01:37:10618 // Request history for both the keyword and default provider. We grab many
619 // more matches than we'll ultimately clamp to so that if there are several
620 // recent multi-word matches who scores are lowered (see
grobye5fcee42014-09-26 03:36:46621 // ScoreHistoryResults()), they won't crowd out older, higher-scoring
[email protected]51124552011-07-16 01:37:10622 // matches. Note that this doesn't fix the problem entirely, but merely
623 // limits it to cases with a very large number of such multi-word matches; for
624 // now, this seems OK compared with the complexity of a real fix, which would
625 // require multiple searches and tracking of "single- vs. multi-word" in the
626 // database.
627 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47628 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
629 if (default_url) {
[email protected]b4bec972014-04-05 18:07:15630 const base::TimeTicks start_time = base::TimeTicks::Now();
grobye5fcee42014-09-26 03:36:46631 url_db->GetMostRecentKeywordSearchTerms(default_url->id(),
632 input_.text(),
633 num_matches,
634 &raw_default_history_results_);
[email protected]31afdf72013-09-26 04:29:36635 UMA_HISTOGRAM_TIMES(
636 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
637 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24638 }
[email protected]85b8d6f2012-05-08 20:53:47639 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
640 if (keyword_url) {
641 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
grobye5fcee42014-09-26 03:36:46642 keyword_input_.text(),
643 num_matches,
644 &raw_keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55645 }
initial.commit09911bf2008-07-26 23:55:29646}
647
bartn1c07e722014-10-27 19:34:24648base::TimeDelta SearchProvider::GetSuggestQueryDelay() const {
649 bool from_last_keystroke;
650 int polling_delay_ms;
651 OmniboxFieldTrial::GetSuggestPollingStrategy(&from_last_keystroke,
652 &polling_delay_ms);
653
654 base::TimeDelta delay(base::TimeDelta::FromMilliseconds(polling_delay_ms));
655 if (from_last_keystroke)
656 return delay;
657
658 base::TimeDelta time_since_last_suggest_request =
659 base::TimeTicks::Now() - time_suggest_request_sent_;
660 return std::max(base::TimeDelta(), delay - time_since_last_suggest_request);
661}
662
[email protected]6dc950f2012-07-16 19:49:08663void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
mpearsond37de7c2015-03-11 01:56:26664 bool query_is_private;
665 if (!IsQuerySuitableForSuggest(&query_is_private)) {
initial.commit09911bf2008-07-26 23:55:29666 StopSuggest();
[email protected]71b46152013-05-03 16:39:20667 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29668 return;
669 }
670
bartn1c07e722014-10-27 19:34:24671 if (OmniboxFieldTrial::DisableResultsCaching())
672 ClearAllResults();
673
initial.commit09911bf2008-07-26 23:55:29674 // For the minimal_changes case, if we finished the previous query and still
675 // have its results, or are allowed to keep running it, just do that, rather
676 // than starting a new query.
677 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24678 (!default_results_.suggest_results.empty() ||
679 !default_results_.navigation_results.empty() ||
680 !keyword_results_.suggest_results.empty() ||
681 !keyword_results_.navigation_results.empty() ||
[email protected]a2770a7d2014-04-22 19:33:35682 (!done_ && input_.want_asynchronous_matches())))
initial.commit09911bf2008-07-26 23:55:29683 return;
684
685 // We can't keep running any previous query, so halt it.
686 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42687
mpearson6c183672014-09-03 02:09:42688 UpdateAllOldResults(minimal_changes);
initial.commit09911bf2008-07-26 23:55:29689
[email protected]ee6110b2014-01-09 22:26:31690 // Update the content classifications of remaining results so they look good
691 // against the current input.
[email protected]23db6492014-01-16 02:35:30692 UpdateMatchContentsClass(input_.text(), &default_results_);
693 if (!keyword_input_.text().empty())
694 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31695
initial.commit09911bf2008-07-26 23:55:29696 // We can't start a new query if we're only allowed synchronous results.
[email protected]a2770a7d2014-04-22 19:33:35697 if (!input_.want_asynchronous_matches())
initial.commit09911bf2008-07-26 23:55:29698 return;
699
bartn1c07e722014-10-27 19:34:24700 // Kick off a timer that will start the URL fetch if it completes before
701 // the user types another character. Requests may be delayed to avoid
702 // flooding the server with requests that are likely to be thrown away later
703 // anyway.
704 const base::TimeDelta delay = GetSuggestQueryDelay();
705 if (delay <= base::TimeDelta()) {
mpearsond37de7c2015-03-11 01:56:26706 Run(query_is_private);
[email protected]515ffa942012-11-27 20:18:24707 return;
708 }
mpearsond37de7c2015-03-11 01:56:26709 timer_.Start(FROM_HERE,
710 delay,
711 base::Bind(&SearchProvider::Run,
712 base::Unretained(this),
713 query_is_private));
initial.commit09911bf2008-07-26 23:55:29714}
715
mpearson84f19a152015-03-12 19:42:21716void SearchProvider::CancelFetcher(scoped_ptr<net::URLFetcher>* fetcher) {
717 if (*fetcher) {
718 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
719 fetcher->reset();
720 }
721}
722
mpearsond37de7c2015-03-11 01:56:26723bool SearchProvider::IsQuerySuitableForSuggest(bool* query_is_private) const {
724 *query_is_private = IsQueryPotentionallyPrivate();
725
[email protected]3954c3a2012-04-10 20:17:55726 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
mpearsond37de7c2015-03-11 01:56:26727 // if the user has disabled it. Also don't send potentionally private data
728 // to the default search provider. (It's always okay to send explicit
729 // keyword input to a keyword suggest server, if any.)
[email protected]85b8d6f2012-05-08 20:53:47730 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
731 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
blundelld130d592015-06-21 19:29:13732 return !client()->IsOffTheRecord() && client()->SearchSuggestEnabled() &&
733 ((default_url && !default_url->suggestions_url().empty() &&
734 !*query_is_private) ||
735 (keyword_url && !keyword_url->suggestions_url().empty()));
mpearsond37de7c2015-03-11 01:56:26736}
[email protected]83c726482008-09-10 06:36:34737
mpearsond37de7c2015-03-11 01:56:26738bool SearchProvider::IsQueryPotentionallyPrivate() const {
[email protected]cac59d32010-08-09 23:23:14739 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34740 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34741
[email protected]cac59d32010-08-09 23:23:14742 // FORCED_QUERY means the user is explicitly asking us to search for this, so
743 // we assume it isn't a URL and/or there isn't private data.
[email protected]3dc75b12014-06-08 00:02:22744 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY)
mpearsond37de7c2015-03-11 01:56:26745 return false;
[email protected]83c726482008-09-10 06:36:34746
[email protected]f608ea102013-03-18 15:08:09747 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
748 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
749 // is both a waste of time and a disclosure of potentially private, local
750 // data. Other "schemes" may actually be usernames, and we don't want to send
751 // passwords. If the scheme is OK, we still need to check other cases below.
752 // If this is QUERY, then the presence of these schemes means the user
753 // explicitly typed one, and thus this is probably a URL that's being entered
754 // and happens to currently be invalid -- in which case we again want to run
755 // our checks below. Other QUERY cases are less likely to be URLs and thus we
756 // assume we're OK.
brettwbc17d2c82015-06-09 22:39:08757 if (!base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpScheme) &&
758 !base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
759 !base::LowerCaseEqualsASCII(input_.scheme(), url::kFtpScheme))
mpearsond37de7c2015-03-11 01:56:26760 return (input_.type() != metrics::OmniboxInputType::QUERY);
[email protected]cac59d32010-08-09 23:23:14761
762 // Don't send URLs with usernames, queries or refs. Some of these are
763 // private, and the Suggest server is unlikely to have any useful results
764 // for any of them. Also don't send URLs with ports, as we may initially
765 // think that a username + password is a host + port (and we don't want to
766 // send usernames/passwords), and even if the port really is a port, the
767 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58768 // Note that we only block based on refs if the input is URL-typed, as search
769 // queries can legitimately have #s in them which the URL parser
770 // overaggressively categorizes as a url with a ref.
[email protected]b45334502014-04-30 19:44:05771 const url::Parsed& parts = input_.parts();
[email protected]cac59d32010-08-09 23:23:14772 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58773 parts.query.is_nonempty() ||
[email protected]3dc75b12014-06-08 00:02:22774 (parts.ref.is_nonempty() &&
775 (input_.type() == metrics::OmniboxInputType::URL)))
mpearsond37de7c2015-03-11 01:56:26776 return true;
[email protected]cac59d32010-08-09 23:23:14777
778 // Don't send anything for https except the hostname. Hostnames are OK
779 // because they are visible when the TCP connection is established, but the
780 // specific path may reveal private information.
brettwbc17d2c82015-06-09 22:39:08781 if (base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36782 parts.path.is_nonempty())
mpearsond37de7c2015-03-11 01:56:26783 return true;
[email protected]83c726482008-09-10 06:36:34784
mpearsond37de7c2015-03-11 01:56:26785 return false;
[email protected]83c726482008-09-10 06:36:34786}
787
mpearson6c183672014-09-03 02:09:42788void SearchProvider::UpdateAllOldResults(bool minimal_changes) {
[email protected]dc735c02013-11-12 23:23:41789 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51790 // User is either in keyword mode with a blank input or out of
791 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24792 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51793 }
mpearson6c183672014-09-03 02:09:42794 UpdateOldResults(minimal_changes, &default_results_);
795 UpdateOldResults(minimal_changes, &keyword_results_);
[email protected]d1f0a7f2012-06-05 10:26:42796}
797
mpearson6c183672014-09-03 02:09:42798void SearchProvider::PersistTopSuggestions(
799 SearchSuggestionParser::Results* results) {
800 // Mark any results matching the current top results as having been received
801 // prior to the last keystroke. That prevents asynchronous updates from
802 // clobbering top results, which may be used for inline autocompletion.
803 // Other results don't need similar changes, because they shouldn't be
804 // displayed asynchronously anyway.
805 if (!top_query_suggestion_match_contents_.empty()) {
806 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
807 results->suggest_results.begin();
808 sug_it != results->suggest_results.end(); ++sug_it) {
809 if (sug_it->match_contents() == top_query_suggestion_match_contents_)
810 sug_it->set_received_after_last_keystroke(false);
811 }
812 }
813 if (top_navigation_suggestion_.is_valid()) {
814 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
815 results->navigation_results.begin();
816 nav_it != results->navigation_results.end(); ++nav_it) {
817 if (nav_it->url() == top_navigation_suggestion_)
818 nav_it->set_received_after_last_keystroke(false);
819 }
820 }
[email protected]d1f0a7f2012-06-05 10:26:42821}
822
[email protected]0b9575f2014-07-30 11:58:37823void SearchProvider::ApplyCalculatedSuggestRelevance(
824 SearchSuggestionParser::SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42825 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37826 SearchSuggestionParser::SuggestResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42827 result.set_relevance(
828 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
829 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07830 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42831 }
832}
833
[email protected]188b50c2013-03-28 07:19:42834void SearchProvider::ApplyCalculatedNavigationRelevance(
[email protected]0b9575f2014-07-30 11:58:37835 SearchSuggestionParser::NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42836 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37837 SearchSuggestionParser::NavigationResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42838 result.set_relevance(
839 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
840 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07841 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42842 }
843}
844
dtapuskadafcf892015-05-01 13:58:25845scoped_ptr<net::URLFetcher> SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12846 int id,
[email protected]9ff91722012-09-07 05:29:12847 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41848 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12849 if (!template_url || template_url->suggestions_url().empty())
850 return NULL;
851
852 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41853 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
[email protected]420472b22014-06-10 13:34:43854 search_term_args.input_type = input.type();
[email protected]14710852013-02-05 23:45:41855 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18856 search_term_args.page_classification = input.current_page_classification();
jdonnelly41c5b46a2015-07-10 21:24:38857 // Session token and prefetch data required for answers.
858 search_term_args.session_token = GetSessionToken();
859 if (!prefetch_data_.full_query_text.empty()) {
860 search_term_args.prefetch_query =
861 base::UTF16ToUTF8(prefetch_data_.full_query_text);
862 search_term_args.prefetch_query_type =
863 base::UTF16ToUTF8(prefetch_data_.query_type);
[email protected]2ef2a6642014-07-30 05:50:29864 }
[email protected]9ff91722012-09-07 05:29:12865 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19866 search_term_args,
blundelld130d592015-06-21 19:29:13867 client()->GetTemplateURLService()->search_terms_data()));
[email protected]9ff91722012-09-07 05:29:12868 if (!suggest_url.is_valid())
869 return NULL;
jdonnelly41c5b46a2015-07-10 21:24:38870
[email protected]9b9fa672013-11-07 06:04:52871 // Send the current page URL if user setting and URL requirements are met and
872 // the user is in the field trial.
blundelld130d592015-06-21 19:29:13873 TemplateURLService* template_url_service = client()->GetTemplateURLService();
mariakhomenko3ac684352015-06-18 20:01:17874 if (CanSendURL(input.current_url(), suggest_url, template_url,
[email protected]e6477f12014-08-05 07:59:54875 input.current_page_classification(),
blundelld130d592015-06-21 19:29:13876 template_url_service->search_terms_data(), client()) &&
[email protected]9b9fa672013-11-07 06:04:52877 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
mariakhomenko3ac684352015-06-18 20:01:17878 search_term_args.current_page_url = input.current_url().spec();
[email protected]9b9fa672013-11-07 06:04:52879 // Create the suggest URL again with the current page URL.
880 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
blundelld130d592015-06-21 19:29:13881 search_term_args, template_url_service->search_terms_data()));
[email protected]9b9fa672013-11-07 06:04:52882 }
[email protected]9ff91722012-09-07 05:29:12883
[email protected]9ff91722012-09-07 05:29:12884 LogOmniboxSuggestRequest(REQUEST_SENT);
885
dtapuskadafcf892015-05-01 13:58:25886 scoped_ptr<net::URLFetcher> fetcher =
[email protected]9ff91722012-09-07 05:29:12887 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
amohammadkhanf76ae112015-09-14 17:34:43888 data_use_measurement::DataUseUserData::AttachToFetcher(
889 fetcher.get(), data_use_measurement::DataUseUserData::OMNIBOX);
blundelld130d592015-06-21 19:29:13890 fetcher->SetRequestContext(client()->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34891 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30892 // Add Chrome experiment state to the request headers.
893 net::HttpRequestHeaders headers;
asvitkine9a279832015-12-18 02:35:50894 variations::AppendVariationHeaders(
blundelld130d592015-06-21 19:29:13895 fetcher->GetOriginalURL(), client()->IsOffTheRecord(), false, &headers);
[email protected]bd3b4712012-12-18 17:01:30896 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24897 fetcher->Start();
898 return fetcher;
899}
900
[email protected]344946a12012-12-20 12:03:42901void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29902 // Convert all the results to matches and add them to a map, so we can keep
903 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36904 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29905 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23906 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24907 int did_not_accept_keyword_suggestion =
908 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29909 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
910 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29911
[email protected]d30268a2013-06-25 22:31:07912 bool relevance_from_server;
913 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24914 int did_not_accept_default_suggestion =
915 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08916 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
917 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]7bc5e162014-08-15 19:41:11918 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]d1f0a7f2012-06-05 10:26:42919 if (verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44920 const base::string16& trimmed_verbatim =
921 base::CollapseWhitespace(input_.text(), false);
[email protected]716cd372014-08-15 18:56:03922
923 // Verbatim results don't get suggestions and hence, answers.
924 // Scan previous matches if the last answer-bearing suggestion matches
925 // verbatim, and if so, copy over answer contents.
926 base::string16 answer_contents;
927 base::string16 answer_type;
jdonnelly7393cee2014-10-31 01:52:56928 scoped_ptr<SuggestionAnswer> answer;
[email protected]716cd372014-08-15 18:56:03929 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
930 ++it) {
jdonnelly7393cee2014-10-31 01:52:56931 if (it->answer && it->fill_into_edit == trimmed_verbatim) {
[email protected]716cd372014-08-15 18:56:03932 answer_contents = it->answer_contents;
933 answer_type = it->answer_type;
jdonnelly7393cee2014-10-31 01:52:56934 answer = SuggestionAnswer::copy(it->answer.get());
[email protected]716cd372014-08-15 18:56:03935 break;
936 }
937 }
938
[email protected]0b9575f2014-07-30 11:58:37939 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44940 trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]716cd372014-08-15 18:56:03941 trimmed_verbatim, base::string16(), base::string16(), answer_contents,
jdonnelly7393cee2014-10-31 01:52:56942 answer_type, answer.Pass(), std::string(), std::string(), false,
943 verbatim_relevance, relevance_from_server, false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37944 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
[email protected]7bc5e162014-08-15 19:41:11945 false, keyword_url != NULL, &map);
[email protected]d1f0a7f2012-06-05 10:26:42946 }
[email protected]5423e562013-02-07 03:58:45947 if (!keyword_input_.text().empty()) {
[email protected]5423e562013-02-07 03:58:45948 // We only create the verbatim search query match for a keyword
949 // if it's not an extension keyword. Extension keywords are handled
950 // in KeywordProvider::Start(). (Extensions are complicated...)
951 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
952 // to the keyword verbatim search query. Do not create other matches
953 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:25954 if (keyword_url &&
955 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:07956 bool keyword_relevance_from_server;
957 const int keyword_verbatim_relevance =
958 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:28959 if (keyword_verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44960 const base::string16& trimmed_verbatim =
961 base::CollapseWhitespace(keyword_input_.text(), false);
[email protected]0b9575f2014-07-30 11:58:37962 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44963 trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
964 trimmed_verbatim, base::string16(), base::string16(),
jdonnelly7393cee2014-10-31 01:52:56965 base::string16(), base::string16(), nullptr, std::string(),
966 std::string(), true, keyword_verbatim_relevance,
967 keyword_relevance_from_server, false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37968 AddMatchToMap(verbatim, std::string(),
[email protected]7bc5e162014-08-15 19:41:11969 did_not_accept_keyword_suggestion, false, true, &map);
[email protected]dab8d52d2013-03-05 07:35:28970 }
[email protected]5423e562013-02-07 03:58:45971 }
972 }
grobye5fcee42014-09-26 03:36:46973 AddRawHistoryResultsToMap(true, did_not_accept_keyword_suggestion, &map);
974 AddRawHistoryResultsToMap(false, did_not_accept_default_suggestion, &map);
[email protected]257ab712009-04-14 17:16:24975
[email protected]d1cb6a822013-09-18 19:43:00976 AddSuggestResultsToMap(keyword_results_.suggest_results,
977 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:18978 AddSuggestResultsToMap(default_results_.suggest_results,
979 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:29980
[email protected]d30268a2013-06-25 22:31:07981 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:29982 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:07983 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:29984
[email protected]d30268a2013-06-25 22:31:07985 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
986 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:29987
[email protected]d30268a2013-06-25 22:31:07988 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
mpearson6c183672014-09-03 02:09:42989 // suggest/navsuggest matches, regardless of origin. We always include in
990 // that set a legal default match if possible. If Instant Extended is enabled
991 // and we have server-provided (and thus hopefully more accurate) scores for
992 // some suggestions, we allow more of those, until we reach
[email protected]d30268a2013-06-25 22:31:07993 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
994 // whole popup).
995 //
996 // We will always return any verbatim matches, no matter how we obtained their
997 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
998 // higher-scoring matches under the conditions above.
999 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
jdonnelly55f66142014-09-25 23:08:111000
mpearson6c183672014-09-03 02:09:421001 // Guarantee that if there's a legal default match anywhere in the result
1002 // set that it'll get returned. The rotate() call does this by moving the
1003 // default match to the front of the list.
1004 ACMatches::iterator default_match = FindTopMatch(&matches);
1005 if (default_match != matches.end())
1006 std::rotate(matches.begin(), default_match, default_match + 1);
[email protected]3723e6e2012-06-11 21:06:561007
jdonnelly55f66142014-09-25 23:08:111008 // It's possible to get a copy of an answer from previous matches and get the
1009 // same or a different answer to another server-provided suggestion. In the
1010 // future we may decide that we want to have answers attached to multiple
1011 // suggestions, but the current assumption is that there should only ever be
1012 // one suggestion with an answer. To maintain this assumption, remove any
1013 // answers after the first.
1014 RemoveExtraAnswers(&matches);
1015
1016 matches_.clear();
[email protected]d30268a2013-06-25 22:31:071017 size_t num_suggestions = 0;
1018 for (ACMatches::const_iterator i(matches.begin());
1019 (i != matches.end()) &&
1020 (matches_.size() < AutocompleteResult::kMaxMatches);
1021 ++i) {
1022 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
1023 // verbatim result, so this condition basically means "if this match is a
1024 // suggestion of some sort".
1025 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
1026 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
1027 // If we've already hit the limit on non-server-scored suggestions, and
1028 // this isn't a server-scored suggestion we can add, skip it.
1029 if ((num_suggestions >= kMaxMatches) &&
sdefresne51bbec7b2015-08-03 14:18:131030 (!search::IsInstantExtendedAPIEnabled() ||
[email protected]d30268a2013-06-25 22:31:071031 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
1032 continue;
1033 }
1034
1035 ++num_suggestions;
1036 }
1037
1038 matches_.push_back(*i);
1039 }
[email protected]31afdf72013-09-26 04:29:361040 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
1041 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:421042}
1043
jdonnelly55f66142014-09-25 23:08:111044void SearchProvider::RemoveExtraAnswers(ACMatches* matches) {
1045 bool answer_seen = false;
1046 for (ACMatches::iterator it = matches->begin(); it != matches->end(); ++it) {
jdonnelly7393cee2014-10-31 01:52:561047 if (it->answer) {
jdonnelly55f66142014-09-25 23:08:111048 if (!answer_seen) {
1049 answer_seen = true;
1050 } else {
1051 it->answer_contents.clear();
1052 it->answer_type.clear();
jdonnelly7393cee2014-10-31 01:52:561053 it->answer.reset();
jdonnelly55f66142014-09-25 23:08:111054 }
1055 }
1056 }
1057}
1058
[email protected]89bd27d12014-04-12 17:36:231059ACMatches::const_iterator SearchProvider::FindTopMatch() const {
[email protected]0a8718b12013-11-13 18:41:311060 ACMatches::const_iterator it = matches_.begin();
1061 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
1062 ++it;
1063 return it;
[email protected]9dfb4d362013-04-05 02:15:121064}
1065
[email protected]89bd27d12014-04-12 17:36:231066bool SearchProvider::IsTopMatchSearchWithURLInput() const {
1067 ACMatches::const_iterator first_match = FindTopMatch();
[email protected]3dc75b12014-06-08 00:02:221068 return (input_.type() == metrics::OmniboxInputType::URL) &&
[email protected]0a8718b12013-11-13 18:41:311069 (first_match != matches_.end()) &&
1070 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
[email protected]78981d8c2014-05-09 15:05:471071 (first_match->type != AutocompleteMatchType::NAVSUGGEST) &&
1072 (first_match->type != AutocompleteMatchType::NAVSUGGEST_PERSONALIZED);
[email protected]344946a12012-12-20 12:03:421073}
1074
[email protected]257ab712009-04-14 17:16:241075void SearchProvider::AddNavigationResultsToMatches(
[email protected]0b9575f2014-07-30 11:58:371076 const SearchSuggestionParser::NavigationResults& navigation_results,
[email protected]d30268a2013-06-25 22:31:071077 ACMatches* matches) {
[email protected]0b9575f2014-07-30 11:58:371078 for (SearchSuggestionParser::NavigationResults::const_iterator it =
1079 navigation_results.begin(); it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:071080 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:231081 // In the absence of suggested relevance scores, use only the single
1082 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:071083 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:231084 return;
[email protected]257ab712009-04-14 17:16:241085 }
1086}
1087
grobye5fcee42014-09-26 03:36:461088void SearchProvider::AddRawHistoryResultsToMap(bool is_keyword,
1089 int did_not_accept_suggestion,
1090 MatchMap* map) {
[email protected]31afdf72013-09-26 04:29:361091 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]51124552011-07-16 01:37:101092
jdonnelly41c5b46a2015-07-10 21:24:381093 const SearchSuggestionParser::SuggestResults* transformed_results =
1094 is_keyword ? &transformed_keyword_history_results_
1095 : &transformed_default_history_results_;
grobye5fcee42014-09-26 03:36:461096 DCHECK(transformed_results);
1097 AddTransformedHistoryResultsToMap(
1098 *transformed_results, did_not_accept_suggestion, map);
[email protected]31afdf72013-09-26 04:29:361099 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1100 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:101101}
1102
grobye5fcee42014-09-26 03:36:461103void SearchProvider::AddTransformedHistoryResultsToMap(
1104 const SearchSuggestionParser::SuggestResults& transformed_results,
1105 int did_not_accept_suggestion,
1106 MatchMap* map) {
1107 for (SearchSuggestionParser::SuggestResults::const_iterator i(
1108 transformed_results.begin());
1109 i != transformed_results.end();
1110 ++i) {
1111 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true,
1112 providers_.GetKeywordProviderURL() != NULL, map);
1113 }
1114}
1115
1116SearchSuggestionParser::SuggestResults
1117SearchProvider::ScoreHistoryResultsHelper(const HistoryResults& results,
1118 bool base_prevent_inline_autocomplete,
1119 bool input_multiple_words,
1120 const base::string16& input_text,
1121 bool is_keyword) {
[email protected]0b9575f2014-07-30 11:58:371122 SearchSuggestionParser::SuggestResults scored_results;
[email protected]ab5fd2f2014-07-17 19:18:521123 // True if the user has asked this exact query previously.
1124 bool found_what_you_typed_match = false;
[email protected]78e5e432013-08-03 02:10:101125 const bool prevent_search_history_inlining =
1126 OmniboxFieldTrial::SearchHistoryPreventInlining(
1127 input_.current_page_classification());
[email protected]c2ca3fd2014-03-22 03:07:441128 const base::string16& trimmed_input =
1129 base::CollapseWhitespace(input_text, false);
[email protected]257ab712009-04-14 17:16:241130 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1131 ++i) {
[email protected]c2ca3fd2014-03-22 03:07:441132 const base::string16& trimmed_suggestion =
1133 base::CollapseWhitespace(i->term, false);
1134
[email protected]51124552011-07-16 01:37:101135 // Don't autocomplete multi-word queries that have only been seen once
1136 // unless the user has typed more than one word.
1137 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
[email protected]c2ca3fd2014-03-22 03:07:441138 (!input_multiple_words && (i->visits < 2) &&
1139 HasMultipleWords(trimmed_suggestion));
[email protected]51124552011-07-16 01:37:101140
[email protected]78e5e432013-08-03 02:10:101141 int relevance = CalculateRelevanceForHistory(
1142 i->time, is_keyword, !prevent_inline_autocomplete,
1143 prevent_search_history_inlining);
[email protected]ab5fd2f2014-07-17 19:18:521144 // Add the match to |scored_results| by putting the what-you-typed match
1145 // on the front and appending all other matches. We want the what-you-
1146 // typed match to always be first.
[email protected]0b9575f2014-07-30 11:58:371147 SearchSuggestionParser::SuggestResults::iterator insertion_position =
1148 scored_results.end();
[email protected]ab5fd2f2014-07-17 19:18:521149 if (trimmed_suggestion == trimmed_input) {
1150 found_what_you_typed_match = true;
1151 insertion_position = scored_results.begin();
1152 }
mpearson6c183672014-09-03 02:09:421153 SearchSuggestionParser::SuggestResult history_suggestion(
1154 trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
1155 trimmed_suggestion, base::string16(), base::string16(),
jdonnelly7393cee2014-10-31 01:52:561156 base::string16(), base::string16(), nullptr, std::string(),
1157 std::string(), is_keyword, relevance, false, false, trimmed_input);
mpearson6c183672014-09-03 02:09:421158 // History results are synchronous; they are received on the last keystroke.
1159 history_suggestion.set_received_after_last_keystroke(false);
1160 scored_results.insert(insertion_position, history_suggestion);
[email protected]257ab712009-04-14 17:16:241161 }
[email protected]51124552011-07-16 01:37:101162
1163 // History returns results sorted for us. However, we may have docked some
[email protected]ab5fd2f2014-07-17 19:18:521164 // results' scores, so things are no longer in order. While keeping the
1165 // what-you-typed match at the front (if it exists), do a stable sort to get
[email protected]51124552011-07-16 01:37:101166 // things back in order without otherwise disturbing results with equal
1167 // scores, then force the scores to be unique, so that the order in which
1168 // they're shown is deterministic.
[email protected]ab5fd2f2014-07-17 19:18:521169 std::stable_sort(scored_results.begin() +
1170 (found_what_you_typed_match ? 1 : 0),
1171 scored_results.end(),
[email protected]55ce8f12012-05-09 04:44:081172 CompareScoredResults());
[email protected]7e3b77f2014-07-25 02:29:441173
1174 // Don't autocomplete to search terms that would normally be treated as URLs
1175 // when typed. For example, if the user searched for "google.com" and types
1176 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1177 // the input will look like a URL but act like a search, which is confusing.
1178 // The 1200 relevance score threshold in the test below is the lowest
1179 // possible score in CalculateRelevanceForHistory()'s aggressive-scoring
1180 // curve. This is an appropriate threshold to use to decide if we're overly
1181 // aggressively inlining because, if we decide the answer is yes, the
1182 // way we resolve it it to not use the aggressive-scoring curve.
1183 // NOTE: We don't check for autocompleting to URLs in the following cases:
1184 // * When inline autocomplete is disabled, we won't be inline autocompleting
1185 // this term, so we don't need to worry about confusion as much. This
1186 // also prevents calling Classify() again from inside the classifier
1187 // (which will corrupt state and likely crash), since the classifier
1188 // always disables inline autocomplete.
1189 // * When the user has typed the whole string before as a query, then it's
1190 // likely the user has no expectation that term should be interpreted as
1191 // as a URL, so we need not do anything special to preserve user
1192 // expectation.
[email protected]51124552011-07-16 01:37:101193 int last_relevance = 0;
[email protected]7e3b77f2014-07-25 02:29:441194 if (!base_prevent_inline_autocomplete && !found_what_you_typed_match &&
hashimoto663b9f42014-08-26 04:29:201195 scored_results.front().relevance() >= 1200) {
[email protected]7e3b77f2014-07-25 02:29:441196 AutocompleteMatch match;
blundelld130d592015-06-21 19:29:131197 client()->Classify(scored_results.front().suggestion(), false, false,
1198 input_.current_page_classification(), &match, NULL);
[email protected]7e3b77f2014-07-25 02:29:441199 // Demote this match that would normally be interpreted as a URL to have
1200 // the highest score a previously-issued search query could have when
1201 // scoring with the non-aggressive method. A consequence of demoting
1202 // by revising |last_relevance| is that this match and all following
1203 // matches get demoted; the relative order of matches is preserved.
1204 // One could imagine demoting only those matches that might cause
1205 // confusion (which, by the way, might change the relative order of
1206 // matches. We have decided to go with the simple demote-all approach
1207 // because selective demotion requires multiple Classify() calls and
1208 // such calls can be expensive (as expensive as running the whole
1209 // autocomplete system).
1210 if (!AutocompleteMatch::IsSearchType(match.type)) {
1211 last_relevance = CalculateRelevanceForHistory(
1212 base::Time::Now(), is_keyword, false,
1213 prevent_search_history_inlining);
1214 }
1215 }
1216
[email protected]0b9575f2014-07-30 11:58:371217 for (SearchSuggestionParser::SuggestResults::iterator i(
1218 scored_results.begin()); i != scored_results.end(); ++i) {
[email protected]7e3b77f2014-07-25 02:29:441219 if ((last_relevance != 0) && (i->relevance() >= last_relevance))
[email protected]55ce8f12012-05-09 04:44:081220 i->set_relevance(last_relevance - 1);
1221 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101222 }
1223
[email protected]55ce8f12012-05-09 04:44:081224 return scored_results;
[email protected]257ab712009-04-14 17:16:241225}
1226
grobye5fcee42014-09-26 03:36:461227void SearchProvider::ScoreHistoryResults(
1228 const HistoryResults& results,
1229 bool is_keyword,
1230 SearchSuggestionParser::SuggestResults* scored_results) {
1231 DCHECK(scored_results);
jdonnellye5f055d92015-01-15 00:58:581232 scored_results->clear();
1233
grobye5fcee42014-09-26 03:36:461234 if (results.empty()) {
grobye5fcee42014-09-26 03:36:461235 return;
1236 }
1237
1238 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1239 (input_.type() == metrics::OmniboxInputType::URL);
1240 const base::string16 input_text = GetInput(is_keyword).text();
1241 bool input_multiple_words = HasMultipleWords(input_text);
1242
1243 if (!prevent_inline_autocomplete && input_multiple_words) {
1244 // ScoreHistoryResultsHelper() allows autocompletion of multi-word, 1-visit
1245 // queries if the input also has multiple words. But if we were already
1246 // scoring a multi-word, multi-visit query aggressively, and the current
1247 // input is still a prefix of it, then changing the suggestion suddenly
1248 // feels wrong. To detect this case, first score as if only one word has
1249 // been typed, then check if the best result came from aggressive search
1250 // history scoring. If it did, then just keep that score set. This
1251 // 1200 the lowest possible score in CalculateRelevanceForHistory()'s
1252 // aggressive-scoring curve.
1253 *scored_results = ScoreHistoryResultsHelper(
1254 results, prevent_inline_autocomplete, false, input_text, is_keyword);
1255 if ((scored_results->front().relevance() < 1200) ||
1256 !HasMultipleWords(scored_results->front().suggestion()))
1257 scored_results->clear(); // Didn't detect the case above, score normally.
1258 }
1259 if (scored_results->empty()) {
1260 *scored_results = ScoreHistoryResultsHelper(results,
1261 prevent_inline_autocomplete,
1262 input_multiple_words,
1263 input_text,
1264 is_keyword);
1265 }
1266}
1267
[email protected]0b9575f2014-07-30 11:58:371268void SearchProvider::AddSuggestResultsToMap(
1269 const SearchSuggestionParser::SuggestResults& results,
1270 const std::string& metadata,
1271 MatchMap* map) {
[email protected]7bc5e162014-08-15 19:41:111272 for (size_t i = 0; i < results.size(); ++i) {
1273 AddMatchToMap(results[i], metadata, i, false,
1274 providers_.GetKeywordProviderURL() != NULL, map);
1275 }
initial.commit09911bf2008-07-26 23:55:291276}
1277
[email protected]d30268a2013-06-25 22:31:071278int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561279 // Use the suggested verbatim relevance score if it is non-negative (valid),
1280 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281281 // and if it won't suppress verbatim, leaving no default provider matches.
1282 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561283 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281284 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561285 // Check for results on each verbatim calculation, as results from older
1286 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231287 bool use_server_relevance =
1288 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281289 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231290 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241291 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231292 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071293 if (relevance_from_server)
1294 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231295 return use_server_relevance ?
1296 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521297}
[email protected]d1f0a7f2012-06-05 10:26:421298
[email protected]382a0642012-06-06 06:13:521299int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471300 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361301 return 250;
[email protected]dab8d52d2013-03-05 07:35:281302 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1303}
[email protected]52d08b12009-10-19 18:42:361304
[email protected]dab8d52d2013-03-05 07:35:281305int SearchProvider::
1306 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291307 switch (input_.type()) {
[email protected]3dc75b12014-06-08 00:02:221308 case metrics::OmniboxInputType::UNKNOWN:
1309 case metrics::OmniboxInputType::QUERY:
1310 case metrics::OmniboxInputType::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131311 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291312
[email protected]3dc75b12014-06-08 00:02:221313 case metrics::OmniboxInputType::URL:
[email protected]52d08b12009-10-19 18:42:361314 return 850;
initial.commit09911bf2008-07-26 23:55:291315
1316 default:
1317 NOTREACHED();
1318 return 0;
1319 }
1320}
1321
[email protected]d30268a2013-06-25 22:31:071322int SearchProvider::GetKeywordVerbatimRelevance(
1323 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281324 // Use the suggested verbatim relevance score if it is non-negative (valid),
1325 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1326 // and if it won't suppress verbatim, leaving no keyword provider matches.
1327 // Otherwise, if the keyword provider returned no matches and was still able
1328 // to suppress verbatim, the user would have no search/nav matches and may be
1329 // left unable to search using their keyword provider from the omnibox.
1330 // Check for results on each verbatim calculation, as results from older
1331 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231332 bool use_server_relevance =
1333 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281334 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231335 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241336 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231337 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071338 if (relevance_from_server)
1339 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231340 return use_server_relevance ?
1341 keyword_results_.verbatim_relevance :
1342 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
mpearson6456fb62015-11-13 06:44:281343 true,
[email protected]bc8bb0cd2013-06-24 21:50:231344 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451345}
1346
[email protected]51124552011-07-16 01:37:101347int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231348 const base::Time& time,
[email protected]51124552011-07-16 01:37:101349 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101350 bool use_aggressive_method,
1351 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181352 // The relevance of past searches falls off over time. There are two distinct
1353 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101354 // provider that we want to score aggressively), the score is in the range
1355 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161356 // it's in the range 1200-1299). If the second equation is used the
1357 // relevance of a search 15 minutes ago is discounted 50 points, while the
1358 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231359 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421360 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101361 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181362 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101363 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181364 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161365 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101366 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161367 max_score = 1299;
1368 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181369 std::pow(elapsed_time / autocomplete_time, 2.5));
1370 }
1371 elapsed_time -= autocomplete_time;
1372 }
1373
[email protected]c3a4bd992010-08-18 20:25:011374 const int score_discount =
1375 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291376
[email protected]6c85aa02009-02-27 12:08:091377 // Don't let scores go below 0. Negative relevance scores are meaningful in
1378 // a different way.
initial.commit09911bf2008-07-26 23:55:291379 int base_score;
[email protected]51124552011-07-16 01:37:101380 if (is_primary_provider)
[email protected]3dc75b12014-06-08 00:02:221381 base_score = (input_.type() == metrics::OmniboxInputType::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101382 else
1383 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291384 return std::max(0, base_score - score_discount);
1385}
1386
initial.commit09911bf2008-07-26 23:55:291387AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]0b9575f2014-07-30 11:58:371388 const SearchSuggestionParser::NavigationResult& navigation) {
[email protected]5889bfb2014-03-19 00:26:481389 base::string16 input;
1390 const bool trimmed_whitespace = base::TrimWhitespace(
1391 navigation.from_keyword_provider() ?
1392 keyword_input_.text() : input_.text(),
1393 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
[email protected]55ce8f12012-05-09 04:44:081394 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]78981d8c2014-05-09 15:05:471395 navigation.type());
[email protected]55ce8f12012-05-09 04:44:081396 match.destination_url = navigation.url();
[email protected]78981d8c2014-05-09 15:05:471397 BaseSearchProvider::SetDeletionURL(navigation.deletion_url(), &match);
[email protected]23db6492014-01-16 02:35:301398 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551399 // without trimming the scheme, so we can find matches at the beginning of the
1400 // scheme.
[email protected]371dab12012-06-01 03:23:551401 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301402 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551403 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301404 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351405 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1406 (!prefix || (match_start != 0));
rsleevi24f64dc22015-08-07 21:39:211407 const url_formatter::FormatUrlTypes format_types =
1408 url_formatter::kFormatUrlOmitAll &
1409 ~(trim_http ? 0 : url_formatter::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551410
blundelld130d592015-06-21 19:29:131411 const std::string languages(client()->GetAcceptLanguages());
[email protected]23db6492014-01-16 02:35:301412 size_t inline_autocomplete_offset = (prefix == NULL) ?
1413 base::string16::npos : (match_start + input.length());
[email protected]371dab12012-06-01 03:23:551414 match.fill_into_edit +=
[email protected]5655ea32014-06-21 05:28:081415 AutocompleteInput::FormattedStringWithEquivalentMeaning(
1416 navigation.url(),
rsleevi24f64dc22015-08-07 21:39:211417 url_formatter::FormatUrl(navigation.url(), languages, format_types,
1418 net::UnescapeRule::SPACES, nullptr, nullptr,
1419 &inline_autocomplete_offset),
blundelld130d592015-06-21 19:29:131420 client()->GetSchemeClassifier());
[email protected]14119032013-11-07 08:14:261421 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1422 // Otherwise, user edits to a suggestion would show non-Search results.
[email protected]3dc75b12014-06-08 00:02:221423 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581424 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031425 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261426 ++inline_autocomplete_offset;
1427 }
[email protected]6c94a1022014-02-21 03:48:041428 if (inline_autocomplete_offset != base::string16::npos) {
[email protected]518024c2013-07-19 23:40:251429 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1430 match.inline_autocompletion =
1431 match.fill_into_edit.substr(inline_autocomplete_offset);
1432 }
[email protected]6c94a1022014-02-21 03:48:041433 // An inlineable navsuggestion can only be the default match when there
1434 // is no keyword provider active, lest it appear first and break the user
mpearson6c183672014-09-03 02:09:421435 // out of keyword mode. We also must have received the navsuggestion before
1436 // the last keystroke, to prevent asynchronous inline autocompletions changes.
1437 // The navsuggestion can also only be default if either the inline
[email protected]5889bfb2014-03-19 00:26:481438 // autocompletion is empty or we're not preventing inline autocompletion.
1439 // Finally, if we have an inlineable navsuggestion with an inline completion
1440 // that we're not preventing, make sure we didn't trim any whitespace.
1441 // We don't want to claim http://foo.com/bar is inlineable against the
1442 // input "foo.com/b ".
mpearson6c183672014-09-03 02:09:421443 match.allowed_to_be_default_match =
1444 (prefix != NULL) &&
[email protected]6c94a1022014-02-21 03:48:041445 (providers_.GetKeywordProviderURL() == NULL) &&
mpearson6c183672014-09-03 02:09:421446 !navigation.received_after_last_keystroke() &&
[email protected]5889bfb2014-03-19 00:26:481447 (match.inline_autocompletion.empty() ||
[email protected]78981d8c2014-05-09 15:05:471448 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
mpearson4923cab62015-06-30 21:57:531449 match.EnsureUWYTIsAllowedToBeDefault(input_, client()->GetAcceptLanguages(),
blundelld130d592015-06-21 19:29:131450 client()->GetTemplateURLService());
[email protected]371dab12012-06-01 03:23:551451
[email protected]23db6492014-01-16 02:35:301452 match.contents = navigation.match_contents();
1453 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081454 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551455 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1456 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071457
1458 match.RecordAdditionalInfo(
1459 kRelevanceFromServerKey,
1460 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181461 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071462
initial.commit09911bf2008-07-26 23:55:291463 return match;
1464}
[email protected]4ab4c7c2010-11-24 04:49:341465
1466void SearchProvider::UpdateDone() {
mpearson84f19a152015-03-12 19:42:211467 // We're done when the timer isn't running and there are no suggest queries
1468 // pending.
1469 done_ = !timer_.IsRunning() && !default_fetcher_ && !keyword_fetcher_;
[email protected]4ab4c7c2010-11-24 04:49:341470}
[email protected]20184242014-05-14 02:57:421471
1472std::string SearchProvider::GetSessionToken() {
1473 base::TimeTicks current_time(base::TimeTicks::Now());
1474 // Renew token if it expired.
1475 if (current_time > token_expiration_time_) {
1476 const size_t kTokenBytes = 12;
1477 std::string raw_data;
Brett Wilsone3c4d1a2015-07-07 23:38:091478 base::RandBytes(base::WriteInto(&raw_data, kTokenBytes + 1), kTokenBytes);
[email protected]20184242014-05-14 02:57:421479 base::Base64Encode(raw_data, &current_token_);
[email protected]ab2c31f72014-05-17 17:03:531480
1481 // Make the base64 encoded value URL and filename safe(see RFC 3548).
1482 std::replace(current_token_.begin(), current_token_.end(), '+', '-');
1483 std::replace(current_token_.begin(), current_token_.end(), '/', '_');
[email protected]20184242014-05-14 02:57:421484 }
1485
1486 // Extend expiration time another 60 seconds.
1487 token_expiration_time_ = current_time + base::TimeDelta::FromSeconds(60);
1488
1489 return current_token_;
1490}
[email protected]2ef2a6642014-07-30 05:50:291491
grobye5fcee42014-09-26 03:36:461492AnswersQueryData SearchProvider::FindAnswersPrefetchData() {
1493 // Retrieve the top entry from scored history results.
1494 MatchMap map;
1495 AddTransformedHistoryResultsToMap(transformed_keyword_history_results_,
1496 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
1497 &map);
1498 AddTransformedHistoryResultsToMap(transformed_default_history_results_,
1499 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
1500 &map);
1501
1502 ACMatches matches;
1503 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
1504 matches.push_back(i->second);
1505 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
1506
1507 // If there is a top scoring entry, find the corresponding answer.
1508 if (!matches.empty())
1509 return answers_cache_.GetTopAnswerEntry(matches[0].contents);
1510
1511 return AnswersQueryData();
[email protected]2ef2a6642014-07-30 05:50:291512}