blob: 078947cfd1d2973c791b278d29de8cc2c0693343 [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]1cb2dac2010-03-08 21:49:1518#include "base/utf_string_conversions.h"
[email protected]ea3b9a502011-04-04 14:19:3719#include "chrome/browser/autocomplete/autocomplete_classifier.h"
[email protected]f5b95ba92012-03-27 14:05:1920#include "chrome/browser/autocomplete/autocomplete_field_trial.h"
[email protected]9ac40092010-10-27 23:05:2621#include "chrome/browser/autocomplete/autocomplete_match.h"
[email protected]2c812ba02011-07-14 00:23:1522#include "chrome/browser/autocomplete/keyword_provider.h"
[email protected]ce560f82009-06-03 09:39:4423#include "chrome/browser/history/history.h"
[email protected]4ab4c7c2010-11-24 04:49:3424#include "chrome/browser/instant/instant_controller.h"
[email protected]f870a322009-01-16 21:47:2725#include "chrome/browser/net/url_fixer_upper.h"
[email protected]37858e52010-08-26 00:22:0226#include "chrome/browser/prefs/pref_service.h"
[email protected]8ecad5e2010-12-02 21:18:3327#include "chrome/browser/profiles/profile.h"
[email protected]8d457132010-11-04 18:13:4028#include "chrome/browser/history/in_memory_database.h"
[email protected]8e5c89a2011-06-07 18:13:3329#include "chrome/browser/search_engines/template_url_service.h"
30#include "chrome/browser/search_engines/template_url_service_factory.h"
initial.commit09911bf2008-07-26 23:55:2931#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0232#include "chrome/common/url_constants.h"
[email protected]36aea2702011-10-26 01:12:2233#include "content/public/common/url_fetcher.h"
initial.commit09911bf2008-07-26 23:55:2934#include "googleurl/src/url_util.h"
[email protected]34ac8f32009-02-22 23:03:2735#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2936#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3437#include "net/base/load_flags.h"
[email protected]319d9e6f2009-02-18 19:47:2138#include "net/http/http_response_headers.h"
39#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1740#include "ui/base/l10n/l10n_util.h"
initial.commit09911bf2008-07-26 23:55:2941
[email protected]e1acf6f2008-10-27 20:43:3342using base::Time;
43using base::TimeDelta;
44
[email protected]51124552011-07-16 01:37:1045namespace {
46
47bool HasMultipleWords(const string16& text) {
48 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
49 bool found_word = false;
50 if (i.Init()) {
51 while (i.Advance()) {
52 if (i.IsWord()) {
53 if (found_word)
54 return true;
55 found_word = true;
56 }
57 }
58 }
59 return false;
60}
61
62};
63
[email protected]033f3422012-03-13 21:24:1864
65// SearchProvider -------------------------------------------------------------
66
[email protected]b547666d2009-04-23 16:37:5867// static
68const int SearchProvider::kDefaultProviderURLFetcherID = 1;
69// static
70const int SearchProvider::kKeywordProviderURLFetcherID = 2;
[email protected]b547666d2009-04-23 16:37:5871// static
72bool SearchProvider::query_suggest_immediately_ = false;
73
[email protected]257ab712009-04-14 17:16:2474void SearchProvider::Providers::Set(const TemplateURL* default_provider,
75 const TemplateURL* keyword_provider) {
76 // TODO(pkasting): http://b/1162970 We shouldn't need to structure-copy
77 // this. Nor should we need |default_provider_| and |keyword_provider_|
78 // just to know whether the provider changed.
79 default_provider_ = default_provider;
80 if (default_provider)
81 cached_default_provider_ = *default_provider;
82 keyword_provider_ = keyword_provider;
83 if (keyword_provider)
84 cached_keyword_provider_ = *keyword_provider;
85}
86
[email protected]601858c02010-09-01 17:08:2087SearchProvider::SearchProvider(ACProviderListener* listener, Profile* profile)
88 : AutocompleteProvider(listener, profile, "Search"),
[email protected]601858c02010-09-01 17:08:2089 suggest_results_pending_(0),
[email protected]8e5cc282010-12-05 18:11:3990 have_suggest_results_(false),
[email protected]4ab4c7c2010-11-24 04:49:3491 instant_finalized_(false) {
[email protected]f5b95ba92012-03-27 14:05:1992 // We use GetSuggestNumberOfGroups() as the group ID to mean "not in field
93 // trial." Field trial groups run from 0 to GetSuggestNumberOfGroups() - 1
94 // (inclusive).
95 int suggest_field_trial_group_number =
96 AutocompleteFieldTrial::GetSuggestNumberOfGroups();
97 if (AutocompleteFieldTrial::InSuggestFieldTrial()) {
98 suggest_field_trial_group_number =
99 AutocompleteFieldTrial::GetSuggestGroupNameAsNumber();
100 }
101 // Add a beacon to the logs that'll allow us to identify later what
102 // suggest field trial group a user is in. Do this by incrementing a
103 // bucket in a histogram, where the bucket represents the user's
104 // suggest group id.
105 UMA_HISTOGRAM_ENUMERATION(
106 "Omnibox.SuggestFieldTrialBeacon",
107 suggest_field_trial_group_number,
108 AutocompleteFieldTrial::GetSuggestNumberOfGroups() + 1);
[email protected]4ab4c7c2010-11-24 04:49:34109}
110
[email protected]a2fedb1e2011-01-25 15:23:36111void SearchProvider::FinalizeInstantQuery(const string16& input_text,
112 const string16& suggest_text) {
[email protected]4ab4c7c2010-11-24 04:49:34113 if (done_ || instant_finalized_)
114 return;
115
116 instant_finalized_ = true;
117 UpdateDone();
118
[email protected]e918c112010-12-08 23:03:49119 if (input_text.empty()) {
[email protected]4ab4c7c2010-11-24 04:49:34120 // We only need to update the listener if we're actually done.
121 if (done_)
122 listener_->OnProviderUpdate(false);
123 return;
124 }
125
[email protected]9e789742011-01-10 23:27:32126 default_provider_suggest_text_ = suggest_text;
127
[email protected]a2fedb1e2011-01-25 15:23:36128 string16 adjusted_input_text(input_text);
[email protected]e918c112010-12-08 23:03:49129 AutocompleteInput::RemoveForcedQueryStringIfNecessary(input_.type(),
130 &adjusted_input_text);
131
[email protected]a2fedb1e2011-01-25 15:23:36132 const string16 text = adjusted_input_text + suggest_text;
[email protected]4ab4c7c2010-11-24 04:49:34133 // Remove any matches that are identical to |text|. We don't use the
134 // destination_url for comparison as it varies depending upon the index passed
135 // to TemplateURL::ReplaceSearchTerms.
136 for (ACMatches::iterator i = matches_.begin(); i != matches_.end();) {
137 if (((i->type == AutocompleteMatch::SEARCH_HISTORY) ||
138 (i->type == AutocompleteMatch::SEARCH_SUGGEST)) &&
139 (i->fill_into_edit == text)) {
[email protected]e030de62010-11-24 05:41:19140 i = matches_.erase(i);
[email protected]4ab4c7c2010-11-24 04:49:34141 } else {
142 ++i;
143 }
144 }
145
146 // Add the new suggest result. We give it a rank higher than
147 // SEARCH_WHAT_YOU_TYPED so that it gets autocompleted.
148 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
149 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
150 TemplateURLRef::NO_SUGGESTION_CHOSEN;
151 MatchMap match_map;
[email protected]e918c112010-12-08 23:03:49152 AddMatchToMap(text, adjusted_input_text,
153 CalculateRelevanceForWhatYouTyped() + 1,
[email protected]4ab4c7c2010-11-24 04:49:34154 AutocompleteMatch::SEARCH_SUGGEST,
[email protected]e918c112010-12-08 23:03:49155 did_not_accept_default_suggestion, false,
[email protected]e0b231d2011-05-09 21:26:42156 input_.prevent_inline_autocomplete(), &match_map);
[email protected]4ab4c7c2010-11-24 04:49:34157 DCHECK_EQ(1u, match_map.size());
158 matches_.push_back(match_map.begin()->second);
159
160 listener_->OnProviderUpdate(true);
[email protected]601858c02010-09-01 17:08:20161}
162
initial.commit09911bf2008-07-26 23:55:29163void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27164 bool minimal_changes) {
initial.commit09911bf2008-07-26 23:55:29165 matches_.clear();
166
[email protected]ea3b9a502011-04-04 14:19:37167 instant_finalized_ =
168 (input.matches_requested() != AutocompleteInput::ALL_MATCHES);
[email protected]4ab4c7c2010-11-24 04:49:34169
[email protected]6c85aa02009-02-27 12:08:09170 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29171 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
172 Stop();
173 return;
174 }
175
[email protected]257ab712009-04-14 17:16:24176 keyword_input_text_.clear();
177 const TemplateURL* keyword_provider =
178 KeywordProvider::GetSubstitutingTemplateURLForInput(profile_, input,
179 &keyword_input_text_);
[email protected]8d457132010-11-04 18:13:40180 if (keyword_input_text_.empty())
[email protected]257ab712009-04-14 17:16:24181 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24182
183 const TemplateURL* default_provider =
[email protected]8e5c89a2011-06-07 18:13:33184 TemplateURLServiceFactory::GetForProfile(profile_)->
185 GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07186 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24187 default_provider = NULL;
188
189 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18190 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24191
192 if (!default_provider && !keyword_provider) {
193 // No valid providers.
initial.commit09911bf2008-07-26 23:55:29194 Stop();
195 return;
196 }
197
198 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24199 // or the providers, abort the query.
[email protected]9e789742011-01-10 23:27:32200 if (!minimal_changes ||
201 !providers_.equals(default_provider, keyword_provider)) {
202 if (done_)
203 default_provider_suggest_text_.clear();
204 else
205 Stop();
[email protected]257ab712009-04-14 17:16:24206 }
initial.commit09911bf2008-07-26 23:55:29207
[email protected]257ab712009-04-14 17:16:24208 providers_.Set(default_provider, keyword_provider);
initial.commit09911bf2008-07-26 23:55:29209
210 if (input.text().empty()) {
211 // User typed "?" alone. Give them a placeholder result indicating what
212 // this syntax does.
[email protected]257ab712009-04-14 17:16:24213 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00214 AutocompleteMatch match;
215 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36216 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24217 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35218 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]0385fc682011-07-07 19:36:17219 match.template_url = &providers_.default_provider();
[email protected]257ab712009-04-14 17:16:24220 matches_.push_back(match);
221 }
initial.commit09911bf2008-07-26 23:55:29222 Stop();
223 return;
224 }
225
226 input_ = input;
227
[email protected]8d457132010-11-04 18:13:40228 DoHistoryQuery(minimal_changes);
[email protected]8deeb952008-10-09 18:21:27229 StartOrStopSuggestQuery(minimal_changes);
initial.commit09911bf2008-07-26 23:55:29230 ConvertResultsToAutocompleteMatches();
231}
232
[email protected]51124552011-07-16 01:37:10233class SearchProvider::CompareScoredTerms {
234 public:
235 bool operator()(const ScoredTerm& a, const ScoredTerm& b) {
236 // Sort in descending relevance order.
237 return a.second > b.second;
238 }
239};
240
initial.commit09911bf2008-07-26 23:55:29241void SearchProvider::Run() {
242 // Start a new request with the current input.
243 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24244 suggest_results_pending_ = 0;
245 if (providers_.valid_suggest_for_keyword_provider()) {
246 suggest_results_pending_++;
[email protected]033f3422012-03-13 21:24:18247 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
248 providers_.keyword_provider(), keyword_input_text_));
[email protected]257ab712009-04-14 17:16:24249 }
250 if (providers_.valid_suggest_for_default_provider()) {
251 suggest_results_pending_++;
[email protected]033f3422012-03-13 21:24:18252 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
253 providers_.default_provider(), input_.text()));
[email protected]257ab712009-04-14 17:16:24254 }
255 // We should only get here if we have a suggest url for the keyword or default
256 // providers.
[email protected]1cb2dac2010-03-08 21:49:15257 DCHECK_GT(suggest_results_pending_, 0);
initial.commit09911bf2008-07-26 23:55:29258}
259
260void SearchProvider::Stop() {
initial.commit09911bf2008-07-26 23:55:29261 StopSuggest();
262 done_ = true;
[email protected]9e789742011-01-10 23:27:32263 default_provider_suggest_text_.clear();
initial.commit09911bf2008-07-26 23:55:29264}
265
[email protected]7cc6e5632011-10-25 17:56:12266void SearchProvider::OnURLFetchComplete(const content::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29267 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24268 suggest_results_pending_--;
[email protected]1cb2dac2010-03-08 21:49:15269 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06270 const net::HttpResponseHeaders* const response_headers =
[email protected]7cc6e5632011-10-25 17:56:12271 source->GetResponseHeaders();
[email protected]c530c852011-10-24 18:18:34272 std::string json_data;
273 source->GetResponseAsString(&json_data);
[email protected]6c85aa02009-02-27 12:08:09274 // JSON is supposed to be UTF-8, but some suggest service providers send JSON
275 // files in non-UTF-8 encodings. The actual encoding is usually specified in
276 // the Content-Type header field.
[email protected]ec9207d32008-09-26 00:51:06277 if (response_headers) {
278 std::string charset;
279 if (response_headers->GetCharset(&charset)) {
[email protected]a2fedb1e2011-01-25 15:23:36280 string16 data_16;
[email protected]ec9207d32008-09-26 00:51:06281 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
[email protected]c530c852011-10-24 18:18:34282 if (base::CodepageToUTF16(json_data, charset.c_str(),
[email protected]a2fedb1e2011-01-25 15:23:36283 base::OnStringConversionError::FAIL,
284 &data_16))
285 json_data = UTF16ToUTF8(data_16);
[email protected]ec9207d32008-09-26 00:51:06286 }
287 }
288
[email protected]257ab712009-04-14 17:16:24289 bool is_keyword_results = (source == keyword_fetcher_.get());
290 SuggestResults* suggest_results = is_keyword_results ?
291 &keyword_suggest_results_ : &default_suggest_results_;
292
[email protected]7cc6e5632011-10-25 17:56:12293 if (source->GetStatus().is_success() && source->GetResponseCode() == 200) {
[email protected]b4cebf82008-12-29 19:59:08294 JSONStringValueSerializer deserializer(json_data);
295 deserializer.set_allow_trailing_comma(true);
[email protected]ba399672010-04-06 15:42:39296 scoped_ptr<Value> root_val(deserializer.Deserialize(NULL, NULL));
[email protected]a2fedb1e2011-01-25 15:23:36297 const string16& input_text =
[email protected]257ab712009-04-14 17:16:24298 is_keyword_results ? keyword_input_text_ : input_.text();
[email protected]b4cebf82008-12-29 19:59:08299 have_suggest_results_ =
[email protected]257ab712009-04-14 17:16:24300 root_val.get() &&
301 ParseSuggestResults(root_val.get(), is_keyword_results, input_text,
302 suggest_results);
[email protected]b4cebf82008-12-29 19:59:08303 }
304
initial.commit09911bf2008-07-26 23:55:29305 ConvertResultsToAutocompleteMatches();
[email protected]257ab712009-04-14 17:16:24306 listener_->OnProviderUpdate(!suggest_results->empty());
initial.commit09911bf2008-07-26 23:55:29307}
308
[email protected]601858c02010-09-01 17:08:20309SearchProvider::~SearchProvider() {
310}
311
[email protected]8d457132010-11-04 18:13:40312void SearchProvider::DoHistoryQuery(bool minimal_changes) {
313 // The history query results are synchronous, so if minimal_changes is true,
314 // we still have the last results and don't need to do anything.
315 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29316 return;
317
[email protected]8d457132010-11-04 18:13:40318 keyword_history_results_.clear();
319 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29320
[email protected]8d457132010-11-04 18:13:40321 HistoryService* const history_service =
322 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
323 history::URLDatabase* url_db = history_service ?
324 history_service->InMemoryDatabase() : NULL;
325 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29326 return;
327
[email protected]51124552011-07-16 01:37:10328 // Request history for both the keyword and default provider. We grab many
329 // more matches than we'll ultimately clamp to so that if there are several
330 // recent multi-word matches who scores are lowered (see
331 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
332 // matches. Note that this doesn't fix the problem entirely, but merely
333 // limits it to cases with a very large number of such multi-word matches; for
334 // now, this seems OK compared with the complexity of a real fix, which would
335 // require multiple searches and tracking of "single- vs. multi-word" in the
336 // database.
337 int num_matches = kMaxMatches * 5;
[email protected]257ab712009-04-14 17:16:24338 if (providers_.valid_keyword_provider()) {
[email protected]51124552011-07-16 01:37:10339 url_db->GetMostRecentKeywordSearchTerms(providers_.keyword_provider().id(),
340 keyword_input_text_, num_matches, &keyword_history_results_);
[email protected]257ab712009-04-14 17:16:24341 }
342 if (providers_.valid_default_provider()) {
[email protected]51124552011-07-16 01:37:10343 url_db->GetMostRecentKeywordSearchTerms(providers_.default_provider().id(),
344 input_.text(), num_matches, &default_history_results_);
[email protected]257ab712009-04-14 17:16:24345 }
initial.commit09911bf2008-07-26 23:55:29346}
347
[email protected]8deeb952008-10-09 18:21:27348void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]6c85aa02009-02-27 12:08:09349 // Don't send any queries to the server until some time has elapsed after
350 // the last keypress, to avoid flooding the server with requests we are
351 // likely to end up throwing away anyway.
[email protected]02c3f6832011-11-16 18:37:40352 const int kQueryDelayMs = 200;
[email protected]6c85aa02009-02-27 12:08:09353
[email protected]83c726482008-09-10 06:36:34354 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29355 StopSuggest();
356 return;
357 }
358
359 // For the minimal_changes case, if we finished the previous query and still
360 // have its results, or are allowed to keep running it, just do that, rather
361 // than starting a new query.
362 if (minimal_changes &&
[email protected]ea3b9a502011-04-04 14:19:37363 (have_suggest_results_ ||
364 (!done_ &&
365 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29366 return;
367
368 // We can't keep running any previous query, so halt it.
369 StopSuggest();
370
371 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37372 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29373 return;
374
[email protected]257ab712009-04-14 17:16:24375 // We'll have at least one pending fetch. Set it to 1 now, but the value is
376 // correctly set in Run. As Run isn't invoked immediately we need to set this
377 // now, else we won't think we're waiting on results from the server when we
378 // really are.
379 suggest_results_pending_ = 1;
380
initial.commit09911bf2008-07-26 23:55:29381 // Kick off a timer that will start the URL fetch if it completes before
382 // the user types another character.
[email protected]b547666d2009-04-23 16:37:58383 int delay = query_suggest_immediately_ ? 0 : kQueryDelayMs;
[email protected]d323a172011-09-02 18:23:02384 timer_.Start(FROM_HERE, TimeDelta::FromMilliseconds(delay), this,
385 &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29386}
387
[email protected]83c726482008-09-10 06:36:34388bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]2c910b72011-03-08 21:16:32389 // Don't run Suggest in incognito mode, the engine doesn't support it, or
[email protected]83c726482008-09-10 06:36:34390 // the user has disabled it.
391 if (profile_->IsOffTheRecord() ||
[email protected]257ab712009-04-14 17:16:24392 (!providers_.valid_suggest_for_keyword_provider() &&
393 !providers_.valid_suggest_for_default_provider()) ||
[email protected]83c726482008-09-10 06:36:34394 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
395 return false;
396
[email protected]cac59d32010-08-09 23:23:14397 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34398 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34399
[email protected]cac59d32010-08-09 23:23:14400 // FORCED_QUERY means the user is explicitly asking us to search for this, so
401 // we assume it isn't a URL and/or there isn't private data.
402 if (input_.type() == AutocompleteInput::FORCED_QUERY)
403 return true;
[email protected]83c726482008-09-10 06:36:34404
[email protected]cac59d32010-08-09 23:23:14405 // Next we check the scheme. If this is UNKNOWN/REQUESTED_URL/URL with a
406 // scheme that isn't http/https/ftp, we shouldn't send it. Sending things
407 // like file: and data: is both a waste of time and a disclosure of
408 // potentially private, local data. Other "schemes" may actually be
409 // usernames, and we don't want to send passwords. If the scheme is OK, we
410 // still need to check other cases below. If this is QUERY, then the presence
411 // of these schemes means the user explicitly typed one, and thus this is
412 // probably a URL that's being entered and happens to currently be invalid --
413 // in which case we again want to run our checks below. Other QUERY cases are
414 // less likely to be URLs and thus we assume we're OK.
[email protected]a2fedb1e2011-01-25 15:23:36415 if (!LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpScheme) &&
416 !LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
417 !LowerCaseEqualsASCII(input_.scheme(), chrome::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14418 return (input_.type() == AutocompleteInput::QUERY);
419
420 // Don't send URLs with usernames, queries or refs. Some of these are
421 // private, and the Suggest server is unlikely to have any useful results
422 // for any of them. Also don't send URLs with ports, as we may initially
423 // think that a username + password is a host + port (and we don't want to
424 // send usernames/passwords), and even if the port really is a port, the
425 // server is once again unlikely to have and useful results.
426 const url_parse::Parsed& parts = input_.parts();
427 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
428 parts.query.is_nonempty() || parts.ref.is_nonempty())
429 return false;
430
431 // Don't send anything for https except the hostname. Hostnames are OK
432 // because they are visible when the TCP connection is established, but the
433 // specific path may reveal private information.
[email protected]a2fedb1e2011-01-25 15:23:36434 if (LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
435 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14436 return false;
[email protected]83c726482008-09-10 06:36:34437
438 return true;
439}
440
initial.commit09911bf2008-07-26 23:55:29441void SearchProvider::StopSuggest() {
[email protected]257ab712009-04-14 17:16:24442 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14443 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24444 // Stop any in-progress URL fetches.
445 keyword_fetcher_.reset();
446 default_fetcher_.reset();
447 keyword_suggest_results_.clear();
448 default_suggest_results_.clear();
449 keyword_navigation_results_.clear();
450 default_navigation_results_.clear();
initial.commit09911bf2008-07-26 23:55:29451 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29452}
453
[email protected]7cc6e5632011-10-25 17:56:12454content::URLFetcher* SearchProvider::CreateSuggestFetcher(
455 int id,
456 const TemplateURL& provider,
457 const string16& text) {
[email protected]360ba052012-04-04 17:26:13458 const TemplateURLRef& suggestions_url = provider.suggestions_url_ref();
459 DCHECK(suggestions_url.SupportsReplacement());
[email protected]033f3422012-03-13 21:24:18460 content::URLFetcher* fetcher = content::URLFetcher::Create(id,
[email protected]360ba052012-04-04 17:26:13461 GURL(suggestions_url.ReplaceSearchTermsUsingProfile(
[email protected]9b74ab52012-03-30 16:08:07462 profile_, text, TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
[email protected]36aea2702011-10-26 01:12:22463 string16())),
[email protected]033f3422012-03-13 21:24:18464 content::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12465 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34466 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]257ab712009-04-14 17:16:24467 fetcher->Start();
468 return fetcher;
469}
470
471bool SearchProvider::ParseSuggestResults(Value* root_val,
472 bool is_keyword,
[email protected]a2fedb1e2011-01-25 15:23:36473 const string16& input_text,
[email protected]257ab712009-04-14 17:16:24474 SuggestResults* suggest_results) {
[email protected]0de764e2011-08-26 01:54:00475 if (!root_val->IsType(Value::TYPE_LIST))
initial.commit09911bf2008-07-26 23:55:29476 return false;
[email protected]0de764e2011-08-26 01:54:00477 ListValue* root_list = static_cast<ListValue*>(root_val);
initial.commit09911bf2008-07-26 23:55:29478
479 Value* query_val;
[email protected]dc9a6762010-08-16 07:13:53480 string16 query_str;
initial.commit09911bf2008-07-26 23:55:29481 Value* result_val;
482 if ((root_list->GetSize() < 2) || !root_list->Get(0, &query_val) ||
[email protected]dc9a6762010-08-16 07:13:53483 !query_val->GetAsString(&query_str) ||
[email protected]a2fedb1e2011-01-25 15:23:36484 (query_str != input_text) ||
[email protected]0de764e2011-08-26 01:54:00485 !root_list->Get(1, &result_val) || !result_val->IsType(Value::TYPE_LIST))
initial.commit09911bf2008-07-26 23:55:29486 return false;
487
488 ListValue* description_list = NULL;
489 if (root_list->GetSize() > 2) {
490 // 3rd element: Description list.
491 Value* description_val;
[email protected]0de764e2011-08-26 01:54:00492 if (root_list->Get(2, &description_val) &&
493 description_val->IsType(Value::TYPE_LIST))
494 description_list = static_cast<ListValue*>(description_val);
initial.commit09911bf2008-07-26 23:55:29495 }
496
497 // We don't care about the query URL list (the fourth element in the
498 // response) for now.
499
500 // Parse optional data in the results from the Suggest server if any.
501 ListValue* type_list = NULL;
502 // 5th argument: Optional key-value pairs.
503 // TODO: We may iterate the 5th+ arguments of the root_list if any other
504 // optional data are defined.
505 if (root_list->GetSize() > 4) {
506 Value* optional_val;
507 if (root_list->Get(4, &optional_val) &&
508 optional_val->IsType(Value::TYPE_DICTIONARY)) {
509 DictionaryValue* dict_val = static_cast<DictionaryValue*>(optional_val);
510
511 // Parse Google Suggest specific type extension.
[email protected]02c3f6832011-11-16 18:37:40512 const std::string kGoogleSuggestType("google:suggesttype");
initial.commit09911bf2008-07-26 23:55:29513 if (dict_val->HasKey(kGoogleSuggestType))
514 dict_val->GetList(kGoogleSuggestType, &type_list);
515 }
516 }
517
518 ListValue* result_list = static_cast<ListValue*>(result_val);
519 for (size_t i = 0; i < result_list->GetSize(); ++i) {
520 Value* suggestion_val;
[email protected]dc9a6762010-08-16 07:13:53521 string16 suggestion_str;
initial.commit09911bf2008-07-26 23:55:29522 if (!result_list->Get(i, &suggestion_val) ||
523 !suggestion_val->GetAsString(&suggestion_str))
524 return false;
525
[email protected]8e81f5092010-09-29 23:19:40526 // Google search may return empty suggestions for weird input characters,
527 // they make no sense at all and can cause problem in our code.
528 // See http://crbug.com/56214
529 if (!suggestion_str.length())
530 continue;
531
initial.commit09911bf2008-07-26 23:55:29532 Value* type_val;
[email protected]dc9a6762010-08-16 07:13:53533 std::string type_str;
initial.commit09911bf2008-07-26 23:55:29534 if (type_list && type_list->Get(i, &type_val) &&
[email protected]dc9a6762010-08-16 07:13:53535 type_val->GetAsString(&type_str) && (type_str == "NAVIGATION")) {
initial.commit09911bf2008-07-26 23:55:29536 Value* site_val;
[email protected]dc9a6762010-08-16 07:13:53537 string16 site_name;
[email protected]257ab712009-04-14 17:16:24538 NavigationResults& navigation_results =
539 is_keyword ? keyword_navigation_results_ :
540 default_navigation_results_;
[email protected]0be9b612010-05-18 01:13:41541 if ((navigation_results.size() < kMaxMatches) &&
initial.commit09911bf2008-07-26 23:55:29542 description_list && description_list->Get(i, &site_val) &&
543 site_val->IsType(Value::TYPE_STRING) &&
544 site_val->GetAsString(&site_name)) {
[email protected]16afe222009-01-08 18:57:45545 // We can't blindly trust the URL coming from the server to be valid.
[email protected]dc9a6762010-08-16 07:13:53546 GURL result_url(URLFixerUpper::FixupURL(UTF16ToUTF8(suggestion_str),
[email protected]76e7da22010-06-18 22:44:49547 std::string()));
[email protected]dc9a6762010-08-16 07:13:53548 if (result_url.is_valid()) {
[email protected]a2fedb1e2011-01-25 15:23:36549 navigation_results.push_back(NavigationResult(result_url, site_name));
[email protected]dc9a6762010-08-16 07:13:53550 }
initial.commit09911bf2008-07-26 23:55:29551 }
552 } else {
553 // TODO(kochi): Currently we treat a calculator result as a query, but it
554 // is better to have better presentation for caluculator results.
[email protected]0be9b612010-05-18 01:13:41555 if (suggest_results->size() < kMaxMatches)
[email protected]a2fedb1e2011-01-25 15:23:36556 suggest_results->push_back(suggestion_str);
initial.commit09911bf2008-07-26 23:55:29557 }
558 }
559
initial.commit09911bf2008-07-26 23:55:29560 return true;
561}
562
563void SearchProvider::ConvertResultsToAutocompleteMatches() {
564 // Convert all the results to matches and add them to a map, so we can keep
565 // the most relevant match for each result.
566 MatchMap map;
[email protected]257ab712009-04-14 17:16:24567 const Time no_time;
568 int did_not_accept_keyword_suggestion = keyword_suggest_results_.empty() ?
initial.commit09911bf2008-07-26 23:55:29569 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
570 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]257ab712009-04-14 17:16:24571 // Keyword what you typed results are handled by the KeywordProvider.
initial.commit09911bf2008-07-26 23:55:29572
[email protected]257ab712009-04-14 17:16:24573 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
574 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
575 TemplateURLRef::NO_SUGGESTION_CHOSEN;
576 if (providers_.valid_default_provider()) {
[email protected]e918c112010-12-08 23:03:49577 AddMatchToMap(input_.text(), input_.text(),
578 CalculateRelevanceForWhatYouTyped(),
[email protected]257ab712009-04-14 17:16:24579 AutocompleteMatch::SEARCH_WHAT_YOU_TYPED,
[email protected]e918c112010-12-08 23:03:49580 did_not_accept_default_suggestion, false,
[email protected]e0b231d2011-05-09 21:26:42581 input_.prevent_inline_autocomplete(), &map);
[email protected]9e789742011-01-10 23:27:32582 if (!default_provider_suggest_text_.empty()) {
583 AddMatchToMap(input_.text() + default_provider_suggest_text_,
584 input_.text(), CalculateRelevanceForWhatYouTyped() + 1,
585 AutocompleteMatch::SEARCH_SUGGEST,
586 did_not_accept_default_suggestion, false,
[email protected]e0b231d2011-05-09 21:26:42587 input_.prevent_inline_autocomplete(), &map);
[email protected]9e789742011-01-10 23:27:32588 }
initial.commit09911bf2008-07-26 23:55:29589 }
590
[email protected]257ab712009-04-14 17:16:24591 AddHistoryResultsToMap(keyword_history_results_, true,
592 did_not_accept_keyword_suggestion, &map);
593 AddHistoryResultsToMap(default_history_results_, false,
594 did_not_accept_default_suggestion, &map);
595
596 AddSuggestResultsToMap(keyword_suggest_results_, true,
597 did_not_accept_keyword_suggestion, &map);
598 AddSuggestResultsToMap(default_suggest_results_, false,
599 did_not_accept_default_suggestion, &map);
initial.commit09911bf2008-07-26 23:55:29600
601 // Now add the most relevant matches from the map to |matches_|.
602 matches_.clear();
603 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
604 matches_.push_back(i->second);
605
[email protected]257ab712009-04-14 17:16:24606 AddNavigationResultsToMatches(keyword_navigation_results_, true);
607 AddNavigationResultsToMatches(default_navigation_results_, false);
initial.commit09911bf2008-07-26 23:55:29608
[email protected]0be9b612010-05-18 01:13:41609 const size_t max_total_matches = kMaxMatches + 1; // 1 for "what you typed"
initial.commit09911bf2008-07-26 23:55:29610 std::partial_sort(matches_.begin(),
611 matches_.begin() + std::min(max_total_matches, matches_.size()),
612 matches_.end(), &AutocompleteMatch::MoreRelevant);
613 if (matches_.size() > max_total_matches)
[email protected]a28e95662008-11-12 19:19:02614 matches_.erase(matches_.begin() + max_total_matches, matches_.end());
initial.commit09911bf2008-07-26 23:55:29615
[email protected]cc63dea2008-08-21 20:56:31616 UpdateStarredStateOfMatches();
617
[email protected]4ab4c7c2010-11-24 04:49:34618 UpdateDone();
[email protected]257ab712009-04-14 17:16:24619}
620
621void SearchProvider::AddNavigationResultsToMatches(
622 const NavigationResults& navigation_results,
623 bool is_keyword) {
624 if (!navigation_results.empty()) {
625 // TODO(kochi): http://b/1170574 We add only one results for navigational
626 // suggestions. If we can get more useful information about the score,
627 // consider adding more results.
[email protected]52d08b12009-10-19 18:42:36628 const size_t num_results = is_keyword ?
629 keyword_navigation_results_.size() : default_navigation_results_.size();
630 matches_.push_back(NavigationToMatch(navigation_results.front(),
631 CalculateRelevanceForNavigation(num_results, 0, is_keyword),
632 is_keyword));
[email protected]257ab712009-04-14 17:16:24633 }
634}
635
636void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
637 bool is_keyword,
638 int did_not_accept_suggestion,
639 MatchMap* map) {
[email protected]51124552011-07-16 01:37:10640 if (results.empty())
641 return;
642
643 bool base_prevent_inline_autocomplete =
644 (input_.type() == AutocompleteInput::URL) ||
645 input_.prevent_inline_autocomplete();
646 const string16& input_text(
647 is_keyword ? keyword_input_text_ : input_.text());
648 bool input_multiple_words = HasMultipleWords(input_text);
649
650 ScoredTerms scored_terms;
651 if (!base_prevent_inline_autocomplete && input_multiple_words) {
652 // ScoreHistoryTerms() allows autocompletion of multi-word, 1-visit queries
653 // if the input also has multiple words. But if we were already
654 // autocompleting a multi-word, multi-visit query, and the current input is
655 // still a prefix of it, then changing the autocompletion suddenly feels
656 // wrong. To detect this case, first score as if only one word has been
657 // typed, then check for a best result that is an autocompleted, multi-word
658 // query. If we find one, then just keep that score set.
659 scored_terms = ScoreHistoryTerms(results, base_prevent_inline_autocomplete,
660 false, input_text, is_keyword);
661 if ((scored_terms[0].second < AutocompleteResult::kLowestDefaultScore) ||
662 !HasMultipleWords(scored_terms[0].first))
663 scored_terms.clear(); // Didn't detect the case above, score normally.
664 }
665 if (scored_terms.empty())
666 scored_terms = ScoreHistoryTerms(results, base_prevent_inline_autocomplete,
667 input_multiple_words, input_text,
668 is_keyword);
669 for (ScoredTerms::const_iterator i(scored_terms.begin());
670 i != scored_terms.end(); ++i) {
671 AddMatchToMap(i->first, input_text, i->second,
672 AutocompleteMatch::SEARCH_HISTORY, did_not_accept_suggestion,
673 is_keyword, input_.prevent_inline_autocomplete(), map);
674 }
675}
676
677SearchProvider::ScoredTerms SearchProvider::ScoreHistoryTerms(
678 const HistoryResults& results,
679 bool base_prevent_inline_autocomplete,
680 bool input_multiple_words,
681 const string16& input_text,
682 bool is_keyword) {
[email protected]ea3b9a502011-04-04 14:19:37683 AutocompleteClassifier* classifier = profile_->GetAutocompleteClassifier();
[email protected]51124552011-07-16 01:37:10684 ScoredTerms scored_terms;
[email protected]257ab712009-04-14 17:16:24685 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
686 ++i) {
[email protected]51124552011-07-16 01:37:10687 // Don't autocomplete multi-word queries that have only been seen once
688 // unless the user has typed more than one word.
689 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
690 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
691
[email protected]ea3b9a502011-04-04 14:19:37692 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:10693 // when typed. For example, if the user searched for "google.com" and types
694 // "goog", don't autocomplete to the search term "google.com". Otherwise,
695 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:48696 // NOTE: We don't check this in the following cases:
697 // * When inline autocomplete is disabled, we won't be inline
698 // autocompleting this term, so we don't need to worry about confusion as
699 // much. This also prevents calling Classify() again from inside the
700 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:10701 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:48702 // * When the user has typed the whole term, the "what you typed" history
703 // match will outrank us for URL-like inputs anyway, so we need not do
704 // anything special.
[email protected]51124552011-07-16 01:37:10705 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:37706 AutocompleteMatch match;
[email protected]72874a8d2011-05-11 03:48:54707 classifier->Classify(i->term, string16(), false, false, &match, NULL);
[email protected]2905f742011-10-13 03:51:58708 prevent_inline_autocomplete =
709 match.transition == content::PAGE_TRANSITION_TYPED;
[email protected]ea3b9a502011-04-04 14:19:37710 }
[email protected]51124552011-07-16 01:37:10711
712 int relevance = CalculateRelevanceForHistory(i->time, is_keyword,
713 prevent_inline_autocomplete);
714 scored_terms.push_back(std::make_pair(i->term, relevance));
[email protected]257ab712009-04-14 17:16:24715 }
[email protected]51124552011-07-16 01:37:10716
717 // History returns results sorted for us. However, we may have docked some
718 // results' scores, so things are no longer in order. Do a stable sort to get
719 // things back in order without otherwise disturbing results with equal
720 // scores, then force the scores to be unique, so that the order in which
721 // they're shown is deterministic.
722 std::stable_sort(scored_terms.begin(), scored_terms.end(),
723 CompareScoredTerms());
724 int last_relevance = 0;
725 for (ScoredTerms::iterator i(scored_terms.begin()); i != scored_terms.end();
726 ++i) {
727 if ((i != scored_terms.begin()) && (i->second >= last_relevance))
728 i->second = last_relevance - 1;
729 last_relevance = i->second;
730 }
731
732 return scored_terms;
[email protected]257ab712009-04-14 17:16:24733}
734
735void SearchProvider::AddSuggestResultsToMap(
736 const SuggestResults& suggest_results,
737 bool is_keyword,
738 int did_not_accept_suggestion,
739 MatchMap* map) {
740 for (size_t i = 0; i < suggest_results.size(); ++i) {
741 AddMatchToMap(suggest_results[i],
[email protected]e918c112010-12-08 23:03:49742 is_keyword ? keyword_input_text_ : input_.text(),
[email protected]52d08b12009-10-19 18:42:36743 CalculateRelevanceForSuggestion(suggest_results.size(), i,
[email protected]257ab712009-04-14 17:16:24744 is_keyword),
745 AutocompleteMatch::SEARCH_SUGGEST,
[email protected]e918c112010-12-08 23:03:49746 static_cast<int>(i), is_keyword,
[email protected]e0b231d2011-05-09 21:26:42747 input_.prevent_inline_autocomplete(), map);
[email protected]257ab712009-04-14 17:16:24748 }
initial.commit09911bf2008-07-26 23:55:29749}
750
751int SearchProvider::CalculateRelevanceForWhatYouTyped() const {
[email protected]52d08b12009-10-19 18:42:36752 if (providers_.valid_keyword_provider())
753 return 250;
754
initial.commit09911bf2008-07-26 23:55:29755 switch (input_.type()) {
756 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:36757 case AutocompleteInput::QUERY:
758 case AutocompleteInput::FORCED_QUERY:
759 return 1300;
initial.commit09911bf2008-07-26 23:55:29760
761 case AutocompleteInput::REQUESTED_URL:
[email protected]52d08b12009-10-19 18:42:36762 return 1150;
initial.commit09911bf2008-07-26 23:55:29763
764 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:36765 return 850;
initial.commit09911bf2008-07-26 23:55:29766
767 default:
768 NOTREACHED();
769 return 0;
770 }
771}
772
[email protected]51124552011-07-16 01:37:10773int SearchProvider::CalculateRelevanceForHistory(
774 const Time& time,
775 bool is_keyword,
776 bool prevent_inline_autocomplete) const {
[email protected]aa613d62010-11-09 20:40:18777 // The relevance of past searches falls off over time. There are two distinct
778 // equations used. If the first equation is used (searches to the primary
[email protected]51124552011-07-16 01:37:10779 // provider that we want to inline autocomplete), the score starts at 1399 and
780 // falls to 1300. If the second equation is used the relevance of a search 15
781 // minutes ago is discounted 50 points, while the relevance of a search two
782 // weeks ago is discounted 450 points.
[email protected]aa613d62010-11-09 20:40:18783 double elapsed_time = std::max((Time::Now() - time).InSecondsF(), 0.);
[email protected]51124552011-07-16 01:37:10784 bool is_primary_provider = providers_.is_primary_provider(is_keyword);
785 if (is_primary_provider && !prevent_inline_autocomplete) {
[email protected]aa613d62010-11-09 20:40:18786 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:10787 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:18788 if (elapsed_time < autocomplete_time) {
[email protected]e17511f2011-07-13 14:09:18789 return (is_keyword ? 1599 : 1399) - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:18790 std::pow(elapsed_time / autocomplete_time, 2.5));
791 }
792 elapsed_time -= autocomplete_time;
793 }
794
[email protected]c3a4bd992010-08-18 20:25:01795 const int score_discount =
796 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:29797
[email protected]6c85aa02009-02-27 12:08:09798 // Don't let scores go below 0. Negative relevance scores are meaningful in
799 // a different way.
initial.commit09911bf2008-07-26 23:55:29800 int base_score;
[email protected]51124552011-07-16 01:37:10801 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:36802 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:10803 else
804 base_score = 200;
initial.commit09911bf2008-07-26 23:55:29805 return std::max(0, base_score - score_discount);
806}
807
[email protected]52d08b12009-10-19 18:42:36808int SearchProvider::CalculateRelevanceForSuggestion(size_t num_results,
809 size_t result_number,
810 bool is_keyword) const {
811 DCHECK(result_number < num_results);
812 int base_score;
813 if (!providers_.is_primary_provider(is_keyword))
814 base_score = 100;
815 else
816 base_score = (input_.type() == AutocompleteInput::URL) ? 300 : 600;
817 return base_score +
818 static_cast<int>(num_results - 1 - result_number);
initial.commit09911bf2008-07-26 23:55:29819}
820
[email protected]52d08b12009-10-19 18:42:36821int SearchProvider::CalculateRelevanceForNavigation(size_t num_results,
822 size_t result_number,
823 bool is_keyword) const {
824 DCHECK(result_number < num_results);
initial.commit09911bf2008-07-26 23:55:29825 // TODO(kochi): http://b/784900 Use relevance score from the NavSuggest
826 // server if possible.
[email protected]52d08b12009-10-19 18:42:36827 return (providers_.is_primary_provider(is_keyword) ? 800 : 150) +
828 static_cast<int>(num_results - 1 - result_number);
initial.commit09911bf2008-07-26 23:55:29829}
830
[email protected]a2fedb1e2011-01-25 15:23:36831void SearchProvider::AddMatchToMap(const string16& query_string,
832 const string16& input_text,
initial.commit09911bf2008-07-26 23:55:29833 int relevance,
[email protected]4c1fb7ec2008-11-13 00:19:00834 AutocompleteMatch::Type type,
initial.commit09911bf2008-07-26 23:55:29835 int accepted_suggestion,
[email protected]257ab712009-04-14 17:16:24836 bool is_keyword,
[email protected]e918c112010-12-08 23:03:49837 bool prevent_inline_autocomplete,
initial.commit09911bf2008-07-26 23:55:29838 MatchMap* map) {
[email protected]92513682011-09-01 06:16:52839 AutocompleteMatch match(this, relevance, false, type);
initial.commit09911bf2008-07-26 23:55:29840 std::vector<size_t> content_param_offsets;
[email protected]257ab712009-04-14 17:16:24841 const TemplateURL& provider = is_keyword ? providers_.keyword_provider() :
842 providers_.default_provider();
[email protected]0385fc682011-07-07 19:36:17843 match.template_url = &provider;
[email protected]70833262011-01-05 23:40:44844 match.contents.assign(query_string);
[email protected]fb5153c52009-07-31 19:40:33845 // We do intra-string highlighting for suggestions - the suggested segment
846 // will be highlighted, e.g. for input_text = "you" the suggestion may be
847 // "youtube", so we'll bold the "tube" section: you*tube*.
848 if (input_text != query_string) {
[email protected]fb5153c52009-07-31 19:40:33849 size_t input_position = match.contents.find(input_text);
[email protected]a2fedb1e2011-01-25 15:23:36850 if (input_position == string16::npos) {
[email protected]fb5153c52009-07-31 19:40:33851 // The input text is not a substring of the query string, e.g. input
852 // text is "slasdot" and the query string is "slashdot", so we bold the
853 // whole thing.
854 match.contents_class.push_back(
855 ACMatchClassification(0, ACMatchClassification::MATCH));
[email protected]ec2379162009-06-09 23:58:17856 } else {
[email protected]fb5153c52009-07-31 19:40:33857 // TODO(beng): ACMatchClassification::MATCH now seems to just mean
858 // "bold" this. Consider modifying the terminology.
859 // We don't iterate over the string here annotating all matches because
860 // it looks odd to have every occurrence of a substring that may be as
861 // short as a single character highlighted in a query suggestion result,
862 // e.g. for input text "s" and query string "southwest airlines", it
863 // looks odd if both the first and last s are highlighted.
864 if (input_position != 0) {
865 match.contents_class.push_back(
866 ACMatchClassification(0, ACMatchClassification::NONE));
867 }
868 match.contents_class.push_back(
869 ACMatchClassification(input_position, ACMatchClassification::DIM));
870 size_t next_fragment_position = input_position + input_text.length();
871 if (next_fragment_position < query_string.length()) {
872 match.contents_class.push_back(
873 ACMatchClassification(next_fragment_position,
874 ACMatchClassification::NONE));
875 }
[email protected]ec2379162009-06-09 23:58:17876 }
initial.commit09911bf2008-07-26 23:55:29877 } else {
[email protected]fb5153c52009-07-31 19:40:33878 // Otherwise, we're dealing with the "default search" result which has no
[email protected]70833262011-01-05 23:40:44879 // completion.
[email protected]fb5153c52009-07-31 19:40:33880 match.contents_class.push_back(
881 ACMatchClassification(0, ACMatchClassification::NONE));
initial.commit09911bf2008-07-26 23:55:29882 }
883
884 // When the user forced a query, we need to make sure all the fill_into_edit
885 // values preserve that property. Otherwise, if the user starts editing a
886 // suggestion, non-Search results will suddenly appear.
887 size_t search_start = 0;
888 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
[email protected]a2fedb1e2011-01-25 15:23:36889 match.fill_into_edit.assign(ASCIIToUTF16("?"));
initial.commit09911bf2008-07-26 23:55:29890 ++search_start;
891 }
[email protected]c0048b42009-05-04 21:47:17892 if (is_keyword) {
[email protected]3cb0f8d92012-02-29 05:43:34893 match.keyword = providers_.keyword_provider().keyword();
[email protected]033f3422012-03-13 21:24:18894 match.fill_into_edit.append(match.keyword + char16(' '));
895 search_start += match.keyword.length() + 1;
[email protected]c0048b42009-05-04 21:47:17896 }
initial.commit09911bf2008-07-26 23:55:29897 match.fill_into_edit.append(query_string);
[email protected]2c33dd22010-02-11 21:46:35898 // Not all suggestions start with the original input.
[email protected]e918c112010-12-08 23:03:49899 if (!prevent_inline_autocomplete &&
[email protected]257ab712009-04-14 17:16:24900 !match.fill_into_edit.compare(search_start, input_text.length(),
901 input_text))
902 match.inline_autocomplete_offset = search_start + input_text.length();
initial.commit09911bf2008-07-26 23:55:29903
[email protected]360ba052012-04-04 17:26:13904 const TemplateURLRef& search_url = provider.url_ref();
905 DCHECK(search_url.SupportsReplacement());
906 match.destination_url = GURL(search_url.ReplaceSearchTermsUsingProfile(
[email protected]9b74ab52012-03-30 16:08:07907 profile_, query_string, accepted_suggestion, input_text));
initial.commit09911bf2008-07-26 23:55:29908
909 // Search results don't look like URLs.
[email protected]2905f742011-10-13 03:51:58910 match.transition = is_keyword ?
911 content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED;
initial.commit09911bf2008-07-26 23:55:29912
913 // Try to add |match| to |map|. If a match for |query_string| is already in
914 // |map|, replace it if |match| is more relevant.
915 // NOTE: Keep this ToLower() call in sync with url_database.cc.
916 const std::pair<MatchMap::iterator, bool> i = map->insert(
[email protected]a2fedb1e2011-01-25 15:23:36917 std::pair<string16, AutocompleteMatch>(
[email protected]503d03872011-05-06 08:36:26918 base::i18n::ToLower(query_string), match));
initial.commit09911bf2008-07-26 23:55:29919 // NOTE: We purposefully do a direct relevance comparison here instead of
920 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items added
921 // first" rather than "items alphabetically first" when the scores are equal.
922 // The only case this matters is when a user has results with the same score
923 // that differ only by capitalization; because the history system returns
924 // results sorted by recency, this means we'll pick the most recent such
925 // result even if the precision of our relevance score is too low to
926 // distinguish the two.
927 if (!i.second && (match.relevance > i.first->second.relevance))
928 i.first->second = match;
929}
930
931AutocompleteMatch SearchProvider::NavigationToMatch(
932 const NavigationResult& navigation,
[email protected]257ab712009-04-14 17:16:24933 int relevance,
934 bool is_keyword) {
[email protected]a2fedb1e2011-01-25 15:23:36935 const string16& input_text =
[email protected]257ab712009-04-14 17:16:24936 is_keyword ? keyword_input_text_ : input_.text();
[email protected]92513682011-09-01 06:16:52937 AutocompleteMatch match(this, relevance, false,
[email protected]4c1fb7ec2008-11-13 00:19:00938 AutocompleteMatch::NAVSUGGEST);
initial.commit09911bf2008-07-26 23:55:29939 match.destination_url = navigation.url;
[email protected]76e7da22010-06-18 22:44:49940 match.contents =
941 StringForURLDisplay(navigation.url, true, !HasHTTPScheme(input_text));
[email protected]257ab712009-04-14 17:16:24942 AutocompleteMatch::ClassifyMatchInString(input_text, match.contents,
initial.commit09911bf2008-07-26 23:55:29943 ACMatchClassification::URL,
944 &match.contents_class);
945
946 match.description = navigation.site_name;
[email protected]257ab712009-04-14 17:16:24947 AutocompleteMatch::ClassifyMatchInString(input_text, navigation.site_name,
initial.commit09911bf2008-07-26 23:55:29948 ACMatchClassification::NONE,
949 &match.description_class);
950
initial.commit09911bf2008-07-26 23:55:29951 // When the user forced a query, we need to make sure all the fill_into_edit
952 // values preserve that property. Otherwise, if the user starts editing a
953 // suggestion, non-Search results will suddenly appear.
954 if (input_.type() == AutocompleteInput::FORCED_QUERY)
[email protected]a2fedb1e2011-01-25 15:23:36955 match.fill_into_edit.assign(ASCIIToUTF16("?"));
[email protected]79845ef2010-06-02 02:37:40956 match.fill_into_edit.append(
957 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url,
958 match.contents));
initial.commit09911bf2008-07-26 23:55:29959 // TODO(pkasting): http://b/1112879 These should perhaps be
960 // inline-autocompletable?
961
962 return match;
963}
[email protected]4ab4c7c2010-11-24 04:49:34964
965void SearchProvider::UpdateDone() {
966 // We're done when there are no more suggest queries pending (this is set to 1
967 // when the timer is started) and we're not waiting on instant.
968 done_ = ((suggest_results_pending_ == 0) &&
969 (instant_finalized_ || !InstantController::IsEnabled(profile_)));
970}