blob: 666e966d9e891debec035204348bde7626e0122d [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
avif57136c12015-12-25 23:27:457#include <stddef.h>
[email protected]1cb2dac2010-03-08 21:49:158#include <algorithm>
[email protected]c3a4bd992010-08-18 20:25:019#include <cmath>
dcheng51ace48a2015-12-26 22:45:1710#include <utility>
[email protected]1cb2dac2010-03-08 21:49:1511
[email protected]20184242014-05-14 02:57:4212#include "base/base64.h"
mpearsond37de7c2015-03-11 01:56:2613#include "base/bind.h"
[email protected]2041cf342010-02-19 03:15:5914#include "base/callback.h"
[email protected]51124552011-07-16 01:37:1015#include "base/i18n/break_iterator.h"
[email protected]503d03872011-05-06 08:36:2616#include "base/i18n/case_conversion.h"
[email protected]ffbec692012-02-26 20:26:4217#include "base/json/json_string_value_serializer.h"
asvitkinea0f05db2015-06-16 21:45:4618#include "base/metrics/histogram_macros.h"
[email protected]f7f41c0e2014-08-11 04:22:2319#include "base/metrics/user_metrics.h"
[email protected]20184242014-05-14 02:57:4220#include "base/rand_util.h"
[email protected]5889bfb2014-03-19 00:26:4821#include "base/strings/string_util.h"
[email protected]135cb802013-06-09 16:44:2022#include "base/strings/utf_string_conversions.h"
a-v-ydd768d54b2016-03-25 21:07:4623#include "base/trace_event/trace_event.h"
amohammadkhanf76ae112015-09-14 17:34:4324#include "components/data_use_measurement/core/data_use_user_data.h"
[email protected]e3ce70ac2014-06-26 18:34:5625#include "components/history/core/browser/in_memory_database.h"
[email protected]73b2d1e72014-06-25 23:45:3626#include "components/history/core/browser/keyword_search_term.h"
[email protected]3dc75b12014-06-08 00:02:2227#include "components/metrics/proto/omnibox_input_type.pb.h"
blundell2102f7c2015-07-09 10:00:5328#include "components/omnibox/browser/autocomplete_provider_client.h"
29#include "components/omnibox/browser/autocomplete_provider_listener.h"
30#include "components/omnibox/browser/autocomplete_result.h"
31#include "components/omnibox/browser/keyword_provider.h"
32#include "components/omnibox/browser/omnibox_field_trial.h"
33#include "components/omnibox/browser/suggestion_answer.h"
34#include "components/omnibox/browser/url_prefix.h"
[email protected]720b10492014-07-23 08:48:4035#include "components/search/search.h"
[email protected]bf5c532d2014-07-05 00:29:5336#include "components/search_engines/template_url_service.h"
rsleevi24f64dc22015-08-07 21:39:2137#include "components/url_formatter/url_formatter.h"
asvitkine9a279832015-12-18 02:35:5038#include "components/variations/net/variations_http_headers.h"
[email protected]53f0cab2014-08-18 09:52:2739#include "grit/components_strings.h"
initial.commit09911bf2008-07-26 23:55:2940#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3441#include "net/base/load_flags.h"
[email protected]bd3b4712012-12-18 17:01:3042#include "net/http/http_request_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5343#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2144#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1745#include "ui/base/l10n/l10n_util.h"
[email protected]cca6f392014-05-28 21:32:2646#include "url/url_constants.h"
[email protected]761fa4702013-07-02 15:25:1547#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2948
[email protected]bc8bb0cd2013-06-24 21:50:2349// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3350
[email protected]51124552011-07-16 01:37:1051namespace {
52
[email protected]7706a522012-08-16 17:42:2553// We keep track in a histogram how many suggest requests we send, how
54// many suggest requests we invalidate (e.g., due to a user typing
55// another character), and how many replies we receive.
56// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
57// (excluding the end-of-list enum value)
58// We do not want values of existing enums to change or else it screws
59// up the statistics.
60enum SuggestRequestsHistogramValue {
61 REQUEST_SENT = 1,
62 REQUEST_INVALIDATED,
63 REPLY_RECEIVED,
64 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
65};
66
[email protected]90fe2bb2013-01-15 03:42:1367// The verbatim score for an input which is not an URL.
68const int kNonURLVerbatimRelevance = 1300;
69
[email protected]7706a522012-08-16 17:42:2570// Increments the appropriate value in the histogram by one.
71void LogOmniboxSuggestRequest(
72 SuggestRequestsHistogramValue request_value) {
73 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
74 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
75}
76
[email protected]0085863a2013-12-06 21:19:0377bool HasMultipleWords(const base::string16& text) {
[email protected]51124552011-07-16 01:37:1078 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
79 bool found_word = false;
80 if (i.Init()) {
81 while (i.Advance()) {
82 if (i.IsWord()) {
83 if (found_word)
84 return true;
85 found_word = true;
86 }
87 }
88 }
89 return false;
90}
91
[email protected]d1f0a7f2012-06-05 10:26:4292} // namespace
[email protected]51124552011-07-16 01:37:1093
[email protected]3954c3a2012-04-10 20:17:5594// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:5895
[email protected]85b8d6f2012-05-08 20:53:4796SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
[email protected]02346202014-02-05 05:18:3097 : template_url_service_(template_url_service) {}
[email protected]85b8d6f2012-05-08 20:53:4798
99const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
100 return default_provider_.empty() ? NULL :
101 template_url_service_->GetTemplateURLForKeyword(default_provider_);
102}
103
104const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
105 return keyword_provider_.empty() ? NULL :
106 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24107}
108
[email protected]3954c3a2012-04-10 20:17:55109
[email protected]bc8bb0cd2013-06-24 21:50:23110// SearchProvider::CompareScoredResults ---------------------------------------
111
112class SearchProvider::CompareScoredResults {
113 public:
[email protected]0b9575f2014-07-30 11:58:37114 bool operator()(const SearchSuggestionParser::Result& a,
115 const SearchSuggestionParser::Result& b) {
[email protected]bc8bb0cd2013-06-24 21:50:23116 // Sort in descending relevance order.
117 return a.relevance() > b.relevance();
118 }
119};
120
121
[email protected]3954c3a2012-04-10 20:17:55122// SearchProvider -------------------------------------------------------------
123
blundell55e35e82015-06-16 08:46:18124SearchProvider::SearchProvider(AutocompleteProviderClient* client,
blundelld130d592015-06-21 19:29:13125 AutocompleteProviderListener* listener)
126 : BaseSearchProvider(AutocompleteProvider::TYPE_SEARCH, client),
[email protected]776ee5902014-08-11 09:15:19127 listener_(listener),
blundelld130d592015-06-21 19:29:13128 providers_(client->GetTemplateURLService()),
groby1dbb8e22014-09-23 21:50:26129 answers_cache_(10) {
blundelld130d592015-06-21 19:29:13130 TemplateURLService* template_url_service = client->GetTemplateURLService();
131
132 // |template_url_service| can be null in tests.
133 if (template_url_service)
134 template_url_service->AddObserver(this);
[email protected]bc8bb0cd2013-06-24 21:50:23135}
136
[email protected]cb86ee6f2013-04-28 16:58:15137// static
[email protected]987fad782013-08-28 06:23:18138std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
139 return match.GetAdditionalInfo(kSuggestMetadataKey);
140}
141
mpearson6456fb62015-11-13 06:44:28142void SearchProvider::RegisterDisplayedAnswers(
143 const AutocompleteResult& result) {
144 if (result.empty())
mpearson84f19a152015-03-12 19:42:21145 return;
146
mpearson6456fb62015-11-13 06:44:28147 // The answer must be in the first or second slot to be considered. It should
148 // only be in the second slot if AutocompleteController ranked a local search
149 // history or a verbatim item higher than the answer.
150 AutocompleteResult::const_iterator match = result.begin();
151 if (match->answer_contents.empty() && result.size() > 1)
152 ++match;
153 if (match->answer_contents.empty() || match->answer_type.empty() ||
154 match->fill_into_edit.empty())
155 return;
mpearson84f19a152015-03-12 19:42:21156
mpearson6456fb62015-11-13 06:44:28157 // Valid answer encountered, cache it for further queries.
158 answers_cache_.UpdateRecentAnswers(match->fill_into_edit, match->answer_type);
159}
160
161// static
162int SearchProvider::CalculateRelevanceForKeywordVerbatim(
163 metrics::OmniboxInputType::Type type,
164 bool allow_exact_keyword_match,
165 bool prefer_keyword) {
166 // This function is responsible for scoring verbatim query matches
167 // for non-extension substituting keywords.
168 // KeywordProvider::CalculateRelevance() scores all other types of
169 // keyword verbatim matches.
170 if (allow_exact_keyword_match && prefer_keyword)
171 return 1500;
172 return (allow_exact_keyword_match &&
173 (type == metrics::OmniboxInputType::QUERY)) ?
174 1450 : 1100;
175}
176
177void SearchProvider::ResetSession() {
mpearson1b55e342016-03-19 04:36:20178 set_field_trial_triggered(false);
mpearson6456fb62015-11-13 06:44:28179 set_field_trial_triggered_in_session(false);
mpearson84f19a152015-03-12 19:42:21180}
181
[email protected]bc8bb0cd2013-06-24 21:50:23182SearchProvider::~SearchProvider() {
blundelld130d592015-06-21 19:29:13183 TemplateURLService* template_url_service = client()->GetTemplateURLService();
184 if (template_url_service)
185 template_url_service->RemoveObserver(this);
[email protected]bc8bb0cd2013-06-24 21:50:23186}
187
[email protected]ee6110b2014-01-09 22:26:31188// static
mpearson6c183672014-09-03 02:09:42189void SearchProvider::UpdateOldResults(
190 bool minimal_changes,
191 SearchSuggestionParser::Results* results) {
192 // When called without |minimal_changes|, it likely means the user has
193 // pressed a key. Revise the cached results appropriately.
194 if (!minimal_changes) {
195 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
196 results->suggest_results.begin();
mpearsonf080b342015-11-11 00:52:44197 sug_it != results->suggest_results.end(); ) {
198 if (sug_it->type() == AutocompleteMatchType::CALCULATOR) {
199 sug_it = results->suggest_results.erase(sug_it);
200 } else {
201 sug_it->set_received_after_last_keystroke(false);
202 ++sug_it;
203 }
mpearson6c183672014-09-03 02:09:42204 }
205 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
206 results->navigation_results.begin();
207 nav_it != results->navigation_results.end(); ++nav_it) {
208 nav_it->set_received_after_last_keystroke(false);
209 }
210 }
211}
212
213// static
214ACMatches::iterator SearchProvider::FindTopMatch(ACMatches* matches) {
215 ACMatches::iterator it = matches->begin();
216 while ((it != matches->end()) && !it->allowed_to_be_default_match)
217 ++it;
218 return it;
219}
220
initial.commit09911bf2008-07-26 23:55:29221void SearchProvider::Start(const AutocompleteInput& input,
jifcf322cd2015-06-17 11:01:18222 bool minimal_changes) {
a-v-ydd768d54b2016-03-25 21:07:46223 TRACE_EVENT0("omnibox", "SearchProvider::Start");
[email protected]04504c242013-01-22 21:08:55224 // Do our best to load the model as early as possible. This will reduce
225 // odds of having the model not ready when really needed (a non-empty input).
blundelld130d592015-06-21 19:29:13226 TemplateURLService* model = client()->GetTemplateURLService();
[email protected]04504c242013-01-22 21:08:55227 DCHECK(model);
228 model->Load();
229
initial.commit09911bf2008-07-26 23:55:29230 matches_.clear();
blundelld130d592015-06-21 19:29:13231 set_field_trial_triggered(false);
initial.commit09911bf2008-07-26 23:55:29232
hashimoto663b9f42014-08-26 04:29:20233 // Can't return search/suggest results for bogus input.
jifcf322cd2015-06-17 11:01:18234 if (input.from_omnibox_focus() ||
mariakhomenko3ef531d72015-01-10 00:03:43235 input.type() == metrics::OmniboxInputType::INVALID) {
mpearson8a37c382015-03-07 05:58:57236 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29237 return;
238 }
239
[email protected]14710852013-02-05 23:45:41240 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24241 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41242 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
243 &keyword_input_);
244 if (keyword_provider == NULL)
245 keyword_input_.Clear();
246 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24247 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24248
[email protected]85b8d6f2012-05-08 20:53:47249 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]ce7ee5f2014-06-16 23:41:19250 if (default_provider &&
251 !default_provider->SupportsReplacement(model->search_terms_data()))
[email protected]257ab712009-04-14 17:16:24252 default_provider = NULL;
253
254 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18255 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24256
257 if (!default_provider && !keyword_provider) {
258 // No valid providers.
mpearson8a37c382015-03-07 05:58:57259 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29260 return;
261 }
262
263 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24264 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03265 base::string16 default_provider_keyword(default_provider ?
266 default_provider->keyword() : base::string16());
267 base::string16 keyword_provider_keyword(keyword_provider ?
268 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32269 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47270 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29271 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15272 if (!done_)
mpearson8a37c382015-03-07 05:58:57273 Stop(false, false);
[email protected]257ab712009-04-14 17:16:24274 }
initial.commit09911bf2008-07-26 23:55:29275
[email protected]85b8d6f2012-05-08 20:53:47276 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29277
278 if (input.text().empty()) {
279 // User typed "?" alone. Give them a placeholder result indicating what
280 // this syntax does.
[email protected]257ab712009-04-14 17:16:24281 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00282 AutocompleteMatch match;
283 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36284 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24285 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35286 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47287 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36288 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24289 matches_.push_back(match);
290 }
mpearson8a37c382015-03-07 05:58:57291 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29292 return;
293 }
294
295 input_ = input;
296
[email protected]e1290ee62013-06-26 18:31:15297 DoHistoryQuery(minimal_changes);
grobye5fcee42014-09-26 03:36:46298 // Answers needs scored history results before any suggest query has been
299 // started, since the query for answer-bearing results needs additional
300 // prefetch information based on the highest-scored local history result.
jdonnelly41c5b46a2015-07-10 21:24:38301 ScoreHistoryResults(raw_default_history_results_,
302 false,
303 &transformed_default_history_results_);
304 ScoreHistoryResults(raw_keyword_history_results_,
305 true,
306 &transformed_keyword_history_results_);
307 prefetch_data_ = FindAnswersPrefetchData();
grobye5fcee42014-09-26 03:36:46308
jdonnelly41c5b46a2015-07-10 21:24:38309 // Raw results are not needed any more.
310 raw_default_history_results_.clear();
311 raw_keyword_history_results_.clear();
grobye5fcee42014-09-26 03:36:46312
[email protected]e1290ee62013-06-26 18:31:15313 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42314 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29315}
316
mpearson8a37c382015-03-07 05:58:57317void SearchProvider::Stop(bool clear_cached_results,
318 bool due_to_user_inactivity) {
[email protected]ec3f679b2014-08-18 07:45:13319 StopSuggest();
320 done_ = true;
321
322 if (clear_cached_results)
323 ClearAllResults();
324}
325
[email protected]776ee5902014-08-11 09:15:19326const TemplateURL* SearchProvider::GetTemplateURL(bool is_keyword) const {
327 return is_keyword ? providers_.GetKeywordProviderURL()
328 : providers_.GetDefaultProviderURL();
329}
330
331const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
332 return is_keyword ? keyword_input_ : input_;
333}
334
335bool SearchProvider::ShouldAppendExtraParams(
336 const SearchSuggestionParser::SuggestResult& result) const {
337 return !result.from_keyword_provider() ||
338 providers_.default_provider().empty();
339}
340
[email protected]776ee5902014-08-11 09:15:19341void SearchProvider::RecordDeletionResult(bool success) {
342 if (success) {
343 base::RecordAction(
344 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
345 } else {
346 base::RecordAction(
347 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
348 }
349}
350
mpearson6456fb62015-11-13 06:44:28351void SearchProvider::OnTemplateURLServiceChanged() {
352 // Only update matches at this time if we haven't already claimed we're done
353 // processing the query.
354 if (done_)
355 return;
356
357 // Check that the engines we're using weren't renamed or deleted. (In short,
358 // require that an engine still exists with the keywords in use.) For each
359 // deleted engine, cancel the in-flight request if any, drop its suggestions,
360 // and, in the case when the default provider was affected, point the cached
361 // default provider keyword name at the new name for the default provider.
362
363 // Get...ProviderURL() looks up the provider using the cached keyword name
364 // stored in |providers_|.
365 const TemplateURL* template_url = providers_.GetDefaultProviderURL();
366 if (!template_url) {
367 CancelFetcher(&default_fetcher_);
368 default_results_.Clear();
369 providers_.set(client()
370 ->GetTemplateURLService()
371 ->GetDefaultSearchProvider()
372 ->keyword(),
373 providers_.keyword_provider());
374 }
375 template_url = providers_.GetKeywordProviderURL();
376 if (!providers_.keyword_provider().empty() && !template_url) {
377 CancelFetcher(&keyword_fetcher_);
378 keyword_results_.Clear();
379 providers_.set(providers_.default_provider(), base::string16());
380 }
381 // It's possible the template URL changed without changing associated keyword.
382 // Hence, it's always necessary to update matches to use the new template
383 // URL. (One could cache the template URL and only call UpdateMatches() and
384 // OnProviderUpdate() if a keyword was deleted/renamed or the template URL
385 // was changed. That would save extra calls to these functions. However,
386 // this is uncommon and not likely to be worth the extra work.)
387 UpdateMatches();
388 listener_->OnProviderUpdate(true); // always pretend something changed
389}
390
[email protected]776ee5902014-08-11 09:15:19391void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
a-v-ydd768d54b2016-03-25 21:07:46392 TRACE_EVENT0("omnibox", "SearchProvider::OnURLFetchComplete");
[email protected]776ee5902014-08-11 09:15:19393 DCHECK(!done_);
[email protected]776ee5902014-08-11 09:15:19394 const bool is_keyword = source == keyword_fetcher_.get();
395
396 // Ensure the request succeeded and that the provider used is still available.
397 // A verbatim match cannot be generated without this provider, causing errors.
398 const bool request_succeeded =
399 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
400 GetTemplateURL(is_keyword);
401
402 LogFetchComplete(request_succeeded, is_keyword);
403
404 bool results_updated = false;
405 if (request_succeeded) {
dcheng259570c2016-04-22 00:45:57406 std::unique_ptr<base::Value> data(
407 SearchSuggestionParser::DeserializeJsonData(
408 SearchSuggestionParser::ExtractJsonData(source)));
[email protected]776ee5902014-08-11 09:15:19409 if (data) {
410 SearchSuggestionParser::Results* results =
411 is_keyword ? &keyword_results_ : &default_results_;
412 results_updated = ParseSuggestResults(*data, -1, is_keyword, results);
413 if (results_updated)
414 SortResults(is_keyword, results);
415 }
416 }
mpearson84f19a152015-03-12 19:42:21417
418 // Delete the fetcher now that we're done with it.
419 if (is_keyword)
420 keyword_fetcher_.reset();
421 else
422 default_fetcher_.reset();
423
424 // Update matches, done status, etc., and send alerts if necessary.
[email protected]776ee5902014-08-11 09:15:19425 UpdateMatches();
426 if (done_ || results_updated)
427 listener_->OnProviderUpdate(results_updated);
428}
429
[email protected]ec3f679b2014-08-18 07:45:13430void SearchProvider::StopSuggest() {
mpearson84f19a152015-03-12 19:42:21431 CancelFetcher(&default_fetcher_);
432 CancelFetcher(&keyword_fetcher_);
[email protected]ec3f679b2014-08-18 07:45:13433 timer_.Stop();
[email protected]ec3f679b2014-08-18 07:45:13434}
435
436void SearchProvider::ClearAllResults() {
437 keyword_results_.Clear();
438 default_results_.Clear();
439}
440
[email protected]776ee5902014-08-11 09:15:19441void SearchProvider::UpdateMatchContentsClass(
442 const base::string16& input_text,
443 SearchSuggestionParser::Results* results) {
444 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
445 results->suggest_results.begin();
446 sug_it != results->suggest_results.end(); ++sug_it) {
447 sug_it->ClassifyMatchContents(false, input_text);
448 }
[email protected]776ee5902014-08-11 09:15:19449 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
450 results->navigation_results.begin();
451 nav_it != results->navigation_results.end(); ++nav_it) {
jshin1fb76462016-04-05 22:13:03452 nav_it->CalculateAndClassifyMatchContents(false, input_text);
[email protected]776ee5902014-08-11 09:15:19453 }
454}
455
[email protected]d4a94b92014-03-04 01:35:22456void SearchProvider::SortResults(bool is_keyword,
[email protected]0b9575f2014-07-30 11:58:37457 SearchSuggestionParser::Results* results) {
[email protected]d4a94b92014-03-04 01:35:22458 // Ignore suggested scores for non-keyword matches in keyword mode; if the
459 // server is allowed to score these, it could interfere with the user's
460 // ability to get good keyword results.
461 const bool abandon_suggested_scores =
462 !is_keyword && !providers_.keyword_provider().empty();
[email protected]0b9575f2014-07-30 11:58:37463 // Apply calculated relevance scores to suggestions if valid relevances were
[email protected]d4a94b92014-03-04 01:35:22464 // not provided or we're abandoning suggested scores entirely.
[email protected]2c802d12014-07-31 12:57:14465 if (!results->relevances_from_server || abandon_suggested_scores) {
[email protected]d4a94b92014-03-04 01:35:22466 ApplyCalculatedSuggestRelevance(&results->suggest_results);
467 ApplyCalculatedNavigationRelevance(&results->navigation_results);
468 // If abandoning scores entirely, also abandon the verbatim score.
469 if (abandon_suggested_scores)
470 results->verbatim_relevance = -1;
471 }
472
473 // Keep the result lists sorted.
474 const CompareScoredResults comparator = CompareScoredResults();
475 std::stable_sort(results->suggest_results.begin(),
476 results->suggest_results.end(),
477 comparator);
478 std::stable_sort(results->navigation_results.begin(),
479 results->navigation_results.end(),
480 comparator);
481}
482
[email protected]cfa164bf2014-03-19 11:51:15483void SearchProvider::LogFetchComplete(bool success, bool is_keyword) {
484 LogOmniboxSuggestRequest(REPLY_RECEIVED);
485 // Record response time for suggest requests sent to Google. We care
486 // only about the common case: the Google default provider used in
487 // non-keyword mode.
488 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
489 if (!is_keyword && default_url &&
vitbarda6a5012016-06-14 18:20:32490 (default_url->GetEngineType(
491 client()->GetTemplateURLService()->search_terms_data()) ==
[email protected]cfa164bf2014-03-19 11:51:15492 SEARCH_ENGINE_GOOGLE)) {
493 const base::TimeDelta elapsed_time =
494 base::TimeTicks::Now() - time_suggest_request_sent_;
495 if (success) {
496 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
497 elapsed_time);
498 } else {
499 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
500 elapsed_time);
501 }
502 }
503}
504
[email protected]cfa164bf2014-03-19 11:51:15505void SearchProvider::UpdateMatches() {
mpearson6c183672014-09-03 02:09:42506 PersistTopSuggestions(&default_results_);
507 PersistTopSuggestions(&keyword_results_);
[email protected]cfa164bf2014-03-19 11:51:15508 ConvertResultsToAutocompleteMatches();
509
510 // Check constraints that may be violated by suggested relevances.
511 if (!matches_.empty() &&
512 (default_results_.HasServerProvidedScores() ||
513 keyword_results_.HasServerProvidedScores())) {
514 // These blocks attempt to repair undesirable behavior by suggested
515 // relevances with minimal impact, preserving other suggested relevances.
[email protected]d0e4ad02014-08-22 18:58:33516 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
517 const bool is_extension_keyword = (keyword_url != NULL) &&
ianwena27b1df2016-09-23 23:08:23518 (keyword_url->type() == TemplateURL::OMNIBOX_API_EXTENSION);
[email protected]d0e4ad02014-08-22 18:58:33519 if ((keyword_url != NULL) && !is_extension_keyword &&
[email protected]7bc5e162014-08-15 19:41:11520 (FindTopMatch() == matches_.end())) {
[email protected]d0e4ad02014-08-22 18:58:33521 // In non-extension keyword mode, disregard the keyword verbatim suggested
522 // relevance if necessary, so at least one match is allowed to be default.
523 // (In extension keyword mode this is not necessary because the extension
mpearson6c183672014-09-03 02:09:42524 // will return a default match.) Give keyword verbatim the lowest
525 // non-zero score to best reflect what the server desired.
526 DCHECK_EQ(0, keyword_results_.verbatim_relevance);
527 keyword_results_.verbatim_relevance = 1;
[email protected]cfa164bf2014-03-19 11:51:15528 ConvertResultsToAutocompleteMatches();
529 }
[email protected]89bd27d12014-04-12 17:36:23530 if (IsTopMatchSearchWithURLInput()) {
[email protected]cfa164bf2014-03-19 11:51:15531 // Disregard the suggested search and verbatim relevances if the input
532 // type is URL and the top match is a highly-ranked search suggestion.
533 // For example, prevent a search for "foo.com" from outranking another
534 // provider's navigation for "foo.com" or "foo.com/url_from_history".
535 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
536 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
537 default_results_.verbatim_relevance = -1;
538 keyword_results_.verbatim_relevance = -1;
539 ConvertResultsToAutocompleteMatches();
540 }
[email protected]d0e4ad02014-08-22 18:58:33541 if (!is_extension_keyword && (FindTopMatch() == matches_.end())) {
542 // Guarantee that SearchProvider returns a legal default match (except
543 // when in extension-based keyword mode). The omnibox always needs at
544 // least one legal default match, and it relies on SearchProvider in
545 // combination with KeywordProvider (for extension-based keywords) to
mpearson6c183672014-09-03 02:09:42546 // always return one. Give the verbatim suggestion the lowest non-zero
547 // scores to best reflect what the server desired.
548 DCHECK_EQ(0, default_results_.verbatim_relevance);
549 default_results_.verbatim_relevance = 1;
550 // We do not have to alter keyword_results_.verbatim_relevance here.
551 // If the user is in keyword mode, we already reverted (earlier in this
552 // function) the instructions to suppress keyword verbatim.
[email protected]cfa164bf2014-03-19 11:51:15553 ConvertResultsToAutocompleteMatches();
554 }
[email protected]89bd27d12014-04-12 17:36:23555 DCHECK(!IsTopMatchSearchWithURLInput());
[email protected]d0e4ad02014-08-22 18:58:33556 DCHECK(is_extension_keyword || (FindTopMatch() != matches_.end()));
[email protected]cfa164bf2014-03-19 11:51:15557 }
558 UMA_HISTOGRAM_CUSTOM_COUNTS(
559 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
mpearson6c183672014-09-03 02:09:42560
561 // Record the top suggestion (if any) for future use.
562 top_query_suggestion_match_contents_ = base::string16();
563 top_navigation_suggestion_ = GURL();
564 ACMatches::const_iterator first_match = FindTopMatch();
565 if ((first_match != matches_.end()) &&
566 !first_match->inline_autocompletion.empty()) {
567 // Identify if this match came from a query suggestion or a navsuggestion.
568 // In either case, extracts the identifying feature of the suggestion
569 // (query string or navigation url).
570 if (AutocompleteMatch::IsSearchType(first_match->type))
571 top_query_suggestion_match_contents_ = first_match->contents;
572 else
573 top_navigation_suggestion_ = first_match->destination_url;
574 }
575
[email protected]cfa164bf2014-03-19 11:51:15576 UpdateDone();
[email protected]cfa164bf2014-03-19 11:51:15577}
578
mpearsond37de7c2015-03-11 01:56:26579void SearchProvider::Run(bool query_is_private) {
[email protected]bc8bb0cd2013-06-24 21:50:23580 // Start a new request with the current input.
mpearson84f19a152015-03-12 19:42:21581 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05582
mpearsond37de7c2015-03-11 01:56:26583 if (!query_is_private) {
dtapuskadafcf892015-05-01 13:58:25584 default_fetcher_ =
585 CreateSuggestFetcher(kDefaultProviderURLFetcherID,
586 providers_.GetDefaultProviderURL(), input_);
mpearsond37de7c2015-03-11 01:56:26587 }
dtapuskadafcf892015-05-01 13:58:25588 keyword_fetcher_ =
589 CreateSuggestFetcher(kKeywordProviderURLFetcherID,
590 providers_.GetKeywordProviderURL(), keyword_input_);
[email protected]bc8bb0cd2013-06-24 21:50:23591
592 // Both the above can fail if the providers have been modified or deleted
593 // since the query began.
mpearson84f19a152015-03-12 19:42:21594 if (!default_fetcher_ && !keyword_fetcher_) {
[email protected]bc8bb0cd2013-06-24 21:50:23595 UpdateDone();
596 // We only need to update the listener if we're actually done.
597 if (done_)
598 listener_->OnProviderUpdate(false);
mpearsond37de7c2015-03-11 01:56:26599 } else {
600 // Sent at least one request.
601 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]bc8bb0cd2013-06-24 21:50:23602 }
[email protected]601858c02010-09-01 17:08:20603}
604
[email protected]8d457132010-11-04 18:13:40605void SearchProvider::DoHistoryQuery(bool minimal_changes) {
606 // The history query results are synchronous, so if minimal_changes is true,
607 // we still have the last results and don't need to do anything.
608 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29609 return;
610
grobye5fcee42014-09-26 03:36:46611 raw_keyword_history_results_.clear();
612 raw_default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29613
[email protected]78e5e432013-08-03 02:10:10614 if (OmniboxFieldTrial::SearchHistoryDisable(
615 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16616 return;
617
blundelld130d592015-06-21 19:29:13618 history::URLDatabase* url_db = client()->GetInMemoryDatabase();
[email protected]8d457132010-11-04 18:13:40619 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29620 return;
621
[email protected]51124552011-07-16 01:37:10622 // Request history for both the keyword and default provider. We grab many
623 // more matches than we'll ultimately clamp to so that if there are several
624 // recent multi-word matches who scores are lowered (see
grobye5fcee42014-09-26 03:36:46625 // ScoreHistoryResults()), they won't crowd out older, higher-scoring
[email protected]51124552011-07-16 01:37:10626 // matches. Note that this doesn't fix the problem entirely, but merely
627 // limits it to cases with a very large number of such multi-word matches; for
628 // now, this seems OK compared with the complexity of a real fix, which would
629 // require multiple searches and tracking of "single- vs. multi-word" in the
630 // database.
631 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47632 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
633 if (default_url) {
[email protected]b4bec972014-04-05 18:07:15634 const base::TimeTicks start_time = base::TimeTicks::Now();
grobye5fcee42014-09-26 03:36:46635 url_db->GetMostRecentKeywordSearchTerms(default_url->id(),
636 input_.text(),
637 num_matches,
638 &raw_default_history_results_);
[email protected]31afdf72013-09-26 04:29:36639 UMA_HISTOGRAM_TIMES(
640 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
641 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24642 }
[email protected]85b8d6f2012-05-08 20:53:47643 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
644 if (keyword_url) {
645 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
grobye5fcee42014-09-26 03:36:46646 keyword_input_.text(),
647 num_matches,
648 &raw_keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55649 }
initial.commit09911bf2008-07-26 23:55:29650}
651
bartn1c07e722014-10-27 19:34:24652base::TimeDelta SearchProvider::GetSuggestQueryDelay() const {
653 bool from_last_keystroke;
654 int polling_delay_ms;
655 OmniboxFieldTrial::GetSuggestPollingStrategy(&from_last_keystroke,
656 &polling_delay_ms);
657
658 base::TimeDelta delay(base::TimeDelta::FromMilliseconds(polling_delay_ms));
659 if (from_last_keystroke)
660 return delay;
661
662 base::TimeDelta time_since_last_suggest_request =
663 base::TimeTicks::Now() - time_suggest_request_sent_;
664 return std::max(base::TimeDelta(), delay - time_since_last_suggest_request);
665}
666
[email protected]6dc950f2012-07-16 19:49:08667void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
mpearsond37de7c2015-03-11 01:56:26668 bool query_is_private;
669 if (!IsQuerySuitableForSuggest(&query_is_private)) {
initial.commit09911bf2008-07-26 23:55:29670 StopSuggest();
[email protected]71b46152013-05-03 16:39:20671 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29672 return;
673 }
674
bartn1c07e722014-10-27 19:34:24675 if (OmniboxFieldTrial::DisableResultsCaching())
676 ClearAllResults();
677
initial.commit09911bf2008-07-26 23:55:29678 // For the minimal_changes case, if we finished the previous query and still
679 // have its results, or are allowed to keep running it, just do that, rather
680 // than starting a new query.
681 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24682 (!default_results_.suggest_results.empty() ||
683 !default_results_.navigation_results.empty() ||
684 !keyword_results_.suggest_results.empty() ||
685 !keyword_results_.navigation_results.empty() ||
[email protected]a2770a7d2014-04-22 19:33:35686 (!done_ && input_.want_asynchronous_matches())))
initial.commit09911bf2008-07-26 23:55:29687 return;
688
689 // We can't keep running any previous query, so halt it.
690 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42691
mpearson6c183672014-09-03 02:09:42692 UpdateAllOldResults(minimal_changes);
initial.commit09911bf2008-07-26 23:55:29693
[email protected]ee6110b2014-01-09 22:26:31694 // Update the content classifications of remaining results so they look good
695 // against the current input.
[email protected]23db6492014-01-16 02:35:30696 UpdateMatchContentsClass(input_.text(), &default_results_);
697 if (!keyword_input_.text().empty())
698 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31699
initial.commit09911bf2008-07-26 23:55:29700 // We can't start a new query if we're only allowed synchronous results.
[email protected]a2770a7d2014-04-22 19:33:35701 if (!input_.want_asynchronous_matches())
initial.commit09911bf2008-07-26 23:55:29702 return;
703
bartn1c07e722014-10-27 19:34:24704 // Kick off a timer that will start the URL fetch if it completes before
705 // the user types another character. Requests may be delayed to avoid
706 // flooding the server with requests that are likely to be thrown away later
707 // anyway.
708 const base::TimeDelta delay = GetSuggestQueryDelay();
709 if (delay <= base::TimeDelta()) {
mpearsond37de7c2015-03-11 01:56:26710 Run(query_is_private);
[email protected]515ffa942012-11-27 20:18:24711 return;
712 }
mpearsond37de7c2015-03-11 01:56:26713 timer_.Start(FROM_HERE,
714 delay,
715 base::Bind(&SearchProvider::Run,
716 base::Unretained(this),
717 query_is_private));
initial.commit09911bf2008-07-26 23:55:29718}
719
dcheng259570c2016-04-22 00:45:57720void SearchProvider::CancelFetcher(std::unique_ptr<net::URLFetcher>* fetcher) {
mpearson84f19a152015-03-12 19:42:21721 if (*fetcher) {
722 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
723 fetcher->reset();
724 }
725}
726
mpearsond37de7c2015-03-11 01:56:26727bool SearchProvider::IsQuerySuitableForSuggest(bool* query_is_private) const {
728 *query_is_private = IsQueryPotentionallyPrivate();
729
[email protected]3954c3a2012-04-10 20:17:55730 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
mpearsond37de7c2015-03-11 01:56:26731 // if the user has disabled it. Also don't send potentionally private data
732 // to the default search provider. (It's always okay to send explicit
733 // keyword input to a keyword suggest server, if any.)
[email protected]85b8d6f2012-05-08 20:53:47734 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
735 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
blundelld130d592015-06-21 19:29:13736 return !client()->IsOffTheRecord() && client()->SearchSuggestEnabled() &&
737 ((default_url && !default_url->suggestions_url().empty() &&
738 !*query_is_private) ||
739 (keyword_url && !keyword_url->suggestions_url().empty()));
mpearsond37de7c2015-03-11 01:56:26740}
[email protected]83c726482008-09-10 06:36:34741
mpearsond37de7c2015-03-11 01:56:26742bool SearchProvider::IsQueryPotentionallyPrivate() const {
[email protected]cac59d32010-08-09 23:23:14743 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34744 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34745
[email protected]f608ea102013-03-18 15:08:09746 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
747 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
748 // is both a waste of time and a disclosure of potentially private, local
749 // data. Other "schemes" may actually be usernames, and we don't want to send
750 // passwords. If the scheme is OK, we still need to check other cases below.
751 // If this is QUERY, then the presence of these schemes means the user
752 // explicitly typed one, and thus this is probably a URL that's being entered
753 // and happens to currently be invalid -- in which case we again want to run
754 // our checks below. Other QUERY cases are less likely to be URLs and thus we
755 // assume we're OK.
brettwbc17d2c82015-06-09 22:39:08756 if (!base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpScheme) &&
757 !base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
758 !base::LowerCaseEqualsASCII(input_.scheme(), url::kFtpScheme))
mpearsond37de7c2015-03-11 01:56:26759 return (input_.type() != metrics::OmniboxInputType::QUERY);
[email protected]cac59d32010-08-09 23:23:14760
761 // Don't send URLs with usernames, queries or refs. Some of these are
762 // private, and the Suggest server is unlikely to have any useful results
763 // for any of them. Also don't send URLs with ports, as we may initially
764 // think that a username + password is a host + port (and we don't want to
765 // send usernames/passwords), and even if the port really is a port, the
766 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58767 // Note that we only block based on refs if the input is URL-typed, as search
768 // queries can legitimately have #s in them which the URL parser
769 // overaggressively categorizes as a url with a ref.
[email protected]b45334502014-04-30 19:44:05770 const url::Parsed& parts = input_.parts();
[email protected]cac59d32010-08-09 23:23:14771 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58772 parts.query.is_nonempty() ||
[email protected]3dc75b12014-06-08 00:02:22773 (parts.ref.is_nonempty() &&
774 (input_.type() == metrics::OmniboxInputType::URL)))
mpearsond37de7c2015-03-11 01:56:26775 return true;
[email protected]cac59d32010-08-09 23:23:14776
777 // Don't send anything for https except the hostname. Hostnames are OK
778 // because they are visible when the TCP connection is established, but the
779 // specific path may reveal private information.
brettwbc17d2c82015-06-09 22:39:08780 if (base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36781 parts.path.is_nonempty())
mpearsond37de7c2015-03-11 01:56:26782 return true;
[email protected]83c726482008-09-10 06:36:34783
mpearsond37de7c2015-03-11 01:56:26784 return false;
[email protected]83c726482008-09-10 06:36:34785}
786
mpearson6c183672014-09-03 02:09:42787void SearchProvider::UpdateAllOldResults(bool minimal_changes) {
[email protected]dc735c02013-11-12 23:23:41788 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51789 // User is either in keyword mode with a blank input or out of
790 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24791 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51792 }
mpearson6c183672014-09-03 02:09:42793 UpdateOldResults(minimal_changes, &default_results_);
794 UpdateOldResults(minimal_changes, &keyword_results_);
[email protected]d1f0a7f2012-06-05 10:26:42795}
796
mpearson6c183672014-09-03 02:09:42797void SearchProvider::PersistTopSuggestions(
798 SearchSuggestionParser::Results* results) {
799 // Mark any results matching the current top results as having been received
800 // prior to the last keystroke. That prevents asynchronous updates from
801 // clobbering top results, which may be used for inline autocompletion.
802 // Other results don't need similar changes, because they shouldn't be
803 // displayed asynchronously anyway.
804 if (!top_query_suggestion_match_contents_.empty()) {
805 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
806 results->suggest_results.begin();
807 sug_it != results->suggest_results.end(); ++sug_it) {
808 if (sug_it->match_contents() == top_query_suggestion_match_contents_)
809 sug_it->set_received_after_last_keystroke(false);
810 }
811 }
812 if (top_navigation_suggestion_.is_valid()) {
813 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
814 results->navigation_results.begin();
815 nav_it != results->navigation_results.end(); ++nav_it) {
816 if (nav_it->url() == top_navigation_suggestion_)
817 nav_it->set_received_after_last_keystroke(false);
818 }
819 }
[email protected]d1f0a7f2012-06-05 10:26:42820}
821
[email protected]0b9575f2014-07-30 11:58:37822void SearchProvider::ApplyCalculatedSuggestRelevance(
823 SearchSuggestionParser::SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42824 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37825 SearchSuggestionParser::SuggestResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42826 result.set_relevance(
827 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
828 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07829 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42830 }
831}
832
[email protected]188b50c2013-03-28 07:19:42833void SearchProvider::ApplyCalculatedNavigationRelevance(
[email protected]0b9575f2014-07-30 11:58:37834 SearchSuggestionParser::NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42835 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37836 SearchSuggestionParser::NavigationResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42837 result.set_relevance(
838 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
839 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07840 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42841 }
842}
843
dcheng259570c2016-04-22 00:45:57844std::unique_ptr<net::URLFetcher> SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12845 int id,
[email protected]9ff91722012-09-07 05:29:12846 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41847 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12848 if (!template_url || template_url->suggestions_url().empty())
849 return NULL;
850
851 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41852 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
[email protected]420472b22014-06-10 13:34:43853 search_term_args.input_type = input.type();
[email protected]14710852013-02-05 23:45:41854 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18855 search_term_args.page_classification = input.current_page_classification();
jdonnelly41c5b46a2015-07-10 21:24:38856 // Session token and prefetch data required for answers.
857 search_term_args.session_token = GetSessionToken();
858 if (!prefetch_data_.full_query_text.empty()) {
859 search_term_args.prefetch_query =
860 base::UTF16ToUTF8(prefetch_data_.full_query_text);
861 search_term_args.prefetch_query_type =
862 base::UTF16ToUTF8(prefetch_data_.query_type);
[email protected]2ef2a6642014-07-30 05:50:29863 }
[email protected]9ff91722012-09-07 05:29:12864 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19865 search_term_args,
blundelld130d592015-06-21 19:29:13866 client()->GetTemplateURLService()->search_terms_data()));
[email protected]9ff91722012-09-07 05:29:12867 if (!suggest_url.is_valid())
868 return NULL;
jdonnelly41c5b46a2015-07-10 21:24:38869
[email protected]9b9fa672013-11-07 06:04:52870 // Send the current page URL if user setting and URL requirements are met and
871 // the user is in the field trial.
blundelld130d592015-06-21 19:29:13872 TemplateURLService* template_url_service = client()->GetTemplateURLService();
mariakhomenko3ac684352015-06-18 20:01:17873 if (CanSendURL(input.current_url(), suggest_url, template_url,
[email protected]e6477f12014-08-05 07:59:54874 input.current_page_classification(),
blundelld130d592015-06-21 19:29:13875 template_url_service->search_terms_data(), client()) &&
[email protected]9b9fa672013-11-07 06:04:52876 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
mariakhomenko3ac684352015-06-18 20:01:17877 search_term_args.current_page_url = input.current_url().spec();
[email protected]9b9fa672013-11-07 06:04:52878 // Create the suggest URL again with the current page URL.
879 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
blundelld130d592015-06-21 19:29:13880 search_term_args, template_url_service->search_terms_data()));
[email protected]9b9fa672013-11-07 06:04:52881 }
[email protected]9ff91722012-09-07 05:29:12882
[email protected]9ff91722012-09-07 05:29:12883 LogOmniboxSuggestRequest(REQUEST_SENT);
884
dcheng259570c2016-04-22 00:45:57885 std::unique_ptr<net::URLFetcher> fetcher =
[email protected]9ff91722012-09-07 05:29:12886 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
amohammadkhanf76ae112015-09-14 17:34:43887 data_use_measurement::DataUseUserData::AttachToFetcher(
888 fetcher.get(), data_use_measurement::DataUseUserData::OMNIBOX);
blundelld130d592015-06-21 19:29:13889 fetcher->SetRequestContext(client()->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34890 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30891 // Add Chrome experiment state to the request headers.
892 net::HttpRequestHeaders headers;
asvitkine9a279832015-12-18 02:35:50893 variations::AppendVariationHeaders(
blundelld130d592015-06-21 19:29:13894 fetcher->GetOriginalURL(), client()->IsOffTheRecord(), false, &headers);
[email protected]bd3b4712012-12-18 17:01:30895 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24896 fetcher->Start();
897 return fetcher;
898}
899
[email protected]344946a12012-12-20 12:03:42900void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29901 // Convert all the results to matches and add them to a map, so we can keep
902 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36903 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29904 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23905 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24906 int did_not_accept_keyword_suggestion =
907 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29908 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
909 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29910
[email protected]d30268a2013-06-25 22:31:07911 bool relevance_from_server;
912 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24913 int did_not_accept_default_suggestion =
914 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08915 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
916 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]7bc5e162014-08-15 19:41:11917 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]d1f0a7f2012-06-05 10:26:42918 if (verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44919 const base::string16& trimmed_verbatim =
920 base::CollapseWhitespace(input_.text(), false);
[email protected]716cd372014-08-15 18:56:03921
922 // Verbatim results don't get suggestions and hence, answers.
923 // Scan previous matches if the last answer-bearing suggestion matches
924 // verbatim, and if so, copy over answer contents.
925 base::string16 answer_contents;
926 base::string16 answer_type;
dcheng259570c2016-04-22 00:45:57927 std::unique_ptr<SuggestionAnswer> answer;
jdonnelly622e2ed2015-12-29 18:17:31928 base::string16 trimmed_verbatim_lower =
929 base::i18n::ToLower(trimmed_verbatim);
[email protected]716cd372014-08-15 18:56:03930 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
931 ++it) {
jdonnelly622e2ed2015-12-29 18:17:31932 if (it->answer &&
933 base::i18n::ToLower(it->fill_into_edit) == trimmed_verbatim_lower) {
[email protected]716cd372014-08-15 18:56:03934 answer_contents = it->answer_contents;
935 answer_type = it->answer_type;
jdonnelly7393cee2014-10-31 01:52:56936 answer = SuggestionAnswer::copy(it->answer.get());
[email protected]716cd372014-08-15 18:56:03937 break;
938 }
939 }
940
[email protected]0b9575f2014-07-30 11:58:37941 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44942 trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]716cd372014-08-15 18:56:03943 trimmed_verbatim, base::string16(), base::string16(), answer_contents,
dcheng51ace48a2015-12-26 22:45:17944 answer_type, std::move(answer), std::string(), std::string(), false,
jdonnelly7393cee2014-10-31 01:52:56945 verbatim_relevance, relevance_from_server, false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37946 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
[email protected]7bc5e162014-08-15 19:41:11947 false, keyword_url != NULL, &map);
[email protected]d1f0a7f2012-06-05 10:26:42948 }
[email protected]5423e562013-02-07 03:58:45949 if (!keyword_input_.text().empty()) {
[email protected]5423e562013-02-07 03:58:45950 // We only create the verbatim search query match for a keyword
951 // if it's not an extension keyword. Extension keywords are handled
952 // in KeywordProvider::Start(). (Extensions are complicated...)
953 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
954 // to the keyword verbatim search query. Do not create other matches
955 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:25956 if (keyword_url &&
ianwena27b1df2016-09-23 23:08:23957 (keyword_url->type() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:07958 bool keyword_relevance_from_server;
959 const int keyword_verbatim_relevance =
960 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:28961 if (keyword_verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44962 const base::string16& trimmed_verbatim =
963 base::CollapseWhitespace(keyword_input_.text(), false);
[email protected]0b9575f2014-07-30 11:58:37964 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44965 trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
966 trimmed_verbatim, base::string16(), base::string16(),
jdonnelly7393cee2014-10-31 01:52:56967 base::string16(), base::string16(), nullptr, std::string(),
968 std::string(), true, keyword_verbatim_relevance,
969 keyword_relevance_from_server, false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37970 AddMatchToMap(verbatim, std::string(),
[email protected]7bc5e162014-08-15 19:41:11971 did_not_accept_keyword_suggestion, false, true, &map);
[email protected]dab8d52d2013-03-05 07:35:28972 }
[email protected]5423e562013-02-07 03:58:45973 }
974 }
grobye5fcee42014-09-26 03:36:46975 AddRawHistoryResultsToMap(true, did_not_accept_keyword_suggestion, &map);
976 AddRawHistoryResultsToMap(false, did_not_accept_default_suggestion, &map);
[email protected]257ab712009-04-14 17:16:24977
[email protected]d1cb6a822013-09-18 19:43:00978 AddSuggestResultsToMap(keyword_results_.suggest_results,
979 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:18980 AddSuggestResultsToMap(default_results_.suggest_results,
981 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:29982
[email protected]d30268a2013-06-25 22:31:07983 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:29984 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:07985 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:29986
[email protected]d30268a2013-06-25 22:31:07987 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
988 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:29989
[email protected]d30268a2013-06-25 22:31:07990 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
mpearson6c183672014-09-03 02:09:42991 // suggest/navsuggest matches, regardless of origin. We always include in
992 // that set a legal default match if possible. If Instant Extended is enabled
993 // and we have server-provided (and thus hopefully more accurate) scores for
994 // some suggestions, we allow more of those, until we reach
[email protected]d30268a2013-06-25 22:31:07995 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
996 // whole popup).
997 //
998 // We will always return any verbatim matches, no matter how we obtained their
999 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
1000 // higher-scoring matches under the conditions above.
1001 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
jdonnelly55f66142014-09-25 23:08:111002
mpearson6c183672014-09-03 02:09:421003 // Guarantee that if there's a legal default match anywhere in the result
1004 // set that it'll get returned. The rotate() call does this by moving the
1005 // default match to the front of the list.
1006 ACMatches::iterator default_match = FindTopMatch(&matches);
1007 if (default_match != matches.end())
1008 std::rotate(matches.begin(), default_match, default_match + 1);
[email protected]3723e6e2012-06-11 21:06:561009
jdonnelly55f66142014-09-25 23:08:111010 // It's possible to get a copy of an answer from previous matches and get the
1011 // same or a different answer to another server-provided suggestion. In the
1012 // future we may decide that we want to have answers attached to multiple
1013 // suggestions, but the current assumption is that there should only ever be
1014 // one suggestion with an answer. To maintain this assumption, remove any
1015 // answers after the first.
1016 RemoveExtraAnswers(&matches);
1017
1018 matches_.clear();
[email protected]d30268a2013-06-25 22:31:071019 size_t num_suggestions = 0;
1020 for (ACMatches::const_iterator i(matches.begin());
1021 (i != matches.end()) &&
1022 (matches_.size() < AutocompleteResult::kMaxMatches);
1023 ++i) {
1024 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
1025 // verbatim result, so this condition basically means "if this match is a
1026 // suggestion of some sort".
1027 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
1028 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
1029 // If we've already hit the limit on non-server-scored suggestions, and
1030 // this isn't a server-scored suggestion we can add, skip it.
1031 if ((num_suggestions >= kMaxMatches) &&
sdefresne51bbec7b2015-08-03 14:18:131032 (!search::IsInstantExtendedAPIEnabled() ||
[email protected]d30268a2013-06-25 22:31:071033 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
1034 continue;
1035 }
1036
1037 ++num_suggestions;
1038 }
1039
1040 matches_.push_back(*i);
1041 }
[email protected]31afdf72013-09-26 04:29:361042 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
1043 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:421044}
1045
jdonnelly55f66142014-09-25 23:08:111046void SearchProvider::RemoveExtraAnswers(ACMatches* matches) {
1047 bool answer_seen = false;
1048 for (ACMatches::iterator it = matches->begin(); it != matches->end(); ++it) {
jdonnelly7393cee2014-10-31 01:52:561049 if (it->answer) {
jdonnelly55f66142014-09-25 23:08:111050 if (!answer_seen) {
1051 answer_seen = true;
1052 } else {
1053 it->answer_contents.clear();
1054 it->answer_type.clear();
jdonnelly7393cee2014-10-31 01:52:561055 it->answer.reset();
jdonnelly55f66142014-09-25 23:08:111056 }
1057 }
1058 }
1059}
1060
[email protected]89bd27d12014-04-12 17:36:231061ACMatches::const_iterator SearchProvider::FindTopMatch() const {
[email protected]0a8718b12013-11-13 18:41:311062 ACMatches::const_iterator it = matches_.begin();
1063 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
1064 ++it;
1065 return it;
[email protected]9dfb4d362013-04-05 02:15:121066}
1067
[email protected]89bd27d12014-04-12 17:36:231068bool SearchProvider::IsTopMatchSearchWithURLInput() const {
1069 ACMatches::const_iterator first_match = FindTopMatch();
[email protected]3dc75b12014-06-08 00:02:221070 return (input_.type() == metrics::OmniboxInputType::URL) &&
[email protected]0a8718b12013-11-13 18:41:311071 (first_match != matches_.end()) &&
1072 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
[email protected]78981d8c2014-05-09 15:05:471073 (first_match->type != AutocompleteMatchType::NAVSUGGEST) &&
1074 (first_match->type != AutocompleteMatchType::NAVSUGGEST_PERSONALIZED);
[email protected]344946a12012-12-20 12:03:421075}
1076
[email protected]257ab712009-04-14 17:16:241077void SearchProvider::AddNavigationResultsToMatches(
[email protected]0b9575f2014-07-30 11:58:371078 const SearchSuggestionParser::NavigationResults& navigation_results,
[email protected]d30268a2013-06-25 22:31:071079 ACMatches* matches) {
[email protected]0b9575f2014-07-30 11:58:371080 for (SearchSuggestionParser::NavigationResults::const_iterator it =
1081 navigation_results.begin(); it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:071082 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:231083 // In the absence of suggested relevance scores, use only the single
1084 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:071085 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:231086 return;
[email protected]257ab712009-04-14 17:16:241087 }
1088}
1089
grobye5fcee42014-09-26 03:36:461090void SearchProvider::AddRawHistoryResultsToMap(bool is_keyword,
1091 int did_not_accept_suggestion,
1092 MatchMap* map) {
[email protected]31afdf72013-09-26 04:29:361093 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]51124552011-07-16 01:37:101094
jdonnelly41c5b46a2015-07-10 21:24:381095 const SearchSuggestionParser::SuggestResults* transformed_results =
1096 is_keyword ? &transformed_keyword_history_results_
1097 : &transformed_default_history_results_;
grobye5fcee42014-09-26 03:36:461098 DCHECK(transformed_results);
1099 AddTransformedHistoryResultsToMap(
1100 *transformed_results, did_not_accept_suggestion, map);
[email protected]31afdf72013-09-26 04:29:361101 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1102 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:101103}
1104
grobye5fcee42014-09-26 03:36:461105void SearchProvider::AddTransformedHistoryResultsToMap(
1106 const SearchSuggestionParser::SuggestResults& transformed_results,
1107 int did_not_accept_suggestion,
1108 MatchMap* map) {
1109 for (SearchSuggestionParser::SuggestResults::const_iterator i(
1110 transformed_results.begin());
1111 i != transformed_results.end();
1112 ++i) {
1113 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true,
1114 providers_.GetKeywordProviderURL() != NULL, map);
1115 }
1116}
1117
1118SearchSuggestionParser::SuggestResults
1119SearchProvider::ScoreHistoryResultsHelper(const HistoryResults& results,
1120 bool base_prevent_inline_autocomplete,
1121 bool input_multiple_words,
1122 const base::string16& input_text,
1123 bool is_keyword) {
[email protected]0b9575f2014-07-30 11:58:371124 SearchSuggestionParser::SuggestResults scored_results;
[email protected]ab5fd2f2014-07-17 19:18:521125 // True if the user has asked this exact query previously.
1126 bool found_what_you_typed_match = false;
[email protected]78e5e432013-08-03 02:10:101127 const bool prevent_search_history_inlining =
1128 OmniboxFieldTrial::SearchHistoryPreventInlining(
1129 input_.current_page_classification());
[email protected]c2ca3fd2014-03-22 03:07:441130 const base::string16& trimmed_input =
1131 base::CollapseWhitespace(input_text, false);
[email protected]257ab712009-04-14 17:16:241132 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1133 ++i) {
[email protected]c2ca3fd2014-03-22 03:07:441134 const base::string16& trimmed_suggestion =
1135 base::CollapseWhitespace(i->term, false);
1136
[email protected]51124552011-07-16 01:37:101137 // Don't autocomplete multi-word queries that have only been seen once
1138 // unless the user has typed more than one word.
1139 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
[email protected]c2ca3fd2014-03-22 03:07:441140 (!input_multiple_words && (i->visits < 2) &&
1141 HasMultipleWords(trimmed_suggestion));
[email protected]51124552011-07-16 01:37:101142
[email protected]78e5e432013-08-03 02:10:101143 int relevance = CalculateRelevanceForHistory(
1144 i->time, is_keyword, !prevent_inline_autocomplete,
1145 prevent_search_history_inlining);
[email protected]ab5fd2f2014-07-17 19:18:521146 // Add the match to |scored_results| by putting the what-you-typed match
1147 // on the front and appending all other matches. We want the what-you-
1148 // typed match to always be first.
[email protected]0b9575f2014-07-30 11:58:371149 SearchSuggestionParser::SuggestResults::iterator insertion_position =
1150 scored_results.end();
[email protected]ab5fd2f2014-07-17 19:18:521151 if (trimmed_suggestion == trimmed_input) {
1152 found_what_you_typed_match = true;
1153 insertion_position = scored_results.begin();
1154 }
mpearson6c183672014-09-03 02:09:421155 SearchSuggestionParser::SuggestResult history_suggestion(
1156 trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
1157 trimmed_suggestion, base::string16(), base::string16(),
jdonnelly7393cee2014-10-31 01:52:561158 base::string16(), base::string16(), nullptr, std::string(),
1159 std::string(), is_keyword, relevance, false, false, trimmed_input);
mpearson6c183672014-09-03 02:09:421160 // History results are synchronous; they are received on the last keystroke.
1161 history_suggestion.set_received_after_last_keystroke(false);
1162 scored_results.insert(insertion_position, history_suggestion);
[email protected]257ab712009-04-14 17:16:241163 }
[email protected]51124552011-07-16 01:37:101164
1165 // History returns results sorted for us. However, we may have docked some
[email protected]ab5fd2f2014-07-17 19:18:521166 // results' scores, so things are no longer in order. While keeping the
1167 // what-you-typed match at the front (if it exists), do a stable sort to get
[email protected]51124552011-07-16 01:37:101168 // things back in order without otherwise disturbing results with equal
1169 // scores, then force the scores to be unique, so that the order in which
1170 // they're shown is deterministic.
[email protected]ab5fd2f2014-07-17 19:18:521171 std::stable_sort(scored_results.begin() +
1172 (found_what_you_typed_match ? 1 : 0),
1173 scored_results.end(),
[email protected]55ce8f12012-05-09 04:44:081174 CompareScoredResults());
[email protected]7e3b77f2014-07-25 02:29:441175
1176 // Don't autocomplete to search terms that would normally be treated as URLs
1177 // when typed. For example, if the user searched for "google.com" and types
1178 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1179 // the input will look like a URL but act like a search, which is confusing.
1180 // The 1200 relevance score threshold in the test below is the lowest
1181 // possible score in CalculateRelevanceForHistory()'s aggressive-scoring
1182 // curve. This is an appropriate threshold to use to decide if we're overly
1183 // aggressively inlining because, if we decide the answer is yes, the
1184 // way we resolve it it to not use the aggressive-scoring curve.
1185 // NOTE: We don't check for autocompleting to URLs in the following cases:
1186 // * When inline autocomplete is disabled, we won't be inline autocompleting
1187 // this term, so we don't need to worry about confusion as much. This
1188 // also prevents calling Classify() again from inside the classifier
1189 // (which will corrupt state and likely crash), since the classifier
1190 // always disables inline autocomplete.
1191 // * When the user has typed the whole string before as a query, then it's
1192 // likely the user has no expectation that term should be interpreted as
1193 // as a URL, so we need not do anything special to preserve user
1194 // expectation.
[email protected]51124552011-07-16 01:37:101195 int last_relevance = 0;
[email protected]7e3b77f2014-07-25 02:29:441196 if (!base_prevent_inline_autocomplete && !found_what_you_typed_match &&
hashimoto663b9f42014-08-26 04:29:201197 scored_results.front().relevance() >= 1200) {
[email protected]7e3b77f2014-07-25 02:29:441198 AutocompleteMatch match;
blundelld130d592015-06-21 19:29:131199 client()->Classify(scored_results.front().suggestion(), false, false,
1200 input_.current_page_classification(), &match, NULL);
[email protected]7e3b77f2014-07-25 02:29:441201 // Demote this match that would normally be interpreted as a URL to have
1202 // the highest score a previously-issued search query could have when
1203 // scoring with the non-aggressive method. A consequence of demoting
1204 // by revising |last_relevance| is that this match and all following
1205 // matches get demoted; the relative order of matches is preserved.
1206 // One could imagine demoting only those matches that might cause
1207 // confusion (which, by the way, might change the relative order of
1208 // matches. We have decided to go with the simple demote-all approach
1209 // because selective demotion requires multiple Classify() calls and
1210 // such calls can be expensive (as expensive as running the whole
1211 // autocomplete system).
1212 if (!AutocompleteMatch::IsSearchType(match.type)) {
1213 last_relevance = CalculateRelevanceForHistory(
1214 base::Time::Now(), is_keyword, false,
1215 prevent_search_history_inlining);
1216 }
1217 }
1218
[email protected]0b9575f2014-07-30 11:58:371219 for (SearchSuggestionParser::SuggestResults::iterator i(
1220 scored_results.begin()); i != scored_results.end(); ++i) {
[email protected]7e3b77f2014-07-25 02:29:441221 if ((last_relevance != 0) && (i->relevance() >= last_relevance))
[email protected]55ce8f12012-05-09 04:44:081222 i->set_relevance(last_relevance - 1);
1223 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101224 }
1225
[email protected]55ce8f12012-05-09 04:44:081226 return scored_results;
[email protected]257ab712009-04-14 17:16:241227}
1228
grobye5fcee42014-09-26 03:36:461229void SearchProvider::ScoreHistoryResults(
1230 const HistoryResults& results,
1231 bool is_keyword,
1232 SearchSuggestionParser::SuggestResults* scored_results) {
1233 DCHECK(scored_results);
jdonnellye5f055d92015-01-15 00:58:581234 scored_results->clear();
1235
grobye5fcee42014-09-26 03:36:461236 if (results.empty()) {
grobye5fcee42014-09-26 03:36:461237 return;
1238 }
1239
1240 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1241 (input_.type() == metrics::OmniboxInputType::URL);
1242 const base::string16 input_text = GetInput(is_keyword).text();
1243 bool input_multiple_words = HasMultipleWords(input_text);
1244
1245 if (!prevent_inline_autocomplete && input_multiple_words) {
1246 // ScoreHistoryResultsHelper() allows autocompletion of multi-word, 1-visit
1247 // queries if the input also has multiple words. But if we were already
1248 // scoring a multi-word, multi-visit query aggressively, and the current
1249 // input is still a prefix of it, then changing the suggestion suddenly
1250 // feels wrong. To detect this case, first score as if only one word has
1251 // been typed, then check if the best result came from aggressive search
1252 // history scoring. If it did, then just keep that score set. This
1253 // 1200 the lowest possible score in CalculateRelevanceForHistory()'s
1254 // aggressive-scoring curve.
1255 *scored_results = ScoreHistoryResultsHelper(
1256 results, prevent_inline_autocomplete, false, input_text, is_keyword);
1257 if ((scored_results->front().relevance() < 1200) ||
1258 !HasMultipleWords(scored_results->front().suggestion()))
1259 scored_results->clear(); // Didn't detect the case above, score normally.
1260 }
1261 if (scored_results->empty()) {
1262 *scored_results = ScoreHistoryResultsHelper(results,
1263 prevent_inline_autocomplete,
1264 input_multiple_words,
1265 input_text,
1266 is_keyword);
1267 }
1268}
1269
[email protected]0b9575f2014-07-30 11:58:371270void SearchProvider::AddSuggestResultsToMap(
1271 const SearchSuggestionParser::SuggestResults& results,
1272 const std::string& metadata,
1273 MatchMap* map) {
[email protected]7bc5e162014-08-15 19:41:111274 for (size_t i = 0; i < results.size(); ++i) {
1275 AddMatchToMap(results[i], metadata, i, false,
1276 providers_.GetKeywordProviderURL() != NULL, map);
1277 }
initial.commit09911bf2008-07-26 23:55:291278}
1279
[email protected]d30268a2013-06-25 22:31:071280int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561281 // Use the suggested verbatim relevance score if it is non-negative (valid),
1282 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281283 // and if it won't suppress verbatim, leaving no default provider matches.
1284 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561285 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281286 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561287 // Check for results on each verbatim calculation, as results from older
1288 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231289 bool use_server_relevance =
1290 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281291 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231292 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241293 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231294 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071295 if (relevance_from_server)
1296 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231297 return use_server_relevance ?
1298 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521299}
[email protected]d1f0a7f2012-06-05 10:26:421300
[email protected]382a0642012-06-06 06:13:521301int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471302 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361303 return 250;
[email protected]dab8d52d2013-03-05 07:35:281304 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1305}
[email protected]52d08b12009-10-19 18:42:361306
[email protected]dab8d52d2013-03-05 07:35:281307int SearchProvider::
1308 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291309 switch (input_.type()) {
[email protected]3dc75b12014-06-08 00:02:221310 case metrics::OmniboxInputType::UNKNOWN:
1311 case metrics::OmniboxInputType::QUERY:
[email protected]90fe2bb2013-01-15 03:42:131312 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291313
[email protected]3dc75b12014-06-08 00:02:221314 case metrics::OmniboxInputType::URL:
[email protected]52d08b12009-10-19 18:42:361315 return 850;
initial.commit09911bf2008-07-26 23:55:291316
1317 default:
1318 NOTREACHED();
1319 return 0;
1320 }
1321}
1322
[email protected]d30268a2013-06-25 22:31:071323int SearchProvider::GetKeywordVerbatimRelevance(
1324 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281325 // Use the suggested verbatim relevance score if it is non-negative (valid),
1326 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1327 // and if it won't suppress verbatim, leaving no keyword provider matches.
1328 // Otherwise, if the keyword provider returned no matches and was still able
1329 // to suppress verbatim, the user would have no search/nav matches and may be
1330 // left unable to search using their keyword provider from the omnibox.
1331 // Check for results on each verbatim calculation, as results from older
1332 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231333 bool use_server_relevance =
1334 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281335 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231336 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241337 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231338 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071339 if (relevance_from_server)
1340 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231341 return use_server_relevance ?
1342 keyword_results_.verbatim_relevance :
1343 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
mpearson6456fb62015-11-13 06:44:281344 true,
[email protected]bc8bb0cd2013-06-24 21:50:231345 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451346}
1347
[email protected]51124552011-07-16 01:37:101348int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231349 const base::Time& time,
[email protected]51124552011-07-16 01:37:101350 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101351 bool use_aggressive_method,
1352 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181353 // The relevance of past searches falls off over time. There are two distinct
1354 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101355 // provider that we want to score aggressively), the score is in the range
1356 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161357 // it's in the range 1200-1299). If the second equation is used the
1358 // relevance of a search 15 minutes ago is discounted 50 points, while the
1359 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231360 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421361 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101362 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181363 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101364 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181365 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161366 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101367 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161368 max_score = 1299;
1369 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181370 std::pow(elapsed_time / autocomplete_time, 2.5));
1371 }
1372 elapsed_time -= autocomplete_time;
1373 }
1374
[email protected]c3a4bd992010-08-18 20:25:011375 const int score_discount =
1376 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291377
[email protected]6c85aa02009-02-27 12:08:091378 // Don't let scores go below 0. Negative relevance scores are meaningful in
1379 // a different way.
initial.commit09911bf2008-07-26 23:55:291380 int base_score;
[email protected]51124552011-07-16 01:37:101381 if (is_primary_provider)
[email protected]3dc75b12014-06-08 00:02:221382 base_score = (input_.type() == metrics::OmniboxInputType::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101383 else
1384 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291385 return std::max(0, base_score - score_discount);
1386}
1387
initial.commit09911bf2008-07-26 23:55:291388AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]0b9575f2014-07-30 11:58:371389 const SearchSuggestionParser::NavigationResult& navigation) {
[email protected]5889bfb2014-03-19 00:26:481390 base::string16 input;
1391 const bool trimmed_whitespace = base::TrimWhitespace(
1392 navigation.from_keyword_provider() ?
1393 keyword_input_.text() : input_.text(),
1394 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
[email protected]55ce8f12012-05-09 04:44:081395 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]78981d8c2014-05-09 15:05:471396 navigation.type());
[email protected]55ce8f12012-05-09 04:44:081397 match.destination_url = navigation.url();
[email protected]78981d8c2014-05-09 15:05:471398 BaseSearchProvider::SetDeletionURL(navigation.deletion_url(), &match);
[email protected]23db6492014-01-16 02:35:301399 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551400 // without trimming the scheme, so we can find matches at the beginning of the
1401 // scheme.
[email protected]371dab12012-06-01 03:23:551402 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301403 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551404 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301405 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351406 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1407 (!prefix || (match_start != 0));
rsleevi24f64dc22015-08-07 21:39:211408 const url_formatter::FormatUrlTypes format_types =
1409 url_formatter::kFormatUrlOmitAll &
1410 ~(trim_http ? 0 : url_formatter::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551411
[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(),
jshin1fb76462016-04-05 22:13:031417 url_formatter::FormatUrl(navigation.url(), format_types,
rsleevi24f64dc22015-08-07 21:39:211418 net::UnescapeRule::SPACES, nullptr, nullptr,
1419 &inline_autocomplete_offset),
blundelld130d592015-06-21 19:29:131420 client()->GetSchemeClassifier());
[email protected]6c94a1022014-02-21 03:48:041421 if (inline_autocomplete_offset != base::string16::npos) {
[email protected]518024c2013-07-19 23:40:251422 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1423 match.inline_autocompletion =
1424 match.fill_into_edit.substr(inline_autocomplete_offset);
1425 }
[email protected]6c94a1022014-02-21 03:48:041426 // An inlineable navsuggestion can only be the default match when there
1427 // is no keyword provider active, lest it appear first and break the user
mpearson6c183672014-09-03 02:09:421428 // out of keyword mode. We also must have received the navsuggestion before
1429 // the last keystroke, to prevent asynchronous inline autocompletions changes.
1430 // The navsuggestion can also only be default if either the inline
[email protected]5889bfb2014-03-19 00:26:481431 // autocompletion is empty or we're not preventing inline autocompletion.
1432 // Finally, if we have an inlineable navsuggestion with an inline completion
1433 // that we're not preventing, make sure we didn't trim any whitespace.
1434 // We don't want to claim http://foo.com/bar is inlineable against the
1435 // input "foo.com/b ".
mpearson6c183672014-09-03 02:09:421436 match.allowed_to_be_default_match =
1437 (prefix != NULL) &&
[email protected]6c94a1022014-02-21 03:48:041438 (providers_.GetKeywordProviderURL() == NULL) &&
mpearson6c183672014-09-03 02:09:421439 !navigation.received_after_last_keystroke() &&
[email protected]5889bfb2014-03-19 00:26:481440 (match.inline_autocompletion.empty() ||
[email protected]78981d8c2014-05-09 15:05:471441 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
jshin1fb76462016-04-05 22:13:031442 match.EnsureUWYTIsAllowedToBeDefault(input_,
blundelld130d592015-06-21 19:29:131443 client()->GetTemplateURLService());
[email protected]371dab12012-06-01 03:23:551444
[email protected]23db6492014-01-16 02:35:301445 match.contents = navigation.match_contents();
1446 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081447 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551448 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1449 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071450
1451 match.RecordAdditionalInfo(
1452 kRelevanceFromServerKey,
1453 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181454 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071455
initial.commit09911bf2008-07-26 23:55:291456 return match;
1457}
[email protected]4ab4c7c2010-11-24 04:49:341458
1459void SearchProvider::UpdateDone() {
mpearson84f19a152015-03-12 19:42:211460 // We're done when the timer isn't running and there are no suggest queries
1461 // pending.
1462 done_ = !timer_.IsRunning() && !default_fetcher_ && !keyword_fetcher_;
[email protected]4ab4c7c2010-11-24 04:49:341463}
[email protected]20184242014-05-14 02:57:421464
1465std::string SearchProvider::GetSessionToken() {
1466 base::TimeTicks current_time(base::TimeTicks::Now());
1467 // Renew token if it expired.
1468 if (current_time > token_expiration_time_) {
1469 const size_t kTokenBytes = 12;
1470 std::string raw_data;
Brett Wilsone3c4d1a2015-07-07 23:38:091471 base::RandBytes(base::WriteInto(&raw_data, kTokenBytes + 1), kTokenBytes);
[email protected]20184242014-05-14 02:57:421472 base::Base64Encode(raw_data, &current_token_);
[email protected]ab2c31f72014-05-17 17:03:531473
1474 // Make the base64 encoded value URL and filename safe(see RFC 3548).
1475 std::replace(current_token_.begin(), current_token_.end(), '+', '-');
1476 std::replace(current_token_.begin(), current_token_.end(), '/', '_');
[email protected]20184242014-05-14 02:57:421477 }
1478
1479 // Extend expiration time another 60 seconds.
1480 token_expiration_time_ = current_time + base::TimeDelta::FromSeconds(60);
1481
1482 return current_token_;
1483}
[email protected]2ef2a6642014-07-30 05:50:291484
grobye5fcee42014-09-26 03:36:461485AnswersQueryData SearchProvider::FindAnswersPrefetchData() {
1486 // Retrieve the top entry from scored history results.
1487 MatchMap map;
1488 AddTransformedHistoryResultsToMap(transformed_keyword_history_results_,
1489 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
1490 &map);
1491 AddTransformedHistoryResultsToMap(transformed_default_history_results_,
1492 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
1493 &map);
1494
1495 ACMatches matches;
1496 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
1497 matches.push_back(i->second);
1498 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
1499
1500 // If there is a top scoring entry, find the corresponding answer.
1501 if (!matches.empty())
1502 return answers_cache_.GetTopAnswerEntry(matches[0].contents);
1503
1504 return AnswersQueryData();
[email protected]2ef2a6642014-07-30 05:50:291505}