blob: 94112fa213f2009fe7faaafe5f2541de02c8ca48 [file] [log] [blame]
[email protected]ffbec692012-02-26 20:26:421// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
5#include "chrome/browser/autocomplete/search_provider.h"
6
[email protected]1cb2dac2010-03-08 21:49:157#include <algorithm>
[email protected]c3a4bd992010-08-18 20:25:018#include <cmath>
[email protected]1cb2dac2010-03-08 21:49:159
[email protected]2041cf342010-02-19 03:15:5910#include "base/callback.h"
[email protected]51124552011-07-16 01:37:1011#include "base/i18n/break_iterator.h"
[email protected]503d03872011-05-06 08:36:2612#include "base/i18n/case_conversion.h"
[email protected]d6e58c6e2009-10-10 20:40:5013#include "base/i18n/icu_string_conversions.h"
[email protected]ffbec692012-02-26 20:26:4214#include "base/json/json_string_value_serializer.h"
initial.commit09911bf2008-07-26 23:55:2915#include "base/message_loop.h"
[email protected]f5b95ba92012-03-27 14:05:1916#include "base/metrics/histogram.h"
[email protected]dc9a6762010-08-16 07:13:5317#include "base/string16.h"
[email protected]371dab12012-06-01 03:23:5518#include "base/string_util.h"
[email protected]1cb2dac2010-03-08 21:49:1519#include "base/utf_string_conversions.h"
[email protected]ea3b9a502011-04-04 14:19:3720#include "chrome/browser/autocomplete/autocomplete_classifier.h"
[email protected]810ffba2012-06-12 01:07:4821#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
[email protected]f5b95ba92012-03-27 14:05:1922#include "chrome/browser/autocomplete/autocomplete_field_trial.h"
[email protected]9ac40092010-10-27 23:05:2623#include "chrome/browser/autocomplete/autocomplete_match.h"
[email protected]5af9bc82012-06-29 00:53:4824#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
[email protected]73c2b1632012-07-02 22:51:3825#include "chrome/browser/autocomplete/autocomplete_result.h"
[email protected]3723e6e2012-06-11 21:06:5626#include "chrome/browser/autocomplete/history_url_provider.h"
[email protected]2c812ba02011-07-14 00:23:1527#include "chrome/browser/autocomplete/keyword_provider.h"
[email protected]371dab12012-06-01 03:23:5528#include "chrome/browser/autocomplete/url_prefix.h"
[email protected]ce560f82009-06-03 09:39:4429#include "chrome/browser/history/history.h"
[email protected]9d2db762012-06-19 00:01:1030#include "chrome/browser/history/history_service_factory.h"
[email protected]10c2d692012-05-11 05:32:2331#include "chrome/browser/history/in_memory_database.h"
[email protected]4ab4c7c2010-11-24 04:49:3432#include "chrome/browser/instant/instant_controller.h"
[email protected]f870a322009-01-16 21:47:2733#include "chrome/browser/net/url_fixer_upper.h"
[email protected]37858e52010-08-26 00:22:0234#include "chrome/browser/prefs/pref_service.h"
[email protected]8ecad5e2010-12-02 21:18:3335#include "chrome/browser/profiles/profile.h"
[email protected]a0ad93ea2012-05-07 22:11:5336#include "chrome/browser/search_engines/search_engine_type.h"
[email protected]9899a612012-08-21 23:50:0437#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
[email protected]8e5c89a2011-06-07 18:13:3338#include "chrome/browser/search_engines/template_url_service.h"
39#include "chrome/browser/search_engines/template_url_service_factory.h"
initial.commit09911bf2008-07-26 23:55:2940#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0241#include "chrome/common/url_constants.h"
initial.commit09911bf2008-07-26 23:55:2942#include "googleurl/src/url_util.h"
[email protected]34ac8f32009-02-22 23:03:2743#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2944#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3445#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5546#include "net/base/net_util.h"
[email protected]319d9e6f2009-02-18 19:47:2147#include "net/http/http_response_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5348#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2149#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1750#include "ui/base/l10n/l10n_util.h"
initial.commit09911bf2008-07-26 23:55:2951
[email protected]e1acf6f2008-10-27 20:43:3352using base::Time;
53using base::TimeDelta;
54
[email protected]51124552011-07-16 01:37:1055namespace {
56
[email protected]7706a522012-08-16 17:42:2557// We keep track in a histogram how many suggest requests we send, how
58// many suggest requests we invalidate (e.g., due to a user typing
59// another character), and how many replies we receive.
60// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
61// (excluding the end-of-list enum value)
62// We do not want values of existing enums to change or else it screws
63// up the statistics.
64enum SuggestRequestsHistogramValue {
65 REQUEST_SENT = 1,
66 REQUEST_INVALIDATED,
67 REPLY_RECEIVED,
68 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
69};
70
71// Increments the appropriate value in the histogram by one.
72void LogOmniboxSuggestRequest(
73 SuggestRequestsHistogramValue request_value) {
74 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
75 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
76}
77
[email protected]51124552011-07-16 01:37:1078bool HasMultipleWords(const string16& text) {
79 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
80 bool found_word = false;
81 if (i.Init()) {
82 while (i.Advance()) {
83 if (i.IsWord()) {
84 if (found_word)
85 return true;
86 found_word = true;
87 }
88 }
89 }
90 return false;
91}
92
[email protected]d1f0a7f2012-06-05 10:26:4293} // namespace
[email protected]51124552011-07-16 01:37:1094
[email protected]033f3422012-03-13 21:24:1895
[email protected]3954c3a2012-04-10 20:17:5596// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:5897
[email protected]85b8d6f2012-05-08 20:53:4798SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
99 : template_url_service_(template_url_service) {
100}
101
102const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
103 return default_provider_.empty() ? NULL :
104 template_url_service_->GetTemplateURLForKeyword(default_provider_);
105}
106
107const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
108 return keyword_provider_.empty() ? NULL :
109 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24110}
111
[email protected]3954c3a2012-04-10 20:17:55112
113// SearchProvider -------------------------------------------------------------
114
115// static
116const int SearchProvider::kDefaultProviderURLFetcherID = 1;
117// static
118const int SearchProvider::kKeywordProviderURLFetcherID = 2;
119// static
120bool SearchProvider::query_suggest_immediately_ = false;
121
[email protected]30f5bc92012-06-26 04:14:55122SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
123 Profile* profile)
[email protected]601858c02010-09-01 17:08:20124 : AutocompleteProvider(listener, profile, "Search"),
[email protected]85b8d6f2012-05-08 20:53:47125 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
[email protected]601858c02010-09-01 17:08:20126 suggest_results_pending_(0),
[email protected]6dc950f2012-07-16 19:49:08127 suggest_field_trial_group_number_(
128 AutocompleteFieldTrial::GetSuggestNumberOfGroups()),
[email protected]d1f0a7f2012-06-05 10:26:42129 has_suggested_relevance_(false),
130 verbatim_relevance_(-1),
[email protected]8e5cc282010-12-05 18:11:39131 have_suggest_results_(false),
[email protected]4ab4c7c2010-11-24 04:49:34132 instant_finalized_(false) {
[email protected]6dc950f2012-07-16 19:49:08133 // Above, we default |suggest_field_trial_group_number_| to the number of
134 // groups to mean "not in field trial." Field trial groups run from 0 to
135 // GetSuggestNumberOfGroups() - 1 (inclusive).
[email protected]f5b95ba92012-03-27 14:05:19136 if (AutocompleteFieldTrial::InSuggestFieldTrial()) {
[email protected]6dc950f2012-07-16 19:49:08137 suggest_field_trial_group_number_ =
[email protected]f5b95ba92012-03-27 14:05:19138 AutocompleteFieldTrial::GetSuggestGroupNameAsNumber();
139 }
140 // Add a beacon to the logs that'll allow us to identify later what
141 // suggest field trial group a user is in. Do this by incrementing a
142 // bucket in a histogram, where the bucket represents the user's
143 // suggest group id.
144 UMA_HISTOGRAM_ENUMERATION(
145 "Omnibox.SuggestFieldTrialBeacon",
[email protected]6dc950f2012-07-16 19:49:08146 suggest_field_trial_group_number_,
[email protected]f5b95ba92012-03-27 14:05:19147 AutocompleteFieldTrial::GetSuggestNumberOfGroups() + 1);
[email protected]4ab4c7c2010-11-24 04:49:34148}
149
[email protected]a2fedb1e2011-01-25 15:23:36150void SearchProvider::FinalizeInstantQuery(const string16& input_text,
151 const string16& suggest_text) {
[email protected]4ab4c7c2010-11-24 04:49:34152 if (done_ || instant_finalized_)
153 return;
154
155 instant_finalized_ = true;
156 UpdateDone();
157
[email protected]e918c112010-12-08 23:03:49158 if (input_text.empty()) {
[email protected]4ab4c7c2010-11-24 04:49:34159 // We only need to update the listener if we're actually done.
160 if (done_)
161 listener_->OnProviderUpdate(false);
162 return;
163 }
164
[email protected]9e789742011-01-10 23:27:32165 default_provider_suggest_text_ = suggest_text;
166
[email protected]a2fedb1e2011-01-25 15:23:36167 string16 adjusted_input_text(input_text);
[email protected]e918c112010-12-08 23:03:49168 AutocompleteInput::RemoveForcedQueryStringIfNecessary(input_.type(),
169 &adjusted_input_text);
170
[email protected]a2fedb1e2011-01-25 15:23:36171 const string16 text = adjusted_input_text + suggest_text;
[email protected]9acdcdc02012-05-21 20:58:36172 bool results_updated = false;
[email protected]4ab4c7c2010-11-24 04:49:34173 // Remove any matches that are identical to |text|. We don't use the
174 // destination_url for comparison as it varies depending upon the index passed
175 // to TemplateURL::ReplaceSearchTerms.
176 for (ACMatches::iterator i = matches_.begin(); i != matches_.end();) {
177 if (((i->type == AutocompleteMatch::SEARCH_HISTORY) ||
178 (i->type == AutocompleteMatch::SEARCH_SUGGEST)) &&
179 (i->fill_into_edit == text)) {
[email protected]e030de62010-11-24 05:41:19180 i = matches_.erase(i);
[email protected]9acdcdc02012-05-21 20:58:36181 results_updated = true;
[email protected]4ab4c7c2010-11-24 04:49:34182 } else {
183 ++i;
184 }
185 }
186
[email protected]55ce8f12012-05-09 04:44:08187 // Add the new instant suggest result. We give it a rank higher than
[email protected]4ab4c7c2010-11-24 04:49:34188 // SEARCH_WHAT_YOU_TYPED so that it gets autocompleted.
189 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
190 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
191 TemplateURLRef::NO_SUGGESTION_CHOSEN;
192 MatchMap match_map;
[email protected]382a0642012-06-06 06:13:52193 AddMatchToMap(text, adjusted_input_text, GetVerbatimRelevance() + 1,
[email protected]4ab4c7c2010-11-24 04:49:34194 AutocompleteMatch::SEARCH_SUGGEST,
[email protected]55ce8f12012-05-09 04:44:08195 did_not_accept_default_suggestion, false, &match_map);
[email protected]9acdcdc02012-05-21 20:58:36196 if (!match_map.empty()) {
197 matches_.push_back(match_map.begin()->second);
198 results_updated = true;
199 }
[email protected]4ab4c7c2010-11-24 04:49:34200
[email protected]9acdcdc02012-05-21 20:58:36201 if (results_updated || done_)
202 listener_->OnProviderUpdate(results_updated);
[email protected]601858c02010-09-01 17:08:20203}
204
initial.commit09911bf2008-07-26 23:55:29205void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27206 bool minimal_changes) {
initial.commit09911bf2008-07-26 23:55:29207 matches_.clear();
208
[email protected]ea3b9a502011-04-04 14:19:37209 instant_finalized_ =
210 (input.matches_requested() != AutocompleteInput::ALL_MATCHES);
[email protected]4ab4c7c2010-11-24 04:49:34211
[email protected]6c85aa02009-02-27 12:08:09212 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29213 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]e29249dc52012-07-19 17:33:50214 Stop(false);
initial.commit09911bf2008-07-26 23:55:29215 return;
216 }
217
[email protected]257ab712009-04-14 17:16:24218 keyword_input_text_.clear();
219 const TemplateURL* keyword_provider =
220 KeywordProvider::GetSubstitutingTemplateURLForInput(profile_, input,
221 &keyword_input_text_);
[email protected]8d457132010-11-04 18:13:40222 if (keyword_input_text_.empty())
[email protected]257ab712009-04-14 17:16:24223 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24224
[email protected]85b8d6f2012-05-08 20:53:47225 TemplateURLService* model = providers_.template_url_service();
226 DCHECK(model);
227 model->Load();
228 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07229 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24230 default_provider = NULL;
231
232 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18233 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24234
235 if (!default_provider && !keyword_provider) {
236 // No valid providers.
[email protected]e29249dc52012-07-19 17:33:50237 Stop(false);
initial.commit09911bf2008-07-26 23:55:29238 return;
239 }
240
241 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24242 // or the providers, abort the query.
[email protected]85b8d6f2012-05-08 20:53:47243 string16 default_provider_keyword(default_provider ?
244 default_provider->keyword() : string16());
245 string16 keyword_provider_keyword(keyword_provider ?
246 keyword_provider->keyword() : string16());
[email protected]9e789742011-01-10 23:27:32247 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47248 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]9e789742011-01-10 23:27:32249 if (done_)
250 default_provider_suggest_text_.clear();
251 else
[email protected]e29249dc52012-07-19 17:33:50252 Stop(false);
[email protected]257ab712009-04-14 17:16:24253 }
initial.commit09911bf2008-07-26 23:55:29254
[email protected]85b8d6f2012-05-08 20:53:47255 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29256
257 if (input.text().empty()) {
258 // User typed "?" alone. Give them a placeholder result indicating what
259 // this syntax does.
[email protected]257ab712009-04-14 17:16:24260 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00261 AutocompleteMatch match;
262 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36263 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24264 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35265 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47266 match.keyword = providers_.default_provider();
[email protected]257ab712009-04-14 17:16:24267 matches_.push_back(match);
268 }
[email protected]e29249dc52012-07-19 17:33:50269 Stop(false);
initial.commit09911bf2008-07-26 23:55:29270 return;
271 }
272
273 input_ = input;
274
[email protected]8d457132010-11-04 18:13:40275 DoHistoryQuery(minimal_changes);
[email protected]8deeb952008-10-09 18:21:27276 StartOrStopSuggestQuery(minimal_changes);
initial.commit09911bf2008-07-26 23:55:29277 ConvertResultsToAutocompleteMatches();
278}
279
[email protected]55ce8f12012-05-09 04:44:08280SearchProvider::Result::Result(int relevance) : relevance_(relevance) {}
281SearchProvider::Result::~Result() {}
282
283SearchProvider::SuggestResult::SuggestResult(const string16& suggestion,
284 int relevance)
285 : Result(relevance),
286 suggestion_(suggestion) {
287}
288
289SearchProvider::SuggestResult::~SuggestResult() {}
290
291SearchProvider::NavigationResult::NavigationResult(const GURL& url,
292 const string16& description,
293 int relevance)
294 : Result(relevance),
295 url_(url),
296 description_(description) {
297 DCHECK(url_.is_valid());
298}
299
300SearchProvider::NavigationResult::~NavigationResult() {}
301
302class SearchProvider::CompareScoredResults {
[email protected]51124552011-07-16 01:37:10303 public:
[email protected]55ce8f12012-05-09 04:44:08304 bool operator()(const Result& a, const Result& b) {
[email protected]51124552011-07-16 01:37:10305 // Sort in descending relevance order.
[email protected]55ce8f12012-05-09 04:44:08306 return a.relevance() > b.relevance();
[email protected]51124552011-07-16 01:37:10307 }
308};
309
initial.commit09911bf2008-07-26 23:55:29310void SearchProvider::Run() {
311 // Start a new request with the current input.
312 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24313 suggest_results_pending_ = 0;
[email protected]a0ad93ea2012-05-07 22:11:53314 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]85b8d6f2012-05-08 20:53:47315 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
316 if (default_url && !default_url->suggestions_url().empty()) {
[email protected]257ab712009-04-14 17:16:24317 suggest_results_pending_++;
[email protected]7706a522012-08-16 17:42:25318 LogOmniboxSuggestRequest(REQUEST_SENT);
[email protected]033f3422012-03-13 21:24:18319 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
[email protected]85b8d6f2012-05-08 20:53:47320 default_url->suggestions_url_ref(), input_.text()));
[email protected]3954c3a2012-04-10 20:17:55321 }
[email protected]85b8d6f2012-05-08 20:53:47322 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
323 if (keyword_url && !keyword_url->suggestions_url().empty()) {
[email protected]3954c3a2012-04-10 20:17:55324 suggest_results_pending_++;
[email protected]7706a522012-08-16 17:42:25325 LogOmniboxSuggestRequest(REQUEST_SENT);
[email protected]3954c3a2012-04-10 20:17:55326 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
[email protected]85b8d6f2012-05-08 20:53:47327 keyword_url->suggestions_url_ref(), keyword_input_text_));
[email protected]257ab712009-04-14 17:16:24328 }
[email protected]85b8d6f2012-05-08 20:53:47329
330 // Both the above can fail if the providers have been modified or deleted
331 // since the query began.
332 if (suggest_results_pending_ == 0) {
333 UpdateDone();
334 // We only need to update the listener if we're actually done.
335 if (done_)
336 listener_->OnProviderUpdate(false);
337 }
initial.commit09911bf2008-07-26 23:55:29338}
339
[email protected]e29249dc52012-07-19 17:33:50340void SearchProvider::Stop(bool clear_cached_results) {
initial.commit09911bf2008-07-26 23:55:29341 StopSuggest();
342 done_ = true;
[email protected]9e789742011-01-10 23:27:32343 default_provider_suggest_text_.clear();
[email protected]e29249dc52012-07-19 17:33:50344
345 if (clear_cached_results)
346 ClearResults();
initial.commit09911bf2008-07-26 23:55:29347}
348
[email protected]0e9e8782012-05-15 23:01:51349void SearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
350 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
351 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
352 new_entry.set_provider(AsOmniboxEventProviderType());
353 new_entry.set_provider_done(done_);
354}
355
[email protected]10c2d692012-05-11 05:32:23356void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29357 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24358 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25359 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15360 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06361 const net::HttpResponseHeaders* const response_headers =
[email protected]7cc6e5632011-10-25 17:56:12362 source->GetResponseHeaders();
[email protected]c530c852011-10-24 18:18:34363 std::string json_data;
364 source->GetResponseAsString(&json_data);
[email protected]6c85aa02009-02-27 12:08:09365 // JSON is supposed to be UTF-8, but some suggest service providers send JSON
366 // files in non-UTF-8 encodings. The actual encoding is usually specified in
367 // the Content-Type header field.
[email protected]ec9207d32008-09-26 00:51:06368 if (response_headers) {
369 std::string charset;
370 if (response_headers->GetCharset(&charset)) {
[email protected]a2fedb1e2011-01-25 15:23:36371 string16 data_16;
[email protected]ec9207d32008-09-26 00:51:06372 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
[email protected]c530c852011-10-24 18:18:34373 if (base::CodepageToUTF16(json_data, charset.c_str(),
[email protected]a2fedb1e2011-01-25 15:23:36374 base::OnStringConversionError::FAIL,
375 &data_16))
376 json_data = UTF16ToUTF8(data_16);
[email protected]ec9207d32008-09-26 00:51:06377 }
378 }
379
[email protected]d7ad4772012-06-01 03:12:54380 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]013e9a02012-05-18 20:27:10381 const bool request_succeeded =
382 source->GetStatus().is_success() && source->GetResponseCode() == 200;
[email protected]a0ad93ea2012-05-07 22:11:53383
384 // Record response time for suggest requests sent to Google. We care
385 // only about the common case: the Google default provider used in
386 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47387 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08388 if (!is_keyword && default_url &&
[email protected]9899a612012-08-21 23:50:04389 (TemplateURLPrepopulateData::GetEngineType(default_url->url()) ==
390 SEARCH_ENGINE_GOOGLE)) {
[email protected]6dc950f2012-07-16 19:49:08391 const TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10392 base::TimeTicks::Now() - time_suggest_request_sent_;
393 if (request_succeeded) {
394 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
395 elapsed_time);
396 } else {
397 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
398 elapsed_time);
399 }
[email protected]b4cebf82008-12-29 19:59:08400 }
401
[email protected]d7ad4772012-06-01 03:12:54402 bool results_updated = false;
403 if (request_succeeded) {
404 JSONStringValueSerializer deserializer(json_data);
405 deserializer.set_allow_trailing_comma(true);
406 scoped_ptr<Value> data(deserializer.Deserialize(NULL, NULL));
407 results_updated = data.get() && ParseSuggestResults(data.get(), is_keyword);
408 }
409
initial.commit09911bf2008-07-26 23:55:29410 ConvertResultsToAutocompleteMatches();
[email protected]d7ad4772012-06-01 03:12:54411 if (done_ || results_updated)
412 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29413}
414
[email protected]601858c02010-09-01 17:08:20415SearchProvider::~SearchProvider() {
416}
417
[email protected]8d457132010-11-04 18:13:40418void SearchProvider::DoHistoryQuery(bool minimal_changes) {
419 // The history query results are synchronous, so if minimal_changes is true,
420 // we still have the last results and don't need to do anything.
421 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29422 return;
423
[email protected]8d457132010-11-04 18:13:40424 keyword_history_results_.clear();
425 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29426
[email protected]8d457132010-11-04 18:13:40427 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10428 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]8d457132010-11-04 18:13:40429 history::URLDatabase* url_db = history_service ?
430 history_service->InMemoryDatabase() : NULL;
431 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29432 return;
433
[email protected]51124552011-07-16 01:37:10434 // Request history for both the keyword and default provider. We grab many
435 // more matches than we'll ultimately clamp to so that if there are several
436 // recent multi-word matches who scores are lowered (see
437 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
438 // matches. Note that this doesn't fix the problem entirely, but merely
439 // limits it to cases with a very large number of such multi-word matches; for
440 // now, this seems OK compared with the complexity of a real fix, which would
441 // require multiple searches and tracking of "single- vs. multi-word" in the
442 // database.
443 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47444 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
445 if (default_url) {
446 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
447 num_matches, &default_history_results_);
[email protected]257ab712009-04-14 17:16:24448 }
[email protected]85b8d6f2012-05-08 20:53:47449 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
450 if (keyword_url) {
451 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]3954c3a2012-04-10 20:17:55452 keyword_input_text_, num_matches, &keyword_history_results_);
453 }
initial.commit09911bf2008-07-26 23:55:29454}
455
[email protected]6dc950f2012-07-16 19:49:08456base::TimeDelta SearchProvider::GetSuggestQueryDelay() {
457 if (query_suggest_immediately_)
458 return TimeDelta();
[email protected]6c85aa02009-02-27 12:08:09459
[email protected]6dc950f2012-07-16 19:49:08460 // By default, wait 200ms after the last keypress before sending the suggest
461 // request. However, in the following field trials, we test different
462 // behavior:
463 // 17 - Wait 200ms since the last suggest request
464 // 18 - Wait 100ms since the last keypress
465 // 19 - Wait 100ms since the last suggest request
466 TimeDelta delay(TimeDelta::FromMilliseconds(200));
467
468 // Set the delay to 100ms if we are in field trial 18 or 19.
469 if (suggest_field_trial_group_number_ == 18 ||
470 suggest_field_trial_group_number_ == 19)
471 delay = TimeDelta::FromMilliseconds(100);
472
473 if (suggest_field_trial_group_number_ != 17 &&
474 suggest_field_trial_group_number_ != 19)
475 return delay;
476
477 // Use the time since last suggest request if we are in field trial 17 or 19.
478 TimeDelta time_since_last_suggest_request =
479 base::TimeTicks::Now() - time_suggest_request_sent_;
480 return std::max(TimeDelta(), delay - time_since_last_suggest_request);
481}
482
483void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34484 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29485 StopSuggest();
[email protected]55ce8f12012-05-09 04:44:08486 ClearResults();
initial.commit09911bf2008-07-26 23:55:29487 return;
488 }
489
490 // For the minimal_changes case, if we finished the previous query and still
491 // have its results, or are allowed to keep running it, just do that, rather
492 // than starting a new query.
493 if (minimal_changes &&
[email protected]ea3b9a502011-04-04 14:19:37494 (have_suggest_results_ ||
495 (!done_ &&
496 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29497 return;
498
499 // We can't keep running any previous query, so halt it.
500 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42501
502 // Remove existing results that cannot inline autocomplete the new input.
503 RemoveStaleResults();
initial.commit09911bf2008-07-26 23:55:29504
505 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37506 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29507 return;
508
[email protected]257ab712009-04-14 17:16:24509 // We'll have at least one pending fetch. Set it to 1 now, but the value is
510 // correctly set in Run. As Run isn't invoked immediately we need to set this
511 // now, else we won't think we're waiting on results from the server when we
512 // really are.
513 suggest_results_pending_ = 1;
514
initial.commit09911bf2008-07-26 23:55:29515 // Kick off a timer that will start the URL fetch if it completes before
[email protected]6dc950f2012-07-16 19:49:08516 // the user types another character. Requests may be delayed to avoid
517 // flooding the server with requests that are likely to be thrown away later
518 // anyway.
519 timer_.Start(FROM_HERE, GetSuggestQueryDelay(), this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29520}
521
[email protected]83c726482008-09-10 06:36:34522bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55523 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
524 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47525 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
526 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34527 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47528 ((!default_url || default_url->suggestions_url().empty()) &&
529 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34530 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
531 return false;
532
[email protected]cac59d32010-08-09 23:23:14533 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34534 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34535
[email protected]cac59d32010-08-09 23:23:14536 // FORCED_QUERY means the user is explicitly asking us to search for this, so
537 // we assume it isn't a URL and/or there isn't private data.
538 if (input_.type() == AutocompleteInput::FORCED_QUERY)
539 return true;
[email protected]83c726482008-09-10 06:36:34540
[email protected]cac59d32010-08-09 23:23:14541 // Next we check the scheme. If this is UNKNOWN/REQUESTED_URL/URL with a
542 // scheme that isn't http/https/ftp, we shouldn't send it. Sending things
543 // like file: and data: is both a waste of time and a disclosure of
544 // potentially private, local data. Other "schemes" may actually be
545 // usernames, and we don't want to send passwords. If the scheme is OK, we
546 // still need to check other cases below. If this is QUERY, then the presence
547 // of these schemes means the user explicitly typed one, and thus this is
548 // probably a URL that's being entered and happens to currently be invalid --
549 // in which case we again want to run our checks below. Other QUERY cases are
550 // less likely to be URLs and thus we assume we're OK.
[email protected]a2fedb1e2011-01-25 15:23:36551 if (!LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpScheme) &&
552 !LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
553 !LowerCaseEqualsASCII(input_.scheme(), chrome::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14554 return (input_.type() == AutocompleteInput::QUERY);
555
556 // Don't send URLs with usernames, queries or refs. Some of these are
557 // private, and the Suggest server is unlikely to have any useful results
558 // for any of them. Also don't send URLs with ports, as we may initially
559 // think that a username + password is a host + port (and we don't want to
560 // send usernames/passwords), and even if the port really is a port, the
561 // server is once again unlikely to have and useful results.
562 const url_parse::Parsed& parts = input_.parts();
563 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
564 parts.query.is_nonempty() || parts.ref.is_nonempty())
565 return false;
566
567 // Don't send anything for https except the hostname. Hostnames are OK
568 // because they are visible when the TCP connection is established, but the
569 // specific path may reveal private information.
[email protected]a2fedb1e2011-01-25 15:23:36570 if (LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
571 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14572 return false;
[email protected]83c726482008-09-10 06:36:34573
574 return true;
575}
576
initial.commit09911bf2008-07-26 23:55:29577void SearchProvider::StopSuggest() {
[email protected]7706a522012-08-16 17:42:25578 // Increment the appropriate field in the histogram by the number of
579 // pending requests that were invalidated.
580 for (int i = 0; i < suggest_results_pending_; i++)
581 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
[email protected]257ab712009-04-14 17:16:24582 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14583 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24584 // Stop any in-progress URL fetches.
585 keyword_fetcher_.reset();
586 default_fetcher_.reset();
[email protected]55ce8f12012-05-09 04:44:08587}
588
589void SearchProvider::ClearResults() {
[email protected]257ab712009-04-14 17:16:24590 keyword_suggest_results_.clear();
591 default_suggest_results_.clear();
592 keyword_navigation_results_.clear();
593 default_navigation_results_.clear();
[email protected]d1f0a7f2012-06-05 10:26:42594 has_suggested_relevance_ = false;
595 verbatim_relevance_ = -1;
initial.commit09911bf2008-07-26 23:55:29596 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29597}
598
[email protected]d1f0a7f2012-06-05 10:26:42599void SearchProvider::RemoveStaleResults() {
600 RemoveStaleSuggestResults(&keyword_suggest_results_, true);
601 RemoveStaleSuggestResults(&default_suggest_results_, false);
602 RemoveStaleNavigationResults(&keyword_navigation_results_, true);
603 RemoveStaleNavigationResults(&default_navigation_results_, false);
604}
605
606void SearchProvider::RemoveStaleSuggestResults(SuggestResults* list,
607 bool is_keyword) {
608 const string16& input = is_keyword ? keyword_input_text_ : input_.text();
609 for (SuggestResults::iterator i = list->begin(); i < list->end();)
610 i = StartsWith(i->suggestion(), input, false) ? (i + 1) : list->erase(i);
611}
612
613void SearchProvider::RemoveStaleNavigationResults(NavigationResults* list,
614 bool is_keyword) {
615 const string16& input = is_keyword ? keyword_input_text_ : input_.text();
616 for (NavigationResults::iterator i = list->begin(); i < list->end();) {
617 const string16 fill(AutocompleteInput::FormattedStringWithEquivalentMeaning(
618 i->url(), StringForURLDisplay(i->url(), true, false)));
619 i = URLPrefix::BestURLPrefix(fill, input) ? (i + 1) : list->erase(i);
620 }
621}
622
623void SearchProvider::ApplyCalculatedRelevance() {
624 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_, true);
625 ApplyCalculatedSuggestRelevance(&default_suggest_results_, false);
626 ApplyCalculatedNavigationRelevance(&keyword_navigation_results_, true);
627 ApplyCalculatedNavigationRelevance(&default_navigation_results_, false);
628 has_suggested_relevance_ = false;
629 verbatim_relevance_ = -1;
630}
631
632void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list,
633 bool is_keyword) {
634 for (size_t i = 0; i < list->size(); ++i) {
635 (*list)[i].set_relevance(CalculateRelevanceForSuggestion(is_keyword) +
636 (list->size() - i - 1));
637 }
638}
639
640void SearchProvider::ApplyCalculatedNavigationRelevance(NavigationResults* list,
641 bool is_keyword) {
642 for (size_t i = 0; i < list->size(); ++i) {
643 (*list)[i].set_relevance(CalculateRelevanceForNavigation(is_keyword) +
644 (list->size() - i - 1));
645 }
646}
647
[email protected]15fb2aa2012-05-22 22:52:59648net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12649 int id,
[email protected]3954c3a2012-04-10 20:17:55650 const TemplateURLRef& suggestions_url,
[email protected]7cc6e5632011-10-25 17:56:12651 const string16& text) {
[email protected]360ba052012-04-04 17:26:13652 DCHECK(suggestions_url.SupportsReplacement());
[email protected]3dc1bc42012-06-19 08:20:53653 net::URLFetcher* fetcher = net::URLFetcher::Create(id,
[email protected]bca359b2012-06-24 07:53:04654 GURL(suggestions_url.ReplaceSearchTerms(
655 TemplateURLRef::SearchTermsArgs(text))),
[email protected]d3ec669b2012-05-23 07:12:14656 net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12657 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34658 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]257ab712009-04-14 17:16:24659 fetcher->Start();
660 return fetcher;
661}
662
[email protected]d7ad4772012-06-01 03:12:54663bool SearchProvider::ParseSuggestResults(Value* root_val, bool is_keyword) {
664 // TODO(pkasting): Fix |have_suggest_results_|; see http://crbug.com/130631
665 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29666
[email protected]d7ad4772012-06-01 03:12:54667 string16 query;
668 ListValue* root_list = NULL;
669 ListValue* results = NULL;
670 const string16& input_text = is_keyword ? keyword_input_text_ : input_.text();
671 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
672 (query != input_text) || !root_list->GetList(1, &results))
initial.commit09911bf2008-07-26 23:55:29673 return false;
674
[email protected]55ce8f12012-05-09 04:44:08675 // 3rd element: Description list.
[email protected]d7ad4772012-06-01 03:12:54676 ListValue* descriptions = NULL;
677 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:29678
[email protected]55ce8f12012-05-09 04:44:08679 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:29680
[email protected]d1f0a7f2012-06-05 10:26:42681 // Reset suggested relevance information from the default provider.
682 if (!is_keyword) {
683 has_suggested_relevance_ = false;
684 verbatim_relevance_ = -1;
685 }
686
[email protected]55ce8f12012-05-09 04:44:08687 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]d7ad4772012-06-01 03:12:54688 ListValue* types = NULL;
[email protected]d1f0a7f2012-06-05 10:26:42689 ListValue* relevances = NULL;
690 DictionaryValue* extras = NULL;
691 if (root_list->GetDictionary(4, &extras)) {
692 extras->GetList("google:suggesttype", &types);
693
694 // Only accept relevance suggestions if Instant is disabled.
695 if (!is_keyword && !InstantController::IsEnabled(profile_)) {
696 // Discard this list if its size does not match that of the suggestions.
697 if (extras->GetList("google:suggestrelevance", &relevances) &&
698 relevances->GetSize() != results->GetSize())
699 relevances = NULL;
700
701 extras->GetInteger("google:verbatimrelevance", &verbatim_relevance_);
702 }
initial.commit09911bf2008-07-26 23:55:29703 }
704
[email protected]d7ad4772012-06-01 03:12:54705 SuggestResults* suggest_results =
706 is_keyword ? &keyword_suggest_results_ : &default_suggest_results_;
707 NavigationResults* navigation_results =
708 is_keyword ? &keyword_navigation_results_ : &default_navigation_results_;
initial.commit09911bf2008-07-26 23:55:29709
[email protected]d1f0a7f2012-06-05 10:26:42710 // Clear the previous results now that new results are available.
711 suggest_results->clear();
712 navigation_results->clear();
713
714 string16 result, title;
715 std::string type;
716 int relevance = -1;
[email protected]d7ad4772012-06-01 03:12:54717 for (size_t index = 0; results->GetString(index, &result); ++index) {
[email protected]8e81f5092010-09-29 23:19:40718 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:08719 // they make no sense at all and can cause problems in our code.
[email protected]d7ad4772012-06-01 03:12:54720 if (result.empty())
[email protected]8e81f5092010-09-29 23:19:40721 continue;
722
[email protected]d1f0a7f2012-06-05 10:26:42723 // Apply valid suggested relevance scores; discard invalid lists.
724 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
725 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:54726 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:42727 // Do not blindly trust the URL coming from the server to be valid.
728 GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(result), std::string()));
729 if (url.is_valid()) {
730 if (descriptions != NULL)
731 descriptions->GetString(index, &title);
732 navigation_results->push_back(NavigationResult(url, title, relevance));
initial.commit09911bf2008-07-26 23:55:29733 }
734 } else {
[email protected]d1f0a7f2012-06-05 10:26:42735 // TODO(kochi): Improve calculator result presentation.
736 suggest_results->push_back(SuggestResult(result, relevance));
initial.commit09911bf2008-07-26 23:55:29737 }
738 }
739
[email protected]d1f0a7f2012-06-05 10:26:42740 // Apply calculated relevance scores if a valid list was not provided.
741 if (relevances == NULL) {
742 ApplyCalculatedSuggestRelevance(suggest_results, is_keyword);
743 ApplyCalculatedNavigationRelevance(navigation_results, is_keyword);
744 } else if (!is_keyword) {
745 has_suggested_relevance_ = true;
746 }
747
[email protected]d7ad4772012-06-01 03:12:54748 have_suggest_results_ = true;
[email protected]d1f0a7f2012-06-05 10:26:42749 return true;
initial.commit09911bf2008-07-26 23:55:29750}
751
752void SearchProvider::ConvertResultsToAutocompleteMatches() {
753 // Convert all the results to matches and add them to a map, so we can keep
754 // the most relevant match for each result.
755 MatchMap map;
[email protected]257ab712009-04-14 17:16:24756 const Time no_time;
757 int did_not_accept_keyword_suggestion = keyword_suggest_results_.empty() ?
initial.commit09911bf2008-07-26 23:55:29758 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
759 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]257ab712009-04-14 17:16:24760 // Keyword what you typed results are handled by the KeywordProvider.
initial.commit09911bf2008-07-26 23:55:29761
[email protected]382a0642012-06-06 06:13:52762 int verbatim_relevance = GetVerbatimRelevance();
[email protected]257ab712009-04-14 17:16:24763 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
[email protected]55ce8f12012-05-09 04:44:08764 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
765 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:42766 if (verbatim_relevance > 0) {
767 AddMatchToMap(input_.text(), input_.text(), verbatim_relevance,
768 AutocompleteMatch::SEARCH_WHAT_YOU_TYPED,
769 did_not_accept_default_suggestion, false, &map);
770 }
[email protected]b9ce8532012-05-24 20:51:15771 const size_t what_you_typed_size = map.size();
[email protected]85b8d6f2012-05-08 20:53:47772 if (!default_provider_suggest_text_.empty()) {
773 AddMatchToMap(input_.text() + default_provider_suggest_text_,
[email protected]55ce8f12012-05-09 04:44:08774 input_.text(), verbatim_relevance + 1,
[email protected]85b8d6f2012-05-08 20:53:47775 AutocompleteMatch::SEARCH_SUGGEST,
[email protected]55ce8f12012-05-09 04:44:08776 did_not_accept_default_suggestion, false, &map);
initial.commit09911bf2008-07-26 23:55:29777 }
778
[email protected]257ab712009-04-14 17:16:24779 AddHistoryResultsToMap(keyword_history_results_, true,
780 did_not_accept_keyword_suggestion, &map);
781 AddHistoryResultsToMap(default_history_results_, false,
782 did_not_accept_default_suggestion, &map);
783
[email protected]55ce8f12012-05-09 04:44:08784 AddSuggestResultsToMap(keyword_suggest_results_, true, &map);
785 AddSuggestResultsToMap(default_suggest_results_, false, &map);
initial.commit09911bf2008-07-26 23:55:29786
787 // Now add the most relevant matches from the map to |matches_|.
788 matches_.clear();
789 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
790 matches_.push_back(i->second);
791
[email protected]257ab712009-04-14 17:16:24792 AddNavigationResultsToMatches(keyword_navigation_results_, true);
793 AddNavigationResultsToMatches(default_navigation_results_, false);
initial.commit09911bf2008-07-26 23:55:29794
[email protected]b9ce8532012-05-24 20:51:15795 // Allow an additional match for "what you typed" if it's present.
796 const size_t max_total_matches = kMaxMatches + what_you_typed_size;
initial.commit09911bf2008-07-26 23:55:29797 std::partial_sort(matches_.begin(),
798 matches_.begin() + std::min(max_total_matches, matches_.size()),
799 matches_.end(), &AutocompleteMatch::MoreRelevant);
[email protected]3723e6e2012-06-11 21:06:56800
801 // If the top match is effectively 'verbatim' but exceeds the calculated
802 // verbatim relevance, and REQUESTED_URL |input_| has a |desired_tld|
803 // (for example ".com" when the CTRL key is pressed for REQUESTED_URL input),
804 // promote a URL_WHAT_YOU_TYPED match to the top. Otherwise, these matches can
805 // stomp the HistoryURLProvider's similar transient URL_WHAT_YOU_TYPED match,
806 // and CTRL+ENTER will invoke the search instead of the expected navigation.
807 if ((has_suggested_relevance_ || verbatim_relevance_ >= 0) &&
808 input_.type() == AutocompleteInput::REQUESTED_URL &&
809 !input_.desired_tld().empty() && !matches_.empty() &&
810 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
811 matches_.front().fill_into_edit == input_.text()) {
812 AutocompleteMatch match = HistoryURLProvider::SuggestExactInput(
813 this, input_, !HasHTTPScheme(input_.text()));
814 match.relevance = matches_.front().relevance + 1;
815 matches_.insert(matches_.begin(), match);
816 }
817
initial.commit09911bf2008-07-26 23:55:29818 if (matches_.size() > max_total_matches)
[email protected]a28e95662008-11-12 19:19:02819 matches_.erase(matches_.begin() + max_total_matches, matches_.end());
initial.commit09911bf2008-07-26 23:55:29820
[email protected]382a0642012-06-06 06:13:52821 // Check constraints that may be violated by suggested relevances.
[email protected]d1f0a7f2012-06-05 10:26:42822 if (!matches_.empty() &&
[email protected]e6acd002012-06-16 22:27:47823 (has_suggested_relevance_ || verbatim_relevance_ >= 0)) {
[email protected]382a0642012-06-06 06:13:52824 bool reconstruct_matches = false;
[email protected]1beee342012-06-19 22:22:28825 if (matches_.front().type != AutocompleteMatch::SEARCH_WHAT_YOU_TYPED &&
826 matches_.front().type != AutocompleteMatch::URL_WHAT_YOU_TYPED &&
827 matches_.front().inline_autocomplete_offset == string16::npos &&
828 matches_.front().fill_into_edit != input_.text()) {
829 // Disregard suggested relevances if the top match is not SWYT, inlinable,
830 // or URL_WHAT_YOU_TYPED (which may be top match regardless of inlining).
831 // For example, input "foo" should not invoke a search for "bar", which
832 // would happen if the "bar" search match outranked all other matches.
833 ApplyCalculatedRelevance();
834 reconstruct_matches = true;
835 } else if (matches_.front().relevance < CalculateRelevanceForVerbatim()) {
836 // Disregard the suggested verbatim relevance if the top score is below
837 // the usual verbatim value. For example, a BarProvider may rely on
838 // SearchProvider's verbatim or inlineable matches for input "foo" to
839 // always outrank its own lowly-ranked non-inlineable "bar" match.
840 verbatim_relevance_ = -1;
841 reconstruct_matches = true;
[email protected]e6acd002012-06-16 22:27:47842 }
843 if (input_.type() == AutocompleteInput::URL &&
844 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
845 (matches_.front().type == AutocompleteMatch::SEARCH_SUGGEST ||
846 matches_.front().type == AutocompleteMatch::SEARCH_WHAT_YOU_TYPED)) {
847 // Disregard the suggested search and verbatim relevances if the input
848 // type is URL and the top match is a highly-ranked search suggestion.
849 // For example, prevent a search for "foo.com" from outranking another
850 // provider's navigation for "foo.com" or "foo.com/url_from_history".
851 // Reconstruction will also ensure that the new top match is inlineable.
852 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_, true);
853 ApplyCalculatedSuggestRelevance(&default_suggest_results_, false);
[email protected]382a0642012-06-06 06:13:52854 verbatim_relevance_ = -1;
855 reconstruct_matches = true;
856 }
857 if (reconstruct_matches) {
858 ConvertResultsToAutocompleteMatches();
859 return;
860 }
[email protected]d1f0a7f2012-06-05 10:26:42861 }
862
[email protected]cc63dea2008-08-21 20:56:31863 UpdateStarredStateOfMatches();
[email protected]4ab4c7c2010-11-24 04:49:34864 UpdateDone();
[email protected]257ab712009-04-14 17:16:24865}
866
867void SearchProvider::AddNavigationResultsToMatches(
868 const NavigationResults& navigation_results,
869 bool is_keyword) {
870 if (!navigation_results.empty()) {
[email protected]6c535842012-05-15 05:20:55871 // TODO(kochi|msw): Add more navigational results if they get more
872 // meaningful relevance values; see http://b/1170574.
[email protected]d7ad4772012-06-01 03:12:54873 // CompareScoredResults sorts by descending relevance; so use min_element.
[email protected]6c535842012-05-15 05:20:55874 NavigationResults::const_iterator result(
[email protected]d7ad4772012-06-01 03:12:54875 std::min_element(navigation_results.begin(),
[email protected]6c535842012-05-15 05:20:55876 navigation_results.end(),
877 CompareScoredResults()));
878 matches_.push_back(NavigationToMatch(*result, is_keyword));
[email protected]257ab712009-04-14 17:16:24879 }
880}
881
882void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
883 bool is_keyword,
884 int did_not_accept_suggestion,
885 MatchMap* map) {
[email protected]51124552011-07-16 01:37:10886 if (results.empty())
887 return;
888
[email protected]d7ad4772012-06-01 03:12:54889 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
890 (input_.type() == AutocompleteInput::URL);
891 const string16& input_text = is_keyword ? keyword_input_text_ : input_.text();
[email protected]51124552011-07-16 01:37:10892 bool input_multiple_words = HasMultipleWords(input_text);
893
[email protected]55ce8f12012-05-09 04:44:08894 SuggestResults scored_results;
895 if (!prevent_inline_autocomplete && input_multiple_words) {
896 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
897 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:10898 // autocompleting a multi-word, multi-visit query, and the current input is
899 // still a prefix of it, then changing the autocompletion suddenly feels
900 // wrong. To detect this case, first score as if only one word has been
901 // typed, then check for a best result that is an autocompleted, multi-word
902 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:08903 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
904 false, input_text, is_keyword);
905 if ((scored_results[0].relevance() <
906 AutocompleteResult::kLowestDefaultScore) ||
907 !HasMultipleWords(scored_results[0].suggestion()))
908 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:10909 }
[email protected]55ce8f12012-05-09 04:44:08910 if (scored_results.empty())
911 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
912 input_multiple_words, input_text,
913 is_keyword);
914 for (SuggestResults::const_iterator i(scored_results.begin());
915 i != scored_results.end(); ++i) {
916 AddMatchToMap(i->suggestion(), input_text, i->relevance(),
[email protected]51124552011-07-16 01:37:10917 AutocompleteMatch::SEARCH_HISTORY, did_not_accept_suggestion,
[email protected]55ce8f12012-05-09 04:44:08918 is_keyword, map);
[email protected]51124552011-07-16 01:37:10919 }
920}
921
[email protected]55ce8f12012-05-09 04:44:08922SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:10923 const HistoryResults& results,
924 bool base_prevent_inline_autocomplete,
925 bool input_multiple_words,
926 const string16& input_text,
927 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:48928 AutocompleteClassifier* classifier =
929 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:08930 SuggestResults scored_results;
[email protected]257ab712009-04-14 17:16:24931 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
932 ++i) {
[email protected]51124552011-07-16 01:37:10933 // Don't autocomplete multi-word queries that have only been seen once
934 // unless the user has typed more than one word.
935 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
936 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
937
[email protected]ea3b9a502011-04-04 14:19:37938 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:10939 // when typed. For example, if the user searched for "google.com" and types
940 // "goog", don't autocomplete to the search term "google.com". Otherwise,
941 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:48942 // NOTE: We don't check this in the following cases:
943 // * When inline autocomplete is disabled, we won't be inline
944 // autocompleting this term, so we don't need to worry about confusion as
945 // much. This also prevents calling Classify() again from inside the
946 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:10947 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:48948 // * When the user has typed the whole term, the "what you typed" history
949 // match will outrank us for URL-like inputs anyway, so we need not do
950 // anything special.
[email protected]51124552011-07-16 01:37:10951 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:37952 AutocompleteMatch match;
[email protected]72874a8d2011-05-11 03:48:54953 classifier->Classify(i->term, string16(), false, false, &match, NULL);
[email protected]2905f742011-10-13 03:51:58954 prevent_inline_autocomplete =
955 match.transition == content::PAGE_TRANSITION_TYPED;
[email protected]ea3b9a502011-04-04 14:19:37956 }
[email protected]51124552011-07-16 01:37:10957
958 int relevance = CalculateRelevanceForHistory(i->time, is_keyword,
959 prevent_inline_autocomplete);
[email protected]55ce8f12012-05-09 04:44:08960 scored_results.push_back(SuggestResult(i->term, relevance));
[email protected]257ab712009-04-14 17:16:24961 }
[email protected]51124552011-07-16 01:37:10962
963 // History returns results sorted for us. However, we may have docked some
964 // results' scores, so things are no longer in order. Do a stable sort to get
965 // things back in order without otherwise disturbing results with equal
966 // scores, then force the scores to be unique, so that the order in which
967 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:08968 std::stable_sort(scored_results.begin(), scored_results.end(),
969 CompareScoredResults());
[email protected]51124552011-07-16 01:37:10970 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:08971 for (SuggestResults::iterator i(scored_results.begin());
972 i != scored_results.end(); ++i) {
973 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
974 i->set_relevance(last_relevance - 1);
975 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:10976 }
977
[email protected]55ce8f12012-05-09 04:44:08978 return scored_results;
[email protected]257ab712009-04-14 17:16:24979}
980
[email protected]55ce8f12012-05-09 04:44:08981void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
982 bool is_keyword,
983 MatchMap* map) {
[email protected]d7ad4772012-06-01 03:12:54984 const string16& input_text = is_keyword ? keyword_input_text_ : input_.text();
[email protected]55ce8f12012-05-09 04:44:08985 for (size_t i = 0; i < results.size(); ++i) {
[email protected]d7ad4772012-06-01 03:12:54986 AddMatchToMap(results[i].suggestion(), input_text, results[i].relevance(),
[email protected]55ce8f12012-05-09 04:44:08987 AutocompleteMatch::SEARCH_SUGGEST, i, is_keyword, map);
[email protected]257ab712009-04-14 17:16:24988 }
initial.commit09911bf2008-07-26 23:55:29989}
990
[email protected]382a0642012-06-06 06:13:52991int SearchProvider::GetVerbatimRelevance() const {
[email protected]dc6943b2012-06-19 06:39:56992 // Use the suggested verbatim relevance score if it is non-negative (valid),
993 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:28994 // and if it won't suppress verbatim, leaving no default provider matches.
995 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:56996 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:28997 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:56998 // Check for results on each verbatim calculation, as results from older
999 // queries (on previous input) may be trimmed for failing to inline new input.
1000 if (verbatim_relevance_ >= 0 && !input_.prevent_inline_autocomplete() &&
[email protected]1beee342012-06-19 22:22:281001 (verbatim_relevance_ > 0 ||
1002 !default_suggest_results_.empty() ||
[email protected]dc6943b2012-06-19 06:39:561003 !default_navigation_results_.empty())) {
[email protected]d1f0a7f2012-06-05 10:26:421004 return verbatim_relevance_;
[email protected]dc6943b2012-06-19 06:39:561005 }
[email protected]382a0642012-06-06 06:13:521006 return CalculateRelevanceForVerbatim();
1007}
[email protected]d1f0a7f2012-06-05 10:26:421008
[email protected]382a0642012-06-06 06:13:521009int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471010 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361011 return 250;
1012
initial.commit09911bf2008-07-26 23:55:291013 switch (input_.type()) {
1014 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361015 case AutocompleteInput::QUERY:
1016 case AutocompleteInput::FORCED_QUERY:
1017 return 1300;
initial.commit09911bf2008-07-26 23:55:291018
1019 case AutocompleteInput::REQUESTED_URL:
[email protected]52d08b12009-10-19 18:42:361020 return 1150;
initial.commit09911bf2008-07-26 23:55:291021
1022 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361023 return 850;
initial.commit09911bf2008-07-26 23:55:291024
1025 default:
1026 NOTREACHED();
1027 return 0;
1028 }
1029}
1030
[email protected]51124552011-07-16 01:37:101031int SearchProvider::CalculateRelevanceForHistory(
1032 const Time& time,
1033 bool is_keyword,
1034 bool prevent_inline_autocomplete) const {
[email protected]aa613d62010-11-09 20:40:181035 // The relevance of past searches falls off over time. There are two distinct
1036 // equations used. If the first equation is used (searches to the primary
[email protected]51124552011-07-16 01:37:101037 // provider that we want to inline autocomplete), the score starts at 1399 and
1038 // falls to 1300. If the second equation is used the relevance of a search 15
1039 // minutes ago is discounted 50 points, while the relevance of a search two
1040 // weeks ago is discounted 450 points.
[email protected]aa613d62010-11-09 20:40:181041 double elapsed_time = std::max((Time::Now() - time).InSecondsF(), 0.);
[email protected]51124552011-07-16 01:37:101042 bool is_primary_provider = providers_.is_primary_provider(is_keyword);
1043 if (is_primary_provider && !prevent_inline_autocomplete) {
[email protected]aa613d62010-11-09 20:40:181044 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101045 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181046 if (elapsed_time < autocomplete_time) {
[email protected]e17511f2011-07-13 14:09:181047 return (is_keyword ? 1599 : 1399) - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181048 std::pow(elapsed_time / autocomplete_time, 2.5));
1049 }
1050 elapsed_time -= autocomplete_time;
1051 }
1052
[email protected]c3a4bd992010-08-18 20:25:011053 const int score_discount =
1054 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291055
[email protected]6c85aa02009-02-27 12:08:091056 // Don't let scores go below 0. Negative relevance scores are meaningful in
1057 // a different way.
initial.commit09911bf2008-07-26 23:55:291058 int base_score;
[email protected]51124552011-07-16 01:37:101059 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361060 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101061 else
1062 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291063 return std::max(0, base_score - score_discount);
1064}
1065
[email protected]55ce8f12012-05-09 04:44:081066int SearchProvider::CalculateRelevanceForSuggestion(bool for_keyword) const {
1067 return !providers_.is_primary_provider(for_keyword) ? 100 :
1068 ((input_.type() == AutocompleteInput::URL) ? 300 : 600);
initial.commit09911bf2008-07-26 23:55:291069}
1070
[email protected]55ce8f12012-05-09 04:44:081071int SearchProvider::CalculateRelevanceForNavigation(bool for_keyword) const {
1072 return providers_.is_primary_provider(for_keyword) ? 800 : 150;
initial.commit09911bf2008-07-26 23:55:291073}
1074
[email protected]a2fedb1e2011-01-25 15:23:361075void SearchProvider::AddMatchToMap(const string16& query_string,
1076 const string16& input_text,
initial.commit09911bf2008-07-26 23:55:291077 int relevance,
[email protected]4c1fb7ec2008-11-13 00:19:001078 AutocompleteMatch::Type type,
initial.commit09911bf2008-07-26 23:55:291079 int accepted_suggestion,
[email protected]257ab712009-04-14 17:16:241080 bool is_keyword,
initial.commit09911bf2008-07-26 23:55:291081 MatchMap* map) {
[email protected]92513682011-09-01 06:16:521082 AutocompleteMatch match(this, relevance, false, type);
initial.commit09911bf2008-07-26 23:55:291083 std::vector<size_t> content_param_offsets;
[email protected]85b8d6f2012-05-08 20:53:471084 // Bail out now if we don't actually have a valid provider.
1085 match.keyword = is_keyword ?
[email protected]3954c3a2012-04-10 20:17:551086 providers_.keyword_provider() : providers_.default_provider();
[email protected]85b8d6f2012-05-08 20:53:471087 const TemplateURL* provider_url = match.GetTemplateURL(profile_);
1088 if (provider_url == NULL)
1089 return;
1090
[email protected]70833262011-01-05 23:40:441091 match.contents.assign(query_string);
[email protected]fb5153c52009-07-31 19:40:331092 // We do intra-string highlighting for suggestions - the suggested segment
1093 // will be highlighted, e.g. for input_text = "you" the suggestion may be
1094 // "youtube", so we'll bold the "tube" section: you*tube*.
1095 if (input_text != query_string) {
[email protected]fb5153c52009-07-31 19:40:331096 size_t input_position = match.contents.find(input_text);
[email protected]a2fedb1e2011-01-25 15:23:361097 if (input_position == string16::npos) {
[email protected]fb5153c52009-07-31 19:40:331098 // The input text is not a substring of the query string, e.g. input
1099 // text is "slasdot" and the query string is "slashdot", so we bold the
1100 // whole thing.
1101 match.contents_class.push_back(
1102 ACMatchClassification(0, ACMatchClassification::MATCH));
[email protected]ec2379162009-06-09 23:58:171103 } else {
[email protected]fb5153c52009-07-31 19:40:331104 // TODO(beng): ACMatchClassification::MATCH now seems to just mean
1105 // "bold" this. Consider modifying the terminology.
1106 // We don't iterate over the string here annotating all matches because
1107 // it looks odd to have every occurrence of a substring that may be as
1108 // short as a single character highlighted in a query suggestion result,
1109 // e.g. for input text "s" and query string "southwest airlines", it
1110 // looks odd if both the first and last s are highlighted.
1111 if (input_position != 0) {
1112 match.contents_class.push_back(
1113 ACMatchClassification(0, ACMatchClassification::NONE));
1114 }
1115 match.contents_class.push_back(
1116 ACMatchClassification(input_position, ACMatchClassification::DIM));
1117 size_t next_fragment_position = input_position + input_text.length();
1118 if (next_fragment_position < query_string.length()) {
1119 match.contents_class.push_back(
1120 ACMatchClassification(next_fragment_position,
1121 ACMatchClassification::NONE));
1122 }
[email protected]ec2379162009-06-09 23:58:171123 }
initial.commit09911bf2008-07-26 23:55:291124 } else {
[email protected]fb5153c52009-07-31 19:40:331125 // Otherwise, we're dealing with the "default search" result which has no
[email protected]70833262011-01-05 23:40:441126 // completion.
[email protected]fb5153c52009-07-31 19:40:331127 match.contents_class.push_back(
1128 ACMatchClassification(0, ACMatchClassification::NONE));
initial.commit09911bf2008-07-26 23:55:291129 }
1130
1131 // When the user forced a query, we need to make sure all the fill_into_edit
1132 // values preserve that property. Otherwise, if the user starts editing a
1133 // suggestion, non-Search results will suddenly appear.
1134 size_t search_start = 0;
1135 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
[email protected]a2fedb1e2011-01-25 15:23:361136 match.fill_into_edit.assign(ASCIIToUTF16("?"));
initial.commit09911bf2008-07-26 23:55:291137 ++search_start;
1138 }
[email protected]c0048b42009-05-04 21:47:171139 if (is_keyword) {
[email protected]033f3422012-03-13 21:24:181140 match.fill_into_edit.append(match.keyword + char16(' '));
1141 search_start += match.keyword.length() + 1;
[email protected]c0048b42009-05-04 21:47:171142 }
initial.commit09911bf2008-07-26 23:55:291143 match.fill_into_edit.append(query_string);
[email protected]2c33dd22010-02-11 21:46:351144 // Not all suggestions start with the original input.
[email protected]55ce8f12012-05-09 04:44:081145 if (!input_.prevent_inline_autocomplete() &&
[email protected]257ab712009-04-14 17:16:241146 !match.fill_into_edit.compare(search_start, input_text.length(),
1147 input_text))
1148 match.inline_autocomplete_offset = search_start + input_text.length();
initial.commit09911bf2008-07-26 23:55:291149
[email protected]85b8d6f2012-05-08 20:53:471150 const TemplateURLRef& search_url = provider_url->url_ref();
[email protected]360ba052012-04-04 17:26:131151 DCHECK(search_url.SupportsReplacement());
[email protected]bca359b2012-06-24 07:53:041152 match.search_terms_args.reset(
1153 new TemplateURLRef::SearchTermsArgs(query_string));
1154 match.search_terms_args->original_query = input_text;
1155 match.search_terms_args->accepted_suggestion = accepted_suggestion;
1156 // This is the destination URL sans assisted query stats. This must be set
1157 // so the AutocompleteController can properly de-dupe; the controller will
1158 // eventually overwrite it before it reaches the user.
1159 match.destination_url =
1160 GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get()));
initial.commit09911bf2008-07-26 23:55:291161
1162 // Search results don't look like URLs.
[email protected]2905f742011-10-13 03:51:581163 match.transition = is_keyword ?
1164 content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED;
initial.commit09911bf2008-07-26 23:55:291165
1166 // Try to add |match| to |map|. If a match for |query_string| is already in
1167 // |map|, replace it if |match| is more relevant.
1168 // NOTE: Keep this ToLower() call in sync with url_database.cc.
1169 const std::pair<MatchMap::iterator, bool> i = map->insert(
[email protected]a2fedb1e2011-01-25 15:23:361170 std::pair<string16, AutocompleteMatch>(
[email protected]503d03872011-05-06 08:36:261171 base::i18n::ToLower(query_string), match));
initial.commit09911bf2008-07-26 23:55:291172 // NOTE: We purposefully do a direct relevance comparison here instead of
1173 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items added
1174 // first" rather than "items alphabetically first" when the scores are equal.
1175 // The only case this matters is when a user has results with the same score
1176 // that differ only by capitalization; because the history system returns
1177 // results sorted by recency, this means we'll pick the most recent such
1178 // result even if the precision of our relevance score is too low to
1179 // distinguish the two.
1180 if (!i.second && (match.relevance > i.first->second.relevance))
1181 i.first->second = match;
1182}
1183
1184AutocompleteMatch SearchProvider::NavigationToMatch(
1185 const NavigationResult& navigation,
[email protected]257ab712009-04-14 17:16:241186 bool is_keyword) {
[email protected]371dab12012-06-01 03:23:551187 const string16& input = is_keyword ? keyword_input_text_ : input_.text();
[email protected]55ce8f12012-05-09 04:44:081188 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]4c1fb7ec2008-11-13 00:19:001189 AutocompleteMatch::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081190 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551191
1192 // First look for the user's input inside the fill_into_edit as it would be
1193 // without trimming the scheme, so we can find matches at the beginning of the
1194 // scheme.
1195 const string16 untrimmed_fill_into_edit(
1196 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1197 StringForURLDisplay(navigation.url(), true, false)));
1198 const URLPrefix* prefix =
1199 URLPrefix::BestURLPrefix(untrimmed_fill_into_edit, input);
1200 size_t match_start = (prefix == NULL) ?
1201 untrimmed_fill_into_edit.find(input) : prefix->prefix.length();
1202 size_t inline_autocomplete_offset = (prefix == NULL) ?
1203 string16::npos : (match_start + input.length());
1204 bool trim_http = !HasHTTPScheme(input) && (!prefix || (match_start != 0));
1205
1206 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1207 // Otherwise, user edits to a suggestion would show non-Search results.
1208 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
1209 match.fill_into_edit = ASCIIToUTF16("?");
1210 if (inline_autocomplete_offset != string16::npos)
1211 ++inline_autocomplete_offset;
1212 }
1213
1214 const std::string languages(
1215 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1216 const net::FormatUrlTypes format_types =
1217 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1218 match.fill_into_edit +=
1219 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1220 net::FormatUrl(navigation.url(), languages, format_types,
1221 net::UnescapeRule::SPACES, NULL, NULL,
1222 &inline_autocomplete_offset));
1223 if (!input_.prevent_inline_autocomplete())
1224 match.inline_autocomplete_offset = inline_autocomplete_offset;
1225 DCHECK((match.inline_autocomplete_offset == string16::npos) ||
1226 (match.inline_autocomplete_offset <= match.fill_into_edit.length()));
1227
1228 match.contents = net::FormatUrl(navigation.url(), languages,
1229 format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1230 // If the first match in the untrimmed string was inside a scheme that we
1231 // trimmed, look for a subsequent match.
1232 if (match_start == string16::npos)
1233 match_start = match.contents.find(input);
1234 // Safe if |match_start| is npos; also safe if the input is longer than the
1235 // remaining contents after |match_start|.
1236 AutocompleteMatch::ClassifyLocationInString(match_start, input.length(),
1237 match.contents.length(), ACMatchClassification::URL,
1238 &match.contents_class);
initial.commit09911bf2008-07-26 23:55:291239
[email protected]55ce8f12012-05-09 04:44:081240 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551241 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1242 ACMatchClassification::NONE, &match.description_class);
initial.commit09911bf2008-07-26 23:55:291243 return match;
1244}
[email protected]4ab4c7c2010-11-24 04:49:341245
1246void SearchProvider::UpdateDone() {
1247 // We're done when there are no more suggest queries pending (this is set to 1
1248 // when the timer is started) and we're not waiting on instant.
1249 done_ = ((suggest_results_pending_ == 0) &&
1250 (instant_finalized_ || !InstantController::IsEnabled(profile_)));
1251}