| OLD | NEW |
| 1 // Copyright 2012 The Chromium Authors. All rights reserved. | 1 // Copyright 2012 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 | 4 |
| 5 #include "chrome/browser/autocomplete/search_provider.h" | 5 #include "chrome/browser/autocomplete/search_provider.h" |
| 6 | 6 |
| 7 #include <algorithm> | 7 #include <algorithm> |
| 8 #include <cmath> | 8 #include <cmath> |
| 9 | 9 |
| 10 #include "base/callback.h" | |
| 11 #include "base/i18n/break_iterator.h" | 10 #include "base/i18n/break_iterator.h" |
| 12 #include "base/i18n/case_conversion.h" | |
| 13 #include "base/i18n/icu_string_conversions.h" | |
| 14 #include "base/json/json_string_value_serializer.h" | |
| 15 #include "base/message_loop/message_loop.h" | |
| 16 #include "base/metrics/histogram.h" | 11 #include "base/metrics/histogram.h" |
| 17 #include "base/prefs/pref_service.h" | 12 #include "base/prefs/pref_service.h" |
| 18 #include "base/strings/string16.h" | 13 #include "base/strings/string16.h" |
| 19 #include "base/strings/string_util.h" | 14 #include "base/strings/string_util.h" |
| 20 #include "base/strings/utf_string_conversions.h" | 15 #include "base/strings/utf_string_conversions.h" |
| 16 #include "base/time/time.h" |
| 17 #include "base/values.h" |
| 21 #include "chrome/browser/autocomplete/autocomplete_classifier.h" | 18 #include "chrome/browser/autocomplete/autocomplete_classifier.h" |
| 22 #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h" | 19 #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h" |
| 20 #include "chrome/browser/autocomplete/autocomplete_input.h" |
| 23 #include "chrome/browser/autocomplete/autocomplete_match.h" | 21 #include "chrome/browser/autocomplete/autocomplete_match.h" |
| 24 #include "chrome/browser/autocomplete/autocomplete_provider_listener.h" | 22 #include "chrome/browser/autocomplete/autocomplete_provider_listener.h" |
| 25 #include "chrome/browser/autocomplete/autocomplete_result.h" | 23 #include "chrome/browser/autocomplete/autocomplete_result.h" |
| 24 #include "chrome/browser/autocomplete/base_search_provider.h" |
| 26 #include "chrome/browser/autocomplete/keyword_provider.h" | 25 #include "chrome/browser/autocomplete/keyword_provider.h" |
| 27 #include "chrome/browser/autocomplete/url_prefix.h" | 26 #include "chrome/browser/autocomplete/url_prefix.h" |
| 28 #include "chrome/browser/google/google_util.h" | |
| 29 #include "chrome/browser/history/history_service.h" | 27 #include "chrome/browser/history/history_service.h" |
| 30 #include "chrome/browser/history/history_service_factory.h" | 28 #include "chrome/browser/history/history_service_factory.h" |
| 31 #include "chrome/browser/history/in_memory_database.h" | 29 #include "chrome/browser/history/in_memory_database.h" |
| 30 #include "chrome/browser/history/url_database.h" |
| 32 #include "chrome/browser/metrics/variations/variations_http_header_provider.h" | 31 #include "chrome/browser/metrics/variations/variations_http_header_provider.h" |
| 33 #include "chrome/browser/omnibox/omnibox_field_trial.h" | 32 #include "chrome/browser/omnibox/omnibox_field_trial.h" |
| 34 #include "chrome/browser/profiles/profile.h" | 33 #include "chrome/browser/profiles/profile.h" |
| 35 #include "chrome/browser/search/search.h" | 34 #include "chrome/browser/search/search.h" |
| 35 #include "chrome/browser/search_engines/template_url.h" |
| 36 #include "chrome/browser/search_engines/template_url_prepopulate_data.h" | 36 #include "chrome/browser/search_engines/template_url_prepopulate_data.h" |
| 37 #include "chrome/browser/search_engines/template_url_service.h" | 37 #include "chrome/browser/search_engines/template_url_service.h" |
| 38 #include "chrome/browser/search_engines/template_url_service_factory.h" | 38 #include "chrome/browser/search_engines/template_url_service_factory.h" |
| 39 #include "chrome/browser/sync/profile_sync_service.h" | |
| 40 #include "chrome/browser/sync/profile_sync_service_factory.h" | |
| 41 #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" | |
| 45 #include "chrome/common/net/url_fixer_upper.h" | |
| 46 #include "chrome/common/pref_names.h" | 39 #include "chrome/common/pref_names.h" |
| 47 #include "chrome/common/url_constants.h" | 40 #include "chrome/common/url_constants.h" |
| 48 #include "content/public/browser/user_metrics.h" | 41 #include "content/public/browser/user_metrics.h" |
| 49 #include "grit/generated_resources.h" | 42 #include "grit/generated_resources.h" |
| 50 #include "net/base/escape.h" | 43 #include "net/base/escape.h" |
| 51 #include "net/base/load_flags.h" | 44 #include "net/base/load_flags.h" |
| 52 #include "net/base/net_util.h" | 45 #include "net/base/net_util.h" |
| 53 #include "net/base/registry_controlled_domains/registry_controlled_domain.h" | |
| 54 #include "net/http/http_request_headers.h" | 46 #include "net/http/http_request_headers.h" |
| 55 #include "net/http/http_response_headers.h" | |
| 56 #include "net/url_request/url_fetcher.h" | 47 #include "net/url_request/url_fetcher.h" |
| 57 #include "net/url_request/url_request_status.h" | |
| 58 #include "ui/base/l10n/l10n_util.h" | 48 #include "ui/base/l10n/l10n_util.h" |
| 59 #include "url/url_util.h" | 49 #include "url/url_util.h" |
| 60 | 50 |
| 61 | |
| 62 // Helpers -------------------------------------------------------------------- | 51 // Helpers -------------------------------------------------------------------- |
| 63 | 52 |
| 64 namespace { | 53 namespace { |
| 65 | 54 |
| 66 // We keep track in a histogram how many suggest requests we send, how | 55 // 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 | 56 // many suggest requests we invalidate (e.g., due to a user typing |
| 68 // another character), and how many replies we receive. | 57 // another character), and how many replies we receive. |
| 69 // *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! *** | 58 // *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! *** |
| 70 // (excluding the end-of-list enum value) | 59 // (excluding the end-of-list enum value) |
| 71 // We do not want values of existing enums to change or else it screws | 60 // We do not want values of existing enums to change or else it screws |
| 72 // up the statistics. | 61 // up the statistics. |
| 73 enum SuggestRequestsHistogramValue { | 62 enum SuggestRequestsHistogramValue { |
| 74 REQUEST_SENT = 1, | 63 REQUEST_SENT = 1, |
| 75 REQUEST_INVALIDATED, | 64 REQUEST_INVALIDATED, |
| 76 REPLY_RECEIVED, | 65 REPLY_RECEIVED, |
| 77 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE | 66 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE |
| 78 }; | 67 }; |
| 79 | 68 |
| 80 // The verbatim score for an input which is not an URL. | 69 // The verbatim score for an input which is not an URL. |
| 81 const int kNonURLVerbatimRelevance = 1300; | 70 const int kNonURLVerbatimRelevance = 1300; |
| 82 | 71 |
| 83 // Increments the appropriate value in the histogram by one. | 72 // Increments the appropriate value in the histogram by one. |
| 84 void LogOmniboxSuggestRequest( | 73 void LogOmniboxSuggestRequest(SuggestRequestsHistogramValue request_value) { |
| 85 SuggestRequestsHistogramValue request_value) { | |
| 86 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value, | 74 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value, |
| 87 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE); | 75 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE); |
| 88 } | 76 } |
| 89 | 77 |
| 90 bool HasMultipleWords(const base::string16& text) { | 78 bool HasMultipleWords(const base::string16& text) { |
| 91 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD); | 79 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD); |
| 92 bool found_word = false; | 80 bool found_word = false; |
| 93 if (i.Init()) { | 81 if (i.Init()) { |
| 94 while (i.Advance()) { | 82 while (i.Advance()) { |
| 95 if (i.IsWord()) { | 83 if (i.IsWord()) { |
| 96 if (found_word) | 84 if (found_word) |
| 97 return true; | 85 return true; |
| 98 found_word = true; | 86 found_word = true; |
| 99 } | 87 } |
| 100 } | 88 } |
| 101 } | 89 } |
| 102 return false; | 90 return false; |
| 103 } | 91 } |
| 104 | 92 |
| 105 AutocompleteMatchType::Type GetAutocompleteMatchType(const std::string& type) { | |
| 106 if (type == "ENTITY") | |
| 107 return AutocompleteMatchType::SEARCH_SUGGEST_ENTITY; | |
| 108 if (type == "INFINITE") | |
| 109 return AutocompleteMatchType::SEARCH_SUGGEST_INFINITE; | |
| 110 if (type == "PERSONALIZED") | |
| 111 return AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED; | |
| 112 if (type == "PROFILE") | |
| 113 return AutocompleteMatchType::SEARCH_SUGGEST_PROFILE; | |
| 114 return AutocompleteMatchType::SEARCH_SUGGEST; | |
| 115 } | |
| 116 | |
| 117 } // namespace | 93 } // namespace |
| 118 | 94 |
| 119 | |
| 120 // SuggestionDeletionHandler ------------------------------------------------- | |
| 121 | |
| 122 // This class handles making requests to the server in order to delete | |
| 123 // personalized suggestions. | |
| 124 class SuggestionDeletionHandler : public net::URLFetcherDelegate { | |
| 125 public: | |
| 126 typedef base::Callback<void(bool, SuggestionDeletionHandler*)> | |
| 127 DeletionCompletedCallback; | |
| 128 | |
| 129 SuggestionDeletionHandler( | |
| 130 const std::string& deletion_url, | |
| 131 Profile* profile, | |
| 132 const DeletionCompletedCallback& callback); | |
| 133 | |
| 134 virtual ~SuggestionDeletionHandler(); | |
| 135 | |
| 136 private: | |
| 137 // net::URLFetcherDelegate: | |
| 138 virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE; | |
| 139 | |
| 140 scoped_ptr<net::URLFetcher> deletion_fetcher_; | |
| 141 DeletionCompletedCallback callback_; | |
| 142 | |
| 143 DISALLOW_COPY_AND_ASSIGN(SuggestionDeletionHandler); | |
| 144 }; | |
| 145 | |
| 146 | |
| 147 SuggestionDeletionHandler::SuggestionDeletionHandler( | |
| 148 const std::string& deletion_url, | |
| 149 Profile* profile, | |
| 150 const DeletionCompletedCallback& callback) : callback_(callback) { | |
| 151 GURL url(deletion_url); | |
| 152 DCHECK(url.is_valid()); | |
| 153 | |
| 154 deletion_fetcher_.reset(net::URLFetcher::Create( | |
| 155 SearchProvider::kDeletionURLFetcherID, | |
| 156 url, | |
| 157 net::URLFetcher::GET, | |
| 158 this)); | |
| 159 deletion_fetcher_->SetRequestContext(profile->GetRequestContext()); | |
| 160 deletion_fetcher_->Start(); | |
| 161 }; | |
| 162 | |
| 163 SuggestionDeletionHandler::~SuggestionDeletionHandler() { | |
| 164 }; | |
| 165 | |
| 166 void SuggestionDeletionHandler::OnURLFetchComplete( | |
| 167 const net::URLFetcher* source) { | |
| 168 DCHECK(source == deletion_fetcher_.get()); | |
| 169 callback_.Run( | |
| 170 source->GetStatus().is_success() && (source->GetResponseCode() == 200), | |
| 171 this); | |
| 172 }; | |
| 173 | |
| 174 | |
| 175 // SearchProvider::Providers -------------------------------------------------- | 95 // SearchProvider::Providers -------------------------------------------------- |
| 176 | 96 |
| 177 SearchProvider::Providers::Providers(TemplateURLService* template_url_service) | 97 SearchProvider::Providers::Providers(TemplateURLService* template_url_service) |
| 178 : template_url_service_(template_url_service) { | 98 : template_url_service_(template_url_service) { |
| 179 } | 99 } |
| 180 | 100 |
| 181 const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const { | 101 const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const { |
| 182 return default_provider_.empty() ? NULL : | 102 return default_provider_.empty() |
| 183 template_url_service_->GetTemplateURLForKeyword(default_provider_); | 103 ? NULL |
| 104 : template_url_service_->GetTemplateURLForKeyword( |
| 105 default_provider_); |
| 184 } | 106 } |
| 185 | 107 |
| 186 const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const { | 108 const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const { |
| 187 return keyword_provider_.empty() ? NULL : | 109 return keyword_provider_.empty() |
| 188 template_url_service_->GetTemplateURLForKeyword(keyword_provider_); | 110 ? NULL |
| 111 : template_url_service_->GetTemplateURLForKeyword( |
| 112 keyword_provider_); |
| 189 } | 113 } |
| 190 | 114 |
| 191 | |
| 192 // SearchProvider::Result ----------------------------------------------------- | |
| 193 | |
| 194 SearchProvider::Result::Result(bool from_keyword_provider, | |
| 195 int relevance, | |
| 196 bool relevance_from_server) | |
| 197 : from_keyword_provider_(from_keyword_provider), | |
| 198 relevance_(relevance), | |
| 199 relevance_from_server_(relevance_from_server) { | |
| 200 } | |
| 201 | |
| 202 SearchProvider::Result::~Result() { | |
| 203 } | |
| 204 | |
| 205 | |
| 206 // SearchProvider::SuggestResult ---------------------------------------------- | |
| 207 | |
| 208 SearchProvider::SuggestResult::SuggestResult( | |
| 209 const base::string16& suggestion, | |
| 210 AutocompleteMatchType::Type type, | |
| 211 const base::string16& match_contents, | |
| 212 const base::string16& annotation, | |
| 213 const std::string& suggest_query_params, | |
| 214 const std::string& deletion_url, | |
| 215 bool from_keyword_provider, | |
| 216 int relevance, | |
| 217 bool relevance_from_server, | |
| 218 bool should_prefetch, | |
| 219 const base::string16& input_text) | |
| 220 : Result(from_keyword_provider, relevance, relevance_from_server), | |
| 221 suggestion_(suggestion), | |
| 222 type_(type), | |
| 223 annotation_(annotation), | |
| 224 suggest_query_params_(suggest_query_params), | |
| 225 deletion_url_(deletion_url), | |
| 226 should_prefetch_(should_prefetch) { | |
| 227 match_contents_ = match_contents; | |
| 228 DCHECK(!match_contents_.empty()); | |
| 229 ClassifyMatchContents(true, input_text); | |
| 230 } | |
| 231 | |
| 232 SearchProvider::SuggestResult::~SuggestResult() { | |
| 233 } | |
| 234 | |
| 235 void SearchProvider::SuggestResult::ClassifyMatchContents( | |
| 236 const bool allow_bolding_all, | |
| 237 const base::string16& input_text) { | |
| 238 size_t input_position = match_contents_.find(input_text); | |
| 239 if (!allow_bolding_all && (input_position == base::string16::npos)) { | |
| 240 // Bail if the code below to update the bolding would bold the whole | |
| 241 // string. Note that the string may already be entirely bolded; if | |
| 242 // so, leave it as is. | |
| 243 return; | |
| 244 } | |
| 245 match_contents_class_.clear(); | |
| 246 // We do intra-string highlighting for suggestions - the suggested segment | |
| 247 // will be highlighted, e.g. for input_text = "you" the suggestion may be | |
| 248 // "youtube", so we'll bold the "tube" section: you*tube*. | |
| 249 if (input_text != match_contents_) { | |
| 250 if (input_position == base::string16::npos) { | |
| 251 // The input text is not a substring of the query string, e.g. input | |
| 252 // text is "slasdot" and the query string is "slashdot", so we bold the | |
| 253 // whole thing. | |
| 254 match_contents_class_.push_back(ACMatchClassification( | |
| 255 0, ACMatchClassification::MATCH)); | |
| 256 } else { | |
| 257 // We don't iterate over the string here annotating all matches because | |
| 258 // it looks odd to have every occurrence of a substring that may be as | |
| 259 // short as a single character highlighted in a query suggestion result, | |
| 260 // e.g. for input text "s" and query string "southwest airlines", it | |
| 261 // looks odd if both the first and last s are highlighted. | |
| 262 if (input_position != 0) { | |
| 263 match_contents_class_.push_back(ACMatchClassification( | |
| 264 0, ACMatchClassification::MATCH)); | |
| 265 } | |
| 266 match_contents_class_.push_back( | |
| 267 ACMatchClassification(input_position, ACMatchClassification::NONE)); | |
| 268 size_t next_fragment_position = input_position + input_text.length(); | |
| 269 if (next_fragment_position < match_contents_.length()) { | |
| 270 match_contents_class_.push_back(ACMatchClassification( | |
| 271 next_fragment_position, ACMatchClassification::MATCH)); | |
| 272 } | |
| 273 } | |
| 274 } else { | |
| 275 // Otherwise, match_contents_ is a verbatim (what-you-typed) match, either | |
| 276 // for the default provider or a keyword search provider. | |
| 277 match_contents_class_.push_back(ACMatchClassification( | |
| 278 0, ACMatchClassification::NONE)); | |
| 279 } | |
| 280 } | |
| 281 | |
| 282 bool SearchProvider::SuggestResult::IsInlineable( | |
| 283 const base::string16& input) const { | |
| 284 return StartsWith(suggestion_, input, false); | |
| 285 } | |
| 286 | |
| 287 int SearchProvider::SuggestResult::CalculateRelevance( | |
| 288 const AutocompleteInput& input, | |
| 289 bool keyword_provider_requested) const { | |
| 290 if (!from_keyword_provider_ && keyword_provider_requested) | |
| 291 return 100; | |
| 292 return ((input.type() == AutocompleteInput::URL) ? 300 : 600); | |
| 293 } | |
| 294 | |
| 295 | |
| 296 // SearchProvider::NavigationResult ------------------------------------------- | |
| 297 | |
| 298 SearchProvider::NavigationResult::NavigationResult( | |
| 299 const AutocompleteProvider& provider, | |
| 300 const GURL& url, | |
| 301 const base::string16& description, | |
| 302 bool from_keyword_provider, | |
| 303 int relevance, | |
| 304 bool relevance_from_server, | |
| 305 const base::string16& input_text, | |
| 306 const std::string& languages) | |
| 307 : Result(from_keyword_provider, relevance, relevance_from_server), | |
| 308 url_(url), | |
| 309 formatted_url_(AutocompleteInput::FormattedStringWithEquivalentMeaning( | |
| 310 url, provider.StringForURLDisplay(url, true, false))), | |
| 311 description_(description) { | |
| 312 DCHECK(url_.is_valid()); | |
| 313 CalculateAndClassifyMatchContents(true, input_text, languages); | |
| 314 } | |
| 315 | |
| 316 SearchProvider::NavigationResult::~NavigationResult() { | |
| 317 } | |
| 318 | |
| 319 void SearchProvider::NavigationResult::CalculateAndClassifyMatchContents( | |
| 320 const bool allow_bolding_nothing, | |
| 321 const base::string16& input_text, | |
| 322 const std::string& languages) { | |
| 323 // First look for the user's input inside the formatted url as it would be | |
| 324 // without trimming the scheme, so we can find matches at the beginning of the | |
| 325 // scheme. | |
| 326 const URLPrefix* prefix = | |
| 327 URLPrefix::BestURLPrefix(formatted_url_, input_text); | |
| 328 size_t match_start = (prefix == NULL) ? | |
| 329 formatted_url_.find(input_text) : prefix->prefix.length(); | |
| 330 bool trim_http = !AutocompleteInput::HasHTTPScheme(input_text) && | |
| 331 (!prefix || (match_start != 0)); | |
| 332 const net::FormatUrlTypes format_types = | |
| 333 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP); | |
| 334 | |
| 335 base::string16 match_contents = net::FormatUrl(url_, languages, format_types, | |
| 336 net::UnescapeRule::SPACES, NULL, NULL, &match_start); | |
| 337 // If the first match in the untrimmed string was inside a scheme that we | |
| 338 // trimmed, look for a subsequent match. | |
| 339 if (match_start == base::string16::npos) | |
| 340 match_start = match_contents.find(input_text); | |
| 341 // Update |match_contents_| and |match_contents_class_| if it's allowed. | |
| 342 if (allow_bolding_nothing || (match_start != base::string16::npos)) { | |
| 343 match_contents_ = match_contents; | |
| 344 // Safe if |match_start| is npos; also safe if the input is longer than the | |
| 345 // remaining contents after |match_start|. | |
| 346 AutocompleteMatch::ClassifyLocationInString(match_start, | |
| 347 input_text.length(), match_contents_.length(), | |
| 348 ACMatchClassification::URL, &match_contents_class_); | |
| 349 } | |
| 350 } | |
| 351 | |
| 352 bool SearchProvider::NavigationResult::IsInlineable( | |
| 353 const base::string16& input) const { | |
| 354 return URLPrefix::BestURLPrefix(formatted_url_, input) != NULL; | |
| 355 } | |
| 356 | |
| 357 int SearchProvider::NavigationResult::CalculateRelevance( | |
| 358 const AutocompleteInput& input, | |
| 359 bool keyword_provider_requested) const { | |
| 360 return (from_keyword_provider_ || !keyword_provider_requested) ? 800 : 150; | |
| 361 } | |
| 362 | |
| 363 | |
| 364 // SearchProvider::CompareScoredResults --------------------------------------- | 115 // SearchProvider::CompareScoredResults --------------------------------------- |
| 365 | 116 |
| 366 class SearchProvider::CompareScoredResults { | 117 class SearchProvider::CompareScoredResults { |
| 367 public: | 118 public: |
| 368 bool operator()(const Result& a, const Result& b) { | 119 bool operator()(const Result& a, const Result& b) { |
| 369 // Sort in descending relevance order. | 120 // Sort in descending relevance order. |
| 370 return a.relevance() > b.relevance(); | 121 return a.relevance() > b.relevance(); |
| 371 } | 122 } |
| 372 }; | 123 }; |
| 373 | 124 |
| 374 | |
| 375 // SearchProvider::Results ---------------------------------------------------- | |
| 376 | |
| 377 SearchProvider::Results::Results() : verbatim_relevance(-1) { | |
| 378 } | |
| 379 | |
| 380 SearchProvider::Results::~Results() { | |
| 381 } | |
| 382 | |
| 383 void SearchProvider::Results::Clear() { | |
| 384 suggest_results.clear(); | |
| 385 navigation_results.clear(); | |
| 386 verbatim_relevance = -1; | |
| 387 metadata.clear(); | |
| 388 } | |
| 389 | |
| 390 bool SearchProvider::Results::HasServerProvidedScores() const { | |
| 391 if (verbatim_relevance >= 0) | |
| 392 return true; | |
| 393 | |
| 394 // Right now either all results of one type will be server-scored or they will | |
| 395 // all be locally scored, but in case we change this later, we'll just check | |
| 396 // them all. | |
| 397 for (SuggestResults::const_iterator i(suggest_results.begin()); | |
| 398 i != suggest_results.end(); ++i) { | |
| 399 if (i->relevance_from_server()) | |
| 400 return true; | |
| 401 } | |
| 402 for (NavigationResults::const_iterator i(navigation_results.begin()); | |
| 403 i != navigation_results.end(); ++i) { | |
| 404 if (i->relevance_from_server()) | |
| 405 return true; | |
| 406 } | |
| 407 | |
| 408 return false; | |
| 409 } | |
| 410 | |
| 411 | |
| 412 // SearchProvider ------------------------------------------------------------- | 125 // SearchProvider ------------------------------------------------------------- |
| 413 | 126 |
| 414 // static | 127 // static |
| 415 const int SearchProvider::kDefaultProviderURLFetcherID = 1; | 128 const int SearchProvider::kDefaultProviderURLFetcherID = 1; |
| 416 const int SearchProvider::kKeywordProviderURLFetcherID = 2; | 129 const int SearchProvider::kKeywordProviderURLFetcherID = 2; |
| 417 const int SearchProvider::kDeletionURLFetcherID = 3; | |
| 418 int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100; | 130 int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100; |
| 419 const char SearchProvider::kRelevanceFromServerKey[] = "relevance_from_server"; | |
| 420 const char SearchProvider::kShouldPrefetchKey[] = "should_prefetch"; | |
| 421 const char SearchProvider::kSuggestMetadataKey[] = "suggest_metadata"; | |
| 422 const char SearchProvider::kDeletionUrlKey[] = "deletion_url"; | |
| 423 const char SearchProvider::kTrue[] = "true"; | |
| 424 const char SearchProvider::kFalse[] = "false"; | |
| 425 | 131 |
| 426 SearchProvider::SearchProvider(AutocompleteProviderListener* listener, | 132 SearchProvider::SearchProvider(AutocompleteProviderListener* listener, |
| 427 Profile* profile) | 133 Profile* profile) |
| 428 : AutocompleteProvider(listener, profile, | 134 : BaseSearchProvider(listener, profile, AutocompleteProvider::TYPE_SEARCH), |
| 429 AutocompleteProvider::TYPE_SEARCH), | 135 providers_(TemplateURLServiceFactory::GetForProfile(profile)) {} |
| 430 providers_(TemplateURLServiceFactory::GetForProfile(profile)), | |
| 431 suggest_results_pending_(0), | |
| 432 field_trial_triggered_(false), | |
| 433 field_trial_triggered_in_session_(false) { | |
| 434 } | |
| 435 | |
| 436 // static | |
| 437 AutocompleteMatch SearchProvider::CreateSearchSuggestion( | |
| 438 AutocompleteProvider* autocomplete_provider, | |
| 439 const AutocompleteInput& input, | |
| 440 const base::string16& input_text, | |
| 441 const SuggestResult& suggestion, | |
| 442 const TemplateURL* template_url, | |
| 443 int accepted_suggestion, | |
| 444 int omnibox_start_margin, | |
| 445 bool append_extra_query_params) { | |
| 446 AutocompleteMatch match(autocomplete_provider, suggestion.relevance(), false, | |
| 447 suggestion.type()); | |
| 448 | |
| 449 if (!template_url) | |
| 450 return match; | |
| 451 match.keyword = template_url->keyword(); | |
| 452 match.contents = suggestion.match_contents(); | |
| 453 match.contents_class = suggestion.match_contents_class(); | |
| 454 | |
| 455 if (!suggestion.annotation().empty()) | |
| 456 match.description = suggestion.annotation(); | |
| 457 | |
| 458 match.allowed_to_be_default_match = | |
| 459 (input_text == suggestion.match_contents()); | |
| 460 | |
| 461 // When the user forced a query, we need to make sure all the fill_into_edit | |
| 462 // values preserve that property. Otherwise, if the user starts editing a | |
| 463 // suggestion, non-Search results will suddenly appear. | |
| 464 if (input.type() == AutocompleteInput::FORCED_QUERY) | |
| 465 match.fill_into_edit.assign(base::ASCIIToUTF16("?")); | |
| 466 if (suggestion.from_keyword_provider()) | |
| 467 match.fill_into_edit.append(match.keyword + base::char16(' ')); | |
| 468 if (!input.prevent_inline_autocomplete() && | |
| 469 StartsWith(suggestion.suggestion(), input_text, false)) { | |
| 470 match.inline_autocompletion = | |
| 471 suggestion.suggestion().substr(input_text.length()); | |
| 472 match.allowed_to_be_default_match = true; | |
| 473 } | |
| 474 match.fill_into_edit.append(suggestion.suggestion()); | |
| 475 | |
| 476 const TemplateURLRef& search_url = template_url->url_ref(); | |
| 477 DCHECK(search_url.SupportsReplacement()); | |
| 478 match.search_terms_args.reset( | |
| 479 new TemplateURLRef::SearchTermsArgs(suggestion.suggestion())); | |
| 480 match.search_terms_args->original_query = input_text; | |
| 481 match.search_terms_args->accepted_suggestion = accepted_suggestion; | |
| 482 match.search_terms_args->omnibox_start_margin = omnibox_start_margin; | |
| 483 match.search_terms_args->suggest_query_params = | |
| 484 suggestion.suggest_query_params(); | |
| 485 match.search_terms_args->append_extra_query_params = | |
| 486 append_extra_query_params; | |
| 487 // This is the destination URL sans assisted query stats. This must be set | |
| 488 // so the AutocompleteController can properly de-dupe; the controller will | |
| 489 // eventually overwrite it before it reaches the user. | |
| 490 match.destination_url = | |
| 491 GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get())); | |
| 492 | |
| 493 // Search results don't look like URLs. | |
| 494 match.transition = suggestion.from_keyword_provider() ? | |
| 495 content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED; | |
| 496 | |
| 497 return match; | |
| 498 } | |
| 499 | |
| 500 // static | |
| 501 bool SearchProvider::ShouldPrefetch(const AutocompleteMatch& match) { | |
| 502 return match.GetAdditionalInfo(kShouldPrefetchKey) == kTrue; | |
| 503 } | |
| 504 | 136 |
| 505 // static | 137 // static |
| 506 std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) { | 138 std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) { |
| 507 return match.GetAdditionalInfo(kSuggestMetadataKey); | 139 return match.GetAdditionalInfo(kSuggestMetadataKey); |
| 508 } | 140 } |
| 509 | 141 |
| 510 void SearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const { | |
| 511 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo()); | |
| 512 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back(); | |
| 513 new_entry.set_provider(AsOmniboxEventProviderType()); | |
| 514 new_entry.set_provider_done(done_); | |
| 515 std::vector<uint32> field_trial_hashes; | |
| 516 OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(&field_trial_hashes); | |
| 517 for (size_t i = 0; i < field_trial_hashes.size(); ++i) { | |
| 518 if (field_trial_triggered_) | |
| 519 new_entry.mutable_field_trial_triggered()->Add(field_trial_hashes[i]); | |
| 520 if (field_trial_triggered_in_session_) { | |
| 521 new_entry.mutable_field_trial_triggered_in_session()->Add( | |
| 522 field_trial_hashes[i]); | |
| 523 } | |
| 524 } | |
| 525 } | |
| 526 | |
| 527 void SearchProvider::DeleteMatch(const AutocompleteMatch& match) { | |
| 528 DCHECK(match.deletable); | |
| 529 | |
| 530 deletion_handlers_.push_back(new SuggestionDeletionHandler( | |
| 531 match.GetAdditionalInfo(SearchProvider::kDeletionUrlKey), | |
| 532 profile_, | |
| 533 base::Bind(&SearchProvider::OnDeletionComplete, base::Unretained(this)))); | |
| 534 | |
| 535 HistoryService* const history_service = | |
| 536 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS); | |
| 537 TemplateURL* template_url = match.GetTemplateURL(profile_, false); | |
| 538 // This may be NULL if the template corresponding to the keyword has been | |
| 539 // deleted or there is no keyword set. | |
| 540 if (template_url != NULL) { | |
| 541 history_service->DeleteMatchingURLsForKeyword(template_url->id(), | |
| 542 match.contents); | |
| 543 } | |
| 544 | |
| 545 // Immediately update the list of matches to show the match was deleted, | |
| 546 // regardless of whether the server request actually succeeds. | |
| 547 DeleteMatchFromMatches(match); | |
| 548 } | |
| 549 | |
| 550 void SearchProvider::ResetSession() { | 142 void SearchProvider::ResetSession() { |
| 551 field_trial_triggered_in_session_ = false; | 143 field_trial_triggered_in_session_ = false; |
| 552 } | 144 } |
| 553 | 145 |
| 554 SearchProvider::~SearchProvider() { | 146 SearchProvider::~SearchProvider() { |
| 555 } | 147 } |
| 556 | 148 |
| 557 // static | 149 // static |
| 558 void SearchProvider::RemoveStaleResults(const base::string16& input, | 150 void SearchProvider::RemoveStaleResults(const base::string16& input, |
| 559 int verbatim_relevance, | 151 int verbatim_relevance, |
| (...skipping 114 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 674 default_provider = NULL; // No use in querying the same provider twice. | 266 default_provider = NULL; // No use in querying the same provider twice. |
| 675 | 267 |
| 676 if (!default_provider && !keyword_provider) { | 268 if (!default_provider && !keyword_provider) { |
| 677 // No valid providers. | 269 // No valid providers. |
| 678 Stop(false); | 270 Stop(false); |
| 679 return; | 271 return; |
| 680 } | 272 } |
| 681 | 273 |
| 682 // If we're still running an old query but have since changed the query text | 274 // If we're still running an old query but have since changed the query text |
| 683 // or the providers, abort the query. | 275 // or the providers, abort the query. |
| 684 base::string16 default_provider_keyword(default_provider ? | 276 base::string16 default_provider_keyword( |
| 685 default_provider->keyword() : base::string16()); | 277 default_provider ? default_provider->keyword() : base::string16()); |
| 686 base::string16 keyword_provider_keyword(keyword_provider ? | 278 base::string16 keyword_provider_keyword( |
| 687 keyword_provider->keyword() : base::string16()); | 279 keyword_provider ? keyword_provider->keyword() : base::string16()); |
| 688 if (!minimal_changes || | 280 if (!minimal_changes || |
| 689 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) { | 281 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) { |
| 690 // Cancel any in-flight suggest requests. | 282 // Cancel any in-flight suggest requests. |
| 691 if (!done_) | 283 if (!done_) |
| 692 Stop(false); | 284 Stop(false); |
| 693 } | 285 } |
| 694 | 286 |
| 695 providers_.set(default_provider_keyword, keyword_provider_keyword); | 287 providers_.set(default_provider_keyword, keyword_provider_keyword); |
| 696 | 288 |
| 697 if (input.text().empty()) { | 289 if (input.text().empty()) { |
| (...skipping 13 matching lines...) Expand all Loading... |
| 711 return; | 303 return; |
| 712 } | 304 } |
| 713 | 305 |
| 714 input_ = input; | 306 input_ = input; |
| 715 | 307 |
| 716 DoHistoryQuery(minimal_changes); | 308 DoHistoryQuery(minimal_changes); |
| 717 StartOrStopSuggestQuery(minimal_changes); | 309 StartOrStopSuggestQuery(minimal_changes); |
| 718 UpdateMatches(); | 310 UpdateMatches(); |
| 719 } | 311 } |
| 720 | 312 |
| 721 void SearchProvider::Stop(bool clear_cached_results) { | 313 bool SearchProvider::IsKeywordRequest(const net::URLFetcher* source) { |
| 722 StopSuggest(); | 314 return source == keyword_fetcher_.get(); |
| 723 done_ = true; | |
| 724 | |
| 725 if (clear_cached_results) | |
| 726 ClearAllResults(); | |
| 727 } | 315 } |
| 728 | 316 |
| 729 void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) { | 317 bool SearchProvider::IsRequestSuccessful(const net::URLFetcher* source) { |
| 730 DCHECK(!done_); | 318 return BaseSearchProvider::IsRequestSuccessful(source) && |
| 731 suggest_results_pending_--; | 319 (IsKeywordRequest(source) ? providers_.GetKeywordProviderURL() |
| 320 : providers_.GetDefaultProviderURL()); |
| 321 } |
| 322 |
| 323 void SearchProvider::LogFetchComplete(const net::URLFetcher* source) { |
| 732 LogOmniboxSuggestRequest(REPLY_RECEIVED); | 324 LogOmniboxSuggestRequest(REPLY_RECEIVED); |
| 733 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative. | |
| 734 | |
| 735 const bool is_keyword = (source == keyword_fetcher_.get()); | |
| 736 // Ensure the request succeeded and that the provider used is still available. | |
| 737 // A verbatim match cannot be generated without this provider, causing errors. | |
| 738 const bool request_succeeded = | |
| 739 source->GetStatus().is_success() && (source->GetResponseCode() == 200) && | |
| 740 (is_keyword ? | |
| 741 providers_.GetKeywordProviderURL() : | |
| 742 providers_.GetDefaultProviderURL()); | |
| 743 | 325 |
| 744 // Record response time for suggest requests sent to Google. We care | 326 // Record response time for suggest requests sent to Google. We care |
| 745 // only about the common case: the Google default provider used in | 327 // only about the common case: the Google default provider used in |
| 746 // non-keyword mode. | 328 // non-keyword mode. |
| 747 const TemplateURL* default_url = providers_.GetDefaultProviderURL(); | 329 const TemplateURL* default_url = providers_.GetDefaultProviderURL(); |
| 748 if (!is_keyword && default_url && | 330 if (IsKeywordRequest(source) && default_url && |
| 749 (TemplateURLPrepopulateData::GetEngineType(*default_url) == | 331 (TemplateURLPrepopulateData::GetEngineType(*default_url) == |
| 750 SEARCH_ENGINE_GOOGLE)) { | 332 SEARCH_ENGINE_GOOGLE)) { |
| 751 const base::TimeDelta elapsed_time = | 333 const base::TimeDelta elapsed_time = |
| 752 base::TimeTicks::Now() - time_suggest_request_sent_; | 334 base::TimeTicks::Now() - time_suggest_request_sent_; |
| 753 if (request_succeeded) { | 335 if (IsRequestSuccessful(source)) { |
| 754 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime", | 336 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime", |
| 755 elapsed_time); | 337 elapsed_time); |
| 756 } else { | 338 } else { |
| 757 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime", | 339 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime", |
| 758 elapsed_time); | 340 elapsed_time); |
| 759 } | 341 } |
| 760 } | 342 } |
| 761 | |
| 762 bool results_updated = false; | |
| 763 if (request_succeeded) { | |
| 764 const net::HttpResponseHeaders* const response_headers = | |
| 765 source->GetResponseHeaders(); | |
| 766 std::string json_data; | |
| 767 source->GetResponseAsString(&json_data); | |
| 768 | |
| 769 // JSON is supposed to be UTF-8, but some suggest service providers send | |
| 770 // JSON files in non-UTF-8 encodings. The actual encoding is usually | |
| 771 // specified in the Content-Type header field. | |
| 772 if (response_headers) { | |
| 773 std::string charset; | |
| 774 if (response_headers->GetCharset(&charset)) { | |
| 775 base::string16 data_16; | |
| 776 // TODO(jungshik): Switch to CodePageToUTF8 after it's added. | |
| 777 if (base::CodepageToUTF16(json_data, charset.c_str(), | |
| 778 base::OnStringConversionError::FAIL, | |
| 779 &data_16)) | |
| 780 json_data = base::UTF16ToUTF8(data_16); | |
| 781 } | |
| 782 } | |
| 783 | |
| 784 scoped_ptr<base::Value> data(DeserializeJsonData(json_data)); | |
| 785 results_updated = data.get() && ParseSuggestResults(data.get(), is_keyword); | |
| 786 } | |
| 787 | |
| 788 UpdateMatches(); | |
| 789 if (done_ || results_updated) | |
| 790 listener_->OnProviderUpdate(results_updated); | |
| 791 } | 343 } |
| 792 | 344 |
| 793 void SearchProvider::OnDeletionComplete(bool success, | 345 bool SearchProvider::IsValidQuery(const base::string16 query, |
| 794 SuggestionDeletionHandler* handler) { | 346 const net::URLFetcher* source) { |
| 795 RecordDeletionResult(success); | 347 return GetInputText(source) == query; |
| 796 SuggestionDeletionHandlers::iterator it = std::find( | |
| 797 deletion_handlers_.begin(), deletion_handlers_.end(), handler); | |
| 798 DCHECK(it != deletion_handlers_.end()); | |
| 799 deletion_handlers_.erase(it); | |
| 800 } | 348 } |
| 801 | 349 |
| 802 | |
| 803 void SearchProvider::RecordDeletionResult(bool success) { | 350 void SearchProvider::RecordDeletionResult(bool success) { |
| 804 if (success) { | 351 if (success) { |
| 805 content::RecordAction( | 352 content::RecordAction( |
| 806 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success")); | 353 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success")); |
| 807 } else { | 354 } else { |
| 808 content::RecordAction( | 355 content::RecordAction( |
| 809 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure")); | 356 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure")); |
| 810 } | 357 } |
| 811 } | 358 } |
| 812 | 359 |
| 813 void SearchProvider::DeleteMatchFromMatches(const AutocompleteMatch& match) { | 360 void SearchProvider::StopSuggest() { |
| 814 for (ACMatches::iterator i(matches_.begin()); i != matches_.end(); ++i) { | 361 // Increment the appropriate field in the histogram by the number of |
| 815 // Find the desired match to delete by checking the type and contents. | 362 // pending requests that were invalidated. |
| 816 // We can't check the destination URL, because the autocomplete controller | 363 for (int i = 0; i < suggest_results_pending_; i++) |
| 817 // may have reformulated that. Not that while checking for matching | 364 LogOmniboxSuggestRequest(REQUEST_INVALIDATED); |
| 818 // contents works for personalized suggestions, if more match types gain | 365 suggest_results_pending_ = 0; |
| 819 // deletion support, this algorithm may need to be re-examined. | 366 timer_.Stop(); |
| 820 if (i->contents == match.contents && i->type == match.type) { | 367 // Stop any in-progress URL fetches. |
| 821 matches_.erase(i); | 368 keyword_fetcher_.reset(); |
| 822 break; | 369 default_fetcher_.reset(); |
| 370 } |
| 371 |
| 372 void SearchProvider::ClearAllResults() { |
| 373 keyword_results_.Clear(); |
| 374 default_results_.Clear(); |
| 375 } |
| 376 |
| 377 int SearchProvider::GetDefaultRelevance() { return -1; } |
| 378 |
| 379 const base::string16 SearchProvider::GetInputText( |
| 380 const net::URLFetcher* source) { |
| 381 return IsKeywordRequest(source) ? keyword_input_.text() : input_.text(); |
| 382 } |
| 383 |
| 384 bool SearchProvider::ShouldAllowNavSuggest(const net::URLFetcher* source) { |
| 385 // Prohibit navsuggest in FORCED_QUERY mode. Users wants queries, not URLs. |
| 386 return (IsKeywordRequest(source) ? keyword_input_.type() : input_.type()) != |
| 387 AutocompleteInput::FORCED_QUERY; |
| 388 } |
| 389 |
| 390 BaseSearchProvider::Results* SearchProvider::GetResultsObjectToFill( |
| 391 const net::URLFetcher* source) { |
| 392 return IsKeywordRequest(source) ? &keyword_results_ : &default_results_; |
| 393 } |
| 394 |
| 395 void SearchProvider::SortResults(const net::URLFetcher* source, |
| 396 const base::ListValue* relevances, |
| 397 Results* results) { |
| 398 // Ignore suggested scores for non-keyword matches in keyword mode; if the |
| 399 // server is allowed to score these, it could interfere with the user's |
| 400 // ability to get good keyword results. |
| 401 const bool abandon_suggested_scores = |
| 402 !IsKeywordRequest(source) && !providers_.keyword_provider().empty(); |
| 403 // Apply calculated relevance scores to suggestions if a valid list was |
| 404 // not provided or we're abandoning suggested scores entirely. |
| 405 |
| 406 if (relevances == NULL || abandon_suggested_scores) { |
| 407 ApplyCalculatedSuggestRelevance(&results->suggest_results); |
| 408 ApplyCalculatedNavigationRelevance(&results->navigation_results); |
| 409 // If abandoning scores entirely, also abandon the verbatim score. |
| 410 if (abandon_suggested_scores) |
| 411 results->verbatim_relevance = -1; |
| 412 } |
| 413 |
| 414 // Keep the result lists sorted. |
| 415 const CompareScoredResults comparator = CompareScoredResults(); |
| 416 std::stable_sort(results->suggest_results.begin(), |
| 417 results->suggest_results.end(), |
| 418 comparator); |
| 419 std::stable_sort(results->navigation_results.begin(), |
| 420 results->navigation_results.end(), |
| 421 comparator); |
| 422 } |
| 423 |
| 424 void SearchProvider::UpdateMatches() { |
| 425 base::TimeTicks update_matches_start_time(base::TimeTicks::Now()); |
| 426 ConvertResultsToAutocompleteMatches(); |
| 427 |
| 428 // Check constraints that may be violated by suggested relevances. |
| 429 if (!matches_.empty() && (default_results_.HasServerProvidedScores() || |
| 430 keyword_results_.HasServerProvidedScores())) { |
| 431 // These blocks attempt to repair undesirable behavior by suggested |
| 432 // relevances with minimal impact, preserving other suggested relevances. |
| 433 |
| 434 // True if the omnibox will reorder matches as necessary to make the first |
| 435 // one something that is allowed to be the default match. |
| 436 const bool omnibox_will_reorder_for_legal_default_match = |
| 437 OmniboxFieldTrial::ReorderForLegalDefaultMatch( |
| 438 input_.current_page_classification()); |
| 439 if (IsTopMatchNavigationInKeywordMode( |
| 440 omnibox_will_reorder_for_legal_default_match)) { |
| 441 // Correct the suggested relevance scores if the top match is a |
| 442 // navigation in keyword mode, since inlining a navigation match |
| 443 // would break the user out of keyword mode. This will only be |
| 444 // triggered in regular (non-reorder) mode; in reorder mode, |
| 445 // navigation matches are marked as not allowed to be the default |
| 446 // match and hence IsTopMatchNavigation() will always return false. |
| 447 DCHECK(!omnibox_will_reorder_for_legal_default_match); |
| 448 DemoteKeywordNavigationMatchesPastTopQuery(); |
| 449 ConvertResultsToAutocompleteMatches(); |
| 450 DCHECK(!IsTopMatchNavigationInKeywordMode( |
| 451 omnibox_will_reorder_for_legal_default_match)); |
| 452 } |
| 453 if (!HasKeywordDefaultMatchInKeywordMode()) { |
| 454 // In keyword mode, disregard the keyword verbatim suggested relevance |
| 455 // if necessary so there at least one keyword match that's allowed to |
| 456 // be the default match. |
| 457 keyword_results_.verbatim_relevance = -1; |
| 458 ConvertResultsToAutocompleteMatches(); |
| 459 } |
| 460 if (IsTopMatchScoreTooLow(omnibox_will_reorder_for_legal_default_match)) { |
| 461 // Disregard the suggested verbatim relevance if the top score is below |
| 462 // the usual verbatim value. For example, a BarProvider may rely on |
| 463 // SearchProvider's verbatim or inlineable matches for input "foo" (all |
| 464 // allowed to be default match) to always outrank its own lowly-ranked |
| 465 // "bar" matches that shouldn't be the default match. |
| 466 default_results_.verbatim_relevance = -1; |
| 467 keyword_results_.verbatim_relevance = -1; |
| 468 ConvertResultsToAutocompleteMatches(); |
| 469 } |
| 470 if (IsTopMatchSearchWithURLInput( |
| 471 omnibox_will_reorder_for_legal_default_match)) { |
| 472 // Disregard the suggested search and verbatim relevances if the input |
| 473 // type is URL and the top match is a highly-ranked search suggestion. |
| 474 // For example, prevent a search for "foo.com" from outranking another |
| 475 // provider's navigation for "foo.com" or "foo.com/url_from_history". |
| 476 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results); |
| 477 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results); |
| 478 default_results_.verbatim_relevance = -1; |
| 479 keyword_results_.verbatim_relevance = -1; |
| 480 ConvertResultsToAutocompleteMatches(); |
| 481 } |
| 482 if (!HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match)) { |
| 483 // If the omnibox is not going to reorder results to put a legal default |
| 484 // match at the top, then this provider needs to guarantee that its top |
| 485 // scoring result is a legal default match (i.e., it's either a verbatim |
| 486 // match or inlinable). For example, input "foo" should not invoke a |
| 487 // search for "bar", which would happen if the "bar" search match |
| 488 // outranked all other matches. On the other hand, if the omnibox will |
| 489 // reorder matches as necessary to put a legal default match at the top, |
| 490 // all we need to guarantee is that SearchProvider returns a legal |
| 491 // default match. (The omnibox always needs at least one legal default |
| 492 // match, and it relies on SearchProvider to always return one.) |
| 493 ApplyCalculatedRelevance(); |
| 494 ConvertResultsToAutocompleteMatches(); |
| 495 } |
| 496 DCHECK(!IsTopMatchNavigationInKeywordMode( |
| 497 omnibox_will_reorder_for_legal_default_match)); |
| 498 DCHECK(HasKeywordDefaultMatchInKeywordMode()); |
| 499 DCHECK( |
| 500 !IsTopMatchScoreTooLow(omnibox_will_reorder_for_legal_default_match)); |
| 501 DCHECK(!IsTopMatchSearchWithURLInput( |
| 502 omnibox_will_reorder_for_legal_default_match)); |
| 503 DCHECK(HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match)); |
| 504 } |
| 505 |
| 506 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL(); |
| 507 if ((keyword_url != NULL) && HasKeywordDefaultMatchInKeywordMode()) { |
| 508 // If there is a keyword match that is allowed to be the default match, |
| 509 // then prohibit default provider matches from being the default match lest |
| 510 // such matches cause the user to break out of keyword mode. |
| 511 for (ACMatches::iterator it = matches_.begin(); it != matches_.end(); |
| 512 ++it) { |
| 513 if (it->keyword != keyword_url->keyword()) |
| 514 it->allowed_to_be_default_match = false; |
| 823 } | 515 } |
| 824 } | 516 } |
| 825 listener_->OnProviderUpdate(true); | 517 |
| 518 base::TimeTicks update_starred_start_time(base::TimeTicks::Now()); |
| 519 UpdateStarredStateOfMatches(); |
| 520 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateStarredTime", |
| 521 base::TimeTicks::Now() - update_starred_start_time); |
| 522 UpdateDone(); |
| 523 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateMatchesTime", |
| 524 base::TimeTicks::Now() - update_matches_start_time); |
| 525 } |
| 526 |
| 527 bool SearchProvider::ShouldSendProviderUpdate(bool results_updated) { |
| 528 return done_ || results_updated; |
| 826 } | 529 } |
| 827 | 530 |
| 828 void SearchProvider::Run() { | 531 void SearchProvider::Run() { |
| 829 // Start a new request with the current input. | 532 // Start a new request with the current input. |
| 830 suggest_results_pending_ = 0; | 533 suggest_results_pending_ = 0; |
| 831 time_suggest_request_sent_ = base::TimeTicks::Now(); | 534 time_suggest_request_sent_ = base::TimeTicks::Now(); |
| 832 | 535 |
| 833 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID, | 536 default_fetcher_.reset( |
| 834 providers_.GetDefaultProviderURL(), input_)); | 537 CreateSuggestFetcher(kDefaultProviderURLFetcherID, |
| 835 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID, | 538 providers_.GetDefaultProviderURL(), |
| 836 providers_.GetKeywordProviderURL(), keyword_input_)); | 539 input_)); |
| 540 keyword_fetcher_.reset( |
| 541 CreateSuggestFetcher(kKeywordProviderURLFetcherID, |
| 542 providers_.GetKeywordProviderURL(), |
| 543 keyword_input_)); |
| 837 | 544 |
| 838 // Both the above can fail if the providers have been modified or deleted | 545 // Both the above can fail if the providers have been modified or deleted |
| 839 // since the query began. | 546 // since the query began. |
| 840 if (suggest_results_pending_ == 0) { | 547 if (suggest_results_pending_ == 0) { |
| 841 UpdateDone(); | 548 UpdateDone(); |
| 842 // We only need to update the listener if we're actually done. | 549 // We only need to update the listener if we're actually done. |
| 843 if (done_) | 550 if (done_) |
| 844 listener_->OnProviderUpdate(false); | 551 listener_->OnProviderUpdate(false); |
| 845 } | 552 } |
| 846 } | 553 } |
| (...skipping 13 matching lines...) Expand all Loading... |
| 860 input_.current_page_classification())) | 567 input_.current_page_classification())) |
| 861 return; | 568 return; |
| 862 | 569 |
| 863 base::TimeTicks start_time(base::TimeTicks::Now()); | 570 base::TimeTicks start_time(base::TimeTicks::Now()); |
| 864 HistoryService* const history_service = | 571 HistoryService* const history_service = |
| 865 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS); | 572 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS); |
| 866 base::TimeTicks now(base::TimeTicks::Now()); | 573 base::TimeTicks now(base::TimeTicks::Now()); |
| 867 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.GetHistoryServiceTime", | 574 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.GetHistoryServiceTime", |
| 868 now - start_time); | 575 now - start_time); |
| 869 start_time = now; | 576 start_time = now; |
| 870 history::URLDatabase* url_db = history_service ? | 577 history::URLDatabase* url_db = |
| 871 history_service->InMemoryDatabase() : NULL; | 578 history_service ? history_service->InMemoryDatabase() : NULL; |
| 872 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.InMemoryDatabaseTime", | 579 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.InMemoryDatabaseTime", |
| 873 base::TimeTicks::Now() - start_time); | 580 base::TimeTicks::Now() - start_time); |
| 874 if (!url_db) | 581 if (!url_db) |
| 875 return; | 582 return; |
| 876 | 583 |
| 877 // Request history for both the keyword and default provider. We grab many | 584 // Request history for both the keyword and default provider. We grab many |
| 878 // more matches than we'll ultimately clamp to so that if there are several | 585 // more matches than we'll ultimately clamp to so that if there are several |
| 879 // recent multi-word matches who scores are lowered (see | 586 // recent multi-word matches who scores are lowered (see |
| 880 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring | 587 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring |
| 881 // matches. Note that this doesn't fix the problem entirely, but merely | 588 // matches. Note that this doesn't fix the problem entirely, but merely |
| 882 // limits it to cases with a very large number of such multi-word matches; for | 589 // limits it to cases with a very large number of such multi-word matches; for |
| 883 // now, this seems OK compared with the complexity of a real fix, which would | 590 // now, this seems OK compared with the complexity of a real fix, which would |
| 884 // require multiple searches and tracking of "single- vs. multi-word" in the | 591 // require multiple searches and tracking of "single- vs. multi-word" in the |
| 885 // database. | 592 // database. |
| 886 int num_matches = kMaxMatches * 5; | 593 int num_matches = kMaxMatches * 5; |
| 887 const TemplateURL* default_url = providers_.GetDefaultProviderURL(); | 594 const TemplateURL* default_url = providers_.GetDefaultProviderURL(); |
| 888 if (default_url) { | 595 if (default_url) { |
| 889 start_time = base::TimeTicks::Now(); | 596 start_time = base::TimeTicks::Now(); |
| 890 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(), | 597 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), |
| 891 num_matches, &default_history_results_); | 598 input_.text(), |
| 599 num_matches, |
| 600 &default_history_results_); |
| 892 UMA_HISTOGRAM_TIMES( | 601 UMA_HISTOGRAM_TIMES( |
| 893 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime", | 602 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime", |
| 894 base::TimeTicks::Now() - start_time); | 603 base::TimeTicks::Now() - start_time); |
| 895 } | 604 } |
| 896 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL(); | 605 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL(); |
| 897 if (keyword_url) { | 606 if (keyword_url) { |
| 898 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(), | 607 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(), |
| 899 keyword_input_.text(), num_matches, &keyword_history_results_); | 608 keyword_input_.text(), |
| 609 num_matches, |
| 610 &keyword_history_results_); |
| 900 } | 611 } |
| 901 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.DoHistoryQueryTime", | 612 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.DoHistoryQueryTime", |
| 902 base::TimeTicks::Now() - do_history_query_start_time); | 613 base::TimeTicks::Now() - do_history_query_start_time); |
| 903 } | 614 } |
| 904 | 615 |
| 905 void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) { | 616 void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) { |
| 906 if (!IsQuerySuitableForSuggest()) { | 617 if (!IsQuerySuitableForSuggest()) { |
| 907 StopSuggest(); | 618 StopSuggest(); |
| 908 ClearAllResults(); | 619 ClearAllResults(); |
| 909 return; | 620 return; |
| 910 } | 621 } |
| 911 | 622 |
| 912 // For the minimal_changes case, if we finished the previous query and still | 623 // For the minimal_changes case, if we finished the previous query and still |
| 913 // have its results, or are allowed to keep running it, just do that, rather | 624 // have its results, or are allowed to keep running it, just do that, rather |
| 914 // than starting a new query. | 625 // than starting a new query. |
| 915 if (minimal_changes && | 626 if (minimal_changes && (!default_results_.suggest_results.empty() || |
| 916 (!default_results_.suggest_results.empty() || | 627 !default_results_.navigation_results.empty() || |
| 917 !default_results_.navigation_results.empty() || | 628 !keyword_results_.suggest_results.empty() || |
| 918 !keyword_results_.suggest_results.empty() || | 629 !keyword_results_.navigation_results.empty() || |
| 919 !keyword_results_.navigation_results.empty() || | 630 (!done_ && input_.matches_requested() == |
| 920 (!done_ && | 631 AutocompleteInput::ALL_MATCHES))) |
| 921 input_.matches_requested() == AutocompleteInput::ALL_MATCHES))) | |
| 922 return; | 632 return; |
| 923 | 633 |
| 924 // We can't keep running any previous query, so halt it. | 634 // We can't keep running any previous query, so halt it. |
| 925 StopSuggest(); | 635 StopSuggest(); |
| 926 | 636 |
| 927 // Remove existing results that cannot inline autocomplete the new input. | 637 // Remove existing results that cannot inline autocomplete the new input. |
| 928 RemoveAllStaleResults(); | 638 RemoveAllStaleResults(); |
| 929 | 639 |
| 930 // Update the content classifications of remaining results so they look good | 640 // Update the content classifications of remaining results so they look good |
| 931 // against the current input. | 641 // against the current input. |
| 932 UpdateMatchContentsClass(input_.text(), &default_results_); | 642 UpdateMatchContentsClass(input_.text(), &default_results_); |
| 933 if (!keyword_input_.text().empty()) | 643 if (!keyword_input_.text().empty()) |
| 934 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_); | 644 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_); |
| 935 | 645 |
| 936 // We can't start a new query if we're only allowed synchronous results. | 646 // We can't start a new query if we're only allowed synchronous results. |
| 937 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES) | 647 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES) |
| 938 return; | 648 return; |
| 939 | 649 |
| 940 // To avoid flooding the suggest server, don't send a query until at | 650 // To avoid flooding the suggest server, don't send a query until at |
| 941 // least 100 ms since the last query. | 651 // least 100 ms since the last query. |
| 942 base::TimeTicks next_suggest_time(time_suggest_request_sent_ + | 652 base::TimeTicks next_suggest_time( |
| 653 time_suggest_request_sent_ + |
| 943 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs)); | 654 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs)); |
| 944 base::TimeTicks now(base::TimeTicks::Now()); | 655 base::TimeTicks now(base::TimeTicks::Now()); |
| 945 if (now >= next_suggest_time) { | 656 if (now >= next_suggest_time) { |
| 946 Run(); | 657 Run(); |
| 947 return; | 658 return; |
| 948 } | 659 } |
| 949 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run); | 660 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run); |
| 950 } | 661 } |
| 951 | 662 |
| 952 bool SearchProvider::IsQuerySuitableForSuggest() const { | 663 bool SearchProvider::IsQuerySuitableForSuggest() const { |
| (...skipping 48 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 1001 // Don't send anything for https except the hostname. Hostnames are OK | 712 // Don't send anything for https except the hostname. Hostnames are OK |
| 1002 // because they are visible when the TCP connection is established, but the | 713 // because they are visible when the TCP connection is established, but the |
| 1003 // specific path may reveal private information. | 714 // specific path may reveal private information. |
| 1004 if (LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) && | 715 if (LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) && |
| 1005 parts.path.is_nonempty()) | 716 parts.path.is_nonempty()) |
| 1006 return false; | 717 return false; |
| 1007 | 718 |
| 1008 return true; | 719 return true; |
| 1009 } | 720 } |
| 1010 | 721 |
| 1011 void SearchProvider::StopSuggest() { | |
| 1012 // Increment the appropriate field in the histogram by the number of | |
| 1013 // pending requests that were invalidated. | |
| 1014 for (int i = 0; i < suggest_results_pending_; i++) | |
| 1015 LogOmniboxSuggestRequest(REQUEST_INVALIDATED); | |
| 1016 suggest_results_pending_ = 0; | |
| 1017 timer_.Stop(); | |
| 1018 // Stop any in-progress URL fetches. | |
| 1019 keyword_fetcher_.reset(); | |
| 1020 default_fetcher_.reset(); | |
| 1021 } | |
| 1022 | |
| 1023 void SearchProvider::ClearAllResults() { | |
| 1024 keyword_results_.Clear(); | |
| 1025 default_results_.Clear(); | |
| 1026 } | |
| 1027 | |
| 1028 void SearchProvider::RemoveAllStaleResults() { | 722 void SearchProvider::RemoveAllStaleResults() { |
| 1029 // We only need to remove stale results (which ensures the top-scoring | 723 // We only need to remove stale results (which ensures the top-scoring |
| 1030 // match is inlineable) if the user is not in reorder mode. In reorder | 724 // match is inlineable) if the user is not in reorder mode. In reorder |
| 1031 // mode, the autocomplete system will reorder results to make sure the | 725 // mode, the autocomplete system will reorder results to make sure the |
| 1032 // top result is inlineable. | 726 // top result is inlineable. |
| 1033 const bool omnibox_will_reorder_for_legal_default_match = | 727 const bool omnibox_will_reorder_for_legal_default_match = |
| 1034 OmniboxFieldTrial::ReorderForLegalDefaultMatch( | 728 OmniboxFieldTrial::ReorderForLegalDefaultMatch( |
| 1035 input_.current_page_classification()); | 729 input_.current_page_classification()); |
| 1036 // In theory it would be better to run an algorithm like that in | 730 // In theory it would be better to run an algorithm like that in |
| 1037 // RemoveStaleResults(...) below that uses all four results lists | 731 // RemoveStaleResults(...) below that uses all four results lists |
| (...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 1092 int id, | 786 int id, |
| 1093 const TemplateURL* template_url, | 787 const TemplateURL* template_url, |
| 1094 const AutocompleteInput& input) { | 788 const AutocompleteInput& input) { |
| 1095 if (!template_url || template_url->suggestions_url().empty()) | 789 if (!template_url || template_url->suggestions_url().empty()) |
| 1096 return NULL; | 790 return NULL; |
| 1097 | 791 |
| 1098 // Bail if the suggestion URL is invalid with the given replacements. | 792 // Bail if the suggestion URL is invalid with the given replacements. |
| 1099 TemplateURLRef::SearchTermsArgs search_term_args(input.text()); | 793 TemplateURLRef::SearchTermsArgs search_term_args(input.text()); |
| 1100 search_term_args.cursor_position = input.cursor_position(); | 794 search_term_args.cursor_position = input.cursor_position(); |
| 1101 search_term_args.page_classification = input.current_page_classification(); | 795 search_term_args.page_classification = input.current_page_classification(); |
| 1102 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms( | 796 GURL suggest_url( |
| 1103 search_term_args)); | 797 template_url->suggestions_url_ref().ReplaceSearchTerms(search_term_args)); |
| 1104 if (!suggest_url.is_valid()) | 798 if (!suggest_url.is_valid()) |
| 1105 return NULL; | 799 return NULL; |
| 1106 // Send the current page URL if user setting and URL requirements are met and | 800 // Send the current page URL if user setting and URL requirements are met and |
| 1107 // the user is in the field trial. | 801 // the user is in the field trial. |
| 1108 if (CanSendURL(current_page_url_, suggest_url, template_url, | 802 if (CanSendURL(current_page_url_, |
| 1109 input.current_page_classification(), profile_) && | 803 suggest_url, |
| 804 template_url, |
| 805 input.current_page_classification(), |
| 806 profile_) && |
| 1110 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) { | 807 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) { |
| 1111 search_term_args.current_page_url = current_page_url_.spec(); | 808 search_term_args.current_page_url = current_page_url_.spec(); |
| 1112 // Create the suggest URL again with the current page URL. | 809 // Create the suggest URL again with the current page URL. |
| 1113 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms( | 810 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms( |
| 1114 search_term_args)); | 811 search_term_args)); |
| 1115 } | 812 } |
| 1116 | 813 |
| 1117 suggest_results_pending_++; | 814 suggest_results_pending_++; |
| 1118 LogOmniboxSuggestRequest(REQUEST_SENT); | 815 LogOmniboxSuggestRequest(REQUEST_SENT); |
| 1119 | 816 |
| 1120 net::URLFetcher* fetcher = | 817 net::URLFetcher* fetcher = |
| 1121 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this); | 818 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this); |
| 1122 fetcher->SetRequestContext(profile_->GetRequestContext()); | 819 fetcher->SetRequestContext(profile_->GetRequestContext()); |
| 1123 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES); | 820 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES); |
| 1124 // Add Chrome experiment state to the request headers. | 821 // Add Chrome experiment state to the request headers. |
| 1125 net::HttpRequestHeaders headers; | 822 net::HttpRequestHeaders headers; |
| 1126 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders( | 823 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders( |
| 1127 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers); | 824 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers); |
| 1128 fetcher->SetExtraRequestHeaders(headers.ToString()); | 825 fetcher->SetExtraRequestHeaders(headers.ToString()); |
| 1129 fetcher->Start(); | 826 fetcher->Start(); |
| 1130 return fetcher; | 827 return fetcher; |
| 1131 } | 828 } |
| 1132 | 829 |
| 1133 scoped_ptr<base::Value> SearchProvider::DeserializeJsonData( | |
| 1134 std::string json_data) { | |
| 1135 // The JSON response should be an array. | |
| 1136 for (size_t response_start_index = json_data.find("["), i = 0; | |
| 1137 response_start_index != std::string::npos && i < 5; | |
| 1138 response_start_index = json_data.find("[", 1), i++) { | |
| 1139 // Remove any XSSI guards to allow for JSON parsing. | |
| 1140 if (response_start_index > 0) | |
| 1141 json_data.erase(0, response_start_index); | |
| 1142 | |
| 1143 JSONStringValueSerializer deserializer(json_data); | |
| 1144 deserializer.set_allow_trailing_comma(true); | |
| 1145 int error_code = 0; | |
| 1146 scoped_ptr<base::Value> data(deserializer.Deserialize(&error_code, NULL)); | |
| 1147 if (error_code == 0) | |
| 1148 return data.Pass(); | |
| 1149 } | |
| 1150 return scoped_ptr<base::Value>(); | |
| 1151 } | |
| 1152 | |
| 1153 bool SearchProvider::ParseSuggestResults(base::Value* root_val, | |
| 1154 bool is_keyword) { | |
| 1155 base::string16 query; | |
| 1156 base::ListValue* root_list = NULL; | |
| 1157 base::ListValue* results_list = NULL; | |
| 1158 const base::string16& input_text = | |
| 1159 is_keyword ? keyword_input_.text() : input_.text(); | |
| 1160 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) || | |
| 1161 (query != input_text) || !root_list->GetList(1, &results_list)) | |
| 1162 return false; | |
| 1163 | |
| 1164 // 3rd element: Description list. | |
| 1165 base::ListValue* descriptions = NULL; | |
| 1166 root_list->GetList(2, &descriptions); | |
| 1167 | |
| 1168 // 4th element: Disregard the query URL list for now. | |
| 1169 | |
| 1170 // Reset suggested relevance information from the default provider. | |
| 1171 Results* results = is_keyword ? &keyword_results_ : &default_results_; | |
| 1172 results->verbatim_relevance = -1; | |
| 1173 | |
| 1174 // 5th element: Optional key-value pairs from the Suggest server. | |
| 1175 base::ListValue* types = NULL; | |
| 1176 base::ListValue* relevances = NULL; | |
| 1177 base::ListValue* suggestion_details = NULL; | |
| 1178 base::DictionaryValue* extras = NULL; | |
| 1179 int prefetch_index = -1; | |
| 1180 if (root_list->GetDictionary(4, &extras)) { | |
| 1181 extras->GetList("google:suggesttype", &types); | |
| 1182 | |
| 1183 // Discard this list if its size does not match that of the suggestions. | |
| 1184 if (extras->GetList("google:suggestrelevance", &relevances) && | |
| 1185 (relevances->GetSize() != results_list->GetSize())) | |
| 1186 relevances = NULL; | |
| 1187 extras->GetInteger("google:verbatimrelevance", | |
| 1188 &results->verbatim_relevance); | |
| 1189 | |
| 1190 // Check if the active suggest field trial (if any) has triggered either | |
| 1191 // for the default provider or keyword provider. | |
| 1192 bool triggered = false; | |
| 1193 extras->GetBoolean("google:fieldtrialtriggered", &triggered); | |
| 1194 field_trial_triggered_ |= triggered; | |
| 1195 field_trial_triggered_in_session_ |= triggered; | |
| 1196 | |
| 1197 base::DictionaryValue* client_data = NULL; | |
| 1198 if (extras->GetDictionary("google:clientdata", &client_data) && client_data) | |
| 1199 client_data->GetInteger("phi", &prefetch_index); | |
| 1200 | |
| 1201 if (extras->GetList("google:suggestdetail", &suggestion_details) && | |
| 1202 suggestion_details->GetSize() != results_list->GetSize()) | |
| 1203 suggestion_details = NULL; | |
| 1204 | |
| 1205 // Store the metadata that came with the response in case we need to pass it | |
| 1206 // along with the prefetch query to Instant. | |
| 1207 JSONStringValueSerializer json_serializer(&results->metadata); | |
| 1208 json_serializer.Serialize(*extras); | |
| 1209 } | |
| 1210 | |
| 1211 // Clear the previous results now that new results are available. | |
| 1212 results->suggest_results.clear(); | |
| 1213 results->navigation_results.clear(); | |
| 1214 | |
| 1215 base::string16 suggestion; | |
| 1216 std::string type; | |
| 1217 int relevance = -1; | |
| 1218 // Prohibit navsuggest in FORCED_QUERY mode. Users wants queries, not URLs. | |
| 1219 const bool allow_navsuggest = | |
| 1220 (is_keyword ? keyword_input_.type() : input_.type()) != | |
| 1221 AutocompleteInput::FORCED_QUERY; | |
| 1222 const std::string languages( | |
| 1223 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)); | |
| 1224 for (size_t index = 0; results_list->GetString(index, &suggestion); ++index) { | |
| 1225 // Google search may return empty suggestions for weird input characters, | |
| 1226 // they make no sense at all and can cause problems in our code. | |
| 1227 if (suggestion.empty()) | |
| 1228 continue; | |
| 1229 | |
| 1230 // Apply valid suggested relevance scores; discard invalid lists. | |
| 1231 if (relevances != NULL && !relevances->GetInteger(index, &relevance)) | |
| 1232 relevances = NULL; | |
| 1233 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) { | |
| 1234 // Do not blindly trust the URL coming from the server to be valid. | |
| 1235 GURL url(URLFixerUpper::FixupURL( | |
| 1236 base::UTF16ToUTF8(suggestion), std::string())); | |
| 1237 if (url.is_valid() && allow_navsuggest) { | |
| 1238 base::string16 title; | |
| 1239 if (descriptions != NULL) | |
| 1240 descriptions->GetString(index, &title); | |
| 1241 results->navigation_results.push_back(NavigationResult( | |
| 1242 *this, url, title, is_keyword, relevance, true, input_text, | |
| 1243 languages)); | |
| 1244 } | |
| 1245 } else { | |
| 1246 AutocompleteMatchType::Type match_type = GetAutocompleteMatchType(type); | |
| 1247 bool should_prefetch = static_cast<int>(index) == prefetch_index; | |
| 1248 base::DictionaryValue* suggestion_detail = NULL; | |
| 1249 base::string16 match_contents = suggestion; | |
| 1250 base::string16 annotation; | |
| 1251 std::string suggest_query_params; | |
| 1252 std::string deletion_url; | |
| 1253 | |
| 1254 if (suggestion_details) { | |
| 1255 suggestion_details->GetDictionary(index, &suggestion_detail); | |
| 1256 if (suggestion_detail) { | |
| 1257 suggestion_detail->GetString("du", &deletion_url); | |
| 1258 suggestion_detail->GetString("title", &match_contents) || | |
| 1259 suggestion_detail->GetString("t", &match_contents); | |
| 1260 // Error correction for bad data from server. | |
| 1261 if (match_contents.empty()) | |
| 1262 match_contents = suggestion; | |
| 1263 suggestion_detail->GetString("annotation", &annotation) || | |
| 1264 suggestion_detail->GetString("a", &annotation); | |
| 1265 suggestion_detail->GetString("query_params", &suggest_query_params) || | |
| 1266 suggestion_detail->GetString("q", &suggest_query_params); | |
| 1267 } | |
| 1268 } | |
| 1269 | |
| 1270 // TODO(kochi): Improve calculator suggestion presentation. | |
| 1271 results->suggest_results.push_back(SuggestResult( | |
| 1272 suggestion, match_type, match_contents, annotation, | |
| 1273 suggest_query_params, deletion_url, is_keyword, relevance, true, | |
| 1274 should_prefetch, input_text)); | |
| 1275 } | |
| 1276 } | |
| 1277 | |
| 1278 // Ignore suggested scores for non-keyword matches in keyword mode; if the | |
| 1279 // server is allowed to score these, it could interfere with the user's | |
| 1280 // ability to get good keyword results. | |
| 1281 const bool abandon_suggested_scores = | |
| 1282 !is_keyword && !providers_.keyword_provider().empty(); | |
| 1283 // Apply calculated relevance scores to suggestions if a valid list was | |
| 1284 // not provided or we're abandoning suggested scores entirely. | |
| 1285 if ((relevances == NULL) || abandon_suggested_scores) { | |
| 1286 ApplyCalculatedSuggestRelevance(&results->suggest_results); | |
| 1287 ApplyCalculatedNavigationRelevance(&results->navigation_results); | |
| 1288 // If abandoning scores entirely, also abandon the verbatim score. | |
| 1289 if (abandon_suggested_scores) | |
| 1290 results->verbatim_relevance = -1; | |
| 1291 } | |
| 1292 | |
| 1293 // Keep the result lists sorted. | |
| 1294 const CompareScoredResults comparator = CompareScoredResults(); | |
| 1295 std::stable_sort(results->suggest_results.begin(), | |
| 1296 results->suggest_results.end(), | |
| 1297 comparator); | |
| 1298 std::stable_sort(results->navigation_results.begin(), | |
| 1299 results->navigation_results.end(), | |
| 1300 comparator); | |
| 1301 return true; | |
| 1302 } | |
| 1303 | |
| 1304 void SearchProvider::ConvertResultsToAutocompleteMatches() { | 830 void SearchProvider::ConvertResultsToAutocompleteMatches() { |
| 1305 // Convert all the results to matches and add them to a map, so we can keep | 831 // Convert all the results to matches and add them to a map, so we can keep |
| 1306 // the most relevant match for each result. | 832 // the most relevant match for each result. |
| 1307 base::TimeTicks start_time(base::TimeTicks::Now()); | 833 base::TimeTicks start_time(base::TimeTicks::Now()); |
| 1308 MatchMap map; | 834 MatchMap map; |
| 1309 const base::Time no_time; | 835 const base::Time no_time; |
| 1310 int did_not_accept_keyword_suggestion = | 836 int did_not_accept_keyword_suggestion = |
| 1311 keyword_results_.suggest_results.empty() ? | 837 keyword_results_.suggest_results.empty() |
| 1312 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE : | 838 ? TemplateURLRef::NO_SUGGESTIONS_AVAILABLE |
| 1313 TemplateURLRef::NO_SUGGESTION_CHOSEN; | 839 : TemplateURLRef::NO_SUGGESTION_CHOSEN; |
| 1314 | 840 |
| 1315 bool relevance_from_server; | 841 bool relevance_from_server; |
| 1316 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server); | 842 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server); |
| 1317 int did_not_accept_default_suggestion = | 843 int did_not_accept_default_suggestion = |
| 1318 default_results_.suggest_results.empty() ? | 844 default_results_.suggest_results.empty() |
| 1319 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE : | 845 ? TemplateURLRef::NO_SUGGESTIONS_AVAILABLE |
| 1320 TemplateURLRef::NO_SUGGESTION_CHOSEN; | 846 : TemplateURLRef::NO_SUGGESTION_CHOSEN; |
| 1321 if (verbatim_relevance > 0) { | 847 if (verbatim_relevance > 0) { |
| 1322 SuggestResult verbatim( | 848 SuggestResult verbatim(input_.text(), |
| 1323 input_.text(), AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, | 849 AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, |
| 1324 input_.text(), base::string16(), std::string(), std::string(), false, | 850 input_.text(), |
| 1325 verbatim_relevance, relevance_from_server, false, input_.text()); | 851 base::string16(), |
| 1326 AddMatchToMap(verbatim, input_.text(), std::string(), | 852 std::string(), |
| 1327 did_not_accept_default_suggestion, &map); | 853 std::string(), |
| 854 false, |
| 855 verbatim_relevance, |
| 856 relevance_from_server, |
| 857 false, |
| 858 input_.text()); |
| 859 AddMatchToMap(verbatim, |
| 860 input_, |
| 861 input_.text(), |
| 862 GetTemplateURL(verbatim), |
| 863 std::string(), |
| 864 did_not_accept_default_suggestion, |
| 865 ShouldAppendExtraQueryParams(verbatim), |
| 866 &map); |
| 1328 } | 867 } |
| 1329 if (!keyword_input_.text().empty()) { | 868 if (!keyword_input_.text().empty()) { |
| 1330 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL(); | 869 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL(); |
| 1331 // We only create the verbatim search query match for a keyword | 870 // We only create the verbatim search query match for a keyword |
| 1332 // if it's not an extension keyword. Extension keywords are handled | 871 // if it's not an extension keyword. Extension keywords are handled |
| 1333 // in KeywordProvider::Start(). (Extensions are complicated...) | 872 // in KeywordProvider::Start(). (Extensions are complicated...) |
| 1334 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond | 873 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond |
| 1335 // to the keyword verbatim search query. Do not create other matches | 874 // to the keyword verbatim search query. Do not create other matches |
| 1336 // of type SEARCH_OTHER_ENGINE. | 875 // of type SEARCH_OTHER_ENGINE. |
| 1337 if (keyword_url && | 876 if (keyword_url && |
| 1338 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) { | 877 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) { |
| 1339 bool keyword_relevance_from_server; | 878 bool keyword_relevance_from_server; |
| 1340 const int keyword_verbatim_relevance = | 879 const int keyword_verbatim_relevance = |
| 1341 GetKeywordVerbatimRelevance(&keyword_relevance_from_server); | 880 GetKeywordVerbatimRelevance(&keyword_relevance_from_server); |
| 1342 if (keyword_verbatim_relevance > 0) { | 881 if (keyword_verbatim_relevance > 0) { |
| 1343 SuggestResult verbatim( | 882 SuggestResult verbatim(keyword_input_.text(), |
| 1344 keyword_input_.text(), AutocompleteMatchType::SEARCH_OTHER_ENGINE, | 883 AutocompleteMatchType::SEARCH_OTHER_ENGINE, |
| 1345 keyword_input_.text(), base::string16(), std::string(), | 884 keyword_input_.text(), |
| 1346 std::string(), true, keyword_verbatim_relevance, | 885 base::string16(), |
| 1347 keyword_relevance_from_server, false, keyword_input_.text()); | 886 std::string(), |
| 1348 AddMatchToMap(verbatim, keyword_input_.text(), std::string(), | 887 std::string(), |
| 1349 did_not_accept_keyword_suggestion, &map); | 888 true, |
| 889 keyword_verbatim_relevance, |
| 890 keyword_relevance_from_server, |
| 891 false, |
| 892 keyword_input_.text()); |
| 893 AddMatchToMap(verbatim, |
| 894 keyword_input_, |
| 895 keyword_input_.text(), |
| 896 GetTemplateURL(verbatim), |
| 897 std::string(), |
| 898 did_not_accept_keyword_suggestion, |
| 899 ShouldAppendExtraQueryParams(verbatim), |
| 900 &map); |
| 1350 } | 901 } |
| 1351 } | 902 } |
| 1352 } | 903 } |
| 1353 AddHistoryResultsToMap(keyword_history_results_, true, | 904 AddHistoryResultsToMap(keyword_history_results_, true, |
| 1354 did_not_accept_keyword_suggestion, &map); | 905 did_not_accept_keyword_suggestion, &map); |
| 1355 AddHistoryResultsToMap(default_history_results_, false, | 906 AddHistoryResultsToMap(default_history_results_, false, |
| 1356 did_not_accept_default_suggestion, &map); | 907 did_not_accept_default_suggestion, &map); |
| 1357 | 908 |
| 1358 AddSuggestResultsToMap(keyword_results_.suggest_results, | 909 AddSuggestResultsToMap(keyword_results_.suggest_results, |
| 1359 keyword_results_.metadata, &map); | 910 keyword_results_.metadata, &map); |
| (...skipping 57 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 1417 while ((it != matches_.end()) && !it->allowed_to_be_default_match) | 968 while ((it != matches_.end()) && !it->allowed_to_be_default_match) |
| 1418 ++it; | 969 ++it; |
| 1419 return it; | 970 return it; |
| 1420 } | 971 } |
| 1421 | 972 |
| 1422 bool SearchProvider::IsTopMatchNavigationInKeywordMode( | 973 bool SearchProvider::IsTopMatchNavigationInKeywordMode( |
| 1423 bool autocomplete_result_will_reorder_for_default_match) const { | 974 bool autocomplete_result_will_reorder_for_default_match) const { |
| 1424 ACMatches::const_iterator first_match = | 975 ACMatches::const_iterator first_match = |
| 1425 FindTopMatch(autocomplete_result_will_reorder_for_default_match); | 976 FindTopMatch(autocomplete_result_will_reorder_for_default_match); |
| 1426 return !providers_.keyword_provider().empty() && | 977 return !providers_.keyword_provider().empty() && |
| 1427 (first_match != matches_.end()) && | 978 (first_match != matches_.end()) && |
| 1428 (first_match->type == AutocompleteMatchType::NAVSUGGEST); | 979 (first_match->type == AutocompleteMatchType::NAVSUGGEST); |
| 1429 } | 980 } |
| 1430 | 981 |
| 1431 bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const { | 982 bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const { |
| 1432 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL(); | 983 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL(); |
| 1433 // If the user is not in keyword mode, return true to say that this | 984 // If the user is not in keyword mode, return true to say that this |
| 1434 // constraint is not violated. | 985 // constraint is not violated. |
| 1435 if (keyword_url == NULL) | 986 if (keyword_url == NULL) |
| 1436 return true; | 987 return true; |
| 1437 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end(); | 988 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end(); |
| 1438 ++it) { | 989 ++it) { |
| (...skipping 13 matching lines...) Expand all Loading... |
| 1452 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState() | 1003 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState() |
| 1453 // rather than CalculateRelevanceForVerbatim() because the latter returns | 1004 // rather than CalculateRelevanceForVerbatim() because the latter returns |
| 1454 // a very low score (250) if keyword mode is active. This is because | 1005 // a very low score (250) if keyword mode is active. This is because |
| 1455 // when keyword mode is active the user probably wants the keyword matches, | 1006 // when keyword mode is active the user probably wants the keyword matches, |
| 1456 // not matches from the default provider. Hence, we use the version of | 1007 // not matches from the default provider. Hence, we use the version of |
| 1457 // the function that ignores whether keyword mode is active. This allows | 1008 // the function that ignores whether keyword mode is active. This allows |
| 1458 // SearchProvider to maintain its contract with the AutocompleteController | 1009 // SearchProvider to maintain its contract with the AutocompleteController |
| 1459 // that it will always provide an inlineable match with a reasonable | 1010 // that it will always provide an inlineable match with a reasonable |
| 1460 // score. | 1011 // score. |
| 1461 return matches_.front().relevance < | 1012 return matches_.front().relevance < |
| 1462 CalculateRelevanceForVerbatimIgnoringKeywordModeState(); | 1013 CalculateRelevanceForVerbatimIgnoringKeywordModeState(); |
| 1463 } | 1014 } |
| 1464 | 1015 |
| 1465 bool SearchProvider::IsTopMatchSearchWithURLInput( | 1016 bool SearchProvider::IsTopMatchSearchWithURLInput( |
| 1466 bool autocomplete_result_will_reorder_for_default_match) const { | 1017 bool autocomplete_result_will_reorder_for_default_match) const { |
| 1467 ACMatches::const_iterator first_match = | 1018 ACMatches::const_iterator first_match = |
| 1468 FindTopMatch(autocomplete_result_will_reorder_for_default_match); | 1019 FindTopMatch(autocomplete_result_will_reorder_for_default_match); |
| 1469 return (input_.type() == AutocompleteInput::URL) && | 1020 return (input_.type() == AutocompleteInput::URL) && |
| 1470 (first_match != matches_.end()) && | 1021 (first_match != matches_.end()) && |
| 1471 (first_match->relevance > CalculateRelevanceForVerbatim()) && | 1022 (first_match->relevance > CalculateRelevanceForVerbatim()) && |
| 1472 (first_match->type != AutocompleteMatchType::NAVSUGGEST); | 1023 (first_match->type != AutocompleteMatchType::NAVSUGGEST); |
| 1473 } | 1024 } |
| 1474 | 1025 |
| 1475 bool SearchProvider::HasValidDefaultMatch( | 1026 bool SearchProvider::HasValidDefaultMatch( |
| 1476 bool autocomplete_result_will_reorder_for_default_match) const { | 1027 bool autocomplete_result_will_reorder_for_default_match) const { |
| 1477 // One of the SearchProvider matches may need to be the overall default. If | 1028 // One of the SearchProvider matches may need to be the overall default. If |
| 1478 // AutocompleteResult is allowed to reorder matches, this means we simply | 1029 // AutocompleteResult is allowed to reorder matches, this means we simply |
| 1479 // need at least one match in the list to be |allowed_to_be_default_match|. | 1030 // need at least one match in the list to be |allowed_to_be_default_match|. |
| 1480 // If no reordering is possible, however, then our first match needs to have | 1031 // If no reordering is possible, however, then our first match needs to have |
| 1481 // this flag. | 1032 // this flag. |
| 1482 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end(); | 1033 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end(); |
| 1483 ++it) { | 1034 ++it) { |
| 1484 if (it->allowed_to_be_default_match) | 1035 if (it->allowed_to_be_default_match) |
| 1485 return true; | 1036 return true; |
| 1486 if (!autocomplete_result_will_reorder_for_default_match) | 1037 if (!autocomplete_result_will_reorder_for_default_match) |
| 1487 return false; | 1038 return false; |
| 1488 } | 1039 } |
| 1489 return false; | 1040 return false; |
| 1490 } | 1041 } |
| 1491 | 1042 |
| 1492 void SearchProvider::UpdateMatches() { | |
| 1493 base::TimeTicks update_matches_start_time(base::TimeTicks::Now()); | |
| 1494 ConvertResultsToAutocompleteMatches(); | |
| 1495 | |
| 1496 // Check constraints that may be violated by suggested relevances. | |
| 1497 if (!matches_.empty() && | |
| 1498 (default_results_.HasServerProvidedScores() || | |
| 1499 keyword_results_.HasServerProvidedScores())) { | |
| 1500 // These blocks attempt to repair undesirable behavior by suggested | |
| 1501 // relevances with minimal impact, preserving other suggested relevances. | |
| 1502 | |
| 1503 // True if the omnibox will reorder matches as necessary to make the first | |
| 1504 // one something that is allowed to be the default match. | |
| 1505 const bool omnibox_will_reorder_for_legal_default_match = | |
| 1506 OmniboxFieldTrial::ReorderForLegalDefaultMatch( | |
| 1507 input_.current_page_classification()); | |
| 1508 if (IsTopMatchNavigationInKeywordMode( | |
| 1509 omnibox_will_reorder_for_legal_default_match)) { | |
| 1510 // Correct the suggested relevance scores if the top match is a | |
| 1511 // navigation in keyword mode, since inlining a navigation match | |
| 1512 // would break the user out of keyword mode. This will only be | |
| 1513 // triggered in regular (non-reorder) mode; in reorder mode, | |
| 1514 // navigation matches are marked as not allowed to be the default | |
| 1515 // match and hence IsTopMatchNavigation() will always return false. | |
| 1516 DCHECK(!omnibox_will_reorder_for_legal_default_match); | |
| 1517 DemoteKeywordNavigationMatchesPastTopQuery(); | |
| 1518 ConvertResultsToAutocompleteMatches(); | |
| 1519 DCHECK(!IsTopMatchNavigationInKeywordMode( | |
| 1520 omnibox_will_reorder_for_legal_default_match)); | |
| 1521 } | |
| 1522 if (!HasKeywordDefaultMatchInKeywordMode()) { | |
| 1523 // In keyword mode, disregard the keyword verbatim suggested relevance | |
| 1524 // if necessary so there at least one keyword match that's allowed to | |
| 1525 // be the default match. | |
| 1526 keyword_results_.verbatim_relevance = -1; | |
| 1527 ConvertResultsToAutocompleteMatches(); | |
| 1528 } | |
| 1529 if (IsTopMatchScoreTooLow(omnibox_will_reorder_for_legal_default_match)) { | |
| 1530 // Disregard the suggested verbatim relevance if the top score is below | |
| 1531 // the usual verbatim value. For example, a BarProvider may rely on | |
| 1532 // SearchProvider's verbatim or inlineable matches for input "foo" (all | |
| 1533 // allowed to be default match) to always outrank its own lowly-ranked | |
| 1534 // "bar" matches that shouldn't be the default match. | |
| 1535 default_results_.verbatim_relevance = -1; | |
| 1536 keyword_results_.verbatim_relevance = -1; | |
| 1537 ConvertResultsToAutocompleteMatches(); | |
| 1538 } | |
| 1539 if (IsTopMatchSearchWithURLInput( | |
| 1540 omnibox_will_reorder_for_legal_default_match)) { | |
| 1541 // Disregard the suggested search and verbatim relevances if the input | |
| 1542 // type is URL and the top match is a highly-ranked search suggestion. | |
| 1543 // For example, prevent a search for "foo.com" from outranking another | |
| 1544 // provider's navigation for "foo.com" or "foo.com/url_from_history". | |
| 1545 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results); | |
| 1546 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results); | |
| 1547 default_results_.verbatim_relevance = -1; | |
| 1548 keyword_results_.verbatim_relevance = -1; | |
| 1549 ConvertResultsToAutocompleteMatches(); | |
| 1550 } | |
| 1551 if (!HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match)) { | |
| 1552 // If the omnibox is not going to reorder results to put a legal default | |
| 1553 // match at the top, then this provider needs to guarantee that its top | |
| 1554 // scoring result is a legal default match (i.e., it's either a verbatim | |
| 1555 // match or inlinable). For example, input "foo" should not invoke a | |
| 1556 // search for "bar", which would happen if the "bar" search match | |
| 1557 // outranked all other matches. On the other hand, if the omnibox will | |
| 1558 // reorder matches as necessary to put a legal default match at the top, | |
| 1559 // all we need to guarantee is that SearchProvider returns a legal | |
| 1560 // default match. (The omnibox always needs at least one legal default | |
| 1561 // match, and it relies on SearchProvider to always return one.) | |
| 1562 ApplyCalculatedRelevance(); | |
| 1563 ConvertResultsToAutocompleteMatches(); | |
| 1564 } | |
| 1565 DCHECK(!IsTopMatchNavigationInKeywordMode( | |
| 1566 omnibox_will_reorder_for_legal_default_match)); | |
| 1567 DCHECK(HasKeywordDefaultMatchInKeywordMode()); | |
| 1568 DCHECK(!IsTopMatchScoreTooLow( | |
| 1569 omnibox_will_reorder_for_legal_default_match)); | |
| 1570 DCHECK(!IsTopMatchSearchWithURLInput( | |
| 1571 omnibox_will_reorder_for_legal_default_match)); | |
| 1572 DCHECK(HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match)); | |
| 1573 } | |
| 1574 | |
| 1575 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL(); | |
| 1576 if ((keyword_url != NULL) && HasKeywordDefaultMatchInKeywordMode()) { | |
| 1577 // If there is a keyword match that is allowed to be the default match, | |
| 1578 // then prohibit default provider matches from being the default match lest | |
| 1579 // such matches cause the user to break out of keyword mode. | |
| 1580 for (ACMatches::iterator it = matches_.begin(); it != matches_.end(); | |
| 1581 ++it) { | |
| 1582 if (it->keyword != keyword_url->keyword()) | |
| 1583 it->allowed_to_be_default_match = false; | |
| 1584 } | |
| 1585 } | |
| 1586 | |
| 1587 base::TimeTicks update_starred_start_time(base::TimeTicks::Now()); | |
| 1588 UpdateStarredStateOfMatches(); | |
| 1589 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateStarredTime", | |
| 1590 base::TimeTicks::Now() - update_starred_start_time); | |
| 1591 UpdateDone(); | |
| 1592 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateMatchesTime", | |
| 1593 base::TimeTicks::Now() - update_matches_start_time); | |
| 1594 } | |
| 1595 | |
| 1596 void SearchProvider::AddNavigationResultsToMatches( | 1043 void SearchProvider::AddNavigationResultsToMatches( |
| 1597 const NavigationResults& navigation_results, | 1044 const NavigationResults& navigation_results, |
| 1598 ACMatches* matches) { | 1045 ACMatches* matches) { |
| 1599 for (NavigationResults::const_iterator it = navigation_results.begin(); | 1046 for (NavigationResults::const_iterator it = navigation_results.begin(); |
| 1600 it != navigation_results.end(); ++it) { | 1047 it != navigation_results.end(); |
| 1048 ++it) { |
| 1601 matches->push_back(NavigationToMatch(*it)); | 1049 matches->push_back(NavigationToMatch(*it)); |
| 1602 // In the absence of suggested relevance scores, use only the single | 1050 // In the absence of suggested relevance scores, use only the single |
| 1603 // highest-scoring result. (The results are already sorted by relevance.) | 1051 // highest-scoring result. (The results are already sorted by relevance.) |
| 1604 if (!it->relevance_from_server()) | 1052 if (!it->relevance_from_server()) |
| 1605 return; | 1053 return; |
| 1606 } | 1054 } |
| 1607 } | 1055 } |
| 1608 | 1056 |
| 1609 void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results, | 1057 void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results, |
| 1610 bool is_keyword, | 1058 bool is_keyword, |
| 1611 int did_not_accept_suggestion, | 1059 int did_not_accept_suggestion, |
| 1612 MatchMap* map) { | 1060 MatchMap* map) { |
| 1613 if (results.empty()) | 1061 if (results.empty()) |
| 1614 return; | 1062 return; |
| 1615 | 1063 |
| 1616 base::TimeTicks start_time(base::TimeTicks::Now()); | 1064 base::TimeTicks start_time(base::TimeTicks::Now()); |
| 1617 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() || | 1065 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() || |
| 1618 (input_.type() == AutocompleteInput::URL); | 1066 (input_.type() == AutocompleteInput::URL); |
| 1619 const base::string16& input_text = | 1067 const base::string16& input_text = |
| 1620 is_keyword ? keyword_input_.text() : input_.text(); | 1068 is_keyword ? keyword_input_.text() : input_.text(); |
| 1621 bool input_multiple_words = HasMultipleWords(input_text); | 1069 bool input_multiple_words = HasMultipleWords(input_text); |
| 1622 | 1070 |
| 1623 SuggestResults scored_results; | 1071 SuggestResults scored_results; |
| 1624 if (!prevent_inline_autocomplete && input_multiple_words) { | 1072 if (!prevent_inline_autocomplete && input_multiple_words) { |
| 1625 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit | 1073 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit |
| 1626 // queries if the input also has multiple words. But if we were already | 1074 // queries if the input also has multiple words. But if we were already |
| 1627 // autocompleting a multi-word, multi-visit query, and the current input is | 1075 // autocompleting a multi-word, multi-visit query, and the current input is |
| 1628 // still a prefix of it, then changing the autocompletion suddenly feels | 1076 // still a prefix of it, then changing the autocompletion suddenly feels |
| 1629 // wrong. To detect this case, first score as if only one word has been | 1077 // wrong. To detect this case, first score as if only one word has been |
| 1630 // typed, then check for a best result that is an autocompleted, multi-word | 1078 // typed, then check for a best result that is an autocompleted, multi-word |
| 1631 // query. If we find one, then just keep that score set. | 1079 // query. If we find one, then just keep that score set. |
| 1632 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete, | 1080 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete, |
| 1633 false, input_text, is_keyword); | 1081 false, input_text, is_keyword); |
| 1634 if ((scored_results.front().relevance() < | 1082 if ((scored_results.front().relevance() < |
| 1635 AutocompleteResult::kLowestDefaultScore) || | 1083 AutocompleteResult::kLowestDefaultScore) || |
| 1636 !HasMultipleWords(scored_results.front().suggestion())) | 1084 !HasMultipleWords(scored_results.front().suggestion())) |
| 1637 scored_results.clear(); // Didn't detect the case above, score normally. | 1085 scored_results.clear(); // Didn't detect the case above, score normally. |
| 1638 } | 1086 } |
| 1639 if (scored_results.empty()) | 1087 if (scored_results.empty()) |
| 1640 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete, | 1088 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete, |
| 1641 input_multiple_words, input_text, | 1089 input_multiple_words, input_text, |
| 1642 is_keyword); | 1090 is_keyword); |
| 1643 for (SuggestResults::const_iterator i(scored_results.begin()); | 1091 for (SuggestResults::const_iterator i(scored_results.begin()); |
| 1644 i != scored_results.end(); ++i) { | 1092 i != scored_results.end(); |
| 1645 AddMatchToMap(*i, input_text, std::string(), | 1093 ++i) { |
| 1646 did_not_accept_suggestion, map); | 1094 AddMatchToMap( |
| 1095 *i, |
| 1096 is_keyword ? keyword_input_ : input_, |
| 1097 input_text, |
| 1098 i->from_keyword_provider() ? providers_.GetKeywordProviderURL() |
| 1099 : providers_.GetDefaultProviderURL(), |
| 1100 std::string(), |
| 1101 did_not_accept_suggestion, |
| 1102 !i->from_keyword_provider() || providers_.default_provider().empty(), |
| 1103 map); |
| 1647 } | 1104 } |
| 1648 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime", | 1105 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime", |
| 1649 base::TimeTicks::Now() - start_time); | 1106 base::TimeTicks::Now() - start_time); |
| 1650 } | 1107 } |
| 1651 | 1108 |
| 1652 SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults( | 1109 SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults( |
| 1653 const HistoryResults& results, | 1110 const HistoryResults& results, |
| 1654 bool base_prevent_inline_autocomplete, | 1111 bool base_prevent_inline_autocomplete, |
| 1655 bool input_multiple_words, | 1112 bool input_multiple_words, |
| 1656 const base::string16& input_text, | 1113 const base::string16& input_text, |
| 1657 bool is_keyword) { | 1114 bool is_keyword) { |
| 1658 AutocompleteClassifier* classifier = | 1115 AutocompleteClassifier* classifier = |
| 1659 AutocompleteClassifierFactory::GetForProfile(profile_); | 1116 AutocompleteClassifierFactory::GetForProfile(profile_); |
| 1660 SuggestResults scored_results; | 1117 SuggestResults scored_results; |
| 1661 const bool prevent_search_history_inlining = | 1118 const bool prevent_search_history_inlining = |
| 1662 OmniboxFieldTrial::SearchHistoryPreventInlining( | 1119 OmniboxFieldTrial::SearchHistoryPreventInlining( |
| 1663 input_.current_page_classification()); | 1120 input_.current_page_classification()); |
| 1664 for (HistoryResults::const_iterator i(results.begin()); i != results.end(); | 1121 for (HistoryResults::const_iterator i(results.begin()); i != results.end(); |
| 1665 ++i) { | 1122 ++i) { |
| 1666 // Don't autocomplete multi-word queries that have only been seen once | 1123 // Don't autocomplete multi-word queries that have only been seen once |
| 1667 // unless the user has typed more than one word. | 1124 // unless the user has typed more than one word. |
| 1668 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete || | 1125 bool prevent_inline_autocomplete = |
| 1126 base_prevent_inline_autocomplete || |
| 1669 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term)); | 1127 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term)); |
| 1670 | 1128 |
| 1671 // Don't autocomplete search terms that would normally be treated as URLs | 1129 // Don't autocomplete search terms that would normally be treated as URLs |
| 1672 // when typed. For example, if the user searched for "google.com" and types | 1130 // when typed. For example, if the user searched for "google.com" and types |
| 1673 // "goog", don't autocomplete to the search term "google.com". Otherwise, | 1131 // "goog", don't autocomplete to the search term "google.com". Otherwise, |
| 1674 // the input will look like a URL but act like a search, which is confusing. | 1132 // the input will look like a URL but act like a search, which is confusing. |
| 1675 // NOTE: We don't check this in the following cases: | 1133 // NOTE: We don't check this in the following cases: |
| 1676 // * When inline autocomplete is disabled, we won't be inline | 1134 // * When inline autocomplete is disabled, we won't be inline |
| 1677 // autocompleting this term, so we don't need to worry about confusion as | 1135 // autocompleting this term, so we don't need to worry about confusion as |
| 1678 // much. This also prevents calling Classify() again from inside the | 1136 // much. This also prevents calling Classify() again from inside the |
| 1679 // classifier (which will corrupt state and likely crash), since the | 1137 // classifier (which will corrupt state and likely crash), since the |
| 1680 // classifier always disables inline autocomplete. | 1138 // classifier always disables inline autocomplete. |
| 1681 // * When the user has typed the whole term, the "what you typed" history | 1139 // * When the user has typed the whole term, the "what you typed" history |
| 1682 // match will outrank us for URL-like inputs anyway, so we need not do | 1140 // match will outrank us for URL-like inputs anyway, so we need not do |
| 1683 // anything special. | 1141 // anything special. |
| 1684 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) { | 1142 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) { |
| 1685 AutocompleteMatch match; | 1143 AutocompleteMatch match; |
| 1686 classifier->Classify(i->term, false, false, &match, NULL); | 1144 classifier->Classify(i->term, false, false, &match, NULL); |
| 1687 prevent_inline_autocomplete = | 1145 prevent_inline_autocomplete = |
| 1688 !AutocompleteMatch::IsSearchType(match.type); | 1146 !AutocompleteMatch::IsSearchType(match.type); |
| 1689 } | 1147 } |
| 1690 | 1148 |
| 1691 int relevance = CalculateRelevanceForHistory( | 1149 int relevance = CalculateRelevanceForHistory( |
| 1692 i->time, is_keyword, !prevent_inline_autocomplete, | 1150 i->time, is_keyword, !prevent_inline_autocomplete, |
| 1693 prevent_search_history_inlining); | 1151 prevent_search_history_inlining); |
| 1694 scored_results.push_back(SuggestResult( | 1152 scored_results.push_back( |
| 1695 i->term, AutocompleteMatchType::SEARCH_HISTORY, i->term, | 1153 SuggestResult(i->term, |
| 1696 base::string16(), std::string(), std::string(), is_keyword, relevance, | 1154 AutocompleteMatchType::SEARCH_HISTORY, |
| 1697 false, false, input_text)); | 1155 i->term, |
| 1156 base::string16(), |
| 1157 std::string(), |
| 1158 std::string(), |
| 1159 is_keyword, |
| 1160 relevance, |
| 1161 false, |
| 1162 false, |
| 1163 input_text)); |
| 1698 } | 1164 } |
| 1699 | 1165 |
| 1700 // History returns results sorted for us. However, we may have docked some | 1166 // History returns results sorted for us. However, we may have docked some |
| 1701 // results' scores, so things are no longer in order. Do a stable sort to get | 1167 // results' scores, so things are no longer in order. Do a stable sort to get |
| 1702 // things back in order without otherwise disturbing results with equal | 1168 // things back in order without otherwise disturbing results with equal |
| 1703 // scores, then force the scores to be unique, so that the order in which | 1169 // scores, then force the scores to be unique, so that the order in which |
| 1704 // they're shown is deterministic. | 1170 // they're shown is deterministic. |
| 1705 std::stable_sort(scored_results.begin(), scored_results.end(), | 1171 std::stable_sort(scored_results.begin(), scored_results.end(), |
| 1706 CompareScoredResults()); | 1172 CompareScoredResults()); |
| 1707 int last_relevance = 0; | 1173 int last_relevance = 0; |
| 1708 for (SuggestResults::iterator i(scored_results.begin()); | 1174 for (SuggestResults::iterator i(scored_results.begin()); |
| 1709 i != scored_results.end(); ++i) { | 1175 i != scored_results.end(); |
| 1176 ++i) { |
| 1710 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance)) | 1177 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance)) |
| 1711 i->set_relevance(last_relevance - 1); | 1178 i->set_relevance(last_relevance - 1); |
| 1712 last_relevance = i->relevance(); | 1179 last_relevance = i->relevance(); |
| 1713 } | 1180 } |
| 1714 | 1181 |
| 1715 return scored_results; | 1182 return scored_results; |
| 1716 } | 1183 } |
| 1717 | 1184 |
| 1718 void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results, | 1185 void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results, |
| 1719 const std::string& metadata, | 1186 const std::string& metadata, |
| 1720 MatchMap* map) { | 1187 MatchMap* map) { |
| 1721 for (size_t i = 0; i < results.size(); ++i) { | 1188 for (size_t i = 0; i < results.size(); ++i) { |
| 1722 const bool is_keyword = results[i].from_keyword_provider(); | 1189 const bool is_keyword = results[i].from_keyword_provider(); |
| 1723 const base::string16& input = is_keyword ? keyword_input_.text() | 1190 const base::string16& input = |
| 1724 : input_.text(); | 1191 is_keyword ? keyword_input_.text() : input_.text(); |
| 1725 AddMatchToMap(results[i], input, metadata, i, map); | 1192 AddMatchToMap(results[i], |
| 1193 is_keyword ? keyword_input_ : input_, |
| 1194 input, |
| 1195 GetTemplateURL(results[i]), |
| 1196 metadata, |
| 1197 i, |
| 1198 ShouldAppendExtraQueryParams(results[i]), |
| 1199 map); |
| 1726 } | 1200 } |
| 1727 } | 1201 } |
| 1728 | 1202 |
| 1203 const TemplateURL* SearchProvider::GetTemplateURL(const SuggestResult& result) { |
| 1204 return result.from_keyword_provider() ? providers_.GetKeywordProviderURL() |
| 1205 : providers_.GetDefaultProviderURL(); |
| 1206 } |
| 1207 |
| 1208 bool SearchProvider::ShouldAppendExtraQueryParams(const SuggestResult& result) { |
| 1209 return !result.from_keyword_provider() || |
| 1210 providers_.default_provider().empty(); |
| 1211 } |
| 1212 |
| 1729 int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const { | 1213 int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const { |
| 1730 // Use the suggested verbatim relevance score if it is non-negative (valid), | 1214 // Use the suggested verbatim relevance score if it is non-negative (valid), |
| 1731 // if inline autocomplete isn't prevented (always show verbatim on backspace), | 1215 // if inline autocomplete isn't prevented (always show verbatim on backspace), |
| 1732 // and if it won't suppress verbatim, leaving no default provider matches. | 1216 // and if it won't suppress verbatim, leaving no default provider matches. |
| 1733 // Otherwise, if the default provider returned no matches and was still able | 1217 // Otherwise, if the default provider returned no matches and was still able |
| 1734 // to suppress verbatim, the user would have no search/nav matches and may be | 1218 // to suppress verbatim, the user would have no search/nav matches and may be |
| 1735 // left unable to search using their default provider from the omnibox. | 1219 // left unable to search using their default provider from the omnibox. |
| 1736 // Check for results on each verbatim calculation, as results from older | 1220 // Check for results on each verbatim calculation, as results from older |
| 1737 // queries (on previous input) may be trimmed for failing to inline new input. | 1221 // queries (on previous input) may be trimmed for failing to inline new input. |
| 1738 bool use_server_relevance = | 1222 bool use_server_relevance = (default_results_.verbatim_relevance >= 0) && |
| 1739 (default_results_.verbatim_relevance >= 0) && | 1223 !input_.prevent_inline_autocomplete() && |
| 1740 !input_.prevent_inline_autocomplete() && | 1224 ((default_results_.verbatim_relevance > 0) || |
| 1741 ((default_results_.verbatim_relevance > 0) || | 1225 !default_results_.suggest_results.empty() || |
| 1742 !default_results_.suggest_results.empty() || | 1226 !default_results_.navigation_results.empty()); |
| 1743 !default_results_.navigation_results.empty()); | |
| 1744 if (relevance_from_server) | 1227 if (relevance_from_server) |
| 1745 *relevance_from_server = use_server_relevance; | 1228 *relevance_from_server = use_server_relevance; |
| 1746 return use_server_relevance ? | 1229 return use_server_relevance ? default_results_.verbatim_relevance |
| 1747 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim(); | 1230 : CalculateRelevanceForVerbatim(); |
| 1748 } | 1231 } |
| 1749 | 1232 |
| 1750 int SearchProvider::CalculateRelevanceForVerbatim() const { | 1233 int SearchProvider::CalculateRelevanceForVerbatim() const { |
| 1751 if (!providers_.keyword_provider().empty()) | 1234 if (!providers_.keyword_provider().empty()) |
| 1752 return 250; | 1235 return 250; |
| 1753 return CalculateRelevanceForVerbatimIgnoringKeywordModeState(); | 1236 return CalculateRelevanceForVerbatimIgnoringKeywordModeState(); |
| 1754 } | 1237 } |
| 1755 | 1238 |
| 1756 int SearchProvider:: | 1239 int SearchProvider::CalculateRelevanceForVerbatimIgnoringKeywordModeState() |
| 1757 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const { | 1240 const { |
| 1758 switch (input_.type()) { | 1241 switch (input_.type()) { |
| 1759 case AutocompleteInput::UNKNOWN: | 1242 case AutocompleteInput::UNKNOWN: |
| 1760 case AutocompleteInput::QUERY: | 1243 case AutocompleteInput::QUERY: |
| 1761 case AutocompleteInput::FORCED_QUERY: | 1244 case AutocompleteInput::FORCED_QUERY: |
| 1762 return kNonURLVerbatimRelevance; | 1245 return kNonURLVerbatimRelevance; |
| 1763 | 1246 |
| 1764 case AutocompleteInput::URL: | 1247 case AutocompleteInput::URL: |
| 1765 return 850; | 1248 return 850; |
| 1766 | 1249 |
| 1767 default: | 1250 default: |
| 1768 NOTREACHED(); | 1251 NOTREACHED(); |
| 1769 return 0; | 1252 return 0; |
| 1770 } | 1253 } |
| 1771 } | 1254 } |
| 1772 | 1255 |
| 1773 int SearchProvider::GetKeywordVerbatimRelevance( | 1256 int SearchProvider::GetKeywordVerbatimRelevance( |
| 1774 bool* relevance_from_server) const { | 1257 bool* relevance_from_server) const { |
| 1775 // Use the suggested verbatim relevance score if it is non-negative (valid), | 1258 // Use the suggested verbatim relevance score if it is non-negative (valid), |
| 1776 // if inline autocomplete isn't prevented (always show verbatim on backspace), | 1259 // if inline autocomplete isn't prevented (always show verbatim on backspace), |
| 1777 // and if it won't suppress verbatim, leaving no keyword provider matches. | 1260 // and if it won't suppress verbatim, leaving no keyword provider matches. |
| 1778 // Otherwise, if the keyword provider returned no matches and was still able | 1261 // Otherwise, if the keyword provider returned no matches and was still able |
| 1779 // to suppress verbatim, the user would have no search/nav matches and may be | 1262 // to suppress verbatim, the user would have no search/nav matches and may be |
| 1780 // left unable to search using their keyword provider from the omnibox. | 1263 // left unable to search using their keyword provider from the omnibox. |
| 1781 // Check for results on each verbatim calculation, as results from older | 1264 // Check for results on each verbatim calculation, as results from older |
| 1782 // queries (on previous input) may be trimmed for failing to inline new input. | 1265 // queries (on previous input) may be trimmed for failing to inline new input. |
| 1783 bool use_server_relevance = | 1266 bool use_server_relevance = (keyword_results_.verbatim_relevance >= 0) && |
| 1784 (keyword_results_.verbatim_relevance >= 0) && | 1267 !input_.prevent_inline_autocomplete() && |
| 1785 !input_.prevent_inline_autocomplete() && | 1268 ((keyword_results_.verbatim_relevance > 0) || |
| 1786 ((keyword_results_.verbatim_relevance > 0) || | 1269 !keyword_results_.suggest_results.empty() || |
| 1787 !keyword_results_.suggest_results.empty() || | 1270 !keyword_results_.navigation_results.empty()); |
| 1788 !keyword_results_.navigation_results.empty()); | |
| 1789 if (relevance_from_server) | 1271 if (relevance_from_server) |
| 1790 *relevance_from_server = use_server_relevance; | 1272 *relevance_from_server = use_server_relevance; |
| 1791 return use_server_relevance ? | 1273 return use_server_relevance |
| 1792 keyword_results_.verbatim_relevance : | 1274 ? keyword_results_.verbatim_relevance |
| 1793 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(), | 1275 : CalculateRelevanceForKeywordVerbatim( |
| 1794 keyword_input_.prefer_keyword()); | 1276 keyword_input_.type(), keyword_input_.prefer_keyword()); |
| 1795 } | 1277 } |
| 1796 | 1278 |
| 1797 int SearchProvider::CalculateRelevanceForHistory( | 1279 int SearchProvider::CalculateRelevanceForHistory( |
| 1798 const base::Time& time, | 1280 const base::Time& time, |
| 1799 bool is_keyword, | 1281 bool is_keyword, |
| 1800 bool use_aggressive_method, | 1282 bool use_aggressive_method, |
| 1801 bool prevent_search_history_inlining) const { | 1283 bool prevent_search_history_inlining) const { |
| 1802 // The relevance of past searches falls off over time. There are two distinct | 1284 // The relevance of past searches falls off over time. There are two distinct |
| 1803 // equations used. If the first equation is used (searches to the primary | 1285 // equations used. If the first equation is used (searches to the primary |
| 1804 // provider that we want to score aggressively), the score is in the range | 1286 // provider that we want to score aggressively), the score is in the range |
| 1805 // 1300-1599 (unless |prevent_search_history_inlining|, in which case | 1287 // 1300-1599 (unless |prevent_search_history_inlining|, in which case |
| 1806 // it's in the range 1200-1299). If the second equation is used the | 1288 // it's in the range 1200-1299). If the second equation is used the |
| 1807 // relevance of a search 15 minutes ago is discounted 50 points, while the | 1289 // relevance of a search 15 minutes ago is discounted 50 points, while the |
| 1808 // relevance of a search two weeks ago is discounted 450 points. | 1290 // relevance of a search two weeks ago is discounted 450 points. |
| 1809 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0); | 1291 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0); |
| 1810 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider(); | 1292 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider(); |
| 1811 if (is_primary_provider && use_aggressive_method) { | 1293 if (is_primary_provider && use_aggressive_method) { |
| 1812 // Searches with the past two days get a different curve. | 1294 // Searches with the past two days get a different curve. |
| 1813 const double autocomplete_time = 2 * 24 * 60 * 60; | 1295 const double autocomplete_time = 2 * 24 * 60 * 60; |
| 1814 if (elapsed_time < autocomplete_time) { | 1296 if (elapsed_time < autocomplete_time) { |
| 1815 int max_score = is_keyword ? 1599 : 1399; | 1297 int max_score = is_keyword ? 1599 : 1399; |
| 1816 if (prevent_search_history_inlining) | 1298 if (prevent_search_history_inlining) |
| 1817 max_score = 1299; | 1299 max_score = 1299; |
| 1818 return max_score - static_cast<int>(99 * | 1300 return max_score - |
| 1819 std::pow(elapsed_time / autocomplete_time, 2.5)); | 1301 static_cast<int>(99 * |
| 1302 std::pow(elapsed_time / autocomplete_time, 2.5)); |
| 1820 } | 1303 } |
| 1821 elapsed_time -= autocomplete_time; | 1304 elapsed_time -= autocomplete_time; |
| 1822 } | 1305 } |
| 1823 | 1306 |
| 1824 const int score_discount = | 1307 const int score_discount = |
| 1825 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3)); | 1308 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3)); |
| 1826 | 1309 |
| 1827 // Don't let scores go below 0. Negative relevance scores are meaningful in | 1310 // Don't let scores go below 0. Negative relevance scores are meaningful in |
| 1828 // a different way. | 1311 // a different way. |
| 1829 int base_score; | 1312 int base_score; |
| 1830 if (is_primary_provider) | 1313 if (is_primary_provider) |
| 1831 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050; | 1314 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050; |
| 1832 else | 1315 else |
| 1833 base_score = 200; | 1316 base_score = 200; |
| 1834 return std::max(0, base_score - score_discount); | 1317 return std::max(0, base_score - score_discount); |
| 1835 } | 1318 } |
| 1836 | 1319 |
| 1837 void SearchProvider::AddMatchToMap(const SuggestResult& result, | |
| 1838 const base::string16& input_text, | |
| 1839 const std::string& metadata, | |
| 1840 int accepted_suggestion, | |
| 1841 MatchMap* map) { | |
| 1842 // On non-mobile, ask the instant controller for the appropriate start margin. | |
| 1843 // On mobile the start margin is unused, so leave the value as default there. | |
| 1844 int omnibox_start_margin = chrome::kDisableStartMargin; | |
| 1845 #if !defined(OS_ANDROID) && !defined(IOS) | |
| 1846 if (chrome::IsInstantExtendedAPIEnabled()) { | |
| 1847 Browser* browser = | |
| 1848 chrome::FindBrowserWithProfile(profile_, chrome::GetActiveDesktop()); | |
| 1849 if (browser && browser->instant_controller() && | |
| 1850 browser->instant_controller()->instant()) { | |
| 1851 omnibox_start_margin = | |
| 1852 browser->instant_controller()->instant()->omnibox_bounds().x(); | |
| 1853 } | |
| 1854 } | |
| 1855 #endif // !defined(OS_ANDROID) && !defined(IOS) | |
| 1856 | |
| 1857 const TemplateURL* template_url = result.from_keyword_provider() ? | |
| 1858 providers_.GetKeywordProviderURL() : providers_.GetDefaultProviderURL(); | |
| 1859 AutocompleteMatch match = CreateSearchSuggestion( | |
| 1860 this, input_, input_text, result, template_url, accepted_suggestion, | |
| 1861 omnibox_start_margin, | |
| 1862 !result.from_keyword_provider() || providers_.default_provider().empty()); | |
| 1863 if (!match.destination_url.is_valid()) | |
| 1864 return; | |
| 1865 match.search_terms_args->bookmark_bar_pinned = | |
| 1866 profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar); | |
| 1867 match.RecordAdditionalInfo(kRelevanceFromServerKey, | |
| 1868 result.relevance_from_server() ? kTrue : kFalse); | |
| 1869 match.RecordAdditionalInfo(kShouldPrefetchKey, | |
| 1870 result.should_prefetch() ? kTrue : kFalse); | |
| 1871 | |
| 1872 if (!result.deletion_url().empty()) { | |
| 1873 GURL url(match.destination_url.GetOrigin().Resolve(result.deletion_url())); | |
| 1874 if (url.is_valid()) { | |
| 1875 match.RecordAdditionalInfo(kDeletionUrlKey, url.spec()); | |
| 1876 match.deletable = true; | |
| 1877 } | |
| 1878 } | |
| 1879 | |
| 1880 // Metadata is needed only for prefetching queries. | |
| 1881 if (result.should_prefetch()) | |
| 1882 match.RecordAdditionalInfo(kSuggestMetadataKey, metadata); | |
| 1883 | |
| 1884 // Try to add |match| to |map|. If a match for |query_string| is already in | |
| 1885 // |map|, replace it if |match| is more relevant. | |
| 1886 // NOTE: Keep this ToLower() call in sync with url_database.cc. | |
| 1887 MatchKey match_key( | |
| 1888 std::make_pair(base::i18n::ToLower(result.suggestion()), | |
| 1889 match.search_terms_args->suggest_query_params)); | |
| 1890 const std::pair<MatchMap::iterator, bool> i( | |
| 1891 map->insert(std::make_pair(match_key, match))); | |
| 1892 | |
| 1893 bool should_prefetch = result.should_prefetch(); | |
| 1894 if (!i.second) { | |
| 1895 // NOTE: We purposefully do a direct relevance comparison here instead of | |
| 1896 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items | |
| 1897 // added first" rather than "items alphabetically first" when the scores are | |
| 1898 // equal. The only case this matters is when a user has results with the | |
| 1899 // same score that differ only by capitalization; because the history system | |
| 1900 // returns results sorted by recency, this means we'll pick the most | |
| 1901 // recent such result even if the precision of our relevance score is too | |
| 1902 // low to distinguish the two. | |
| 1903 if (match.relevance > i.first->second.relevance) { | |
| 1904 i.first->second = match; | |
| 1905 } else if (match.keyword == i.first->second.keyword) { | |
| 1906 // Old and new matches are from the same search provider. It is okay to | |
| 1907 // record one match's prefetch data onto a different match (for the same | |
| 1908 // query string) for the following reasons: | |
| 1909 // 1. Because the suggest server only sends down a query string from which | |
| 1910 // we construct a URL, rather than sending a full URL, and because we | |
| 1911 // construct URLs from query strings in the same way every time, the URLs | |
| 1912 // for the two matches will be the same. Therefore, we won't end up | |
| 1913 // prefetching something the server didn't intend. | |
| 1914 // 2. Presumably the server sets the prefetch bit on a match it things is | |
| 1915 // sufficiently relevant that the user is likely to choose it. Surely | |
| 1916 // setting the prefetch bit on a match of even higher relevance won't | |
| 1917 // violate this assumption. | |
| 1918 should_prefetch |= ShouldPrefetch(i.first->second); | |
| 1919 i.first->second.RecordAdditionalInfo(kShouldPrefetchKey, | |
| 1920 should_prefetch ? kTrue : kFalse); | |
| 1921 if (should_prefetch) | |
| 1922 i.first->second.RecordAdditionalInfo(kSuggestMetadataKey, metadata); | |
| 1923 } | |
| 1924 } | |
| 1925 } | |
| 1926 | |
| 1927 AutocompleteMatch SearchProvider::NavigationToMatch( | 1320 AutocompleteMatch SearchProvider::NavigationToMatch( |
| 1928 const NavigationResult& navigation) { | 1321 const NavigationResult& navigation) { |
| 1929 const base::string16& input = navigation.from_keyword_provider() ? | 1322 const base::string16& input = navigation.from_keyword_provider() |
| 1930 keyword_input_.text() : input_.text(); | 1323 ? keyword_input_.text() |
| 1324 : input_.text(); |
| 1931 AutocompleteMatch match(this, navigation.relevance(), false, | 1325 AutocompleteMatch match(this, navigation.relevance(), false, |
| 1932 AutocompleteMatchType::NAVSUGGEST); | 1326 AutocompleteMatchType::NAVSUGGEST); |
| 1933 match.destination_url = navigation.url(); | 1327 match.destination_url = navigation.url(); |
| 1934 | 1328 |
| 1935 // First look for the user's input inside the formatted url as it would be | 1329 // First look for the user's input inside the formatted url as it would be |
| 1936 // without trimming the scheme, so we can find matches at the beginning of the | 1330 // without trimming the scheme, so we can find matches at the beginning of the |
| 1937 // scheme. | 1331 // scheme. |
| 1938 const URLPrefix* prefix = | 1332 const URLPrefix* prefix = |
| 1939 URLPrefix::BestURLPrefix(navigation.formatted_url(), input); | 1333 URLPrefix::BestURLPrefix(navigation.formatted_url(), input); |
| 1940 size_t match_start = (prefix == NULL) ? | 1334 size_t match_start = (prefix == NULL) ? |
| 1941 navigation.formatted_url().find(input) : prefix->prefix.length(); | 1335 navigation.formatted_url().find(input) : prefix->prefix.length(); |
| 1942 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) && | 1336 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) && |
| 1943 (!prefix || (match_start != 0)); | 1337 (!prefix || (match_start != 0)); |
| 1944 const net::FormatUrlTypes format_types = | 1338 const net::FormatUrlTypes format_types = |
| 1945 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP); | 1339 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP); |
| 1946 | 1340 |
| 1947 const std::string languages( | 1341 const std::string languages( |
| 1948 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)); | 1342 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)); |
| 1949 size_t inline_autocomplete_offset = (prefix == NULL) ? | 1343 size_t inline_autocomplete_offset = (prefix == NULL) ? |
| 1950 base::string16::npos : (match_start + input.length()); | 1344 base::string16::npos : (match_start + input.length()); |
| 1951 match.fill_into_edit += | 1345 match.fill_into_edit += |
| 1952 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(), | 1346 AutocompleteInput::FormattedStringWithEquivalentMeaning( |
| 1953 net::FormatUrl(navigation.url(), languages, format_types, | 1347 navigation.url(), |
| 1954 net::UnescapeRule::SPACES, NULL, NULL, | 1348 net::FormatUrl(navigation.url(), |
| 1349 languages, |
| 1350 format_types, |
| 1351 net::UnescapeRule::SPACES, |
| 1352 NULL, |
| 1353 NULL, |
| 1955 &inline_autocomplete_offset)); | 1354 &inline_autocomplete_offset)); |
| 1956 // Preserve the forced query '?' prefix in |match.fill_into_edit|. | 1355 // Preserve the forced query '?' prefix in |match.fill_into_edit|. |
| 1957 // Otherwise, user edits to a suggestion would show non-Search results. | 1356 // Otherwise, user edits to a suggestion would show non-Search results. |
| 1958 if (input_.type() == AutocompleteInput::FORCED_QUERY) { | 1357 if (input_.type() == AutocompleteInput::FORCED_QUERY) { |
| 1959 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?")); | 1358 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?")); |
| 1960 if (inline_autocomplete_offset != base::string16::npos) | 1359 if (inline_autocomplete_offset != base::string16::npos) |
| 1961 ++inline_autocomplete_offset; | 1360 ++inline_autocomplete_offset; |
| 1962 } | 1361 } |
| 1963 if (!input_.prevent_inline_autocomplete() && | 1362 if (!input_.prevent_inline_autocomplete() && |
| 1964 (inline_autocomplete_offset != base::string16::npos)) { | 1363 (inline_autocomplete_offset != base::string16::npos)) { |
| 1965 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length()); | 1364 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length()); |
| 1966 // A navsuggestion can only be the default match when there is no | 1365 // A navsuggestion can only be the default match when there is no |
| 1967 // keyword provider active, lest it appear first and break the user | 1366 // keyword provider active, lest it appear first and break the user |
| 1968 // out of keyword mode. | 1367 // out of keyword mode. |
| 1969 match.allowed_to_be_default_match = | 1368 match.allowed_to_be_default_match = |
| 1970 (providers_.GetKeywordProviderURL() == NULL); | 1369 (providers_.GetKeywordProviderURL() == NULL); |
| 1971 match.inline_autocompletion = | 1370 match.inline_autocompletion = |
| 1972 match.fill_into_edit.substr(inline_autocomplete_offset); | 1371 match.fill_into_edit.substr(inline_autocomplete_offset); |
| 1973 } | 1372 } |
| 1974 | 1373 |
| 1975 match.contents = navigation.match_contents(); | 1374 match.contents = navigation.match_contents(); |
| 1976 match.contents_class = navigation.match_contents_class(); | 1375 match.contents_class = navigation.match_contents_class(); |
| 1977 match.description = navigation.description(); | 1376 match.description = navigation.description(); |
| 1978 AutocompleteMatch::ClassifyMatchInString(input, match.description, | 1377 AutocompleteMatch::ClassifyMatchInString(input, |
| 1979 ACMatchClassification::NONE, &match.description_class); | 1378 match.description, |
| 1379 ACMatchClassification::NONE, |
| 1380 &match.description_class); |
| 1980 | 1381 |
| 1981 match.RecordAdditionalInfo( | 1382 match.RecordAdditionalInfo( |
| 1982 kRelevanceFromServerKey, | 1383 kRelevanceFromServerKey, |
| 1983 navigation.relevance_from_server() ? kTrue : kFalse); | 1384 navigation.relevance_from_server() ? kTrue : kFalse); |
| 1984 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse); | 1385 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse); |
| 1985 | 1386 |
| 1986 return match; | 1387 return match; |
| 1987 } | 1388 } |
| 1988 | 1389 |
| 1989 void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() { | 1390 void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() { |
| (...skipping 21 matching lines...) Expand all Loading... |
| 2011 keyword_results_.verbatim_relevance = -1; | 1412 keyword_results_.verbatim_relevance = -1; |
| 2012 default_results_.verbatim_relevance = -1; | 1413 default_results_.verbatim_relevance = -1; |
| 2013 return; | 1414 return; |
| 2014 } | 1415 } |
| 2015 // Now we know we can enforce the minimum score constraint even after | 1416 // Now we know we can enforce the minimum score constraint even after |
| 2016 // the navigation matches are demoted. Proceed to demote the navigation | 1417 // the navigation matches are demoted. Proceed to demote the navigation |
| 2017 // matches to enforce the query-must-come-first constraint. | 1418 // matches to enforce the query-must-come-first constraint. |
| 2018 // Cap the relevance score of all results. | 1419 // Cap the relevance score of all results. |
| 2019 for (NavigationResults::iterator it = | 1420 for (NavigationResults::iterator it = |
| 2020 keyword_results_.navigation_results.begin(); | 1421 keyword_results_.navigation_results.begin(); |
| 2021 it != keyword_results_.navigation_results.end(); ++it) { | 1422 it != keyword_results_.navigation_results.end(); |
| 1423 ++it) { |
| 2022 if (it->relevance() < max_query_relevance) | 1424 if (it->relevance() < max_query_relevance) |
| 2023 return; | 1425 return; |
| 2024 max_query_relevance = std::max(max_query_relevance - 1, 0); | 1426 max_query_relevance = std::max(max_query_relevance - 1, 0); |
| 2025 it->set_relevance(max_query_relevance); | 1427 it->set_relevance(max_query_relevance); |
| 2026 it->set_relevance_from_server(relevance_from_server); | 1428 it->set_relevance_from_server(relevance_from_server); |
| 2027 } | 1429 } |
| 2028 } | 1430 } |
| 2029 | 1431 |
| 2030 void SearchProvider::UpdateDone() { | 1432 void SearchProvider::UpdateDone() { |
| 2031 // We're done when the timer isn't running, there are no suggest queries | 1433 // We're done when the timer isn't running, there are no suggest queries |
| 2032 // pending, and we're not waiting on Instant. | 1434 // pending, and we're not waiting on Instant. |
| 2033 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0); | 1435 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0); |
| 2034 } | 1436 } |
| 2035 | 1437 |
| 2036 bool SearchProvider::CanSendURL( | |
| 2037 const GURL& current_page_url, | |
| 2038 const GURL& suggest_url, | |
| 2039 const TemplateURL* template_url, | |
| 2040 AutocompleteInput::PageClassification page_classification, | |
| 2041 Profile* profile) { | |
| 2042 if (!current_page_url.is_valid()) | |
| 2043 return false; | |
| 2044 | |
| 2045 // TODO(hfung): Show Most Visited on NTP with appropriate verbatim | |
| 2046 // description when the user actively focuses on the omnibox as discussed in | |
| 2047 // crbug/305366 if Most Visited (or something similar) will launch. | |
| 2048 if ((page_classification == | |
| 2049 AutocompleteInput::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS) || | |
| 2050 (page_classification == | |
| 2051 AutocompleteInput::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS)) | |
| 2052 return false; | |
| 2053 | |
| 2054 // Only allow HTTP URLs or HTTPS URLs for the same domain as the search | |
| 2055 // provider. | |
| 2056 if ((current_page_url.scheme() != content::kHttpScheme) && | |
| 2057 ((current_page_url.scheme() != content::kHttpsScheme) || | |
| 2058 !net::registry_controlled_domains::SameDomainOrHost( | |
| 2059 current_page_url, suggest_url, | |
| 2060 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES))) | |
| 2061 return false; | |
| 2062 | |
| 2063 // Make sure we are sending the suggest request through HTTPS to prevent | |
| 2064 // exposing the current page URL to networks before the search provider. | |
| 2065 if (!suggest_url.SchemeIs(content::kHttpsScheme)) | |
| 2066 return false; | |
| 2067 | |
| 2068 // Don't run if there's no profile or in incognito mode. | |
| 2069 if (profile == NULL || profile->IsOffTheRecord()) | |
| 2070 return false; | |
| 2071 | |
| 2072 // Don't run if we can't get preferences or search suggest is not enabled. | |
| 2073 PrefService* prefs = profile->GetPrefs(); | |
| 2074 if (!prefs->GetBoolean(prefs::kSearchSuggestEnabled)) | |
| 2075 return false; | |
| 2076 | |
| 2077 // Only make the request if we know that the provider supports zero suggest | |
| 2078 // (currently only the prepopulated Google provider). | |
| 2079 if (template_url == NULL || !template_url->SupportsReplacement() || | |
| 2080 TemplateURLPrepopulateData::GetEngineType(*template_url) != | |
| 2081 SEARCH_ENGINE_GOOGLE) | |
| 2082 return false; | |
| 2083 | |
| 2084 // Check field trials and settings allow sending the URL on suggest requests. | |
| 2085 ProfileSyncService* service = | |
| 2086 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile); | |
| 2087 browser_sync::SyncPrefs sync_prefs(prefs); | |
| 2088 if (!OmniboxFieldTrial::InZeroSuggestFieldTrial() || | |
| 2089 service == NULL || | |
| 2090 !service->IsSyncEnabledAndLoggedIn() || | |
| 2091 !sync_prefs.GetPreferredDataTypes(syncer::UserTypes()).Has( | |
| 2092 syncer::PROXY_TABS) || | |
| 2093 service->GetEncryptedDataTypes().Has(syncer::SESSIONS)) | |
| 2094 return false; | |
| 2095 | |
| 2096 return true; | |
| 2097 } | |
| OLD | NEW |