blob: 1a4011e5bc6725b7ad13e8294601af725c92afe7 [file] [log] [blame]
[email protected]e41982a72012-11-20 07:16:511// Copyright 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
5#include "chrome/browser/autocomplete/search_provider.h"
6
[email protected]1cb2dac2010-03-08 21:49:157#include <algorithm>
[email protected]c3a4bd992010-08-18 20:25:018#include <cmath>
[email protected]1cb2dac2010-03-08 21:49:159
[email protected]2041cf342010-02-19 03:15:5910#include "base/callback.h"
[email protected]51124552011-07-16 01:37:1011#include "base/i18n/break_iterator.h"
[email protected]503d03872011-05-06 08:36:2612#include "base/i18n/case_conversion.h"
[email protected]d6e58c6e2009-10-10 20:40:5013#include "base/i18n/icu_string_conversions.h"
[email protected]ffbec692012-02-26 20:26:4214#include "base/json/json_string_value_serializer.h"
initial.commit09911bf2008-07-26 23:55:2915#include "base/message_loop.h"
[email protected]f5b95ba92012-03-27 14:05:1916#include "base/metrics/histogram.h"
[email protected]dc9a6762010-08-16 07:13:5317#include "base/string16.h"
[email protected]371dab12012-06-01 03:23:5518#include "base/string_util.h"
[email protected]1cb2dac2010-03-08 21:49:1519#include "base/utf_string_conversions.h"
[email protected]ea3b9a502011-04-04 14:19:3720#include "chrome/browser/autocomplete/autocomplete_classifier.h"
[email protected]810ffba2012-06-12 01:07:4821#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
[email protected]9ac40092010-10-27 23:05:2622#include "chrome/browser/autocomplete/autocomplete_match.h"
[email protected]5af9bc82012-06-29 00:53:4823#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
[email protected]73c2b1632012-07-02 22:51:3824#include "chrome/browser/autocomplete/autocomplete_result.h"
[email protected]3723e6e2012-06-11 21:06:5625#include "chrome/browser/autocomplete/history_url_provider.h"
[email protected]2c812ba02011-07-14 00:23:1526#include "chrome/browser/autocomplete/keyword_provider.h"
[email protected]371dab12012-06-01 03:23:5527#include "chrome/browser/autocomplete/url_prefix.h"
[email protected]ce560f82009-06-03 09:39:4428#include "chrome/browser/history/history.h"
[email protected]9d2db762012-06-19 00:01:1029#include "chrome/browser/history/history_service_factory.h"
[email protected]10c2d692012-05-11 05:32:2330#include "chrome/browser/history/in_memory_database.h"
[email protected]f870a322009-01-16 21:47:2731#include "chrome/browser/net/url_fixer_upper.h"
[email protected]37858e52010-08-26 00:22:0232#include "chrome/browser/prefs/pref_service.h"
[email protected]8ecad5e2010-12-02 21:18:3333#include "chrome/browser/profiles/profile.h"
[email protected]a0ad93ea2012-05-07 22:11:5334#include "chrome/browser/search_engines/search_engine_type.h"
[email protected]9899a612012-08-21 23:50:0435#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
[email protected]8e5c89a2011-06-07 18:13:3336#include "chrome/browser/search_engines/template_url_service.h"
37#include "chrome/browser/search_engines/template_url_service_factory.h"
[email protected]e41982a72012-11-20 07:16:5138#include "chrome/browser/ui/browser_instant_controller.h"
[email protected]5cd06c3e2012-09-20 03:25:2039#include "chrome/browser/ui/search/search.h"
initial.commit09911bf2008-07-26 23:55:2940#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0241#include "chrome/common/url_constants.h"
initial.commit09911bf2008-07-26 23:55:2942#include "googleurl/src/url_util.h"
[email protected]34ac8f32009-02-22 23:03:2743#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2944#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3445#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5546#include "net/base/net_util.h"
[email protected]319d9e6f2009-02-18 19:47:2147#include "net/http/http_response_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5348#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2149#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1750#include "ui/base/l10n/l10n_util.h"
initial.commit09911bf2008-07-26 23:55:2951
[email protected]e1acf6f2008-10-27 20:43:3352using base::Time;
53using base::TimeDelta;
54
[email protected]51124552011-07-16 01:37:1055namespace {
56
[email protected]7706a522012-08-16 17:42:2557// We keep track in a histogram how many suggest requests we send, how
58// many suggest requests we invalidate (e.g., due to a user typing
59// another character), and how many replies we receive.
60// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
61// (excluding the end-of-list enum value)
62// We do not want values of existing enums to change or else it screws
63// up the statistics.
64enum SuggestRequestsHistogramValue {
65 REQUEST_SENT = 1,
66 REQUEST_INVALIDATED,
67 REPLY_RECEIVED,
68 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
69};
70
71// Increments the appropriate value in the histogram by one.
72void LogOmniboxSuggestRequest(
73 SuggestRequestsHistogramValue request_value) {
74 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
75 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
76}
77
[email protected]51124552011-07-16 01:37:1078bool HasMultipleWords(const string16& text) {
79 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
80 bool found_word = false;
81 if (i.Init()) {
82 while (i.Advance()) {
83 if (i.IsWord()) {
84 if (found_word)
85 return true;
86 found_word = true;
87 }
88 }
89 }
90 return false;
91}
92
[email protected]d1f0a7f2012-06-05 10:26:4293} // namespace
[email protected]51124552011-07-16 01:37:1094
[email protected]033f3422012-03-13 21:24:1895
[email protected]3954c3a2012-04-10 20:17:5596// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:5897
[email protected]85b8d6f2012-05-08 20:53:4798SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
99 : template_url_service_(template_url_service) {
100}
101
102const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
103 return default_provider_.empty() ? NULL :
104 template_url_service_->GetTemplateURLForKeyword(default_provider_);
105}
106
107const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
108 return keyword_provider_.empty() ? NULL :
109 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24110}
111
[email protected]3954c3a2012-04-10 20:17:55112
113// SearchProvider -------------------------------------------------------------
114
115// static
116const int SearchProvider::kDefaultProviderURLFetcherID = 1;
117// static
118const int SearchProvider::kKeywordProviderURLFetcherID = 2;
[email protected]3954c3a2012-04-10 20:17:55119
[email protected]30f5bc92012-06-26 04:14:55120SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
121 Profile* profile)
[email protected]35f1f4f02012-09-11 13:17:00122 : AutocompleteProvider(listener, profile,
123 AutocompleteProvider::TYPE_SEARCH),
[email protected]85b8d6f2012-05-08 20:53:47124 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
[email protected]601858c02010-09-01 17:08:20125 suggest_results_pending_(0),
[email protected]d1f0a7f2012-06-05 10:26:42126 has_suggested_relevance_(false),
127 verbatim_relevance_(-1),
[email protected]8e5cc282010-12-05 18:11:39128 have_suggest_results_(false),
[email protected]4ab4c7c2010-11-24 04:49:34129 instant_finalized_(false) {
[email protected]4ab4c7c2010-11-24 04:49:34130}
131
[email protected]a2fedb1e2011-01-25 15:23:36132void SearchProvider::FinalizeInstantQuery(const string16& input_text,
[email protected]93b73832012-10-18 20:18:38133 const InstantSuggestion& suggestion) {
[email protected]4ab4c7c2010-11-24 04:49:34134 if (done_ || instant_finalized_)
135 return;
136
137 instant_finalized_ = true;
138 UpdateDone();
139
[email protected]e918c112010-12-08 23:03:49140 if (input_text.empty()) {
[email protected]4ab4c7c2010-11-24 04:49:34141 // We only need to update the listener if we're actually done.
142 if (done_)
143 listener_->OnProviderUpdate(false);
144 return;
145 }
146
[email protected]93b73832012-10-18 20:18:38147 default_provider_suggestion_ = suggestion;
[email protected]9e789742011-01-10 23:27:32148
[email protected]a2fedb1e2011-01-25 15:23:36149 string16 adjusted_input_text(input_text);
[email protected]e918c112010-12-08 23:03:49150 AutocompleteInput::RemoveForcedQueryStringIfNecessary(input_.type(),
151 &adjusted_input_text);
152
[email protected]93b73832012-10-18 20:18:38153 const string16 text = adjusted_input_text + suggestion.text;
[email protected]9acdcdc02012-05-21 20:58:36154 bool results_updated = false;
[email protected]4ab4c7c2010-11-24 04:49:34155 // Remove any matches that are identical to |text|. We don't use the
156 // destination_url for comparison as it varies depending upon the index passed
157 // to TemplateURL::ReplaceSearchTerms.
158 for (ACMatches::iterator i = matches_.begin(); i != matches_.end();) {
159 if (((i->type == AutocompleteMatch::SEARCH_HISTORY) ||
160 (i->type == AutocompleteMatch::SEARCH_SUGGEST)) &&
161 (i->fill_into_edit == text)) {
[email protected]e030de62010-11-24 05:41:19162 i = matches_.erase(i);
[email protected]9acdcdc02012-05-21 20:58:36163 results_updated = true;
[email protected]4ab4c7c2010-11-24 04:49:34164 } else {
165 ++i;
166 }
167 }
168
[email protected]55ce8f12012-05-09 04:44:08169 // Add the new instant suggest result. We give it a rank higher than
[email protected]4ab4c7c2010-11-24 04:49:34170 // SEARCH_WHAT_YOU_TYPED so that it gets autocompleted.
[email protected]93b73832012-10-18 20:18:38171 const int verbatim_relevance = GetVerbatimRelevance();
172 if (suggestion.type == INSTANT_SUGGESTION_SEARCH) {
173 // Instant has a query suggestion.
174 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
[email protected]4ab4c7c2010-11-24 04:49:34175 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
176 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]93b73832012-10-18 20:18:38177 MatchMap match_map;
178 AddMatchToMap(text, adjusted_input_text, verbatim_relevance + 1,
179 AutocompleteMatch::SEARCH_SUGGEST,
180 did_not_accept_default_suggestion, false, &match_map);
181 if (!match_map.empty()) {
182 matches_.push_back(match_map.begin()->second);
183 results_updated = true;
184 }
185 } else {
186 // Instant has an URL suggestion.
187 matches_.push_back(NavigationToMatch(
188 NavigationResult(GURL(UTF16ToUTF8(suggestion.text)),
189 string16(),
190 verbatim_relevance + 1),
191 false));
[email protected]9acdcdc02012-05-21 20:58:36192 results_updated = true;
193 }
[email protected]4ab4c7c2010-11-24 04:49:34194
[email protected]9acdcdc02012-05-21 20:58:36195 if (results_updated || done_)
196 listener_->OnProviderUpdate(results_updated);
[email protected]601858c02010-09-01 17:08:20197}
198
initial.commit09911bf2008-07-26 23:55:29199void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27200 bool minimal_changes) {
initial.commit09911bf2008-07-26 23:55:29201 matches_.clear();
202
[email protected]ea3b9a502011-04-04 14:19:37203 instant_finalized_ =
204 (input.matches_requested() != AutocompleteInput::ALL_MATCHES);
[email protected]4ab4c7c2010-11-24 04:49:34205
[email protected]6c85aa02009-02-27 12:08:09206 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29207 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]e29249dc52012-07-19 17:33:50208 Stop(false);
initial.commit09911bf2008-07-26 23:55:29209 return;
210 }
211
[email protected]257ab712009-04-14 17:16:24212 keyword_input_text_.clear();
213 const TemplateURL* keyword_provider =
214 KeywordProvider::GetSubstitutingTemplateURLForInput(profile_, input,
215 &keyword_input_text_);
[email protected]8d457132010-11-04 18:13:40216 if (keyword_input_text_.empty())
[email protected]257ab712009-04-14 17:16:24217 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24218
[email protected]85b8d6f2012-05-08 20:53:47219 TemplateURLService* model = providers_.template_url_service();
220 DCHECK(model);
221 model->Load();
222 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07223 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24224 default_provider = NULL;
225
226 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18227 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24228
229 if (!default_provider && !keyword_provider) {
230 // No valid providers.
[email protected]e29249dc52012-07-19 17:33:50231 Stop(false);
initial.commit09911bf2008-07-26 23:55:29232 return;
233 }
234
235 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24236 // or the providers, abort the query.
[email protected]85b8d6f2012-05-08 20:53:47237 string16 default_provider_keyword(default_provider ?
238 default_provider->keyword() : string16());
239 string16 keyword_provider_keyword(keyword_provider ?
240 keyword_provider->keyword() : string16());
[email protected]9e789742011-01-10 23:27:32241 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47242 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]9e789742011-01-10 23:27:32243 if (done_)
[email protected]93b73832012-10-18 20:18:38244 default_provider_suggestion_ = InstantSuggestion();
[email protected]9e789742011-01-10 23:27:32245 else
[email protected]e29249dc52012-07-19 17:33:50246 Stop(false);
[email protected]257ab712009-04-14 17:16:24247 }
initial.commit09911bf2008-07-26 23:55:29248
[email protected]85b8d6f2012-05-08 20:53:47249 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29250
251 if (input.text().empty()) {
252 // User typed "?" alone. Give them a placeholder result indicating what
253 // this syntax does.
[email protected]257ab712009-04-14 17:16:24254 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00255 AutocompleteMatch match;
256 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36257 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24258 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35259 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47260 match.keyword = providers_.default_provider();
[email protected]257ab712009-04-14 17:16:24261 matches_.push_back(match);
262 }
[email protected]e29249dc52012-07-19 17:33:50263 Stop(false);
initial.commit09911bf2008-07-26 23:55:29264 return;
265 }
266
267 input_ = input;
268
[email protected]5cd06c3e2012-09-20 03:25:20269 // Don't run the normal provider flow when the Instant Extended API is
270 // enabled. (When the Extended API is enabled, the embedded page will handle
271 // all search suggestions itself.)
272 // TODO(dcblack): once we are done refactoring the omnibox so we don't need to
273 // use FinalizeInstantQuery anymore, we can take out this check and remove
274 // this provider from kInstantExtendedOmniboxProviders.
275 if (!chrome::search::IsInstantExtendedAPIEnabled(profile_)) {
276 DoHistoryQuery(minimal_changes);
277 StartOrStopSuggestQuery(minimal_changes);
278 }
initial.commit09911bf2008-07-26 23:55:29279 ConvertResultsToAutocompleteMatches();
280}
281
[email protected]55ce8f12012-05-09 04:44:08282SearchProvider::Result::Result(int relevance) : relevance_(relevance) {}
283SearchProvider::Result::~Result() {}
284
285SearchProvider::SuggestResult::SuggestResult(const string16& suggestion,
286 int relevance)
287 : Result(relevance),
288 suggestion_(suggestion) {
289}
290
291SearchProvider::SuggestResult::~SuggestResult() {}
292
293SearchProvider::NavigationResult::NavigationResult(const GURL& url,
294 const string16& description,
295 int relevance)
296 : Result(relevance),
297 url_(url),
298 description_(description) {
299 DCHECK(url_.is_valid());
300}
301
302SearchProvider::NavigationResult::~NavigationResult() {}
303
304class SearchProvider::CompareScoredResults {
[email protected]51124552011-07-16 01:37:10305 public:
[email protected]55ce8f12012-05-09 04:44:08306 bool operator()(const Result& a, const Result& b) {
[email protected]51124552011-07-16 01:37:10307 // Sort in descending relevance order.
[email protected]55ce8f12012-05-09 04:44:08308 return a.relevance() > b.relevance();
[email protected]51124552011-07-16 01:37:10309 }
310};
311
initial.commit09911bf2008-07-26 23:55:29312void SearchProvider::Run() {
313 // Start a new request with the current input.
[email protected]257ab712009-04-14 17:16:24314 suggest_results_pending_ = 0;
[email protected]a0ad93ea2012-05-07 22:11:53315 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]9ff91722012-09-07 05:29:12316
317 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
318 providers_.GetDefaultProviderURL(), input_.text()));
319 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
320 providers_.GetKeywordProviderURL(), keyword_input_text_));
[email protected]85b8d6f2012-05-08 20:53:47321
322 // Both the above can fail if the providers have been modified or deleted
323 // since the query began.
324 if (suggest_results_pending_ == 0) {
325 UpdateDone();
326 // We only need to update the listener if we're actually done.
327 if (done_)
328 listener_->OnProviderUpdate(false);
329 }
initial.commit09911bf2008-07-26 23:55:29330}
331
[email protected]e29249dc52012-07-19 17:33:50332void SearchProvider::Stop(bool clear_cached_results) {
initial.commit09911bf2008-07-26 23:55:29333 StopSuggest();
334 done_ = true;
[email protected]93b73832012-10-18 20:18:38335 default_provider_suggestion_ = InstantSuggestion();
[email protected]e29249dc52012-07-19 17:33:50336
337 if (clear_cached_results)
338 ClearResults();
initial.commit09911bf2008-07-26 23:55:29339}
340
[email protected]0e9e8782012-05-15 23:01:51341void SearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
342 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
343 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
344 new_entry.set_provider(AsOmniboxEventProviderType());
345 new_entry.set_provider_done(done_);
346}
347
[email protected]10c2d692012-05-11 05:32:23348void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29349 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24350 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25351 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15352 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06353 const net::HttpResponseHeaders* const response_headers =
[email protected]7cc6e5632011-10-25 17:56:12354 source->GetResponseHeaders();
[email protected]c530c852011-10-24 18:18:34355 std::string json_data;
356 source->GetResponseAsString(&json_data);
[email protected]6c85aa02009-02-27 12:08:09357 // JSON is supposed to be UTF-8, but some suggest service providers send JSON
358 // files in non-UTF-8 encodings. The actual encoding is usually specified in
359 // the Content-Type header field.
[email protected]ec9207d32008-09-26 00:51:06360 if (response_headers) {
361 std::string charset;
362 if (response_headers->GetCharset(&charset)) {
[email protected]a2fedb1e2011-01-25 15:23:36363 string16 data_16;
[email protected]ec9207d32008-09-26 00:51:06364 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
[email protected]c530c852011-10-24 18:18:34365 if (base::CodepageToUTF16(json_data, charset.c_str(),
[email protected]a2fedb1e2011-01-25 15:23:36366 base::OnStringConversionError::FAIL,
367 &data_16))
368 json_data = UTF16ToUTF8(data_16);
[email protected]ec9207d32008-09-26 00:51:06369 }
370 }
371
[email protected]d7ad4772012-06-01 03:12:54372 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]013e9a02012-05-18 20:27:10373 const bool request_succeeded =
374 source->GetStatus().is_success() && source->GetResponseCode() == 200;
[email protected]a0ad93ea2012-05-07 22:11:53375
376 // Record response time for suggest requests sent to Google. We care
377 // only about the common case: the Google default provider used in
378 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47379 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08380 if (!is_keyword && default_url &&
[email protected]9899a612012-08-21 23:50:04381 (TemplateURLPrepopulateData::GetEngineType(default_url->url()) ==
382 SEARCH_ENGINE_GOOGLE)) {
[email protected]6dc950f2012-07-16 19:49:08383 const TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10384 base::TimeTicks::Now() - time_suggest_request_sent_;
385 if (request_succeeded) {
386 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
387 elapsed_time);
388 } else {
389 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
390 elapsed_time);
391 }
[email protected]b4cebf82008-12-29 19:59:08392 }
393
[email protected]d7ad4772012-06-01 03:12:54394 bool results_updated = false;
395 if (request_succeeded) {
396 JSONStringValueSerializer deserializer(json_data);
397 deserializer.set_allow_trailing_comma(true);
398 scoped_ptr<Value> data(deserializer.Deserialize(NULL, NULL));
399 results_updated = data.get() && ParseSuggestResults(data.get(), is_keyword);
400 }
401
initial.commit09911bf2008-07-26 23:55:29402 ConvertResultsToAutocompleteMatches();
[email protected]d7ad4772012-06-01 03:12:54403 if (done_ || results_updated)
404 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29405}
406
[email protected]601858c02010-09-01 17:08:20407SearchProvider::~SearchProvider() {
408}
409
[email protected]8d457132010-11-04 18:13:40410void SearchProvider::DoHistoryQuery(bool minimal_changes) {
411 // The history query results are synchronous, so if minimal_changes is true,
412 // we still have the last results and don't need to do anything.
413 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29414 return;
415
[email protected]8d457132010-11-04 18:13:40416 keyword_history_results_.clear();
417 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29418
[email protected]8d457132010-11-04 18:13:40419 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10420 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]8d457132010-11-04 18:13:40421 history::URLDatabase* url_db = history_service ?
422 history_service->InMemoryDatabase() : NULL;
423 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29424 return;
425
[email protected]51124552011-07-16 01:37:10426 // Request history for both the keyword and default provider. We grab many
427 // more matches than we'll ultimately clamp to so that if there are several
428 // recent multi-word matches who scores are lowered (see
429 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
430 // matches. Note that this doesn't fix the problem entirely, but merely
431 // limits it to cases with a very large number of such multi-word matches; for
432 // now, this seems OK compared with the complexity of a real fix, which would
433 // require multiple searches and tracking of "single- vs. multi-word" in the
434 // database.
435 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47436 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
437 if (default_url) {
438 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
439 num_matches, &default_history_results_);
[email protected]257ab712009-04-14 17:16:24440 }
[email protected]85b8d6f2012-05-08 20:53:47441 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
442 if (keyword_url) {
443 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]3954c3a2012-04-10 20:17:55444 keyword_input_text_, num_matches, &keyword_history_results_);
445 }
initial.commit09911bf2008-07-26 23:55:29446}
447
[email protected]6dc950f2012-07-16 19:49:08448void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34449 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29450 StopSuggest();
[email protected]55ce8f12012-05-09 04:44:08451 ClearResults();
initial.commit09911bf2008-07-26 23:55:29452 return;
453 }
454
455 // For the minimal_changes case, if we finished the previous query and still
456 // have its results, or are allowed to keep running it, just do that, rather
457 // than starting a new query.
458 if (minimal_changes &&
[email protected]ea3b9a502011-04-04 14:19:37459 (have_suggest_results_ ||
460 (!done_ &&
461 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29462 return;
463
464 // We can't keep running any previous query, so halt it.
465 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42466
467 // Remove existing results that cannot inline autocomplete the new input.
468 RemoveStaleResults();
initial.commit09911bf2008-07-26 23:55:29469
470 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37471 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29472 return;
473
[email protected]515ffa942012-11-27 20:18:24474 // To avoid flooding the suggest server, don't send a query until at least 100
475 // ms since the last query.
476 const int kMinimumTimeBetweenSuggestQueriesMs = 100;
477 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
478 TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
479 base::TimeTicks now(base::TimeTicks::Now());
480 if (now >= next_suggest_time) {
481 Run();
482 return;
483 }
484 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29485}
486
[email protected]83c726482008-09-10 06:36:34487bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55488 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
489 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47490 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
491 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34492 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47493 ((!default_url || default_url->suggestions_url().empty()) &&
494 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34495 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
496 return false;
497
[email protected]cac59d32010-08-09 23:23:14498 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34499 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34500
[email protected]cac59d32010-08-09 23:23:14501 // FORCED_QUERY means the user is explicitly asking us to search for this, so
502 // we assume it isn't a URL and/or there isn't private data.
503 if (input_.type() == AutocompleteInput::FORCED_QUERY)
504 return true;
[email protected]83c726482008-09-10 06:36:34505
[email protected]cac59d32010-08-09 23:23:14506 // Next we check the scheme. If this is UNKNOWN/REQUESTED_URL/URL with a
507 // scheme that isn't http/https/ftp, we shouldn't send it. Sending things
508 // like file: and data: is both a waste of time and a disclosure of
509 // potentially private, local data. Other "schemes" may actually be
510 // usernames, and we don't want to send passwords. If the scheme is OK, we
511 // still need to check other cases below. If this is QUERY, then the presence
512 // of these schemes means the user explicitly typed one, and thus this is
513 // probably a URL that's being entered and happens to currently be invalid --
514 // in which case we again want to run our checks below. Other QUERY cases are
515 // less likely to be URLs and thus we assume we're OK.
[email protected]a2fedb1e2011-01-25 15:23:36516 if (!LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpScheme) &&
517 !LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
518 !LowerCaseEqualsASCII(input_.scheme(), chrome::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14519 return (input_.type() == AutocompleteInput::QUERY);
520
521 // Don't send URLs with usernames, queries or refs. Some of these are
522 // private, and the Suggest server is unlikely to have any useful results
523 // for any of them. Also don't send URLs with ports, as we may initially
524 // think that a username + password is a host + port (and we don't want to
525 // send usernames/passwords), and even if the port really is a port, the
526 // server is once again unlikely to have and useful results.
527 const url_parse::Parsed& parts = input_.parts();
528 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
529 parts.query.is_nonempty() || parts.ref.is_nonempty())
530 return false;
531
532 // Don't send anything for https except the hostname. Hostnames are OK
533 // because they are visible when the TCP connection is established, but the
534 // specific path may reveal private information.
[email protected]a2fedb1e2011-01-25 15:23:36535 if (LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
536 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14537 return false;
[email protected]83c726482008-09-10 06:36:34538
539 return true;
540}
541
initial.commit09911bf2008-07-26 23:55:29542void SearchProvider::StopSuggest() {
[email protected]7706a522012-08-16 17:42:25543 // Increment the appropriate field in the histogram by the number of
544 // pending requests that were invalidated.
545 for (int i = 0; i < suggest_results_pending_; i++)
546 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
[email protected]257ab712009-04-14 17:16:24547 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14548 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24549 // Stop any in-progress URL fetches.
550 keyword_fetcher_.reset();
551 default_fetcher_.reset();
[email protected]55ce8f12012-05-09 04:44:08552}
553
554void SearchProvider::ClearResults() {
[email protected]257ab712009-04-14 17:16:24555 keyword_suggest_results_.clear();
556 default_suggest_results_.clear();
557 keyword_navigation_results_.clear();
558 default_navigation_results_.clear();
[email protected]d1f0a7f2012-06-05 10:26:42559 has_suggested_relevance_ = false;
560 verbatim_relevance_ = -1;
initial.commit09911bf2008-07-26 23:55:29561 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29562}
563
[email protected]d1f0a7f2012-06-05 10:26:42564void SearchProvider::RemoveStaleResults() {
565 RemoveStaleSuggestResults(&keyword_suggest_results_, true);
566 RemoveStaleSuggestResults(&default_suggest_results_, false);
567 RemoveStaleNavigationResults(&keyword_navigation_results_, true);
568 RemoveStaleNavigationResults(&default_navigation_results_, false);
569}
570
571void SearchProvider::RemoveStaleSuggestResults(SuggestResults* list,
572 bool is_keyword) {
573 const string16& input = is_keyword ? keyword_input_text_ : input_.text();
574 for (SuggestResults::iterator i = list->begin(); i < list->end();)
575 i = StartsWith(i->suggestion(), input, false) ? (i + 1) : list->erase(i);
576}
577
578void SearchProvider::RemoveStaleNavigationResults(NavigationResults* list,
579 bool is_keyword) {
580 const string16& input = is_keyword ? keyword_input_text_ : input_.text();
581 for (NavigationResults::iterator i = list->begin(); i < list->end();) {
582 const string16 fill(AutocompleteInput::FormattedStringWithEquivalentMeaning(
583 i->url(), StringForURLDisplay(i->url(), true, false)));
584 i = URLPrefix::BestURLPrefix(fill, input) ? (i + 1) : list->erase(i);
585 }
586}
587
588void SearchProvider::ApplyCalculatedRelevance() {
589 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_, true);
590 ApplyCalculatedSuggestRelevance(&default_suggest_results_, false);
591 ApplyCalculatedNavigationRelevance(&keyword_navigation_results_, true);
592 ApplyCalculatedNavigationRelevance(&default_navigation_results_, false);
593 has_suggested_relevance_ = false;
594 verbatim_relevance_ = -1;
595}
596
597void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list,
598 bool is_keyword) {
599 for (size_t i = 0; i < list->size(); ++i) {
600 (*list)[i].set_relevance(CalculateRelevanceForSuggestion(is_keyword) +
601 (list->size() - i - 1));
602 }
603}
604
605void SearchProvider::ApplyCalculatedNavigationRelevance(NavigationResults* list,
606 bool is_keyword) {
607 for (size_t i = 0; i < list->size(); ++i) {
608 (*list)[i].set_relevance(CalculateRelevanceForNavigation(is_keyword) +
609 (list->size() - i - 1));
610 }
611}
612
[email protected]15fb2aa2012-05-22 22:52:59613net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12614 int id,
[email protected]9ff91722012-09-07 05:29:12615 const TemplateURL* template_url,
[email protected]7cc6e5632011-10-25 17:56:12616 const string16& text) {
[email protected]9ff91722012-09-07 05:29:12617 if (!template_url || template_url->suggestions_url().empty())
618 return NULL;
619
620 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]00790562012-12-14 09:57:16621 TemplateURLRef::SearchTermsArgs search_term_args(text);
622 search_term_args.cursor_position = input_.cursor_position();
[email protected]9ff91722012-09-07 05:29:12623 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:16624 search_term_args));
[email protected]9ff91722012-09-07 05:29:12625 if (!suggest_url.is_valid())
626 return NULL;
627
628 suggest_results_pending_++;
629 LogOmniboxSuggestRequest(REQUEST_SENT);
630
631 net::URLFetcher* fetcher =
632 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12633 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34634 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]257ab712009-04-14 17:16:24635 fetcher->Start();
636 return fetcher;
637}
638
[email protected]d7ad4772012-06-01 03:12:54639bool SearchProvider::ParseSuggestResults(Value* root_val, bool is_keyword) {
640 // TODO(pkasting): Fix |have_suggest_results_|; see http://crbug.com/130631
641 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29642
[email protected]d7ad4772012-06-01 03:12:54643 string16 query;
644 ListValue* root_list = NULL;
645 ListValue* results = NULL;
646 const string16& input_text = is_keyword ? keyword_input_text_ : input_.text();
647 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
648 (query != input_text) || !root_list->GetList(1, &results))
initial.commit09911bf2008-07-26 23:55:29649 return false;
650
[email protected]55ce8f12012-05-09 04:44:08651 // 3rd element: Description list.
[email protected]d7ad4772012-06-01 03:12:54652 ListValue* descriptions = NULL;
653 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:29654
[email protected]55ce8f12012-05-09 04:44:08655 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:29656
[email protected]d1f0a7f2012-06-05 10:26:42657 // Reset suggested relevance information from the default provider.
658 if (!is_keyword) {
659 has_suggested_relevance_ = false;
660 verbatim_relevance_ = -1;
661 }
662
[email protected]55ce8f12012-05-09 04:44:08663 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]d7ad4772012-06-01 03:12:54664 ListValue* types = NULL;
[email protected]d1f0a7f2012-06-05 10:26:42665 ListValue* relevances = NULL;
666 DictionaryValue* extras = NULL;
667 if (root_list->GetDictionary(4, &extras)) {
668 extras->GetList("google:suggesttype", &types);
669
670 // Only accept relevance suggestions if Instant is disabled.
[email protected]e41982a72012-11-20 07:16:51671 if (!is_keyword &&
672 !chrome::BrowserInstantController::IsInstantEnabled(profile_)) {
[email protected]d1f0a7f2012-06-05 10:26:42673 // Discard this list if its size does not match that of the suggestions.
674 if (extras->GetList("google:suggestrelevance", &relevances) &&
675 relevances->GetSize() != results->GetSize())
676 relevances = NULL;
677
678 extras->GetInteger("google:verbatimrelevance", &verbatim_relevance_);
679 }
initial.commit09911bf2008-07-26 23:55:29680 }
681
[email protected]d7ad4772012-06-01 03:12:54682 SuggestResults* suggest_results =
683 is_keyword ? &keyword_suggest_results_ : &default_suggest_results_;
684 NavigationResults* navigation_results =
685 is_keyword ? &keyword_navigation_results_ : &default_navigation_results_;
initial.commit09911bf2008-07-26 23:55:29686
[email protected]d1f0a7f2012-06-05 10:26:42687 // Clear the previous results now that new results are available.
688 suggest_results->clear();
689 navigation_results->clear();
690
691 string16 result, title;
692 std::string type;
693 int relevance = -1;
[email protected]d7ad4772012-06-01 03:12:54694 for (size_t index = 0; results->GetString(index, &result); ++index) {
[email protected]8e81f5092010-09-29 23:19:40695 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:08696 // they make no sense at all and can cause problems in our code.
[email protected]d7ad4772012-06-01 03:12:54697 if (result.empty())
[email protected]8e81f5092010-09-29 23:19:40698 continue;
699
[email protected]d1f0a7f2012-06-05 10:26:42700 // Apply valid suggested relevance scores; discard invalid lists.
701 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
702 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:54703 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:42704 // Do not blindly trust the URL coming from the server to be valid.
705 GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(result), std::string()));
706 if (url.is_valid()) {
707 if (descriptions != NULL)
708 descriptions->GetString(index, &title);
709 navigation_results->push_back(NavigationResult(url, title, relevance));
initial.commit09911bf2008-07-26 23:55:29710 }
711 } else {
[email protected]d1f0a7f2012-06-05 10:26:42712 // TODO(kochi): Improve calculator result presentation.
713 suggest_results->push_back(SuggestResult(result, relevance));
initial.commit09911bf2008-07-26 23:55:29714 }
715 }
716
[email protected]d1f0a7f2012-06-05 10:26:42717 // Apply calculated relevance scores if a valid list was not provided.
718 if (relevances == NULL) {
719 ApplyCalculatedSuggestRelevance(suggest_results, is_keyword);
720 ApplyCalculatedNavigationRelevance(navigation_results, is_keyword);
721 } else if (!is_keyword) {
722 has_suggested_relevance_ = true;
723 }
724
[email protected]d7ad4772012-06-01 03:12:54725 have_suggest_results_ = true;
[email protected]d1f0a7f2012-06-05 10:26:42726 return true;
initial.commit09911bf2008-07-26 23:55:29727}
728
729void SearchProvider::ConvertResultsToAutocompleteMatches() {
730 // Convert all the results to matches and add them to a map, so we can keep
731 // the most relevant match for each result.
732 MatchMap map;
[email protected]257ab712009-04-14 17:16:24733 const Time no_time;
734 int did_not_accept_keyword_suggestion = keyword_suggest_results_.empty() ?
initial.commit09911bf2008-07-26 23:55:29735 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
736 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]257ab712009-04-14 17:16:24737 // Keyword what you typed results are handled by the KeywordProvider.
initial.commit09911bf2008-07-26 23:55:29738
[email protected]382a0642012-06-06 06:13:52739 int verbatim_relevance = GetVerbatimRelevance();
[email protected]257ab712009-04-14 17:16:24740 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
[email protected]55ce8f12012-05-09 04:44:08741 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
742 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:42743 if (verbatim_relevance > 0) {
744 AddMatchToMap(input_.text(), input_.text(), verbatim_relevance,
745 AutocompleteMatch::SEARCH_WHAT_YOU_TYPED,
746 did_not_accept_default_suggestion, false, &map);
747 }
[email protected]b9ce8532012-05-24 20:51:15748 const size_t what_you_typed_size = map.size();
[email protected]93b73832012-10-18 20:18:38749 if (!default_provider_suggestion_.text.empty() &&
750 default_provider_suggestion_.type == INSTANT_SUGGESTION_SEARCH)
751 AddMatchToMap(input_.text() + default_provider_suggestion_.text,
[email protected]55ce8f12012-05-09 04:44:08752 input_.text(), verbatim_relevance + 1,
[email protected]85b8d6f2012-05-08 20:53:47753 AutocompleteMatch::SEARCH_SUGGEST,
[email protected]55ce8f12012-05-09 04:44:08754 did_not_accept_default_suggestion, false, &map);
initial.commit09911bf2008-07-26 23:55:29755
[email protected]257ab712009-04-14 17:16:24756 AddHistoryResultsToMap(keyword_history_results_, true,
757 did_not_accept_keyword_suggestion, &map);
758 AddHistoryResultsToMap(default_history_results_, false,
759 did_not_accept_default_suggestion, &map);
760
[email protected]55ce8f12012-05-09 04:44:08761 AddSuggestResultsToMap(keyword_suggest_results_, true, &map);
762 AddSuggestResultsToMap(default_suggest_results_, false, &map);
initial.commit09911bf2008-07-26 23:55:29763
764 // Now add the most relevant matches from the map to |matches_|.
765 matches_.clear();
766 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
767 matches_.push_back(i->second);
768
[email protected]93b73832012-10-18 20:18:38769 if (!default_provider_suggestion_.text.empty() &&
770 default_provider_suggestion_.type == INSTANT_SUGGESTION_URL)
771 matches_.push_back(NavigationToMatch(
772 NavigationResult(GURL(UTF16ToUTF8(default_provider_suggestion_.text)),
773 string16(),
774 verbatim_relevance + 1),
775 false));
[email protected]257ab712009-04-14 17:16:24776 AddNavigationResultsToMatches(keyword_navigation_results_, true);
777 AddNavigationResultsToMatches(default_navigation_results_, false);
initial.commit09911bf2008-07-26 23:55:29778
[email protected]b9ce8532012-05-24 20:51:15779 // Allow an additional match for "what you typed" if it's present.
780 const size_t max_total_matches = kMaxMatches + what_you_typed_size;
initial.commit09911bf2008-07-26 23:55:29781 std::partial_sort(matches_.begin(),
782 matches_.begin() + std::min(max_total_matches, matches_.size()),
783 matches_.end(), &AutocompleteMatch::MoreRelevant);
[email protected]3723e6e2012-06-11 21:06:56784
785 // If the top match is effectively 'verbatim' but exceeds the calculated
786 // verbatim relevance, and REQUESTED_URL |input_| has a |desired_tld|
787 // (for example ".com" when the CTRL key is pressed for REQUESTED_URL input),
788 // promote a URL_WHAT_YOU_TYPED match to the top. Otherwise, these matches can
789 // stomp the HistoryURLProvider's similar transient URL_WHAT_YOU_TYPED match,
790 // and CTRL+ENTER will invoke the search instead of the expected navigation.
791 if ((has_suggested_relevance_ || verbatim_relevance_ >= 0) &&
792 input_.type() == AutocompleteInput::REQUESTED_URL &&
793 !input_.desired_tld().empty() && !matches_.empty() &&
794 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
795 matches_.front().fill_into_edit == input_.text()) {
796 AutocompleteMatch match = HistoryURLProvider::SuggestExactInput(
797 this, input_, !HasHTTPScheme(input_.text()));
798 match.relevance = matches_.front().relevance + 1;
799 matches_.insert(matches_.begin(), match);
800 }
801
initial.commit09911bf2008-07-26 23:55:29802 if (matches_.size() > max_total_matches)
[email protected]a28e95662008-11-12 19:19:02803 matches_.erase(matches_.begin() + max_total_matches, matches_.end());
initial.commit09911bf2008-07-26 23:55:29804
[email protected]382a0642012-06-06 06:13:52805 // Check constraints that may be violated by suggested relevances.
[email protected]d1f0a7f2012-06-05 10:26:42806 if (!matches_.empty() &&
[email protected]e6acd002012-06-16 22:27:47807 (has_suggested_relevance_ || verbatim_relevance_ >= 0)) {
[email protected]382a0642012-06-06 06:13:52808 bool reconstruct_matches = false;
[email protected]1beee342012-06-19 22:22:28809 if (matches_.front().type != AutocompleteMatch::SEARCH_WHAT_YOU_TYPED &&
810 matches_.front().type != AutocompleteMatch::URL_WHAT_YOU_TYPED &&
811 matches_.front().inline_autocomplete_offset == string16::npos &&
812 matches_.front().fill_into_edit != input_.text()) {
813 // Disregard suggested relevances if the top match is not SWYT, inlinable,
814 // or URL_WHAT_YOU_TYPED (which may be top match regardless of inlining).
815 // For example, input "foo" should not invoke a search for "bar", which
816 // would happen if the "bar" search match outranked all other matches.
817 ApplyCalculatedRelevance();
818 reconstruct_matches = true;
819 } else if (matches_.front().relevance < CalculateRelevanceForVerbatim()) {
820 // Disregard the suggested verbatim relevance if the top score is below
821 // the usual verbatim value. For example, a BarProvider may rely on
822 // SearchProvider's verbatim or inlineable matches for input "foo" to
823 // always outrank its own lowly-ranked non-inlineable "bar" match.
824 verbatim_relevance_ = -1;
825 reconstruct_matches = true;
[email protected]e6acd002012-06-16 22:27:47826 }
827 if (input_.type() == AutocompleteInput::URL &&
828 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
829 (matches_.front().type == AutocompleteMatch::SEARCH_SUGGEST ||
830 matches_.front().type == AutocompleteMatch::SEARCH_WHAT_YOU_TYPED)) {
831 // Disregard the suggested search and verbatim relevances if the input
832 // type is URL and the top match is a highly-ranked search suggestion.
833 // For example, prevent a search for "foo.com" from outranking another
834 // provider's navigation for "foo.com" or "foo.com/url_from_history".
835 // Reconstruction will also ensure that the new top match is inlineable.
836 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_, true);
837 ApplyCalculatedSuggestRelevance(&default_suggest_results_, false);
[email protected]382a0642012-06-06 06:13:52838 verbatim_relevance_ = -1;
839 reconstruct_matches = true;
840 }
841 if (reconstruct_matches) {
842 ConvertResultsToAutocompleteMatches();
843 return;
844 }
[email protected]d1f0a7f2012-06-05 10:26:42845 }
846
[email protected]cc63dea2008-08-21 20:56:31847 UpdateStarredStateOfMatches();
[email protected]4ab4c7c2010-11-24 04:49:34848 UpdateDone();
[email protected]257ab712009-04-14 17:16:24849}
850
851void SearchProvider::AddNavigationResultsToMatches(
852 const NavigationResults& navigation_results,
853 bool is_keyword) {
854 if (!navigation_results.empty()) {
[email protected]6c535842012-05-15 05:20:55855 // TODO(kochi|msw): Add more navigational results if they get more
856 // meaningful relevance values; see http://b/1170574.
[email protected]d7ad4772012-06-01 03:12:54857 // CompareScoredResults sorts by descending relevance; so use min_element.
[email protected]6c535842012-05-15 05:20:55858 NavigationResults::const_iterator result(
[email protected]d7ad4772012-06-01 03:12:54859 std::min_element(navigation_results.begin(),
[email protected]6c535842012-05-15 05:20:55860 navigation_results.end(),
861 CompareScoredResults()));
862 matches_.push_back(NavigationToMatch(*result, is_keyword));
[email protected]257ab712009-04-14 17:16:24863 }
864}
865
866void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
867 bool is_keyword,
868 int did_not_accept_suggestion,
869 MatchMap* map) {
[email protected]51124552011-07-16 01:37:10870 if (results.empty())
871 return;
872
[email protected]d7ad4772012-06-01 03:12:54873 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
874 (input_.type() == AutocompleteInput::URL);
875 const string16& input_text = is_keyword ? keyword_input_text_ : input_.text();
[email protected]51124552011-07-16 01:37:10876 bool input_multiple_words = HasMultipleWords(input_text);
877
[email protected]55ce8f12012-05-09 04:44:08878 SuggestResults scored_results;
879 if (!prevent_inline_autocomplete && input_multiple_words) {
880 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
881 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:10882 // autocompleting a multi-word, multi-visit query, and the current input is
883 // still a prefix of it, then changing the autocompletion suddenly feels
884 // wrong. To detect this case, first score as if only one word has been
885 // typed, then check for a best result that is an autocompleted, multi-word
886 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:08887 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
888 false, input_text, is_keyword);
889 if ((scored_results[0].relevance() <
890 AutocompleteResult::kLowestDefaultScore) ||
891 !HasMultipleWords(scored_results[0].suggestion()))
892 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:10893 }
[email protected]55ce8f12012-05-09 04:44:08894 if (scored_results.empty())
895 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
896 input_multiple_words, input_text,
897 is_keyword);
898 for (SuggestResults::const_iterator i(scored_results.begin());
899 i != scored_results.end(); ++i) {
900 AddMatchToMap(i->suggestion(), input_text, i->relevance(),
[email protected]51124552011-07-16 01:37:10901 AutocompleteMatch::SEARCH_HISTORY, did_not_accept_suggestion,
[email protected]55ce8f12012-05-09 04:44:08902 is_keyword, map);
[email protected]51124552011-07-16 01:37:10903 }
904}
905
[email protected]55ce8f12012-05-09 04:44:08906SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:10907 const HistoryResults& results,
908 bool base_prevent_inline_autocomplete,
909 bool input_multiple_words,
910 const string16& input_text,
911 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:48912 AutocompleteClassifier* classifier =
913 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:08914 SuggestResults scored_results;
[email protected]257ab712009-04-14 17:16:24915 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
916 ++i) {
[email protected]51124552011-07-16 01:37:10917 // Don't autocomplete multi-word queries that have only been seen once
918 // unless the user has typed more than one word.
919 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
920 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
921
[email protected]ea3b9a502011-04-04 14:19:37922 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:10923 // when typed. For example, if the user searched for "google.com" and types
924 // "goog", don't autocomplete to the search term "google.com". Otherwise,
925 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:48926 // NOTE: We don't check this in the following cases:
927 // * When inline autocomplete is disabled, we won't be inline
928 // autocompleting this term, so we don't need to worry about confusion as
929 // much. This also prevents calling Classify() again from inside the
930 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:10931 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:48932 // * When the user has typed the whole term, the "what you typed" history
933 // match will outrank us for URL-like inputs anyway, so we need not do
934 // anything special.
[email protected]51124552011-07-16 01:37:10935 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:37936 AutocompleteMatch match;
[email protected]72874a8d2011-05-11 03:48:54937 classifier->Classify(i->term, string16(), false, false, &match, NULL);
[email protected]2905f742011-10-13 03:51:58938 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:46939 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:37940 }
[email protected]51124552011-07-16 01:37:10941
942 int relevance = CalculateRelevanceForHistory(i->time, is_keyword,
943 prevent_inline_autocomplete);
[email protected]55ce8f12012-05-09 04:44:08944 scored_results.push_back(SuggestResult(i->term, relevance));
[email protected]257ab712009-04-14 17:16:24945 }
[email protected]51124552011-07-16 01:37:10946
947 // History returns results sorted for us. However, we may have docked some
948 // results' scores, so things are no longer in order. Do a stable sort to get
949 // things back in order without otherwise disturbing results with equal
950 // scores, then force the scores to be unique, so that the order in which
951 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:08952 std::stable_sort(scored_results.begin(), scored_results.end(),
953 CompareScoredResults());
[email protected]51124552011-07-16 01:37:10954 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:08955 for (SuggestResults::iterator i(scored_results.begin());
956 i != scored_results.end(); ++i) {
957 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
958 i->set_relevance(last_relevance - 1);
959 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:10960 }
961
[email protected]55ce8f12012-05-09 04:44:08962 return scored_results;
[email protected]257ab712009-04-14 17:16:24963}
964
[email protected]55ce8f12012-05-09 04:44:08965void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
966 bool is_keyword,
967 MatchMap* map) {
[email protected]d7ad4772012-06-01 03:12:54968 const string16& input_text = is_keyword ? keyword_input_text_ : input_.text();
[email protected]55ce8f12012-05-09 04:44:08969 for (size_t i = 0; i < results.size(); ++i) {
[email protected]d7ad4772012-06-01 03:12:54970 AddMatchToMap(results[i].suggestion(), input_text, results[i].relevance(),
[email protected]55ce8f12012-05-09 04:44:08971 AutocompleteMatch::SEARCH_SUGGEST, i, is_keyword, map);
[email protected]257ab712009-04-14 17:16:24972 }
initial.commit09911bf2008-07-26 23:55:29973}
974
[email protected]382a0642012-06-06 06:13:52975int SearchProvider::GetVerbatimRelevance() const {
[email protected]dc6943b2012-06-19 06:39:56976 // Use the suggested verbatim relevance score if it is non-negative (valid),
977 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:28978 // and if it won't suppress verbatim, leaving no default provider matches.
979 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:56980 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:28981 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:56982 // Check for results on each verbatim calculation, as results from older
983 // queries (on previous input) may be trimmed for failing to inline new input.
984 if (verbatim_relevance_ >= 0 && !input_.prevent_inline_autocomplete() &&
[email protected]1beee342012-06-19 22:22:28985 (verbatim_relevance_ > 0 ||
986 !default_suggest_results_.empty() ||
[email protected]dc6943b2012-06-19 06:39:56987 !default_navigation_results_.empty())) {
[email protected]d1f0a7f2012-06-05 10:26:42988 return verbatim_relevance_;
[email protected]dc6943b2012-06-19 06:39:56989 }
[email protected]382a0642012-06-06 06:13:52990 return CalculateRelevanceForVerbatim();
991}
[email protected]d1f0a7f2012-06-05 10:26:42992
[email protected]382a0642012-06-06 06:13:52993int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:47994 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:36995 return 250;
996
initial.commit09911bf2008-07-26 23:55:29997 switch (input_.type()) {
998 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:36999 case AutocompleteInput::QUERY:
1000 case AutocompleteInput::FORCED_QUERY:
1001 return 1300;
initial.commit09911bf2008-07-26 23:55:291002
1003 case AutocompleteInput::REQUESTED_URL:
[email protected]52d08b12009-10-19 18:42:361004 return 1150;
initial.commit09911bf2008-07-26 23:55:291005
1006 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361007 return 850;
initial.commit09911bf2008-07-26 23:55:291008
1009 default:
1010 NOTREACHED();
1011 return 0;
1012 }
1013}
1014
[email protected]51124552011-07-16 01:37:101015int SearchProvider::CalculateRelevanceForHistory(
1016 const Time& time,
1017 bool is_keyword,
1018 bool prevent_inline_autocomplete) const {
[email protected]aa613d62010-11-09 20:40:181019 // The relevance of past searches falls off over time. There are two distinct
1020 // equations used. If the first equation is used (searches to the primary
[email protected]51124552011-07-16 01:37:101021 // provider that we want to inline autocomplete), the score starts at 1399 and
1022 // falls to 1300. If the second equation is used the relevance of a search 15
1023 // minutes ago is discounted 50 points, while the relevance of a search two
1024 // weeks ago is discounted 450 points.
[email protected]aa613d62010-11-09 20:40:181025 double elapsed_time = std::max((Time::Now() - time).InSecondsF(), 0.);
[email protected]51124552011-07-16 01:37:101026 bool is_primary_provider = providers_.is_primary_provider(is_keyword);
1027 if (is_primary_provider && !prevent_inline_autocomplete) {
[email protected]aa613d62010-11-09 20:40:181028 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101029 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181030 if (elapsed_time < autocomplete_time) {
[email protected]e17511f2011-07-13 14:09:181031 return (is_keyword ? 1599 : 1399) - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181032 std::pow(elapsed_time / autocomplete_time, 2.5));
1033 }
1034 elapsed_time -= autocomplete_time;
1035 }
1036
[email protected]c3a4bd992010-08-18 20:25:011037 const int score_discount =
1038 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291039
[email protected]6c85aa02009-02-27 12:08:091040 // Don't let scores go below 0. Negative relevance scores are meaningful in
1041 // a different way.
initial.commit09911bf2008-07-26 23:55:291042 int base_score;
[email protected]51124552011-07-16 01:37:101043 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361044 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101045 else
1046 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291047 return std::max(0, base_score - score_discount);
1048}
1049
[email protected]55ce8f12012-05-09 04:44:081050int SearchProvider::CalculateRelevanceForSuggestion(bool for_keyword) const {
1051 return !providers_.is_primary_provider(for_keyword) ? 100 :
1052 ((input_.type() == AutocompleteInput::URL) ? 300 : 600);
initial.commit09911bf2008-07-26 23:55:291053}
1054
[email protected]55ce8f12012-05-09 04:44:081055int SearchProvider::CalculateRelevanceForNavigation(bool for_keyword) const {
1056 return providers_.is_primary_provider(for_keyword) ? 800 : 150;
initial.commit09911bf2008-07-26 23:55:291057}
1058
[email protected]a2fedb1e2011-01-25 15:23:361059void SearchProvider::AddMatchToMap(const string16& query_string,
1060 const string16& input_text,
initial.commit09911bf2008-07-26 23:55:291061 int relevance,
[email protected]4c1fb7ec2008-11-13 00:19:001062 AutocompleteMatch::Type type,
initial.commit09911bf2008-07-26 23:55:291063 int accepted_suggestion,
[email protected]257ab712009-04-14 17:16:241064 bool is_keyword,
initial.commit09911bf2008-07-26 23:55:291065 MatchMap* map) {
[email protected]92513682011-09-01 06:16:521066 AutocompleteMatch match(this, relevance, false, type);
initial.commit09911bf2008-07-26 23:55:291067 std::vector<size_t> content_param_offsets;
[email protected]85b8d6f2012-05-08 20:53:471068 // Bail out now if we don't actually have a valid provider.
1069 match.keyword = is_keyword ?
[email protected]3954c3a2012-04-10 20:17:551070 providers_.keyword_provider() : providers_.default_provider();
[email protected]dbff446582012-10-30 00:20:261071 const TemplateURL* provider_url = match.GetTemplateURL(profile_, false);
[email protected]85b8d6f2012-05-08 20:53:471072 if (provider_url == NULL)
1073 return;
1074
[email protected]70833262011-01-05 23:40:441075 match.contents.assign(query_string);
[email protected]fb5153c52009-07-31 19:40:331076 // We do intra-string highlighting for suggestions - the suggested segment
1077 // will be highlighted, e.g. for input_text = "you" the suggestion may be
1078 // "youtube", so we'll bold the "tube" section: you*tube*.
1079 if (input_text != query_string) {
[email protected]fb5153c52009-07-31 19:40:331080 size_t input_position = match.contents.find(input_text);
[email protected]a2fedb1e2011-01-25 15:23:361081 if (input_position == string16::npos) {
[email protected]fb5153c52009-07-31 19:40:331082 // The input text is not a substring of the query string, e.g. input
1083 // text is "slasdot" and the query string is "slashdot", so we bold the
1084 // whole thing.
1085 match.contents_class.push_back(
1086 ACMatchClassification(0, ACMatchClassification::MATCH));
[email protected]ec2379162009-06-09 23:58:171087 } else {
[email protected]fb5153c52009-07-31 19:40:331088 // TODO(beng): ACMatchClassification::MATCH now seems to just mean
1089 // "bold" this. Consider modifying the terminology.
1090 // We don't iterate over the string here annotating all matches because
1091 // it looks odd to have every occurrence of a substring that may be as
1092 // short as a single character highlighted in a query suggestion result,
1093 // e.g. for input text "s" and query string "southwest airlines", it
1094 // looks odd if both the first and last s are highlighted.
1095 if (input_position != 0) {
1096 match.contents_class.push_back(
1097 ACMatchClassification(0, ACMatchClassification::NONE));
1098 }
1099 match.contents_class.push_back(
1100 ACMatchClassification(input_position, ACMatchClassification::DIM));
1101 size_t next_fragment_position = input_position + input_text.length();
1102 if (next_fragment_position < query_string.length()) {
1103 match.contents_class.push_back(
1104 ACMatchClassification(next_fragment_position,
1105 ACMatchClassification::NONE));
1106 }
[email protected]ec2379162009-06-09 23:58:171107 }
initial.commit09911bf2008-07-26 23:55:291108 } else {
[email protected]fb5153c52009-07-31 19:40:331109 // Otherwise, we're dealing with the "default search" result which has no
[email protected]70833262011-01-05 23:40:441110 // completion.
[email protected]fb5153c52009-07-31 19:40:331111 match.contents_class.push_back(
1112 ACMatchClassification(0, ACMatchClassification::NONE));
initial.commit09911bf2008-07-26 23:55:291113 }
1114
1115 // When the user forced a query, we need to make sure all the fill_into_edit
1116 // values preserve that property. Otherwise, if the user starts editing a
1117 // suggestion, non-Search results will suddenly appear.
[email protected]8f2249b2012-08-29 02:27:241118 if (input_.type() == AutocompleteInput::FORCED_QUERY)
[email protected]a2fedb1e2011-01-25 15:23:361119 match.fill_into_edit.assign(ASCIIToUTF16("?"));
[email protected]8f2249b2012-08-29 02:27:241120 if (is_keyword)
[email protected]033f3422012-03-13 21:24:181121 match.fill_into_edit.append(match.keyword + char16(' '));
[email protected]8f2249b2012-08-29 02:27:241122 if (!input_.prevent_inline_autocomplete() &&
1123 StartsWith(query_string, input_text, false)) {
1124 match.inline_autocomplete_offset =
1125 match.fill_into_edit.length() + input_text.length();
[email protected]c0048b42009-05-04 21:47:171126 }
initial.commit09911bf2008-07-26 23:55:291127 match.fill_into_edit.append(query_string);
initial.commit09911bf2008-07-26 23:55:291128
[email protected]85b8d6f2012-05-08 20:53:471129 const TemplateURLRef& search_url = provider_url->url_ref();
[email protected]360ba052012-04-04 17:26:131130 DCHECK(search_url.SupportsReplacement());
[email protected]bca359b2012-06-24 07:53:041131 match.search_terms_args.reset(
1132 new TemplateURLRef::SearchTermsArgs(query_string));
1133 match.search_terms_args->original_query = input_text;
1134 match.search_terms_args->accepted_suggestion = accepted_suggestion;
1135 // This is the destination URL sans assisted query stats. This must be set
1136 // so the AutocompleteController can properly de-dupe; the controller will
1137 // eventually overwrite it before it reaches the user.
1138 match.destination_url =
1139 GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get()));
initial.commit09911bf2008-07-26 23:55:291140
1141 // Search results don't look like URLs.
[email protected]2905f742011-10-13 03:51:581142 match.transition = is_keyword ?
1143 content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED;
initial.commit09911bf2008-07-26 23:55:291144
1145 // Try to add |match| to |map|. If a match for |query_string| is already in
1146 // |map|, replace it if |match| is more relevant.
1147 // NOTE: Keep this ToLower() call in sync with url_database.cc.
1148 const std::pair<MatchMap::iterator, bool> i = map->insert(
[email protected]a2fedb1e2011-01-25 15:23:361149 std::pair<string16, AutocompleteMatch>(
[email protected]503d03872011-05-06 08:36:261150 base::i18n::ToLower(query_string), match));
initial.commit09911bf2008-07-26 23:55:291151 // NOTE: We purposefully do a direct relevance comparison here instead of
1152 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items added
1153 // first" rather than "items alphabetically first" when the scores are equal.
1154 // The only case this matters is when a user has results with the same score
1155 // that differ only by capitalization; because the history system returns
1156 // results sorted by recency, this means we'll pick the most recent such
1157 // result even if the precision of our relevance score is too low to
1158 // distinguish the two.
1159 if (!i.second && (match.relevance > i.first->second.relevance))
1160 i.first->second = match;
1161}
1162
1163AutocompleteMatch SearchProvider::NavigationToMatch(
1164 const NavigationResult& navigation,
[email protected]257ab712009-04-14 17:16:241165 bool is_keyword) {
[email protected]371dab12012-06-01 03:23:551166 const string16& input = is_keyword ? keyword_input_text_ : input_.text();
[email protected]55ce8f12012-05-09 04:44:081167 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]4c1fb7ec2008-11-13 00:19:001168 AutocompleteMatch::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081169 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551170
1171 // First look for the user's input inside the fill_into_edit as it would be
1172 // without trimming the scheme, so we can find matches at the beginning of the
1173 // scheme.
1174 const string16 untrimmed_fill_into_edit(
1175 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1176 StringForURLDisplay(navigation.url(), true, false)));
1177 const URLPrefix* prefix =
1178 URLPrefix::BestURLPrefix(untrimmed_fill_into_edit, input);
1179 size_t match_start = (prefix == NULL) ?
1180 untrimmed_fill_into_edit.find(input) : prefix->prefix.length();
1181 size_t inline_autocomplete_offset = (prefix == NULL) ?
1182 string16::npos : (match_start + input.length());
1183 bool trim_http = !HasHTTPScheme(input) && (!prefix || (match_start != 0));
1184
1185 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1186 // Otherwise, user edits to a suggestion would show non-Search results.
1187 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
1188 match.fill_into_edit = ASCIIToUTF16("?");
1189 if (inline_autocomplete_offset != string16::npos)
1190 ++inline_autocomplete_offset;
1191 }
1192
1193 const std::string languages(
1194 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1195 const net::FormatUrlTypes format_types =
1196 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1197 match.fill_into_edit +=
1198 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1199 net::FormatUrl(navigation.url(), languages, format_types,
1200 net::UnescapeRule::SPACES, NULL, NULL,
1201 &inline_autocomplete_offset));
1202 if (!input_.prevent_inline_autocomplete())
1203 match.inline_autocomplete_offset = inline_autocomplete_offset;
1204 DCHECK((match.inline_autocomplete_offset == string16::npos) ||
1205 (match.inline_autocomplete_offset <= match.fill_into_edit.length()));
1206
1207 match.contents = net::FormatUrl(navigation.url(), languages,
1208 format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1209 // If the first match in the untrimmed string was inside a scheme that we
1210 // trimmed, look for a subsequent match.
1211 if (match_start == string16::npos)
1212 match_start = match.contents.find(input);
1213 // Safe if |match_start| is npos; also safe if the input is longer than the
1214 // remaining contents after |match_start|.
1215 AutocompleteMatch::ClassifyLocationInString(match_start, input.length(),
1216 match.contents.length(), ACMatchClassification::URL,
1217 &match.contents_class);
initial.commit09911bf2008-07-26 23:55:291218
[email protected]55ce8f12012-05-09 04:44:081219 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551220 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1221 ACMatchClassification::NONE, &match.description_class);
initial.commit09911bf2008-07-26 23:55:291222 return match;
1223}
[email protected]4ab4c7c2010-11-24 04:49:341224
1225void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331226 // We're done when the timer isn't running, there are no suggest queries
1227 // pending, and we're not waiting on instant.
1228 done_ = (!timer_.IsRunning() && (suggest_results_pending_ == 0) &&
[email protected]b67d0a42012-09-04 20:57:351229 (instant_finalized_ ||
[email protected]249a0352012-11-26 21:06:191230 (!chrome::BrowserInstantController::IsInstantEnabled(profile_) &&
1231 !chrome::search::IsInstantExtendedAPIEnabled(profile_))));
[email protected]4ab4c7c2010-11-24 04:49:341232}