blob: dca916af65b59ad6d826273a8ba9d026d04e9812 [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"
[email protected]2041cf342010-02-19 03:15:5911#include "base/callback.h"
[email protected]51124552011-07-16 01:37:1012#include "base/i18n/break_iterator.h"
[email protected]503d03872011-05-06 08:36:2613#include "base/i18n/case_conversion.h"
[email protected]ffbec692012-02-26 20:26:4214#include "base/json/json_string_value_serializer.h"
[email protected]f5b95ba92012-03-27 14:05:1915#include "base/metrics/histogram.h"
[email protected]f7f41c0e2014-08-11 04:22:2316#include "base/metrics/user_metrics.h"
[email protected]20184242014-05-14 02:57:4217#include "base/rand_util.h"
[email protected]5889bfb2014-03-19 00:26:4818#include "base/strings/string_util.h"
[email protected]135cb802013-06-09 16:44:2019#include "base/strings/utf_string_conversions.h"
[email protected]e3ce70ac2014-06-26 18:34:5620#include "components/history/core/browser/in_memory_database.h"
[email protected]73b2d1e72014-06-25 23:45:3621#include "components/history/core/browser/keyword_search_term.h"
[email protected]3dc75b12014-06-08 00:02:2222#include "components/metrics/proto/omnibox_input_type.pb.h"
Ryo Hashimoto884ad192014-08-28 05:54:3023#include "components/omnibox/autocomplete_provider_client.h"
[email protected]b1c5ab682014-08-07 11:53:1724#include "components/omnibox/autocomplete_provider_listener.h"
[email protected]4b56c602014-08-14 17:02:3125#include "components/omnibox/autocomplete_result.h"
[email protected]02f5e32d2014-08-22 07:44:4626#include "components/omnibox/keyword_provider.h"
[email protected]4c583b62014-08-08 10:37:2327#include "components/omnibox/omnibox_field_trial.h"
[email protected]b1c5ab682014-08-07 11:53:1728#include "components/omnibox/url_prefix.h"
[email protected]720b10492014-07-23 08:48:4029#include "components/search/search.h"
[email protected]0915b352014-06-25 19:58:1430#include "components/search_engines/template_url_prepopulate_data.h"
[email protected]bf5c532d2014-07-05 00:29:5331#include "components/search_engines/template_url_service.h"
[email protected]71011c1682014-07-09 17:19:1632#include "components/variations/variations_http_header_provider.h"
[email protected]53f0cab2014-08-18 09:52:2733#include "grit/components_strings.h"
initial.commit09911bf2008-07-26 23:55:2934#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3435#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5536#include "net/base/net_util.h"
[email protected]bd3b4712012-12-18 17:01:3037#include "net/http/http_request_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5338#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2139#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1740#include "ui/base/l10n/l10n_util.h"
[email protected]cca6f392014-05-28 21:32:2641#include "url/url_constants.h"
[email protected]761fa4702013-07-02 15:25:1542#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2943
[email protected]bc8bb0cd2013-06-24 21:50:2344// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3345
[email protected]51124552011-07-16 01:37:1046namespace {
47
[email protected]7706a522012-08-16 17:42:2548// We keep track in a histogram how many suggest requests we send, how
49// many suggest requests we invalidate (e.g., due to a user typing
50// another character), and how many replies we receive.
51// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
52// (excluding the end-of-list enum value)
53// We do not want values of existing enums to change or else it screws
54// up the statistics.
55enum SuggestRequestsHistogramValue {
56 REQUEST_SENT = 1,
57 REQUEST_INVALIDATED,
58 REPLY_RECEIVED,
59 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
60};
61
[email protected]90fe2bb2013-01-15 03:42:1362// The verbatim score for an input which is not an URL.
63const int kNonURLVerbatimRelevance = 1300;
64
[email protected]7706a522012-08-16 17:42:2565// Increments the appropriate value in the histogram by one.
66void LogOmniboxSuggestRequest(
67 SuggestRequestsHistogramValue request_value) {
68 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
69 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
70}
71
[email protected]0085863a2013-12-06 21:19:0372bool HasMultipleWords(const base::string16& text) {
[email protected]51124552011-07-16 01:37:1073 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
74 bool found_word = false;
75 if (i.Init()) {
76 while (i.Advance()) {
77 if (i.IsWord()) {
78 if (found_word)
79 return true;
80 found_word = true;
81 }
82 }
83 }
84 return false;
85}
86
[email protected]d1f0a7f2012-06-05 10:26:4287} // namespace
[email protected]51124552011-07-16 01:37:1088
[email protected]3954c3a2012-04-10 20:17:5589// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:5890
[email protected]85b8d6f2012-05-08 20:53:4791SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
[email protected]02346202014-02-05 05:18:3092 : template_url_service_(template_url_service) {}
[email protected]85b8d6f2012-05-08 20:53:4793
94const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
95 return default_provider_.empty() ? NULL :
96 template_url_service_->GetTemplateURLForKeyword(default_provider_);
97}
98
99const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
100 return keyword_provider_.empty() ? NULL :
101 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24102}
103
[email protected]3954c3a2012-04-10 20:17:55104
[email protected]bc8bb0cd2013-06-24 21:50:23105// SearchProvider::CompareScoredResults ---------------------------------------
106
107class SearchProvider::CompareScoredResults {
108 public:
[email protected]0b9575f2014-07-30 11:58:37109 bool operator()(const SearchSuggestionParser::Result& a,
110 const SearchSuggestionParser::Result& b) {
[email protected]bc8bb0cd2013-06-24 21:50:23111 // Sort in descending relevance order.
112 return a.relevance() > b.relevance();
113 }
114};
115
116
[email protected]3954c3a2012-04-10 20:17:55117// SearchProvider -------------------------------------------------------------
118
119// static
[email protected]24dbf2302013-04-05 16:59:25120int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]3954c3a2012-04-10 20:17:55121
hashimoto663b9f42014-08-26 04:29:20122SearchProvider::SearchProvider(
123 AutocompleteProviderListener* listener,
124 TemplateURLService* template_url_service,
Ryo Hashimoto884ad192014-08-28 05:54:30125 scoped_ptr<AutocompleteProviderClient> client)
126 : BaseSearchProvider(template_url_service, client.Pass(),
[email protected]e6477f12014-08-05 07:59:54127 AutocompleteProvider::TYPE_SEARCH),
[email protected]776ee5902014-08-11 09:15:19128 listener_(listener),
129 suggest_results_pending_(0),
[email protected]ebbac63e2014-08-22 01:43:06130 providers_(template_url_service),
groby1dbb8e22014-09-23 21:50:26131 answers_cache_(10) {
[email protected]bc8bb0cd2013-06-24 21:50:23132}
133
[email protected]cb86ee6f2013-04-28 16:58:15134// static
[email protected]987fad782013-08-28 06:23:18135std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
136 return match.GetAdditionalInfo(kSuggestMetadataKey);
137}
138
[email protected]bc8bb0cd2013-06-24 21:50:23139void SearchProvider::ResetSession() {
140 field_trial_triggered_in_session_ = false;
[email protected]4ab4c7c2010-11-24 04:49:34141}
142
[email protected]bc8bb0cd2013-06-24 21:50:23143SearchProvider::~SearchProvider() {
144}
145
[email protected]ee6110b2014-01-09 22:26:31146// static
[email protected]bc8bb0cd2013-06-24 21:50:23147int SearchProvider::CalculateRelevanceForKeywordVerbatim(
[email protected]332d17d22014-06-20 16:56:03148 metrics::OmniboxInputType::Type type,
[email protected]bc8bb0cd2013-06-24 21:50:23149 bool prefer_keyword) {
150 // This function is responsible for scoring verbatim query matches
151 // for non-extension keywords. KeywordProvider::CalculateRelevance()
152 // scores verbatim query matches for extension keywords, as well as
153 // for keyword matches (i.e., suggestions of a keyword itself, not a
154 // suggestion of a query on a keyword search engine). These two
155 // functions are currently in sync, but there's no reason we
156 // couldn't decide in the future to score verbatim matches
157 // differently for extension and non-extension keywords. If you
158 // make such a change, however, you should update this comment to
159 // describe it, so it's clear why the functions diverge.
160 if (prefer_keyword)
161 return 1500;
[email protected]3dc75b12014-06-08 00:02:22162 return (type == metrics::OmniboxInputType::QUERY) ? 1450 : 1100;
[email protected]bc8bb0cd2013-06-24 21:50:23163}
164
mpearson6c183672014-09-03 02:09:42165// static
166void SearchProvider::UpdateOldResults(
167 bool minimal_changes,
168 SearchSuggestionParser::Results* results) {
169 // When called without |minimal_changes|, it likely means the user has
170 // pressed a key. Revise the cached results appropriately.
171 if (!minimal_changes) {
172 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
173 results->suggest_results.begin();
174 sug_it != results->suggest_results.end(); ++sug_it) {
175 sug_it->set_received_after_last_keystroke(false);
176 }
177 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
178 results->navigation_results.begin();
179 nav_it != results->navigation_results.end(); ++nav_it) {
180 nav_it->set_received_after_last_keystroke(false);
181 }
182 }
183}
184
185// static
186ACMatches::iterator SearchProvider::FindTopMatch(ACMatches* matches) {
187 ACMatches::iterator it = matches->begin();
188 while ((it != matches->end()) && !it->allowed_to_be_default_match)
189 ++it;
190 return it;
191}
192
initial.commit09911bf2008-07-26 23:55:29193void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27194 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55195 // Do our best to load the model as early as possible. This will reduce
196 // odds of having the model not ready when really needed (a non-empty input).
197 TemplateURLService* model = providers_.template_url_service();
198 DCHECK(model);
199 model->Load();
200
initial.commit09911bf2008-07-26 23:55:29201 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57202 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29203
hashimoto663b9f42014-08-26 04:29:20204 // Can't return search/suggest results for bogus input.
205 if (input.type() == metrics::OmniboxInputType::INVALID) {
[email protected]9950e5d52014-02-25 23:34:19206 Stop(true);
initial.commit09911bf2008-07-26 23:55:29207 return;
208 }
209
[email protected]14710852013-02-05 23:45:41210 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24211 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41212 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
213 &keyword_input_);
214 if (keyword_provider == NULL)
215 keyword_input_.Clear();
216 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24217 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24218
[email protected]85b8d6f2012-05-08 20:53:47219 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]ce7ee5f2014-06-16 23:41:19220 if (default_provider &&
221 !default_provider->SupportsReplacement(model->search_terms_data()))
[email protected]257ab712009-04-14 17:16:24222 default_provider = NULL;
223
224 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18225 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24226
227 if (!default_provider && !keyword_provider) {
228 // No valid providers.
[email protected]9950e5d52014-02-25 23:34:19229 Stop(true);
initial.commit09911bf2008-07-26 23:55:29230 return;
231 }
232
233 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24234 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03235 base::string16 default_provider_keyword(default_provider ?
236 default_provider->keyword() : base::string16());
237 base::string16 keyword_provider_keyword(keyword_provider ?
238 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32239 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47240 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29241 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15242 if (!done_)
[email protected]e29249dc52012-07-19 17:33:50243 Stop(false);
[email protected]257ab712009-04-14 17:16:24244 }
initial.commit09911bf2008-07-26 23:55:29245
[email protected]85b8d6f2012-05-08 20:53:47246 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29247
248 if (input.text().empty()) {
249 // User typed "?" alone. Give them a placeholder result indicating what
250 // this syntax does.
[email protected]257ab712009-04-14 17:16:24251 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00252 AutocompleteMatch match;
253 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36254 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24255 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35256 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47257 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36258 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24259 matches_.push_back(match);
260 }
[email protected]9950e5d52014-02-25 23:34:19261 Stop(true);
initial.commit09911bf2008-07-26 23:55:29262 return;
263 }
264
265 input_ = input;
266
[email protected]e1290ee62013-06-26 18:31:15267 DoHistoryQuery(minimal_changes);
[email protected]2ef2a6642014-07-30 05:50:29268 DoAnswersQuery(input);
[email protected]e1290ee62013-06-26 18:31:15269 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42270 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29271}
272
[email protected]ec3f679b2014-08-18 07:45:13273void SearchProvider::Stop(bool clear_cached_results) {
274 StopSuggest();
275 done_ = true;
276
277 if (clear_cached_results)
278 ClearAllResults();
279}
280
[email protected]776ee5902014-08-11 09:15:19281const TemplateURL* SearchProvider::GetTemplateURL(bool is_keyword) const {
282 return is_keyword ? providers_.GetKeywordProviderURL()
283 : providers_.GetDefaultProviderURL();
284}
285
286const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
287 return is_keyword ? keyword_input_ : input_;
288}
289
290bool SearchProvider::ShouldAppendExtraParams(
291 const SearchSuggestionParser::SuggestResult& result) const {
292 return !result.from_keyword_provider() ||
293 providers_.default_provider().empty();
294}
295
[email protected]776ee5902014-08-11 09:15:19296void SearchProvider::RecordDeletionResult(bool success) {
297 if (success) {
298 base::RecordAction(
299 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
300 } else {
301 base::RecordAction(
302 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
303 }
304}
305
306void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
307 DCHECK(!done_);
308 --suggest_results_pending_;
309 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
310
311 const bool is_keyword = source == keyword_fetcher_.get();
312
313 // Ensure the request succeeded and that the provider used is still available.
314 // A verbatim match cannot be generated without this provider, causing errors.
315 const bool request_succeeded =
316 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
317 GetTemplateURL(is_keyword);
318
319 LogFetchComplete(request_succeeded, is_keyword);
320
321 bool results_updated = false;
322 if (request_succeeded) {
323 scoped_ptr<base::Value> data(SearchSuggestionParser::DeserializeJsonData(
324 SearchSuggestionParser::ExtractJsonData(source)));
325 if (data) {
326 SearchSuggestionParser::Results* results =
327 is_keyword ? &keyword_results_ : &default_results_;
328 results_updated = ParseSuggestResults(*data, -1, is_keyword, results);
329 if (results_updated)
330 SortResults(is_keyword, results);
331 }
332 }
333 UpdateMatches();
334 if (done_ || results_updated)
335 listener_->OnProviderUpdate(results_updated);
336}
337
[email protected]ec3f679b2014-08-18 07:45:13338void SearchProvider::StopSuggest() {
339 // Increment the appropriate field in the histogram by the number of
340 // pending requests that were invalidated.
341 for (int i = 0; i < suggest_results_pending_; ++i)
342 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
343 suggest_results_pending_ = 0;
344 timer_.Stop();
345 // Stop any in-progress URL fetches.
346 keyword_fetcher_.reset();
347 default_fetcher_.reset();
348}
349
350void SearchProvider::ClearAllResults() {
351 keyword_results_.Clear();
352 default_results_.Clear();
353}
354
[email protected]776ee5902014-08-11 09:15:19355void SearchProvider::UpdateMatchContentsClass(
356 const base::string16& input_text,
357 SearchSuggestionParser::Results* results) {
358 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
359 results->suggest_results.begin();
360 sug_it != results->suggest_results.end(); ++sug_it) {
361 sug_it->ClassifyMatchContents(false, input_text);
362 }
Ryo Hashimoto884ad192014-08-28 05:54:30363 const std::string languages(client_->AcceptLanguages());
[email protected]776ee5902014-08-11 09:15:19364 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
365 results->navigation_results.begin();
366 nav_it != results->navigation_results.end(); ++nav_it) {
367 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
368 }
369}
370
[email protected]d4a94b92014-03-04 01:35:22371void SearchProvider::SortResults(bool is_keyword,
[email protected]0b9575f2014-07-30 11:58:37372 SearchSuggestionParser::Results* results) {
[email protected]d4a94b92014-03-04 01:35:22373 // Ignore suggested scores for non-keyword matches in keyword mode; if the
374 // server is allowed to score these, it could interfere with the user's
375 // ability to get good keyword results.
376 const bool abandon_suggested_scores =
377 !is_keyword && !providers_.keyword_provider().empty();
[email protected]0b9575f2014-07-30 11:58:37378 // Apply calculated relevance scores to suggestions if valid relevances were
[email protected]d4a94b92014-03-04 01:35:22379 // not provided or we're abandoning suggested scores entirely.
[email protected]2c802d12014-07-31 12:57:14380 if (!results->relevances_from_server || abandon_suggested_scores) {
[email protected]d4a94b92014-03-04 01:35:22381 ApplyCalculatedSuggestRelevance(&results->suggest_results);
382 ApplyCalculatedNavigationRelevance(&results->navigation_results);
383 // If abandoning scores entirely, also abandon the verbatim score.
384 if (abandon_suggested_scores)
385 results->verbatim_relevance = -1;
386 }
387
388 // Keep the result lists sorted.
389 const CompareScoredResults comparator = CompareScoredResults();
390 std::stable_sort(results->suggest_results.begin(),
391 results->suggest_results.end(),
392 comparator);
393 std::stable_sort(results->navigation_results.begin(),
394 results->navigation_results.end(),
395 comparator);
396}
397
[email protected]cfa164bf2014-03-19 11:51:15398void SearchProvider::LogFetchComplete(bool success, bool is_keyword) {
399 LogOmniboxSuggestRequest(REPLY_RECEIVED);
400 // Record response time for suggest requests sent to Google. We care
401 // only about the common case: the Google default provider used in
402 // non-keyword mode.
403 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
404 if (!is_keyword && default_url &&
[email protected]ce7ee5f2014-06-16 23:41:19405 (TemplateURLPrepopulateData::GetEngineType(
406 *default_url,
407 providers_.template_url_service()->search_terms_data()) ==
[email protected]cfa164bf2014-03-19 11:51:15408 SEARCH_ENGINE_GOOGLE)) {
409 const base::TimeDelta elapsed_time =
410 base::TimeTicks::Now() - time_suggest_request_sent_;
411 if (success) {
412 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
413 elapsed_time);
414 } else {
415 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
416 elapsed_time);
417 }
418 }
419}
420
[email protected]cfa164bf2014-03-19 11:51:15421void SearchProvider::UpdateMatches() {
mpearson6c183672014-09-03 02:09:42422 PersistTopSuggestions(&default_results_);
423 PersistTopSuggestions(&keyword_results_);
[email protected]cfa164bf2014-03-19 11:51:15424 ConvertResultsToAutocompleteMatches();
425
426 // Check constraints that may be violated by suggested relevances.
427 if (!matches_.empty() &&
428 (default_results_.HasServerProvidedScores() ||
429 keyword_results_.HasServerProvidedScores())) {
430 // These blocks attempt to repair undesirable behavior by suggested
431 // relevances with minimal impact, preserving other suggested relevances.
432
[email protected]d0e4ad02014-08-22 18:58:33433 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
434 const bool is_extension_keyword = (keyword_url != NULL) &&
435 (keyword_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION);
436 if ((keyword_url != NULL) && !is_extension_keyword &&
[email protected]7bc5e162014-08-15 19:41:11437 (FindTopMatch() == matches_.end())) {
[email protected]d0e4ad02014-08-22 18:58:33438 // In non-extension keyword mode, disregard the keyword verbatim suggested
439 // relevance if necessary, so at least one match is allowed to be default.
440 // (In extension keyword mode this is not necessary because the extension
mpearson6c183672014-09-03 02:09:42441 // will return a default match.) Give keyword verbatim the lowest
442 // non-zero score to best reflect what the server desired.
443 DCHECK_EQ(0, keyword_results_.verbatim_relevance);
444 keyword_results_.verbatim_relevance = 1;
[email protected]cfa164bf2014-03-19 11:51:15445 ConvertResultsToAutocompleteMatches();
446 }
[email protected]89bd27d12014-04-12 17:36:23447 if (IsTopMatchSearchWithURLInput()) {
[email protected]cfa164bf2014-03-19 11:51:15448 // Disregard the suggested search and verbatim relevances if the input
449 // type is URL and the top match is a highly-ranked search suggestion.
450 // For example, prevent a search for "foo.com" from outranking another
451 // provider's navigation for "foo.com" or "foo.com/url_from_history".
452 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
453 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
454 default_results_.verbatim_relevance = -1;
455 keyword_results_.verbatim_relevance = -1;
456 ConvertResultsToAutocompleteMatches();
457 }
[email protected]d0e4ad02014-08-22 18:58:33458 if (!is_extension_keyword && (FindTopMatch() == matches_.end())) {
459 // Guarantee that SearchProvider returns a legal default match (except
460 // when in extension-based keyword mode). The omnibox always needs at
461 // least one legal default match, and it relies on SearchProvider in
462 // combination with KeywordProvider (for extension-based keywords) to
mpearson6c183672014-09-03 02:09:42463 // always return one. Give the verbatim suggestion the lowest non-zero
464 // scores to best reflect what the server desired.
465 DCHECK_EQ(0, default_results_.verbatim_relevance);
466 default_results_.verbatim_relevance = 1;
467 // We do not have to alter keyword_results_.verbatim_relevance here.
468 // If the user is in keyword mode, we already reverted (earlier in this
469 // function) the instructions to suppress keyword verbatim.
[email protected]cfa164bf2014-03-19 11:51:15470 ConvertResultsToAutocompleteMatches();
471 }
[email protected]89bd27d12014-04-12 17:36:23472 DCHECK(!IsTopMatchSearchWithURLInput());
[email protected]d0e4ad02014-08-22 18:58:33473 DCHECK(is_extension_keyword || (FindTopMatch() != matches_.end()));
[email protected]cfa164bf2014-03-19 11:51:15474 }
475 UMA_HISTOGRAM_CUSTOM_COUNTS(
476 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
mpearson6c183672014-09-03 02:09:42477
478 // Record the top suggestion (if any) for future use.
479 top_query_suggestion_match_contents_ = base::string16();
480 top_navigation_suggestion_ = GURL();
481 ACMatches::const_iterator first_match = FindTopMatch();
482 if ((first_match != matches_.end()) &&
483 !first_match->inline_autocompletion.empty()) {
484 // Identify if this match came from a query suggestion or a navsuggestion.
485 // In either case, extracts the identifying feature of the suggestion
486 // (query string or navigation url).
487 if (AutocompleteMatch::IsSearchType(first_match->type))
488 top_query_suggestion_match_contents_ = first_match->contents;
489 else
490 top_navigation_suggestion_ = first_match->destination_url;
491 }
492
[email protected]cfa164bf2014-03-19 11:51:15493 UpdateDone();
[email protected]cfa164bf2014-03-19 11:51:15494}
495
[email protected]bc8bb0cd2013-06-24 21:50:23496void SearchProvider::Run() {
497 // Start a new request with the current input.
498 suggest_results_pending_ = 0;
499 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05500
[email protected]bc8bb0cd2013-06-24 21:50:23501 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
502 providers_.GetDefaultProviderURL(), input_));
503 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
504 providers_.GetKeywordProviderURL(), keyword_input_));
505
506 // Both the above can fail if the providers have been modified or deleted
507 // since the query began.
508 if (suggest_results_pending_ == 0) {
509 UpdateDone();
510 // We only need to update the listener if we're actually done.
511 if (done_)
512 listener_->OnProviderUpdate(false);
513 }
[email protected]601858c02010-09-01 17:08:20514}
515
[email protected]8d457132010-11-04 18:13:40516void SearchProvider::DoHistoryQuery(bool minimal_changes) {
517 // The history query results are synchronous, so if minimal_changes is true,
518 // we still have the last results and don't need to do anything.
519 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29520 return;
521
[email protected]8d457132010-11-04 18:13:40522 keyword_history_results_.clear();
523 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29524
[email protected]78e5e432013-08-03 02:10:10525 if (OmniboxFieldTrial::SearchHistoryDisable(
526 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16527 return;
528
Ryo Hashimoto884ad192014-08-28 05:54:30529 history::URLDatabase* url_db = client_->InMemoryDatabase();
[email protected]8d457132010-11-04 18:13:40530 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29531 return;
532
[email protected]51124552011-07-16 01:37:10533 // Request history for both the keyword and default provider. We grab many
534 // more matches than we'll ultimately clamp to so that if there are several
535 // recent multi-word matches who scores are lowered (see
536 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
537 // matches. Note that this doesn't fix the problem entirely, but merely
538 // limits it to cases with a very large number of such multi-word matches; for
539 // now, this seems OK compared with the complexity of a real fix, which would
540 // require multiple searches and tracking of "single- vs. multi-word" in the
541 // database.
542 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47543 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
544 if (default_url) {
[email protected]b4bec972014-04-05 18:07:15545 const base::TimeTicks start_time = base::TimeTicks::Now();
[email protected]85b8d6f2012-05-08 20:53:47546 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
547 num_matches, &default_history_results_);
[email protected]31afdf72013-09-26 04:29:36548 UMA_HISTOGRAM_TIMES(
549 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
550 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24551 }
[email protected]85b8d6f2012-05-08 20:53:47552 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
553 if (keyword_url) {
554 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41555 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55556 }
initial.commit09911bf2008-07-26 23:55:29557}
558
[email protected]6dc950f2012-07-16 19:49:08559void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34560 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29561 StopSuggest();
[email protected]71b46152013-05-03 16:39:20562 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29563 return;
564 }
565
566 // For the minimal_changes case, if we finished the previous query and still
567 // have its results, or are allowed to keep running it, just do that, rather
568 // than starting a new query.
569 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24570 (!default_results_.suggest_results.empty() ||
571 !default_results_.navigation_results.empty() ||
572 !keyword_results_.suggest_results.empty() ||
573 !keyword_results_.navigation_results.empty() ||
[email protected]a2770a7d2014-04-22 19:33:35574 (!done_ && input_.want_asynchronous_matches())))
initial.commit09911bf2008-07-26 23:55:29575 return;
576
577 // We can't keep running any previous query, so halt it.
578 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42579
mpearson6c183672014-09-03 02:09:42580 UpdateAllOldResults(minimal_changes);
initial.commit09911bf2008-07-26 23:55:29581
[email protected]ee6110b2014-01-09 22:26:31582 // Update the content classifications of remaining results so they look good
583 // against the current input.
[email protected]23db6492014-01-16 02:35:30584 UpdateMatchContentsClass(input_.text(), &default_results_);
585 if (!keyword_input_.text().empty())
586 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31587
initial.commit09911bf2008-07-26 23:55:29588 // We can't start a new query if we're only allowed synchronous results.
[email protected]a2770a7d2014-04-22 19:33:35589 if (!input_.want_asynchronous_matches())
initial.commit09911bf2008-07-26 23:55:29590 return;
591
[email protected]24dbf2302013-04-05 16:59:25592 // To avoid flooding the suggest server, don't send a query until at
593 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24594 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
[email protected]bc8bb0cd2013-06-24 21:50:23595 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
[email protected]515ffa942012-11-27 20:18:24596 base::TimeTicks now(base::TimeTicks::Now());
597 if (now >= next_suggest_time) {
598 Run();
599 return;
600 }
601 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29602}
603
[email protected]83c726482008-09-10 06:36:34604bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55605 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
606 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47607 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
608 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
Ryo Hashimoto884ad192014-08-28 05:54:30609 if (client_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47610 ((!default_url || default_url->suggestions_url().empty()) &&
611 (!keyword_url || keyword_url->suggestions_url().empty())) ||
Ryo Hashimoto884ad192014-08-28 05:54:30612 !client_->SearchSuggestEnabled())
[email protected]83c726482008-09-10 06:36:34613 return false;
614
[email protected]cac59d32010-08-09 23:23:14615 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34616 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34617
[email protected]cac59d32010-08-09 23:23:14618 // FORCED_QUERY means the user is explicitly asking us to search for this, so
619 // we assume it isn't a URL and/or there isn't private data.
[email protected]3dc75b12014-06-08 00:02:22620 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY)
[email protected]cac59d32010-08-09 23:23:14621 return true;
[email protected]83c726482008-09-10 06:36:34622
[email protected]f608ea102013-03-18 15:08:09623 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
624 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
625 // is both a waste of time and a disclosure of potentially private, local
626 // data. Other "schemes" may actually be usernames, and we don't want to send
627 // passwords. If the scheme is OK, we still need to check other cases below.
628 // If this is QUERY, then the presence of these schemes means the user
629 // explicitly typed one, and thus this is probably a URL that's being entered
630 // and happens to currently be invalid -- in which case we again want to run
631 // our checks below. Other QUERY cases are less likely to be URLs and thus we
632 // assume we're OK.
[email protected]df807042014-08-13 16:48:41633 if (!LowerCaseEqualsASCII(input_.scheme(), url::kHttpScheme) &&
634 !LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
635 !LowerCaseEqualsASCII(input_.scheme(), url::kFtpScheme))
[email protected]3dc75b12014-06-08 00:02:22636 return (input_.type() == metrics::OmniboxInputType::QUERY);
[email protected]cac59d32010-08-09 23:23:14637
638 // Don't send URLs with usernames, queries or refs. Some of these are
639 // private, and the Suggest server is unlikely to have any useful results
640 // for any of them. Also don't send URLs with ports, as we may initially
641 // think that a username + password is a host + port (and we don't want to
642 // send usernames/passwords), and even if the port really is a port, the
643 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58644 // Note that we only block based on refs if the input is URL-typed, as search
645 // queries can legitimately have #s in them which the URL parser
646 // overaggressively categorizes as a url with a ref.
[email protected]b45334502014-04-30 19:44:05647 const url::Parsed& parts = input_.parts();
[email protected]cac59d32010-08-09 23:23:14648 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58649 parts.query.is_nonempty() ||
[email protected]3dc75b12014-06-08 00:02:22650 (parts.ref.is_nonempty() &&
651 (input_.type() == metrics::OmniboxInputType::URL)))
[email protected]cac59d32010-08-09 23:23:14652 return false;
653
654 // Don't send anything for https except the hostname. Hostnames are OK
655 // because they are visible when the TCP connection is established, but the
656 // specific path may reveal private information.
[email protected]df807042014-08-13 16:48:41657 if (LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36658 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14659 return false;
[email protected]83c726482008-09-10 06:36:34660
661 return true;
662}
663
mpearson6c183672014-09-03 02:09:42664void SearchProvider::UpdateAllOldResults(bool minimal_changes) {
[email protected]dc735c02013-11-12 23:23:41665 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51666 // User is either in keyword mode with a blank input or out of
667 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24668 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51669 }
mpearson6c183672014-09-03 02:09:42670 UpdateOldResults(minimal_changes, &default_results_);
671 UpdateOldResults(minimal_changes, &keyword_results_);
[email protected]d1f0a7f2012-06-05 10:26:42672}
673
mpearson6c183672014-09-03 02:09:42674void SearchProvider::PersistTopSuggestions(
675 SearchSuggestionParser::Results* results) {
676 // Mark any results matching the current top results as having been received
677 // prior to the last keystroke. That prevents asynchronous updates from
678 // clobbering top results, which may be used for inline autocompletion.
679 // Other results don't need similar changes, because they shouldn't be
680 // displayed asynchronously anyway.
681 if (!top_query_suggestion_match_contents_.empty()) {
682 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
683 results->suggest_results.begin();
684 sug_it != results->suggest_results.end(); ++sug_it) {
685 if (sug_it->match_contents() == top_query_suggestion_match_contents_)
686 sug_it->set_received_after_last_keystroke(false);
687 }
688 }
689 if (top_navigation_suggestion_.is_valid()) {
690 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
691 results->navigation_results.begin();
692 nav_it != results->navigation_results.end(); ++nav_it) {
693 if (nav_it->url() == top_navigation_suggestion_)
694 nav_it->set_received_after_last_keystroke(false);
695 }
696 }
[email protected]d1f0a7f2012-06-05 10:26:42697}
698
[email protected]0b9575f2014-07-30 11:58:37699void SearchProvider::ApplyCalculatedSuggestRelevance(
700 SearchSuggestionParser::SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42701 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37702 SearchSuggestionParser::SuggestResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42703 result.set_relevance(
704 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
705 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07706 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42707 }
708}
709
[email protected]188b50c2013-03-28 07:19:42710void SearchProvider::ApplyCalculatedNavigationRelevance(
[email protected]0b9575f2014-07-30 11:58:37711 SearchSuggestionParser::NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42712 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37713 SearchSuggestionParser::NavigationResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42714 result.set_relevance(
715 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
716 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07717 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42718 }
719}
720
[email protected]15fb2aa2012-05-22 22:52:59721net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12722 int id,
[email protected]9ff91722012-09-07 05:29:12723 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41724 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12725 if (!template_url || template_url->suggestions_url().empty())
726 return NULL;
727
728 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41729 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
[email protected]420472b22014-06-10 13:34:43730 search_term_args.input_type = input.type();
[email protected]14710852013-02-05 23:45:41731 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18732 search_term_args.page_classification = input.current_page_classification();
[email protected]2ef2a6642014-07-30 05:50:29733 if (OmniboxFieldTrial::EnableAnswersInSuggest()) {
[email protected]20184242014-05-14 02:57:42734 search_term_args.session_token = GetSessionToken();
[email protected]2ef2a6642014-07-30 05:50:29735 if (!prefetch_data_.full_query_text.empty()) {
736 search_term_args.prefetch_query =
[email protected]ebbac63e2014-08-22 01:43:06737 base::UTF16ToUTF8(prefetch_data_.full_query_text);
[email protected]2ef2a6642014-07-30 05:50:29738 search_term_args.prefetch_query_type =
[email protected]ebbac63e2014-08-22 01:43:06739 base::UTF16ToUTF8(prefetch_data_.query_type);
[email protected]2ef2a6642014-07-30 05:50:29740 }
741 }
[email protected]9ff91722012-09-07 05:29:12742 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19743 search_term_args,
744 providers_.template_url_service()->search_terms_data()));
[email protected]9ff91722012-09-07 05:29:12745 if (!suggest_url.is_valid())
746 return NULL;
[email protected]9b9fa672013-11-07 06:04:52747 // Send the current page URL if user setting and URL requirements are met and
748 // the user is in the field trial.
749 if (CanSendURL(current_page_url_, suggest_url, template_url,
[email protected]e6477f12014-08-05 07:59:54750 input.current_page_classification(),
Ryo Hashimoto884ad192014-08-28 05:54:30751 template_url_service_->search_terms_data(), client_.get()) &&
[email protected]9b9fa672013-11-07 06:04:52752 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
753 search_term_args.current_page_url = current_page_url_.spec();
754 // Create the suggest URL again with the current page URL.
755 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19756 search_term_args,
757 providers_.template_url_service()->search_terms_data()));
[email protected]9b9fa672013-11-07 06:04:52758 }
[email protected]9ff91722012-09-07 05:29:12759
760 suggest_results_pending_++;
761 LogOmniboxSuggestRequest(REQUEST_SENT);
762
763 net::URLFetcher* fetcher =
764 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
Ryo Hashimoto884ad192014-08-28 05:54:30765 fetcher->SetRequestContext(client_->RequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34766 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30767 // Add Chrome experiment state to the request headers.
768 net::HttpRequestHeaders headers;
[email protected]71011c1682014-07-09 17:19:16769 variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
Ryo Hashimoto884ad192014-08-28 05:54:30770 fetcher->GetOriginalURL(), client_->IsOffTheRecord(), false, &headers);
[email protected]bd3b4712012-12-18 17:01:30771 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24772 fetcher->Start();
773 return fetcher;
774}
775
[email protected]344946a12012-12-20 12:03:42776void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29777 // Convert all the results to matches and add them to a map, so we can keep
778 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36779 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29780 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23781 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24782 int did_not_accept_keyword_suggestion =
783 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29784 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
785 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29786
[email protected]d30268a2013-06-25 22:31:07787 bool relevance_from_server;
788 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24789 int did_not_accept_default_suggestion =
790 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08791 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
792 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]7bc5e162014-08-15 19:41:11793 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]d1f0a7f2012-06-05 10:26:42794 if (verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44795 const base::string16& trimmed_verbatim =
796 base::CollapseWhitespace(input_.text(), false);
[email protected]716cd372014-08-15 18:56:03797
798 // Verbatim results don't get suggestions and hence, answers.
799 // Scan previous matches if the last answer-bearing suggestion matches
800 // verbatim, and if so, copy over answer contents.
801 base::string16 answer_contents;
802 base::string16 answer_type;
803 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
804 ++it) {
805 if (!it->answer_contents.empty() &&
806 it->fill_into_edit == trimmed_verbatim) {
807 answer_contents = it->answer_contents;
808 answer_type = it->answer_type;
809 break;
810 }
811 }
812
[email protected]0b9575f2014-07-30 11:58:37813 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44814 trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]716cd372014-08-15 18:56:03815 trimmed_verbatim, base::string16(), base::string16(), answer_contents,
816 answer_type, std::string(), std::string(), false, verbatim_relevance,
817 relevance_from_server, false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37818 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
[email protected]7bc5e162014-08-15 19:41:11819 false, keyword_url != NULL, &map);
[email protected]d1f0a7f2012-06-05 10:26:42820 }
[email protected]5423e562013-02-07 03:58:45821 if (!keyword_input_.text().empty()) {
[email protected]5423e562013-02-07 03:58:45822 // We only create the verbatim search query match for a keyword
823 // if it's not an extension keyword. Extension keywords are handled
824 // in KeywordProvider::Start(). (Extensions are complicated...)
825 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
826 // to the keyword verbatim search query. Do not create other matches
827 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:25828 if (keyword_url &&
829 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:07830 bool keyword_relevance_from_server;
831 const int keyword_verbatim_relevance =
832 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:28833 if (keyword_verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44834 const base::string16& trimmed_verbatim =
835 base::CollapseWhitespace(keyword_input_.text(), false);
[email protected]0b9575f2014-07-30 11:58:37836 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44837 trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
838 trimmed_verbatim, base::string16(), base::string16(),
[email protected]7ec287e2014-05-16 02:50:08839 base::string16(), base::string16(), std::string(), std::string(),
840 true, keyword_verbatim_relevance, keyword_relevance_from_server,
841 false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37842 AddMatchToMap(verbatim, std::string(),
[email protected]7bc5e162014-08-15 19:41:11843 did_not_accept_keyword_suggestion, false, true, &map);
[email protected]dab8d52d2013-03-05 07:35:28844 }
[email protected]5423e562013-02-07 03:58:45845 }
846 }
[email protected]257ab712009-04-14 17:16:24847 AddHistoryResultsToMap(keyword_history_results_, true,
848 did_not_accept_keyword_suggestion, &map);
849 AddHistoryResultsToMap(default_history_results_, false,
850 did_not_accept_default_suggestion, &map);
851
[email protected]d1cb6a822013-09-18 19:43:00852 AddSuggestResultsToMap(keyword_results_.suggest_results,
853 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:18854 AddSuggestResultsToMap(default_results_.suggest_results,
855 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:29856
[email protected]d30268a2013-06-25 22:31:07857 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:29858 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:07859 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:29860
[email protected]d30268a2013-06-25 22:31:07861 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
862 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:29863
[email protected]d30268a2013-06-25 22:31:07864 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
mpearson6c183672014-09-03 02:09:42865 // suggest/navsuggest matches, regardless of origin. We always include in
866 // that set a legal default match if possible. If Instant Extended is enabled
867 // and we have server-provided (and thus hopefully more accurate) scores for
868 // some suggestions, we allow more of those, until we reach
[email protected]d30268a2013-06-25 22:31:07869 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
870 // whole popup).
871 //
872 // We will always return any verbatim matches, no matter how we obtained their
873 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
874 // higher-scoring matches under the conditions above.
875 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
876 matches_.clear();
mpearson6c183672014-09-03 02:09:42877 // Guarantee that if there's a legal default match anywhere in the result
878 // set that it'll get returned. The rotate() call does this by moving the
879 // default match to the front of the list.
880 ACMatches::iterator default_match = FindTopMatch(&matches);
881 if (default_match != matches.end())
882 std::rotate(matches.begin(), default_match, default_match + 1);
[email protected]3723e6e2012-06-11 21:06:56883
[email protected]d30268a2013-06-25 22:31:07884 size_t num_suggestions = 0;
885 for (ACMatches::const_iterator i(matches.begin());
886 (i != matches.end()) &&
887 (matches_.size() < AutocompleteResult::kMaxMatches);
888 ++i) {
889 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
890 // verbatim result, so this condition basically means "if this match is a
891 // suggestion of some sort".
892 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
893 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
894 // If we've already hit the limit on non-server-scored suggestions, and
895 // this isn't a server-scored suggestion we can add, skip it.
896 if ((num_suggestions >= kMaxMatches) &&
897 (!chrome::IsInstantExtendedAPIEnabled() ||
898 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
899 continue;
900 }
901
902 ++num_suggestions;
903 }
904
905 matches_.push_back(*i);
906 }
[email protected]31afdf72013-09-26 04:29:36907 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
908 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:42909}
910
[email protected]89bd27d12014-04-12 17:36:23911ACMatches::const_iterator SearchProvider::FindTopMatch() const {
[email protected]0a8718b12013-11-13 18:41:31912 ACMatches::const_iterator it = matches_.begin();
913 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
914 ++it;
915 return it;
[email protected]9dfb4d362013-04-05 02:15:12916}
917
[email protected]89bd27d12014-04-12 17:36:23918bool SearchProvider::IsTopMatchSearchWithURLInput() const {
919 ACMatches::const_iterator first_match = FindTopMatch();
[email protected]3dc75b12014-06-08 00:02:22920 return (input_.type() == metrics::OmniboxInputType::URL) &&
[email protected]0a8718b12013-11-13 18:41:31921 (first_match != matches_.end()) &&
922 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
[email protected]78981d8c2014-05-09 15:05:47923 (first_match->type != AutocompleteMatchType::NAVSUGGEST) &&
924 (first_match->type != AutocompleteMatchType::NAVSUGGEST_PERSONALIZED);
[email protected]344946a12012-12-20 12:03:42925}
926
[email protected]257ab712009-04-14 17:16:24927void SearchProvider::AddNavigationResultsToMatches(
[email protected]0b9575f2014-07-30 11:58:37928 const SearchSuggestionParser::NavigationResults& navigation_results,
[email protected]d30268a2013-06-25 22:31:07929 ACMatches* matches) {
[email protected]0b9575f2014-07-30 11:58:37930 for (SearchSuggestionParser::NavigationResults::const_iterator it =
931 navigation_results.begin(); it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:07932 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:23933 // In the absence of suggested relevance scores, use only the single
934 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:07935 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:23936 return;
[email protected]257ab712009-04-14 17:16:24937 }
938}
939
940void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
941 bool is_keyword,
942 int did_not_accept_suggestion,
943 MatchMap* map) {
[email protected]51124552011-07-16 01:37:10944 if (results.empty())
945 return;
946
[email protected]31afdf72013-09-26 04:29:36947 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]d7ad4772012-06-01 03:12:54948 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
[email protected]3dc75b12014-06-08 00:02:22949 (input_.type() == metrics::OmniboxInputType::URL);
[email protected]0085863a2013-12-06 21:19:03950 const base::string16& input_text =
[email protected]14710852013-02-05 23:45:41951 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:10952 bool input_multiple_words = HasMultipleWords(input_text);
953
[email protected]0b9575f2014-07-30 11:58:37954 SearchSuggestionParser::SuggestResults scored_results;
[email protected]55ce8f12012-05-09 04:44:08955 if (!prevent_inline_autocomplete && input_multiple_words) {
956 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
957 // queries if the input also has multiple words. But if we were already
[email protected]f13a2132014-04-22 08:13:52958 // scoring a multi-word, multi-visit query aggressively, and the current
959 // input is still a prefix of it, then changing the suggestion suddenly
960 // feels wrong. To detect this case, first score as if only one word has
961 // been typed, then check if the best result came from aggressive search
962 // history scoring. If it did, then just keep that score set. This
963 // 1200 the lowest possible score in CalculateRelevanceForHistory()'s
964 // aggressive-scoring curve.
[email protected]55ce8f12012-05-09 04:44:08965 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
966 false, input_text, is_keyword);
[email protected]f13a2132014-04-22 08:13:52967 if ((scored_results.front().relevance() < 1200) ||
[email protected]9dfb4d362013-04-05 02:15:12968 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:08969 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:10970 }
[email protected]55ce8f12012-05-09 04:44:08971 if (scored_results.empty())
972 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
973 input_multiple_words, input_text,
974 is_keyword);
[email protected]0b9575f2014-07-30 11:58:37975 for (SearchSuggestionParser::SuggestResults::const_iterator i(
976 scored_results.begin()); i != scored_results.end(); ++i) {
[email protected]7bc5e162014-08-15 19:41:11977 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true,
978 providers_.GetKeywordProviderURL() != NULL, map);
[email protected]51124552011-07-16 01:37:10979 }
[email protected]31afdf72013-09-26 04:29:36980 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
981 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:10982}
983
[email protected]0b9575f2014-07-30 11:58:37984SearchSuggestionParser::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:10985 const HistoryResults& results,
986 bool base_prevent_inline_autocomplete,
987 bool input_multiple_words,
[email protected]0085863a2013-12-06 21:19:03988 const base::string16& input_text,
[email protected]51124552011-07-16 01:37:10989 bool is_keyword) {
[email protected]0b9575f2014-07-30 11:58:37990 SearchSuggestionParser::SuggestResults scored_results;
[email protected]ab5fd2f2014-07-17 19:18:52991 // True if the user has asked this exact query previously.
992 bool found_what_you_typed_match = false;
[email protected]78e5e432013-08-03 02:10:10993 const bool prevent_search_history_inlining =
994 OmniboxFieldTrial::SearchHistoryPreventInlining(
995 input_.current_page_classification());
[email protected]c2ca3fd2014-03-22 03:07:44996 const base::string16& trimmed_input =
997 base::CollapseWhitespace(input_text, false);
[email protected]257ab712009-04-14 17:16:24998 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
999 ++i) {
[email protected]c2ca3fd2014-03-22 03:07:441000 const base::string16& trimmed_suggestion =
1001 base::CollapseWhitespace(i->term, false);
1002
[email protected]51124552011-07-16 01:37:101003 // Don't autocomplete multi-word queries that have only been seen once
1004 // unless the user has typed more than one word.
1005 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
[email protected]c2ca3fd2014-03-22 03:07:441006 (!input_multiple_words && (i->visits < 2) &&
1007 HasMultipleWords(trimmed_suggestion));
[email protected]51124552011-07-16 01:37:101008
[email protected]78e5e432013-08-03 02:10:101009 int relevance = CalculateRelevanceForHistory(
1010 i->time, is_keyword, !prevent_inline_autocomplete,
1011 prevent_search_history_inlining);
[email protected]ab5fd2f2014-07-17 19:18:521012 // Add the match to |scored_results| by putting the what-you-typed match
1013 // on the front and appending all other matches. We want the what-you-
1014 // typed match to always be first.
[email protected]0b9575f2014-07-30 11:58:371015 SearchSuggestionParser::SuggestResults::iterator insertion_position =
1016 scored_results.end();
[email protected]ab5fd2f2014-07-17 19:18:521017 if (trimmed_suggestion == trimmed_input) {
1018 found_what_you_typed_match = true;
1019 insertion_position = scored_results.begin();
1020 }
mpearson6c183672014-09-03 02:09:421021 SearchSuggestionParser::SuggestResult history_suggestion(
1022 trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
1023 trimmed_suggestion, base::string16(), base::string16(),
1024 base::string16(), base::string16(), std::string(), std::string(),
1025 is_keyword, relevance, false, false, trimmed_input);
1026 // History results are synchronous; they are received on the last keystroke.
1027 history_suggestion.set_received_after_last_keystroke(false);
1028 scored_results.insert(insertion_position, history_suggestion);
[email protected]257ab712009-04-14 17:16:241029 }
[email protected]51124552011-07-16 01:37:101030
1031 // History returns results sorted for us. However, we may have docked some
[email protected]ab5fd2f2014-07-17 19:18:521032 // results' scores, so things are no longer in order. While keeping the
1033 // what-you-typed match at the front (if it exists), do a stable sort to get
[email protected]51124552011-07-16 01:37:101034 // things back in order without otherwise disturbing results with equal
1035 // scores, then force the scores to be unique, so that the order in which
1036 // they're shown is deterministic.
[email protected]ab5fd2f2014-07-17 19:18:521037 std::stable_sort(scored_results.begin() +
1038 (found_what_you_typed_match ? 1 : 0),
1039 scored_results.end(),
[email protected]55ce8f12012-05-09 04:44:081040 CompareScoredResults());
[email protected]7e3b77f2014-07-25 02:29:441041
1042 // Don't autocomplete to search terms that would normally be treated as URLs
1043 // when typed. For example, if the user searched for "google.com" and types
1044 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1045 // the input will look like a URL but act like a search, which is confusing.
1046 // The 1200 relevance score threshold in the test below is the lowest
1047 // possible score in CalculateRelevanceForHistory()'s aggressive-scoring
1048 // curve. This is an appropriate threshold to use to decide if we're overly
1049 // aggressively inlining because, if we decide the answer is yes, the
1050 // way we resolve it it to not use the aggressive-scoring curve.
1051 // NOTE: We don't check for autocompleting to URLs in the following cases:
1052 // * When inline autocomplete is disabled, we won't be inline autocompleting
1053 // this term, so we don't need to worry about confusion as much. This
1054 // also prevents calling Classify() again from inside the classifier
1055 // (which will corrupt state and likely crash), since the classifier
1056 // always disables inline autocomplete.
1057 // * When the user has typed the whole string before as a query, then it's
1058 // likely the user has no expectation that term should be interpreted as
1059 // as a URL, so we need not do anything special to preserve user
1060 // expectation.
[email protected]51124552011-07-16 01:37:101061 int last_relevance = 0;
[email protected]7e3b77f2014-07-25 02:29:441062 if (!base_prevent_inline_autocomplete && !found_what_you_typed_match &&
hashimoto663b9f42014-08-26 04:29:201063 scored_results.front().relevance() >= 1200) {
[email protected]7e3b77f2014-07-25 02:29:441064 AutocompleteMatch match;
Ryo Hashimoto884ad192014-08-28 05:54:301065 client_->Classify(scored_results.front().suggestion(), false, false,
1066 input_.current_page_classification(), &match, NULL);
[email protected]7e3b77f2014-07-25 02:29:441067 // Demote this match that would normally be interpreted as a URL to have
1068 // the highest score a previously-issued search query could have when
1069 // scoring with the non-aggressive method. A consequence of demoting
1070 // by revising |last_relevance| is that this match and all following
1071 // matches get demoted; the relative order of matches is preserved.
1072 // One could imagine demoting only those matches that might cause
1073 // confusion (which, by the way, might change the relative order of
1074 // matches. We have decided to go with the simple demote-all approach
1075 // because selective demotion requires multiple Classify() calls and
1076 // such calls can be expensive (as expensive as running the whole
1077 // autocomplete system).
1078 if (!AutocompleteMatch::IsSearchType(match.type)) {
1079 last_relevance = CalculateRelevanceForHistory(
1080 base::Time::Now(), is_keyword, false,
1081 prevent_search_history_inlining);
1082 }
1083 }
1084
[email protected]0b9575f2014-07-30 11:58:371085 for (SearchSuggestionParser::SuggestResults::iterator i(
1086 scored_results.begin()); i != scored_results.end(); ++i) {
[email protected]7e3b77f2014-07-25 02:29:441087 if ((last_relevance != 0) && (i->relevance() >= last_relevance))
[email protected]55ce8f12012-05-09 04:44:081088 i->set_relevance(last_relevance - 1);
1089 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101090 }
1091
[email protected]55ce8f12012-05-09 04:44:081092 return scored_results;
[email protected]257ab712009-04-14 17:16:241093}
1094
[email protected]0b9575f2014-07-30 11:58:371095void SearchProvider::AddSuggestResultsToMap(
1096 const SearchSuggestionParser::SuggestResults& results,
1097 const std::string& metadata,
1098 MatchMap* map) {
[email protected]7bc5e162014-08-15 19:41:111099 for (size_t i = 0; i < results.size(); ++i) {
1100 AddMatchToMap(results[i], metadata, i, false,
1101 providers_.GetKeywordProviderURL() != NULL, map);
1102 }
initial.commit09911bf2008-07-26 23:55:291103}
1104
[email protected]d30268a2013-06-25 22:31:071105int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561106 // Use the suggested verbatim relevance score if it is non-negative (valid),
1107 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281108 // and if it won't suppress verbatim, leaving no default provider matches.
1109 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561110 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281111 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561112 // Check for results on each verbatim calculation, as results from older
1113 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231114 bool use_server_relevance =
1115 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281116 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231117 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241118 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231119 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071120 if (relevance_from_server)
1121 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231122 return use_server_relevance ?
1123 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521124}
[email protected]d1f0a7f2012-06-05 10:26:421125
[email protected]382a0642012-06-06 06:13:521126int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471127 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361128 return 250;
[email protected]dab8d52d2013-03-05 07:35:281129 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1130}
[email protected]52d08b12009-10-19 18:42:361131
[email protected]dab8d52d2013-03-05 07:35:281132int SearchProvider::
1133 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291134 switch (input_.type()) {
[email protected]3dc75b12014-06-08 00:02:221135 case metrics::OmniboxInputType::UNKNOWN:
1136 case metrics::OmniboxInputType::QUERY:
1137 case metrics::OmniboxInputType::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131138 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291139
[email protected]3dc75b12014-06-08 00:02:221140 case metrics::OmniboxInputType::URL:
[email protected]52d08b12009-10-19 18:42:361141 return 850;
initial.commit09911bf2008-07-26 23:55:291142
1143 default:
1144 NOTREACHED();
1145 return 0;
1146 }
1147}
1148
[email protected]d30268a2013-06-25 22:31:071149int SearchProvider::GetKeywordVerbatimRelevance(
1150 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281151 // Use the suggested verbatim relevance score if it is non-negative (valid),
1152 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1153 // and if it won't suppress verbatim, leaving no keyword provider matches.
1154 // Otherwise, if the keyword provider returned no matches and was still able
1155 // to suppress verbatim, the user would have no search/nav matches and may be
1156 // left unable to search using their keyword provider from the omnibox.
1157 // Check for results on each verbatim calculation, as results from older
1158 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231159 bool use_server_relevance =
1160 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281161 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231162 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241163 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231164 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071165 if (relevance_from_server)
1166 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231167 return use_server_relevance ?
1168 keyword_results_.verbatim_relevance :
1169 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1170 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451171}
1172
[email protected]51124552011-07-16 01:37:101173int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231174 const base::Time& time,
[email protected]51124552011-07-16 01:37:101175 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101176 bool use_aggressive_method,
1177 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181178 // The relevance of past searches falls off over time. There are two distinct
1179 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101180 // provider that we want to score aggressively), the score is in the range
1181 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161182 // it's in the range 1200-1299). If the second equation is used the
1183 // relevance of a search 15 minutes ago is discounted 50 points, while the
1184 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231185 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421186 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101187 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181188 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101189 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181190 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161191 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101192 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161193 max_score = 1299;
1194 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181195 std::pow(elapsed_time / autocomplete_time, 2.5));
1196 }
1197 elapsed_time -= autocomplete_time;
1198 }
1199
[email protected]c3a4bd992010-08-18 20:25:011200 const int score_discount =
1201 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291202
[email protected]6c85aa02009-02-27 12:08:091203 // Don't let scores go below 0. Negative relevance scores are meaningful in
1204 // a different way.
initial.commit09911bf2008-07-26 23:55:291205 int base_score;
[email protected]51124552011-07-16 01:37:101206 if (is_primary_provider)
[email protected]3dc75b12014-06-08 00:02:221207 base_score = (input_.type() == metrics::OmniboxInputType::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101208 else
1209 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291210 return std::max(0, base_score - score_discount);
1211}
1212
initial.commit09911bf2008-07-26 23:55:291213AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]0b9575f2014-07-30 11:58:371214 const SearchSuggestionParser::NavigationResult& navigation) {
[email protected]5889bfb2014-03-19 00:26:481215 base::string16 input;
1216 const bool trimmed_whitespace = base::TrimWhitespace(
1217 navigation.from_keyword_provider() ?
1218 keyword_input_.text() : input_.text(),
1219 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
[email protected]55ce8f12012-05-09 04:44:081220 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]78981d8c2014-05-09 15:05:471221 navigation.type());
[email protected]55ce8f12012-05-09 04:44:081222 match.destination_url = navigation.url();
[email protected]78981d8c2014-05-09 15:05:471223 BaseSearchProvider::SetDeletionURL(navigation.deletion_url(), &match);
[email protected]23db6492014-01-16 02:35:301224 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551225 // without trimming the scheme, so we can find matches at the beginning of the
1226 // scheme.
[email protected]371dab12012-06-01 03:23:551227 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301228 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551229 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301230 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351231 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1232 (!prefix || (match_start != 0));
[email protected]23db6492014-01-16 02:35:301233 const net::FormatUrlTypes format_types =
1234 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551235
Ryo Hashimoto884ad192014-08-28 05:54:301236 const std::string languages(client_->AcceptLanguages());
[email protected]23db6492014-01-16 02:35:301237 size_t inline_autocomplete_offset = (prefix == NULL) ?
1238 base::string16::npos : (match_start + input.length());
[email protected]371dab12012-06-01 03:23:551239 match.fill_into_edit +=
[email protected]5655ea32014-06-21 05:28:081240 AutocompleteInput::FormattedStringWithEquivalentMeaning(
1241 navigation.url(),
[email protected]371dab12012-06-01 03:23:551242 net::FormatUrl(navigation.url(), languages, format_types,
1243 net::UnescapeRule::SPACES, NULL, NULL,
[email protected]5655ea32014-06-21 05:28:081244 &inline_autocomplete_offset),
Ryo Hashimoto884ad192014-08-28 05:54:301245 client_->SchemeClassifier());
[email protected]14119032013-11-07 08:14:261246 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1247 // Otherwise, user edits to a suggestion would show non-Search results.
[email protected]3dc75b12014-06-08 00:02:221248 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581249 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031250 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261251 ++inline_autocomplete_offset;
1252 }
[email protected]6c94a1022014-02-21 03:48:041253 if (inline_autocomplete_offset != base::string16::npos) {
[email protected]518024c2013-07-19 23:40:251254 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1255 match.inline_autocompletion =
1256 match.fill_into_edit.substr(inline_autocomplete_offset);
1257 }
[email protected]6c94a1022014-02-21 03:48:041258 // An inlineable navsuggestion can only be the default match when there
1259 // is no keyword provider active, lest it appear first and break the user
mpearson6c183672014-09-03 02:09:421260 // out of keyword mode. We also must have received the navsuggestion before
1261 // the last keystroke, to prevent asynchronous inline autocompletions changes.
1262 // The navsuggestion can also only be default if either the inline
[email protected]5889bfb2014-03-19 00:26:481263 // autocompletion is empty or we're not preventing inline autocompletion.
1264 // Finally, if we have an inlineable navsuggestion with an inline completion
1265 // that we're not preventing, make sure we didn't trim any whitespace.
1266 // We don't want to claim http://foo.com/bar is inlineable against the
1267 // input "foo.com/b ".
mpearson6c183672014-09-03 02:09:421268 match.allowed_to_be_default_match =
1269 (prefix != NULL) &&
[email protected]6c94a1022014-02-21 03:48:041270 (providers_.GetKeywordProviderURL() == NULL) &&
mpearson6c183672014-09-03 02:09:421271 !navigation.received_after_last_keystroke() &&
[email protected]5889bfb2014-03-19 00:26:481272 (match.inline_autocompletion.empty() ||
[email protected]78981d8c2014-05-09 15:05:471273 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
[email protected]c7b8be02014-07-11 19:46:341274 match.EnsureUWYTIsAllowedToBeDefault(
1275 input_.canonicalized_url(), providers_.template_url_service());
[email protected]371dab12012-06-01 03:23:551276
[email protected]23db6492014-01-16 02:35:301277 match.contents = navigation.match_contents();
1278 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081279 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551280 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1281 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071282
1283 match.RecordAdditionalInfo(
1284 kRelevanceFromServerKey,
1285 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181286 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071287
initial.commit09911bf2008-07-26 23:55:291288 return match;
1289}
[email protected]4ab4c7c2010-11-24 04:49:341290
1291void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331292 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311293 // pending, and we're not waiting on Instant.
[email protected]e1290ee62013-06-26 18:31:151294 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
[email protected]4ab4c7c2010-11-24 04:49:341295}
[email protected]20184242014-05-14 02:57:421296
1297std::string SearchProvider::GetSessionToken() {
1298 base::TimeTicks current_time(base::TimeTicks::Now());
1299 // Renew token if it expired.
1300 if (current_time > token_expiration_time_) {
1301 const size_t kTokenBytes = 12;
1302 std::string raw_data;
1303 base::RandBytes(WriteInto(&raw_data, kTokenBytes + 1), kTokenBytes);
1304 base::Base64Encode(raw_data, &current_token_);
[email protected]ab2c31f72014-05-17 17:03:531305
1306 // Make the base64 encoded value URL and filename safe(see RFC 3548).
1307 std::replace(current_token_.begin(), current_token_.end(), '+', '-');
1308 std::replace(current_token_.begin(), current_token_.end(), '/', '_');
[email protected]20184242014-05-14 02:57:421309 }
1310
1311 // Extend expiration time another 60 seconds.
1312 token_expiration_time_ = current_time + base::TimeDelta::FromSeconds(60);
1313
1314 return current_token_;
1315}
[email protected]2ef2a6642014-07-30 05:50:291316
1317void SearchProvider::RegisterDisplayedAnswers(
1318 const AutocompleteResult& result) {
1319 if (result.empty())
1320 return;
1321
1322 // The answer must be in the first or second slot to be considered. It should
1323 // only be in the second slot if AutocompleteController ranked a local search
1324 // history or a verbatim item higher than the answer.
1325 AutocompleteResult::const_iterator match = result.begin();
1326 if (match->answer_contents.empty() && result.size() > 1)
1327 ++match;
1328 if (match->answer_contents.empty() || match->answer_type.empty() ||
1329 match->fill_into_edit.empty())
1330 return;
1331
1332 // Valid answer encountered, cache it for further queries.
[email protected]ebbac63e2014-08-22 01:43:061333 answers_cache_.UpdateRecentAnswers(match->fill_into_edit, match->answer_type);
[email protected]2ef2a6642014-07-30 05:50:291334}
1335
1336void SearchProvider::DoAnswersQuery(const AutocompleteInput& input) {
[email protected]ebbac63e2014-08-22 01:43:061337 prefetch_data_ = answers_cache_.GetTopAnswerEntry(input.text());
[email protected]2ef2a6642014-07-30 05:50:291338}