blob: ab129045d463d475bec2afa4412c14ecfade3212 [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]0915b352014-06-25 19:58:1436#include "components/search_engines/template_url_prepopulate_data.h"
[email protected]bf5c532d2014-07-05 00:29:5337#include "components/search_engines/template_url_service.h"
rsleevi24f64dc22015-08-07 21:39:2138#include "components/url_formatter/url_formatter.h"
asvitkine9a279832015-12-18 02:35:5039#include "components/variations/net/variations_http_headers.h"
[email protected]53f0cab2014-08-18 09:52:2740#include "grit/components_strings.h"
initial.commit09911bf2008-07-26 23:55:2941#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3442#include "net/base/load_flags.h"
[email protected]bd3b4712012-12-18 17:01:3043#include "net/http/http_request_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5344#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2145#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1746#include "ui/base/l10n/l10n_util.h"
[email protected]cca6f392014-05-28 21:32:2647#include "url/url_constants.h"
[email protected]761fa4702013-07-02 15:25:1548#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2949
[email protected]bc8bb0cd2013-06-24 21:50:2350// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3351
[email protected]51124552011-07-16 01:37:1052namespace {
53
[email protected]7706a522012-08-16 17:42:2554// We keep track in a histogram how many suggest requests we send, how
55// many suggest requests we invalidate (e.g., due to a user typing
56// another character), and how many replies we receive.
57// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
58// (excluding the end-of-list enum value)
59// We do not want values of existing enums to change or else it screws
60// up the statistics.
61enum SuggestRequestsHistogramValue {
62 REQUEST_SENT = 1,
63 REQUEST_INVALIDATED,
64 REPLY_RECEIVED,
65 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
66};
67
[email protected]90fe2bb2013-01-15 03:42:1368// The verbatim score for an input which is not an URL.
69const int kNonURLVerbatimRelevance = 1300;
70
[email protected]7706a522012-08-16 17:42:2571// Increments the appropriate value in the histogram by one.
72void LogOmniboxSuggestRequest(
73 SuggestRequestsHistogramValue request_value) {
74 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
75 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
76}
77
[email protected]0085863a2013-12-06 21:19:0378bool HasMultipleWords(const base::string16& text) {
[email protected]51124552011-07-16 01:37:1079 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
80 bool found_word = false;
81 if (i.Init()) {
82 while (i.Advance()) {
83 if (i.IsWord()) {
84 if (found_word)
85 return true;
86 found_word = true;
87 }
88 }
89 }
90 return false;
91}
92
[email protected]d1f0a7f2012-06-05 10:26:4293} // namespace
[email protected]51124552011-07-16 01:37:1094
[email protected]3954c3a2012-04-10 20:17:5595// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:5896
[email protected]85b8d6f2012-05-08 20:53:4797SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
[email protected]02346202014-02-05 05:18:3098 : template_url_service_(template_url_service) {}
[email protected]85b8d6f2012-05-08 20:53:4799
100const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
101 return default_provider_.empty() ? NULL :
102 template_url_service_->GetTemplateURLForKeyword(default_provider_);
103}
104
105const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
106 return keyword_provider_.empty() ? NULL :
107 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24108}
109
[email protected]3954c3a2012-04-10 20:17:55110
[email protected]bc8bb0cd2013-06-24 21:50:23111// SearchProvider::CompareScoredResults ---------------------------------------
112
113class SearchProvider::CompareScoredResults {
114 public:
[email protected]0b9575f2014-07-30 11:58:37115 bool operator()(const SearchSuggestionParser::Result& a,
116 const SearchSuggestionParser::Result& b) {
[email protected]bc8bb0cd2013-06-24 21:50:23117 // Sort in descending relevance order.
118 return a.relevance() > b.relevance();
119 }
120};
121
122
[email protected]3954c3a2012-04-10 20:17:55123// SearchProvider -------------------------------------------------------------
124
blundell55e35e82015-06-16 08:46:18125SearchProvider::SearchProvider(AutocompleteProviderClient* client,
blundelld130d592015-06-21 19:29:13126 AutocompleteProviderListener* listener)
127 : BaseSearchProvider(AutocompleteProvider::TYPE_SEARCH, client),
[email protected]776ee5902014-08-11 09:15:19128 listener_(listener),
blundelld130d592015-06-21 19:29:13129 providers_(client->GetTemplateURLService()),
groby1dbb8e22014-09-23 21:50:26130 answers_cache_(10) {
blundelld130d592015-06-21 19:29:13131 TemplateURLService* template_url_service = client->GetTemplateURLService();
132
133 // |template_url_service| can be null in tests.
134 if (template_url_service)
135 template_url_service->AddObserver(this);
[email protected]bc8bb0cd2013-06-24 21:50:23136}
137
[email protected]cb86ee6f2013-04-28 16:58:15138// static
[email protected]987fad782013-08-28 06:23:18139std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
140 return match.GetAdditionalInfo(kSuggestMetadataKey);
141}
142
mpearson6456fb62015-11-13 06:44:28143void SearchProvider::RegisterDisplayedAnswers(
144 const AutocompleteResult& result) {
145 if (result.empty())
mpearson84f19a152015-03-12 19:42:21146 return;
147
mpearson6456fb62015-11-13 06:44:28148 // The answer must be in the first or second slot to be considered. It should
149 // only be in the second slot if AutocompleteController ranked a local search
150 // history or a verbatim item higher than the answer.
151 AutocompleteResult::const_iterator match = result.begin();
152 if (match->answer_contents.empty() && result.size() > 1)
153 ++match;
154 if (match->answer_contents.empty() || match->answer_type.empty() ||
155 match->fill_into_edit.empty())
156 return;
mpearson84f19a152015-03-12 19:42:21157
mpearson6456fb62015-11-13 06:44:28158 // Valid answer encountered, cache it for further queries.
159 answers_cache_.UpdateRecentAnswers(match->fill_into_edit, match->answer_type);
160}
161
162// static
163int SearchProvider::CalculateRelevanceForKeywordVerbatim(
164 metrics::OmniboxInputType::Type type,
165 bool allow_exact_keyword_match,
166 bool prefer_keyword) {
167 // This function is responsible for scoring verbatim query matches
168 // for non-extension substituting keywords.
169 // KeywordProvider::CalculateRelevance() scores all other types of
170 // keyword verbatim matches.
171 if (allow_exact_keyword_match && prefer_keyword)
172 return 1500;
173 return (allow_exact_keyword_match &&
174 (type == metrics::OmniboxInputType::QUERY)) ?
175 1450 : 1100;
176}
177
178void SearchProvider::ResetSession() {
mpearson1b55e342016-03-19 04:36:20179 set_field_trial_triggered(false);
mpearson6456fb62015-11-13 06:44:28180 set_field_trial_triggered_in_session(false);
mpearson84f19a152015-03-12 19:42:21181}
182
[email protected]bc8bb0cd2013-06-24 21:50:23183SearchProvider::~SearchProvider() {
blundelld130d592015-06-21 19:29:13184 TemplateURLService* template_url_service = client()->GetTemplateURLService();
185 if (template_url_service)
186 template_url_service->RemoveObserver(this);
[email protected]bc8bb0cd2013-06-24 21:50:23187}
188
[email protected]ee6110b2014-01-09 22:26:31189// static
mpearson6c183672014-09-03 02:09:42190void SearchProvider::UpdateOldResults(
191 bool minimal_changes,
192 SearchSuggestionParser::Results* results) {
193 // When called without |minimal_changes|, it likely means the user has
194 // pressed a key. Revise the cached results appropriately.
195 if (!minimal_changes) {
196 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
197 results->suggest_results.begin();
mpearsonf080b342015-11-11 00:52:44198 sug_it != results->suggest_results.end(); ) {
199 if (sug_it->type() == AutocompleteMatchType::CALCULATOR) {
200 sug_it = results->suggest_results.erase(sug_it);
201 } else {
202 sug_it->set_received_after_last_keystroke(false);
203 ++sug_it;
204 }
mpearson6c183672014-09-03 02:09:42205 }
206 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
207 results->navigation_results.begin();
208 nav_it != results->navigation_results.end(); ++nav_it) {
209 nav_it->set_received_after_last_keystroke(false);
210 }
211 }
212}
213
214// static
215ACMatches::iterator SearchProvider::FindTopMatch(ACMatches* matches) {
216 ACMatches::iterator it = matches->begin();
217 while ((it != matches->end()) && !it->allowed_to_be_default_match)
218 ++it;
219 return it;
220}
221
initial.commit09911bf2008-07-26 23:55:29222void SearchProvider::Start(const AutocompleteInput& input,
jifcf322cda2015-06-17 11:01:18223 bool minimal_changes) {
a-v-ydd768d54b2016-03-25 21:07:46224 TRACE_EVENT0("omnibox", "SearchProvider::Start");
[email protected]04504c242013-01-22 21:08:55225 // Do our best to load the model as early as possible. This will reduce
226 // odds of having the model not ready when really needed (a non-empty input).
blundelld130d592015-06-21 19:29:13227 TemplateURLService* model = client()->GetTemplateURLService();
[email protected]04504c242013-01-22 21:08:55228 DCHECK(model);
229 model->Load();
230
initial.commit09911bf2008-07-26 23:55:29231 matches_.clear();
blundelld130d592015-06-21 19:29:13232 set_field_trial_triggered(false);
initial.commit09911bf2008-07-26 23:55:29233
hashimoto663b9f42014-08-26 04:29:20234 // Can't return search/suggest results for bogus input.
jifcf322cda2015-06-17 11:01:18235 if (input.from_omnibox_focus() ||
mariakhomenko3ef531d72015-01-10 00:03:43236 input.type() == metrics::OmniboxInputType::INVALID) {
mpearson8a37c382015-03-07 05:58:57237 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29238 return;
239 }
240
[email protected]14710852013-02-05 23:45:41241 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24242 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41243 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
244 &keyword_input_);
245 if (keyword_provider == NULL)
246 keyword_input_.Clear();
247 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24248 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24249
[email protected]85b8d6f2012-05-08 20:53:47250 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]ce7ee5f2014-06-16 23:41:19251 if (default_provider &&
252 !default_provider->SupportsReplacement(model->search_terms_data()))
[email protected]257ab712009-04-14 17:16:24253 default_provider = NULL;
254
255 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18256 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24257
258 if (!default_provider && !keyword_provider) {
259 // No valid providers.
mpearson8a37c382015-03-07 05:58:57260 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29261 return;
262 }
263
264 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24265 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03266 base::string16 default_provider_keyword(default_provider ?
267 default_provider->keyword() : base::string16());
268 base::string16 keyword_provider_keyword(keyword_provider ?
269 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32270 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47271 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29272 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15273 if (!done_)
mpearson8a37c382015-03-07 05:58:57274 Stop(false, false);
[email protected]257ab712009-04-14 17:16:24275 }
initial.commit09911bf2008-07-26 23:55:29276
[email protected]85b8d6f2012-05-08 20:53:47277 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29278
279 if (input.text().empty()) {
280 // User typed "?" alone. Give them a placeholder result indicating what
281 // this syntax does.
[email protected]257ab712009-04-14 17:16:24282 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00283 AutocompleteMatch match;
284 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36285 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24286 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35287 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47288 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36289 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24290 matches_.push_back(match);
291 }
mpearson8a37c382015-03-07 05:58:57292 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29293 return;
294 }
295
296 input_ = input;
297
[email protected]e1290ee62013-06-26 18:31:15298 DoHistoryQuery(minimal_changes);
grobye5fcee42014-09-26 03:36:46299 // Answers needs scored history results before any suggest query has been
300 // started, since the query for answer-bearing results needs additional
301 // prefetch information based on the highest-scored local history result.
jdonnelly41c5b46a2015-07-10 21:24:38302 ScoreHistoryResults(raw_default_history_results_,
303 false,
304 &transformed_default_history_results_);
305 ScoreHistoryResults(raw_keyword_history_results_,
306 true,
307 &transformed_keyword_history_results_);
308 prefetch_data_ = FindAnswersPrefetchData();
grobye5fcee42014-09-26 03:36:46309
jdonnelly41c5b46a2015-07-10 21:24:38310 // Raw results are not needed any more.
311 raw_default_history_results_.clear();
312 raw_keyword_history_results_.clear();
grobye5fcee42014-09-26 03:36:46313
[email protected]e1290ee62013-06-26 18:31:15314 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42315 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29316}
317
mpearson8a37c382015-03-07 05:58:57318void SearchProvider::Stop(bool clear_cached_results,
319 bool due_to_user_inactivity) {
[email protected]ec3f679b2014-08-18 07:45:13320 StopSuggest();
321 done_ = true;
322
323 if (clear_cached_results)
324 ClearAllResults();
325}
326
[email protected]776ee5902014-08-11 09:15:19327const TemplateURL* SearchProvider::GetTemplateURL(bool is_keyword) const {
328 return is_keyword ? providers_.GetKeywordProviderURL()
329 : providers_.GetDefaultProviderURL();
330}
331
332const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
333 return is_keyword ? keyword_input_ : input_;
334}
335
336bool SearchProvider::ShouldAppendExtraParams(
337 const SearchSuggestionParser::SuggestResult& result) const {
338 return !result.from_keyword_provider() ||
339 providers_.default_provider().empty();
340}
341
[email protected]776ee5902014-08-11 09:15:19342void SearchProvider::RecordDeletionResult(bool success) {
343 if (success) {
344 base::RecordAction(
345 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
346 } else {
347 base::RecordAction(
348 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
349 }
350}
351
mpearson6456fb62015-11-13 06:44:28352void SearchProvider::OnTemplateURLServiceChanged() {
353 // Only update matches at this time if we haven't already claimed we're done
354 // processing the query.
355 if (done_)
356 return;
357
358 // Check that the engines we're using weren't renamed or deleted. (In short,
359 // require that an engine still exists with the keywords in use.) For each
360 // deleted engine, cancel the in-flight request if any, drop its suggestions,
361 // and, in the case when the default provider was affected, point the cached
362 // default provider keyword name at the new name for the default provider.
363
364 // Get...ProviderURL() looks up the provider using the cached keyword name
365 // stored in |providers_|.
366 const TemplateURL* template_url = providers_.GetDefaultProviderURL();
367 if (!template_url) {
368 CancelFetcher(&default_fetcher_);
369 default_results_.Clear();
370 providers_.set(client()
371 ->GetTemplateURLService()
372 ->GetDefaultSearchProvider()
373 ->keyword(),
374 providers_.keyword_provider());
375 }
376 template_url = providers_.GetKeywordProviderURL();
377 if (!providers_.keyword_provider().empty() && !template_url) {
378 CancelFetcher(&keyword_fetcher_);
379 keyword_results_.Clear();
380 providers_.set(providers_.default_provider(), base::string16());
381 }
382 // It's possible the template URL changed without changing associated keyword.
383 // Hence, it's always necessary to update matches to use the new template
384 // URL. (One could cache the template URL and only call UpdateMatches() and
385 // OnProviderUpdate() if a keyword was deleted/renamed or the template URL
386 // was changed. That would save extra calls to these functions. However,
387 // this is uncommon and not likely to be worth the extra work.)
388 UpdateMatches();
389 listener_->OnProviderUpdate(true); // always pretend something changed
390}
391
[email protected]776ee5902014-08-11 09:15:19392void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
a-v-ydd768d54b2016-03-25 21:07:46393 TRACE_EVENT0("omnibox", "SearchProvider::OnURLFetchComplete");
[email protected]776ee5902014-08-11 09:15:19394 DCHECK(!done_);
[email protected]776ee5902014-08-11 09:15:19395 const bool is_keyword = source == keyword_fetcher_.get();
396
397 // Ensure the request succeeded and that the provider used is still available.
398 // A verbatim match cannot be generated without this provider, causing errors.
399 const bool request_succeeded =
400 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
401 GetTemplateURL(is_keyword);
402
403 LogFetchComplete(request_succeeded, is_keyword);
404
405 bool results_updated = false;
406 if (request_succeeded) {
407 scoped_ptr<base::Value> data(SearchSuggestionParser::DeserializeJsonData(
408 SearchSuggestionParser::ExtractJsonData(source)));
409 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 }
blundelld130d592015-06-21 19:29:13449 const std::string languages(client()->GetAcceptLanguages());
[email protected]776ee5902014-08-11 09:15:19450 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
451 results->navigation_results.begin();
452 nav_it != results->navigation_results.end(); ++nav_it) {
453 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
454 }
455}
456
[email protected]d4a94b92014-03-04 01:35:22457void SearchProvider::SortResults(bool is_keyword,
[email protected]0b9575f2014-07-30 11:58:37458 SearchSuggestionParser::Results* results) {
[email protected]d4a94b92014-03-04 01:35:22459 // Ignore suggested scores for non-keyword matches in keyword mode; if the
460 // server is allowed to score these, it could interfere with the user's
461 // ability to get good keyword results.
462 const bool abandon_suggested_scores =
463 !is_keyword && !providers_.keyword_provider().empty();
[email protected]0b9575f2014-07-30 11:58:37464 // Apply calculated relevance scores to suggestions if valid relevances were
[email protected]d4a94b92014-03-04 01:35:22465 // not provided or we're abandoning suggested scores entirely.
[email protected]2c802d12014-07-31 12:57:14466 if (!results->relevances_from_server || abandon_suggested_scores) {
[email protected]d4a94b92014-03-04 01:35:22467 ApplyCalculatedSuggestRelevance(&results->suggest_results);
468 ApplyCalculatedNavigationRelevance(&results->navigation_results);
469 // If abandoning scores entirely, also abandon the verbatim score.
470 if (abandon_suggested_scores)
471 results->verbatim_relevance = -1;
472 }
473
474 // Keep the result lists sorted.
475 const CompareScoredResults comparator = CompareScoredResults();
476 std::stable_sort(results->suggest_results.begin(),
477 results->suggest_results.end(),
478 comparator);
479 std::stable_sort(results->navigation_results.begin(),
480 results->navigation_results.end(),
481 comparator);
482}
483
[email protected]cfa164bf2014-03-19 11:51:15484void SearchProvider::LogFetchComplete(bool success, bool is_keyword) {
485 LogOmniboxSuggestRequest(REPLY_RECEIVED);
486 // Record response time for suggest requests sent to Google. We care
487 // only about the common case: the Google default provider used in
488 // non-keyword mode.
489 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
490 if (!is_keyword && default_url &&
[email protected]ce7ee5f2014-06-16 23:41:19491 (TemplateURLPrepopulateData::GetEngineType(
blundelld130d592015-06-21 19:29:13492 *default_url,
493 client()->GetTemplateURLService()->search_terms_data()) ==
[email protected]cfa164bf2014-03-19 11:51:15494 SEARCH_ENGINE_GOOGLE)) {
495 const base::TimeDelta elapsed_time =
496 base::TimeTicks::Now() - time_suggest_request_sent_;
497 if (success) {
498 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
499 elapsed_time);
500 } else {
501 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
502 elapsed_time);
503 }
504 }
505}
506
[email protected]cfa164bf2014-03-19 11:51:15507void SearchProvider::UpdateMatches() {
mpearson6c183672014-09-03 02:09:42508 PersistTopSuggestions(&default_results_);
509 PersistTopSuggestions(&keyword_results_);
[email protected]cfa164bf2014-03-19 11:51:15510 ConvertResultsToAutocompleteMatches();
511
512 // Check constraints that may be violated by suggested relevances.
513 if (!matches_.empty() &&
514 (default_results_.HasServerProvidedScores() ||
515 keyword_results_.HasServerProvidedScores())) {
516 // These blocks attempt to repair undesirable behavior by suggested
517 // relevances with minimal impact, preserving other suggested relevances.
[email protected]d0e4ad02014-08-22 18:58:33518 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
519 const bool is_extension_keyword = (keyword_url != NULL) &&
520 (keyword_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION);
521 if ((keyword_url != NULL) && !is_extension_keyword &&
[email protected]7bc5e162014-08-15 19:41:11522 (FindTopMatch() == matches_.end())) {
[email protected]d0e4ad02014-08-22 18:58:33523 // In non-extension keyword mode, disregard the keyword verbatim suggested
524 // relevance if necessary, so at least one match is allowed to be default.
525 // (In extension keyword mode this is not necessary because the extension
mpearson6c183672014-09-03 02:09:42526 // will return a default match.) Give keyword verbatim the lowest
527 // non-zero score to best reflect what the server desired.
528 DCHECK_EQ(0, keyword_results_.verbatim_relevance);
529 keyword_results_.verbatim_relevance = 1;
[email protected]cfa164bf2014-03-19 11:51:15530 ConvertResultsToAutocompleteMatches();
531 }
[email protected]89bd27d12014-04-12 17:36:23532 if (IsTopMatchSearchWithURLInput()) {
[email protected]cfa164bf2014-03-19 11:51:15533 // Disregard the suggested search and verbatim relevances if the input
534 // type is URL and the top match is a highly-ranked search suggestion.
535 // For example, prevent a search for "foo.com" from outranking another
536 // provider's navigation for "foo.com" or "foo.com/url_from_history".
537 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
538 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
539 default_results_.verbatim_relevance = -1;
540 keyword_results_.verbatim_relevance = -1;
541 ConvertResultsToAutocompleteMatches();
542 }
[email protected]d0e4ad02014-08-22 18:58:33543 if (!is_extension_keyword && (FindTopMatch() == matches_.end())) {
544 // Guarantee that SearchProvider returns a legal default match (except
545 // when in extension-based keyword mode). The omnibox always needs at
546 // least one legal default match, and it relies on SearchProvider in
547 // combination with KeywordProvider (for extension-based keywords) to
mpearson6c183672014-09-03 02:09:42548 // always return one. Give the verbatim suggestion the lowest non-zero
549 // scores to best reflect what the server desired.
550 DCHECK_EQ(0, default_results_.verbatim_relevance);
551 default_results_.verbatim_relevance = 1;
552 // We do not have to alter keyword_results_.verbatim_relevance here.
553 // If the user is in keyword mode, we already reverted (earlier in this
554 // function) the instructions to suppress keyword verbatim.
[email protected]cfa164bf2014-03-19 11:51:15555 ConvertResultsToAutocompleteMatches();
556 }
[email protected]89bd27d12014-04-12 17:36:23557 DCHECK(!IsTopMatchSearchWithURLInput());
[email protected]d0e4ad02014-08-22 18:58:33558 DCHECK(is_extension_keyword || (FindTopMatch() != matches_.end()));
[email protected]cfa164bf2014-03-19 11:51:15559 }
560 UMA_HISTOGRAM_CUSTOM_COUNTS(
561 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
mpearson6c183672014-09-03 02:09:42562
563 // Record the top suggestion (if any) for future use.
564 top_query_suggestion_match_contents_ = base::string16();
565 top_navigation_suggestion_ = GURL();
566 ACMatches::const_iterator first_match = FindTopMatch();
567 if ((first_match != matches_.end()) &&
568 !first_match->inline_autocompletion.empty()) {
569 // Identify if this match came from a query suggestion or a navsuggestion.
570 // In either case, extracts the identifying feature of the suggestion
571 // (query string or navigation url).
572 if (AutocompleteMatch::IsSearchType(first_match->type))
573 top_query_suggestion_match_contents_ = first_match->contents;
574 else
575 top_navigation_suggestion_ = first_match->destination_url;
576 }
577
[email protected]cfa164bf2014-03-19 11:51:15578 UpdateDone();
[email protected]cfa164bf2014-03-19 11:51:15579}
580
mpearsond37de7c2015-03-11 01:56:26581void SearchProvider::Run(bool query_is_private) {
[email protected]bc8bb0cd2013-06-24 21:50:23582 // Start a new request with the current input.
mpearson84f19a152015-03-12 19:42:21583 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05584
mpearsond37de7c2015-03-11 01:56:26585 if (!query_is_private) {
dtapuskadafcf892015-05-01 13:58:25586 default_fetcher_ =
587 CreateSuggestFetcher(kDefaultProviderURLFetcherID,
588 providers_.GetDefaultProviderURL(), input_);
mpearsond37de7c2015-03-11 01:56:26589 }
dtapuskadafcf892015-05-01 13:58:25590 keyword_fetcher_ =
591 CreateSuggestFetcher(kKeywordProviderURLFetcherID,
592 providers_.GetKeywordProviderURL(), keyword_input_);
[email protected]bc8bb0cd2013-06-24 21:50:23593
594 // Both the above can fail if the providers have been modified or deleted
595 // since the query began.
mpearson84f19a152015-03-12 19:42:21596 if (!default_fetcher_ && !keyword_fetcher_) {
[email protected]bc8bb0cd2013-06-24 21:50:23597 UpdateDone();
598 // We only need to update the listener if we're actually done.
599 if (done_)
600 listener_->OnProviderUpdate(false);
mpearsond37de7c2015-03-11 01:56:26601 } else {
602 // Sent at least one request.
603 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]bc8bb0cd2013-06-24 21:50:23604 }
[email protected]601858c02010-09-01 17:08:20605}
606
[email protected]8d457132010-11-04 18:13:40607void SearchProvider::DoHistoryQuery(bool minimal_changes) {
608 // The history query results are synchronous, so if minimal_changes is true,
609 // we still have the last results and don't need to do anything.
610 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29611 return;
612
grobye5fcee42014-09-26 03:36:46613 raw_keyword_history_results_.clear();
614 raw_default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29615
[email protected]78e5e432013-08-03 02:10:10616 if (OmniboxFieldTrial::SearchHistoryDisable(
617 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16618 return;
619
blundelld130d592015-06-21 19:29:13620 history::URLDatabase* url_db = client()->GetInMemoryDatabase();
[email protected]8d457132010-11-04 18:13:40621 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29622 return;
623
[email protected]51124552011-07-16 01:37:10624 // Request history for both the keyword and default provider. We grab many
625 // more matches than we'll ultimately clamp to so that if there are several
626 // recent multi-word matches who scores are lowered (see
grobye5fcee42014-09-26 03:36:46627 // ScoreHistoryResults()), they won't crowd out older, higher-scoring
[email protected]51124552011-07-16 01:37:10628 // matches. Note that this doesn't fix the problem entirely, but merely
629 // limits it to cases with a very large number of such multi-word matches; for
630 // now, this seems OK compared with the complexity of a real fix, which would
631 // require multiple searches and tracking of "single- vs. multi-word" in the
632 // database.
633 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47634 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
635 if (default_url) {
[email protected]b4bec972014-04-05 18:07:15636 const base::TimeTicks start_time = base::TimeTicks::Now();
grobye5fcee42014-09-26 03:36:46637 url_db->GetMostRecentKeywordSearchTerms(default_url->id(),
638 input_.text(),
639 num_matches,
640 &raw_default_history_results_);
[email protected]31afdf72013-09-26 04:29:36641 UMA_HISTOGRAM_TIMES(
642 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
643 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24644 }
[email protected]85b8d6f2012-05-08 20:53:47645 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
646 if (keyword_url) {
647 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
grobye5fcee42014-09-26 03:36:46648 keyword_input_.text(),
649 num_matches,
650 &raw_keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55651 }
initial.commit09911bf2008-07-26 23:55:29652}
653
bartn1c07e722014-10-27 19:34:24654base::TimeDelta SearchProvider::GetSuggestQueryDelay() const {
655 bool from_last_keystroke;
656 int polling_delay_ms;
657 OmniboxFieldTrial::GetSuggestPollingStrategy(&from_last_keystroke,
658 &polling_delay_ms);
659
660 base::TimeDelta delay(base::TimeDelta::FromMilliseconds(polling_delay_ms));
661 if (from_last_keystroke)
662 return delay;
663
664 base::TimeDelta time_since_last_suggest_request =
665 base::TimeTicks::Now() - time_suggest_request_sent_;
666 return std::max(base::TimeDelta(), delay - time_since_last_suggest_request);
667}
668
[email protected]6dc950f2012-07-16 19:49:08669void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
mpearsond37de7c2015-03-11 01:56:26670 bool query_is_private;
671 if (!IsQuerySuitableForSuggest(&query_is_private)) {
initial.commit09911bf2008-07-26 23:55:29672 StopSuggest();
[email protected]71b46152013-05-03 16:39:20673 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29674 return;
675 }
676
bartn1c07e722014-10-27 19:34:24677 if (OmniboxFieldTrial::DisableResultsCaching())
678 ClearAllResults();
679
initial.commit09911bf2008-07-26 23:55:29680 // For the minimal_changes case, if we finished the previous query and still
681 // have its results, or are allowed to keep running it, just do that, rather
682 // than starting a new query.
683 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24684 (!default_results_.suggest_results.empty() ||
685 !default_results_.navigation_results.empty() ||
686 !keyword_results_.suggest_results.empty() ||
687 !keyword_results_.navigation_results.empty() ||
[email protected]a2770a7d2014-04-22 19:33:35688 (!done_ && input_.want_asynchronous_matches())))
initial.commit09911bf2008-07-26 23:55:29689 return;
690
691 // We can't keep running any previous query, so halt it.
692 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42693
mpearson6c183672014-09-03 02:09:42694 UpdateAllOldResults(minimal_changes);
initial.commit09911bf2008-07-26 23:55:29695
[email protected]ee6110b2014-01-09 22:26:31696 // Update the content classifications of remaining results so they look good
697 // against the current input.
[email protected]23db6492014-01-16 02:35:30698 UpdateMatchContentsClass(input_.text(), &default_results_);
699 if (!keyword_input_.text().empty())
700 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31701
initial.commit09911bf2008-07-26 23:55:29702 // We can't start a new query if we're only allowed synchronous results.
[email protected]a2770a7d2014-04-22 19:33:35703 if (!input_.want_asynchronous_matches())
initial.commit09911bf2008-07-26 23:55:29704 return;
705
bartn1c07e722014-10-27 19:34:24706 // Kick off a timer that will start the URL fetch if it completes before
707 // the user types another character. Requests may be delayed to avoid
708 // flooding the server with requests that are likely to be thrown away later
709 // anyway.
710 const base::TimeDelta delay = GetSuggestQueryDelay();
711 if (delay <= base::TimeDelta()) {
mpearsond37de7c2015-03-11 01:56:26712 Run(query_is_private);
[email protected]515ffa942012-11-27 20:18:24713 return;
714 }
mpearsond37de7c2015-03-11 01:56:26715 timer_.Start(FROM_HERE,
716 delay,
717 base::Bind(&SearchProvider::Run,
718 base::Unretained(this),
719 query_is_private));
initial.commit09911bf2008-07-26 23:55:29720}
721
mpearson84f19a152015-03-12 19:42:21722void SearchProvider::CancelFetcher(scoped_ptr<net::URLFetcher>* fetcher) {
723 if (*fetcher) {
724 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
725 fetcher->reset();
726 }
727}
728
mpearsond37de7c2015-03-11 01:56:26729bool SearchProvider::IsQuerySuitableForSuggest(bool* query_is_private) const {
730 *query_is_private = IsQueryPotentionallyPrivate();
731
[email protected]3954c3a2012-04-10 20:17:55732 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
mpearsond37de7c2015-03-11 01:56:26733 // if the user has disabled it. Also don't send potentionally private data
734 // to the default search provider. (It's always okay to send explicit
735 // keyword input to a keyword suggest server, if any.)
[email protected]85b8d6f2012-05-08 20:53:47736 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
737 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
blundelld130d592015-06-21 19:29:13738 return !client()->IsOffTheRecord() && client()->SearchSuggestEnabled() &&
739 ((default_url && !default_url->suggestions_url().empty() &&
740 !*query_is_private) ||
741 (keyword_url && !keyword_url->suggestions_url().empty()));
mpearsond37de7c2015-03-11 01:56:26742}
[email protected]83c726482008-09-10 06:36:34743
mpearsond37de7c2015-03-11 01:56:26744bool SearchProvider::IsQueryPotentionallyPrivate() const {
[email protected]cac59d32010-08-09 23:23:14745 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34746 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34747
[email protected]cac59d32010-08-09 23:23:14748 // FORCED_QUERY means the user is explicitly asking us to search for this, so
749 // we assume it isn't a URL and/or there isn't private data.
[email protected]3dc75b12014-06-08 00:02:22750 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY)
mpearsond37de7c2015-03-11 01:56:26751 return false;
[email protected]83c726482008-09-10 06:36:34752
[email protected]f608ea102013-03-18 15:08:09753 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
754 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
755 // is both a waste of time and a disclosure of potentially private, local
756 // data. Other "schemes" may actually be usernames, and we don't want to send
757 // passwords. If the scheme is OK, we still need to check other cases below.
758 // If this is QUERY, then the presence of these schemes means the user
759 // explicitly typed one, and thus this is probably a URL that's being entered
760 // and happens to currently be invalid -- in which case we again want to run
761 // our checks below. Other QUERY cases are less likely to be URLs and thus we
762 // assume we're OK.
brettwbc17d2c82015-06-09 22:39:08763 if (!base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpScheme) &&
764 !base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
765 !base::LowerCaseEqualsASCII(input_.scheme(), url::kFtpScheme))
mpearsond37de7c2015-03-11 01:56:26766 return (input_.type() != metrics::OmniboxInputType::QUERY);
[email protected]cac59d32010-08-09 23:23:14767
768 // Don't send URLs with usernames, queries or refs. Some of these are
769 // private, and the Suggest server is unlikely to have any useful results
770 // for any of them. Also don't send URLs with ports, as we may initially
771 // think that a username + password is a host + port (and we don't want to
772 // send usernames/passwords), and even if the port really is a port, the
773 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58774 // Note that we only block based on refs if the input is URL-typed, as search
775 // queries can legitimately have #s in them which the URL parser
776 // overaggressively categorizes as a url with a ref.
[email protected]b45334502014-04-30 19:44:05777 const url::Parsed& parts = input_.parts();
[email protected]cac59d32010-08-09 23:23:14778 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58779 parts.query.is_nonempty() ||
[email protected]3dc75b12014-06-08 00:02:22780 (parts.ref.is_nonempty() &&
781 (input_.type() == metrics::OmniboxInputType::URL)))
mpearsond37de7c2015-03-11 01:56:26782 return true;
[email protected]cac59d32010-08-09 23:23:14783
784 // Don't send anything for https except the hostname. Hostnames are OK
785 // because they are visible when the TCP connection is established, but the
786 // specific path may reveal private information.
brettwbc17d2c82015-06-09 22:39:08787 if (base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36788 parts.path.is_nonempty())
mpearsond37de7c2015-03-11 01:56:26789 return true;
[email protected]83c726482008-09-10 06:36:34790
mpearsond37de7c2015-03-11 01:56:26791 return false;
[email protected]83c726482008-09-10 06:36:34792}
793
mpearson6c183672014-09-03 02:09:42794void SearchProvider::UpdateAllOldResults(bool minimal_changes) {
[email protected]dc735c02013-11-12 23:23:41795 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51796 // User is either in keyword mode with a blank input or out of
797 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24798 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51799 }
mpearson6c183672014-09-03 02:09:42800 UpdateOldResults(minimal_changes, &default_results_);
801 UpdateOldResults(minimal_changes, &keyword_results_);
[email protected]d1f0a7f2012-06-05 10:26:42802}
803
mpearson6c183672014-09-03 02:09:42804void SearchProvider::PersistTopSuggestions(
805 SearchSuggestionParser::Results* results) {
806 // Mark any results matching the current top results as having been received
807 // prior to the last keystroke. That prevents asynchronous updates from
808 // clobbering top results, which may be used for inline autocompletion.
809 // Other results don't need similar changes, because they shouldn't be
810 // displayed asynchronously anyway.
811 if (!top_query_suggestion_match_contents_.empty()) {
812 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
813 results->suggest_results.begin();
814 sug_it != results->suggest_results.end(); ++sug_it) {
815 if (sug_it->match_contents() == top_query_suggestion_match_contents_)
816 sug_it->set_received_after_last_keystroke(false);
817 }
818 }
819 if (top_navigation_suggestion_.is_valid()) {
820 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
821 results->navigation_results.begin();
822 nav_it != results->navigation_results.end(); ++nav_it) {
823 if (nav_it->url() == top_navigation_suggestion_)
824 nav_it->set_received_after_last_keystroke(false);
825 }
826 }
[email protected]d1f0a7f2012-06-05 10:26:42827}
828
[email protected]0b9575f2014-07-30 11:58:37829void SearchProvider::ApplyCalculatedSuggestRelevance(
830 SearchSuggestionParser::SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42831 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37832 SearchSuggestionParser::SuggestResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42833 result.set_relevance(
834 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
835 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07836 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42837 }
838}
839
[email protected]188b50c2013-03-28 07:19:42840void SearchProvider::ApplyCalculatedNavigationRelevance(
[email protected]0b9575f2014-07-30 11:58:37841 SearchSuggestionParser::NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42842 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37843 SearchSuggestionParser::NavigationResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42844 result.set_relevance(
845 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
846 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07847 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42848 }
849}
850
dtapuskadafcf892015-05-01 13:58:25851scoped_ptr<net::URLFetcher> SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12852 int id,
[email protected]9ff91722012-09-07 05:29:12853 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41854 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12855 if (!template_url || template_url->suggestions_url().empty())
856 return NULL;
857
858 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41859 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
[email protected]420472b22014-06-10 13:34:43860 search_term_args.input_type = input.type();
[email protected]14710852013-02-05 23:45:41861 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18862 search_term_args.page_classification = input.current_page_classification();
jdonnelly41c5b46a2015-07-10 21:24:38863 // Session token and prefetch data required for answers.
864 search_term_args.session_token = GetSessionToken();
865 if (!prefetch_data_.full_query_text.empty()) {
866 search_term_args.prefetch_query =
867 base::UTF16ToUTF8(prefetch_data_.full_query_text);
868 search_term_args.prefetch_query_type =
869 base::UTF16ToUTF8(prefetch_data_.query_type);
[email protected]2ef2a6642014-07-30 05:50:29870 }
[email protected]9ff91722012-09-07 05:29:12871 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19872 search_term_args,
blundelld130d592015-06-21 19:29:13873 client()->GetTemplateURLService()->search_terms_data()));
[email protected]9ff91722012-09-07 05:29:12874 if (!suggest_url.is_valid())
875 return NULL;
jdonnelly41c5b46a2015-07-10 21:24:38876
[email protected]9b9fa672013-11-07 06:04:52877 // Send the current page URL if user setting and URL requirements are met and
878 // the user is in the field trial.
blundelld130d592015-06-21 19:29:13879 TemplateURLService* template_url_service = client()->GetTemplateURLService();
mariakhomenko3ac684352015-06-18 20:01:17880 if (CanSendURL(input.current_url(), suggest_url, template_url,
[email protected]e6477f12014-08-05 07:59:54881 input.current_page_classification(),
blundelld130d592015-06-21 19:29:13882 template_url_service->search_terms_data(), client()) &&
[email protected]9b9fa672013-11-07 06:04:52883 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
mariakhomenko3ac684352015-06-18 20:01:17884 search_term_args.current_page_url = input.current_url().spec();
[email protected]9b9fa672013-11-07 06:04:52885 // Create the suggest URL again with the current page URL.
886 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
blundelld130d592015-06-21 19:29:13887 search_term_args, template_url_service->search_terms_data()));
[email protected]9b9fa672013-11-07 06:04:52888 }
[email protected]9ff91722012-09-07 05:29:12889
[email protected]9ff91722012-09-07 05:29:12890 LogOmniboxSuggestRequest(REQUEST_SENT);
891
dtapuskadafcf892015-05-01 13:58:25892 scoped_ptr<net::URLFetcher> fetcher =
[email protected]9ff91722012-09-07 05:29:12893 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
amohammadkhanf76ae112015-09-14 17:34:43894 data_use_measurement::DataUseUserData::AttachToFetcher(
895 fetcher.get(), data_use_measurement::DataUseUserData::OMNIBOX);
blundelld130d592015-06-21 19:29:13896 fetcher->SetRequestContext(client()->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34897 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30898 // Add Chrome experiment state to the request headers.
899 net::HttpRequestHeaders headers;
asvitkine9a279832015-12-18 02:35:50900 variations::AppendVariationHeaders(
blundelld130d592015-06-21 19:29:13901 fetcher->GetOriginalURL(), client()->IsOffTheRecord(), false, &headers);
[email protected]bd3b4712012-12-18 17:01:30902 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24903 fetcher->Start();
904 return fetcher;
905}
906
[email protected]344946a12012-12-20 12:03:42907void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29908 // Convert all the results to matches and add them to a map, so we can keep
909 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36910 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29911 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23912 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24913 int did_not_accept_keyword_suggestion =
914 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29915 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
916 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29917
[email protected]d30268a2013-06-25 22:31:07918 bool relevance_from_server;
919 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24920 int did_not_accept_default_suggestion =
921 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08922 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
923 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]7bc5e162014-08-15 19:41:11924 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]d1f0a7f2012-06-05 10:26:42925 if (verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44926 const base::string16& trimmed_verbatim =
927 base::CollapseWhitespace(input_.text(), false);
[email protected]716cd372014-08-15 18:56:03928
929 // Verbatim results don't get suggestions and hence, answers.
930 // Scan previous matches if the last answer-bearing suggestion matches
931 // verbatim, and if so, copy over answer contents.
932 base::string16 answer_contents;
933 base::string16 answer_type;
jdonnelly7393cee2014-10-31 01:52:56934 scoped_ptr<SuggestionAnswer> answer;
jdonnelly622e2ed2015-12-29 18:17:31935 base::string16 trimmed_verbatim_lower =
936 base::i18n::ToLower(trimmed_verbatim);
[email protected]716cd372014-08-15 18:56:03937 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
938 ++it) {
jdonnelly622e2ed2015-12-29 18:17:31939 if (it->answer &&
940 base::i18n::ToLower(it->fill_into_edit) == trimmed_verbatim_lower) {
[email protected]716cd372014-08-15 18:56:03941 answer_contents = it->answer_contents;
942 answer_type = it->answer_type;
jdonnelly7393cee2014-10-31 01:52:56943 answer = SuggestionAnswer::copy(it->answer.get());
[email protected]716cd372014-08-15 18:56:03944 break;
945 }
946 }
947
[email protected]0b9575f2014-07-30 11:58:37948 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44949 trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]716cd372014-08-15 18:56:03950 trimmed_verbatim, base::string16(), base::string16(), answer_contents,
dcheng51ace48a2015-12-26 22:45:17951 answer_type, std::move(answer), std::string(), std::string(), false,
jdonnelly7393cee2014-10-31 01:52:56952 verbatim_relevance, relevance_from_server, false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37953 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
[email protected]7bc5e162014-08-15 19:41:11954 false, keyword_url != NULL, &map);
[email protected]d1f0a7f2012-06-05 10:26:42955 }
[email protected]5423e562013-02-07 03:58:45956 if (!keyword_input_.text().empty()) {
[email protected]5423e562013-02-07 03:58:45957 // We only create the verbatim search query match for a keyword
958 // if it's not an extension keyword. Extension keywords are handled
959 // in KeywordProvider::Start(). (Extensions are complicated...)
960 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
961 // to the keyword verbatim search query. Do not create other matches
962 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:25963 if (keyword_url &&
964 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:07965 bool keyword_relevance_from_server;
966 const int keyword_verbatim_relevance =
967 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:28968 if (keyword_verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44969 const base::string16& trimmed_verbatim =
970 base::CollapseWhitespace(keyword_input_.text(), false);
[email protected]0b9575f2014-07-30 11:58:37971 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44972 trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
973 trimmed_verbatim, base::string16(), base::string16(),
jdonnelly7393cee2014-10-31 01:52:56974 base::string16(), base::string16(), nullptr, std::string(),
975 std::string(), true, keyword_verbatim_relevance,
976 keyword_relevance_from_server, false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37977 AddMatchToMap(verbatim, std::string(),
[email protected]7bc5e162014-08-15 19:41:11978 did_not_accept_keyword_suggestion, false, true, &map);
[email protected]dab8d52d2013-03-05 07:35:28979 }
[email protected]5423e562013-02-07 03:58:45980 }
981 }
grobye5fcee42014-09-26 03:36:46982 AddRawHistoryResultsToMap(true, did_not_accept_keyword_suggestion, &map);
983 AddRawHistoryResultsToMap(false, did_not_accept_default_suggestion, &map);
[email protected]257ab712009-04-14 17:16:24984
[email protected]d1cb6a822013-09-18 19:43:00985 AddSuggestResultsToMap(keyword_results_.suggest_results,
986 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:18987 AddSuggestResultsToMap(default_results_.suggest_results,
988 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:29989
[email protected]d30268a2013-06-25 22:31:07990 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:29991 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:07992 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:29993
[email protected]d30268a2013-06-25 22:31:07994 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
995 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:29996
[email protected]d30268a2013-06-25 22:31:07997 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
mpearson6c183672014-09-03 02:09:42998 // suggest/navsuggest matches, regardless of origin. We always include in
999 // that set a legal default match if possible. If Instant Extended is enabled
1000 // and we have server-provided (and thus hopefully more accurate) scores for
1001 // some suggestions, we allow more of those, until we reach
[email protected]d30268a2013-06-25 22:31:071002 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
1003 // whole popup).
1004 //
1005 // We will always return any verbatim matches, no matter how we obtained their
1006 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
1007 // higher-scoring matches under the conditions above.
1008 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
jdonnelly55f66142014-09-25 23:08:111009
mpearson6c183672014-09-03 02:09:421010 // Guarantee that if there's a legal default match anywhere in the result
1011 // set that it'll get returned. The rotate() call does this by moving the
1012 // default match to the front of the list.
1013 ACMatches::iterator default_match = FindTopMatch(&matches);
1014 if (default_match != matches.end())
1015 std::rotate(matches.begin(), default_match, default_match + 1);
[email protected]3723e6e2012-06-11 21:06:561016
jdonnelly55f66142014-09-25 23:08:111017 // It's possible to get a copy of an answer from previous matches and get the
1018 // same or a different answer to another server-provided suggestion. In the
1019 // future we may decide that we want to have answers attached to multiple
1020 // suggestions, but the current assumption is that there should only ever be
1021 // one suggestion with an answer. To maintain this assumption, remove any
1022 // answers after the first.
1023 RemoveExtraAnswers(&matches);
1024
1025 matches_.clear();
[email protected]d30268a2013-06-25 22:31:071026 size_t num_suggestions = 0;
1027 for (ACMatches::const_iterator i(matches.begin());
1028 (i != matches.end()) &&
1029 (matches_.size() < AutocompleteResult::kMaxMatches);
1030 ++i) {
1031 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
1032 // verbatim result, so this condition basically means "if this match is a
1033 // suggestion of some sort".
1034 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
1035 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
1036 // If we've already hit the limit on non-server-scored suggestions, and
1037 // this isn't a server-scored suggestion we can add, skip it.
1038 if ((num_suggestions >= kMaxMatches) &&
sdefresne51bbec7b2015-08-03 14:18:131039 (!search::IsInstantExtendedAPIEnabled() ||
[email protected]d30268a2013-06-25 22:31:071040 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
1041 continue;
1042 }
1043
1044 ++num_suggestions;
1045 }
1046
1047 matches_.push_back(*i);
1048 }
[email protected]31afdf72013-09-26 04:29:361049 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
1050 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:421051}
1052
jdonnelly55f66142014-09-25 23:08:111053void SearchProvider::RemoveExtraAnswers(ACMatches* matches) {
1054 bool answer_seen = false;
1055 for (ACMatches::iterator it = matches->begin(); it != matches->end(); ++it) {
jdonnelly7393cee2014-10-31 01:52:561056 if (it->answer) {
jdonnelly55f66142014-09-25 23:08:111057 if (!answer_seen) {
1058 answer_seen = true;
1059 } else {
1060 it->answer_contents.clear();
1061 it->answer_type.clear();
jdonnelly7393cee2014-10-31 01:52:561062 it->answer.reset();
jdonnelly55f66142014-09-25 23:08:111063 }
1064 }
1065 }
1066}
1067
[email protected]89bd27d12014-04-12 17:36:231068ACMatches::const_iterator SearchProvider::FindTopMatch() const {
[email protected]0a8718b12013-11-13 18:41:311069 ACMatches::const_iterator it = matches_.begin();
1070 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
1071 ++it;
1072 return it;
[email protected]9dfb4d362013-04-05 02:15:121073}
1074
[email protected]89bd27d12014-04-12 17:36:231075bool SearchProvider::IsTopMatchSearchWithURLInput() const {
1076 ACMatches::const_iterator first_match = FindTopMatch();
[email protected]3dc75b12014-06-08 00:02:221077 return (input_.type() == metrics::OmniboxInputType::URL) &&
[email protected]0a8718b12013-11-13 18:41:311078 (first_match != matches_.end()) &&
1079 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
[email protected]78981d8c2014-05-09 15:05:471080 (first_match->type != AutocompleteMatchType::NAVSUGGEST) &&
1081 (first_match->type != AutocompleteMatchType::NAVSUGGEST_PERSONALIZED);
[email protected]344946a12012-12-20 12:03:421082}
1083
[email protected]257ab712009-04-14 17:16:241084void SearchProvider::AddNavigationResultsToMatches(
[email protected]0b9575f2014-07-30 11:58:371085 const SearchSuggestionParser::NavigationResults& navigation_results,
[email protected]d30268a2013-06-25 22:31:071086 ACMatches* matches) {
[email protected]0b9575f2014-07-30 11:58:371087 for (SearchSuggestionParser::NavigationResults::const_iterator it =
1088 navigation_results.begin(); it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:071089 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:231090 // In the absence of suggested relevance scores, use only the single
1091 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:071092 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:231093 return;
[email protected]257ab712009-04-14 17:16:241094 }
1095}
1096
grobye5fcee42014-09-26 03:36:461097void SearchProvider::AddRawHistoryResultsToMap(bool is_keyword,
1098 int did_not_accept_suggestion,
1099 MatchMap* map) {
[email protected]31afdf72013-09-26 04:29:361100 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]51124552011-07-16 01:37:101101
jdonnelly41c5b46a2015-07-10 21:24:381102 const SearchSuggestionParser::SuggestResults* transformed_results =
1103 is_keyword ? &transformed_keyword_history_results_
1104 : &transformed_default_history_results_;
grobye5fcee42014-09-26 03:36:461105 DCHECK(transformed_results);
1106 AddTransformedHistoryResultsToMap(
1107 *transformed_results, did_not_accept_suggestion, map);
[email protected]31afdf72013-09-26 04:29:361108 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1109 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:101110}
1111
grobye5fcee42014-09-26 03:36:461112void SearchProvider::AddTransformedHistoryResultsToMap(
1113 const SearchSuggestionParser::SuggestResults& transformed_results,
1114 int did_not_accept_suggestion,
1115 MatchMap* map) {
1116 for (SearchSuggestionParser::SuggestResults::const_iterator i(
1117 transformed_results.begin());
1118 i != transformed_results.end();
1119 ++i) {
1120 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true,
1121 providers_.GetKeywordProviderURL() != NULL, map);
1122 }
1123}
1124
1125SearchSuggestionParser::SuggestResults
1126SearchProvider::ScoreHistoryResultsHelper(const HistoryResults& results,
1127 bool base_prevent_inline_autocomplete,
1128 bool input_multiple_words,
1129 const base::string16& input_text,
1130 bool is_keyword) {
[email protected]0b9575f2014-07-30 11:58:371131 SearchSuggestionParser::SuggestResults scored_results;
[email protected]ab5fd2f2014-07-17 19:18:521132 // True if the user has asked this exact query previously.
1133 bool found_what_you_typed_match = false;
[email protected]78e5e432013-08-03 02:10:101134 const bool prevent_search_history_inlining =
1135 OmniboxFieldTrial::SearchHistoryPreventInlining(
1136 input_.current_page_classification());
[email protected]c2ca3fd2014-03-22 03:07:441137 const base::string16& trimmed_input =
1138 base::CollapseWhitespace(input_text, false);
[email protected]257ab712009-04-14 17:16:241139 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1140 ++i) {
[email protected]c2ca3fd2014-03-22 03:07:441141 const base::string16& trimmed_suggestion =
1142 base::CollapseWhitespace(i->term, false);
1143
[email protected]51124552011-07-16 01:37:101144 // Don't autocomplete multi-word queries that have only been seen once
1145 // unless the user has typed more than one word.
1146 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
[email protected]c2ca3fd2014-03-22 03:07:441147 (!input_multiple_words && (i->visits < 2) &&
1148 HasMultipleWords(trimmed_suggestion));
[email protected]51124552011-07-16 01:37:101149
[email protected]78e5e432013-08-03 02:10:101150 int relevance = CalculateRelevanceForHistory(
1151 i->time, is_keyword, !prevent_inline_autocomplete,
1152 prevent_search_history_inlining);
[email protected]ab5fd2f2014-07-17 19:18:521153 // Add the match to |scored_results| by putting the what-you-typed match
1154 // on the front and appending all other matches. We want the what-you-
1155 // typed match to always be first.
[email protected]0b9575f2014-07-30 11:58:371156 SearchSuggestionParser::SuggestResults::iterator insertion_position =
1157 scored_results.end();
[email protected]ab5fd2f2014-07-17 19:18:521158 if (trimmed_suggestion == trimmed_input) {
1159 found_what_you_typed_match = true;
1160 insertion_position = scored_results.begin();
1161 }
mpearson6c183672014-09-03 02:09:421162 SearchSuggestionParser::SuggestResult history_suggestion(
1163 trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
1164 trimmed_suggestion, base::string16(), base::string16(),
jdonnelly7393cee2014-10-31 01:52:561165 base::string16(), base::string16(), nullptr, std::string(),
1166 std::string(), is_keyword, relevance, false, false, trimmed_input);
mpearson6c183672014-09-03 02:09:421167 // History results are synchronous; they are received on the last keystroke.
1168 history_suggestion.set_received_after_last_keystroke(false);
1169 scored_results.insert(insertion_position, history_suggestion);
[email protected]257ab712009-04-14 17:16:241170 }
[email protected]51124552011-07-16 01:37:101171
1172 // History returns results sorted for us. However, we may have docked some
[email protected]ab5fd2f2014-07-17 19:18:521173 // results' scores, so things are no longer in order. While keeping the
1174 // what-you-typed match at the front (if it exists), do a stable sort to get
[email protected]51124552011-07-16 01:37:101175 // things back in order without otherwise disturbing results with equal
1176 // scores, then force the scores to be unique, so that the order in which
1177 // they're shown is deterministic.
[email protected]ab5fd2f2014-07-17 19:18:521178 std::stable_sort(scored_results.begin() +
1179 (found_what_you_typed_match ? 1 : 0),
1180 scored_results.end(),
[email protected]55ce8f12012-05-09 04:44:081181 CompareScoredResults());
[email protected]7e3b77f2014-07-25 02:29:441182
1183 // Don't autocomplete to search terms that would normally be treated as URLs
1184 // when typed. For example, if the user searched for "google.com" and types
1185 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1186 // the input will look like a URL but act like a search, which is confusing.
1187 // The 1200 relevance score threshold in the test below is the lowest
1188 // possible score in CalculateRelevanceForHistory()'s aggressive-scoring
1189 // curve. This is an appropriate threshold to use to decide if we're overly
1190 // aggressively inlining because, if we decide the answer is yes, the
1191 // way we resolve it it to not use the aggressive-scoring curve.
1192 // NOTE: We don't check for autocompleting to URLs in the following cases:
1193 // * When inline autocomplete is disabled, we won't be inline autocompleting
1194 // this term, so we don't need to worry about confusion as much. This
1195 // also prevents calling Classify() again from inside the classifier
1196 // (which will corrupt state and likely crash), since the classifier
1197 // always disables inline autocomplete.
1198 // * When the user has typed the whole string before as a query, then it's
1199 // likely the user has no expectation that term should be interpreted as
1200 // as a URL, so we need not do anything special to preserve user
1201 // expectation.
[email protected]51124552011-07-16 01:37:101202 int last_relevance = 0;
[email protected]7e3b77f2014-07-25 02:29:441203 if (!base_prevent_inline_autocomplete && !found_what_you_typed_match &&
hashimoto663b9f42014-08-26 04:29:201204 scored_results.front().relevance() >= 1200) {
[email protected]7e3b77f2014-07-25 02:29:441205 AutocompleteMatch match;
blundelld130d592015-06-21 19:29:131206 client()->Classify(scored_results.front().suggestion(), false, false,
1207 input_.current_page_classification(), &match, NULL);
[email protected]7e3b77f2014-07-25 02:29:441208 // Demote this match that would normally be interpreted as a URL to have
1209 // the highest score a previously-issued search query could have when
1210 // scoring with the non-aggressive method. A consequence of demoting
1211 // by revising |last_relevance| is that this match and all following
1212 // matches get demoted; the relative order of matches is preserved.
1213 // One could imagine demoting only those matches that might cause
1214 // confusion (which, by the way, might change the relative order of
1215 // matches. We have decided to go with the simple demote-all approach
1216 // because selective demotion requires multiple Classify() calls and
1217 // such calls can be expensive (as expensive as running the whole
1218 // autocomplete system).
1219 if (!AutocompleteMatch::IsSearchType(match.type)) {
1220 last_relevance = CalculateRelevanceForHistory(
1221 base::Time::Now(), is_keyword, false,
1222 prevent_search_history_inlining);
1223 }
1224 }
1225
[email protected]0b9575f2014-07-30 11:58:371226 for (SearchSuggestionParser::SuggestResults::iterator i(
1227 scored_results.begin()); i != scored_results.end(); ++i) {
[email protected]7e3b77f2014-07-25 02:29:441228 if ((last_relevance != 0) && (i->relevance() >= last_relevance))
[email protected]55ce8f12012-05-09 04:44:081229 i->set_relevance(last_relevance - 1);
1230 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101231 }
1232
[email protected]55ce8f12012-05-09 04:44:081233 return scored_results;
[email protected]257ab712009-04-14 17:16:241234}
1235
grobye5fcee42014-09-26 03:36:461236void SearchProvider::ScoreHistoryResults(
1237 const HistoryResults& results,
1238 bool is_keyword,
1239 SearchSuggestionParser::SuggestResults* scored_results) {
1240 DCHECK(scored_results);
jdonnellye5f055d92015-01-15 00:58:581241 scored_results->clear();
1242
grobye5fcee42014-09-26 03:36:461243 if (results.empty()) {
grobye5fcee42014-09-26 03:36:461244 return;
1245 }
1246
1247 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1248 (input_.type() == metrics::OmniboxInputType::URL);
1249 const base::string16 input_text = GetInput(is_keyword).text();
1250 bool input_multiple_words = HasMultipleWords(input_text);
1251
1252 if (!prevent_inline_autocomplete && input_multiple_words) {
1253 // ScoreHistoryResultsHelper() allows autocompletion of multi-word, 1-visit
1254 // queries if the input also has multiple words. But if we were already
1255 // scoring a multi-word, multi-visit query aggressively, and the current
1256 // input is still a prefix of it, then changing the suggestion suddenly
1257 // feels wrong. To detect this case, first score as if only one word has
1258 // been typed, then check if the best result came from aggressive search
1259 // history scoring. If it did, then just keep that score set. This
1260 // 1200 the lowest possible score in CalculateRelevanceForHistory()'s
1261 // aggressive-scoring curve.
1262 *scored_results = ScoreHistoryResultsHelper(
1263 results, prevent_inline_autocomplete, false, input_text, is_keyword);
1264 if ((scored_results->front().relevance() < 1200) ||
1265 !HasMultipleWords(scored_results->front().suggestion()))
1266 scored_results->clear(); // Didn't detect the case above, score normally.
1267 }
1268 if (scored_results->empty()) {
1269 *scored_results = ScoreHistoryResultsHelper(results,
1270 prevent_inline_autocomplete,
1271 input_multiple_words,
1272 input_text,
1273 is_keyword);
1274 }
1275}
1276
[email protected]0b9575f2014-07-30 11:58:371277void SearchProvider::AddSuggestResultsToMap(
1278 const SearchSuggestionParser::SuggestResults& results,
1279 const std::string& metadata,
1280 MatchMap* map) {
[email protected]7bc5e162014-08-15 19:41:111281 for (size_t i = 0; i < results.size(); ++i) {
1282 AddMatchToMap(results[i], metadata, i, false,
1283 providers_.GetKeywordProviderURL() != NULL, map);
1284 }
initial.commit09911bf2008-07-26 23:55:291285}
1286
[email protected]d30268a2013-06-25 22:31:071287int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561288 // Use the suggested verbatim relevance score if it is non-negative (valid),
1289 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281290 // and if it won't suppress verbatim, leaving no default provider matches.
1291 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561292 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281293 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561294 // Check for results on each verbatim calculation, as results from older
1295 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231296 bool use_server_relevance =
1297 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281298 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231299 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241300 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231301 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071302 if (relevance_from_server)
1303 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231304 return use_server_relevance ?
1305 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521306}
[email protected]d1f0a7f2012-06-05 10:26:421307
[email protected]382a0642012-06-06 06:13:521308int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471309 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361310 return 250;
[email protected]dab8d52d2013-03-05 07:35:281311 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1312}
[email protected]52d08b12009-10-19 18:42:361313
[email protected]dab8d52d2013-03-05 07:35:281314int SearchProvider::
1315 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291316 switch (input_.type()) {
[email protected]3dc75b12014-06-08 00:02:221317 case metrics::OmniboxInputType::UNKNOWN:
1318 case metrics::OmniboxInputType::QUERY:
1319 case metrics::OmniboxInputType::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131320 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291321
[email protected]3dc75b12014-06-08 00:02:221322 case metrics::OmniboxInputType::URL:
[email protected]52d08b12009-10-19 18:42:361323 return 850;
initial.commit09911bf2008-07-26 23:55:291324
1325 default:
1326 NOTREACHED();
1327 return 0;
1328 }
1329}
1330
[email protected]d30268a2013-06-25 22:31:071331int SearchProvider::GetKeywordVerbatimRelevance(
1332 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281333 // Use the suggested verbatim relevance score if it is non-negative (valid),
1334 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1335 // and if it won't suppress verbatim, leaving no keyword provider matches.
1336 // Otherwise, if the keyword provider returned no matches and was still able
1337 // to suppress verbatim, the user would have no search/nav matches and may be
1338 // left unable to search using their keyword provider from the omnibox.
1339 // Check for results on each verbatim calculation, as results from older
1340 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231341 bool use_server_relevance =
1342 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281343 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231344 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241345 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231346 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071347 if (relevance_from_server)
1348 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231349 return use_server_relevance ?
1350 keyword_results_.verbatim_relevance :
1351 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
mpearson6456fb62015-11-13 06:44:281352 true,
[email protected]bc8bb0cd2013-06-24 21:50:231353 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451354}
1355
[email protected]51124552011-07-16 01:37:101356int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231357 const base::Time& time,
[email protected]51124552011-07-16 01:37:101358 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101359 bool use_aggressive_method,
1360 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181361 // The relevance of past searches falls off over time. There are two distinct
1362 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101363 // provider that we want to score aggressively), the score is in the range
1364 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161365 // it's in the range 1200-1299). If the second equation is used the
1366 // relevance of a search 15 minutes ago is discounted 50 points, while the
1367 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231368 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421369 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101370 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181371 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101372 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181373 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161374 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101375 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161376 max_score = 1299;
1377 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181378 std::pow(elapsed_time / autocomplete_time, 2.5));
1379 }
1380 elapsed_time -= autocomplete_time;
1381 }
1382
[email protected]c3a4bd992010-08-18 20:25:011383 const int score_discount =
1384 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291385
[email protected]6c85aa02009-02-27 12:08:091386 // Don't let scores go below 0. Negative relevance scores are meaningful in
1387 // a different way.
initial.commit09911bf2008-07-26 23:55:291388 int base_score;
[email protected]51124552011-07-16 01:37:101389 if (is_primary_provider)
[email protected]3dc75b12014-06-08 00:02:221390 base_score = (input_.type() == metrics::OmniboxInputType::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101391 else
1392 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291393 return std::max(0, base_score - score_discount);
1394}
1395
initial.commit09911bf2008-07-26 23:55:291396AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]0b9575f2014-07-30 11:58:371397 const SearchSuggestionParser::NavigationResult& navigation) {
[email protected]5889bfb2014-03-19 00:26:481398 base::string16 input;
1399 const bool trimmed_whitespace = base::TrimWhitespace(
1400 navigation.from_keyword_provider() ?
1401 keyword_input_.text() : input_.text(),
1402 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
[email protected]55ce8f12012-05-09 04:44:081403 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]78981d8c2014-05-09 15:05:471404 navigation.type());
[email protected]55ce8f12012-05-09 04:44:081405 match.destination_url = navigation.url();
[email protected]78981d8c2014-05-09 15:05:471406 BaseSearchProvider::SetDeletionURL(navigation.deletion_url(), &match);
[email protected]23db6492014-01-16 02:35:301407 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551408 // without trimming the scheme, so we can find matches at the beginning of the
1409 // scheme.
[email protected]371dab12012-06-01 03:23:551410 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301411 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551412 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301413 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351414 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1415 (!prefix || (match_start != 0));
rsleevi24f64dc22015-08-07 21:39:211416 const url_formatter::FormatUrlTypes format_types =
1417 url_formatter::kFormatUrlOmitAll &
1418 ~(trim_http ? 0 : url_formatter::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551419
blundelld130d592015-06-21 19:29:131420 const std::string languages(client()->GetAcceptLanguages());
[email protected]23db6492014-01-16 02:35:301421 size_t inline_autocomplete_offset = (prefix == NULL) ?
1422 base::string16::npos : (match_start + input.length());
[email protected]371dab12012-06-01 03:23:551423 match.fill_into_edit +=
[email protected]5655ea32014-06-21 05:28:081424 AutocompleteInput::FormattedStringWithEquivalentMeaning(
1425 navigation.url(),
rsleevi24f64dc22015-08-07 21:39:211426 url_formatter::FormatUrl(navigation.url(), languages, format_types,
1427 net::UnescapeRule::SPACES, nullptr, nullptr,
1428 &inline_autocomplete_offset),
blundelld130d592015-06-21 19:29:131429 client()->GetSchemeClassifier());
[email protected]14119032013-11-07 08:14:261430 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1431 // Otherwise, user edits to a suggestion would show non-Search results.
[email protected]3dc75b12014-06-08 00:02:221432 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581433 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031434 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261435 ++inline_autocomplete_offset;
1436 }
[email protected]6c94a1022014-02-21 03:48:041437 if (inline_autocomplete_offset != base::string16::npos) {
[email protected]518024c2013-07-19 23:40:251438 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1439 match.inline_autocompletion =
1440 match.fill_into_edit.substr(inline_autocomplete_offset);
1441 }
[email protected]6c94a1022014-02-21 03:48:041442 // An inlineable navsuggestion can only be the default match when there
1443 // is no keyword provider active, lest it appear first and break the user
mpearson6c183672014-09-03 02:09:421444 // out of keyword mode. We also must have received the navsuggestion before
1445 // the last keystroke, to prevent asynchronous inline autocompletions changes.
1446 // The navsuggestion can also only be default if either the inline
[email protected]5889bfb2014-03-19 00:26:481447 // autocompletion is empty or we're not preventing inline autocompletion.
1448 // Finally, if we have an inlineable navsuggestion with an inline completion
1449 // that we're not preventing, make sure we didn't trim any whitespace.
1450 // We don't want to claim http://foo.com/bar is inlineable against the
1451 // input "foo.com/b ".
mpearson6c183672014-09-03 02:09:421452 match.allowed_to_be_default_match =
1453 (prefix != NULL) &&
[email protected]6c94a1022014-02-21 03:48:041454 (providers_.GetKeywordProviderURL() == NULL) &&
mpearson6c183672014-09-03 02:09:421455 !navigation.received_after_last_keystroke() &&
[email protected]5889bfb2014-03-19 00:26:481456 (match.inline_autocompletion.empty() ||
[email protected]78981d8c2014-05-09 15:05:471457 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
mpearson4923cab62015-06-30 21:57:531458 match.EnsureUWYTIsAllowedToBeDefault(input_, client()->GetAcceptLanguages(),
blundelld130d592015-06-21 19:29:131459 client()->GetTemplateURLService());
[email protected]371dab12012-06-01 03:23:551460
[email protected]23db6492014-01-16 02:35:301461 match.contents = navigation.match_contents();
1462 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081463 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551464 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1465 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071466
1467 match.RecordAdditionalInfo(
1468 kRelevanceFromServerKey,
1469 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181470 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071471
initial.commit09911bf2008-07-26 23:55:291472 return match;
1473}
[email protected]4ab4c7c2010-11-24 04:49:341474
1475void SearchProvider::UpdateDone() {
mpearson84f19a152015-03-12 19:42:211476 // We're done when the timer isn't running and there are no suggest queries
1477 // pending.
1478 done_ = !timer_.IsRunning() && !default_fetcher_ && !keyword_fetcher_;
[email protected]4ab4c7c2010-11-24 04:49:341479}
[email protected]20184242014-05-14 02:57:421480
1481std::string SearchProvider::GetSessionToken() {
1482 base::TimeTicks current_time(base::TimeTicks::Now());
1483 // Renew token if it expired.
1484 if (current_time > token_expiration_time_) {
1485 const size_t kTokenBytes = 12;
1486 std::string raw_data;
Brett Wilsone3c4d1a2015-07-07 23:38:091487 base::RandBytes(base::WriteInto(&raw_data, kTokenBytes + 1), kTokenBytes);
[email protected]20184242014-05-14 02:57:421488 base::Base64Encode(raw_data, &current_token_);
[email protected]ab2c31f72014-05-17 17:03:531489
1490 // Make the base64 encoded value URL and filename safe(see RFC 3548).
1491 std::replace(current_token_.begin(), current_token_.end(), '+', '-');
1492 std::replace(current_token_.begin(), current_token_.end(), '/', '_');
[email protected]20184242014-05-14 02:57:421493 }
1494
1495 // Extend expiration time another 60 seconds.
1496 token_expiration_time_ = current_time + base::TimeDelta::FromSeconds(60);
1497
1498 return current_token_;
1499}
[email protected]2ef2a6642014-07-30 05:50:291500
grobye5fcee42014-09-26 03:36:461501AnswersQueryData SearchProvider::FindAnswersPrefetchData() {
1502 // Retrieve the top entry from scored history results.
1503 MatchMap map;
1504 AddTransformedHistoryResultsToMap(transformed_keyword_history_results_,
1505 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
1506 &map);
1507 AddTransformedHistoryResultsToMap(transformed_default_history_results_,
1508 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
1509 &map);
1510
1511 ACMatches matches;
1512 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
1513 matches.push_back(i->second);
1514 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
1515
1516 // If there is a top scoring entry, find the corresponding answer.
1517 if (!matches.empty())
1518 return answers_cache_.GetTopAnswerEntry(matches[0].contents);
1519
1520 return AnswersQueryData();
[email protected]2ef2a6642014-07-30 05:50:291521}