blob: fa492adc5ccb5613d1ea2f5323a566d07673b397 [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]618d6e62012-12-16 05:55:5722#include "chrome/browser/autocomplete/autocomplete_field_trial.h"
[email protected]9ac40092010-10-27 23:05:2623#include "chrome/browser/autocomplete/autocomplete_match.h"
[email protected]5af9bc82012-06-29 00:53:4824#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
[email protected]73c2b1632012-07-02 22:51:3825#include "chrome/browser/autocomplete/autocomplete_result.h"
[email protected]3723e6e2012-06-11 21:06:5626#include "chrome/browser/autocomplete/history_url_provider.h"
[email protected]2c812ba02011-07-14 00:23:1527#include "chrome/browser/autocomplete/keyword_provider.h"
[email protected]371dab12012-06-01 03:23:5528#include "chrome/browser/autocomplete/url_prefix.h"
[email protected]ce560f82009-06-03 09:39:4429#include "chrome/browser/history/history.h"
[email protected]9d2db762012-06-19 00:01:1030#include "chrome/browser/history/history_service_factory.h"
[email protected]10c2d692012-05-11 05:32:2331#include "chrome/browser/history/in_memory_database.h"
[email protected]ab7780792013-01-10 01:26:0932#include "chrome/browser/metrics/variations/variations_http_header_provider.h"
[email protected]f870a322009-01-16 21:47:2733#include "chrome/browser/net/url_fixer_upper.h"
[email protected]37858e52010-08-26 00:22:0234#include "chrome/browser/prefs/pref_service.h"
[email protected]8ecad5e2010-12-02 21:18:3335#include "chrome/browser/profiles/profile.h"
[email protected]a0ad93ea2012-05-07 22:11:5336#include "chrome/browser/search_engines/search_engine_type.h"
[email protected]9899a612012-08-21 23:50:0437#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
[email protected]8e5c89a2011-06-07 18:13:3338#include "chrome/browser/search_engines/template_url_service.h"
39#include "chrome/browser/search_engines/template_url_service_factory.h"
[email protected]e41982a72012-11-20 07:16:5140#include "chrome/browser/ui/browser_instant_controller.h"
[email protected]5cd06c3e2012-09-20 03:25:2041#include "chrome/browser/ui/search/search.h"
initial.commit09911bf2008-07-26 23:55:2942#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0243#include "chrome/common/url_constants.h"
initial.commit09911bf2008-07-26 23:55:2944#include "googleurl/src/url_util.h"
[email protected]34ac8f32009-02-22 23:03:2745#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2946#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3447#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5548#include "net/base/net_util.h"
[email protected]bd3b4712012-12-18 17:01:3049#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2150#include "net/http/http_response_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5351#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2152#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1753#include "ui/base/l10n/l10n_util.h"
initial.commit09911bf2008-07-26 23:55:2954
[email protected]e1acf6f2008-10-27 20:43:3355using base::Time;
56using base::TimeDelta;
57
[email protected]51124552011-07-16 01:37:1058namespace {
59
[email protected]7706a522012-08-16 17:42:2560// We keep track in a histogram how many suggest requests we send, how
61// many suggest requests we invalidate (e.g., due to a user typing
62// another character), and how many replies we receive.
63// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
64// (excluding the end-of-list enum value)
65// We do not want values of existing enums to change or else it screws
66// up the statistics.
67enum SuggestRequestsHistogramValue {
68 REQUEST_SENT = 1,
69 REQUEST_INVALIDATED,
70 REPLY_RECEIVED,
71 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
72};
73
74// Increments the appropriate value in the histogram by one.
75void LogOmniboxSuggestRequest(
76 SuggestRequestsHistogramValue request_value) {
77 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
78 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
79}
80
[email protected]51124552011-07-16 01:37:1081bool HasMultipleWords(const string16& text) {
82 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
83 bool found_word = false;
84 if (i.Init()) {
85 while (i.Advance()) {
86 if (i.IsWord()) {
87 if (found_word)
88 return true;
89 found_word = true;
90 }
91 }
92 }
93 return false;
94}
95
[email protected]d1f0a7f2012-06-05 10:26:4296} // namespace
[email protected]51124552011-07-16 01:37:1097
[email protected]033f3422012-03-13 21:24:1898
[email protected]3954c3a2012-04-10 20:17:5599// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:58100
[email protected]85b8d6f2012-05-08 20:53:47101SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
102 : template_url_service_(template_url_service) {
103}
104
105const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
106 return default_provider_.empty() ? NULL :
107 template_url_service_->GetTemplateURLForKeyword(default_provider_);
108}
109
110const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
111 return keyword_provider_.empty() ? NULL :
112 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24113}
114
[email protected]3954c3a2012-04-10 20:17:55115
116// SearchProvider -------------------------------------------------------------
117
118// static
119const int SearchProvider::kDefaultProviderURLFetcherID = 1;
120// static
121const int SearchProvider::kKeywordProviderURLFetcherID = 2;
[email protected]3954c3a2012-04-10 20:17:55122
[email protected]30f5bc92012-06-26 04:14:55123SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
124 Profile* profile)
[email protected]35f1f4f02012-09-11 13:17:00125 : AutocompleteProvider(listener, profile,
126 AutocompleteProvider::TYPE_SEARCH),
[email protected]85b8d6f2012-05-08 20:53:47127 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
[email protected]601858c02010-09-01 17:08:20128 suggest_results_pending_(0),
[email protected]d1f0a7f2012-06-05 10:26:42129 has_suggested_relevance_(false),
130 verbatim_relevance_(-1),
[email protected]8e5cc282010-12-05 18:11:39131 have_suggest_results_(false),
[email protected]618d6e62012-12-16 05:55:57132 instant_finalized_(false),
133 field_trial_triggered_(false),
134 field_trial_triggered_in_session_(false) {
[email protected]4ab4c7c2010-11-24 04:49:34135}
136
[email protected]a2fedb1e2011-01-25 15:23:36137void SearchProvider::FinalizeInstantQuery(const string16& input_text,
[email protected]93b73832012-10-18 20:18:38138 const InstantSuggestion& suggestion) {
[email protected]4ab4c7c2010-11-24 04:49:34139 if (done_ || instant_finalized_)
140 return;
141
142 instant_finalized_ = true;
143 UpdateDone();
144
[email protected]e918c112010-12-08 23:03:49145 if (input_text.empty()) {
[email protected]4ab4c7c2010-11-24 04:49:34146 // We only need to update the listener if we're actually done.
147 if (done_)
148 listener_->OnProviderUpdate(false);
149 return;
150 }
151
[email protected]93b73832012-10-18 20:18:38152 default_provider_suggestion_ = suggestion;
[email protected]9e789742011-01-10 23:27:32153
[email protected]a2fedb1e2011-01-25 15:23:36154 string16 adjusted_input_text(input_text);
[email protected]e918c112010-12-08 23:03:49155 AutocompleteInput::RemoveForcedQueryStringIfNecessary(input_.type(),
156 &adjusted_input_text);
157
[email protected]93b73832012-10-18 20:18:38158 const string16 text = adjusted_input_text + suggestion.text;
[email protected]9acdcdc02012-05-21 20:58:36159 bool results_updated = false;
[email protected]4ab4c7c2010-11-24 04:49:34160 // Remove any matches that are identical to |text|. We don't use the
161 // destination_url for comparison as it varies depending upon the index passed
162 // to TemplateURL::ReplaceSearchTerms.
163 for (ACMatches::iterator i = matches_.begin(); i != matches_.end();) {
164 if (((i->type == AutocompleteMatch::SEARCH_HISTORY) ||
165 (i->type == AutocompleteMatch::SEARCH_SUGGEST)) &&
166 (i->fill_into_edit == text)) {
[email protected]e030de62010-11-24 05:41:19167 i = matches_.erase(i);
[email protected]9acdcdc02012-05-21 20:58:36168 results_updated = true;
[email protected]4ab4c7c2010-11-24 04:49:34169 } else {
170 ++i;
171 }
172 }
173
[email protected]55ce8f12012-05-09 04:44:08174 // Add the new instant suggest result. We give it a rank higher than
[email protected]4ab4c7c2010-11-24 04:49:34175 // SEARCH_WHAT_YOU_TYPED so that it gets autocompleted.
[email protected]93b73832012-10-18 20:18:38176 const int verbatim_relevance = GetVerbatimRelevance();
177 if (suggestion.type == INSTANT_SUGGESTION_SEARCH) {
178 // Instant has a query suggestion.
179 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
[email protected]4ab4c7c2010-11-24 04:49:34180 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
181 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]93b73832012-10-18 20:18:38182 MatchMap match_map;
183 AddMatchToMap(text, adjusted_input_text, verbatim_relevance + 1,
184 AutocompleteMatch::SEARCH_SUGGEST,
185 did_not_accept_default_suggestion, false, &match_map);
186 if (!match_map.empty()) {
187 matches_.push_back(match_map.begin()->second);
188 results_updated = true;
189 }
190 } else {
191 // Instant has an URL suggestion.
192 matches_.push_back(NavigationToMatch(
193 NavigationResult(GURL(UTF16ToUTF8(suggestion.text)),
194 string16(),
195 verbatim_relevance + 1),
196 false));
[email protected]9acdcdc02012-05-21 20:58:36197 results_updated = true;
198 }
[email protected]4ab4c7c2010-11-24 04:49:34199
[email protected]9acdcdc02012-05-21 20:58:36200 if (results_updated || done_)
201 listener_->OnProviderUpdate(results_updated);
[email protected]601858c02010-09-01 17:08:20202}
203
initial.commit09911bf2008-07-26 23:55:29204void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27205 bool minimal_changes) {
initial.commit09911bf2008-07-26 23:55:29206 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57207 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29208
[email protected]ea3b9a502011-04-04 14:19:37209 instant_finalized_ =
210 (input.matches_requested() != AutocompleteInput::ALL_MATCHES);
[email protected]4ab4c7c2010-11-24 04:49:34211
[email protected]6c85aa02009-02-27 12:08:09212 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29213 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]e29249dc52012-07-19 17:33:50214 Stop(false);
initial.commit09911bf2008-07-26 23:55:29215 return;
216 }
217
[email protected]257ab712009-04-14 17:16:24218 keyword_input_text_.clear();
219 const TemplateURL* keyword_provider =
220 KeywordProvider::GetSubstitutingTemplateURLForInput(profile_, input,
221 &keyword_input_text_);
[email protected]8d457132010-11-04 18:13:40222 if (keyword_input_text_.empty())
[email protected]257ab712009-04-14 17:16:24223 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24224
[email protected]85b8d6f2012-05-08 20:53:47225 TemplateURLService* model = providers_.template_url_service();
226 DCHECK(model);
227 model->Load();
228 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07229 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24230 default_provider = NULL;
231
232 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18233 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24234
235 if (!default_provider && !keyword_provider) {
236 // No valid providers.
[email protected]e29249dc52012-07-19 17:33:50237 Stop(false);
initial.commit09911bf2008-07-26 23:55:29238 return;
239 }
240
241 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24242 // or the providers, abort the query.
[email protected]85b8d6f2012-05-08 20:53:47243 string16 default_provider_keyword(default_provider ?
244 default_provider->keyword() : string16());
245 string16 keyword_provider_keyword(keyword_provider ?
246 keyword_provider->keyword() : string16());
[email protected]9e789742011-01-10 23:27:32247 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47248 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]9e789742011-01-10 23:27:32249 if (done_)
[email protected]93b73832012-10-18 20:18:38250 default_provider_suggestion_ = InstantSuggestion();
[email protected]9e789742011-01-10 23:27:32251 else
[email protected]e29249dc52012-07-19 17:33:50252 Stop(false);
[email protected]257ab712009-04-14 17:16:24253 }
initial.commit09911bf2008-07-26 23:55:29254
[email protected]85b8d6f2012-05-08 20:53:47255 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29256
257 if (input.text().empty()) {
258 // User typed "?" alone. Give them a placeholder result indicating what
259 // this syntax does.
[email protected]257ab712009-04-14 17:16:24260 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00261 AutocompleteMatch match;
262 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36263 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24264 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35265 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47266 match.keyword = providers_.default_provider();
[email protected]257ab712009-04-14 17:16:24267 matches_.push_back(match);
268 }
[email protected]e29249dc52012-07-19 17:33:50269 Stop(false);
initial.commit09911bf2008-07-26 23:55:29270 return;
271 }
272
273 input_ = input;
274
[email protected]5cd06c3e2012-09-20 03:25:20275 // Don't run the normal provider flow when the Instant Extended API is
276 // enabled. (When the Extended API is enabled, the embedded page will handle
277 // all search suggestions itself.)
278 // TODO(dcblack): once we are done refactoring the omnibox so we don't need to
279 // use FinalizeInstantQuery anymore, we can take out this check and remove
280 // this provider from kInstantExtendedOmniboxProviders.
281 if (!chrome::search::IsInstantExtendedAPIEnabled(profile_)) {
282 DoHistoryQuery(minimal_changes);
283 StartOrStopSuggestQuery(minimal_changes);
284 }
[email protected]344946a12012-12-20 12:03:42285 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29286}
287
[email protected]55ce8f12012-05-09 04:44:08288SearchProvider::Result::Result(int relevance) : relevance_(relevance) {}
289SearchProvider::Result::~Result() {}
290
291SearchProvider::SuggestResult::SuggestResult(const string16& suggestion,
292 int relevance)
293 : Result(relevance),
294 suggestion_(suggestion) {
295}
296
297SearchProvider::SuggestResult::~SuggestResult() {}
298
299SearchProvider::NavigationResult::NavigationResult(const GURL& url,
300 const string16& description,
301 int relevance)
302 : Result(relevance),
303 url_(url),
304 description_(description) {
305 DCHECK(url_.is_valid());
306}
307
308SearchProvider::NavigationResult::~NavigationResult() {}
309
310class SearchProvider::CompareScoredResults {
[email protected]51124552011-07-16 01:37:10311 public:
[email protected]55ce8f12012-05-09 04:44:08312 bool operator()(const Result& a, const Result& b) {
[email protected]51124552011-07-16 01:37:10313 // Sort in descending relevance order.
[email protected]55ce8f12012-05-09 04:44:08314 return a.relevance() > b.relevance();
[email protected]51124552011-07-16 01:37:10315 }
316};
317
initial.commit09911bf2008-07-26 23:55:29318void SearchProvider::Run() {
319 // Start a new request with the current input.
[email protected]257ab712009-04-14 17:16:24320 suggest_results_pending_ = 0;
[email protected]a0ad93ea2012-05-07 22:11:53321 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]9ff91722012-09-07 05:29:12322
323 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
324 providers_.GetDefaultProviderURL(), input_.text()));
325 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
326 providers_.GetKeywordProviderURL(), keyword_input_text_));
[email protected]85b8d6f2012-05-08 20:53:47327
328 // Both the above can fail if the providers have been modified or deleted
329 // since the query began.
330 if (suggest_results_pending_ == 0) {
331 UpdateDone();
332 // We only need to update the listener if we're actually done.
333 if (done_)
334 listener_->OnProviderUpdate(false);
335 }
initial.commit09911bf2008-07-26 23:55:29336}
337
[email protected]e29249dc52012-07-19 17:33:50338void SearchProvider::Stop(bool clear_cached_results) {
initial.commit09911bf2008-07-26 23:55:29339 StopSuggest();
340 done_ = true;
[email protected]93b73832012-10-18 20:18:38341 default_provider_suggestion_ = InstantSuggestion();
[email protected]e29249dc52012-07-19 17:33:50342
343 if (clear_cached_results)
344 ClearResults();
initial.commit09911bf2008-07-26 23:55:29345}
346
[email protected]0e9e8782012-05-15 23:01:51347void SearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
348 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
349 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
350 new_entry.set_provider(AsOmniboxEventProviderType());
351 new_entry.set_provider_done(done_);
[email protected]618d6e62012-12-16 05:55:57352 uint32 field_trial_hash = 0;
353 if (AutocompleteFieldTrial::GetActiveSuggestFieldTrialHash(
[email protected]d78d7362012-12-19 18:43:28354 &field_trial_hash)) {
[email protected]618d6e62012-12-16 05:55:57355 if (field_trial_triggered_)
356 new_entry.mutable_field_trial_triggered()->Add(field_trial_hash);
[email protected]d78d7362012-12-19 18:43:28357 if (field_trial_triggered_in_session_) {
[email protected]618d6e62012-12-16 05:55:57358 new_entry.mutable_field_trial_triggered_in_session()->Add(
359 field_trial_hash);
[email protected]d78d7362012-12-19 18:43:28360 }
[email protected]618d6e62012-12-16 05:55:57361 }
362}
363
364void SearchProvider::ResetSession() {
365 field_trial_triggered_in_session_ = false;
[email protected]0e9e8782012-05-15 23:01:51366}
367
[email protected]10c2d692012-05-11 05:32:23368void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29369 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24370 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25371 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15372 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06373 const net::HttpResponseHeaders* const response_headers =
[email protected]7cc6e5632011-10-25 17:56:12374 source->GetResponseHeaders();
[email protected]c530c852011-10-24 18:18:34375 std::string json_data;
376 source->GetResponseAsString(&json_data);
[email protected]6c85aa02009-02-27 12:08:09377 // JSON is supposed to be UTF-8, but some suggest service providers send JSON
378 // files in non-UTF-8 encodings. The actual encoding is usually specified in
379 // the Content-Type header field.
[email protected]ec9207d32008-09-26 00:51:06380 if (response_headers) {
381 std::string charset;
382 if (response_headers->GetCharset(&charset)) {
[email protected]a2fedb1e2011-01-25 15:23:36383 string16 data_16;
[email protected]ec9207d32008-09-26 00:51:06384 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
[email protected]c530c852011-10-24 18:18:34385 if (base::CodepageToUTF16(json_data, charset.c_str(),
[email protected]a2fedb1e2011-01-25 15:23:36386 base::OnStringConversionError::FAIL,
387 &data_16))
388 json_data = UTF16ToUTF8(data_16);
[email protected]ec9207d32008-09-26 00:51:06389 }
390 }
391
[email protected]d7ad4772012-06-01 03:12:54392 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]013e9a02012-05-18 20:27:10393 const bool request_succeeded =
394 source->GetStatus().is_success() && source->GetResponseCode() == 200;
[email protected]a0ad93ea2012-05-07 22:11:53395
396 // Record response time for suggest requests sent to Google. We care
397 // only about the common case: the Google default provider used in
398 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47399 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08400 if (!is_keyword && default_url &&
[email protected]9899a612012-08-21 23:50:04401 (TemplateURLPrepopulateData::GetEngineType(default_url->url()) ==
402 SEARCH_ENGINE_GOOGLE)) {
[email protected]6dc950f2012-07-16 19:49:08403 const TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10404 base::TimeTicks::Now() - time_suggest_request_sent_;
405 if (request_succeeded) {
406 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
407 elapsed_time);
408 } else {
409 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
410 elapsed_time);
411 }
[email protected]b4cebf82008-12-29 19:59:08412 }
413
[email protected]d7ad4772012-06-01 03:12:54414 bool results_updated = false;
415 if (request_succeeded) {
416 JSONStringValueSerializer deserializer(json_data);
417 deserializer.set_allow_trailing_comma(true);
418 scoped_ptr<Value> data(deserializer.Deserialize(NULL, NULL));
419 results_updated = data.get() && ParseSuggestResults(data.get(), is_keyword);
420 }
421
[email protected]344946a12012-12-20 12:03:42422 UpdateMatches();
[email protected]d7ad4772012-06-01 03:12:54423 if (done_ || results_updated)
424 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29425}
426
[email protected]601858c02010-09-01 17:08:20427SearchProvider::~SearchProvider() {
428}
429
[email protected]8d457132010-11-04 18:13:40430void SearchProvider::DoHistoryQuery(bool minimal_changes) {
431 // The history query results are synchronous, so if minimal_changes is true,
432 // we still have the last results and don't need to do anything.
433 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29434 return;
435
[email protected]8d457132010-11-04 18:13:40436 keyword_history_results_.clear();
437 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29438
[email protected]8d457132010-11-04 18:13:40439 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10440 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]8d457132010-11-04 18:13:40441 history::URLDatabase* url_db = history_service ?
442 history_service->InMemoryDatabase() : NULL;
443 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29444 return;
445
[email protected]51124552011-07-16 01:37:10446 // Request history for both the keyword and default provider. We grab many
447 // more matches than we'll ultimately clamp to so that if there are several
448 // recent multi-word matches who scores are lowered (see
449 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
450 // matches. Note that this doesn't fix the problem entirely, but merely
451 // limits it to cases with a very large number of such multi-word matches; for
452 // now, this seems OK compared with the complexity of a real fix, which would
453 // require multiple searches and tracking of "single- vs. multi-word" in the
454 // database.
455 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47456 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
457 if (default_url) {
458 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
459 num_matches, &default_history_results_);
[email protected]257ab712009-04-14 17:16:24460 }
[email protected]85b8d6f2012-05-08 20:53:47461 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
462 if (keyword_url) {
463 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]3954c3a2012-04-10 20:17:55464 keyword_input_text_, num_matches, &keyword_history_results_);
465 }
initial.commit09911bf2008-07-26 23:55:29466}
467
[email protected]6dc950f2012-07-16 19:49:08468void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34469 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29470 StopSuggest();
[email protected]55ce8f12012-05-09 04:44:08471 ClearResults();
initial.commit09911bf2008-07-26 23:55:29472 return;
473 }
474
475 // For the minimal_changes case, if we finished the previous query and still
476 // have its results, or are allowed to keep running it, just do that, rather
477 // than starting a new query.
478 if (minimal_changes &&
[email protected]ea3b9a502011-04-04 14:19:37479 (have_suggest_results_ ||
480 (!done_ &&
481 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29482 return;
483
484 // We can't keep running any previous query, so halt it.
485 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42486
487 // Remove existing results that cannot inline autocomplete the new input.
488 RemoveStaleResults();
initial.commit09911bf2008-07-26 23:55:29489
490 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37491 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29492 return;
493
[email protected]515ffa942012-11-27 20:18:24494 // To avoid flooding the suggest server, don't send a query until at least 100
495 // ms since the last query.
496 const int kMinimumTimeBetweenSuggestQueriesMs = 100;
497 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
498 TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
499 base::TimeTicks now(base::TimeTicks::Now());
500 if (now >= next_suggest_time) {
501 Run();
502 return;
503 }
504 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29505}
506
[email protected]83c726482008-09-10 06:36:34507bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55508 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
509 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47510 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
511 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34512 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47513 ((!default_url || default_url->suggestions_url().empty()) &&
514 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34515 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
516 return false;
517
[email protected]cac59d32010-08-09 23:23:14518 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34519 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34520
[email protected]cac59d32010-08-09 23:23:14521 // FORCED_QUERY means the user is explicitly asking us to search for this, so
522 // we assume it isn't a URL and/or there isn't private data.
523 if (input_.type() == AutocompleteInput::FORCED_QUERY)
524 return true;
[email protected]83c726482008-09-10 06:36:34525
[email protected]cac59d32010-08-09 23:23:14526 // Next we check the scheme. If this is UNKNOWN/REQUESTED_URL/URL with a
527 // scheme that isn't http/https/ftp, we shouldn't send it. Sending things
528 // like file: and data: is both a waste of time and a disclosure of
529 // potentially private, local data. Other "schemes" may actually be
530 // usernames, and we don't want to send passwords. If the scheme is OK, we
531 // still need to check other cases below. If this is QUERY, then the presence
532 // of these schemes means the user explicitly typed one, and thus this is
533 // probably a URL that's being entered and happens to currently be invalid --
534 // in which case we again want to run our checks below. Other QUERY cases are
535 // less likely to be URLs and thus we assume we're OK.
[email protected]a2fedb1e2011-01-25 15:23:36536 if (!LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpScheme) &&
537 !LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
538 !LowerCaseEqualsASCII(input_.scheme(), chrome::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14539 return (input_.type() == AutocompleteInput::QUERY);
540
541 // Don't send URLs with usernames, queries or refs. Some of these are
542 // private, and the Suggest server is unlikely to have any useful results
543 // for any of them. Also don't send URLs with ports, as we may initially
544 // think that a username + password is a host + port (and we don't want to
545 // send usernames/passwords), and even if the port really is a port, the
546 // server is once again unlikely to have and useful results.
547 const url_parse::Parsed& parts = input_.parts();
548 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
549 parts.query.is_nonempty() || parts.ref.is_nonempty())
550 return false;
551
552 // Don't send anything for https except the hostname. Hostnames are OK
553 // because they are visible when the TCP connection is established, but the
554 // specific path may reveal private information.
[email protected]a2fedb1e2011-01-25 15:23:36555 if (LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
556 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14557 return false;
[email protected]83c726482008-09-10 06:36:34558
559 return true;
560}
561
initial.commit09911bf2008-07-26 23:55:29562void SearchProvider::StopSuggest() {
[email protected]7706a522012-08-16 17:42:25563 // Increment the appropriate field in the histogram by the number of
564 // pending requests that were invalidated.
565 for (int i = 0; i < suggest_results_pending_; i++)
566 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
[email protected]257ab712009-04-14 17:16:24567 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14568 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24569 // Stop any in-progress URL fetches.
570 keyword_fetcher_.reset();
571 default_fetcher_.reset();
[email protected]55ce8f12012-05-09 04:44:08572}
573
574void SearchProvider::ClearResults() {
[email protected]257ab712009-04-14 17:16:24575 keyword_suggest_results_.clear();
576 default_suggest_results_.clear();
577 keyword_navigation_results_.clear();
578 default_navigation_results_.clear();
[email protected]d1f0a7f2012-06-05 10:26:42579 has_suggested_relevance_ = false;
580 verbatim_relevance_ = -1;
initial.commit09911bf2008-07-26 23:55:29581 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29582}
583
[email protected]d1f0a7f2012-06-05 10:26:42584void SearchProvider::RemoveStaleResults() {
585 RemoveStaleSuggestResults(&keyword_suggest_results_, true);
586 RemoveStaleSuggestResults(&default_suggest_results_, false);
587 RemoveStaleNavigationResults(&keyword_navigation_results_, true);
588 RemoveStaleNavigationResults(&default_navigation_results_, false);
589}
590
591void SearchProvider::RemoveStaleSuggestResults(SuggestResults* list,
592 bool is_keyword) {
593 const string16& input = is_keyword ? keyword_input_text_ : input_.text();
594 for (SuggestResults::iterator i = list->begin(); i < list->end();)
595 i = StartsWith(i->suggestion(), input, false) ? (i + 1) : list->erase(i);
596}
597
598void SearchProvider::RemoveStaleNavigationResults(NavigationResults* list,
599 bool is_keyword) {
600 const string16& input = is_keyword ? keyword_input_text_ : input_.text();
601 for (NavigationResults::iterator i = list->begin(); i < list->end();) {
602 const string16 fill(AutocompleteInput::FormattedStringWithEquivalentMeaning(
603 i->url(), StringForURLDisplay(i->url(), true, false)));
604 i = URLPrefix::BestURLPrefix(fill, input) ? (i + 1) : list->erase(i);
605 }
606}
607
608void SearchProvider::ApplyCalculatedRelevance() {
609 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_, true);
610 ApplyCalculatedSuggestRelevance(&default_suggest_results_, false);
611 ApplyCalculatedNavigationRelevance(&keyword_navigation_results_, true);
612 ApplyCalculatedNavigationRelevance(&default_navigation_results_, false);
613 has_suggested_relevance_ = false;
614 verbatim_relevance_ = -1;
615}
616
617void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list,
618 bool is_keyword) {
619 for (size_t i = 0; i < list->size(); ++i) {
620 (*list)[i].set_relevance(CalculateRelevanceForSuggestion(is_keyword) +
621 (list->size() - i - 1));
622 }
623}
624
625void SearchProvider::ApplyCalculatedNavigationRelevance(NavigationResults* list,
626 bool is_keyword) {
627 for (size_t i = 0; i < list->size(); ++i) {
628 (*list)[i].set_relevance(CalculateRelevanceForNavigation(is_keyword) +
629 (list->size() - i - 1));
630 }
631}
632
[email protected]15fb2aa2012-05-22 22:52:59633net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12634 int id,
[email protected]9ff91722012-09-07 05:29:12635 const TemplateURL* template_url,
[email protected]7cc6e5632011-10-25 17:56:12636 const string16& text) {
[email protected]9ff91722012-09-07 05:29:12637 if (!template_url || template_url->suggestions_url().empty())
638 return NULL;
639
640 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]00790562012-12-14 09:57:16641 TemplateURLRef::SearchTermsArgs search_term_args(text);
642 search_term_args.cursor_position = input_.cursor_position();
[email protected]9ff91722012-09-07 05:29:12643 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:16644 search_term_args));
[email protected]9ff91722012-09-07 05:29:12645 if (!suggest_url.is_valid())
646 return NULL;
647
648 suggest_results_pending_++;
649 LogOmniboxSuggestRequest(REQUEST_SENT);
650
651 net::URLFetcher* fetcher =
652 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12653 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34654 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30655 // Add Chrome experiment state to the request headers.
656 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:09657 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30658 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
659 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24660 fetcher->Start();
661 return fetcher;
662}
663
[email protected]d7ad4772012-06-01 03:12:54664bool SearchProvider::ParseSuggestResults(Value* root_val, bool is_keyword) {
665 // TODO(pkasting): Fix |have_suggest_results_|; see http://crbug.com/130631
666 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29667
[email protected]d7ad4772012-06-01 03:12:54668 string16 query;
669 ListValue* root_list = NULL;
670 ListValue* results = NULL;
671 const string16& input_text = is_keyword ? keyword_input_text_ : input_.text();
672 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
673 (query != input_text) || !root_list->GetList(1, &results))
initial.commit09911bf2008-07-26 23:55:29674 return false;
675
[email protected]55ce8f12012-05-09 04:44:08676 // 3rd element: Description list.
[email protected]d7ad4772012-06-01 03:12:54677 ListValue* descriptions = NULL;
678 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:29679
[email protected]55ce8f12012-05-09 04:44:08680 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:29681
[email protected]d1f0a7f2012-06-05 10:26:42682 // Reset suggested relevance information from the default provider.
683 if (!is_keyword) {
684 has_suggested_relevance_ = false;
685 verbatim_relevance_ = -1;
686 }
687
[email protected]55ce8f12012-05-09 04:44:08688 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]d7ad4772012-06-01 03:12:54689 ListValue* types = NULL;
[email protected]d1f0a7f2012-06-05 10:26:42690 ListValue* relevances = NULL;
691 DictionaryValue* extras = NULL;
692 if (root_list->GetDictionary(4, &extras)) {
693 extras->GetList("google:suggesttype", &types);
694
695 // Only accept relevance suggestions if Instant is disabled.
[email protected]e41982a72012-11-20 07:16:51696 if (!is_keyword &&
697 !chrome::BrowserInstantController::IsInstantEnabled(profile_)) {
[email protected]d1f0a7f2012-06-05 10:26:42698 // Discard this list if its size does not match that of the suggestions.
699 if (extras->GetList("google:suggestrelevance", &relevances) &&
700 relevances->GetSize() != results->GetSize())
701 relevances = NULL;
702
703 extras->GetInteger("google:verbatimrelevance", &verbatim_relevance_);
704 }
[email protected]618d6e62012-12-16 05:55:57705
706 // Check if the active suggest field trial (if any) has triggered either
707 // for the default provider or keyword provider.
708 bool triggered = false;
709 extras->GetBoolean("google:fieldtrialtriggered", &triggered);
710 field_trial_triggered_ |= triggered;
711 field_trial_triggered_in_session_ |= triggered;
initial.commit09911bf2008-07-26 23:55:29712 }
713
[email protected]d7ad4772012-06-01 03:12:54714 SuggestResults* suggest_results =
715 is_keyword ? &keyword_suggest_results_ : &default_suggest_results_;
716 NavigationResults* navigation_results =
717 is_keyword ? &keyword_navigation_results_ : &default_navigation_results_;
initial.commit09911bf2008-07-26 23:55:29718
[email protected]d1f0a7f2012-06-05 10:26:42719 // Clear the previous results now that new results are available.
720 suggest_results->clear();
721 navigation_results->clear();
722
723 string16 result, title;
724 std::string type;
725 int relevance = -1;
[email protected]d7ad4772012-06-01 03:12:54726 for (size_t index = 0; results->GetString(index, &result); ++index) {
[email protected]8e81f5092010-09-29 23:19:40727 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:08728 // they make no sense at all and can cause problems in our code.
[email protected]d7ad4772012-06-01 03:12:54729 if (result.empty())
[email protected]8e81f5092010-09-29 23:19:40730 continue;
731
[email protected]d1f0a7f2012-06-05 10:26:42732 // Apply valid suggested relevance scores; discard invalid lists.
733 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
734 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:54735 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:42736 // Do not blindly trust the URL coming from the server to be valid.
737 GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(result), std::string()));
738 if (url.is_valid()) {
739 if (descriptions != NULL)
740 descriptions->GetString(index, &title);
741 navigation_results->push_back(NavigationResult(url, title, relevance));
initial.commit09911bf2008-07-26 23:55:29742 }
743 } else {
[email protected]d1f0a7f2012-06-05 10:26:42744 // TODO(kochi): Improve calculator result presentation.
745 suggest_results->push_back(SuggestResult(result, relevance));
initial.commit09911bf2008-07-26 23:55:29746 }
747 }
748
[email protected]d1f0a7f2012-06-05 10:26:42749 // Apply calculated relevance scores if a valid list was not provided.
750 if (relevances == NULL) {
751 ApplyCalculatedSuggestRelevance(suggest_results, is_keyword);
752 ApplyCalculatedNavigationRelevance(navigation_results, is_keyword);
753 } else if (!is_keyword) {
754 has_suggested_relevance_ = true;
755 }
756
[email protected]d7ad4772012-06-01 03:12:54757 have_suggest_results_ = true;
[email protected]d1f0a7f2012-06-05 10:26:42758 return true;
initial.commit09911bf2008-07-26 23:55:29759}
760
[email protected]344946a12012-12-20 12:03:42761void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29762 // Convert all the results to matches and add them to a map, so we can keep
763 // the most relevant match for each result.
764 MatchMap map;
[email protected]257ab712009-04-14 17:16:24765 const Time no_time;
766 int did_not_accept_keyword_suggestion = keyword_suggest_results_.empty() ?
initial.commit09911bf2008-07-26 23:55:29767 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
768 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]257ab712009-04-14 17:16:24769 // Keyword what you typed results are handled by the KeywordProvider.
initial.commit09911bf2008-07-26 23:55:29770
[email protected]382a0642012-06-06 06:13:52771 int verbatim_relevance = GetVerbatimRelevance();
[email protected]257ab712009-04-14 17:16:24772 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
[email protected]55ce8f12012-05-09 04:44:08773 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
774 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:42775 if (verbatim_relevance > 0) {
776 AddMatchToMap(input_.text(), input_.text(), verbatim_relevance,
777 AutocompleteMatch::SEARCH_WHAT_YOU_TYPED,
778 did_not_accept_default_suggestion, false, &map);
779 }
[email protected]b9ce8532012-05-24 20:51:15780 const size_t what_you_typed_size = map.size();
[email protected]93b73832012-10-18 20:18:38781 if (!default_provider_suggestion_.text.empty() &&
[email protected]2ac15ba2013-01-14 22:38:59782 default_provider_suggestion_.type == INSTANT_SUGGESTION_SEARCH &&
783 !input_.prevent_inline_autocomplete())
[email protected]93b73832012-10-18 20:18:38784 AddMatchToMap(input_.text() + default_provider_suggestion_.text,
[email protected]55ce8f12012-05-09 04:44:08785 input_.text(), verbatim_relevance + 1,
[email protected]85b8d6f2012-05-08 20:53:47786 AutocompleteMatch::SEARCH_SUGGEST,
[email protected]55ce8f12012-05-09 04:44:08787 did_not_accept_default_suggestion, false, &map);
initial.commit09911bf2008-07-26 23:55:29788
[email protected]257ab712009-04-14 17:16:24789 AddHistoryResultsToMap(keyword_history_results_, true,
790 did_not_accept_keyword_suggestion, &map);
791 AddHistoryResultsToMap(default_history_results_, false,
792 did_not_accept_default_suggestion, &map);
793
[email protected]55ce8f12012-05-09 04:44:08794 AddSuggestResultsToMap(keyword_suggest_results_, true, &map);
795 AddSuggestResultsToMap(default_suggest_results_, false, &map);
initial.commit09911bf2008-07-26 23:55:29796
797 // Now add the most relevant matches from the map to |matches_|.
798 matches_.clear();
799 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
800 matches_.push_back(i->second);
801
[email protected]93b73832012-10-18 20:18:38802 if (!default_provider_suggestion_.text.empty() &&
[email protected]2ac15ba2013-01-14 22:38:59803 default_provider_suggestion_.type == INSTANT_SUGGESTION_URL &&
804 !input_.prevent_inline_autocomplete())
[email protected]93b73832012-10-18 20:18:38805 matches_.push_back(NavigationToMatch(
806 NavigationResult(GURL(UTF16ToUTF8(default_provider_suggestion_.text)),
807 string16(),
808 verbatim_relevance + 1),
809 false));
[email protected]257ab712009-04-14 17:16:24810 AddNavigationResultsToMatches(keyword_navigation_results_, true);
811 AddNavigationResultsToMatches(default_navigation_results_, false);
initial.commit09911bf2008-07-26 23:55:29812
[email protected]b9ce8532012-05-24 20:51:15813 // Allow an additional match for "what you typed" if it's present.
814 const size_t max_total_matches = kMaxMatches + what_you_typed_size;
initial.commit09911bf2008-07-26 23:55:29815 std::partial_sort(matches_.begin(),
816 matches_.begin() + std::min(max_total_matches, matches_.size()),
817 matches_.end(), &AutocompleteMatch::MoreRelevant);
[email protected]3723e6e2012-06-11 21:06:56818
819 // If the top match is effectively 'verbatim' but exceeds the calculated
820 // verbatim relevance, and REQUESTED_URL |input_| has a |desired_tld|
821 // (for example ".com" when the CTRL key is pressed for REQUESTED_URL input),
822 // promote a URL_WHAT_YOU_TYPED match to the top. Otherwise, these matches can
823 // stomp the HistoryURLProvider's similar transient URL_WHAT_YOU_TYPED match,
824 // and CTRL+ENTER will invoke the search instead of the expected navigation.
825 if ((has_suggested_relevance_ || verbatim_relevance_ >= 0) &&
826 input_.type() == AutocompleteInput::REQUESTED_URL &&
827 !input_.desired_tld().empty() && !matches_.empty() &&
828 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
829 matches_.front().fill_into_edit == input_.text()) {
830 AutocompleteMatch match = HistoryURLProvider::SuggestExactInput(
831 this, input_, !HasHTTPScheme(input_.text()));
832 match.relevance = matches_.front().relevance + 1;
833 matches_.insert(matches_.begin(), match);
834 }
835
initial.commit09911bf2008-07-26 23:55:29836 if (matches_.size() > max_total_matches)
[email protected]344946a12012-12-20 12:03:42837 matches_.resize(max_total_matches);
838}
839
840bool SearchProvider::IsTopMatchScoreTooLow() const {
841 return matches_.front().relevance < CalculateRelevanceForVerbatim();
842}
843
844bool SearchProvider::IsTopMatchHighRankSearchForURL() const {
845 return input_.type() == AutocompleteInput::URL &&
846 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
847 (matches_.front().type == AutocompleteMatch::SEARCH_SUGGEST ||
848 matches_.front().type == AutocompleteMatch::SEARCH_WHAT_YOU_TYPED);
849}
850
851bool SearchProvider::IsTopMatchNotInlinable() const {
852 return matches_.front().type != AutocompleteMatch::SEARCH_WHAT_YOU_TYPED &&
853 matches_.front().type != AutocompleteMatch::URL_WHAT_YOU_TYPED &&
854 matches_.front().inline_autocomplete_offset == string16::npos &&
855 matches_.front().fill_into_edit != input_.text();
856}
857
858void SearchProvider::UpdateMatches() {
859 ConvertResultsToAutocompleteMatches();
initial.commit09911bf2008-07-26 23:55:29860
[email protected]382a0642012-06-06 06:13:52861 // Check constraints that may be violated by suggested relevances.
[email protected]344946a12012-12-20 12:03:42862 if (!matches_.empty() &&
[email protected]e6acd002012-06-16 22:27:47863 (has_suggested_relevance_ || verbatim_relevance_ >= 0)) {
[email protected]344946a12012-12-20 12:03:42864 // These two blocks attempt to repair undesriable behavior by suggested
865 // relevances with minimal impact, preserving other suggested relevances.
866 if (IsTopMatchScoreTooLow()) {
[email protected]1beee342012-06-19 22:22:28867 // Disregard the suggested verbatim relevance if the top score is below
868 // the usual verbatim value. For example, a BarProvider may rely on
869 // SearchProvider's verbatim or inlineable matches for input "foo" to
870 // always outrank its own lowly-ranked non-inlineable "bar" match.
871 verbatim_relevance_ = -1;
[email protected]344946a12012-12-20 12:03:42872 ConvertResultsToAutocompleteMatches();
[email protected]e6acd002012-06-16 22:27:47873 }
[email protected]344946a12012-12-20 12:03:42874 if (IsTopMatchHighRankSearchForURL()) {
[email protected]e6acd002012-06-16 22:27:47875 // Disregard the suggested search and verbatim relevances if the input
876 // type is URL and the top match is a highly-ranked search suggestion.
877 // For example, prevent a search for "foo.com" from outranking another
878 // provider's navigation for "foo.com" or "foo.com/url_from_history".
[email protected]e6acd002012-06-16 22:27:47879 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_, true);
880 ApplyCalculatedSuggestRelevance(&default_suggest_results_, false);
[email protected]382a0642012-06-06 06:13:52881 verbatim_relevance_ = -1;
[email protected]344946a12012-12-20 12:03:42882 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:52883 }
[email protected]344946a12012-12-20 12:03:42884 if (IsTopMatchNotInlinable()) {
885 // Disregard suggested relevances if the top match is not SWYT, inlinable,
886 // or URL_WHAT_YOU_TYPED (which may be top match regardless of inlining).
887 // For example, input "foo" should not invoke a search for "bar", which
888 // would happen if the "bar" search match outranked all other matches.
889 ApplyCalculatedRelevance();
890 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:52891 }
[email protected]344946a12012-12-20 12:03:42892 DCHECK(!IsTopMatchScoreTooLow());
893 DCHECK(!IsTopMatchHighRankSearchForURL());
894 DCHECK(!IsTopMatchNotInlinable());
[email protected]d1f0a7f2012-06-05 10:26:42895 }
896
[email protected]cc63dea2008-08-21 20:56:31897 UpdateStarredStateOfMatches();
[email protected]4ab4c7c2010-11-24 04:49:34898 UpdateDone();
[email protected]257ab712009-04-14 17:16:24899}
900
901void SearchProvider::AddNavigationResultsToMatches(
902 const NavigationResults& navigation_results,
903 bool is_keyword) {
904 if (!navigation_results.empty()) {
[email protected]6c535842012-05-15 05:20:55905 // TODO(kochi|msw): Add more navigational results if they get more
906 // meaningful relevance values; see http://b/1170574.
[email protected]d7ad4772012-06-01 03:12:54907 // CompareScoredResults sorts by descending relevance; so use min_element.
[email protected]6c535842012-05-15 05:20:55908 NavigationResults::const_iterator result(
[email protected]d7ad4772012-06-01 03:12:54909 std::min_element(navigation_results.begin(),
[email protected]6c535842012-05-15 05:20:55910 navigation_results.end(),
911 CompareScoredResults()));
912 matches_.push_back(NavigationToMatch(*result, is_keyword));
[email protected]257ab712009-04-14 17:16:24913 }
914}
915
916void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
917 bool is_keyword,
918 int did_not_accept_suggestion,
919 MatchMap* map) {
[email protected]51124552011-07-16 01:37:10920 if (results.empty())
921 return;
922
[email protected]d7ad4772012-06-01 03:12:54923 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
924 (input_.type() == AutocompleteInput::URL);
925 const string16& input_text = is_keyword ? keyword_input_text_ : input_.text();
[email protected]51124552011-07-16 01:37:10926 bool input_multiple_words = HasMultipleWords(input_text);
927
[email protected]55ce8f12012-05-09 04:44:08928 SuggestResults scored_results;
929 if (!prevent_inline_autocomplete && input_multiple_words) {
930 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
931 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:10932 // autocompleting a multi-word, multi-visit query, and the current input is
933 // still a prefix of it, then changing the autocompletion suddenly feels
934 // wrong. To detect this case, first score as if only one word has been
935 // typed, then check for a best result that is an autocompleted, multi-word
936 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:08937 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
938 false, input_text, is_keyword);
939 if ((scored_results[0].relevance() <
940 AutocompleteResult::kLowestDefaultScore) ||
941 !HasMultipleWords(scored_results[0].suggestion()))
942 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:10943 }
[email protected]55ce8f12012-05-09 04:44:08944 if (scored_results.empty())
945 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
946 input_multiple_words, input_text,
947 is_keyword);
948 for (SuggestResults::const_iterator i(scored_results.begin());
949 i != scored_results.end(); ++i) {
950 AddMatchToMap(i->suggestion(), input_text, i->relevance(),
[email protected]51124552011-07-16 01:37:10951 AutocompleteMatch::SEARCH_HISTORY, did_not_accept_suggestion,
[email protected]55ce8f12012-05-09 04:44:08952 is_keyword, map);
[email protected]51124552011-07-16 01:37:10953 }
954}
955
[email protected]55ce8f12012-05-09 04:44:08956SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:10957 const HistoryResults& results,
958 bool base_prevent_inline_autocomplete,
959 bool input_multiple_words,
960 const string16& input_text,
961 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:48962 AutocompleteClassifier* classifier =
963 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:08964 SuggestResults scored_results;
[email protected]257ab712009-04-14 17:16:24965 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
966 ++i) {
[email protected]51124552011-07-16 01:37:10967 // Don't autocomplete multi-word queries that have only been seen once
968 // unless the user has typed more than one word.
969 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
970 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
971
[email protected]ea3b9a502011-04-04 14:19:37972 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:10973 // when typed. For example, if the user searched for "google.com" and types
974 // "goog", don't autocomplete to the search term "google.com". Otherwise,
975 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:48976 // NOTE: We don't check this in the following cases:
977 // * When inline autocomplete is disabled, we won't be inline
978 // autocompleting this term, so we don't need to worry about confusion as
979 // much. This also prevents calling Classify() again from inside the
980 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:10981 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:48982 // * When the user has typed the whole term, the "what you typed" history
983 // match will outrank us for URL-like inputs anyway, so we need not do
984 // anything special.
[email protected]51124552011-07-16 01:37:10985 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:37986 AutocompleteMatch match;
[email protected]72874a8d2011-05-11 03:48:54987 classifier->Classify(i->term, string16(), false, false, &match, NULL);
[email protected]2905f742011-10-13 03:51:58988 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:46989 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:37990 }
[email protected]51124552011-07-16 01:37:10991
992 int relevance = CalculateRelevanceForHistory(i->time, is_keyword,
993 prevent_inline_autocomplete);
[email protected]55ce8f12012-05-09 04:44:08994 scored_results.push_back(SuggestResult(i->term, relevance));
[email protected]257ab712009-04-14 17:16:24995 }
[email protected]51124552011-07-16 01:37:10996
997 // History returns results sorted for us. However, we may have docked some
998 // results' scores, so things are no longer in order. Do a stable sort to get
999 // things back in order without otherwise disturbing results with equal
1000 // scores, then force the scores to be unique, so that the order in which
1001 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081002 std::stable_sort(scored_results.begin(), scored_results.end(),
1003 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101004 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081005 for (SuggestResults::iterator i(scored_results.begin());
1006 i != scored_results.end(); ++i) {
1007 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1008 i->set_relevance(last_relevance - 1);
1009 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101010 }
1011
[email protected]55ce8f12012-05-09 04:44:081012 return scored_results;
[email protected]257ab712009-04-14 17:16:241013}
1014
[email protected]55ce8f12012-05-09 04:44:081015void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
1016 bool is_keyword,
1017 MatchMap* map) {
[email protected]d7ad4772012-06-01 03:12:541018 const string16& input_text = is_keyword ? keyword_input_text_ : input_.text();
[email protected]55ce8f12012-05-09 04:44:081019 for (size_t i = 0; i < results.size(); ++i) {
[email protected]d7ad4772012-06-01 03:12:541020 AddMatchToMap(results[i].suggestion(), input_text, results[i].relevance(),
[email protected]55ce8f12012-05-09 04:44:081021 AutocompleteMatch::SEARCH_SUGGEST, i, is_keyword, map);
[email protected]257ab712009-04-14 17:16:241022 }
initial.commit09911bf2008-07-26 23:55:291023}
1024
[email protected]382a0642012-06-06 06:13:521025int SearchProvider::GetVerbatimRelevance() const {
[email protected]dc6943b2012-06-19 06:39:561026 // Use the suggested verbatim relevance score if it is non-negative (valid),
1027 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281028 // and if it won't suppress verbatim, leaving no default provider matches.
1029 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561030 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281031 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561032 // Check for results on each verbatim calculation, as results from older
1033 // queries (on previous input) may be trimmed for failing to inline new input.
1034 if (verbatim_relevance_ >= 0 && !input_.prevent_inline_autocomplete() &&
[email protected]1beee342012-06-19 22:22:281035 (verbatim_relevance_ > 0 ||
1036 !default_suggest_results_.empty() ||
[email protected]dc6943b2012-06-19 06:39:561037 !default_navigation_results_.empty())) {
[email protected]d1f0a7f2012-06-05 10:26:421038 return verbatim_relevance_;
[email protected]dc6943b2012-06-19 06:39:561039 }
[email protected]382a0642012-06-06 06:13:521040 return CalculateRelevanceForVerbatim();
1041}
[email protected]d1f0a7f2012-06-05 10:26:421042
[email protected]382a0642012-06-06 06:13:521043int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471044 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361045 return 250;
1046
initial.commit09911bf2008-07-26 23:55:291047 switch (input_.type()) {
1048 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361049 case AutocompleteInput::QUERY:
1050 case AutocompleteInput::FORCED_QUERY:
1051 return 1300;
initial.commit09911bf2008-07-26 23:55:291052
1053 case AutocompleteInput::REQUESTED_URL:
[email protected]52d08b12009-10-19 18:42:361054 return 1150;
initial.commit09911bf2008-07-26 23:55:291055
1056 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361057 return 850;
initial.commit09911bf2008-07-26 23:55:291058
1059 default:
1060 NOTREACHED();
1061 return 0;
1062 }
1063}
1064
[email protected]51124552011-07-16 01:37:101065int SearchProvider::CalculateRelevanceForHistory(
1066 const Time& time,
1067 bool is_keyword,
1068 bool prevent_inline_autocomplete) const {
[email protected]aa613d62010-11-09 20:40:181069 // The relevance of past searches falls off over time. There are two distinct
1070 // equations used. If the first equation is used (searches to the primary
[email protected]51124552011-07-16 01:37:101071 // provider that we want to inline autocomplete), the score starts at 1399 and
1072 // falls to 1300. If the second equation is used the relevance of a search 15
1073 // minutes ago is discounted 50 points, while the relevance of a search two
1074 // weeks ago is discounted 450 points.
[email protected]aa613d62010-11-09 20:40:181075 double elapsed_time = std::max((Time::Now() - time).InSecondsF(), 0.);
[email protected]51124552011-07-16 01:37:101076 bool is_primary_provider = providers_.is_primary_provider(is_keyword);
1077 if (is_primary_provider && !prevent_inline_autocomplete) {
[email protected]aa613d62010-11-09 20:40:181078 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101079 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181080 if (elapsed_time < autocomplete_time) {
[email protected]e17511f2011-07-13 14:09:181081 return (is_keyword ? 1599 : 1399) - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181082 std::pow(elapsed_time / autocomplete_time, 2.5));
1083 }
1084 elapsed_time -= autocomplete_time;
1085 }
1086
[email protected]c3a4bd992010-08-18 20:25:011087 const int score_discount =
1088 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291089
[email protected]6c85aa02009-02-27 12:08:091090 // Don't let scores go below 0. Negative relevance scores are meaningful in
1091 // a different way.
initial.commit09911bf2008-07-26 23:55:291092 int base_score;
[email protected]51124552011-07-16 01:37:101093 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361094 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101095 else
1096 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291097 return std::max(0, base_score - score_discount);
1098}
1099
[email protected]55ce8f12012-05-09 04:44:081100int SearchProvider::CalculateRelevanceForSuggestion(bool for_keyword) const {
1101 return !providers_.is_primary_provider(for_keyword) ? 100 :
1102 ((input_.type() == AutocompleteInput::URL) ? 300 : 600);
initial.commit09911bf2008-07-26 23:55:291103}
1104
[email protected]55ce8f12012-05-09 04:44:081105int SearchProvider::CalculateRelevanceForNavigation(bool for_keyword) const {
1106 return providers_.is_primary_provider(for_keyword) ? 800 : 150;
initial.commit09911bf2008-07-26 23:55:291107}
1108
[email protected]a2fedb1e2011-01-25 15:23:361109void SearchProvider::AddMatchToMap(const string16& query_string,
1110 const string16& input_text,
initial.commit09911bf2008-07-26 23:55:291111 int relevance,
[email protected]4c1fb7ec2008-11-13 00:19:001112 AutocompleteMatch::Type type,
initial.commit09911bf2008-07-26 23:55:291113 int accepted_suggestion,
[email protected]257ab712009-04-14 17:16:241114 bool is_keyword,
initial.commit09911bf2008-07-26 23:55:291115 MatchMap* map) {
[email protected]92513682011-09-01 06:16:521116 AutocompleteMatch match(this, relevance, false, type);
initial.commit09911bf2008-07-26 23:55:291117 std::vector<size_t> content_param_offsets;
[email protected]85b8d6f2012-05-08 20:53:471118 // Bail out now if we don't actually have a valid provider.
1119 match.keyword = is_keyword ?
[email protected]3954c3a2012-04-10 20:17:551120 providers_.keyword_provider() : providers_.default_provider();
[email protected]dbff446582012-10-30 00:20:261121 const TemplateURL* provider_url = match.GetTemplateURL(profile_, false);
[email protected]85b8d6f2012-05-08 20:53:471122 if (provider_url == NULL)
1123 return;
1124
[email protected]70833262011-01-05 23:40:441125 match.contents.assign(query_string);
[email protected]fb5153c52009-07-31 19:40:331126 // We do intra-string highlighting for suggestions - the suggested segment
1127 // will be highlighted, e.g. for input_text = "you" the suggestion may be
1128 // "youtube", so we'll bold the "tube" section: you*tube*.
1129 if (input_text != query_string) {
[email protected]fb5153c52009-07-31 19:40:331130 size_t input_position = match.contents.find(input_text);
[email protected]a2fedb1e2011-01-25 15:23:361131 if (input_position == string16::npos) {
[email protected]fb5153c52009-07-31 19:40:331132 // The input text is not a substring of the query string, e.g. input
1133 // text is "slasdot" and the query string is "slashdot", so we bold the
1134 // whole thing.
1135 match.contents_class.push_back(
1136 ACMatchClassification(0, ACMatchClassification::MATCH));
[email protected]ec2379162009-06-09 23:58:171137 } else {
[email protected]fb5153c52009-07-31 19:40:331138 // TODO(beng): ACMatchClassification::MATCH now seems to just mean
1139 // "bold" this. Consider modifying the terminology.
1140 // We don't iterate over the string here annotating all matches because
1141 // it looks odd to have every occurrence of a substring that may be as
1142 // short as a single character highlighted in a query suggestion result,
1143 // e.g. for input text "s" and query string "southwest airlines", it
1144 // looks odd if both the first and last s are highlighted.
1145 if (input_position != 0) {
1146 match.contents_class.push_back(
1147 ACMatchClassification(0, ACMatchClassification::NONE));
1148 }
1149 match.contents_class.push_back(
1150 ACMatchClassification(input_position, ACMatchClassification::DIM));
1151 size_t next_fragment_position = input_position + input_text.length();
1152 if (next_fragment_position < query_string.length()) {
1153 match.contents_class.push_back(
1154 ACMatchClassification(next_fragment_position,
1155 ACMatchClassification::NONE));
1156 }
[email protected]ec2379162009-06-09 23:58:171157 }
initial.commit09911bf2008-07-26 23:55:291158 } else {
[email protected]fb5153c52009-07-31 19:40:331159 // Otherwise, we're dealing with the "default search" result which has no
[email protected]70833262011-01-05 23:40:441160 // completion.
[email protected]fb5153c52009-07-31 19:40:331161 match.contents_class.push_back(
1162 ACMatchClassification(0, ACMatchClassification::NONE));
initial.commit09911bf2008-07-26 23:55:291163 }
1164
1165 // When the user forced a query, we need to make sure all the fill_into_edit
1166 // values preserve that property. Otherwise, if the user starts editing a
1167 // suggestion, non-Search results will suddenly appear.
[email protected]8f2249b2012-08-29 02:27:241168 if (input_.type() == AutocompleteInput::FORCED_QUERY)
[email protected]a2fedb1e2011-01-25 15:23:361169 match.fill_into_edit.assign(ASCIIToUTF16("?"));
[email protected]8f2249b2012-08-29 02:27:241170 if (is_keyword)
[email protected]033f3422012-03-13 21:24:181171 match.fill_into_edit.append(match.keyword + char16(' '));
[email protected]8f2249b2012-08-29 02:27:241172 if (!input_.prevent_inline_autocomplete() &&
1173 StartsWith(query_string, input_text, false)) {
1174 match.inline_autocomplete_offset =
1175 match.fill_into_edit.length() + input_text.length();
[email protected]c0048b42009-05-04 21:47:171176 }
initial.commit09911bf2008-07-26 23:55:291177 match.fill_into_edit.append(query_string);
initial.commit09911bf2008-07-26 23:55:291178
[email protected]85b8d6f2012-05-08 20:53:471179 const TemplateURLRef& search_url = provider_url->url_ref();
[email protected]360ba052012-04-04 17:26:131180 DCHECK(search_url.SupportsReplacement());
[email protected]bca359b2012-06-24 07:53:041181 match.search_terms_args.reset(
1182 new TemplateURLRef::SearchTermsArgs(query_string));
1183 match.search_terms_args->original_query = input_text;
1184 match.search_terms_args->accepted_suggestion = accepted_suggestion;
1185 // This is the destination URL sans assisted query stats. This must be set
1186 // so the AutocompleteController can properly de-dupe; the controller will
1187 // eventually overwrite it before it reaches the user.
1188 match.destination_url =
1189 GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get()));
initial.commit09911bf2008-07-26 23:55:291190
1191 // Search results don't look like URLs.
[email protected]2905f742011-10-13 03:51:581192 match.transition = is_keyword ?
1193 content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED;
initial.commit09911bf2008-07-26 23:55:291194
1195 // Try to add |match| to |map|. If a match for |query_string| is already in
1196 // |map|, replace it if |match| is more relevant.
1197 // NOTE: Keep this ToLower() call in sync with url_database.cc.
1198 const std::pair<MatchMap::iterator, bool> i = map->insert(
[email protected]a2fedb1e2011-01-25 15:23:361199 std::pair<string16, AutocompleteMatch>(
[email protected]503d03872011-05-06 08:36:261200 base::i18n::ToLower(query_string), match));
initial.commit09911bf2008-07-26 23:55:291201 // NOTE: We purposefully do a direct relevance comparison here instead of
1202 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items added
1203 // first" rather than "items alphabetically first" when the scores are equal.
1204 // The only case this matters is when a user has results with the same score
1205 // that differ only by capitalization; because the history system returns
1206 // results sorted by recency, this means we'll pick the most recent such
1207 // result even if the precision of our relevance score is too low to
1208 // distinguish the two.
1209 if (!i.second && (match.relevance > i.first->second.relevance))
1210 i.first->second = match;
1211}
1212
1213AutocompleteMatch SearchProvider::NavigationToMatch(
1214 const NavigationResult& navigation,
[email protected]257ab712009-04-14 17:16:241215 bool is_keyword) {
[email protected]371dab12012-06-01 03:23:551216 const string16& input = is_keyword ? keyword_input_text_ : input_.text();
[email protected]55ce8f12012-05-09 04:44:081217 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]4c1fb7ec2008-11-13 00:19:001218 AutocompleteMatch::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081219 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551220
1221 // First look for the user's input inside the fill_into_edit as it would be
1222 // without trimming the scheme, so we can find matches at the beginning of the
1223 // scheme.
1224 const string16 untrimmed_fill_into_edit(
1225 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1226 StringForURLDisplay(navigation.url(), true, false)));
1227 const URLPrefix* prefix =
1228 URLPrefix::BestURLPrefix(untrimmed_fill_into_edit, input);
1229 size_t match_start = (prefix == NULL) ?
1230 untrimmed_fill_into_edit.find(input) : prefix->prefix.length();
1231 size_t inline_autocomplete_offset = (prefix == NULL) ?
1232 string16::npos : (match_start + input.length());
1233 bool trim_http = !HasHTTPScheme(input) && (!prefix || (match_start != 0));
1234
1235 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1236 // Otherwise, user edits to a suggestion would show non-Search results.
1237 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
1238 match.fill_into_edit = ASCIIToUTF16("?");
1239 if (inline_autocomplete_offset != string16::npos)
1240 ++inline_autocomplete_offset;
1241 }
1242
1243 const std::string languages(
1244 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1245 const net::FormatUrlTypes format_types =
1246 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1247 match.fill_into_edit +=
1248 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1249 net::FormatUrl(navigation.url(), languages, format_types,
1250 net::UnescapeRule::SPACES, NULL, NULL,
1251 &inline_autocomplete_offset));
1252 if (!input_.prevent_inline_autocomplete())
1253 match.inline_autocomplete_offset = inline_autocomplete_offset;
1254 DCHECK((match.inline_autocomplete_offset == string16::npos) ||
1255 (match.inline_autocomplete_offset <= match.fill_into_edit.length()));
1256
1257 match.contents = net::FormatUrl(navigation.url(), languages,
1258 format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1259 // If the first match in the untrimmed string was inside a scheme that we
1260 // trimmed, look for a subsequent match.
1261 if (match_start == string16::npos)
1262 match_start = match.contents.find(input);
1263 // Safe if |match_start| is npos; also safe if the input is longer than the
1264 // remaining contents after |match_start|.
1265 AutocompleteMatch::ClassifyLocationInString(match_start, input.length(),
1266 match.contents.length(), ACMatchClassification::URL,
1267 &match.contents_class);
initial.commit09911bf2008-07-26 23:55:291268
[email protected]55ce8f12012-05-09 04:44:081269 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551270 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1271 ACMatchClassification::NONE, &match.description_class);
initial.commit09911bf2008-07-26 23:55:291272 return match;
1273}
[email protected]4ab4c7c2010-11-24 04:49:341274
1275void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331276 // We're done when the timer isn't running, there are no suggest queries
1277 // pending, and we're not waiting on instant.
1278 done_ = (!timer_.IsRunning() && (suggest_results_pending_ == 0) &&
[email protected]b67d0a42012-09-04 20:57:351279 (instant_finalized_ ||
[email protected]249a0352012-11-26 21:06:191280 (!chrome::BrowserInstantController::IsInstantEnabled(profile_) &&
1281 !chrome::search::IsInstantExtendedAPIEnabled(profile_))));
[email protected]4ab4c7c2010-11-24 04:49:341282}