blob: 80f8648c574d0198e373d5f657c241a230546478 [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
5#include "chrome/browser/autocomplete/search_provider.h"
6
[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]2041cf342010-02-19 03:15:5910#include "base/callback.h"
[email protected]51124552011-07-16 01:37:1011#include "base/i18n/break_iterator.h"
[email protected]503d03872011-05-06 08:36:2612#include "base/i18n/case_conversion.h"
[email protected]d6e58c6e2009-10-10 20:40:5013#include "base/i18n/icu_string_conversions.h"
[email protected]ffbec692012-02-26 20:26:4214#include "base/json/json_string_value_serializer.h"
[email protected]fa1e0e12013-07-18 00:10:1415#include "base/message_loop/message_loop.h"
[email protected]f5b95ba92012-03-27 14:05:1916#include "base/metrics/histogram.h"
[email protected]3853a4c2013-02-11 17:15:5717#include "base/prefs/pref_service.h"
[email protected]98570e12013-06-10 19:54:2218#include "base/strings/string16.h"
19#include "base/strings/string_util.h"
[email protected]135cb802013-06-09 16:44:2020#include "base/strings/utf_string_conversions.h"
[email protected]ea3b9a502011-04-04 14:19:3721#include "chrome/browser/autocomplete/autocomplete_classifier.h"
[email protected]810ffba2012-06-12 01:07:4822#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
[email protected]9ac40092010-10-27 23:05:2623#include "chrome/browser/autocomplete/autocomplete_match.h"
[email protected]5af9bc82012-06-29 00:53:4824#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
[email protected]73c2b1632012-07-02 22:51:3825#include "chrome/browser/autocomplete/autocomplete_result.h"
[email protected]2c812ba02011-07-14 00:23:1526#include "chrome/browser/autocomplete/keyword_provider.h"
[email protected]371dab12012-06-01 03:23:5527#include "chrome/browser/autocomplete/url_prefix.h"
[email protected]9b9fa672013-11-07 06:04:5228#include "chrome/browser/google/google_util.h"
[email protected]6a2c09f2013-01-25 04:50:0729#include "chrome/browser/history/history_service.h"
[email protected]9d2db762012-06-19 00:01:1030#include "chrome/browser/history/history_service_factory.h"
[email protected]10c2d692012-05-11 05:32:2331#include "chrome/browser/history/in_memory_database.h"
[email protected]ab7780792013-01-10 01:26:0932#include "chrome/browser/metrics/variations/variations_http_header_provider.h"
[email protected]684fcc12013-03-08 22:50:0233#include "chrome/browser/omnibox/omnibox_field_trial.h"
[email protected]8ecad5e2010-12-02 21:18:3334#include "chrome/browser/profiles/profile.h"
[email protected]a7b8e43d2013-03-18 18:52:4335#include "chrome/browser/search/search.h"
[email protected]9899a612012-08-21 23:50:0436#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
[email protected]8e5c89a2011-06-07 18:13:3337#include "chrome/browser/search_engines/template_url_service.h"
38#include "chrome/browser/search_engines/template_url_service_factory.h"
[email protected]9b9fa672013-11-07 06:04:5239#include "chrome/browser/sync/profile_sync_service.h"
40#include "chrome/browser/sync/profile_sync_service_factory.h"
[email protected]c4a9d4c2013-08-10 07:06:2741#include "chrome/browser/ui/browser.h"
42#include "chrome/browser/ui/browser_finder.h"
43#include "chrome/browser/ui/browser_instant_controller.h"
44#include "chrome/browser/ui/search/instant_controller.h"
[email protected]4f3b4462013-07-27 19:20:1845#include "chrome/common/net/url_fixer_upper.h"
initial.commit09911bf2008-07-26 23:55:2946#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0247#include "chrome/common/url_constants.h"
[email protected]7267ff82013-12-03 17:20:3048#include "content/public/browser/user_metrics.h"
[email protected]34ac8f32009-02-22 23:03:2749#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2950#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3451#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5552#include "net/base/net_util.h"
[email protected]9b9fa672013-11-07 06:04:5253#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
[email protected]bd3b4712012-12-18 17:01:3054#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2155#include "net/http/http_response_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5356#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2157#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1758#include "ui/base/l10n/l10n_util.h"
[email protected]761fa4702013-07-02 15:25:1559#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2960
[email protected]bc8bb0cd2013-06-24 21:50:2361
62// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3363
[email protected]51124552011-07-16 01:37:1064namespace {
65
[email protected]7706a522012-08-16 17:42:2566// We keep track in a histogram how many suggest requests we send, how
67// many suggest requests we invalidate (e.g., due to a user typing
68// another character), and how many replies we receive.
69// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
70// (excluding the end-of-list enum value)
71// We do not want values of existing enums to change or else it screws
72// up the statistics.
73enum SuggestRequestsHistogramValue {
74 REQUEST_SENT = 1,
75 REQUEST_INVALIDATED,
76 REPLY_RECEIVED,
77 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
78};
79
[email protected]90fe2bb2013-01-15 03:42:1380// The verbatim score for an input which is not an URL.
81const int kNonURLVerbatimRelevance = 1300;
82
[email protected]7706a522012-08-16 17:42:2583// Increments the appropriate value in the histogram by one.
84void LogOmniboxSuggestRequest(
85 SuggestRequestsHistogramValue request_value) {
86 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
87 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
88}
89
[email protected]0085863a2013-12-06 21:19:0390bool HasMultipleWords(const base::string16& text) {
[email protected]51124552011-07-16 01:37:1091 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
92 bool found_word = false;
93 if (i.Init()) {
94 while (i.Advance()) {
95 if (i.IsWord()) {
96 if (found_word)
97 return true;
98 found_word = true;
99 }
100 }
101 }
102 return false;
103}
104
[email protected]621ade062013-10-28 06:27:43105// Builds the match contents and classification for the contents, and updates
106// the given |AutocompleteMatch|.
[email protected]0085863a2013-12-06 21:19:03107void SetAndClassifyMatchContents(const base::string16& query_string,
108 const base::string16& input_text,
109 const base::string16& match_contents,
[email protected]621ade062013-10-28 06:27:43110 AutocompleteMatch* match) {
[email protected]2c03c06b2013-12-11 20:45:02111 match->contents = match_contents.empty() ? query_string : match_contents;
[email protected]621ade062013-10-28 06:27:43112
113 // We do intra-string highlighting for suggestions - the suggested segment
114 // will be highlighted, e.g. for input_text = "you" the suggestion may be
115 // "youtube", so we'll bold the "tube" section: you*tube*.
116 if (input_text != match_contents) {
[email protected]2c03c06b2013-12-11 20:45:02117 size_t input_position = match->contents.find(input_text);
[email protected]0085863a2013-12-06 21:19:03118 if (input_position == base::string16::npos) {
[email protected]621ade062013-10-28 06:27:43119 // The input text is not a substring of the query string, e.g. input
120 // text is "slasdot" and the query string is "slashdot", so we bold the
121 // whole thing.
122 match->contents_class.push_back(ACMatchClassification(
[email protected]2c03c06b2013-12-11 20:45:02123 0, ACMatchClassification::MATCH));
[email protected]621ade062013-10-28 06:27:43124 } else {
[email protected]621ade062013-10-28 06:27:43125 // TODO(beng): ACMatchClassification::MATCH now seems to just mean
126 // "bold" this. Consider modifying the terminology.
127 // We don't iterate over the string here annotating all matches because
128 // it looks odd to have every occurrence of a substring that may be as
129 // short as a single character highlighted in a query suggestion result,
130 // e.g. for input text "s" and query string "southwest airlines", it
131 // looks odd if both the first and last s are highlighted.
[email protected]2c03c06b2013-12-11 20:45:02132 if (input_position != 0) {
[email protected]621ade062013-10-28 06:27:43133 match->contents_class.push_back(ACMatchClassification(
[email protected]2c03c06b2013-12-11 20:45:02134 0, ACMatchClassification::MATCH));
[email protected]621ade062013-10-28 06:27:43135 }
136 match->contents_class.push_back(
137 ACMatchClassification(input_position, ACMatchClassification::NONE));
138 size_t next_fragment_position = input_position + input_text.length();
139 if (next_fragment_position < query_string.length()) {
140 match->contents_class.push_back(ACMatchClassification(
141 next_fragment_position, ACMatchClassification::MATCH));
142 }
143 }
144 } else {
145 // Otherwise, |match| is a verbatim (what-you-typed) match, either for the
146 // default provider or a keyword search provider.
147 match->contents_class.push_back(ACMatchClassification(
[email protected]2c03c06b2013-12-11 20:45:02148 0, ACMatchClassification::NONE));
[email protected]621ade062013-10-28 06:27:43149 }
[email protected]2c03c06b2013-12-11 20:45:02150}
[email protected]621ade062013-10-28 06:27:43151
[email protected]2c03c06b2013-12-11 20:45:02152AutocompleteMatchType::Type GetAutocompleteMatchType(const std::string& type) {
153 if (type == "ENTITY")
154 return AutocompleteMatchType::SEARCH_SUGGEST_ENTITY;
155 if (type == "INFINITE")
156 return AutocompleteMatchType::SEARCH_SUGGEST_INFINITE;
157 if (type == "PERSONALIZED")
158 return AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED;
159 if (type == "PROFILE")
160 return AutocompleteMatchType::SEARCH_SUGGEST_PROFILE;
161 return AutocompleteMatchType::SEARCH_SUGGEST;
[email protected]621ade062013-10-28 06:27:43162}
163
[email protected]d1f0a7f2012-06-05 10:26:42164} // namespace
[email protected]51124552011-07-16 01:37:10165
[email protected]033f3422012-03-13 21:24:18166
[email protected]7267ff82013-12-03 17:20:30167// SuggestionDeletionHandler -------------------------------------------------
168
169// This class handles making requests to the server in order to delete
170// personalized suggestions.
171class SuggestionDeletionHandler : public net::URLFetcherDelegate {
172 public:
173 typedef base::Callback<void(bool, SuggestionDeletionHandler*)>
174 DeletionCompletedCallback;
175
176 SuggestionDeletionHandler(
177 const std::string& deletion_url,
178 Profile* profile,
179 const DeletionCompletedCallback& callback);
180
181 virtual ~SuggestionDeletionHandler();
182
183 private:
184 // net::URLFetcherDelegate:
185 virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE;
186
187 scoped_ptr<net::URLFetcher> deletion_fetcher_;
188 DeletionCompletedCallback callback_;
189
190 DISALLOW_COPY_AND_ASSIGN(SuggestionDeletionHandler);
191};
192
193
194SuggestionDeletionHandler::SuggestionDeletionHandler(
195 const std::string& deletion_url,
196 Profile* profile,
197 const DeletionCompletedCallback& callback) : callback_(callback) {
198 GURL url(deletion_url);
199 DCHECK(url.is_valid());
200
201 deletion_fetcher_.reset(net::URLFetcher::Create(
202 SearchProvider::kDeletionURLFetcherID,
203 url,
204 net::URLFetcher::GET,
205 this));
206 deletion_fetcher_->SetRequestContext(profile->GetRequestContext());
207 deletion_fetcher_->Start();
208};
209
210SuggestionDeletionHandler::~SuggestionDeletionHandler() {
211};
212
213void SuggestionDeletionHandler::OnURLFetchComplete(
214 const net::URLFetcher* source) {
215 DCHECK(source == deletion_fetcher_.get());
216 callback_.Run(
217 source->GetStatus().is_success() && (source->GetResponseCode() == 200),
218 this);
219};
220
221
[email protected]3954c3a2012-04-10 20:17:55222// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:58223
[email protected]85b8d6f2012-05-08 20:53:47224SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
225 : template_url_service_(template_url_service) {
226}
227
228const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
229 return default_provider_.empty() ? NULL :
230 template_url_service_->GetTemplateURLForKeyword(default_provider_);
231}
232
233const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
234 return keyword_provider_.empty() ? NULL :
235 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24236}
237
[email protected]3954c3a2012-04-10 20:17:55238
[email protected]bc8bb0cd2013-06-24 21:50:23239// SearchProvider::Result -----------------------------------------------------
240
241SearchProvider::Result::Result(bool from_keyword_provider,
[email protected]d30268a2013-06-25 22:31:07242 int relevance,
243 bool relevance_from_server)
[email protected]bc8bb0cd2013-06-24 21:50:23244 : from_keyword_provider_(from_keyword_provider),
[email protected]d30268a2013-06-25 22:31:07245 relevance_(relevance),
246 relevance_from_server_(relevance_from_server) {
[email protected]bc8bb0cd2013-06-24 21:50:23247}
248
249SearchProvider::Result::~Result() {
250}
251
252
253// SearchProvider::SuggestResult ----------------------------------------------
254
[email protected]621ade062013-10-28 06:27:43255SearchProvider::SuggestResult::SuggestResult(
[email protected]0085863a2013-12-06 21:19:03256 const base::string16& suggestion,
[email protected]2c03c06b2013-12-11 20:45:02257 AutocompleteMatchType::Type type,
[email protected]0085863a2013-12-06 21:19:03258 const base::string16& match_contents,
259 const base::string16& annotation,
[email protected]621ade062013-10-28 06:27:43260 const std::string& suggest_query_params,
[email protected]7267ff82013-12-03 17:20:30261 const std::string& deletion_url,
[email protected]621ade062013-10-28 06:27:43262 bool from_keyword_provider,
263 int relevance,
264 bool relevance_from_server,
265 bool should_prefetch)
[email protected]d30268a2013-06-25 22:31:07266 : Result(from_keyword_provider, relevance, relevance_from_server),
[email protected]987fad782013-08-28 06:23:18267 suggestion_(suggestion),
[email protected]2c03c06b2013-12-11 20:45:02268 type_(type),
[email protected]621ade062013-10-28 06:27:43269 match_contents_(match_contents),
270 annotation_(annotation),
271 suggest_query_params_(suggest_query_params),
[email protected]7267ff82013-12-03 17:20:30272 deletion_url_(deletion_url),
[email protected]987fad782013-08-28 06:23:18273 should_prefetch_(should_prefetch) {
[email protected]bc8bb0cd2013-06-24 21:50:23274}
275
276SearchProvider::SuggestResult::~SuggestResult() {
277}
278
[email protected]0085863a2013-12-06 21:19:03279bool SearchProvider::SuggestResult::IsInlineable(
280 const base::string16& input) const {
[email protected]bc8bb0cd2013-06-24 21:50:23281 return StartsWith(suggestion_, input, false);
282}
283
284int SearchProvider::SuggestResult::CalculateRelevance(
285 const AutocompleteInput& input,
286 bool keyword_provider_requested) const {
287 if (!from_keyword_provider_ && keyword_provider_requested)
288 return 100;
289 return ((input.type() == AutocompleteInput::URL) ? 300 : 600);
290}
291
292
293// SearchProvider::NavigationResult -------------------------------------------
294
295SearchProvider::NavigationResult::NavigationResult(
296 const AutocompleteProvider& provider,
297 const GURL& url,
[email protected]0085863a2013-12-06 21:19:03298 const base::string16& description,
[email protected]bc8bb0cd2013-06-24 21:50:23299 bool from_keyword_provider,
[email protected]d30268a2013-06-25 22:31:07300 int relevance,
301 bool relevance_from_server)
302 : Result(from_keyword_provider, relevance, relevance_from_server),
[email protected]bc8bb0cd2013-06-24 21:50:23303 url_(url),
304 formatted_url_(AutocompleteInput::FormattedStringWithEquivalentMeaning(
305 url, provider.StringForURLDisplay(url, true, false))),
306 description_(description) {
307 DCHECK(url_.is_valid());
308}
309
310SearchProvider::NavigationResult::~NavigationResult() {
311}
312
313bool SearchProvider::NavigationResult::IsInlineable(
[email protected]0085863a2013-12-06 21:19:03314 const base::string16& input) const {
[email protected]bc8bb0cd2013-06-24 21:50:23315 return URLPrefix::BestURLPrefix(formatted_url_, input) != NULL;
316}
317
318int SearchProvider::NavigationResult::CalculateRelevance(
319 const AutocompleteInput& input,
320 bool keyword_provider_requested) const {
321 return (from_keyword_provider_ || !keyword_provider_requested) ? 800 : 150;
322}
323
324
325// SearchProvider::CompareScoredResults ---------------------------------------
326
327class SearchProvider::CompareScoredResults {
328 public:
329 bool operator()(const Result& a, const Result& b) {
330 // Sort in descending relevance order.
331 return a.relevance() > b.relevance();
332 }
333};
334
335
336// SearchProvider::Results ----------------------------------------------------
337
[email protected]d30268a2013-06-25 22:31:07338SearchProvider::Results::Results() : verbatim_relevance(-1) {
[email protected]bc8bb0cd2013-06-24 21:50:23339}
340
341SearchProvider::Results::~Results() {
342}
343
344void SearchProvider::Results::Clear() {
345 suggest_results.clear();
346 navigation_results.clear();
[email protected]bc8bb0cd2013-06-24 21:50:23347 verbatim_relevance = -1;
[email protected]987fad782013-08-28 06:23:18348 metadata.clear();
[email protected]bc8bb0cd2013-06-24 21:50:23349}
350
351bool SearchProvider::Results::HasServerProvidedScores() const {
352 if (verbatim_relevance >= 0)
353 return true;
354
[email protected]d30268a2013-06-25 22:31:07355 // Right now either all results of one type will be server-scored or they will
356 // all be locally scored, but in case we change this later, we'll just check
357 // them all.
358 for (SuggestResults::const_iterator i(suggest_results.begin());
359 i != suggest_results.end(); ++i) {
360 if (i->relevance_from_server())
361 return true;
362 }
363 for (NavigationResults::const_iterator i(navigation_results.begin());
364 i != navigation_results.end(); ++i) {
365 if (i->relevance_from_server())
366 return true;
367 }
368
369 return false;
[email protected]bc8bb0cd2013-06-24 21:50:23370}
[email protected]d30268a2013-06-25 22:31:07371
372
[email protected]3954c3a2012-04-10 20:17:55373// SearchProvider -------------------------------------------------------------
374
375// static
376const int SearchProvider::kDefaultProviderURLFetcherID = 1;
[email protected]3954c3a2012-04-10 20:17:55377const int SearchProvider::kKeywordProviderURLFetcherID = 2;
[email protected]7267ff82013-12-03 17:20:30378const int SearchProvider::kDeletionURLFetcherID = 3;
[email protected]24dbf2302013-04-05 16:59:25379int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]d30268a2013-06-25 22:31:07380const char SearchProvider::kRelevanceFromServerKey[] = "relevance_from_server";
[email protected]987fad782013-08-28 06:23:18381const char SearchProvider::kShouldPrefetchKey[] = "should_prefetch";
382const char SearchProvider::kSuggestMetadataKey[] = "suggest_metadata";
[email protected]7267ff82013-12-03 17:20:30383const char SearchProvider::kDeletionUrlKey[] = "deletion_url";
[email protected]d30268a2013-06-25 22:31:07384const char SearchProvider::kTrue[] = "true";
385const char SearchProvider::kFalse[] = "false";
[email protected]3954c3a2012-04-10 20:17:55386
[email protected]bc8bb0cd2013-06-24 21:50:23387SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
388 Profile* profile)
389 : AutocompleteProvider(listener, profile,
390 AutocompleteProvider::TYPE_SEARCH),
391 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
392 suggest_results_pending_(0),
[email protected]bc8bb0cd2013-06-24 21:50:23393 field_trial_triggered_(false),
[email protected]c4a9d4c2013-08-10 07:06:27394 field_trial_triggered_in_session_(false) {
[email protected]bc8bb0cd2013-06-24 21:50:23395}
396
[email protected]cb86ee6f2013-04-28 16:58:15397// static
398AutocompleteMatch SearchProvider::CreateSearchSuggestion(
[email protected]cb86ee6f2013-04-28 16:58:15399 AutocompleteProvider* autocomplete_provider,
[email protected]621ade062013-10-28 06:27:43400 const AutocompleteInput& input,
[email protected]0085863a2013-12-06 21:19:03401 const base::string16& input_text,
[email protected]575b2122014-01-03 20:35:33402 const SuggestResult& suggestion,
[email protected]bba9e632013-06-28 22:52:19403 const TemplateURL* template_url,
[email protected]bba9e632013-06-28 22:52:19404 int accepted_suggestion,
[email protected]56fa29592013-07-02 20:25:53405 int omnibox_start_margin,
406 bool append_extra_query_params) {
[email protected]575b2122014-01-03 20:35:33407 AutocompleteMatch match(autocomplete_provider, suggestion.relevance(), false,
408 suggestion.type());
[email protected]cb86ee6f2013-04-28 16:58:15409
[email protected]bba9e632013-06-28 22:52:19410 if (!template_url)
[email protected]cb86ee6f2013-04-28 16:58:15411 return match;
[email protected]bba9e632013-06-28 22:52:19412 match.keyword = template_url->keyword();
[email protected]cb86ee6f2013-04-28 16:58:15413
[email protected]575b2122014-01-03 20:35:33414 SetAndClassifyMatchContents(suggestion.suggestion(), input_text,
415 suggestion.match_contents(), &match);
[email protected]2c03c06b2013-12-11 20:45:02416
[email protected]575b2122014-01-03 20:35:33417 if (!suggestion.annotation().empty())
418 match.description = suggestion.annotation();
[email protected]621ade062013-10-28 06:27:43419
[email protected]575b2122014-01-03 20:35:33420 match.allowed_to_be_default_match =
421 (input_text == suggestion.match_contents());
[email protected]cb86ee6f2013-04-28 16:58:15422
423 // When the user forced a query, we need to make sure all the fill_into_edit
424 // values preserve that property. Otherwise, if the user starts editing a
425 // suggestion, non-Search results will suddenly appear.
426 if (input.type() == AutocompleteInput::FORCED_QUERY)
[email protected]670d3232013-12-24 17:58:58427 match.fill_into_edit.assign(base::ASCIIToUTF16("?"));
[email protected]575b2122014-01-03 20:35:33428 if (suggestion.from_keyword_provider())
[email protected]b6775d782013-12-25 20:04:53429 match.fill_into_edit.append(match.keyword + base::char16(' '));
[email protected]cb86ee6f2013-04-28 16:58:15430 if (!input.prevent_inline_autocomplete() &&
[email protected]575b2122014-01-03 20:35:33431 StartsWith(suggestion.suggestion(), input_text, false)) {
432 match.inline_autocompletion =
433 suggestion.suggestion().substr(input_text.length());
[email protected]45f89a92013-08-12 13:41:36434 match.allowed_to_be_default_match = true;
[email protected]cb86ee6f2013-04-28 16:58:15435 }
[email protected]575b2122014-01-03 20:35:33436 match.fill_into_edit.append(suggestion.suggestion());
[email protected]cb86ee6f2013-04-28 16:58:15437
[email protected]bba9e632013-06-28 22:52:19438 const TemplateURLRef& search_url = template_url->url_ref();
[email protected]cb86ee6f2013-04-28 16:58:15439 DCHECK(search_url.SupportsReplacement());
440 match.search_terms_args.reset(
[email protected]575b2122014-01-03 20:35:33441 new TemplateURLRef::SearchTermsArgs(suggestion.suggestion()));
[email protected]cb86ee6f2013-04-28 16:58:15442 match.search_terms_args->original_query = input_text;
443 match.search_terms_args->accepted_suggestion = accepted_suggestion;
[email protected]f3e46eec2013-06-11 14:46:28444 match.search_terms_args->omnibox_start_margin = omnibox_start_margin;
[email protected]575b2122014-01-03 20:35:33445 match.search_terms_args->suggest_query_params =
446 suggestion.suggest_query_params();
[email protected]56fa29592013-07-02 20:25:53447 match.search_terms_args->append_extra_query_params =
448 append_extra_query_params;
[email protected]cb86ee6f2013-04-28 16:58:15449 // This is the destination URL sans assisted query stats. This must be set
450 // so the AutocompleteController can properly de-dupe; the controller will
451 // eventually overwrite it before it reaches the user.
452 match.destination_url =
453 GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get()));
454
455 // Search results don't look like URLs.
[email protected]575b2122014-01-03 20:35:33456 match.transition = suggestion.from_keyword_provider() ?
[email protected]cb86ee6f2013-04-28 16:58:15457 content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED;
458
459 return match;
460}
461
[email protected]987fad782013-08-28 06:23:18462// static
463bool SearchProvider::ShouldPrefetch(const AutocompleteMatch& match) {
464 return match.GetAdditionalInfo(kShouldPrefetchKey) == kTrue;
465}
466
467// static
468std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
469 return match.GetAdditionalInfo(kSuggestMetadataKey);
470}
471
[email protected]bc8bb0cd2013-06-24 21:50:23472void SearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
473 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
474 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
475 new_entry.set_provider(AsOmniboxEventProviderType());
476 new_entry.set_provider_done(done_);
477 std::vector<uint32> field_trial_hashes;
478 OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(&field_trial_hashes);
479 for (size_t i = 0; i < field_trial_hashes.size(); ++i) {
480 if (field_trial_triggered_)
481 new_entry.mutable_field_trial_triggered()->Add(field_trial_hashes[i]);
482 if (field_trial_triggered_in_session_) {
483 new_entry.mutable_field_trial_triggered_in_session()->Add(
484 field_trial_hashes[i]);
485 }
486 }
487}
488
[email protected]7267ff82013-12-03 17:20:30489void SearchProvider::DeleteMatch(const AutocompleteMatch& match) {
[email protected]7267ff82013-12-03 17:20:30490 DCHECK(match.deletable);
491
492 deletion_handlers_.push_back(new SuggestionDeletionHandler(
493 match.GetAdditionalInfo(SearchProvider::kDeletionUrlKey),
494 profile_,
495 base::Bind(&SearchProvider::OnDeletionComplete, base::Unretained(this))));
496
[email protected]fba587fc2013-12-16 15:51:24497 HistoryService* const history_service =
498 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
499 TemplateURL* template_url = match.GetTemplateURL(profile_, false);
500 // This may be NULL if the template corresponding to the keyword has been
501 // deleted or there is no keyword set.
502 if (template_url != NULL) {
503 history_service->DeleteMatchingURLsForKeyword(template_url->id(),
504 match.contents);
505 }
506
[email protected]7267ff82013-12-03 17:20:30507 // Immediately update the list of matches to show the match was deleted,
508 // regardless of whether the server request actually succeeds.
509 DeleteMatchFromMatches(match);
510}
511
[email protected]bc8bb0cd2013-06-24 21:50:23512void SearchProvider::ResetSession() {
513 field_trial_triggered_in_session_ = false;
[email protected]4ab4c7c2010-11-24 04:49:34514}
515
[email protected]bc8bb0cd2013-06-24 21:50:23516SearchProvider::~SearchProvider() {
517}
518
519// static
[email protected]0085863a2013-12-06 21:19:03520void SearchProvider::RemoveStaleResults(const base::string16& input,
[email protected]bc8bb0cd2013-06-24 21:50:23521 int verbatim_relevance,
522 SuggestResults* suggest_results,
523 NavigationResults* navigation_results) {
524 DCHECK_GE(verbatim_relevance, 0);
525 // Keep pointers to the head of (the highest scoring elements of)
526 // |suggest_results| and |navigation_results|. Iterate down the lists
527 // removing non-inlineable results in order of decreasing relevance
528 // scores. Stop when the highest scoring element among those remaining
529 // is inlineable or the element is less than |verbatim_relevance|.
530 // This allows non-inlineable lower-scoring results to remain
531 // because (i) they are guaranteed to not be inlined and (ii)
532 // letting them remain reduces visual jank. For instance, as the
533 // user types the mis-spelled query "fpobar" (for foobar), the
534 // suggestion "foobar" will be suggested on every keystroke. If the
535 // SearchProvider always removes all non-inlineable results, the user will
536 // see visual jitter/jank as the result disappears and re-appears moments
537 // later as the suggest server returns results.
538 SuggestResults::iterator sug_it = suggest_results->begin();
539 NavigationResults::iterator nav_it = navigation_results->begin();
540 while ((sug_it != suggest_results->end()) ||
541 (nav_it != navigation_results->end())) {
542 const int sug_rel =
543 (sug_it != suggest_results->end()) ? sug_it->relevance() : -1;
544 const int nav_rel =
545 (nav_it != navigation_results->end()) ? nav_it->relevance() : -1;
546 if (std::max(sug_rel, nav_rel) < verbatim_relevance)
547 break;
548 if (sug_rel > nav_rel) {
549 // The current top result is a search suggestion.
550 if (sug_it->IsInlineable(input))
551 break;
552 sug_it = suggest_results->erase(sug_it);
553 } else if (sug_rel == nav_rel) {
554 // Have both results and they're tied.
555 const bool sug_inlineable = sug_it->IsInlineable(input);
556 const bool nav_inlineable = nav_it->IsInlineable(input);
557 if (!sug_inlineable)
558 sug_it = suggest_results->erase(sug_it);
559 if (!nav_inlineable)
560 nav_it = navigation_results->erase(nav_it);
561 if (sug_inlineable || nav_inlineable)
562 break;
563 } else {
564 // The current top result is a navigational suggestion.
565 if (nav_it->IsInlineable(input))
566 break;
567 nav_it = navigation_results->erase(nav_it);
568 }
569 }
570}
571
572// static
573int SearchProvider::CalculateRelevanceForKeywordVerbatim(
574 AutocompleteInput::Type type,
575 bool prefer_keyword) {
576 // This function is responsible for scoring verbatim query matches
577 // for non-extension keywords. KeywordProvider::CalculateRelevance()
578 // scores verbatim query matches for extension keywords, as well as
579 // for keyword matches (i.e., suggestions of a keyword itself, not a
580 // suggestion of a query on a keyword search engine). These two
581 // functions are currently in sync, but there's no reason we
582 // couldn't decide in the future to score verbatim matches
583 // differently for extension and non-extension keywords. If you
584 // make such a change, however, you should update this comment to
585 // describe it, so it's clear why the functions diverge.
586 if (prefer_keyword)
587 return 1500;
588 return (type == AutocompleteInput::QUERY) ? 1450 : 1100;
589}
590
initial.commit09911bf2008-07-26 23:55:29591void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27592 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55593 // Do our best to load the model as early as possible. This will reduce
594 // odds of having the model not ready when really needed (a non-empty input).
595 TemplateURLService* model = providers_.template_url_service();
596 DCHECK(model);
597 model->Load();
598
initial.commit09911bf2008-07-26 23:55:29599 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57600 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29601
[email protected]6c85aa02009-02-27 12:08:09602 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29603 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]e29249dc52012-07-19 17:33:50604 Stop(false);
initial.commit09911bf2008-07-26 23:55:29605 return;
606 }
607
[email protected]14710852013-02-05 23:45:41608 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24609 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41610 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
611 &keyword_input_);
612 if (keyword_provider == NULL)
613 keyword_input_.Clear();
614 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24615 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24616
[email protected]85b8d6f2012-05-08 20:53:47617 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07618 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24619 default_provider = NULL;
620
621 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18622 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24623
624 if (!default_provider && !keyword_provider) {
625 // No valid providers.
[email protected]e29249dc52012-07-19 17:33:50626 Stop(false);
initial.commit09911bf2008-07-26 23:55:29627 return;
628 }
629
630 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24631 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03632 base::string16 default_provider_keyword(default_provider ?
633 default_provider->keyword() : base::string16());
634 base::string16 keyword_provider_keyword(keyword_provider ?
635 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32636 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47637 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29638 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15639 if (!done_)
[email protected]e29249dc52012-07-19 17:33:50640 Stop(false);
[email protected]257ab712009-04-14 17:16:24641 }
initial.commit09911bf2008-07-26 23:55:29642
[email protected]85b8d6f2012-05-08 20:53:47643 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29644
645 if (input.text().empty()) {
646 // User typed "?" alone. Give them a placeholder result indicating what
647 // this syntax does.
[email protected]257ab712009-04-14 17:16:24648 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00649 AutocompleteMatch match;
650 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36651 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24652 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35653 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47654 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36655 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24656 matches_.push_back(match);
657 }
[email protected]e29249dc52012-07-19 17:33:50658 Stop(false);
initial.commit09911bf2008-07-26 23:55:29659 return;
660 }
661
662 input_ = input;
663
[email protected]e1290ee62013-06-26 18:31:15664 DoHistoryQuery(minimal_changes);
665 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42666 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29667}
668
[email protected]e29249dc52012-07-19 17:33:50669void SearchProvider::Stop(bool clear_cached_results) {
initial.commit09911bf2008-07-26 23:55:29670 StopSuggest();
671 done_ = true;
[email protected]e29249dc52012-07-19 17:33:50672
673 if (clear_cached_results)
[email protected]71b46152013-05-03 16:39:20674 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29675}
676
[email protected]10c2d692012-05-11 05:32:23677void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29678 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24679 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25680 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15681 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06682
[email protected]d7ad4772012-06-01 03:12:54683 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]f2916ea2013-01-26 02:20:14684 // Ensure the request succeeded and that the provider used is still available.
685 // A verbatim match cannot be generated without this provider, causing errors.
[email protected]013e9a02012-05-18 20:27:10686 const bool request_succeeded =
[email protected]bc8bb0cd2013-06-24 21:50:23687 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
688 (is_keyword ?
689 providers_.GetKeywordProviderURL() :
690 providers_.GetDefaultProviderURL());
[email protected]a0ad93ea2012-05-07 22:11:53691
692 // Record response time for suggest requests sent to Google. We care
693 // only about the common case: the Google default provider used in
694 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47695 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08696 if (!is_keyword && default_url &&
[email protected]628392f2013-08-16 00:34:45697 (TemplateURLPrepopulateData::GetEngineType(*default_url) ==
[email protected]9899a612012-08-21 23:50:04698 SEARCH_ENGINE_GOOGLE)) {
[email protected]bc8bb0cd2013-06-24 21:50:23699 const base::TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10700 base::TimeTicks::Now() - time_suggest_request_sent_;
701 if (request_succeeded) {
702 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
703 elapsed_time);
704 } else {
705 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
706 elapsed_time);
707 }
[email protected]b4cebf82008-12-29 19:59:08708 }
709
[email protected]d7ad4772012-06-01 03:12:54710 bool results_updated = false;
711 if (request_succeeded) {
[email protected]ed9b1802013-10-31 04:09:48712 const net::HttpResponseHeaders* const response_headers =
713 source->GetResponseHeaders();
714 std::string json_data;
715 source->GetResponseAsString(&json_data);
[email protected]7267ff82013-12-03 17:20:30716
[email protected]ed9b1802013-10-31 04:09:48717 // JSON is supposed to be UTF-8, but some suggest service providers send
718 // JSON files in non-UTF-8 encodings. The actual encoding is usually
719 // specified in the Content-Type header field.
720 if (response_headers) {
721 std::string charset;
722 if (response_headers->GetCharset(&charset)) {
[email protected]0085863a2013-12-06 21:19:03723 base::string16 data_16;
[email protected]ed9b1802013-10-31 04:09:48724 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
725 if (base::CodepageToUTF16(json_data, charset.c_str(),
726 base::OnStringConversionError::FAIL,
727 &data_16))
[email protected]670d3232013-12-24 17:58:58728 json_data = base::UTF16ToUTF8(data_16);
[email protected]ed9b1802013-10-31 04:09:48729 }
730 }
731
[email protected]5bcdd99d2013-12-23 18:28:30732 scoped_ptr<base::Value> data(DeserializeJsonData(json_data));
[email protected]2e8c6012013-12-03 12:00:01733 results_updated = data.get() && ParseSuggestResults(data.get(), is_keyword);
[email protected]d7ad4772012-06-01 03:12:54734 }
735
[email protected]344946a12012-12-20 12:03:42736 UpdateMatches();
[email protected]d7ad4772012-06-01 03:12:54737 if (done_ || results_updated)
738 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29739}
740
[email protected]7267ff82013-12-03 17:20:30741void SearchProvider::OnDeletionComplete(bool success,
742 SuggestionDeletionHandler* handler) {
743 RecordDeletionResult(success);
744 SuggestionDeletionHandlers::iterator it = std::find(
745 deletion_handlers_.begin(), deletion_handlers_.end(), handler);
746 DCHECK(it != deletion_handlers_.end());
747 deletion_handlers_.erase(it);
748}
749
750
751void SearchProvider::RecordDeletionResult(bool success) {
752 if (success) {
753 content::RecordAction(
754 content::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
755 } else {
756 content::RecordAction(
757 content::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
758 }
759}
760
761void SearchProvider::DeleteMatchFromMatches(const AutocompleteMatch& match) {
762 for (ACMatches::iterator i(matches_.begin()); i != matches_.end(); ++i) {
763 // Find the desired match to delete by checking the type and contents.
764 // We can't check the destination URL, because the autocomplete controller
765 // may have reformulated that. Not that while checking for matching
766 // contents works for personalized suggestions, if more match types gain
767 // deletion support, this algorithm may need to be re-examined.
768 if (i->contents == match.contents && i->type == match.type) {
769 matches_.erase(i);
770 break;
771 }
772 }
773 listener_->OnProviderUpdate(true);
774}
775
[email protected]bc8bb0cd2013-06-24 21:50:23776void SearchProvider::Run() {
777 // Start a new request with the current input.
778 suggest_results_pending_ = 0;
779 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05780
[email protected]bc8bb0cd2013-06-24 21:50:23781 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
782 providers_.GetDefaultProviderURL(), input_));
783 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
784 providers_.GetKeywordProviderURL(), keyword_input_));
785
786 // Both the above can fail if the providers have been modified or deleted
787 // since the query began.
788 if (suggest_results_pending_ == 0) {
789 UpdateDone();
790 // We only need to update the listener if we're actually done.
791 if (done_)
792 listener_->OnProviderUpdate(false);
793 }
[email protected]601858c02010-09-01 17:08:20794}
795
[email protected]8d457132010-11-04 18:13:40796void SearchProvider::DoHistoryQuery(bool minimal_changes) {
797 // The history query results are synchronous, so if minimal_changes is true,
798 // we still have the last results and don't need to do anything.
799 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29800 return;
801
[email protected]31afdf72013-09-26 04:29:36802 base::TimeTicks do_history_query_start_time(base::TimeTicks::Now());
803
[email protected]8d457132010-11-04 18:13:40804 keyword_history_results_.clear();
805 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29806
[email protected]78e5e432013-08-03 02:10:10807 if (OmniboxFieldTrial::SearchHistoryDisable(
808 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16809 return;
810
[email protected]31afdf72013-09-26 04:29:36811 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]8d457132010-11-04 18:13:40812 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10813 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]31afdf72013-09-26 04:29:36814 base::TimeTicks now(base::TimeTicks::Now());
815 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.GetHistoryServiceTime",
816 now - start_time);
817 start_time = now;
[email protected]8d457132010-11-04 18:13:40818 history::URLDatabase* url_db = history_service ?
819 history_service->InMemoryDatabase() : NULL;
[email protected]31afdf72013-09-26 04:29:36820 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.InMemoryDatabaseTime",
821 base::TimeTicks::Now() - start_time);
[email protected]8d457132010-11-04 18:13:40822 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29823 return;
824
[email protected]51124552011-07-16 01:37:10825 // Request history for both the keyword and default provider. We grab many
826 // more matches than we'll ultimately clamp to so that if there are several
827 // recent multi-word matches who scores are lowered (see
828 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
829 // matches. Note that this doesn't fix the problem entirely, but merely
830 // limits it to cases with a very large number of such multi-word matches; for
831 // now, this seems OK compared with the complexity of a real fix, which would
832 // require multiple searches and tracking of "single- vs. multi-word" in the
833 // database.
834 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47835 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
836 if (default_url) {
[email protected]31afdf72013-09-26 04:29:36837 start_time = base::TimeTicks::Now();
[email protected]85b8d6f2012-05-08 20:53:47838 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
839 num_matches, &default_history_results_);
[email protected]31afdf72013-09-26 04:29:36840 UMA_HISTOGRAM_TIMES(
841 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
842 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24843 }
[email protected]85b8d6f2012-05-08 20:53:47844 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
845 if (keyword_url) {
846 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41847 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55848 }
[email protected]31afdf72013-09-26 04:29:36849 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.DoHistoryQueryTime",
850 base::TimeTicks::Now() - do_history_query_start_time);
initial.commit09911bf2008-07-26 23:55:29851}
852
[email protected]6dc950f2012-07-16 19:49:08853void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34854 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29855 StopSuggest();
[email protected]71b46152013-05-03 16:39:20856 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29857 return;
858 }
859
860 // For the minimal_changes case, if we finished the previous query and still
861 // have its results, or are allowed to keep running it, just do that, rather
862 // than starting a new query.
863 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24864 (!default_results_.suggest_results.empty() ||
865 !default_results_.navigation_results.empty() ||
866 !keyword_results_.suggest_results.empty() ||
867 !keyword_results_.navigation_results.empty() ||
[email protected]ea3b9a502011-04-04 14:19:37868 (!done_ &&
869 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29870 return;
871
872 // We can't keep running any previous query, so halt it.
873 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42874
875 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20876 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29877
878 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37879 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29880 return;
881
[email protected]24dbf2302013-04-05 16:59:25882 // To avoid flooding the suggest server, don't send a query until at
883 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24884 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
[email protected]bc8bb0cd2013-06-24 21:50:23885 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
[email protected]515ffa942012-11-27 20:18:24886 base::TimeTicks now(base::TimeTicks::Now());
887 if (now >= next_suggest_time) {
888 Run();
889 return;
890 }
891 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29892}
893
[email protected]83c726482008-09-10 06:36:34894bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55895 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
896 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47897 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
898 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34899 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47900 ((!default_url || default_url->suggestions_url().empty()) &&
901 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34902 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
903 return false;
904
[email protected]cac59d32010-08-09 23:23:14905 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34906 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34907
[email protected]cac59d32010-08-09 23:23:14908 // FORCED_QUERY means the user is explicitly asking us to search for this, so
909 // we assume it isn't a URL and/or there isn't private data.
910 if (input_.type() == AutocompleteInput::FORCED_QUERY)
911 return true;
[email protected]83c726482008-09-10 06:36:34912
[email protected]f608ea102013-03-18 15:08:09913 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
914 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
915 // is both a waste of time and a disclosure of potentially private, local
916 // data. Other "schemes" may actually be usernames, and we don't want to send
917 // passwords. If the scheme is OK, we still need to check other cases below.
918 // If this is QUERY, then the presence of these schemes means the user
919 // explicitly typed one, and thus this is probably a URL that's being entered
920 // and happens to currently be invalid -- in which case we again want to run
921 // our checks below. Other QUERY cases are less likely to be URLs and thus we
922 // assume we're OK.
[email protected]e9a82042013-09-15 03:38:29923 if (!LowerCaseEqualsASCII(input_.scheme(), content::kHttpScheme) &&
[email protected]4654bfe2013-08-26 03:36:58924 !LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]72aa4c22013-12-01 15:09:35925 !LowerCaseEqualsASCII(input_.scheme(), content::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14926 return (input_.type() == AutocompleteInput::QUERY);
927
928 // Don't send URLs with usernames, queries or refs. Some of these are
929 // private, and the Suggest server is unlikely to have any useful results
930 // for any of them. Also don't send URLs with ports, as we may initially
931 // think that a username + password is a host + port (and we don't want to
932 // send usernames/passwords), and even if the port really is a port, the
933 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58934 // Note that we only block based on refs if the input is URL-typed, as search
935 // queries can legitimately have #s in them which the URL parser
936 // overaggressively categorizes as a url with a ref.
[email protected]cac59d32010-08-09 23:23:14937 const url_parse::Parsed& parts = input_.parts();
938 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58939 parts.query.is_nonempty() ||
940 (parts.ref.is_nonempty() && (input_.type() == AutocompleteInput::URL)))
[email protected]cac59d32010-08-09 23:23:14941 return false;
942
943 // Don't send anything for https except the hostname. Hostnames are OK
944 // because they are visible when the TCP connection is established, but the
945 // specific path may reveal private information.
[email protected]4654bfe2013-08-26 03:36:58946 if (LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36947 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14948 return false;
[email protected]83c726482008-09-10 06:36:34949
950 return true;
951}
952
initial.commit09911bf2008-07-26 23:55:29953void SearchProvider::StopSuggest() {
[email protected]7706a522012-08-16 17:42:25954 // Increment the appropriate field in the histogram by the number of
955 // pending requests that were invalidated.
956 for (int i = 0; i < suggest_results_pending_; i++)
957 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
[email protected]257ab712009-04-14 17:16:24958 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14959 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24960 // Stop any in-progress URL fetches.
961 keyword_fetcher_.reset();
962 default_fetcher_.reset();
[email protected]55ce8f12012-05-09 04:44:08963}
964
[email protected]71b46152013-05-03 16:39:20965void SearchProvider::ClearAllResults() {
[email protected]cc1526e2013-05-17 04:04:24966 keyword_results_.Clear();
967 default_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51968}
969
[email protected]71b46152013-05-03 16:39:20970void SearchProvider::RemoveAllStaleResults() {
[email protected]dc735c02013-11-12 23:23:41971 // We only need to remove stale results (which ensures the top-scoring
972 // match is inlineable) if the user is not in reorder mode. In reorder
973 // mode, the autocomplete system will reorder results to make sure the
974 // top result is inlineable.
975 const bool omnibox_will_reorder_for_legal_default_match =
976 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
977 input_.current_page_classification());
[email protected]1e1550e2013-05-02 17:37:51978 // In theory it would be better to run an algorithm like that in
979 // RemoveStaleResults(...) below that uses all four results lists
980 // and both verbatim scores at once. However, that will be much
981 // more complicated for little obvious gain. For code simplicity
982 // and ease in reasoning about the invariants involved, this code
983 // removes stales results from the keyword provider and default
984 // provider independently.
[email protected]dc735c02013-11-12 23:23:41985 if (!omnibox_will_reorder_for_legal_default_match) {
986 RemoveStaleResults(input_.text(), GetVerbatimRelevance(NULL),
987 &default_results_.suggest_results,
988 &default_results_.navigation_results);
989 if (!keyword_input_.text().empty()) {
990 RemoveStaleResults(keyword_input_.text(),
991 GetKeywordVerbatimRelevance(NULL),
992 &keyword_results_.suggest_results,
993 &keyword_results_.navigation_results);
994 }
995 }
996 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51997 // User is either in keyword mode with a blank input or out of
998 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24999 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:511000 }
[email protected]d1f0a7f2012-06-05 10:26:421001}
1002
[email protected]d1f0a7f2012-06-05 10:26:421003void SearchProvider::ApplyCalculatedRelevance() {
[email protected]cc1526e2013-05-17 04:04:241004 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
1005 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
1006 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
1007 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
[email protected]cc1526e2013-05-17 04:04:241008 default_results_.verbatim_relevance = -1;
1009 keyword_results_.verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:421010}
1011
[email protected]188b50c2013-03-28 07:19:421012void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:421013 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:421014 SuggestResult& result = (*list)[i];
1015 result.set_relevance(
1016 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
1017 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:071018 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:421019 }
1020}
1021
[email protected]188b50c2013-03-28 07:19:421022void SearchProvider::ApplyCalculatedNavigationRelevance(
1023 NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:421024 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:421025 NavigationResult& result = (*list)[i];
1026 result.set_relevance(
1027 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
1028 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:071029 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:421030 }
1031}
1032
[email protected]15fb2aa2012-05-22 22:52:591033net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:121034 int id,
[email protected]9ff91722012-09-07 05:29:121035 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:411036 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:121037 if (!template_url || template_url->suggestions_url().empty())
1038 return NULL;
1039
1040 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:411041 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
1042 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:181043 search_term_args.page_classification = input.current_page_classification();
[email protected]9ff91722012-09-07 05:29:121044 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:161045 search_term_args));
[email protected]9ff91722012-09-07 05:29:121046 if (!suggest_url.is_valid())
1047 return NULL;
[email protected]9b9fa672013-11-07 06:04:521048 // Send the current page URL if user setting and URL requirements are met and
1049 // the user is in the field trial.
1050 if (CanSendURL(current_page_url_, suggest_url, template_url,
1051 input.current_page_classification(), profile_) &&
1052 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
1053 search_term_args.current_page_url = current_page_url_.spec();
1054 // Create the suggest URL again with the current page URL.
1055 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
1056 search_term_args));
1057 }
[email protected]9ff91722012-09-07 05:29:121058
1059 suggest_results_pending_++;
1060 LogOmniboxSuggestRequest(REQUEST_SENT);
1061
1062 net::URLFetcher* fetcher =
1063 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:121064 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:341065 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:301066 // Add Chrome experiment state to the request headers.
1067 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:091068 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:301069 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
1070 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:241071 fetcher->Start();
1072 return fetcher;
1073}
1074
[email protected]5bcdd99d2013-12-23 18:28:301075scoped_ptr<base::Value> SearchProvider::DeserializeJsonData(
1076 std::string json_data) {
[email protected]2e8c6012013-12-03 12:00:011077 // The JSON response should be an array.
1078 for (size_t response_start_index = json_data.find("["), i = 0;
1079 response_start_index != std::string::npos && i < 5;
1080 response_start_index = json_data.find("[", 1), i++) {
1081 // Remove any XSSI guards to allow for JSON parsing.
1082 if (response_start_index > 0)
1083 json_data.erase(0, response_start_index);
1084
1085 JSONStringValueSerializer deserializer(json_data);
1086 deserializer.set_allow_trailing_comma(true);
1087 int error_code = 0;
[email protected]5bcdd99d2013-12-23 18:28:301088 scoped_ptr<base::Value> data(deserializer.Deserialize(&error_code, NULL));
[email protected]2e8c6012013-12-03 12:00:011089 if (error_code == 0)
1090 return data.Pass();
1091 }
[email protected]5bcdd99d2013-12-23 18:28:301092 return scoped_ptr<base::Value>();
[email protected]2e8c6012013-12-03 12:00:011093}
1094
[email protected]5bcdd99d2013-12-23 18:28:301095bool SearchProvider::ParseSuggestResults(base::Value* root_val,
1096 bool is_keyword) {
[email protected]0085863a2013-12-06 21:19:031097 base::string16 query;
[email protected]5bcdd99d2013-12-23 18:28:301098 base::ListValue* root_list = NULL;
1099 base::ListValue* results_list = NULL;
[email protected]0085863a2013-12-06 21:19:031100 const base::string16& input_text =
[email protected]14710852013-02-05 23:45:411101 is_keyword ? keyword_input_.text() : input_.text();
[email protected]d7ad4772012-06-01 03:12:541102 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
[email protected]cc1526e2013-05-17 04:04:241103 (query != input_text) || !root_list->GetList(1, &results_list))
initial.commit09911bf2008-07-26 23:55:291104 return false;
1105
[email protected]55ce8f12012-05-09 04:44:081106 // 3rd element: Description list.
[email protected]5bcdd99d2013-12-23 18:28:301107 base::ListValue* descriptions = NULL;
[email protected]d7ad4772012-06-01 03:12:541108 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:291109
[email protected]55ce8f12012-05-09 04:44:081110 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:291111
[email protected]d1f0a7f2012-06-05 10:26:421112 // Reset suggested relevance information from the default provider.
[email protected]cc1526e2013-05-17 04:04:241113 Results* results = is_keyword ? &keyword_results_ : &default_results_;
[email protected]cc1526e2013-05-17 04:04:241114 results->verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:421115
[email protected]55ce8f12012-05-09 04:44:081116 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]5bcdd99d2013-12-23 18:28:301117 base::ListValue* types = NULL;
1118 base::ListValue* relevances = NULL;
1119 base::ListValue* suggestion_details = NULL;
1120 base::DictionaryValue* extras = NULL;
[email protected]987fad782013-08-28 06:23:181121 int prefetch_index = -1;
[email protected]d1f0a7f2012-06-05 10:26:421122 if (root_list->GetDictionary(4, &extras)) {
1123 extras->GetList("google:suggesttype", &types);
1124
[email protected]eb8330d2013-06-15 00:55:081125 // Discard this list if its size does not match that of the suggestions.
1126 if (extras->GetList("google:suggestrelevance", &relevances) &&
[email protected]621ade062013-10-28 06:27:431127 (relevances->GetSize() != results_list->GetSize()))
[email protected]eb8330d2013-06-15 00:55:081128 relevances = NULL;
1129 extras->GetInteger("google:verbatimrelevance",
1130 &results->verbatim_relevance);
[email protected]618d6e62012-12-16 05:55:571131
1132 // Check if the active suggest field trial (if any) has triggered either
1133 // for the default provider or keyword provider.
1134 bool triggered = false;
1135 extras->GetBoolean("google:fieldtrialtriggered", &triggered);
1136 field_trial_triggered_ |= triggered;
1137 field_trial_triggered_in_session_ |= triggered;
[email protected]987fad782013-08-28 06:23:181138
[email protected]5bcdd99d2013-12-23 18:28:301139 base::DictionaryValue* client_data = NULL;
[email protected]987fad782013-08-28 06:23:181140 if (extras->GetDictionary("google:clientdata", &client_data) && client_data)
1141 client_data->GetInteger("phi", &prefetch_index);
1142
[email protected]621ade062013-10-28 06:27:431143 if (extras->GetList("google:suggestdetail", &suggestion_details) &&
1144 suggestion_details->GetSize() != results_list->GetSize())
1145 suggestion_details = NULL;
1146
[email protected]987fad782013-08-28 06:23:181147 // Store the metadata that came with the response in case we need to pass it
1148 // along with the prefetch query to Instant.
1149 JSONStringValueSerializer json_serializer(&results->metadata);
1150 json_serializer.Serialize(*extras);
initial.commit09911bf2008-07-26 23:55:291151 }
1152
[email protected]d1f0a7f2012-06-05 10:26:421153 // Clear the previous results now that new results are available.
[email protected]cc1526e2013-05-17 04:04:241154 results->suggest_results.clear();
1155 results->navigation_results.clear();
[email protected]d1f0a7f2012-06-05 10:26:421156
[email protected]0085863a2013-12-06 21:19:031157 base::string16 suggestion;
[email protected]d1f0a7f2012-06-05 10:26:421158 std::string type;
1159 int relevance = -1;
[email protected]3f381592013-11-05 20:43:511160 // Prohibit navsuggest in FORCED_QUERY mode. Users wants queries, not URLs.
1161 const bool allow_navsuggest =
1162 (is_keyword ? keyword_input_.type() : input_.type()) !=
1163 AutocompleteInput::FORCED_QUERY;
[email protected]621ade062013-10-28 06:27:431164 for (size_t index = 0; results_list->GetString(index, &suggestion); ++index) {
[email protected]8e81f5092010-09-29 23:19:401165 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:081166 // they make no sense at all and can cause problems in our code.
[email protected]621ade062013-10-28 06:27:431167 if (suggestion.empty())
[email protected]8e81f5092010-09-29 23:19:401168 continue;
1169
[email protected]d1f0a7f2012-06-05 10:26:421170 // Apply valid suggested relevance scores; discard invalid lists.
1171 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
1172 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:541173 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:421174 // Do not blindly trust the URL coming from the server to be valid.
[email protected]670d3232013-12-24 17:58:581175 GURL url(URLFixerUpper::FixupURL(
1176 base::UTF16ToUTF8(suggestion), std::string()));
[email protected]3f381592013-11-05 20:43:511177 if (url.is_valid() && allow_navsuggest) {
[email protected]0085863a2013-12-06 21:19:031178 base::string16 title;
[email protected]d1f0a7f2012-06-05 10:26:421179 if (descriptions != NULL)
1180 descriptions->GetString(index, &title);
[email protected]d30268a2013-06-25 22:31:071181 results->navigation_results.push_back(NavigationResult(
1182 *this, url, title, is_keyword, relevance, true));
initial.commit09911bf2008-07-26 23:55:291183 }
1184 } else {
[email protected]2c03c06b2013-12-11 20:45:021185 AutocompleteMatchType::Type match_type = GetAutocompleteMatchType(type);
[email protected]987fad782013-08-28 06:23:181186 bool should_prefetch = static_cast<int>(index) == prefetch_index;
[email protected]5bcdd99d2013-12-23 18:28:301187 base::DictionaryValue* suggestion_detail = NULL;
[email protected]0085863a2013-12-06 21:19:031188 base::string16 match_contents = suggestion;
1189 base::string16 annotation;
[email protected]621ade062013-10-28 06:27:431190 std::string suggest_query_params;
[email protected]7267ff82013-12-03 17:20:301191 std::string deletion_url;
1192
1193 if (suggestion_details) {
1194 suggestion_details->GetDictionary(index, &suggestion_detail);
1195 if (suggestion_detail) {
1196 suggestion_detail->GetString("du", &deletion_url);
[email protected]2c03c06b2013-12-11 20:45:021197 suggestion_detail->GetString("title", &match_contents) ||
1198 suggestion_detail->GetString("t", &match_contents);
1199 suggestion_detail->GetString("annotation", &annotation) ||
1200 suggestion_detail->GetString("a", &annotation);
1201 suggestion_detail->GetString("query_params", &suggest_query_params) ||
1202 suggestion_detail->GetString("q", &suggest_query_params);
[email protected]7267ff82013-12-03 17:20:301203 }
[email protected]621ade062013-10-28 06:27:431204 }
[email protected]7267ff82013-12-03 17:20:301205
[email protected]621ade062013-10-28 06:27:431206 // TODO(kochi): Improve calculator suggestion presentation.
1207 results->suggest_results.push_back(SuggestResult(
[email protected]2c03c06b2013-12-11 20:45:021208 suggestion, match_type, match_contents, annotation,
1209 suggest_query_params, deletion_url, is_keyword, relevance, true,
1210 should_prefetch));
initial.commit09911bf2008-07-26 23:55:291211 }
1212 }
1213
[email protected]43126b7192013-11-14 18:10:341214 // Ignore suggested scores for non-keyword matches in keyword mode; if the
1215 // server is allowed to score these, it could interfere with the user's
1216 // ability to get good keyword results.
1217 const bool abandon_suggested_scores =
1218 !is_keyword && !providers_.keyword_provider().empty();
1219 // Apply calculated relevance scores to suggestions if a valid list was
1220 // not provided or we're abandoning suggested scores entirely.
1221 if ((relevances == NULL) || abandon_suggested_scores) {
[email protected]cc1526e2013-05-17 04:04:241222 ApplyCalculatedSuggestRelevance(&results->suggest_results);
1223 ApplyCalculatedNavigationRelevance(&results->navigation_results);
[email protected]43126b7192013-11-14 18:10:341224 // If abandoning scores entirely, also abandon the verbatim score.
1225 if (abandon_suggested_scores)
1226 results->verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:421227 }
[email protected]43126b7192013-11-14 18:10:341228
[email protected]9dfb4d362013-04-05 02:15:121229 // Keep the result lists sorted.
1230 const CompareScoredResults comparator = CompareScoredResults();
[email protected]cc1526e2013-05-17 04:04:241231 std::stable_sort(results->suggest_results.begin(),
1232 results->suggest_results.end(),
[email protected]9dfb4d362013-04-05 02:15:121233 comparator);
[email protected]cc1526e2013-05-17 04:04:241234 std::stable_sort(results->navigation_results.begin(),
1235 results->navigation_results.end(),
[email protected]9dfb4d362013-04-05 02:15:121236 comparator);
[email protected]d1f0a7f2012-06-05 10:26:421237 return true;
initial.commit09911bf2008-07-26 23:55:291238}
1239
[email protected]344946a12012-12-20 12:03:421240void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:291241 // Convert all the results to matches and add them to a map, so we can keep
1242 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:361243 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:291244 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:231245 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:241246 int did_not_accept_keyword_suggestion =
1247 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:291248 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
1249 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:291250
[email protected]d30268a2013-06-25 22:31:071251 bool relevance_from_server;
1252 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:241253 int did_not_accept_default_suggestion =
1254 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:081255 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
1256 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:421257 if (verbatim_relevance > 0) {
[email protected]2c03c06b2013-12-11 20:45:021258 SuggestResult verbatim(
1259 input_.text(), AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
1260 input_.text(), base::string16(), std::string(), std::string(),
1261 false, verbatim_relevance, relevance_from_server, false);
[email protected]866f02e2013-12-10 17:12:051262 AddMatchToMap(verbatim, input_.text(), std::string(),
[email protected]866f02e2013-12-10 17:12:051263 did_not_accept_default_suggestion, &map);
[email protected]d1f0a7f2012-06-05 10:26:421264 }
[email protected]5423e562013-02-07 03:58:451265 if (!keyword_input_.text().empty()) {
1266 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1267 // We only create the verbatim search query match for a keyword
1268 // if it's not an extension keyword. Extension keywords are handled
1269 // in KeywordProvider::Start(). (Extensions are complicated...)
1270 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
1271 // to the keyword verbatim search query. Do not create other matches
1272 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:251273 if (keyword_url &&
1274 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:071275 bool keyword_relevance_from_server;
1276 const int keyword_verbatim_relevance =
1277 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:281278 if (keyword_verbatim_relevance > 0) {
[email protected]2c03c06b2013-12-11 20:45:021279 SuggestResult verbatim(
1280 keyword_input_.text(), AutocompleteMatchType::SEARCH_OTHER_ENGINE,
1281 keyword_input_.text(), base::string16(), std::string(),
1282 std::string(), true, keyword_verbatim_relevance,
1283 keyword_relevance_from_server, false);
[email protected]866f02e2013-12-10 17:12:051284 AddMatchToMap(verbatim, keyword_input_.text(), std::string(),
[email protected]866f02e2013-12-10 17:12:051285 did_not_accept_keyword_suggestion, &map);
[email protected]dab8d52d2013-03-05 07:35:281286 }
[email protected]5423e562013-02-07 03:58:451287 }
1288 }
[email protected]257ab712009-04-14 17:16:241289 AddHistoryResultsToMap(keyword_history_results_, true,
1290 did_not_accept_keyword_suggestion, &map);
1291 AddHistoryResultsToMap(default_history_results_, false,
1292 did_not_accept_default_suggestion, &map);
1293
[email protected]d1cb6a822013-09-18 19:43:001294 AddSuggestResultsToMap(keyword_results_.suggest_results,
1295 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:181296 AddSuggestResultsToMap(default_results_.suggest_results,
1297 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:291298
[email protected]d30268a2013-06-25 22:31:071299 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:291300 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:071301 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:291302
[email protected]d30268a2013-06-25 22:31:071303 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
1304 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:291305
[email protected]d30268a2013-06-25 22:31:071306 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
1307 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
1308 // enabled and we have server-provided (and thus hopefully more accurate)
1309 // scores for some suggestions, we allow more of those, until we reach
1310 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
1311 // whole popup).
1312 //
1313 // We will always return any verbatim matches, no matter how we obtained their
1314 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
1315 // higher-scoring matches under the conditions above.
[email protected]31afdf72013-09-26 04:29:361316 UMA_HISTOGRAM_CUSTOM_COUNTS(
1317 "Omnibox.SearchProvider.NumMatchesToSort", matches.size(), 1, 50, 20);
[email protected]d30268a2013-06-25 22:31:071318 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
1319 matches_.clear();
[email protected]3723e6e2012-06-11 21:06:561320
[email protected]d30268a2013-06-25 22:31:071321 size_t num_suggestions = 0;
1322 for (ACMatches::const_iterator i(matches.begin());
1323 (i != matches.end()) &&
1324 (matches_.size() < AutocompleteResult::kMaxMatches);
1325 ++i) {
1326 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
1327 // verbatim result, so this condition basically means "if this match is a
1328 // suggestion of some sort".
1329 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
1330 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
1331 // If we've already hit the limit on non-server-scored suggestions, and
1332 // this isn't a server-scored suggestion we can add, skip it.
1333 if ((num_suggestions >= kMaxMatches) &&
1334 (!chrome::IsInstantExtendedAPIEnabled() ||
1335 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
1336 continue;
1337 }
1338
1339 ++num_suggestions;
1340 }
1341
1342 matches_.push_back(*i);
1343 }
[email protected]31afdf72013-09-26 04:29:361344 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
1345 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:421346}
1347
[email protected]0a8718b12013-11-13 18:41:311348ACMatches::const_iterator SearchProvider::FindTopMatch(
1349 bool autocomplete_result_will_reorder_for_default_match) const {
1350 if (!autocomplete_result_will_reorder_for_default_match)
1351 return matches_.begin();
1352 ACMatches::const_iterator it = matches_.begin();
1353 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
1354 ++it;
1355 return it;
[email protected]9dfb4d362013-04-05 02:15:121356}
1357
[email protected]0a8718b12013-11-13 18:41:311358bool SearchProvider::IsTopMatchNavigationInKeywordMode(
1359 bool autocomplete_result_will_reorder_for_default_match) const {
1360 ACMatches::const_iterator first_match =
1361 FindTopMatch(autocomplete_result_will_reorder_for_default_match);
1362 return !providers_.keyword_provider().empty() &&
1363 (first_match != matches_.end()) &&
1364 (first_match->type == AutocompleteMatchType::NAVSUGGEST);
1365}
1366
[email protected]1c1e7842013-11-22 16:28:161367bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const {
1368 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1369 // If the user is not in keyword mode, return true to say that this
1370 // constraint is not violated.
1371 if (keyword_url == NULL)
1372 return true;
1373 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
1374 ++it) {
1375 if ((it->keyword == keyword_url->keyword()) &&
1376 it->allowed_to_be_default_match)
1377 return true;
1378 }
1379 return false;
1380}
1381
[email protected]0a8718b12013-11-13 18:41:311382bool SearchProvider::IsTopMatchScoreTooLow(
1383 bool autocomplete_result_will_reorder_for_default_match) const {
1384 // In reorder mode, there's no such thing as a score that's too low.
1385 if (autocomplete_result_will_reorder_for_default_match)
1386 return false;
1387
[email protected]dab8d52d2013-03-05 07:35:281388 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
1389 // rather than CalculateRelevanceForVerbatim() because the latter returns
1390 // a very low score (250) if keyword mode is active. This is because
1391 // when keyword mode is active the user probably wants the keyword matches,
1392 // not matches from the default provider. Hence, we use the version of
1393 // the function that ignores whether keyword mode is active. This allows
1394 // SearchProvider to maintain its contract with the AutocompleteController
1395 // that it will always provide an inlineable match with a reasonable
1396 // score.
1397 return matches_.front().relevance <
1398 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
[email protected]344946a12012-12-20 12:03:421399}
1400
[email protected]0a8718b12013-11-13 18:41:311401bool SearchProvider::IsTopMatchSearchWithURLInput(
1402 bool autocomplete_result_will_reorder_for_default_match) const {
1403 ACMatches::const_iterator first_match =
1404 FindTopMatch(autocomplete_result_will_reorder_for_default_match);
1405 return (input_.type() == AutocompleteInput::URL) &&
1406 (first_match != matches_.end()) &&
1407 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
1408 (first_match->type != AutocompleteMatchType::NAVSUGGEST);
[email protected]344946a12012-12-20 12:03:421409}
1410
[email protected]45f89a92013-08-12 13:41:361411bool SearchProvider::HasValidDefaultMatch(
1412 bool autocomplete_result_will_reorder_for_default_match) const {
1413 // One of the SearchProvider matches may need to be the overall default. If
1414 // AutocompleteResult is allowed to reorder matches, this means we simply
1415 // need at least one match in the list to be |allowed_to_be_default_match|.
1416 // If no reordering is possible, however, then our first match needs to have
1417 // this flag.
1418 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
1419 ++it) {
1420 if (it->allowed_to_be_default_match)
1421 return true;
1422 if (!autocomplete_result_will_reorder_for_default_match)
1423 return false;
1424 }
1425 return false;
[email protected]344946a12012-12-20 12:03:421426}
1427
1428void SearchProvider::UpdateMatches() {
[email protected]31afdf72013-09-26 04:29:361429 base::TimeTicks update_matches_start_time(base::TimeTicks::Now());
[email protected]344946a12012-12-20 12:03:421430 ConvertResultsToAutocompleteMatches();
initial.commit09911bf2008-07-26 23:55:291431
[email protected]382a0642012-06-06 06:13:521432 // Check constraints that may be violated by suggested relevances.
[email protected]344946a12012-12-20 12:03:421433 if (!matches_.empty() &&
[email protected]bc8bb0cd2013-06-24 21:50:231434 (default_results_.HasServerProvidedScores() ||
1435 keyword_results_.HasServerProvidedScores())) {
[email protected]9dfb4d362013-04-05 02:15:121436 // These blocks attempt to repair undesirable behavior by suggested
[email protected]344946a12012-12-20 12:03:421437 // relevances with minimal impact, preserving other suggested relevances.
[email protected]0a8718b12013-11-13 18:41:311438
1439 // True if the omnibox will reorder matches as necessary to make the first
1440 // one something that is allowed to be the default match.
1441 const bool omnibox_will_reorder_for_legal_default_match =
1442 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
1443 input_.current_page_classification());
1444 if (IsTopMatchNavigationInKeywordMode(
1445 omnibox_will_reorder_for_legal_default_match)) {
[email protected]9dfb4d362013-04-05 02:15:121446 // Correct the suggested relevance scores if the top match is a
1447 // navigation in keyword mode, since inlining a navigation match
[email protected]1c1e7842013-11-22 16:28:161448 // would break the user out of keyword mode. This will only be
1449 // triggered in regular (non-reorder) mode; in reorder mode,
1450 // navigation matches are marked as not allowed to be the default
1451 // match and hence IsTopMatchNavigation() will always return false.
1452 DCHECK(!omnibox_will_reorder_for_legal_default_match);
[email protected]9dfb4d362013-04-05 02:15:121453 DemoteKeywordNavigationMatchesPastTopQuery();
1454 ConvertResultsToAutocompleteMatches();
[email protected]0a8718b12013-11-13 18:41:311455 DCHECK(!IsTopMatchNavigationInKeywordMode(
1456 omnibox_will_reorder_for_legal_default_match));
[email protected]9dfb4d362013-04-05 02:15:121457 }
[email protected]1c1e7842013-11-22 16:28:161458 if (!HasKeywordDefaultMatchInKeywordMode()) {
1459 // In keyword mode, disregard the keyword verbatim suggested relevance
1460 // if necessary so there at least one keyword match that's allowed to
1461 // be the default match.
1462 keyword_results_.verbatim_relevance = -1;
1463 ConvertResultsToAutocompleteMatches();
1464 }
[email protected]0a8718b12013-11-13 18:41:311465 if (IsTopMatchScoreTooLow(omnibox_will_reorder_for_legal_default_match)) {
[email protected]1beee342012-06-19 22:22:281466 // Disregard the suggested verbatim relevance if the top score is below
1467 // the usual verbatim value. For example, a BarProvider may rely on
[email protected]45f89a92013-08-12 13:41:361468 // SearchProvider's verbatim or inlineable matches for input "foo" (all
1469 // allowed to be default match) to always outrank its own lowly-ranked
[email protected]0a8718b12013-11-13 18:41:311470 // "bar" matches that shouldn't be the default match.
[email protected]cc1526e2013-05-17 04:04:241471 default_results_.verbatim_relevance = -1;
1472 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421473 ConvertResultsToAutocompleteMatches();
[email protected]e6acd002012-06-16 22:27:471474 }
[email protected]0a8718b12013-11-13 18:41:311475 if (IsTopMatchSearchWithURLInput(
1476 omnibox_will_reorder_for_legal_default_match)) {
[email protected]e6acd002012-06-16 22:27:471477 // Disregard the suggested search and verbatim relevances if the input
1478 // type is URL and the top match is a highly-ranked search suggestion.
1479 // For example, prevent a search for "foo.com" from outranking another
1480 // provider's navigation for "foo.com" or "foo.com/url_from_history".
[email protected]cc1526e2013-05-17 04:04:241481 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
1482 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
1483 default_results_.verbatim_relevance = -1;
1484 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421485 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521486 }
[email protected]45f89a92013-08-12 13:41:361487 if (!HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match)) {
1488 // If the omnibox is not going to reorder results to put a legal default
1489 // match at the top, then this provider needs to guarantee that its top
1490 // scoring result is a legal default match (i.e., it's either a verbatim
1491 // match or inlinable). For example, input "foo" should not invoke a
1492 // search for "bar", which would happen if the "bar" search match
1493 // outranked all other matches. On the other hand, if the omnibox will
1494 // reorder matches as necessary to put a legal default match at the top,
1495 // all we need to guarantee is that SearchProvider returns a legal
1496 // default match. (The omnibox always needs at least one legal default
1497 // match, and it relies on SearchProvider to always return one.)
[email protected]344946a12012-12-20 12:03:421498 ApplyCalculatedRelevance();
1499 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521500 }
[email protected]0a8718b12013-11-13 18:41:311501 DCHECK(!IsTopMatchNavigationInKeywordMode(
1502 omnibox_will_reorder_for_legal_default_match));
[email protected]1c1e7842013-11-22 16:28:161503 DCHECK(HasKeywordDefaultMatchInKeywordMode());
[email protected]0a8718b12013-11-13 18:41:311504 DCHECK(!IsTopMatchScoreTooLow(
1505 omnibox_will_reorder_for_legal_default_match));
1506 DCHECK(!IsTopMatchSearchWithURLInput(
1507 omnibox_will_reorder_for_legal_default_match));
[email protected]45f89a92013-08-12 13:41:361508 DCHECK(HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match));
[email protected]d1f0a7f2012-06-05 10:26:421509 }
1510
[email protected]1c1e7842013-11-22 16:28:161511 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1512 if ((keyword_url != NULL) && HasKeywordDefaultMatchInKeywordMode()) {
1513 // If there is a keyword match that is allowed to be the default match,
1514 // then prohibit default provider matches from being the default match lest
1515 // such matches cause the user to break out of keyword mode.
1516 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
1517 ++it) {
1518 if (it->keyword != keyword_url->keyword())
1519 it->allowed_to_be_default_match = false;
1520 }
1521 }
1522
[email protected]31afdf72013-09-26 04:29:361523 base::TimeTicks update_starred_start_time(base::TimeTicks::Now());
[email protected]cc63dea2008-08-21 20:56:311524 UpdateStarredStateOfMatches();
[email protected]31afdf72013-09-26 04:29:361525 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateStarredTime",
1526 base::TimeTicks::Now() - update_starred_start_time);
[email protected]4ab4c7c2010-11-24 04:49:341527 UpdateDone();
[email protected]31afdf72013-09-26 04:29:361528 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateMatchesTime",
1529 base::TimeTicks::Now() - update_matches_start_time);
[email protected]257ab712009-04-14 17:16:241530}
1531
1532void SearchProvider::AddNavigationResultsToMatches(
[email protected]d30268a2013-06-25 22:31:071533 const NavigationResults& navigation_results,
1534 ACMatches* matches) {
[email protected]bc8bb0cd2013-06-24 21:50:231535 for (NavigationResults::const_iterator it = navigation_results.begin();
1536 it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:071537 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:231538 // In the absence of suggested relevance scores, use only the single
1539 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:071540 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:231541 return;
[email protected]257ab712009-04-14 17:16:241542 }
1543}
1544
1545void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
1546 bool is_keyword,
1547 int did_not_accept_suggestion,
1548 MatchMap* map) {
[email protected]51124552011-07-16 01:37:101549 if (results.empty())
1550 return;
1551
[email protected]31afdf72013-09-26 04:29:361552 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]d7ad4772012-06-01 03:12:541553 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1554 (input_.type() == AutocompleteInput::URL);
[email protected]0085863a2013-12-06 21:19:031555 const base::string16& input_text =
[email protected]14710852013-02-05 23:45:411556 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:101557 bool input_multiple_words = HasMultipleWords(input_text);
1558
[email protected]55ce8f12012-05-09 04:44:081559 SuggestResults scored_results;
1560 if (!prevent_inline_autocomplete && input_multiple_words) {
1561 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1562 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:101563 // autocompleting a multi-word, multi-visit query, and the current input is
1564 // still a prefix of it, then changing the autocompletion suddenly feels
1565 // wrong. To detect this case, first score as if only one word has been
1566 // typed, then check for a best result that is an autocompleted, multi-word
1567 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:081568 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1569 false, input_text, is_keyword);
[email protected]9dfb4d362013-04-05 02:15:121570 if ((scored_results.front().relevance() <
[email protected]55ce8f12012-05-09 04:44:081571 AutocompleteResult::kLowestDefaultScore) ||
[email protected]9dfb4d362013-04-05 02:15:121572 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:081573 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:101574 }
[email protected]55ce8f12012-05-09 04:44:081575 if (scored_results.empty())
1576 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1577 input_multiple_words, input_text,
1578 is_keyword);
1579 for (SuggestResults::const_iterator i(scored_results.begin());
1580 i != scored_results.end(); ++i) {
[email protected]866f02e2013-12-10 17:12:051581 AddMatchToMap(*i, input_text, std::string(),
[email protected]866f02e2013-12-10 17:12:051582 did_not_accept_suggestion, map);
[email protected]51124552011-07-16 01:37:101583 }
[email protected]31afdf72013-09-26 04:29:361584 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1585 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:101586}
1587
[email protected]55ce8f12012-05-09 04:44:081588SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:101589 const HistoryResults& results,
1590 bool base_prevent_inline_autocomplete,
1591 bool input_multiple_words,
[email protected]0085863a2013-12-06 21:19:031592 const base::string16& input_text,
[email protected]51124552011-07-16 01:37:101593 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:481594 AutocompleteClassifier* classifier =
1595 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:081596 SuggestResults scored_results;
[email protected]78e5e432013-08-03 02:10:101597 const bool prevent_search_history_inlining =
1598 OmniboxFieldTrial::SearchHistoryPreventInlining(
1599 input_.current_page_classification());
[email protected]257ab712009-04-14 17:16:241600 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1601 ++i) {
[email protected]51124552011-07-16 01:37:101602 // Don't autocomplete multi-word queries that have only been seen once
1603 // unless the user has typed more than one word.
1604 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1605 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
1606
[email protected]ea3b9a502011-04-04 14:19:371607 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:101608 // when typed. For example, if the user searched for "google.com" and types
1609 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1610 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:481611 // NOTE: We don't check this in the following cases:
1612 // * When inline autocomplete is disabled, we won't be inline
1613 // autocompleting this term, so we don't need to worry about confusion as
1614 // much. This also prevents calling Classify() again from inside the
1615 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:101616 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:481617 // * When the user has typed the whole term, the "what you typed" history
1618 // match will outrank us for URL-like inputs anyway, so we need not do
1619 // anything special.
[email protected]51124552011-07-16 01:37:101620 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:371621 AutocompleteMatch match;
[email protected]f608ea102013-03-18 15:08:091622 classifier->Classify(i->term, false, false, &match, NULL);
[email protected]2905f742011-10-13 03:51:581623 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:461624 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:371625 }
[email protected]51124552011-07-16 01:37:101626
[email protected]78e5e432013-08-03 02:10:101627 int relevance = CalculateRelevanceForHistory(
1628 i->time, is_keyword, !prevent_inline_autocomplete,
1629 prevent_search_history_inlining);
[email protected]2c03c06b2013-12-11 20:45:021630 scored_results.push_back(SuggestResult(
1631 i->term, AutocompleteMatchType::SEARCH_HISTORY, i->term,
1632 base::string16(), std::string(), std::string(), is_keyword, relevance,
1633 false, false));
[email protected]257ab712009-04-14 17:16:241634 }
[email protected]51124552011-07-16 01:37:101635
1636 // History returns results sorted for us. However, we may have docked some
1637 // results' scores, so things are no longer in order. Do a stable sort to get
1638 // things back in order without otherwise disturbing results with equal
1639 // scores, then force the scores to be unique, so that the order in which
1640 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081641 std::stable_sort(scored_results.begin(), scored_results.end(),
1642 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101643 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081644 for (SuggestResults::iterator i(scored_results.begin());
1645 i != scored_results.end(); ++i) {
1646 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1647 i->set_relevance(last_relevance - 1);
1648 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101649 }
1650
[email protected]55ce8f12012-05-09 04:44:081651 return scored_results;
[email protected]257ab712009-04-14 17:16:241652}
1653
[email protected]55ce8f12012-05-09 04:44:081654void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
[email protected]987fad782013-08-28 06:23:181655 const std::string& metadata,
[email protected]55ce8f12012-05-09 04:44:081656 MatchMap* map) {
[email protected]55ce8f12012-05-09 04:44:081657 for (size_t i = 0; i < results.size(); ++i) {
[email protected]188b50c2013-03-28 07:19:421658 const bool is_keyword = results[i].from_keyword_provider();
[email protected]0085863a2013-12-06 21:19:031659 const base::string16& input = is_keyword ? keyword_input_.text()
1660 : input_.text();
[email protected]2c03c06b2013-12-11 20:45:021661 AddMatchToMap(results[i], input, metadata, i, map);
[email protected]257ab712009-04-14 17:16:241662 }
initial.commit09911bf2008-07-26 23:55:291663}
1664
[email protected]d30268a2013-06-25 22:31:071665int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561666 // Use the suggested verbatim relevance score if it is non-negative (valid),
1667 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281668 // and if it won't suppress verbatim, leaving no default provider matches.
1669 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561670 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281671 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561672 // Check for results on each verbatim calculation, as results from older
1673 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231674 bool use_server_relevance =
1675 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281676 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231677 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241678 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231679 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071680 if (relevance_from_server)
1681 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231682 return use_server_relevance ?
1683 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521684}
[email protected]d1f0a7f2012-06-05 10:26:421685
[email protected]382a0642012-06-06 06:13:521686int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471687 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361688 return 250;
[email protected]dab8d52d2013-03-05 07:35:281689 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1690}
[email protected]52d08b12009-10-19 18:42:361691
[email protected]dab8d52d2013-03-05 07:35:281692int SearchProvider::
1693 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291694 switch (input_.type()) {
1695 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361696 case AutocompleteInput::QUERY:
1697 case AutocompleteInput::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131698 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291699
initial.commit09911bf2008-07-26 23:55:291700 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361701 return 850;
initial.commit09911bf2008-07-26 23:55:291702
1703 default:
1704 NOTREACHED();
1705 return 0;
1706 }
1707}
1708
[email protected]d30268a2013-06-25 22:31:071709int SearchProvider::GetKeywordVerbatimRelevance(
1710 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281711 // Use the suggested verbatim relevance score if it is non-negative (valid),
1712 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1713 // and if it won't suppress verbatim, leaving no keyword provider matches.
1714 // Otherwise, if the keyword provider returned no matches and was still able
1715 // to suppress verbatim, the user would have no search/nav matches and may be
1716 // left unable to search using their keyword provider from the omnibox.
1717 // Check for results on each verbatim calculation, as results from older
1718 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231719 bool use_server_relevance =
1720 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281721 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231722 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241723 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231724 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071725 if (relevance_from_server)
1726 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231727 return use_server_relevance ?
1728 keyword_results_.verbatim_relevance :
1729 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1730 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451731}
1732
[email protected]51124552011-07-16 01:37:101733int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231734 const base::Time& time,
[email protected]51124552011-07-16 01:37:101735 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101736 bool use_aggressive_method,
1737 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181738 // The relevance of past searches falls off over time. There are two distinct
1739 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101740 // provider that we want to score aggressively), the score is in the range
1741 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161742 // it's in the range 1200-1299). If the second equation is used the
1743 // relevance of a search 15 minutes ago is discounted 50 points, while the
1744 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231745 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421746 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101747 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181748 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101749 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181750 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161751 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101752 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161753 max_score = 1299;
1754 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181755 std::pow(elapsed_time / autocomplete_time, 2.5));
1756 }
1757 elapsed_time -= autocomplete_time;
1758 }
1759
[email protected]c3a4bd992010-08-18 20:25:011760 const int score_discount =
1761 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291762
[email protected]6c85aa02009-02-27 12:08:091763 // Don't let scores go below 0. Negative relevance scores are meaningful in
1764 // a different way.
initial.commit09911bf2008-07-26 23:55:291765 int base_score;
[email protected]51124552011-07-16 01:37:101766 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361767 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101768 else
1769 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291770 return std::max(0, base_score - score_discount);
1771}
1772
[email protected]866f02e2013-12-10 17:12:051773void SearchProvider::AddMatchToMap(const SuggestResult& result,
1774 const base::string16& input_text,
[email protected]987fad782013-08-28 06:23:181775 const std::string& metadata,
[email protected]621ade062013-10-28 06:27:431776 int accepted_suggestion,
initial.commit09911bf2008-07-26 23:55:291777 MatchMap* map) {
[email protected]c4a9d4c2013-08-10 07:06:271778 // On non-mobile, ask the instant controller for the appropriate start margin.
1779 // On mobile the start margin is unused, so leave the value as default there.
1780 int omnibox_start_margin = chrome::kDisableStartMargin;
1781#if !defined(OS_ANDROID) && !defined(IOS)
1782 if (chrome::IsInstantExtendedAPIEnabled()) {
1783 Browser* browser =
1784 chrome::FindBrowserWithProfile(profile_, chrome::GetActiveDesktop());
1785 if (browser && browser->instant_controller() &&
1786 browser->instant_controller()->instant()) {
1787 omnibox_start_margin =
1788 browser->instant_controller()->instant()->omnibox_bounds().x();
1789 }
1790 }
1791#endif // !defined(OS_ANDROID) && !defined(IOS)
1792
[email protected]866f02e2013-12-10 17:12:051793 const TemplateURL* template_url = result.from_keyword_provider() ?
[email protected]bba9e632013-06-28 22:52:191794 providers_.GetKeywordProviderURL() : providers_.GetDefaultProviderURL();
[email protected]621ade062013-10-28 06:27:431795 AutocompleteMatch match = CreateSearchSuggestion(
[email protected]575b2122014-01-03 20:35:331796 this, input_, input_text, result, template_url, accepted_suggestion,
1797 omnibox_start_margin,
[email protected]866f02e2013-12-10 17:12:051798 !result.from_keyword_provider() || providers_.default_provider().empty());
[email protected]cb86ee6f2013-04-28 16:58:151799 if (!match.destination_url.is_valid())
[email protected]85b8d6f2012-05-08 20:53:471800 return;
[email protected]a048de8a2013-10-02 18:30:061801 match.search_terms_args->bookmark_bar_pinned =
1802 profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
[email protected]d30268a2013-06-25 22:31:071803 match.RecordAdditionalInfo(kRelevanceFromServerKey,
[email protected]866f02e2013-12-10 17:12:051804 result.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181805 match.RecordAdditionalInfo(kShouldPrefetchKey,
[email protected]866f02e2013-12-10 17:12:051806 result.should_prefetch() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181807
[email protected]866f02e2013-12-10 17:12:051808 if (!result.deletion_url().empty()) {
1809 GURL url(match.destination_url.GetOrigin().Resolve(result.deletion_url()));
[email protected]f8c43e82013-12-06 12:46:231810 if (url.is_valid()) {
1811 match.RecordAdditionalInfo(kDeletionUrlKey, url.spec());
1812 match.deletable = true;
1813 }
[email protected]7267ff82013-12-03 17:20:301814 }
1815
[email protected]987fad782013-08-28 06:23:181816 // Metadata is needed only for prefetching queries.
[email protected]866f02e2013-12-10 17:12:051817 if (result.should_prefetch())
[email protected]987fad782013-08-28 06:23:181818 match.RecordAdditionalInfo(kSuggestMetadataKey, metadata);
[email protected]85b8d6f2012-05-08 20:53:471819
initial.commit09911bf2008-07-26 23:55:291820 // Try to add |match| to |map|. If a match for |query_string| is already in
1821 // |map|, replace it if |match| is more relevant.
1822 // NOTE: Keep this ToLower() call in sync with url_database.cc.
[email protected]621ade062013-10-28 06:27:431823 MatchKey match_key(
[email protected]866f02e2013-12-10 17:12:051824 std::make_pair(base::i18n::ToLower(result.suggestion()),
[email protected]621ade062013-10-28 06:27:431825 match.search_terms_args->suggest_query_params));
[email protected]bc8bb0cd2013-06-24 21:50:231826 const std::pair<MatchMap::iterator, bool> i(
[email protected]621ade062013-10-28 06:27:431827 map->insert(std::make_pair(match_key, match)));
[email protected]987fad782013-08-28 06:23:181828
[email protected]866f02e2013-12-10 17:12:051829 bool should_prefetch = result.should_prefetch();
[email protected]987fad782013-08-28 06:23:181830 if (!i.second) {
1831 // NOTE: We purposefully do a direct relevance comparison here instead of
1832 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items
1833 // added first" rather than "items alphabetically first" when the scores are
1834 // equal. The only case this matters is when a user has results with the
1835 // same score that differ only by capitalization; because the history system
1836 // returns results sorted by recency, this means we'll pick the most
1837 // recent such result even if the precision of our relevance score is too
1838 // low to distinguish the two.
1839 if (match.relevance > i.first->second.relevance) {
1840 i.first->second = match;
1841 } else if (match.keyword == i.first->second.keyword) {
1842 // Old and new matches are from the same search provider. It is okay to
1843 // record one match's prefetch data onto a different match (for the same
1844 // query string) for the following reasons:
1845 // 1. Because the suggest server only sends down a query string from which
1846 // we construct a URL, rather than sending a full URL, and because we
1847 // construct URLs from query strings in the same way every time, the URLs
1848 // for the two matches will be the same. Therefore, we won't end up
1849 // prefetching something the server didn't intend.
1850 // 2. Presumably the server sets the prefetch bit on a match it things is
1851 // sufficiently relevant that the user is likely to choose it. Surely
1852 // setting the prefetch bit on a match of even higher relevance won't
1853 // violate this assumption.
1854 should_prefetch |= ShouldPrefetch(i.first->second);
1855 i.first->second.RecordAdditionalInfo(kShouldPrefetchKey,
1856 should_prefetch ? kTrue : kFalse);
1857 if (should_prefetch)
1858 i.first->second.RecordAdditionalInfo(kSuggestMetadataKey, metadata);
1859 }
1860 }
initial.commit09911bf2008-07-26 23:55:291861}
1862
1863AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421864 const NavigationResult& navigation) {
[email protected]0085863a2013-12-06 21:19:031865 const base::string16& input = navigation.from_keyword_provider() ?
[email protected]188b50c2013-03-28 07:19:421866 keyword_input_.text() : input_.text();
[email protected]55ce8f12012-05-09 04:44:081867 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]b7f64d742013-05-21 04:04:041868 AutocompleteMatchType::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081869 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551870
1871 // First look for the user's input inside the fill_into_edit as it would be
1872 // without trimming the scheme, so we can find matches at the beginning of the
1873 // scheme.
[email protected]0085863a2013-12-06 21:19:031874 const base::string16& untrimmed_fill_into_edit = navigation.formatted_url();
[email protected]371dab12012-06-01 03:23:551875 const URLPrefix* prefix =
1876 URLPrefix::BestURLPrefix(untrimmed_fill_into_edit, input);
1877 size_t match_start = (prefix == NULL) ?
1878 untrimmed_fill_into_edit.find(input) : prefix->prefix.length();
1879 size_t inline_autocomplete_offset = (prefix == NULL) ?
[email protected]0085863a2013-12-06 21:19:031880 base::string16::npos : (match_start + input.length());
[email protected]d2445c82013-11-04 22:28:351881 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1882 (!prefix || (match_start != 0));
[email protected]371dab12012-06-01 03:23:551883
[email protected]371dab12012-06-01 03:23:551884 const std::string languages(
1885 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1886 const net::FormatUrlTypes format_types =
1887 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1888 match.fill_into_edit +=
1889 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1890 net::FormatUrl(navigation.url(), languages, format_types,
1891 net::UnescapeRule::SPACES, NULL, NULL,
1892 &inline_autocomplete_offset));
[email protected]14119032013-11-07 08:14:261893 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1894 // Otherwise, user edits to a suggestion would show non-Search results.
1895 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581896 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031897 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261898 ++inline_autocomplete_offset;
1899 }
[email protected]518024c2013-07-19 23:40:251900 if (!input_.prevent_inline_autocomplete() &&
[email protected]0085863a2013-12-06 21:19:031901 (inline_autocomplete_offset != base::string16::npos)) {
[email protected]518024c2013-07-19 23:40:251902 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
[email protected]1c1e7842013-11-22 16:28:161903 // A navsuggestion can only be the default match when there is no
1904 // keyword provider active, lest it appear first and break the user
1905 // out of keyword mode.
1906 match.allowed_to_be_default_match =
1907 (providers_.GetKeywordProviderURL() == NULL);
[email protected]518024c2013-07-19 23:40:251908 match.inline_autocompletion =
1909 match.fill_into_edit.substr(inline_autocomplete_offset);
1910 }
[email protected]371dab12012-06-01 03:23:551911
1912 match.contents = net::FormatUrl(navigation.url(), languages,
1913 format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1914 // If the first match in the untrimmed string was inside a scheme that we
1915 // trimmed, look for a subsequent match.
[email protected]0085863a2013-12-06 21:19:031916 if (match_start == base::string16::npos)
[email protected]371dab12012-06-01 03:23:551917 match_start = match.contents.find(input);
1918 // Safe if |match_start| is npos; also safe if the input is longer than the
1919 // remaining contents after |match_start|.
1920 AutocompleteMatch::ClassifyLocationInString(match_start, input.length(),
1921 match.contents.length(), ACMatchClassification::URL,
1922 &match.contents_class);
initial.commit09911bf2008-07-26 23:55:291923
[email protected]55ce8f12012-05-09 04:44:081924 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551925 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1926 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071927
1928 match.RecordAdditionalInfo(
1929 kRelevanceFromServerKey,
1930 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181931 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071932
initial.commit09911bf2008-07-26 23:55:291933 return match;
1934}
[email protected]4ab4c7c2010-11-24 04:49:341935
[email protected]9dfb4d362013-04-05 02:15:121936void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
[email protected]d519d392013-03-27 09:24:461937 // First, determine the maximum score of any keyword query match (verbatim or
1938 // query suggestion).
[email protected]d30268a2013-06-25 22:31:071939 bool relevance_from_server;
1940 int max_query_relevance = GetKeywordVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:241941 if (!keyword_results_.suggest_results.empty()) {
[email protected]d30268a2013-06-25 22:31:071942 const SuggestResult& top_keyword = keyword_results_.suggest_results.front();
1943 const int suggest_relevance = top_keyword.relevance();
1944 if (suggest_relevance > max_query_relevance) {
1945 max_query_relevance = suggest_relevance;
1946 relevance_from_server = top_keyword.relevance_from_server();
1947 } else if (suggest_relevance == max_query_relevance) {
1948 relevance_from_server |= top_keyword.relevance_from_server();
1949 }
[email protected]d519d392013-03-27 09:24:461950 }
1951 // If no query is supposed to appear, then navigational matches cannot
[email protected]9dfb4d362013-04-05 02:15:121952 // be demoted past it. Get rid of suggested relevance scores for
1953 // navsuggestions and introduce the verbatim results again. The keyword
1954 // verbatim match will outscore the navsuggest matches.
1955 if (max_query_relevance == 0) {
[email protected]cc1526e2013-05-17 04:04:241956 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
1957 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
1958 keyword_results_.verbatim_relevance = -1;
1959 default_results_.verbatim_relevance = -1;
[email protected]9dfb4d362013-04-05 02:15:121960 return;
1961 }
[email protected]d519d392013-03-27 09:24:461962 // Now we know we can enforce the minimum score constraint even after
1963 // the navigation matches are demoted. Proceed to demote the navigation
1964 // matches to enforce the query-must-come-first constraint.
[email protected]d519d392013-03-27 09:24:461965 // Cap the relevance score of all results.
[email protected]cc1526e2013-05-17 04:04:241966 for (NavigationResults::iterator it =
1967 keyword_results_.navigation_results.begin();
1968 it != keyword_results_.navigation_results.end(); ++it) {
[email protected]9dfb4d362013-04-05 02:15:121969 if (it->relevance() < max_query_relevance)
1970 return;
1971 max_query_relevance = std::max(max_query_relevance - 1, 0);
1972 it->set_relevance(max_query_relevance);
[email protected]d30268a2013-06-25 22:31:071973 it->set_relevance_from_server(relevance_from_server);
[email protected]d519d392013-03-27 09:24:461974 }
[email protected]d519d392013-03-27 09:24:461975}
1976
[email protected]4ab4c7c2010-11-24 04:49:341977void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331978 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311979 // pending, and we're not waiting on Instant.
[email protected]e1290ee62013-06-26 18:31:151980 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
[email protected]4ab4c7c2010-11-24 04:49:341981}
[email protected]7267ff82013-12-03 17:20:301982
1983bool SearchProvider::CanSendURL(
1984 const GURL& current_page_url,
1985 const GURL& suggest_url,
1986 const TemplateURL* template_url,
1987 AutocompleteInput::PageClassification page_classification,
1988 Profile* profile) {
1989 if (!current_page_url.is_valid())
1990 return false;
1991
1992 // TODO(hfung): Show Most Visited on NTP with appropriate verbatim
1993 // description when the user actively focuses on the omnibox as discussed in
1994 // crbug/305366 if Most Visited (or something similar) will launch.
1995 if ((page_classification ==
1996 AutocompleteInput::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS) ||
1997 (page_classification ==
1998 AutocompleteInput::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS))
1999 return false;
2000
2001 // Only allow HTTP URLs or HTTPS URLs for the same domain as the search
2002 // provider.
2003 if ((current_page_url.scheme() != content::kHttpScheme) &&
2004 ((current_page_url.scheme() != content::kHttpsScheme) ||
2005 !net::registry_controlled_domains::SameDomainOrHost(
2006 current_page_url, suggest_url,
2007 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES)))
2008 return false;
2009
2010 // Make sure we are sending the suggest request through HTTPS to prevent
2011 // exposing the current page URL to networks before the search provider.
2012 if (!suggest_url.SchemeIs(content::kHttpsScheme))
2013 return false;
2014
2015 // Don't run if there's no profile or in incognito mode.
2016 if (profile == NULL || profile->IsOffTheRecord())
2017 return false;
2018
2019 // Don't run if we can't get preferences or search suggest is not enabled.
2020 PrefService* prefs = profile->GetPrefs();
2021 if (!prefs->GetBoolean(prefs::kSearchSuggestEnabled))
2022 return false;
2023
2024 // Only make the request if we know that the provider supports zero suggest
2025 // (currently only the prepopulated Google provider).
2026 if (template_url == NULL || !template_url->SupportsReplacement() ||
2027 TemplateURLPrepopulateData::GetEngineType(*template_url) !=
2028 SEARCH_ENGINE_GOOGLE)
2029 return false;
2030
2031 // Check field trials and settings allow sending the URL on suggest requests.
2032 ProfileSyncService* service =
2033 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile);
2034 browser_sync::SyncPrefs sync_prefs(prefs);
2035 if (!OmniboxFieldTrial::InZeroSuggestFieldTrial() ||
2036 service == NULL ||
2037 !service->IsSyncEnabledAndLoggedIn() ||
2038 !sync_prefs.GetPreferredDataTypes(syncer::UserTypes()).Has(
2039 syncer::PROXY_TABS) ||
2040 service->GetEncryptedDataTypes().Has(syncer::SESSIONS))
2041 return false;
2042
2043 return true;
2044}