blob: e97e7f09302160f4873e7784974334e0ab634d8f [file] [log] [blame]
[email protected]e41982a72012-11-20 07:16:511// Copyright 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
hashimoto5f7db4b2014-08-27 02:46:205#include "components/omnibox/search_provider.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]1cb2dac2010-03-08 21:49:157#include <algorithm>
[email protected]c3a4bd992010-08-18 20:25:018#include <cmath>
[email protected]1cb2dac2010-03-08 21:49:159
[email protected]20184242014-05-14 02:57:4210#include "base/base64.h"
mpearsond37de7c2015-03-11 01:56:2611#include "base/bind.h"
[email protected]2041cf342010-02-19 03:15:5912#include "base/callback.h"
[email protected]51124552011-07-16 01:37:1013#include "base/i18n/break_iterator.h"
[email protected]503d03872011-05-06 08:36:2614#include "base/i18n/case_conversion.h"
[email protected]ffbec692012-02-26 20:26:4215#include "base/json/json_string_value_serializer.h"
[email protected]f5b95ba92012-03-27 14:05:1916#include "base/metrics/histogram.h"
[email protected]f7f41c0e2014-08-11 04:22:2317#include "base/metrics/user_metrics.h"
[email protected]20184242014-05-14 02:57:4218#include "base/rand_util.h"
[email protected]5889bfb2014-03-19 00:26:4819#include "base/strings/string_util.h"
[email protected]135cb802013-06-09 16:44:2020#include "base/strings/utf_string_conversions.h"
[email protected]e3ce70ac2014-06-26 18:34:5621#include "components/history/core/browser/in_memory_database.h"
[email protected]73b2d1e72014-06-25 23:45:3622#include "components/history/core/browser/keyword_search_term.h"
[email protected]3dc75b12014-06-08 00:02:2223#include "components/metrics/proto/omnibox_input_type.pb.h"
Ryo Hashimoto884ad192014-08-28 05:54:3024#include "components/omnibox/autocomplete_provider_client.h"
[email protected]b1c5ab682014-08-07 11:53:1725#include "components/omnibox/autocomplete_provider_listener.h"
[email protected]4b56c602014-08-14 17:02:3126#include "components/omnibox/autocomplete_result.h"
[email protected]02f5e32d2014-08-22 07:44:4627#include "components/omnibox/keyword_provider.h"
[email protected]4c583b62014-08-08 10:37:2328#include "components/omnibox/omnibox_field_trial.h"
jdonnelly7393cee2014-10-31 01:52:5629#include "components/omnibox/suggestion_answer.h"
[email protected]b1c5ab682014-08-07 11:53:1730#include "components/omnibox/url_prefix.h"
[email protected]720b10492014-07-23 08:48:4031#include "components/search/search.h"
[email protected]0915b352014-06-25 19:58:1432#include "components/search_engines/template_url_prepopulate_data.h"
[email protected]bf5c532d2014-07-05 00:29:5333#include "components/search_engines/template_url_service.h"
isherman3be67db2014-10-24 05:57:4434#include "components/variations/net/variations_http_header_provider.h"
[email protected]53f0cab2014-08-18 09:52:2735#include "grit/components_strings.h"
initial.commit09911bf2008-07-26 23:55:2936#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3437#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5538#include "net/base/net_util.h"
[email protected]bd3b4712012-12-18 17:01:3039#include "net/http/http_request_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5340#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2141#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1742#include "ui/base/l10n/l10n_util.h"
[email protected]cca6f392014-05-28 21:32:2643#include "url/url_constants.h"
[email protected]761fa4702013-07-02 15:25:1544#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2945
[email protected]bc8bb0cd2013-06-24 21:50:2346// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3347
[email protected]51124552011-07-16 01:37:1048namespace {
49
[email protected]7706a522012-08-16 17:42:2550// We keep track in a histogram how many suggest requests we send, how
51// many suggest requests we invalidate (e.g., due to a user typing
52// another character), and how many replies we receive.
53// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
54// (excluding the end-of-list enum value)
55// We do not want values of existing enums to change or else it screws
56// up the statistics.
57enum SuggestRequestsHistogramValue {
58 REQUEST_SENT = 1,
59 REQUEST_INVALIDATED,
60 REPLY_RECEIVED,
61 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
62};
63
[email protected]90fe2bb2013-01-15 03:42:1364// The verbatim score for an input which is not an URL.
65const int kNonURLVerbatimRelevance = 1300;
66
[email protected]7706a522012-08-16 17:42:2567// Increments the appropriate value in the histogram by one.
68void LogOmniboxSuggestRequest(
69 SuggestRequestsHistogramValue request_value) {
70 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
71 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
72}
73
[email protected]0085863a2013-12-06 21:19:0374bool HasMultipleWords(const base::string16& text) {
[email protected]51124552011-07-16 01:37:1075 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
76 bool found_word = false;
77 if (i.Init()) {
78 while (i.Advance()) {
79 if (i.IsWord()) {
80 if (found_word)
81 return true;
82 found_word = true;
83 }
84 }
85 }
86 return false;
87}
88
[email protected]d1f0a7f2012-06-05 10:26:4289} // namespace
[email protected]51124552011-07-16 01:37:1090
[email protected]3954c3a2012-04-10 20:17:5591// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:5892
[email protected]85b8d6f2012-05-08 20:53:4793SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
[email protected]02346202014-02-05 05:18:3094 : template_url_service_(template_url_service) {}
[email protected]85b8d6f2012-05-08 20:53:4795
96const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
97 return default_provider_.empty() ? NULL :
98 template_url_service_->GetTemplateURLForKeyword(default_provider_);
99}
100
101const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
102 return keyword_provider_.empty() ? NULL :
103 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24104}
105
[email protected]3954c3a2012-04-10 20:17:55106
[email protected]bc8bb0cd2013-06-24 21:50:23107// SearchProvider::CompareScoredResults ---------------------------------------
108
109class SearchProvider::CompareScoredResults {
110 public:
[email protected]0b9575f2014-07-30 11:58:37111 bool operator()(const SearchSuggestionParser::Result& a,
112 const SearchSuggestionParser::Result& b) {
[email protected]bc8bb0cd2013-06-24 21:50:23113 // Sort in descending relevance order.
114 return a.relevance() > b.relevance();
115 }
116};
117
118
[email protected]3954c3a2012-04-10 20:17:55119// SearchProvider -------------------------------------------------------------
120
hashimoto663b9f42014-08-26 04:29:20121SearchProvider::SearchProvider(
122 AutocompleteProviderListener* listener,
123 TemplateURLService* template_url_service,
Ryo Hashimoto884ad192014-08-28 05:54:30124 scoped_ptr<AutocompleteProviderClient> client)
125 : BaseSearchProvider(template_url_service, client.Pass(),
[email protected]e6477f12014-08-05 07:59:54126 AutocompleteProvider::TYPE_SEARCH),
[email protected]776ee5902014-08-11 09:15:19127 listener_(listener),
[email protected]ebbac63e2014-08-22 01:43:06128 providers_(template_url_service),
groby1dbb8e22014-09-23 21:50:26129 answers_cache_(10) {
mpearson84f19a152015-03-12 19:42:21130 // |template_url_service_| can be null in tests.
131 if (template_url_service_)
132 template_url_service_->AddObserver(this);
[email protected]bc8bb0cd2013-06-24 21:50:23133}
134
[email protected]cb86ee6f2013-04-28 16:58:15135// static
[email protected]987fad782013-08-28 06:23:18136std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
137 return match.GetAdditionalInfo(kSuggestMetadataKey);
138}
139
[email protected]bc8bb0cd2013-06-24 21:50:23140void SearchProvider::ResetSession() {
141 field_trial_triggered_in_session_ = false;
[email protected]4ab4c7c2010-11-24 04:49:34142}
143
mpearson84f19a152015-03-12 19:42:21144void SearchProvider::OnTemplateURLServiceChanged() {
145 // Only update matches at this time if we haven't already claimed we're done
146 // processing the query.
147 if (done_)
148 return;
149
150 // Check that the engines we're using weren't renamed or deleted. (In short,
151 // require that an engine still exists with the keywords in use.) For each
152 // deleted engine, cancel the in-flight request if any, drop its suggestions,
153 // and, in the case when the default provider was affected, point the cached
154 // default provider keyword name at the new name for the default provider.
155
156 // Get...ProviderURL() looks up the provider using the cached keyword name
157 // stored in |providers_|.
158 const TemplateURL* template_url = providers_.GetDefaultProviderURL();
159 if (!template_url) {
160 CancelFetcher(&default_fetcher_);
161 default_results_.Clear();
162 providers_.set(template_url_service_->GetDefaultSearchProvider()->keyword(),
163 providers_.keyword_provider());
164 }
165 template_url = providers_.GetKeywordProviderURL();
166 if (!providers_.keyword_provider().empty() && !template_url) {
167 CancelFetcher(&keyword_fetcher_);
168 keyword_results_.Clear();
169 providers_.set(providers_.default_provider(), base::string16());
170 }
171 // It's possible the template URL changed without changing associated keyword.
172 // Hence, it's always necessary to update matches to use the new template
173 // URL. (One could cache the template URL and only call UpdateMatches() and
174 // OnProviderUpdate() if a keyword was deleted/renamed or the template URL
175 // was changed. That would save extra calls to these functions. However,
176 // this is uncommon and not likely to be worth the extra work.)
177 UpdateMatches();
178 listener_->OnProviderUpdate(true); // always pretend something changed
179}
180
[email protected]bc8bb0cd2013-06-24 21:50:23181SearchProvider::~SearchProvider() {
mpearson84f19a152015-03-12 19:42:21182 if (template_url_service_)
183 template_url_service_->RemoveObserver(this);
[email protected]bc8bb0cd2013-06-24 21:50:23184}
185
[email protected]ee6110b2014-01-09 22:26:31186// static
[email protected]bc8bb0cd2013-06-24 21:50:23187int SearchProvider::CalculateRelevanceForKeywordVerbatim(
[email protected]332d17d22014-06-20 16:56:03188 metrics::OmniboxInputType::Type type,
[email protected]bc8bb0cd2013-06-24 21:50:23189 bool prefer_keyword) {
190 // This function is responsible for scoring verbatim query matches
191 // for non-extension keywords. KeywordProvider::CalculateRelevance()
192 // scores verbatim query matches for extension keywords, as well as
193 // for keyword matches (i.e., suggestions of a keyword itself, not a
194 // suggestion of a query on a keyword search engine). These two
195 // functions are currently in sync, but there's no reason we
196 // couldn't decide in the future to score verbatim matches
197 // differently for extension and non-extension keywords. If you
198 // make such a change, however, you should update this comment to
199 // describe it, so it's clear why the functions diverge.
200 if (prefer_keyword)
201 return 1500;
[email protected]3dc75b12014-06-08 00:02:22202 return (type == metrics::OmniboxInputType::QUERY) ? 1450 : 1100;
[email protected]bc8bb0cd2013-06-24 21:50:23203}
204
mpearson6c183672014-09-03 02:09:42205// static
206void SearchProvider::UpdateOldResults(
207 bool minimal_changes,
208 SearchSuggestionParser::Results* results) {
209 // When called without |minimal_changes|, it likely means the user has
210 // pressed a key. Revise the cached results appropriately.
211 if (!minimal_changes) {
212 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
213 results->suggest_results.begin();
214 sug_it != results->suggest_results.end(); ++sug_it) {
215 sug_it->set_received_after_last_keystroke(false);
216 }
217 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
218 results->navigation_results.begin();
219 nav_it != results->navigation_results.end(); ++nav_it) {
220 nav_it->set_received_after_last_keystroke(false);
221 }
222 }
223}
224
225// static
226ACMatches::iterator SearchProvider::FindTopMatch(ACMatches* matches) {
227 ACMatches::iterator it = matches->begin();
228 while ((it != matches->end()) && !it->allowed_to_be_default_match)
229 ++it;
230 return it;
231}
232
initial.commit09911bf2008-07-26 23:55:29233void SearchProvider::Start(const AutocompleteInput& input,
mariakhomenko3ef531d72015-01-10 00:03:43234 bool minimal_changes,
235 bool called_due_to_focus) {
[email protected]04504c242013-01-22 21:08:55236 // Do our best to load the model as early as possible. This will reduce
237 // odds of having the model not ready when really needed (a non-empty input).
238 TemplateURLService* model = providers_.template_url_service();
239 DCHECK(model);
240 model->Load();
241
initial.commit09911bf2008-07-26 23:55:29242 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57243 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29244
hashimoto663b9f42014-08-26 04:29:20245 // Can't return search/suggest results for bogus input.
mariakhomenko3ef531d72015-01-10 00:03:43246 if (called_due_to_focus ||
247 input.type() == metrics::OmniboxInputType::INVALID) {
mpearson8a37c382015-03-07 05:58:57248 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29249 return;
250 }
251
[email protected]14710852013-02-05 23:45:41252 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24253 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41254 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
255 &keyword_input_);
256 if (keyword_provider == NULL)
257 keyword_input_.Clear();
258 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24259 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24260
[email protected]85b8d6f2012-05-08 20:53:47261 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]ce7ee5f2014-06-16 23:41:19262 if (default_provider &&
263 !default_provider->SupportsReplacement(model->search_terms_data()))
[email protected]257ab712009-04-14 17:16:24264 default_provider = NULL;
265
266 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18267 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24268
269 if (!default_provider && !keyword_provider) {
270 // No valid providers.
mpearson8a37c382015-03-07 05:58:57271 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29272 return;
273 }
274
275 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24276 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03277 base::string16 default_provider_keyword(default_provider ?
278 default_provider->keyword() : base::string16());
279 base::string16 keyword_provider_keyword(keyword_provider ?
280 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32281 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47282 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29283 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15284 if (!done_)
mpearson8a37c382015-03-07 05:58:57285 Stop(false, false);
[email protected]257ab712009-04-14 17:16:24286 }
initial.commit09911bf2008-07-26 23:55:29287
[email protected]85b8d6f2012-05-08 20:53:47288 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29289
290 if (input.text().empty()) {
291 // User typed "?" alone. Give them a placeholder result indicating what
292 // this syntax does.
[email protected]257ab712009-04-14 17:16:24293 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00294 AutocompleteMatch match;
295 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36296 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24297 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35298 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47299 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36300 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24301 matches_.push_back(match);
302 }
mpearson8a37c382015-03-07 05:58:57303 Stop(true, false);
initial.commit09911bf2008-07-26 23:55:29304 return;
305 }
306
307 input_ = input;
308
[email protected]e1290ee62013-06-26 18:31:15309 DoHistoryQuery(minimal_changes);
grobye5fcee42014-09-26 03:36:46310 // Answers needs scored history results before any suggest query has been
311 // started, since the query for answer-bearing results needs additional
312 // prefetch information based on the highest-scored local history result.
313 if (OmniboxFieldTrial::EnableAnswersInSuggest()) {
314 ScoreHistoryResults(raw_default_history_results_,
315 false,
316 &transformed_default_history_results_);
317 ScoreHistoryResults(raw_keyword_history_results_,
318 true,
319 &transformed_keyword_history_results_);
320 prefetch_data_ = FindAnswersPrefetchData();
321
322 // Raw results are not needed any more.
323 raw_default_history_results_.clear();
324 raw_keyword_history_results_.clear();
grobye5fcee42014-09-26 03:36:46325 }
326
[email protected]e1290ee62013-06-26 18:31:15327 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42328 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29329}
330
mpearson8a37c382015-03-07 05:58:57331void SearchProvider::Stop(bool clear_cached_results,
332 bool due_to_user_inactivity) {
[email protected]ec3f679b2014-08-18 07:45:13333 StopSuggest();
334 done_ = true;
335
336 if (clear_cached_results)
337 ClearAllResults();
338}
339
[email protected]776ee5902014-08-11 09:15:19340const TemplateURL* SearchProvider::GetTemplateURL(bool is_keyword) const {
341 return is_keyword ? providers_.GetKeywordProviderURL()
342 : providers_.GetDefaultProviderURL();
343}
344
345const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
346 return is_keyword ? keyword_input_ : input_;
347}
348
349bool SearchProvider::ShouldAppendExtraParams(
350 const SearchSuggestionParser::SuggestResult& result) const {
351 return !result.from_keyword_provider() ||
352 providers_.default_provider().empty();
353}
354
[email protected]776ee5902014-08-11 09:15:19355void SearchProvider::RecordDeletionResult(bool success) {
356 if (success) {
357 base::RecordAction(
358 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
359 } else {
360 base::RecordAction(
361 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
362 }
363}
364
365void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
366 DCHECK(!done_);
[email protected]776ee5902014-08-11 09:15:19367 const bool is_keyword = source == keyword_fetcher_.get();
368
369 // Ensure the request succeeded and that the provider used is still available.
370 // A verbatim match cannot be generated without this provider, causing errors.
371 const bool request_succeeded =
372 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
373 GetTemplateURL(is_keyword);
374
375 LogFetchComplete(request_succeeded, is_keyword);
376
377 bool results_updated = false;
378 if (request_succeeded) {
379 scoped_ptr<base::Value> data(SearchSuggestionParser::DeserializeJsonData(
380 SearchSuggestionParser::ExtractJsonData(source)));
381 if (data) {
382 SearchSuggestionParser::Results* results =
383 is_keyword ? &keyword_results_ : &default_results_;
384 results_updated = ParseSuggestResults(*data, -1, is_keyword, results);
385 if (results_updated)
386 SortResults(is_keyword, results);
387 }
388 }
mpearson84f19a152015-03-12 19:42:21389
390 // Delete the fetcher now that we're done with it.
391 if (is_keyword)
392 keyword_fetcher_.reset();
393 else
394 default_fetcher_.reset();
395
396 // Update matches, done status, etc., and send alerts if necessary.
[email protected]776ee5902014-08-11 09:15:19397 UpdateMatches();
398 if (done_ || results_updated)
399 listener_->OnProviderUpdate(results_updated);
400}
401
[email protected]ec3f679b2014-08-18 07:45:13402void SearchProvider::StopSuggest() {
mpearson84f19a152015-03-12 19:42:21403 CancelFetcher(&default_fetcher_);
404 CancelFetcher(&keyword_fetcher_);
[email protected]ec3f679b2014-08-18 07:45:13405 timer_.Stop();
[email protected]ec3f679b2014-08-18 07:45:13406}
407
408void SearchProvider::ClearAllResults() {
409 keyword_results_.Clear();
410 default_results_.Clear();
411}
412
[email protected]776ee5902014-08-11 09:15:19413void SearchProvider::UpdateMatchContentsClass(
414 const base::string16& input_text,
415 SearchSuggestionParser::Results* results) {
416 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
417 results->suggest_results.begin();
418 sug_it != results->suggest_results.end(); ++sug_it) {
419 sug_it->ClassifyMatchContents(false, input_text);
420 }
Ryo Hashimoto884ad192014-08-28 05:54:30421 const std::string languages(client_->AcceptLanguages());
[email protected]776ee5902014-08-11 09:15:19422 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
423 results->navigation_results.begin();
424 nav_it != results->navigation_results.end(); ++nav_it) {
425 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
426 }
427}
428
[email protected]d4a94b92014-03-04 01:35:22429void SearchProvider::SortResults(bool is_keyword,
[email protected]0b9575f2014-07-30 11:58:37430 SearchSuggestionParser::Results* results) {
[email protected]d4a94b92014-03-04 01:35:22431 // Ignore suggested scores for non-keyword matches in keyword mode; if the
432 // server is allowed to score these, it could interfere with the user's
433 // ability to get good keyword results.
434 const bool abandon_suggested_scores =
435 !is_keyword && !providers_.keyword_provider().empty();
[email protected]0b9575f2014-07-30 11:58:37436 // Apply calculated relevance scores to suggestions if valid relevances were
[email protected]d4a94b92014-03-04 01:35:22437 // not provided or we're abandoning suggested scores entirely.
[email protected]2c802d12014-07-31 12:57:14438 if (!results->relevances_from_server || abandon_suggested_scores) {
[email protected]d4a94b92014-03-04 01:35:22439 ApplyCalculatedSuggestRelevance(&results->suggest_results);
440 ApplyCalculatedNavigationRelevance(&results->navigation_results);
441 // If abandoning scores entirely, also abandon the verbatim score.
442 if (abandon_suggested_scores)
443 results->verbatim_relevance = -1;
444 }
445
446 // Keep the result lists sorted.
447 const CompareScoredResults comparator = CompareScoredResults();
448 std::stable_sort(results->suggest_results.begin(),
449 results->suggest_results.end(),
450 comparator);
451 std::stable_sort(results->navigation_results.begin(),
452 results->navigation_results.end(),
453 comparator);
454}
455
[email protected]cfa164bf2014-03-19 11:51:15456void SearchProvider::LogFetchComplete(bool success, bool is_keyword) {
457 LogOmniboxSuggestRequest(REPLY_RECEIVED);
458 // Record response time for suggest requests sent to Google. We care
459 // only about the common case: the Google default provider used in
460 // non-keyword mode.
461 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
462 if (!is_keyword && default_url &&
[email protected]ce7ee5f2014-06-16 23:41:19463 (TemplateURLPrepopulateData::GetEngineType(
464 *default_url,
465 providers_.template_url_service()->search_terms_data()) ==
[email protected]cfa164bf2014-03-19 11:51:15466 SEARCH_ENGINE_GOOGLE)) {
467 const base::TimeDelta elapsed_time =
468 base::TimeTicks::Now() - time_suggest_request_sent_;
469 if (success) {
470 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
471 elapsed_time);
472 } else {
473 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
474 elapsed_time);
475 }
476 }
477}
478
[email protected]cfa164bf2014-03-19 11:51:15479void SearchProvider::UpdateMatches() {
mpearson6c183672014-09-03 02:09:42480 PersistTopSuggestions(&default_results_);
481 PersistTopSuggestions(&keyword_results_);
[email protected]cfa164bf2014-03-19 11:51:15482 ConvertResultsToAutocompleteMatches();
483
484 // Check constraints that may be violated by suggested relevances.
485 if (!matches_.empty() &&
486 (default_results_.HasServerProvidedScores() ||
487 keyword_results_.HasServerProvidedScores())) {
488 // These blocks attempt to repair undesirable behavior by suggested
489 // relevances with minimal impact, preserving other suggested relevances.
[email protected]d0e4ad02014-08-22 18:58:33490 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
491 const bool is_extension_keyword = (keyword_url != NULL) &&
492 (keyword_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION);
493 if ((keyword_url != NULL) && !is_extension_keyword &&
[email protected]7bc5e162014-08-15 19:41:11494 (FindTopMatch() == matches_.end())) {
[email protected]d0e4ad02014-08-22 18:58:33495 // In non-extension keyword mode, disregard the keyword verbatim suggested
496 // relevance if necessary, so at least one match is allowed to be default.
497 // (In extension keyword mode this is not necessary because the extension
mpearson6c183672014-09-03 02:09:42498 // will return a default match.) Give keyword verbatim the lowest
499 // non-zero score to best reflect what the server desired.
500 DCHECK_EQ(0, keyword_results_.verbatim_relevance);
501 keyword_results_.verbatim_relevance = 1;
[email protected]cfa164bf2014-03-19 11:51:15502 ConvertResultsToAutocompleteMatches();
503 }
[email protected]89bd27d12014-04-12 17:36:23504 if (IsTopMatchSearchWithURLInput()) {
[email protected]cfa164bf2014-03-19 11:51:15505 // Disregard the suggested search and verbatim relevances if the input
506 // type is URL and the top match is a highly-ranked search suggestion.
507 // For example, prevent a search for "foo.com" from outranking another
508 // provider's navigation for "foo.com" or "foo.com/url_from_history".
509 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
510 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
511 default_results_.verbatim_relevance = -1;
512 keyword_results_.verbatim_relevance = -1;
513 ConvertResultsToAutocompleteMatches();
514 }
[email protected]d0e4ad02014-08-22 18:58:33515 if (!is_extension_keyword && (FindTopMatch() == matches_.end())) {
516 // Guarantee that SearchProvider returns a legal default match (except
517 // when in extension-based keyword mode). The omnibox always needs at
518 // least one legal default match, and it relies on SearchProvider in
519 // combination with KeywordProvider (for extension-based keywords) to
mpearson6c183672014-09-03 02:09:42520 // always return one. Give the verbatim suggestion the lowest non-zero
521 // scores to best reflect what the server desired.
522 DCHECK_EQ(0, default_results_.verbatim_relevance);
523 default_results_.verbatim_relevance = 1;
524 // We do not have to alter keyword_results_.verbatim_relevance here.
525 // If the user is in keyword mode, we already reverted (earlier in this
526 // function) the instructions to suppress keyword verbatim.
[email protected]cfa164bf2014-03-19 11:51:15527 ConvertResultsToAutocompleteMatches();
528 }
[email protected]89bd27d12014-04-12 17:36:23529 DCHECK(!IsTopMatchSearchWithURLInput());
[email protected]d0e4ad02014-08-22 18:58:33530 DCHECK(is_extension_keyword || (FindTopMatch() != matches_.end()));
[email protected]cfa164bf2014-03-19 11:51:15531 }
532 UMA_HISTOGRAM_CUSTOM_COUNTS(
533 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
mpearson6c183672014-09-03 02:09:42534
535 // Record the top suggestion (if any) for future use.
536 top_query_suggestion_match_contents_ = base::string16();
537 top_navigation_suggestion_ = GURL();
538 ACMatches::const_iterator first_match = FindTopMatch();
539 if ((first_match != matches_.end()) &&
540 !first_match->inline_autocompletion.empty()) {
541 // Identify if this match came from a query suggestion or a navsuggestion.
542 // In either case, extracts the identifying feature of the suggestion
543 // (query string or navigation url).
544 if (AutocompleteMatch::IsSearchType(first_match->type))
545 top_query_suggestion_match_contents_ = first_match->contents;
546 else
547 top_navigation_suggestion_ = first_match->destination_url;
548 }
549
[email protected]cfa164bf2014-03-19 11:51:15550 UpdateDone();
[email protected]cfa164bf2014-03-19 11:51:15551}
552
mpearsond37de7c2015-03-11 01:56:26553void SearchProvider::Run(bool query_is_private) {
[email protected]bc8bb0cd2013-06-24 21:50:23554 // Start a new request with the current input.
mpearson84f19a152015-03-12 19:42:21555 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05556
mpearsond37de7c2015-03-11 01:56:26557 if (!query_is_private) {
dtapuskadafcf892015-05-01 13:58:25558 default_fetcher_ =
559 CreateSuggestFetcher(kDefaultProviderURLFetcherID,
560 providers_.GetDefaultProviderURL(), input_);
mpearsond37de7c2015-03-11 01:56:26561 }
dtapuskadafcf892015-05-01 13:58:25562 keyword_fetcher_ =
563 CreateSuggestFetcher(kKeywordProviderURLFetcherID,
564 providers_.GetKeywordProviderURL(), keyword_input_);
[email protected]bc8bb0cd2013-06-24 21:50:23565
566 // Both the above can fail if the providers have been modified or deleted
567 // since the query began.
mpearson84f19a152015-03-12 19:42:21568 if (!default_fetcher_ && !keyword_fetcher_) {
[email protected]bc8bb0cd2013-06-24 21:50:23569 UpdateDone();
570 // We only need to update the listener if we're actually done.
571 if (done_)
572 listener_->OnProviderUpdate(false);
mpearsond37de7c2015-03-11 01:56:26573 } else {
574 // Sent at least one request.
575 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]bc8bb0cd2013-06-24 21:50:23576 }
[email protected]601858c02010-09-01 17:08:20577}
578
[email protected]8d457132010-11-04 18:13:40579void SearchProvider::DoHistoryQuery(bool minimal_changes) {
580 // The history query results are synchronous, so if minimal_changes is true,
581 // we still have the last results and don't need to do anything.
582 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29583 return;
584
grobye5fcee42014-09-26 03:36:46585 raw_keyword_history_results_.clear();
586 raw_default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29587
[email protected]78e5e432013-08-03 02:10:10588 if (OmniboxFieldTrial::SearchHistoryDisable(
589 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16590 return;
591
Ryo Hashimoto884ad192014-08-28 05:54:30592 history::URLDatabase* url_db = client_->InMemoryDatabase();
[email protected]8d457132010-11-04 18:13:40593 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29594 return;
595
[email protected]51124552011-07-16 01:37:10596 // Request history for both the keyword and default provider. We grab many
597 // more matches than we'll ultimately clamp to so that if there are several
598 // recent multi-word matches who scores are lowered (see
grobye5fcee42014-09-26 03:36:46599 // ScoreHistoryResults()), they won't crowd out older, higher-scoring
[email protected]51124552011-07-16 01:37:10600 // matches. Note that this doesn't fix the problem entirely, but merely
601 // limits it to cases with a very large number of such multi-word matches; for
602 // now, this seems OK compared with the complexity of a real fix, which would
603 // require multiple searches and tracking of "single- vs. multi-word" in the
604 // database.
605 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47606 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
607 if (default_url) {
[email protected]b4bec972014-04-05 18:07:15608 const base::TimeTicks start_time = base::TimeTicks::Now();
grobye5fcee42014-09-26 03:36:46609 url_db->GetMostRecentKeywordSearchTerms(default_url->id(),
610 input_.text(),
611 num_matches,
612 &raw_default_history_results_);
[email protected]31afdf72013-09-26 04:29:36613 UMA_HISTOGRAM_TIMES(
614 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
615 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24616 }
[email protected]85b8d6f2012-05-08 20:53:47617 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
618 if (keyword_url) {
619 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
grobye5fcee42014-09-26 03:36:46620 keyword_input_.text(),
621 num_matches,
622 &raw_keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55623 }
initial.commit09911bf2008-07-26 23:55:29624}
625
bartn1c07e722014-10-27 19:34:24626base::TimeDelta SearchProvider::GetSuggestQueryDelay() const {
627 bool from_last_keystroke;
628 int polling_delay_ms;
629 OmniboxFieldTrial::GetSuggestPollingStrategy(&from_last_keystroke,
630 &polling_delay_ms);
631
632 base::TimeDelta delay(base::TimeDelta::FromMilliseconds(polling_delay_ms));
633 if (from_last_keystroke)
634 return delay;
635
636 base::TimeDelta time_since_last_suggest_request =
637 base::TimeTicks::Now() - time_suggest_request_sent_;
638 return std::max(base::TimeDelta(), delay - time_since_last_suggest_request);
639}
640
[email protected]6dc950f2012-07-16 19:49:08641void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
mpearsond37de7c2015-03-11 01:56:26642 bool query_is_private;
643 if (!IsQuerySuitableForSuggest(&query_is_private)) {
initial.commit09911bf2008-07-26 23:55:29644 StopSuggest();
[email protected]71b46152013-05-03 16:39:20645 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29646 return;
647 }
648
bartn1c07e722014-10-27 19:34:24649 if (OmniboxFieldTrial::DisableResultsCaching())
650 ClearAllResults();
651
initial.commit09911bf2008-07-26 23:55:29652 // For the minimal_changes case, if we finished the previous query and still
653 // have its results, or are allowed to keep running it, just do that, rather
654 // than starting a new query.
655 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24656 (!default_results_.suggest_results.empty() ||
657 !default_results_.navigation_results.empty() ||
658 !keyword_results_.suggest_results.empty() ||
659 !keyword_results_.navigation_results.empty() ||
[email protected]a2770a7d2014-04-22 19:33:35660 (!done_ && input_.want_asynchronous_matches())))
initial.commit09911bf2008-07-26 23:55:29661 return;
662
663 // We can't keep running any previous query, so halt it.
664 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42665
mpearson6c183672014-09-03 02:09:42666 UpdateAllOldResults(minimal_changes);
initial.commit09911bf2008-07-26 23:55:29667
[email protected]ee6110b2014-01-09 22:26:31668 // Update the content classifications of remaining results so they look good
669 // against the current input.
[email protected]23db6492014-01-16 02:35:30670 UpdateMatchContentsClass(input_.text(), &default_results_);
671 if (!keyword_input_.text().empty())
672 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31673
initial.commit09911bf2008-07-26 23:55:29674 // We can't start a new query if we're only allowed synchronous results.
[email protected]a2770a7d2014-04-22 19:33:35675 if (!input_.want_asynchronous_matches())
initial.commit09911bf2008-07-26 23:55:29676 return;
677
bartn1c07e722014-10-27 19:34:24678 // Kick off a timer that will start the URL fetch if it completes before
679 // the user types another character. Requests may be delayed to avoid
680 // flooding the server with requests that are likely to be thrown away later
681 // anyway.
682 const base::TimeDelta delay = GetSuggestQueryDelay();
683 if (delay <= base::TimeDelta()) {
mpearsond37de7c2015-03-11 01:56:26684 Run(query_is_private);
[email protected]515ffa942012-11-27 20:18:24685 return;
686 }
mpearsond37de7c2015-03-11 01:56:26687 timer_.Start(FROM_HERE,
688 delay,
689 base::Bind(&SearchProvider::Run,
690 base::Unretained(this),
691 query_is_private));
initial.commit09911bf2008-07-26 23:55:29692}
693
mpearson84f19a152015-03-12 19:42:21694void SearchProvider::CancelFetcher(scoped_ptr<net::URLFetcher>* fetcher) {
695 if (*fetcher) {
696 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
697 fetcher->reset();
698 }
699}
700
mpearsond37de7c2015-03-11 01:56:26701bool SearchProvider::IsQuerySuitableForSuggest(bool* query_is_private) const {
702 *query_is_private = IsQueryPotentionallyPrivate();
703
[email protected]3954c3a2012-04-10 20:17:55704 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
mpearsond37de7c2015-03-11 01:56:26705 // if the user has disabled it. Also don't send potentionally private data
706 // to the default search provider. (It's always okay to send explicit
707 // keyword input to a keyword suggest server, if any.)
[email protected]85b8d6f2012-05-08 20:53:47708 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
709 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
mpearsond37de7c2015-03-11 01:56:26710 return !client_->IsOffTheRecord() && client_->SearchSuggestEnabled() &&
711 ((default_url && !default_url->suggestions_url().empty() &&
712 !*query_is_private) ||
713 (keyword_url && !keyword_url->suggestions_url().empty()));
714}
[email protected]83c726482008-09-10 06:36:34715
mpearsond37de7c2015-03-11 01:56:26716bool SearchProvider::IsQueryPotentionallyPrivate() const {
[email protected]cac59d32010-08-09 23:23:14717 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34718 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34719
[email protected]cac59d32010-08-09 23:23:14720 // FORCED_QUERY means the user is explicitly asking us to search for this, so
721 // we assume it isn't a URL and/or there isn't private data.
[email protected]3dc75b12014-06-08 00:02:22722 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY)
mpearsond37de7c2015-03-11 01:56:26723 return false;
[email protected]83c726482008-09-10 06:36:34724
[email protected]f608ea102013-03-18 15:08:09725 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
726 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
727 // is both a waste of time and a disclosure of potentially private, local
728 // data. Other "schemes" may actually be usernames, and we don't want to send
729 // passwords. If the scheme is OK, we still need to check other cases below.
730 // If this is QUERY, then the presence of these schemes means the user
731 // explicitly typed one, and thus this is probably a URL that's being entered
732 // and happens to currently be invalid -- in which case we again want to run
733 // our checks below. Other QUERY cases are less likely to be URLs and thus we
734 // assume we're OK.
brettwbc17d2c82015-06-09 22:39:08735 if (!base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpScheme) &&
736 !base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
737 !base::LowerCaseEqualsASCII(input_.scheme(), url::kFtpScheme))
mpearsond37de7c2015-03-11 01:56:26738 return (input_.type() != metrics::OmniboxInputType::QUERY);
[email protected]cac59d32010-08-09 23:23:14739
740 // Don't send URLs with usernames, queries or refs. Some of these are
741 // private, and the Suggest server is unlikely to have any useful results
742 // for any of them. Also don't send URLs with ports, as we may initially
743 // think that a username + password is a host + port (and we don't want to
744 // send usernames/passwords), and even if the port really is a port, the
745 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58746 // Note that we only block based on refs if the input is URL-typed, as search
747 // queries can legitimately have #s in them which the URL parser
748 // overaggressively categorizes as a url with a ref.
[email protected]b45334502014-04-30 19:44:05749 const url::Parsed& parts = input_.parts();
[email protected]cac59d32010-08-09 23:23:14750 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58751 parts.query.is_nonempty() ||
[email protected]3dc75b12014-06-08 00:02:22752 (parts.ref.is_nonempty() &&
753 (input_.type() == metrics::OmniboxInputType::URL)))
mpearsond37de7c2015-03-11 01:56:26754 return true;
[email protected]cac59d32010-08-09 23:23:14755
756 // Don't send anything for https except the hostname. Hostnames are OK
757 // because they are visible when the TCP connection is established, but the
758 // specific path may reveal private information.
brettwbc17d2c82015-06-09 22:39:08759 if (base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36760 parts.path.is_nonempty())
mpearsond37de7c2015-03-11 01:56:26761 return true;
[email protected]83c726482008-09-10 06:36:34762
mpearsond37de7c2015-03-11 01:56:26763 return false;
[email protected]83c726482008-09-10 06:36:34764}
765
mpearson6c183672014-09-03 02:09:42766void SearchProvider::UpdateAllOldResults(bool minimal_changes) {
[email protected]dc735c02013-11-12 23:23:41767 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51768 // User is either in keyword mode with a blank input or out of
769 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24770 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51771 }
mpearson6c183672014-09-03 02:09:42772 UpdateOldResults(minimal_changes, &default_results_);
773 UpdateOldResults(minimal_changes, &keyword_results_);
[email protected]d1f0a7f2012-06-05 10:26:42774}
775
mpearson6c183672014-09-03 02:09:42776void SearchProvider::PersistTopSuggestions(
777 SearchSuggestionParser::Results* results) {
778 // Mark any results matching the current top results as having been received
779 // prior to the last keystroke. That prevents asynchronous updates from
780 // clobbering top results, which may be used for inline autocompletion.
781 // Other results don't need similar changes, because they shouldn't be
782 // displayed asynchronously anyway.
783 if (!top_query_suggestion_match_contents_.empty()) {
784 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
785 results->suggest_results.begin();
786 sug_it != results->suggest_results.end(); ++sug_it) {
787 if (sug_it->match_contents() == top_query_suggestion_match_contents_)
788 sug_it->set_received_after_last_keystroke(false);
789 }
790 }
791 if (top_navigation_suggestion_.is_valid()) {
792 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
793 results->navigation_results.begin();
794 nav_it != results->navigation_results.end(); ++nav_it) {
795 if (nav_it->url() == top_navigation_suggestion_)
796 nav_it->set_received_after_last_keystroke(false);
797 }
798 }
[email protected]d1f0a7f2012-06-05 10:26:42799}
800
[email protected]0b9575f2014-07-30 11:58:37801void SearchProvider::ApplyCalculatedSuggestRelevance(
802 SearchSuggestionParser::SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42803 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37804 SearchSuggestionParser::SuggestResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42805 result.set_relevance(
806 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
807 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07808 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42809 }
810}
811
[email protected]188b50c2013-03-28 07:19:42812void SearchProvider::ApplyCalculatedNavigationRelevance(
[email protected]0b9575f2014-07-30 11:58:37813 SearchSuggestionParser::NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42814 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37815 SearchSuggestionParser::NavigationResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42816 result.set_relevance(
817 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
818 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07819 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42820 }
821}
822
dtapuskadafcf892015-05-01 13:58:25823scoped_ptr<net::URLFetcher> SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12824 int id,
[email protected]9ff91722012-09-07 05:29:12825 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41826 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12827 if (!template_url || template_url->suggestions_url().empty())
828 return NULL;
829
830 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41831 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
[email protected]420472b22014-06-10 13:34:43832 search_term_args.input_type = input.type();
[email protected]14710852013-02-05 23:45:41833 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18834 search_term_args.page_classification = input.current_page_classification();
[email protected]2ef2a6642014-07-30 05:50:29835 if (OmniboxFieldTrial::EnableAnswersInSuggest()) {
[email protected]20184242014-05-14 02:57:42836 search_term_args.session_token = GetSessionToken();
[email protected]2ef2a6642014-07-30 05:50:29837 if (!prefetch_data_.full_query_text.empty()) {
838 search_term_args.prefetch_query =
[email protected]ebbac63e2014-08-22 01:43:06839 base::UTF16ToUTF8(prefetch_data_.full_query_text);
[email protected]2ef2a6642014-07-30 05:50:29840 search_term_args.prefetch_query_type =
[email protected]ebbac63e2014-08-22 01:43:06841 base::UTF16ToUTF8(prefetch_data_.query_type);
[email protected]2ef2a6642014-07-30 05:50:29842 }
843 }
[email protected]9ff91722012-09-07 05:29:12844 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19845 search_term_args,
846 providers_.template_url_service()->search_terms_data()));
[email protected]9ff91722012-09-07 05:29:12847 if (!suggest_url.is_valid())
848 return NULL;
[email protected]9b9fa672013-11-07 06:04:52849 // Send the current page URL if user setting and URL requirements are met and
850 // the user is in the field trial.
851 if (CanSendURL(current_page_url_, suggest_url, template_url,
[email protected]e6477f12014-08-05 07:59:54852 input.current_page_classification(),
Ryo Hashimoto884ad192014-08-28 05:54:30853 template_url_service_->search_terms_data(), client_.get()) &&
[email protected]9b9fa672013-11-07 06:04:52854 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
855 search_term_args.current_page_url = current_page_url_.spec();
856 // Create the suggest URL again with the current page URL.
857 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19858 search_term_args,
859 providers_.template_url_service()->search_terms_data()));
[email protected]9b9fa672013-11-07 06:04:52860 }
[email protected]9ff91722012-09-07 05:29:12861
[email protected]9ff91722012-09-07 05:29:12862 LogOmniboxSuggestRequest(REQUEST_SENT);
863
dtapuskadafcf892015-05-01 13:58:25864 scoped_ptr<net::URLFetcher> fetcher =
[email protected]9ff91722012-09-07 05:29:12865 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
Ryo Hashimoto884ad192014-08-28 05:54:30866 fetcher->SetRequestContext(client_->RequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34867 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30868 // Add Chrome experiment state to the request headers.
869 net::HttpRequestHeaders headers;
[email protected]71011c1682014-07-09 17:19:16870 variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
Ryo Hashimoto884ad192014-08-28 05:54:30871 fetcher->GetOriginalURL(), client_->IsOffTheRecord(), false, &headers);
[email protected]bd3b4712012-12-18 17:01:30872 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24873 fetcher->Start();
874 return fetcher;
875}
876
[email protected]344946a12012-12-20 12:03:42877void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29878 // Convert all the results to matches and add them to a map, so we can keep
879 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36880 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29881 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23882 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24883 int did_not_accept_keyword_suggestion =
884 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29885 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
886 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29887
[email protected]d30268a2013-06-25 22:31:07888 bool relevance_from_server;
889 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24890 int did_not_accept_default_suggestion =
891 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08892 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
893 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]7bc5e162014-08-15 19:41:11894 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]d1f0a7f2012-06-05 10:26:42895 if (verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44896 const base::string16& trimmed_verbatim =
897 base::CollapseWhitespace(input_.text(), false);
[email protected]716cd372014-08-15 18:56:03898
899 // Verbatim results don't get suggestions and hence, answers.
900 // Scan previous matches if the last answer-bearing suggestion matches
901 // verbatim, and if so, copy over answer contents.
902 base::string16 answer_contents;
903 base::string16 answer_type;
jdonnelly7393cee2014-10-31 01:52:56904 scoped_ptr<SuggestionAnswer> answer;
[email protected]716cd372014-08-15 18:56:03905 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
906 ++it) {
jdonnelly7393cee2014-10-31 01:52:56907 if (it->answer && it->fill_into_edit == trimmed_verbatim) {
[email protected]716cd372014-08-15 18:56:03908 answer_contents = it->answer_contents;
909 answer_type = it->answer_type;
jdonnelly7393cee2014-10-31 01:52:56910 answer = SuggestionAnswer::copy(it->answer.get());
[email protected]716cd372014-08-15 18:56:03911 break;
912 }
913 }
914
[email protected]0b9575f2014-07-30 11:58:37915 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44916 trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]716cd372014-08-15 18:56:03917 trimmed_verbatim, base::string16(), base::string16(), answer_contents,
jdonnelly7393cee2014-10-31 01:52:56918 answer_type, answer.Pass(), std::string(), std::string(), false,
919 verbatim_relevance, relevance_from_server, false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37920 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
[email protected]7bc5e162014-08-15 19:41:11921 false, keyword_url != NULL, &map);
[email protected]d1f0a7f2012-06-05 10:26:42922 }
[email protected]5423e562013-02-07 03:58:45923 if (!keyword_input_.text().empty()) {
[email protected]5423e562013-02-07 03:58:45924 // We only create the verbatim search query match for a keyword
925 // if it's not an extension keyword. Extension keywords are handled
926 // in KeywordProvider::Start(). (Extensions are complicated...)
927 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
928 // to the keyword verbatim search query. Do not create other matches
929 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:25930 if (keyword_url &&
931 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:07932 bool keyword_relevance_from_server;
933 const int keyword_verbatim_relevance =
934 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:28935 if (keyword_verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44936 const base::string16& trimmed_verbatim =
937 base::CollapseWhitespace(keyword_input_.text(), false);
[email protected]0b9575f2014-07-30 11:58:37938 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44939 trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
940 trimmed_verbatim, base::string16(), base::string16(),
jdonnelly7393cee2014-10-31 01:52:56941 base::string16(), base::string16(), nullptr, std::string(),
942 std::string(), true, keyword_verbatim_relevance,
943 keyword_relevance_from_server, false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37944 AddMatchToMap(verbatim, std::string(),
[email protected]7bc5e162014-08-15 19:41:11945 did_not_accept_keyword_suggestion, false, true, &map);
[email protected]dab8d52d2013-03-05 07:35:28946 }
[email protected]5423e562013-02-07 03:58:45947 }
948 }
grobye5fcee42014-09-26 03:36:46949 AddRawHistoryResultsToMap(true, did_not_accept_keyword_suggestion, &map);
950 AddRawHistoryResultsToMap(false, did_not_accept_default_suggestion, &map);
[email protected]257ab712009-04-14 17:16:24951
[email protected]d1cb6a822013-09-18 19:43:00952 AddSuggestResultsToMap(keyword_results_.suggest_results,
953 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:18954 AddSuggestResultsToMap(default_results_.suggest_results,
955 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:29956
[email protected]d30268a2013-06-25 22:31:07957 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:29958 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:07959 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:29960
[email protected]d30268a2013-06-25 22:31:07961 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
962 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:29963
[email protected]d30268a2013-06-25 22:31:07964 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
mpearson6c183672014-09-03 02:09:42965 // suggest/navsuggest matches, regardless of origin. We always include in
966 // that set a legal default match if possible. If Instant Extended is enabled
967 // and we have server-provided (and thus hopefully more accurate) scores for
968 // some suggestions, we allow more of those, until we reach
[email protected]d30268a2013-06-25 22:31:07969 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
970 // whole popup).
971 //
972 // We will always return any verbatim matches, no matter how we obtained their
973 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
974 // higher-scoring matches under the conditions above.
975 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
jdonnelly55f66142014-09-25 23:08:11976
mpearson6c183672014-09-03 02:09:42977 // Guarantee that if there's a legal default match anywhere in the result
978 // set that it'll get returned. The rotate() call does this by moving the
979 // default match to the front of the list.
980 ACMatches::iterator default_match = FindTopMatch(&matches);
981 if (default_match != matches.end())
982 std::rotate(matches.begin(), default_match, default_match + 1);
[email protected]3723e6e2012-06-11 21:06:56983
jdonnelly55f66142014-09-25 23:08:11984 // It's possible to get a copy of an answer from previous matches and get the
985 // same or a different answer to another server-provided suggestion. In the
986 // future we may decide that we want to have answers attached to multiple
987 // suggestions, but the current assumption is that there should only ever be
988 // one suggestion with an answer. To maintain this assumption, remove any
989 // answers after the first.
990 RemoveExtraAnswers(&matches);
991
992 matches_.clear();
[email protected]d30268a2013-06-25 22:31:07993 size_t num_suggestions = 0;
994 for (ACMatches::const_iterator i(matches.begin());
995 (i != matches.end()) &&
996 (matches_.size() < AutocompleteResult::kMaxMatches);
997 ++i) {
998 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
999 // verbatim result, so this condition basically means "if this match is a
1000 // suggestion of some sort".
1001 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
1002 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
1003 // If we've already hit the limit on non-server-scored suggestions, and
1004 // this isn't a server-scored suggestion we can add, skip it.
1005 if ((num_suggestions >= kMaxMatches) &&
1006 (!chrome::IsInstantExtendedAPIEnabled() ||
1007 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
1008 continue;
1009 }
1010
1011 ++num_suggestions;
1012 }
1013
1014 matches_.push_back(*i);
1015 }
[email protected]31afdf72013-09-26 04:29:361016 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
1017 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:421018}
1019
jdonnelly55f66142014-09-25 23:08:111020void SearchProvider::RemoveExtraAnswers(ACMatches* matches) {
1021 bool answer_seen = false;
1022 for (ACMatches::iterator it = matches->begin(); it != matches->end(); ++it) {
jdonnelly7393cee2014-10-31 01:52:561023 if (it->answer) {
jdonnelly55f66142014-09-25 23:08:111024 if (!answer_seen) {
1025 answer_seen = true;
1026 } else {
1027 it->answer_contents.clear();
1028 it->answer_type.clear();
jdonnelly7393cee2014-10-31 01:52:561029 it->answer.reset();
jdonnelly55f66142014-09-25 23:08:111030 }
1031 }
1032 }
1033}
1034
[email protected]89bd27d12014-04-12 17:36:231035ACMatches::const_iterator SearchProvider::FindTopMatch() const {
[email protected]0a8718b12013-11-13 18:41:311036 ACMatches::const_iterator it = matches_.begin();
1037 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
1038 ++it;
1039 return it;
[email protected]9dfb4d362013-04-05 02:15:121040}
1041
[email protected]89bd27d12014-04-12 17:36:231042bool SearchProvider::IsTopMatchSearchWithURLInput() const {
1043 ACMatches::const_iterator first_match = FindTopMatch();
[email protected]3dc75b12014-06-08 00:02:221044 return (input_.type() == metrics::OmniboxInputType::URL) &&
[email protected]0a8718b12013-11-13 18:41:311045 (first_match != matches_.end()) &&
1046 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
[email protected]78981d8c2014-05-09 15:05:471047 (first_match->type != AutocompleteMatchType::NAVSUGGEST) &&
1048 (first_match->type != AutocompleteMatchType::NAVSUGGEST_PERSONALIZED);
[email protected]344946a12012-12-20 12:03:421049}
1050
[email protected]257ab712009-04-14 17:16:241051void SearchProvider::AddNavigationResultsToMatches(
[email protected]0b9575f2014-07-30 11:58:371052 const SearchSuggestionParser::NavigationResults& navigation_results,
[email protected]d30268a2013-06-25 22:31:071053 ACMatches* matches) {
[email protected]0b9575f2014-07-30 11:58:371054 for (SearchSuggestionParser::NavigationResults::const_iterator it =
1055 navigation_results.begin(); it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:071056 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:231057 // In the absence of suggested relevance scores, use only the single
1058 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:071059 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:231060 return;
[email protected]257ab712009-04-14 17:16:241061 }
1062}
1063
grobye5fcee42014-09-26 03:36:461064void SearchProvider::AddRawHistoryResultsToMap(bool is_keyword,
1065 int did_not_accept_suggestion,
1066 MatchMap* map) {
1067 const HistoryResults& raw_results =
1068 is_keyword ? raw_keyword_history_results_ : raw_default_history_results_;
1069 if (!OmniboxFieldTrial::EnableAnswersInSuggest() && raw_results.empty())
[email protected]51124552011-07-16 01:37:101070 return;
1071
[email protected]31afdf72013-09-26 04:29:361072 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]51124552011-07-16 01:37:101073
grobye5fcee42014-09-26 03:36:461074 // Until Answers becomes default, scoring of history results will still happen
1075 // here for non-Answers Chrome, to prevent scoring performance regressions
1076 // resulting from moving the scoring code before the suggest request is sent.
1077 // For users with Answers enabled, the history results have already been
1078 // scored earlier, right after calling DoHistoryQuery().
1079 SearchSuggestionParser::SuggestResults local_transformed_results;
1080 const SearchSuggestionParser::SuggestResults* transformed_results = NULL;
1081 if (!OmniboxFieldTrial::EnableAnswersInSuggest()) {
1082 ScoreHistoryResults(raw_results, is_keyword, &local_transformed_results);
1083 transformed_results = &local_transformed_results;
1084 } else {
1085 transformed_results = is_keyword ? &transformed_keyword_history_results_
1086 : &transformed_default_history_results_;
[email protected]51124552011-07-16 01:37:101087 }
grobye5fcee42014-09-26 03:36:461088 DCHECK(transformed_results);
1089 AddTransformedHistoryResultsToMap(
1090 *transformed_results, did_not_accept_suggestion, map);
[email protected]31afdf72013-09-26 04:29:361091 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1092 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:101093}
1094
grobye5fcee42014-09-26 03:36:461095void SearchProvider::AddTransformedHistoryResultsToMap(
1096 const SearchSuggestionParser::SuggestResults& transformed_results,
1097 int did_not_accept_suggestion,
1098 MatchMap* map) {
1099 for (SearchSuggestionParser::SuggestResults::const_iterator i(
1100 transformed_results.begin());
1101 i != transformed_results.end();
1102 ++i) {
1103 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true,
1104 providers_.GetKeywordProviderURL() != NULL, map);
1105 }
1106}
1107
1108SearchSuggestionParser::SuggestResults
1109SearchProvider::ScoreHistoryResultsHelper(const HistoryResults& results,
1110 bool base_prevent_inline_autocomplete,
1111 bool input_multiple_words,
1112 const base::string16& input_text,
1113 bool is_keyword) {
[email protected]0b9575f2014-07-30 11:58:371114 SearchSuggestionParser::SuggestResults scored_results;
[email protected]ab5fd2f2014-07-17 19:18:521115 // True if the user has asked this exact query previously.
1116 bool found_what_you_typed_match = false;
[email protected]78e5e432013-08-03 02:10:101117 const bool prevent_search_history_inlining =
1118 OmniboxFieldTrial::SearchHistoryPreventInlining(
1119 input_.current_page_classification());
[email protected]c2ca3fd2014-03-22 03:07:441120 const base::string16& trimmed_input =
1121 base::CollapseWhitespace(input_text, false);
[email protected]257ab712009-04-14 17:16:241122 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1123 ++i) {
[email protected]c2ca3fd2014-03-22 03:07:441124 const base::string16& trimmed_suggestion =
1125 base::CollapseWhitespace(i->term, false);
1126
[email protected]51124552011-07-16 01:37:101127 // Don't autocomplete multi-word queries that have only been seen once
1128 // unless the user has typed more than one word.
1129 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
[email protected]c2ca3fd2014-03-22 03:07:441130 (!input_multiple_words && (i->visits < 2) &&
1131 HasMultipleWords(trimmed_suggestion));
[email protected]51124552011-07-16 01:37:101132
[email protected]78e5e432013-08-03 02:10:101133 int relevance = CalculateRelevanceForHistory(
1134 i->time, is_keyword, !prevent_inline_autocomplete,
1135 prevent_search_history_inlining);
[email protected]ab5fd2f2014-07-17 19:18:521136 // Add the match to |scored_results| by putting the what-you-typed match
1137 // on the front and appending all other matches. We want the what-you-
1138 // typed match to always be first.
[email protected]0b9575f2014-07-30 11:58:371139 SearchSuggestionParser::SuggestResults::iterator insertion_position =
1140 scored_results.end();
[email protected]ab5fd2f2014-07-17 19:18:521141 if (trimmed_suggestion == trimmed_input) {
1142 found_what_you_typed_match = true;
1143 insertion_position = scored_results.begin();
1144 }
mpearson6c183672014-09-03 02:09:421145 SearchSuggestionParser::SuggestResult history_suggestion(
1146 trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
1147 trimmed_suggestion, base::string16(), base::string16(),
jdonnelly7393cee2014-10-31 01:52:561148 base::string16(), base::string16(), nullptr, std::string(),
1149 std::string(), is_keyword, relevance, false, false, trimmed_input);
mpearson6c183672014-09-03 02:09:421150 // History results are synchronous; they are received on the last keystroke.
1151 history_suggestion.set_received_after_last_keystroke(false);
1152 scored_results.insert(insertion_position, history_suggestion);
[email protected]257ab712009-04-14 17:16:241153 }
[email protected]51124552011-07-16 01:37:101154
1155 // History returns results sorted for us. However, we may have docked some
[email protected]ab5fd2f2014-07-17 19:18:521156 // results' scores, so things are no longer in order. While keeping the
1157 // what-you-typed match at the front (if it exists), do a stable sort to get
[email protected]51124552011-07-16 01:37:101158 // things back in order without otherwise disturbing results with equal
1159 // scores, then force the scores to be unique, so that the order in which
1160 // they're shown is deterministic.
[email protected]ab5fd2f2014-07-17 19:18:521161 std::stable_sort(scored_results.begin() +
1162 (found_what_you_typed_match ? 1 : 0),
1163 scored_results.end(),
[email protected]55ce8f12012-05-09 04:44:081164 CompareScoredResults());
[email protected]7e3b77f2014-07-25 02:29:441165
1166 // Don't autocomplete to search terms that would normally be treated as URLs
1167 // when typed. For example, if the user searched for "google.com" and types
1168 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1169 // the input will look like a URL but act like a search, which is confusing.
1170 // The 1200 relevance score threshold in the test below is the lowest
1171 // possible score in CalculateRelevanceForHistory()'s aggressive-scoring
1172 // curve. This is an appropriate threshold to use to decide if we're overly
1173 // aggressively inlining because, if we decide the answer is yes, the
1174 // way we resolve it it to not use the aggressive-scoring curve.
1175 // NOTE: We don't check for autocompleting to URLs in the following cases:
1176 // * When inline autocomplete is disabled, we won't be inline autocompleting
1177 // this term, so we don't need to worry about confusion as much. This
1178 // also prevents calling Classify() again from inside the classifier
1179 // (which will corrupt state and likely crash), since the classifier
1180 // always disables inline autocomplete.
1181 // * When the user has typed the whole string before as a query, then it's
1182 // likely the user has no expectation that term should be interpreted as
1183 // as a URL, so we need not do anything special to preserve user
1184 // expectation.
[email protected]51124552011-07-16 01:37:101185 int last_relevance = 0;
[email protected]7e3b77f2014-07-25 02:29:441186 if (!base_prevent_inline_autocomplete && !found_what_you_typed_match &&
hashimoto663b9f42014-08-26 04:29:201187 scored_results.front().relevance() >= 1200) {
[email protected]7e3b77f2014-07-25 02:29:441188 AutocompleteMatch match;
Ryo Hashimoto884ad192014-08-28 05:54:301189 client_->Classify(scored_results.front().suggestion(), false, false,
1190 input_.current_page_classification(), &match, NULL);
[email protected]7e3b77f2014-07-25 02:29:441191 // Demote this match that would normally be interpreted as a URL to have
1192 // the highest score a previously-issued search query could have when
1193 // scoring with the non-aggressive method. A consequence of demoting
1194 // by revising |last_relevance| is that this match and all following
1195 // matches get demoted; the relative order of matches is preserved.
1196 // One could imagine demoting only those matches that might cause
1197 // confusion (which, by the way, might change the relative order of
1198 // matches. We have decided to go with the simple demote-all approach
1199 // because selective demotion requires multiple Classify() calls and
1200 // such calls can be expensive (as expensive as running the whole
1201 // autocomplete system).
1202 if (!AutocompleteMatch::IsSearchType(match.type)) {
1203 last_relevance = CalculateRelevanceForHistory(
1204 base::Time::Now(), is_keyword, false,
1205 prevent_search_history_inlining);
1206 }
1207 }
1208
[email protected]0b9575f2014-07-30 11:58:371209 for (SearchSuggestionParser::SuggestResults::iterator i(
1210 scored_results.begin()); i != scored_results.end(); ++i) {
[email protected]7e3b77f2014-07-25 02:29:441211 if ((last_relevance != 0) && (i->relevance() >= last_relevance))
[email protected]55ce8f12012-05-09 04:44:081212 i->set_relevance(last_relevance - 1);
1213 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101214 }
1215
[email protected]55ce8f12012-05-09 04:44:081216 return scored_results;
[email protected]257ab712009-04-14 17:16:241217}
1218
grobye5fcee42014-09-26 03:36:461219void SearchProvider::ScoreHistoryResults(
1220 const HistoryResults& results,
1221 bool is_keyword,
1222 SearchSuggestionParser::SuggestResults* scored_results) {
1223 DCHECK(scored_results);
jdonnellye5f055d92015-01-15 00:58:581224 scored_results->clear();
1225
grobye5fcee42014-09-26 03:36:461226 if (results.empty()) {
grobye5fcee42014-09-26 03:36:461227 return;
1228 }
1229
1230 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1231 (input_.type() == metrics::OmniboxInputType::URL);
1232 const base::string16 input_text = GetInput(is_keyword).text();
1233 bool input_multiple_words = HasMultipleWords(input_text);
1234
1235 if (!prevent_inline_autocomplete && input_multiple_words) {
1236 // ScoreHistoryResultsHelper() allows autocompletion of multi-word, 1-visit
1237 // queries if the input also has multiple words. But if we were already
1238 // scoring a multi-word, multi-visit query aggressively, and the current
1239 // input is still a prefix of it, then changing the suggestion suddenly
1240 // feels wrong. To detect this case, first score as if only one word has
1241 // been typed, then check if the best result came from aggressive search
1242 // history scoring. If it did, then just keep that score set. This
1243 // 1200 the lowest possible score in CalculateRelevanceForHistory()'s
1244 // aggressive-scoring curve.
1245 *scored_results = ScoreHistoryResultsHelper(
1246 results, prevent_inline_autocomplete, false, input_text, is_keyword);
1247 if ((scored_results->front().relevance() < 1200) ||
1248 !HasMultipleWords(scored_results->front().suggestion()))
1249 scored_results->clear(); // Didn't detect the case above, score normally.
1250 }
1251 if (scored_results->empty()) {
1252 *scored_results = ScoreHistoryResultsHelper(results,
1253 prevent_inline_autocomplete,
1254 input_multiple_words,
1255 input_text,
1256 is_keyword);
1257 }
1258}
1259
[email protected]0b9575f2014-07-30 11:58:371260void SearchProvider::AddSuggestResultsToMap(
1261 const SearchSuggestionParser::SuggestResults& results,
1262 const std::string& metadata,
1263 MatchMap* map) {
[email protected]7bc5e162014-08-15 19:41:111264 for (size_t i = 0; i < results.size(); ++i) {
1265 AddMatchToMap(results[i], metadata, i, false,
1266 providers_.GetKeywordProviderURL() != NULL, map);
1267 }
initial.commit09911bf2008-07-26 23:55:291268}
1269
[email protected]d30268a2013-06-25 22:31:071270int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561271 // Use the suggested verbatim relevance score if it is non-negative (valid),
1272 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281273 // and if it won't suppress verbatim, leaving no default provider matches.
1274 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561275 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281276 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561277 // Check for results on each verbatim calculation, as results from older
1278 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231279 bool use_server_relevance =
1280 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281281 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231282 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241283 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231284 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071285 if (relevance_from_server)
1286 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231287 return use_server_relevance ?
1288 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521289}
[email protected]d1f0a7f2012-06-05 10:26:421290
[email protected]382a0642012-06-06 06:13:521291int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471292 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361293 return 250;
[email protected]dab8d52d2013-03-05 07:35:281294 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1295}
[email protected]52d08b12009-10-19 18:42:361296
[email protected]dab8d52d2013-03-05 07:35:281297int SearchProvider::
1298 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291299 switch (input_.type()) {
[email protected]3dc75b12014-06-08 00:02:221300 case metrics::OmniboxInputType::UNKNOWN:
1301 case metrics::OmniboxInputType::QUERY:
1302 case metrics::OmniboxInputType::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131303 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291304
[email protected]3dc75b12014-06-08 00:02:221305 case metrics::OmniboxInputType::URL:
[email protected]52d08b12009-10-19 18:42:361306 return 850;
initial.commit09911bf2008-07-26 23:55:291307
1308 default:
1309 NOTREACHED();
1310 return 0;
1311 }
1312}
1313
[email protected]d30268a2013-06-25 22:31:071314int SearchProvider::GetKeywordVerbatimRelevance(
1315 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281316 // Use the suggested verbatim relevance score if it is non-negative (valid),
1317 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1318 // and if it won't suppress verbatim, leaving no keyword provider matches.
1319 // Otherwise, if the keyword provider returned no matches and was still able
1320 // to suppress verbatim, the user would have no search/nav matches and may be
1321 // left unable to search using their keyword provider from the omnibox.
1322 // Check for results on each verbatim calculation, as results from older
1323 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231324 bool use_server_relevance =
1325 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281326 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231327 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241328 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231329 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071330 if (relevance_from_server)
1331 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231332 return use_server_relevance ?
1333 keyword_results_.verbatim_relevance :
1334 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1335 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451336}
1337
[email protected]51124552011-07-16 01:37:101338int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231339 const base::Time& time,
[email protected]51124552011-07-16 01:37:101340 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101341 bool use_aggressive_method,
1342 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181343 // The relevance of past searches falls off over time. There are two distinct
1344 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101345 // provider that we want to score aggressively), the score is in the range
1346 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161347 // it's in the range 1200-1299). If the second equation is used the
1348 // relevance of a search 15 minutes ago is discounted 50 points, while the
1349 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231350 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421351 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101352 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181353 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101354 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181355 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161356 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101357 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161358 max_score = 1299;
1359 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181360 std::pow(elapsed_time / autocomplete_time, 2.5));
1361 }
1362 elapsed_time -= autocomplete_time;
1363 }
1364
[email protected]c3a4bd992010-08-18 20:25:011365 const int score_discount =
1366 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291367
[email protected]6c85aa02009-02-27 12:08:091368 // Don't let scores go below 0. Negative relevance scores are meaningful in
1369 // a different way.
initial.commit09911bf2008-07-26 23:55:291370 int base_score;
[email protected]51124552011-07-16 01:37:101371 if (is_primary_provider)
[email protected]3dc75b12014-06-08 00:02:221372 base_score = (input_.type() == metrics::OmniboxInputType::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101373 else
1374 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291375 return std::max(0, base_score - score_discount);
1376}
1377
initial.commit09911bf2008-07-26 23:55:291378AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]0b9575f2014-07-30 11:58:371379 const SearchSuggestionParser::NavigationResult& navigation) {
[email protected]5889bfb2014-03-19 00:26:481380 base::string16 input;
1381 const bool trimmed_whitespace = base::TrimWhitespace(
1382 navigation.from_keyword_provider() ?
1383 keyword_input_.text() : input_.text(),
1384 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
[email protected]55ce8f12012-05-09 04:44:081385 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]78981d8c2014-05-09 15:05:471386 navigation.type());
[email protected]55ce8f12012-05-09 04:44:081387 match.destination_url = navigation.url();
[email protected]78981d8c2014-05-09 15:05:471388 BaseSearchProvider::SetDeletionURL(navigation.deletion_url(), &match);
[email protected]23db6492014-01-16 02:35:301389 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551390 // without trimming the scheme, so we can find matches at the beginning of the
1391 // scheme.
[email protected]371dab12012-06-01 03:23:551392 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301393 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551394 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301395 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351396 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1397 (!prefix || (match_start != 0));
[email protected]23db6492014-01-16 02:35:301398 const net::FormatUrlTypes format_types =
1399 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551400
Ryo Hashimoto884ad192014-08-28 05:54:301401 const std::string languages(client_->AcceptLanguages());
[email protected]23db6492014-01-16 02:35:301402 size_t inline_autocomplete_offset = (prefix == NULL) ?
1403 base::string16::npos : (match_start + input.length());
[email protected]371dab12012-06-01 03:23:551404 match.fill_into_edit +=
[email protected]5655ea32014-06-21 05:28:081405 AutocompleteInput::FormattedStringWithEquivalentMeaning(
1406 navigation.url(),
[email protected]371dab12012-06-01 03:23:551407 net::FormatUrl(navigation.url(), languages, format_types,
1408 net::UnescapeRule::SPACES, NULL, NULL,
[email protected]5655ea32014-06-21 05:28:081409 &inline_autocomplete_offset),
Ryo Hashimoto884ad192014-08-28 05:54:301410 client_->SchemeClassifier());
[email protected]14119032013-11-07 08:14:261411 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1412 // Otherwise, user edits to a suggestion would show non-Search results.
[email protected]3dc75b12014-06-08 00:02:221413 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581414 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031415 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261416 ++inline_autocomplete_offset;
1417 }
[email protected]6c94a1022014-02-21 03:48:041418 if (inline_autocomplete_offset != base::string16::npos) {
[email protected]518024c2013-07-19 23:40:251419 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1420 match.inline_autocompletion =
1421 match.fill_into_edit.substr(inline_autocomplete_offset);
1422 }
[email protected]6c94a1022014-02-21 03:48:041423 // An inlineable navsuggestion can only be the default match when there
1424 // is no keyword provider active, lest it appear first and break the user
mpearson6c183672014-09-03 02:09:421425 // out of keyword mode. We also must have received the navsuggestion before
1426 // the last keystroke, to prevent asynchronous inline autocompletions changes.
1427 // The navsuggestion can also only be default if either the inline
[email protected]5889bfb2014-03-19 00:26:481428 // autocompletion is empty or we're not preventing inline autocompletion.
1429 // Finally, if we have an inlineable navsuggestion with an inline completion
1430 // that we're not preventing, make sure we didn't trim any whitespace.
1431 // We don't want to claim http://foo.com/bar is inlineable against the
1432 // input "foo.com/b ".
mpearson6c183672014-09-03 02:09:421433 match.allowed_to_be_default_match =
1434 (prefix != NULL) &&
[email protected]6c94a1022014-02-21 03:48:041435 (providers_.GetKeywordProviderURL() == NULL) &&
mpearson6c183672014-09-03 02:09:421436 !navigation.received_after_last_keystroke() &&
[email protected]5889bfb2014-03-19 00:26:481437 (match.inline_autocompletion.empty() ||
[email protected]78981d8c2014-05-09 15:05:471438 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
[email protected]c7b8be02014-07-11 19:46:341439 match.EnsureUWYTIsAllowedToBeDefault(
1440 input_.canonicalized_url(), providers_.template_url_service());
[email protected]371dab12012-06-01 03:23:551441
[email protected]23db6492014-01-16 02:35:301442 match.contents = navigation.match_contents();
1443 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081444 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551445 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1446 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071447
1448 match.RecordAdditionalInfo(
1449 kRelevanceFromServerKey,
1450 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181451 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071452
initial.commit09911bf2008-07-26 23:55:291453 return match;
1454}
[email protected]4ab4c7c2010-11-24 04:49:341455
1456void SearchProvider::UpdateDone() {
mpearson84f19a152015-03-12 19:42:211457 // We're done when the timer isn't running and there are no suggest queries
1458 // pending.
1459 done_ = !timer_.IsRunning() && !default_fetcher_ && !keyword_fetcher_;
[email protected]4ab4c7c2010-11-24 04:49:341460}
[email protected]20184242014-05-14 02:57:421461
1462std::string SearchProvider::GetSessionToken() {
1463 base::TimeTicks current_time(base::TimeTicks::Now());
1464 // Renew token if it expired.
1465 if (current_time > token_expiration_time_) {
1466 const size_t kTokenBytes = 12;
1467 std::string raw_data;
1468 base::RandBytes(WriteInto(&raw_data, kTokenBytes + 1), kTokenBytes);
1469 base::Base64Encode(raw_data, &current_token_);
[email protected]ab2c31f72014-05-17 17:03:531470
1471 // Make the base64 encoded value URL and filename safe(see RFC 3548).
1472 std::replace(current_token_.begin(), current_token_.end(), '+', '-');
1473 std::replace(current_token_.begin(), current_token_.end(), '/', '_');
[email protected]20184242014-05-14 02:57:421474 }
1475
1476 // Extend expiration time another 60 seconds.
1477 token_expiration_time_ = current_time + base::TimeDelta::FromSeconds(60);
1478
1479 return current_token_;
1480}
[email protected]2ef2a6642014-07-30 05:50:291481
1482void SearchProvider::RegisterDisplayedAnswers(
1483 const AutocompleteResult& result) {
1484 if (result.empty())
1485 return;
1486
1487 // The answer must be in the first or second slot to be considered. It should
1488 // only be in the second slot if AutocompleteController ranked a local search
1489 // history or a verbatim item higher than the answer.
1490 AutocompleteResult::const_iterator match = result.begin();
1491 if (match->answer_contents.empty() && result.size() > 1)
1492 ++match;
1493 if (match->answer_contents.empty() || match->answer_type.empty() ||
1494 match->fill_into_edit.empty())
1495 return;
1496
1497 // Valid answer encountered, cache it for further queries.
[email protected]ebbac63e2014-08-22 01:43:061498 answers_cache_.UpdateRecentAnswers(match->fill_into_edit, match->answer_type);
[email protected]2ef2a6642014-07-30 05:50:291499}
1500
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}