blob: 0ec478c20151c53609d0992b57677dbfdfb8ffbd [file] [log] [blame]
[email protected]2c33dd22010-02-11 21:46:351// Copyright (c) 2010 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]a92b8642009-05-05 23:38:5610#include "app/l10n_util.h"
[email protected]2041cf342010-02-19 03:15:5911#include "base/callback.h"
[email protected]d6e58c6e2009-10-10 20:40:5012#include "base/i18n/icu_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2913#include "base/message_loop.h"
[email protected]dc9a6762010-08-16 07:13:5314#include "base/string16.h"
[email protected]1cb2dac2010-03-08 21:49:1515#include "base/utf_string_conversions.h"
[email protected]257ab712009-04-14 17:16:2416#include "chrome/browser/autocomplete/keyword_provider.h"
initial.commit09911bf2008-07-26 23:55:2917#include "chrome/browser/browser_process.h"
[email protected]f7578f52010-08-30 22:22:4918#include "chrome/browser/google/google_util.h"
[email protected]ce560f82009-06-03 09:39:4419#include "chrome/browser/history/history.h"
[email protected]f870a322009-01-16 21:47:2720#include "chrome/browser/net/url_fixer_upper.h"
[email protected]37858e52010-08-26 00:22:0221#include "chrome/browser/prefs/pref_service.h"
initial.commit09911bf2008-07-26 23:55:2922#include "chrome/browser/profile.h"
[email protected]d54e03a52009-01-16 00:31:0423#include "chrome/browser/search_engines/template_url_model.h"
initial.commit09911bf2008-07-26 23:55:2924#include "chrome/common/json_value_serializer.h"
initial.commit09911bf2008-07-26 23:55:2925#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0226#include "chrome/common/url_constants.h"
initial.commit09911bf2008-07-26 23:55:2927#include "googleurl/src/url_util.h"
[email protected]34ac8f32009-02-22 23:03:2728#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2929#include "net/base/escape.h"
[email protected]319d9e6f2009-02-18 19:47:2130#include "net/http/http_response_headers.h"
31#include "net/url_request/url_request_status.h"
initial.commit09911bf2008-07-26 23:55:2932
[email protected]e1acf6f2008-10-27 20:43:3333using base::Time;
34using base::TimeDelta;
35
[email protected]b547666d2009-04-23 16:37:5836// static
37const int SearchProvider::kDefaultProviderURLFetcherID = 1;
38// static
39const int SearchProvider::kKeywordProviderURLFetcherID = 2;
40
41// static
42bool SearchProvider::query_suggest_immediately_ = false;
43
[email protected]257ab712009-04-14 17:16:2444void SearchProvider::Providers::Set(const TemplateURL* default_provider,
45 const TemplateURL* keyword_provider) {
46 // TODO(pkasting): http://b/1162970 We shouldn't need to structure-copy
47 // this. Nor should we need |default_provider_| and |keyword_provider_|
48 // just to know whether the provider changed.
49 default_provider_ = default_provider;
50 if (default_provider)
51 cached_default_provider_ = *default_provider;
52 keyword_provider_ = keyword_provider;
53 if (keyword_provider)
54 cached_keyword_provider_ = *keyword_provider;
55}
56
[email protected]601858c02010-09-01 17:08:2057SearchProvider::SearchProvider(ACProviderListener* listener, Profile* profile)
58 : AutocompleteProvider(listener, profile, "Search"),
59 have_history_results_(false),
60 history_request_pending_(false),
61 suggest_results_pending_(0),
62 have_suggest_results_(false) {
63}
64
initial.commit09911bf2008-07-26 23:55:2965void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:2766 bool minimal_changes) {
initial.commit09911bf2008-07-26 23:55:2967 matches_.clear();
68
[email protected]6c85aa02009-02-27 12:08:0969 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:2970 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
71 Stop();
72 return;
73 }
74
[email protected]257ab712009-04-14 17:16:2475 keyword_input_text_.clear();
76 const TemplateURL* keyword_provider =
77 KeywordProvider::GetSubstitutingTemplateURLForInput(profile_, input,
78 &keyword_input_text_);
79 if (!TemplateURL::SupportsReplacement(keyword_provider) ||
80 keyword_input_text_.empty()) {
81 keyword_provider = NULL;
82 }
83
84 const TemplateURL* default_provider =
initial.commit09911bf2008-07-26 23:55:2985 profile_->GetTemplateURLModel()->GetDefaultSearchProvider();
[email protected]257ab712009-04-14 17:16:2486 if (!TemplateURL::SupportsReplacement(default_provider))
87 default_provider = NULL;
88
89 if (keyword_provider == default_provider)
90 keyword_provider = NULL; // No use in querying the same provider twice.
91
92 if (!default_provider && !keyword_provider) {
93 // No valid providers.
initial.commit09911bf2008-07-26 23:55:2994 Stop();
95 return;
96 }
97
98 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:2499 // or the providers, abort the query.
initial.commit09911bf2008-07-26 23:55:29100 if (!done_ && (!minimal_changes ||
[email protected]257ab712009-04-14 17:16:24101 !providers_.equals(default_provider, keyword_provider))) {
initial.commit09911bf2008-07-26 23:55:29102 Stop();
[email protected]257ab712009-04-14 17:16:24103 }
initial.commit09911bf2008-07-26 23:55:29104
[email protected]257ab712009-04-14 17:16:24105 providers_.Set(default_provider, keyword_provider);
initial.commit09911bf2008-07-26 23:55:29106
107 if (input.text().empty()) {
108 // User typed "?" alone. Give them a placeholder result indicating what
109 // this syntax does.
[email protected]257ab712009-04-14 17:16:24110 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00111 AutocompleteMatch match;
112 match.provider = this;
[email protected]2c33dd22010-02-11 21:46:35113 match.contents.assign(l10n_util::GetString(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24114 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35115 ACMatchClassification(0, ACMatchClassification::NONE));
116 match.description.assign(l10n_util::GetStringF(
117 IDS_AUTOCOMPLETE_SEARCH_DESCRIPTION,
118 default_provider->AdjustedShortNameForLocaleDirection()));
119 match.description_class.push_back(
[email protected]257ab712009-04-14 17:16:24120 ACMatchClassification(0, ACMatchClassification::DIM));
121 matches_.push_back(match);
122 }
initial.commit09911bf2008-07-26 23:55:29123 Stop();
124 return;
125 }
126
127 input_ = input;
128
[email protected]8deeb952008-10-09 18:21:27129 StartOrStopHistoryQuery(minimal_changes);
130 StartOrStopSuggestQuery(minimal_changes);
initial.commit09911bf2008-07-26 23:55:29131 ConvertResultsToAutocompleteMatches();
132}
133
134void SearchProvider::Run() {
135 // Start a new request with the current input.
136 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24137 suggest_results_pending_ = 0;
138 if (providers_.valid_suggest_for_keyword_provider()) {
139 suggest_results_pending_++;
140 keyword_fetcher_.reset(
[email protected]b547666d2009-04-23 16:37:58141 CreateSuggestFetcher(kKeywordProviderURLFetcherID,
142 providers_.keyword_provider(),
[email protected]257ab712009-04-14 17:16:24143 keyword_input_text_));
144 }
145 if (providers_.valid_suggest_for_default_provider()) {
146 suggest_results_pending_++;
147 default_fetcher_.reset(
[email protected]b547666d2009-04-23 16:37:58148 CreateSuggestFetcher(kDefaultProviderURLFetcherID,
149 providers_.default_provider(), input_.text()));
[email protected]257ab712009-04-14 17:16:24150 }
151 // We should only get here if we have a suggest url for the keyword or default
152 // providers.
[email protected]1cb2dac2010-03-08 21:49:15153 DCHECK_GT(suggest_results_pending_, 0);
initial.commit09911bf2008-07-26 23:55:29154}
155
156void SearchProvider::Stop() {
157 StopHistory();
158 StopSuggest();
159 done_ = true;
160}
161
162void SearchProvider::OnURLFetchComplete(const URLFetcher* source,
163 const GURL& url,
164 const URLRequestStatus& status,
165 int response_code,
166 const ResponseCookies& cookie,
167 const std::string& data) {
168 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24169 suggest_results_pending_--;
[email protected]1cb2dac2010-03-08 21:49:15170 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06171 const net::HttpResponseHeaders* const response_headers =
172 source->response_headers();
173 std::string json_data(data);
[email protected]6c85aa02009-02-27 12:08:09174 // JSON is supposed to be UTF-8, but some suggest service providers send JSON
175 // files in non-UTF-8 encodings. The actual encoding is usually specified in
176 // the Content-Type header field.
[email protected]ec9207d32008-09-26 00:51:06177 if (response_headers) {
178 std::string charset;
179 if (response_headers->GetCharset(&charset)) {
180 std::wstring wide_data;
181 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
[email protected]d6e58c6e2009-10-10 20:40:50182 if (base::CodepageToWide(data, charset.c_str(),
183 base::OnStringConversionError::FAIL,
184 &wide_data))
[email protected]f0a51fb52009-03-05 12:46:38185 json_data = WideToUTF8(wide_data);
[email protected]ec9207d32008-09-26 00:51:06186 }
187 }
188
[email protected]257ab712009-04-14 17:16:24189 bool is_keyword_results = (source == keyword_fetcher_.get());
190 SuggestResults* suggest_results = is_keyword_results ?
191 &keyword_suggest_results_ : &default_suggest_results_;
192
[email protected]b4cebf82008-12-29 19:59:08193 if (status.is_success() && response_code == 200) {
194 JSONStringValueSerializer deserializer(json_data);
195 deserializer.set_allow_trailing_comma(true);
[email protected]ba399672010-04-06 15:42:39196 scoped_ptr<Value> root_val(deserializer.Deserialize(NULL, NULL));
[email protected]257ab712009-04-14 17:16:24197 const std::wstring& input_text =
198 is_keyword_results ? keyword_input_text_ : input_.text();
[email protected]b4cebf82008-12-29 19:59:08199 have_suggest_results_ =
[email protected]257ab712009-04-14 17:16:24200 root_val.get() &&
201 ParseSuggestResults(root_val.get(), is_keyword_results, input_text,
202 suggest_results);
[email protected]b4cebf82008-12-29 19:59:08203 }
204
initial.commit09911bf2008-07-26 23:55:29205 ConvertResultsToAutocompleteMatches();
[email protected]257ab712009-04-14 17:16:24206 listener_->OnProviderUpdate(!suggest_results->empty());
initial.commit09911bf2008-07-26 23:55:29207}
208
[email protected]601858c02010-09-01 17:08:20209SearchProvider::~SearchProvider() {
210}
211
[email protected]8deeb952008-10-09 18:21:27212void SearchProvider::StartOrStopHistoryQuery(bool minimal_changes) {
initial.commit09911bf2008-07-26 23:55:29213 // For the minimal_changes case, if we finished the previous query and still
214 // have its results, or are allowed to keep running it, just do that, rather
215 // than starting a new query.
216 if (minimal_changes &&
[email protected]8deeb952008-10-09 18:21:27217 (have_history_results_ || (!done_ && !input_.synchronous_only())))
initial.commit09911bf2008-07-26 23:55:29218 return;
219
220 // We can't keep running any previous query, so halt it.
221 StopHistory();
222
223 // We can't start a new query if we're only allowed synchronous results.
[email protected]8deeb952008-10-09 18:21:27224 if (input_.synchronous_only())
initial.commit09911bf2008-07-26 23:55:29225 return;
226
[email protected]257ab712009-04-14 17:16:24227 // Request history for both the keyword and default provider.
228 if (providers_.valid_keyword_provider()) {
229 ScheduleHistoryQuery(providers_.keyword_provider().id(),
230 keyword_input_text_);
231 }
232 if (providers_.valid_default_provider()) {
233 ScheduleHistoryQuery(providers_.default_provider().id(),
234 input_.text());
235 }
initial.commit09911bf2008-07-26 23:55:29236}
237
[email protected]8deeb952008-10-09 18:21:27238void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]6c85aa02009-02-27 12:08:09239 // Don't send any queries to the server until some time has elapsed after
240 // the last keypress, to avoid flooding the server with requests we are
241 // likely to end up throwing away anyway.
242 static const int kQueryDelayMs = 200;
243
[email protected]83c726482008-09-10 06:36:34244 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29245 StopSuggest();
246 return;
247 }
248
249 // For the minimal_changes case, if we finished the previous query and still
250 // have its results, or are allowed to keep running it, just do that, rather
251 // than starting a new query.
252 if (minimal_changes &&
[email protected]8deeb952008-10-09 18:21:27253 (have_suggest_results_ || (!done_ && !input_.synchronous_only())))
initial.commit09911bf2008-07-26 23:55:29254 return;
255
256 // We can't keep running any previous query, so halt it.
257 StopSuggest();
258
259 // We can't start a new query if we're only allowed synchronous results.
[email protected]8deeb952008-10-09 18:21:27260 if (input_.synchronous_only())
initial.commit09911bf2008-07-26 23:55:29261 return;
262
[email protected]257ab712009-04-14 17:16:24263 // We'll have at least one pending fetch. Set it to 1 now, but the value is
264 // correctly set in Run. As Run isn't invoked immediately we need to set this
265 // now, else we won't think we're waiting on results from the server when we
266 // really are.
267 suggest_results_pending_ = 1;
268
initial.commit09911bf2008-07-26 23:55:29269 // Kick off a timer that will start the URL fetch if it completes before
270 // the user types another character.
[email protected]b547666d2009-04-23 16:37:58271 int delay = query_suggest_immediately_ ? 0 : kQueryDelayMs;
272 timer_.Start(TimeDelta::FromMilliseconds(delay), this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29273}
274
[email protected]83c726482008-09-10 06:36:34275bool SearchProvider::IsQuerySuitableForSuggest() const {
276 // Don't run Suggest when off the record, the engine doesn't support it, or
277 // the user has disabled it.
278 if (profile_->IsOffTheRecord() ||
[email protected]257ab712009-04-14 17:16:24279 (!providers_.valid_suggest_for_keyword_provider() &&
280 !providers_.valid_suggest_for_default_provider()) ||
[email protected]83c726482008-09-10 06:36:34281 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
282 return false;
283
[email protected]cac59d32010-08-09 23:23:14284 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34285 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34286
[email protected]cac59d32010-08-09 23:23:14287 // FORCED_QUERY means the user is explicitly asking us to search for this, so
288 // we assume it isn't a URL and/or there isn't private data.
289 if (input_.type() == AutocompleteInput::FORCED_QUERY)
290 return true;
[email protected]83c726482008-09-10 06:36:34291
[email protected]cac59d32010-08-09 23:23:14292 // Next we check the scheme. If this is UNKNOWN/REQUESTED_URL/URL with a
293 // scheme that isn't http/https/ftp, we shouldn't send it. Sending things
294 // like file: and data: is both a waste of time and a disclosure of
295 // potentially private, local data. Other "schemes" may actually be
296 // usernames, and we don't want to send passwords. If the scheme is OK, we
297 // still need to check other cases below. If this is QUERY, then the presence
298 // of these schemes means the user explicitly typed one, and thus this is
299 // probably a URL that's being entered and happens to currently be invalid --
300 // in which case we again want to run our checks below. Other QUERY cases are
301 // less likely to be URLs and thus we assume we're OK.
302 if ((input_.scheme() != L"http") && (input_.scheme() != L"https") &&
303 (input_.scheme() != L"ftp"))
304 return (input_.type() == AutocompleteInput::QUERY);
305
306 // Don't send URLs with usernames, queries or refs. Some of these are
307 // private, and the Suggest server is unlikely to have any useful results
308 // for any of them. Also don't send URLs with ports, as we may initially
309 // think that a username + password is a host + port (and we don't want to
310 // send usernames/passwords), and even if the port really is a port, the
311 // server is once again unlikely to have and useful results.
312 const url_parse::Parsed& parts = input_.parts();
313 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
314 parts.query.is_nonempty() || parts.ref.is_nonempty())
315 return false;
316
317 // Don't send anything for https except the hostname. Hostnames are OK
318 // because they are visible when the TCP connection is established, but the
319 // specific path may reveal private information.
320 if ((input_.scheme() == L"https") && parts.path.is_nonempty())
321 return false;
[email protected]83c726482008-09-10 06:36:34322
323 return true;
324}
325
initial.commit09911bf2008-07-26 23:55:29326void SearchProvider::StopHistory() {
327 history_request_consumer_.CancelAllRequests();
328 history_request_pending_ = false;
[email protected]257ab712009-04-14 17:16:24329 keyword_history_results_.clear();
330 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29331 have_history_results_ = false;
332}
333
334void SearchProvider::StopSuggest() {
[email protected]257ab712009-04-14 17:16:24335 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14336 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24337 // Stop any in-progress URL fetches.
338 keyword_fetcher_.reset();
339 default_fetcher_.reset();
340 keyword_suggest_results_.clear();
341 default_suggest_results_.clear();
342 keyword_navigation_results_.clear();
343 default_navigation_results_.clear();
initial.commit09911bf2008-07-26 23:55:29344 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29345}
346
[email protected]8b62334b2010-08-31 22:37:11347void SearchProvider::ScheduleHistoryQuery(TemplateURLID search_id,
[email protected]257ab712009-04-14 17:16:24348 const std::wstring& text) {
349 DCHECK(!text.empty());
350 HistoryService* const history_service =
351 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
352 HistoryService::Handle request_handle =
353 history_service->GetMostRecentKeywordSearchTerms(
[email protected]e53668962010-06-23 15:35:25354 search_id, WideToUTF16(text), static_cast<int>(kMaxMatches),
[email protected]257ab712009-04-14 17:16:24355 &history_request_consumer_,
356 NewCallback(this,
357 &SearchProvider::OnGotMostRecentKeywordSearchTerms));
358 history_request_consumer_.SetClientData(history_service, request_handle,
359 search_id);
360 history_request_pending_ = true;
361}
362
initial.commit09911bf2008-07-26 23:55:29363void SearchProvider::OnGotMostRecentKeywordSearchTerms(
364 CancelableRequestProvider::Handle handle,
365 HistoryResults* results) {
[email protected]257ab712009-04-14 17:16:24366 HistoryService* history_service =
367 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
368 DCHECK(history_service);
369 if (providers_.valid_keyword_provider() &&
[email protected]bed9bd6c2009-04-21 17:27:47370 (providers_.keyword_provider().id() ==
[email protected]257ab712009-04-14 17:16:24371 history_request_consumer_.GetClientData(history_service, handle))) {
372 keyword_history_results_ = *results;
373 } else {
374 default_history_results_ = *results;
375 }
[email protected]257ab712009-04-14 17:16:24376
377 if (history_request_consumer_.PendingRequestCount() == 1) {
378 // Requests are removed AFTER the callback is invoked. If the count == 1,
379 // it means no more history requests are pending.
380 history_request_pending_ = false;
381 have_history_results_ = true;
382 }
[email protected]b547666d2009-04-23 16:37:58383
384 ConvertResultsToAutocompleteMatches();
385 listener_->OnProviderUpdate(!results->empty());
initial.commit09911bf2008-07-26 23:55:29386}
387
[email protected]b547666d2009-04-23 16:37:58388URLFetcher* SearchProvider::CreateSuggestFetcher(int id,
389 const TemplateURL& provider,
[email protected]257ab712009-04-14 17:16:24390 const std::wstring& text) {
391 const TemplateURLRef* const suggestions_url = provider.suggestions_url();
392 DCHECK(suggestions_url->SupportsReplacement());
[email protected]b547666d2009-04-23 16:37:58393 URLFetcher* fetcher = URLFetcher::Create(id,
[email protected]ddd231e2010-06-29 20:35:19394 GURL(suggestions_url->ReplaceSearchTerms(
395 provider, text, TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
396 std::wstring())),
[email protected]257ab712009-04-14 17:16:24397 URLFetcher::GET, this);
398 fetcher->set_request_context(profile_->GetRequestContext());
399 fetcher->Start();
400 return fetcher;
401}
402
403bool SearchProvider::ParseSuggestResults(Value* root_val,
404 bool is_keyword,
405 const std::wstring& input_text,
406 SuggestResults* suggest_results) {
initial.commit09911bf2008-07-26 23:55:29407 if (!root_val->IsType(Value::TYPE_LIST))
408 return false;
409 ListValue* root_list = static_cast<ListValue*>(root_val);
410
411 Value* query_val;
[email protected]dc9a6762010-08-16 07:13:53412 string16 query_str;
initial.commit09911bf2008-07-26 23:55:29413 Value* result_val;
414 if ((root_list->GetSize() < 2) || !root_list->Get(0, &query_val) ||
[email protected]dc9a6762010-08-16 07:13:53415 !query_val->GetAsString(&query_str) ||
416 (query_str != WideToUTF16Hack(input_text)) ||
initial.commit09911bf2008-07-26 23:55:29417 !root_list->Get(1, &result_val) || !result_val->IsType(Value::TYPE_LIST))
418 return false;
419
420 ListValue* description_list = NULL;
421 if (root_list->GetSize() > 2) {
422 // 3rd element: Description list.
423 Value* description_val;
424 if (root_list->Get(2, &description_val) &&
425 description_val->IsType(Value::TYPE_LIST))
426 description_list = static_cast<ListValue*>(description_val);
427 }
428
429 // We don't care about the query URL list (the fourth element in the
430 // response) for now.
431
432 // Parse optional data in the results from the Suggest server if any.
433 ListValue* type_list = NULL;
434 // 5th argument: Optional key-value pairs.
435 // TODO: We may iterate the 5th+ arguments of the root_list if any other
436 // optional data are defined.
437 if (root_list->GetSize() > 4) {
438 Value* optional_val;
439 if (root_list->Get(4, &optional_val) &&
440 optional_val->IsType(Value::TYPE_DICTIONARY)) {
441 DictionaryValue* dict_val = static_cast<DictionaryValue*>(optional_val);
442
443 // Parse Google Suggest specific type extension.
[email protected]a65175d2010-08-17 04:00:57444 static const std::string kGoogleSuggestType("google:suggesttype");
initial.commit09911bf2008-07-26 23:55:29445 if (dict_val->HasKey(kGoogleSuggestType))
446 dict_val->GetList(kGoogleSuggestType, &type_list);
447 }
448 }
449
450 ListValue* result_list = static_cast<ListValue*>(result_val);
451 for (size_t i = 0; i < result_list->GetSize(); ++i) {
452 Value* suggestion_val;
[email protected]dc9a6762010-08-16 07:13:53453 string16 suggestion_str;
initial.commit09911bf2008-07-26 23:55:29454 if (!result_list->Get(i, &suggestion_val) ||
455 !suggestion_val->GetAsString(&suggestion_str))
456 return false;
457
458 Value* type_val;
[email protected]dc9a6762010-08-16 07:13:53459 std::string type_str;
initial.commit09911bf2008-07-26 23:55:29460 if (type_list && type_list->Get(i, &type_val) &&
[email protected]dc9a6762010-08-16 07:13:53461 type_val->GetAsString(&type_str) && (type_str == "NAVIGATION")) {
initial.commit09911bf2008-07-26 23:55:29462 Value* site_val;
[email protected]dc9a6762010-08-16 07:13:53463 string16 site_name;
[email protected]257ab712009-04-14 17:16:24464 NavigationResults& navigation_results =
465 is_keyword ? keyword_navigation_results_ :
466 default_navigation_results_;
[email protected]0be9b612010-05-18 01:13:41467 if ((navigation_results.size() < kMaxMatches) &&
initial.commit09911bf2008-07-26 23:55:29468 description_list && description_list->Get(i, &site_val) &&
469 site_val->IsType(Value::TYPE_STRING) &&
470 site_val->GetAsString(&site_name)) {
[email protected]16afe222009-01-08 18:57:45471 // We can't blindly trust the URL coming from the server to be valid.
[email protected]dc9a6762010-08-16 07:13:53472 GURL result_url(URLFixerUpper::FixupURL(UTF16ToUTF8(suggestion_str),
[email protected]76e7da22010-06-18 22:44:49473 std::string()));
[email protected]dc9a6762010-08-16 07:13:53474 if (result_url.is_valid()) {
475 navigation_results.push_back(NavigationResult(result_url,
476 UTF16ToWideHack(site_name)));
477 }
initial.commit09911bf2008-07-26 23:55:29478 }
479 } else {
480 // TODO(kochi): Currently we treat a calculator result as a query, but it
481 // is better to have better presentation for caluculator results.
[email protected]0be9b612010-05-18 01:13:41482 if (suggest_results->size() < kMaxMatches)
[email protected]dc9a6762010-08-16 07:13:53483 suggest_results->push_back(UTF16ToWideHack(suggestion_str));
initial.commit09911bf2008-07-26 23:55:29484 }
485 }
486
initial.commit09911bf2008-07-26 23:55:29487 return true;
488}
489
490void SearchProvider::ConvertResultsToAutocompleteMatches() {
491 // Convert all the results to matches and add them to a map, so we can keep
492 // the most relevant match for each result.
493 MatchMap map;
[email protected]257ab712009-04-14 17:16:24494 const Time no_time;
495 int did_not_accept_keyword_suggestion = keyword_suggest_results_.empty() ?
initial.commit09911bf2008-07-26 23:55:29496 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
497 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]257ab712009-04-14 17:16:24498 // Keyword what you typed results are handled by the KeywordProvider.
initial.commit09911bf2008-07-26 23:55:29499
[email protected]257ab712009-04-14 17:16:24500 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
501 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
502 TemplateURLRef::NO_SUGGESTION_CHOSEN;
503 if (providers_.valid_default_provider()) {
504 AddMatchToMap(input_.text(), CalculateRelevanceForWhatYouTyped(),
505 AutocompleteMatch::SEARCH_WHAT_YOU_TYPED,
506 did_not_accept_default_suggestion, false, &map);
initial.commit09911bf2008-07-26 23:55:29507 }
508
[email protected]257ab712009-04-14 17:16:24509 AddHistoryResultsToMap(keyword_history_results_, true,
510 did_not_accept_keyword_suggestion, &map);
511 AddHistoryResultsToMap(default_history_results_, false,
512 did_not_accept_default_suggestion, &map);
513
514 AddSuggestResultsToMap(keyword_suggest_results_, true,
515 did_not_accept_keyword_suggestion, &map);
516 AddSuggestResultsToMap(default_suggest_results_, false,
517 did_not_accept_default_suggestion, &map);
initial.commit09911bf2008-07-26 23:55:29518
519 // Now add the most relevant matches from the map to |matches_|.
520 matches_.clear();
521 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
522 matches_.push_back(i->second);
523
[email protected]257ab712009-04-14 17:16:24524 AddNavigationResultsToMatches(keyword_navigation_results_, true);
525 AddNavigationResultsToMatches(default_navigation_results_, false);
initial.commit09911bf2008-07-26 23:55:29526
[email protected]0be9b612010-05-18 01:13:41527 const size_t max_total_matches = kMaxMatches + 1; // 1 for "what you typed"
initial.commit09911bf2008-07-26 23:55:29528 std::partial_sort(matches_.begin(),
529 matches_.begin() + std::min(max_total_matches, matches_.size()),
530 matches_.end(), &AutocompleteMatch::MoreRelevant);
531 if (matches_.size() > max_total_matches)
[email protected]a28e95662008-11-12 19:19:02532 matches_.erase(matches_.begin() + max_total_matches, matches_.end());
initial.commit09911bf2008-07-26 23:55:29533
[email protected]cc63dea2008-08-21 20:56:31534 UpdateStarredStateOfMatches();
535
[email protected]6c85aa02009-02-27 12:08:09536 // We're done when both asynchronous subcomponents have finished. We can't
537 // use CancelableRequestConsumer.HasPendingRequests() for history requests
538 // here. A pending request is not cleared until after the completion
539 // callback has returned, but we've reached here from inside that callback.
540 // HasPendingRequests() would therefore return true, and if this is the last
541 // thing left to calculate for this query, we'll never mark the query "done".
[email protected]257ab712009-04-14 17:16:24542 done_ = !history_request_pending_ && !suggest_results_pending_;
543}
544
545void SearchProvider::AddNavigationResultsToMatches(
546 const NavigationResults& navigation_results,
547 bool is_keyword) {
548 if (!navigation_results.empty()) {
549 // TODO(kochi): http://b/1170574 We add only one results for navigational
550 // suggestions. If we can get more useful information about the score,
551 // consider adding more results.
[email protected]52d08b12009-10-19 18:42:36552 const size_t num_results = is_keyword ?
553 keyword_navigation_results_.size() : default_navigation_results_.size();
554 matches_.push_back(NavigationToMatch(navigation_results.front(),
555 CalculateRelevanceForNavigation(num_results, 0, is_keyword),
556 is_keyword));
[email protected]257ab712009-04-14 17:16:24557 }
558}
559
560void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
561 bool is_keyword,
562 int did_not_accept_suggestion,
563 MatchMap* map) {
564 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
565 ++i) {
[email protected]e53668962010-06-23 15:35:25566 AddMatchToMap(UTF16ToWide(i->term),
567 CalculateRelevanceForHistory(i->time, is_keyword),
[email protected]257ab712009-04-14 17:16:24568 AutocompleteMatch::SEARCH_HISTORY, did_not_accept_suggestion,
569 is_keyword, map);
570 }
571}
572
573void SearchProvider::AddSuggestResultsToMap(
574 const SuggestResults& suggest_results,
575 bool is_keyword,
576 int did_not_accept_suggestion,
577 MatchMap* map) {
578 for (size_t i = 0; i < suggest_results.size(); ++i) {
579 AddMatchToMap(suggest_results[i],
[email protected]52d08b12009-10-19 18:42:36580 CalculateRelevanceForSuggestion(suggest_results.size(), i,
[email protected]257ab712009-04-14 17:16:24581 is_keyword),
582 AutocompleteMatch::SEARCH_SUGGEST,
583 static_cast<int>(i), is_keyword, map);
584 }
initial.commit09911bf2008-07-26 23:55:29585}
586
587int SearchProvider::CalculateRelevanceForWhatYouTyped() const {
[email protected]52d08b12009-10-19 18:42:36588 if (providers_.valid_keyword_provider())
589 return 250;
590
initial.commit09911bf2008-07-26 23:55:29591 switch (input_.type()) {
592 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:36593 case AutocompleteInput::QUERY:
594 case AutocompleteInput::FORCED_QUERY:
595 return 1300;
initial.commit09911bf2008-07-26 23:55:29596
597 case AutocompleteInput::REQUESTED_URL:
[email protected]52d08b12009-10-19 18:42:36598 return 1150;
initial.commit09911bf2008-07-26 23:55:29599
600 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:36601 return 850;
initial.commit09911bf2008-07-26 23:55:29602
603 default:
604 NOTREACHED();
605 return 0;
606 }
607}
608
[email protected]257ab712009-04-14 17:16:24609int SearchProvider::CalculateRelevanceForHistory(const Time& time,
610 bool is_keyword) const {
initial.commit09911bf2008-07-26 23:55:29611 // The relevance of past searches falls off over time. This curve is chosen
612 // so that the relevance of a search 15 minutes ago is discounted about 50
613 // points, while the relevance of a search two weeks ago is discounted about
614 // 450 points.
615 const double elapsed_time = std::max((Time::Now() - time).InSecondsF(), 0.);
[email protected]c3a4bd992010-08-18 20:25:01616 const int score_discount =
617 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:29618
[email protected]6c85aa02009-02-27 12:08:09619 // Don't let scores go below 0. Negative relevance scores are meaningful in
620 // a different way.
initial.commit09911bf2008-07-26 23:55:29621 int base_score;
[email protected]52d08b12009-10-19 18:42:36622 if (!providers_.is_primary_provider(is_keyword))
623 base_score = 200;
624 else
625 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
initial.commit09911bf2008-07-26 23:55:29626 return std::max(0, base_score - score_discount);
627}
628
[email protected]52d08b12009-10-19 18:42:36629int SearchProvider::CalculateRelevanceForSuggestion(size_t num_results,
630 size_t result_number,
631 bool is_keyword) const {
632 DCHECK(result_number < num_results);
633 int base_score;
634 if (!providers_.is_primary_provider(is_keyword))
635 base_score = 100;
636 else
637 base_score = (input_.type() == AutocompleteInput::URL) ? 300 : 600;
638 return base_score +
639 static_cast<int>(num_results - 1 - result_number);
initial.commit09911bf2008-07-26 23:55:29640}
641
[email protected]52d08b12009-10-19 18:42:36642int SearchProvider::CalculateRelevanceForNavigation(size_t num_results,
643 size_t result_number,
644 bool is_keyword) const {
645 DCHECK(result_number < num_results);
initial.commit09911bf2008-07-26 23:55:29646 // TODO(kochi): http://b/784900 Use relevance score from the NavSuggest
647 // server if possible.
[email protected]52d08b12009-10-19 18:42:36648 return (providers_.is_primary_provider(is_keyword) ? 800 : 150) +
649 static_cast<int>(num_results - 1 - result_number);
initial.commit09911bf2008-07-26 23:55:29650}
651
652void SearchProvider::AddMatchToMap(const std::wstring& query_string,
653 int relevance,
[email protected]4c1fb7ec2008-11-13 00:19:00654 AutocompleteMatch::Type type,
initial.commit09911bf2008-07-26 23:55:29655 int accepted_suggestion,
[email protected]257ab712009-04-14 17:16:24656 bool is_keyword,
initial.commit09911bf2008-07-26 23:55:29657 MatchMap* map) {
[email protected]257ab712009-04-14 17:16:24658 const std::wstring& input_text =
659 is_keyword ? keyword_input_text_ : input_.text();
[email protected]4c1fb7ec2008-11-13 00:19:00660 AutocompleteMatch match(this, relevance, false, type);
initial.commit09911bf2008-07-26 23:55:29661 std::vector<size_t> content_param_offsets;
[email protected]257ab712009-04-14 17:16:24662 const TemplateURL& provider = is_keyword ? providers_.keyword_provider() :
663 providers_.default_provider();
[email protected]fb5153c52009-07-31 19:40:33664 // We do intra-string highlighting for suggestions - the suggested segment
665 // will be highlighted, e.g. for input_text = "you" the suggestion may be
666 // "youtube", so we'll bold the "tube" section: you*tube*.
667 if (input_text != query_string) {
668 match.contents.assign(query_string);
669 size_t input_position = match.contents.find(input_text);
670 if (input_position == std::wstring::npos) {
671 // The input text is not a substring of the query string, e.g. input
672 // text is "slasdot" and the query string is "slashdot", so we bold the
673 // whole thing.
674 match.contents_class.push_back(
675 ACMatchClassification(0, ACMatchClassification::MATCH));
[email protected]ec2379162009-06-09 23:58:17676 } else {
[email protected]fb5153c52009-07-31 19:40:33677 // TODO(beng): ACMatchClassification::MATCH now seems to just mean
678 // "bold" this. Consider modifying the terminology.
679 // We don't iterate over the string here annotating all matches because
680 // it looks odd to have every occurrence of a substring that may be as
681 // short as a single character highlighted in a query suggestion result,
682 // e.g. for input text "s" and query string "southwest airlines", it
683 // looks odd if both the first and last s are highlighted.
684 if (input_position != 0) {
685 match.contents_class.push_back(
686 ACMatchClassification(0, ACMatchClassification::NONE));
687 }
688 match.contents_class.push_back(
689 ACMatchClassification(input_position, ACMatchClassification::DIM));
690 size_t next_fragment_position = input_position + input_text.length();
691 if (next_fragment_position < query_string.length()) {
692 match.contents_class.push_back(
693 ACMatchClassification(next_fragment_position,
694 ACMatchClassification::NONE));
695 }
[email protected]ec2379162009-06-09 23:58:17696 }
initial.commit09911bf2008-07-26 23:55:29697 } else {
[email protected]fb5153c52009-07-31 19:40:33698 // Otherwise, we're dealing with the "default search" result which has no
699 // completion, but has the search provider name as the description.
700 match.contents.assign(query_string);
701 match.contents_class.push_back(
702 ACMatchClassification(0, ACMatchClassification::NONE));
703 match.description.assign(l10n_util::GetStringF(
704 IDS_AUTOCOMPLETE_SEARCH_DESCRIPTION,
[email protected]2c33dd22010-02-11 21:46:35705 provider.AdjustedShortNameForLocaleDirection()));
[email protected]fb5153c52009-07-31 19:40:33706 match.description_class.push_back(
707 ACMatchClassification(0, ACMatchClassification::DIM));
initial.commit09911bf2008-07-26 23:55:29708 }
709
710 // When the user forced a query, we need to make sure all the fill_into_edit
711 // values preserve that property. Otherwise, if the user starts editing a
712 // suggestion, non-Search results will suddenly appear.
713 size_t search_start = 0;
714 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
715 match.fill_into_edit.assign(L"?");
716 ++search_start;
717 }
[email protected]c0048b42009-05-04 21:47:17718 if (is_keyword) {
719 match.fill_into_edit.append(providers_.keyword_provider().keyword() + L" ");
720 match.template_url = &providers_.keyword_provider();
721 }
initial.commit09911bf2008-07-26 23:55:29722 match.fill_into_edit.append(query_string);
[email protected]2c33dd22010-02-11 21:46:35723 // Not all suggestions start with the original input.
initial.commit09911bf2008-07-26 23:55:29724 if (!input_.prevent_inline_autocomplete() &&
[email protected]257ab712009-04-14 17:16:24725 !match.fill_into_edit.compare(search_start, input_text.length(),
726 input_text))
727 match.inline_autocomplete_offset = search_start + input_text.length();
initial.commit09911bf2008-07-26 23:55:29728
[email protected]257ab712009-04-14 17:16:24729 const TemplateURLRef* const search_url = provider.url();
initial.commit09911bf2008-07-26 23:55:29730 DCHECK(search_url->SupportsReplacement());
[email protected]7b9f3672009-06-15 18:31:22731 match.destination_url =
[email protected]ddd231e2010-06-29 20:35:19732 GURL(search_url->ReplaceSearchTerms(provider,
733 query_string,
734 accepted_suggestion,
735 input_text));
initial.commit09911bf2008-07-26 23:55:29736
737 // Search results don't look like URLs.
[email protected]0bfc29a2009-04-27 16:15:44738 match.transition =
739 is_keyword ? PageTransition::KEYWORD : PageTransition::GENERATED;
initial.commit09911bf2008-07-26 23:55:29740
741 // Try to add |match| to |map|. If a match for |query_string| is already in
742 // |map|, replace it if |match| is more relevant.
743 // NOTE: Keep this ToLower() call in sync with url_database.cc.
744 const std::pair<MatchMap::iterator, bool> i = map->insert(
745 std::pair<std::wstring, AutocompleteMatch>(
[email protected]e5a8c472010-08-04 19:47:20746 UTF16ToWide(l10n_util::ToLower(WideToUTF16(query_string))), match));
initial.commit09911bf2008-07-26 23:55:29747 // NOTE: We purposefully do a direct relevance comparison here instead of
748 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items added
749 // first" rather than "items alphabetically first" when the scores are equal.
750 // The only case this matters is when a user has results with the same score
751 // that differ only by capitalization; because the history system returns
752 // results sorted by recency, this means we'll pick the most recent such
753 // result even if the precision of our relevance score is too low to
754 // distinguish the two.
755 if (!i.second && (match.relevance > i.first->second.relevance))
756 i.first->second = match;
757}
758
759AutocompleteMatch SearchProvider::NavigationToMatch(
760 const NavigationResult& navigation,
[email protected]257ab712009-04-14 17:16:24761 int relevance,
762 bool is_keyword) {
763 const std::wstring& input_text =
764 is_keyword ? keyword_input_text_ : input_.text();
[email protected]4c1fb7ec2008-11-13 00:19:00765 AutocompleteMatch match(this, relevance, false,
766 AutocompleteMatch::NAVSUGGEST);
initial.commit09911bf2008-07-26 23:55:29767 match.destination_url = navigation.url;
[email protected]76e7da22010-06-18 22:44:49768 match.contents =
769 StringForURLDisplay(navigation.url, true, !HasHTTPScheme(input_text));
[email protected]257ab712009-04-14 17:16:24770 AutocompleteMatch::ClassifyMatchInString(input_text, match.contents,
initial.commit09911bf2008-07-26 23:55:29771 ACMatchClassification::URL,
772 &match.contents_class);
773
774 match.description = navigation.site_name;
[email protected]257ab712009-04-14 17:16:24775 AutocompleteMatch::ClassifyMatchInString(input_text, navigation.site_name,
initial.commit09911bf2008-07-26 23:55:29776 ACMatchClassification::NONE,
777 &match.description_class);
778
initial.commit09911bf2008-07-26 23:55:29779 // When the user forced a query, we need to make sure all the fill_into_edit
780 // values preserve that property. Otherwise, if the user starts editing a
781 // suggestion, non-Search results will suddenly appear.
782 if (input_.type() == AutocompleteInput::FORCED_QUERY)
783 match.fill_into_edit.assign(L"?");
[email protected]79845ef2010-06-02 02:37:40784 match.fill_into_edit.append(
785 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url,
786 match.contents));
initial.commit09911bf2008-07-26 23:55:29787 // TODO(pkasting): http://b/1112879 These should perhaps be
788 // inline-autocompletable?
789
790 return match;
791}