blob: 7f72b8f1873026b171c468de684616c19361a8b7 [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]6a2c09f2013-01-25 04:50:0729#include "chrome/browser/history/history_service.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
[email protected]90fe2bb2013-01-15 03:42:1374// The verbatim score for an input which is not an URL.
75const int kNonURLVerbatimRelevance = 1300;
76
[email protected]7706a522012-08-16 17:42:2577// Increments the appropriate value in the histogram by one.
78void LogOmniboxSuggestRequest(
79 SuggestRequestsHistogramValue request_value) {
80 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
81 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
82}
83
[email protected]51124552011-07-16 01:37:1084bool HasMultipleWords(const string16& text) {
85 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
86 bool found_word = false;
87 if (i.Init()) {
88 while (i.Advance()) {
89 if (i.IsWord()) {
90 if (found_word)
91 return true;
92 found_word = true;
93 }
94 }
95 }
96 return false;
97}
98
[email protected]d1f0a7f2012-06-05 10:26:4299} // namespace
[email protected]51124552011-07-16 01:37:10100
[email protected]033f3422012-03-13 21:24:18101
[email protected]3954c3a2012-04-10 20:17:55102// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:58103
[email protected]85b8d6f2012-05-08 20:53:47104SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
105 : template_url_service_(template_url_service) {
106}
107
108const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
109 return default_provider_.empty() ? NULL :
110 template_url_service_->GetTemplateURLForKeyword(default_provider_);
111}
112
113const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
114 return keyword_provider_.empty() ? NULL :
115 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24116}
117
[email protected]3954c3a2012-04-10 20:17:55118
119// SearchProvider -------------------------------------------------------------
120
121// static
122const int SearchProvider::kDefaultProviderURLFetcherID = 1;
123// static
124const int SearchProvider::kKeywordProviderURLFetcherID = 2;
[email protected]3954c3a2012-04-10 20:17:55125
[email protected]30f5bc92012-06-26 04:14:55126SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
127 Profile* profile)
[email protected]35f1f4f02012-09-11 13:17:00128 : AutocompleteProvider(listener, profile,
129 AutocompleteProvider::TYPE_SEARCH),
[email protected]85b8d6f2012-05-08 20:53:47130 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
[email protected]601858c02010-09-01 17:08:20131 suggest_results_pending_(0),
[email protected]d1f0a7f2012-06-05 10:26:42132 has_suggested_relevance_(false),
133 verbatim_relevance_(-1),
[email protected]8e5cc282010-12-05 18:11:39134 have_suggest_results_(false),
[email protected]618d6e62012-12-16 05:55:57135 instant_finalized_(false),
136 field_trial_triggered_(false),
137 field_trial_triggered_in_session_(false) {
[email protected]4ab4c7c2010-11-24 04:49:34138}
139
[email protected]a2fedb1e2011-01-25 15:23:36140void SearchProvider::FinalizeInstantQuery(const string16& input_text,
[email protected]93b73832012-10-18 20:18:38141 const InstantSuggestion& suggestion) {
[email protected]4ab4c7c2010-11-24 04:49:34142 if (done_ || instant_finalized_)
143 return;
144
145 instant_finalized_ = true;
146 UpdateDone();
147
[email protected]e918c112010-12-08 23:03:49148 if (input_text.empty()) {
[email protected]4ab4c7c2010-11-24 04:49:34149 // We only need to update the listener if we're actually done.
150 if (done_)
151 listener_->OnProviderUpdate(false);
152 return;
153 }
154
[email protected]93b73832012-10-18 20:18:38155 default_provider_suggestion_ = suggestion;
[email protected]9e789742011-01-10 23:27:32156
[email protected]a2fedb1e2011-01-25 15:23:36157 string16 adjusted_input_text(input_text);
[email protected]e918c112010-12-08 23:03:49158 AutocompleteInput::RemoveForcedQueryStringIfNecessary(input_.type(),
159 &adjusted_input_text);
160
[email protected]93b73832012-10-18 20:18:38161 const string16 text = adjusted_input_text + suggestion.text;
[email protected]9acdcdc02012-05-21 20:58:36162 bool results_updated = false;
[email protected]4ab4c7c2010-11-24 04:49:34163 // Remove any matches that are identical to |text|. We don't use the
164 // destination_url for comparison as it varies depending upon the index passed
165 // to TemplateURL::ReplaceSearchTerms.
166 for (ACMatches::iterator i = matches_.begin(); i != matches_.end();) {
167 if (((i->type == AutocompleteMatch::SEARCH_HISTORY) ||
168 (i->type == AutocompleteMatch::SEARCH_SUGGEST)) &&
169 (i->fill_into_edit == text)) {
[email protected]e030de62010-11-24 05:41:19170 i = matches_.erase(i);
[email protected]9acdcdc02012-05-21 20:58:36171 results_updated = true;
[email protected]4ab4c7c2010-11-24 04:49:34172 } else {
173 ++i;
174 }
175 }
176
[email protected]90fe2bb2013-01-15 03:42:13177 // Add the new instant suggest result.
[email protected]93b73832012-10-18 20:18:38178 if (suggestion.type == INSTANT_SUGGESTION_SEARCH) {
[email protected]90fe2bb2013-01-15 03:42:13179 // Instant has a query suggestion. Rank it higher than SEARCH_WHAT_YOU_TYPED
180 // so that it gets autocompleted.
181 const int verbatim_relevance = GetVerbatimRelevance();
[email protected]93b73832012-10-18 20:18:38182 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
[email protected]4ab4c7c2010-11-24 04:49:34183 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
184 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]93b73832012-10-18 20:18:38185 MatchMap match_map;
186 AddMatchToMap(text, adjusted_input_text, verbatim_relevance + 1,
187 AutocompleteMatch::SEARCH_SUGGEST,
188 did_not_accept_default_suggestion, false, &match_map);
189 if (!match_map.empty()) {
190 matches_.push_back(match_map.begin()->second);
191 results_updated = true;
192 }
193 } else {
[email protected]c112f0fe72013-01-18 20:30:09194 // Instant has a URL suggestion. Rank it higher than URL_WHAT_YOU_TYPED so
[email protected]90fe2bb2013-01-15 03:42:13195 // it gets autocompleted; use kNonURLVerbatimRelevance rather than
196 // verbatim_relevance so that the score does not change if the user keeps
197 // typing and the input changes from type UNKNOWN to URL.
[email protected]93b73832012-10-18 20:18:38198 matches_.push_back(NavigationToMatch(
199 NavigationResult(GURL(UTF16ToUTF8(suggestion.text)),
200 string16(),
[email protected]90fe2bb2013-01-15 03:42:13201 kNonURLVerbatimRelevance + 1),
[email protected]93b73832012-10-18 20:18:38202 false));
[email protected]9acdcdc02012-05-21 20:58:36203 results_updated = true;
204 }
[email protected]4ab4c7c2010-11-24 04:49:34205
[email protected]9acdcdc02012-05-21 20:58:36206 if (results_updated || done_)
207 listener_->OnProviderUpdate(results_updated);
[email protected]601858c02010-09-01 17:08:20208}
209
initial.commit09911bf2008-07-26 23:55:29210void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27211 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55212 // Do our best to load the model as early as possible. This will reduce
213 // odds of having the model not ready when really needed (a non-empty input).
214 TemplateURLService* model = providers_.template_url_service();
215 DCHECK(model);
216 model->Load();
217
initial.commit09911bf2008-07-26 23:55:29218 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57219 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29220
[email protected]ea3b9a502011-04-04 14:19:37221 instant_finalized_ =
222 (input.matches_requested() != AutocompleteInput::ALL_MATCHES);
[email protected]4ab4c7c2010-11-24 04:49:34223
[email protected]6c85aa02009-02-27 12:08:09224 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29225 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]e29249dc52012-07-19 17:33:50226 Stop(false);
initial.commit09911bf2008-07-26 23:55:29227 return;
228 }
229
[email protected]14710852013-02-05 23:45:41230 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24231 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41232 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
233 &keyword_input_);
234 if (keyword_provider == NULL)
235 keyword_input_.Clear();
236 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24237 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24238
[email protected]85b8d6f2012-05-08 20:53:47239 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07240 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24241 default_provider = NULL;
242
243 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18244 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24245
246 if (!default_provider && !keyword_provider) {
247 // No valid providers.
[email protected]e29249dc52012-07-19 17:33:50248 Stop(false);
initial.commit09911bf2008-07-26 23:55:29249 return;
250 }
251
252 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24253 // or the providers, abort the query.
[email protected]85b8d6f2012-05-08 20:53:47254 string16 default_provider_keyword(default_provider ?
255 default_provider->keyword() : string16());
256 string16 keyword_provider_keyword(keyword_provider ?
257 keyword_provider->keyword() : string16());
[email protected]9e789742011-01-10 23:27:32258 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47259 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]9e789742011-01-10 23:27:32260 if (done_)
[email protected]93b73832012-10-18 20:18:38261 default_provider_suggestion_ = InstantSuggestion();
[email protected]9e789742011-01-10 23:27:32262 else
[email protected]e29249dc52012-07-19 17:33:50263 Stop(false);
[email protected]257ab712009-04-14 17:16:24264 }
initial.commit09911bf2008-07-26 23:55:29265
[email protected]85b8d6f2012-05-08 20:53:47266 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29267
268 if (input.text().empty()) {
269 // User typed "?" alone. Give them a placeholder result indicating what
270 // this syntax does.
[email protected]257ab712009-04-14 17:16:24271 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00272 AutocompleteMatch match;
273 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36274 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24275 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35276 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47277 match.keyword = providers_.default_provider();
[email protected]257ab712009-04-14 17:16:24278 matches_.push_back(match);
279 }
[email protected]e29249dc52012-07-19 17:33:50280 Stop(false);
initial.commit09911bf2008-07-26 23:55:29281 return;
282 }
283
284 input_ = input;
285
[email protected]5cd06c3e2012-09-20 03:25:20286 // Don't run the normal provider flow when the Instant Extended API is
287 // enabled. (When the Extended API is enabled, the embedded page will handle
288 // all search suggestions itself.)
289 // TODO(dcblack): once we are done refactoring the omnibox so we don't need to
290 // use FinalizeInstantQuery anymore, we can take out this check and remove
291 // this provider from kInstantExtendedOmniboxProviders.
292 if (!chrome::search::IsInstantExtendedAPIEnabled(profile_)) {
293 DoHistoryQuery(minimal_changes);
294 StartOrStopSuggestQuery(minimal_changes);
295 }
[email protected]344946a12012-12-20 12:03:42296 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29297}
298
[email protected]55ce8f12012-05-09 04:44:08299SearchProvider::Result::Result(int relevance) : relevance_(relevance) {}
300SearchProvider::Result::~Result() {}
301
302SearchProvider::SuggestResult::SuggestResult(const string16& suggestion,
303 int relevance)
304 : Result(relevance),
305 suggestion_(suggestion) {
306}
307
308SearchProvider::SuggestResult::~SuggestResult() {}
309
310SearchProvider::NavigationResult::NavigationResult(const GURL& url,
311 const string16& description,
312 int relevance)
313 : Result(relevance),
314 url_(url),
315 description_(description) {
316 DCHECK(url_.is_valid());
317}
318
319SearchProvider::NavigationResult::~NavigationResult() {}
320
321class SearchProvider::CompareScoredResults {
[email protected]51124552011-07-16 01:37:10322 public:
[email protected]55ce8f12012-05-09 04:44:08323 bool operator()(const Result& a, const Result& b) {
[email protected]51124552011-07-16 01:37:10324 // Sort in descending relevance order.
[email protected]55ce8f12012-05-09 04:44:08325 return a.relevance() > b.relevance();
[email protected]51124552011-07-16 01:37:10326 }
327};
328
initial.commit09911bf2008-07-26 23:55:29329void SearchProvider::Run() {
330 // Start a new request with the current input.
[email protected]257ab712009-04-14 17:16:24331 suggest_results_pending_ = 0;
[email protected]a0ad93ea2012-05-07 22:11:53332 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]9ff91722012-09-07 05:29:12333
334 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
[email protected]14710852013-02-05 23:45:41335 providers_.GetDefaultProviderURL(), input_));
[email protected]9ff91722012-09-07 05:29:12336 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
[email protected]14710852013-02-05 23:45:41337 providers_.GetKeywordProviderURL(), keyword_input_));
[email protected]85b8d6f2012-05-08 20:53:47338
339 // Both the above can fail if the providers have been modified or deleted
340 // since the query began.
341 if (suggest_results_pending_ == 0) {
342 UpdateDone();
343 // We only need to update the listener if we're actually done.
344 if (done_)
345 listener_->OnProviderUpdate(false);
346 }
initial.commit09911bf2008-07-26 23:55:29347}
348
[email protected]e29249dc52012-07-19 17:33:50349void SearchProvider::Stop(bool clear_cached_results) {
initial.commit09911bf2008-07-26 23:55:29350 StopSuggest();
351 done_ = true;
[email protected]93b73832012-10-18 20:18:38352 default_provider_suggestion_ = InstantSuggestion();
[email protected]e29249dc52012-07-19 17:33:50353
354 if (clear_cached_results)
355 ClearResults();
initial.commit09911bf2008-07-26 23:55:29356}
357
[email protected]0e9e8782012-05-15 23:01:51358void SearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
359 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
360 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
361 new_entry.set_provider(AsOmniboxEventProviderType());
362 new_entry.set_provider_done(done_);
[email protected]618d6e62012-12-16 05:55:57363 uint32 field_trial_hash = 0;
364 if (AutocompleteFieldTrial::GetActiveSuggestFieldTrialHash(
[email protected]d78d7362012-12-19 18:43:28365 &field_trial_hash)) {
[email protected]618d6e62012-12-16 05:55:57366 if (field_trial_triggered_)
367 new_entry.mutable_field_trial_triggered()->Add(field_trial_hash);
[email protected]d78d7362012-12-19 18:43:28368 if (field_trial_triggered_in_session_) {
[email protected]618d6e62012-12-16 05:55:57369 new_entry.mutable_field_trial_triggered_in_session()->Add(
370 field_trial_hash);
[email protected]d78d7362012-12-19 18:43:28371 }
[email protected]618d6e62012-12-16 05:55:57372 }
373}
374
375void SearchProvider::ResetSession() {
376 field_trial_triggered_in_session_ = false;
[email protected]0e9e8782012-05-15 23:01:51377}
378
[email protected]10c2d692012-05-11 05:32:23379void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29380 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24381 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25382 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15383 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06384 const net::HttpResponseHeaders* const response_headers =
[email protected]7cc6e5632011-10-25 17:56:12385 source->GetResponseHeaders();
[email protected]c530c852011-10-24 18:18:34386 std::string json_data;
387 source->GetResponseAsString(&json_data);
[email protected]6c85aa02009-02-27 12:08:09388 // JSON is supposed to be UTF-8, but some suggest service providers send JSON
389 // files in non-UTF-8 encodings. The actual encoding is usually specified in
390 // the Content-Type header field.
[email protected]ec9207d32008-09-26 00:51:06391 if (response_headers) {
392 std::string charset;
393 if (response_headers->GetCharset(&charset)) {
[email protected]a2fedb1e2011-01-25 15:23:36394 string16 data_16;
[email protected]ec9207d32008-09-26 00:51:06395 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
[email protected]c530c852011-10-24 18:18:34396 if (base::CodepageToUTF16(json_data, charset.c_str(),
[email protected]a2fedb1e2011-01-25 15:23:36397 base::OnStringConversionError::FAIL,
398 &data_16))
399 json_data = UTF16ToUTF8(data_16);
[email protected]ec9207d32008-09-26 00:51:06400 }
401 }
402
[email protected]d7ad4772012-06-01 03:12:54403 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]f2916ea2013-01-26 02:20:14404 // Ensure the request succeeded and that the provider used is still available.
405 // A verbatim match cannot be generated without this provider, causing errors.
[email protected]013e9a02012-05-18 20:27:10406 const bool request_succeeded =
[email protected]f2916ea2013-01-26 02:20:14407 source->GetStatus().is_success() && source->GetResponseCode() == 200 &&
408 ((is_keyword && providers_.GetKeywordProviderURL()) ||
409 (!is_keyword && providers_.GetDefaultProviderURL()));
[email protected]a0ad93ea2012-05-07 22:11:53410
411 // Record response time for suggest requests sent to Google. We care
412 // only about the common case: the Google default provider used in
413 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47414 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08415 if (!is_keyword && default_url &&
[email protected]9899a612012-08-21 23:50:04416 (TemplateURLPrepopulateData::GetEngineType(default_url->url()) ==
417 SEARCH_ENGINE_GOOGLE)) {
[email protected]6dc950f2012-07-16 19:49:08418 const TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10419 base::TimeTicks::Now() - time_suggest_request_sent_;
420 if (request_succeeded) {
421 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
422 elapsed_time);
423 } else {
424 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
425 elapsed_time);
426 }
[email protected]b4cebf82008-12-29 19:59:08427 }
428
[email protected]d7ad4772012-06-01 03:12:54429 bool results_updated = false;
430 if (request_succeeded) {
431 JSONStringValueSerializer deserializer(json_data);
432 deserializer.set_allow_trailing_comma(true);
433 scoped_ptr<Value> data(deserializer.Deserialize(NULL, NULL));
434 results_updated = data.get() && ParseSuggestResults(data.get(), is_keyword);
435 }
436
[email protected]344946a12012-12-20 12:03:42437 UpdateMatches();
[email protected]d7ad4772012-06-01 03:12:54438 if (done_ || results_updated)
439 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29440}
441
[email protected]601858c02010-09-01 17:08:20442SearchProvider::~SearchProvider() {
443}
444
[email protected]8d457132010-11-04 18:13:40445void SearchProvider::DoHistoryQuery(bool minimal_changes) {
446 // The history query results are synchronous, so if minimal_changes is true,
447 // we still have the last results and don't need to do anything.
448 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29449 return;
450
[email protected]8d457132010-11-04 18:13:40451 keyword_history_results_.clear();
452 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29453
[email protected]8d457132010-11-04 18:13:40454 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10455 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]8d457132010-11-04 18:13:40456 history::URLDatabase* url_db = history_service ?
457 history_service->InMemoryDatabase() : NULL;
458 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29459 return;
460
[email protected]51124552011-07-16 01:37:10461 // Request history for both the keyword and default provider. We grab many
462 // more matches than we'll ultimately clamp to so that if there are several
463 // recent multi-word matches who scores are lowered (see
464 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
465 // matches. Note that this doesn't fix the problem entirely, but merely
466 // limits it to cases with a very large number of such multi-word matches; for
467 // now, this seems OK compared with the complexity of a real fix, which would
468 // require multiple searches and tracking of "single- vs. multi-word" in the
469 // database.
470 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47471 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
472 if (default_url) {
473 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
474 num_matches, &default_history_results_);
[email protected]257ab712009-04-14 17:16:24475 }
[email protected]85b8d6f2012-05-08 20:53:47476 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
477 if (keyword_url) {
478 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41479 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55480 }
initial.commit09911bf2008-07-26 23:55:29481}
482
[email protected]6dc950f2012-07-16 19:49:08483void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34484 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29485 StopSuggest();
[email protected]55ce8f12012-05-09 04:44:08486 ClearResults();
initial.commit09911bf2008-07-26 23:55:29487 return;
488 }
489
490 // For the minimal_changes case, if we finished the previous query and still
491 // have its results, or are allowed to keep running it, just do that, rather
492 // than starting a new query.
493 if (minimal_changes &&
[email protected]ea3b9a502011-04-04 14:19:37494 (have_suggest_results_ ||
495 (!done_ &&
496 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29497 return;
498
499 // We can't keep running any previous query, so halt it.
500 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42501
502 // Remove existing results that cannot inline autocomplete the new input.
503 RemoveStaleResults();
initial.commit09911bf2008-07-26 23:55:29504
505 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37506 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29507 return;
508
[email protected]515ffa942012-11-27 20:18:24509 // To avoid flooding the suggest server, don't send a query until at least 100
510 // ms since the last query.
511 const int kMinimumTimeBetweenSuggestQueriesMs = 100;
512 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
513 TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
514 base::TimeTicks now(base::TimeTicks::Now());
515 if (now >= next_suggest_time) {
516 Run();
517 return;
518 }
519 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29520}
521
[email protected]83c726482008-09-10 06:36:34522bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55523 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
524 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47525 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
526 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34527 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47528 ((!default_url || default_url->suggestions_url().empty()) &&
529 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34530 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
531 return false;
532
[email protected]cac59d32010-08-09 23:23:14533 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34534 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34535
[email protected]cac59d32010-08-09 23:23:14536 // FORCED_QUERY means the user is explicitly asking us to search for this, so
537 // we assume it isn't a URL and/or there isn't private data.
538 if (input_.type() == AutocompleteInput::FORCED_QUERY)
539 return true;
[email protected]83c726482008-09-10 06:36:34540
[email protected]cac59d32010-08-09 23:23:14541 // Next we check the scheme. If this is UNKNOWN/REQUESTED_URL/URL with a
542 // scheme that isn't http/https/ftp, we shouldn't send it. Sending things
543 // like file: and data: is both a waste of time and a disclosure of
544 // potentially private, local data. Other "schemes" may actually be
545 // usernames, and we don't want to send passwords. If the scheme is OK, we
546 // still need to check other cases below. If this is QUERY, then the presence
547 // of these schemes means the user explicitly typed one, and thus this is
548 // probably a URL that's being entered and happens to currently be invalid --
549 // in which case we again want to run our checks below. Other QUERY cases are
550 // less likely to be URLs and thus we assume we're OK.
[email protected]a2fedb1e2011-01-25 15:23:36551 if (!LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpScheme) &&
552 !LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
553 !LowerCaseEqualsASCII(input_.scheme(), chrome::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14554 return (input_.type() == AutocompleteInput::QUERY);
555
556 // Don't send URLs with usernames, queries or refs. Some of these are
557 // private, and the Suggest server is unlikely to have any useful results
558 // for any of them. Also don't send URLs with ports, as we may initially
559 // think that a username + password is a host + port (and we don't want to
560 // send usernames/passwords), and even if the port really is a port, the
561 // server is once again unlikely to have and useful results.
562 const url_parse::Parsed& parts = input_.parts();
563 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
564 parts.query.is_nonempty() || parts.ref.is_nonempty())
565 return false;
566
567 // Don't send anything for https except the hostname. Hostnames are OK
568 // because they are visible when the TCP connection is established, but the
569 // specific path may reveal private information.
[email protected]a2fedb1e2011-01-25 15:23:36570 if (LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
571 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14572 return false;
[email protected]83c726482008-09-10 06:36:34573
574 return true;
575}
576
initial.commit09911bf2008-07-26 23:55:29577void SearchProvider::StopSuggest() {
[email protected]7706a522012-08-16 17:42:25578 // Increment the appropriate field in the histogram by the number of
579 // pending requests that were invalidated.
580 for (int i = 0; i < suggest_results_pending_; i++)
581 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
[email protected]257ab712009-04-14 17:16:24582 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14583 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24584 // Stop any in-progress URL fetches.
585 keyword_fetcher_.reset();
586 default_fetcher_.reset();
[email protected]55ce8f12012-05-09 04:44:08587}
588
589void SearchProvider::ClearResults() {
[email protected]257ab712009-04-14 17:16:24590 keyword_suggest_results_.clear();
591 default_suggest_results_.clear();
592 keyword_navigation_results_.clear();
593 default_navigation_results_.clear();
[email protected]d1f0a7f2012-06-05 10:26:42594 has_suggested_relevance_ = false;
595 verbatim_relevance_ = -1;
initial.commit09911bf2008-07-26 23:55:29596 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29597}
598
[email protected]d1f0a7f2012-06-05 10:26:42599void SearchProvider::RemoveStaleResults() {
[email protected]14710852013-02-05 23:45:41600 // Keyword provider results should match |keyword_input_.text()|, unless
[email protected]42cfd01d02013-01-23 02:40:02601 // the input was just changed to non-keyword mode; in that case, compare
602 // against |input_.text()|.
603 const string16& keyword_input =
[email protected]14710852013-02-05 23:45:41604 !keyword_input_.text().empty() ? keyword_input_.text() : input_.text();
[email protected]42cfd01d02013-01-23 02:40:02605 RemoveStaleSuggestResults(&keyword_suggest_results_, keyword_input);
606 RemoveStaleSuggestResults(&default_suggest_results_, input_.text());
607 RemoveStaleNavigationResults(&keyword_navigation_results_, keyword_input);
608 RemoveStaleNavigationResults(&default_navigation_results_, input_.text());
[email protected]d1f0a7f2012-06-05 10:26:42609}
610
[email protected]42cfd01d02013-01-23 02:40:02611// static
[email protected]d1f0a7f2012-06-05 10:26:42612void SearchProvider::RemoveStaleSuggestResults(SuggestResults* list,
[email protected]42cfd01d02013-01-23 02:40:02613 const string16& input) {
[email protected]d1f0a7f2012-06-05 10:26:42614 for (SuggestResults::iterator i = list->begin(); i < list->end();)
615 i = StartsWith(i->suggestion(), input, false) ? (i + 1) : list->erase(i);
616}
617
618void SearchProvider::RemoveStaleNavigationResults(NavigationResults* list,
[email protected]42cfd01d02013-01-23 02:40:02619 const string16& input) {
[email protected]d1f0a7f2012-06-05 10:26:42620 for (NavigationResults::iterator i = list->begin(); i < list->end();) {
621 const string16 fill(AutocompleteInput::FormattedStringWithEquivalentMeaning(
622 i->url(), StringForURLDisplay(i->url(), true, false)));
623 i = URLPrefix::BestURLPrefix(fill, input) ? (i + 1) : list->erase(i);
624 }
625}
626
627void SearchProvider::ApplyCalculatedRelevance() {
628 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_, true);
629 ApplyCalculatedSuggestRelevance(&default_suggest_results_, false);
630 ApplyCalculatedNavigationRelevance(&keyword_navigation_results_, true);
631 ApplyCalculatedNavigationRelevance(&default_navigation_results_, false);
632 has_suggested_relevance_ = false;
633 verbatim_relevance_ = -1;
634}
635
636void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list,
637 bool is_keyword) {
638 for (size_t i = 0; i < list->size(); ++i) {
639 (*list)[i].set_relevance(CalculateRelevanceForSuggestion(is_keyword) +
640 (list->size() - i - 1));
641 }
642}
643
644void SearchProvider::ApplyCalculatedNavigationRelevance(NavigationResults* list,
645 bool is_keyword) {
646 for (size_t i = 0; i < list->size(); ++i) {
647 (*list)[i].set_relevance(CalculateRelevanceForNavigation(is_keyword) +
648 (list->size() - i - 1));
649 }
650}
651
[email protected]15fb2aa2012-05-22 22:52:59652net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12653 int id,
[email protected]9ff91722012-09-07 05:29:12654 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41655 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12656 if (!template_url || template_url->suggestions_url().empty())
657 return NULL;
658
659 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41660 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
661 search_term_args.cursor_position = input.cursor_position();
[email protected]9ff91722012-09-07 05:29:12662 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:16663 search_term_args));
[email protected]9ff91722012-09-07 05:29:12664 if (!suggest_url.is_valid())
665 return NULL;
666
667 suggest_results_pending_++;
668 LogOmniboxSuggestRequest(REQUEST_SENT);
669
670 net::URLFetcher* fetcher =
671 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12672 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34673 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30674 // Add Chrome experiment state to the request headers.
675 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:09676 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30677 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
678 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24679 fetcher->Start();
680 return fetcher;
681}
682
[email protected]d7ad4772012-06-01 03:12:54683bool SearchProvider::ParseSuggestResults(Value* root_val, bool is_keyword) {
684 // TODO(pkasting): Fix |have_suggest_results_|; see http://crbug.com/130631
685 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29686
[email protected]d7ad4772012-06-01 03:12:54687 string16 query;
688 ListValue* root_list = NULL;
689 ListValue* results = NULL;
[email protected]14710852013-02-05 23:45:41690 const string16& input_text =
691 is_keyword ? keyword_input_.text() : input_.text();
[email protected]d7ad4772012-06-01 03:12:54692 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
693 (query != input_text) || !root_list->GetList(1, &results))
initial.commit09911bf2008-07-26 23:55:29694 return false;
695
[email protected]55ce8f12012-05-09 04:44:08696 // 3rd element: Description list.
[email protected]d7ad4772012-06-01 03:12:54697 ListValue* descriptions = NULL;
698 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:29699
[email protected]55ce8f12012-05-09 04:44:08700 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:29701
[email protected]d1f0a7f2012-06-05 10:26:42702 // Reset suggested relevance information from the default provider.
703 if (!is_keyword) {
704 has_suggested_relevance_ = false;
705 verbatim_relevance_ = -1;
706 }
707
[email protected]55ce8f12012-05-09 04:44:08708 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]d7ad4772012-06-01 03:12:54709 ListValue* types = NULL;
[email protected]d1f0a7f2012-06-05 10:26:42710 ListValue* relevances = NULL;
711 DictionaryValue* extras = NULL;
712 if (root_list->GetDictionary(4, &extras)) {
713 extras->GetList("google:suggesttype", &types);
714
715 // Only accept relevance suggestions if Instant is disabled.
[email protected]e41982a72012-11-20 07:16:51716 if (!is_keyword &&
717 !chrome::BrowserInstantController::IsInstantEnabled(profile_)) {
[email protected]d1f0a7f2012-06-05 10:26:42718 // Discard this list if its size does not match that of the suggestions.
719 if (extras->GetList("google:suggestrelevance", &relevances) &&
720 relevances->GetSize() != results->GetSize())
721 relevances = NULL;
722
723 extras->GetInteger("google:verbatimrelevance", &verbatim_relevance_);
724 }
[email protected]618d6e62012-12-16 05:55:57725
726 // Check if the active suggest field trial (if any) has triggered either
727 // for the default provider or keyword provider.
728 bool triggered = false;
729 extras->GetBoolean("google:fieldtrialtriggered", &triggered);
730 field_trial_triggered_ |= triggered;
731 field_trial_triggered_in_session_ |= triggered;
initial.commit09911bf2008-07-26 23:55:29732 }
733
[email protected]d7ad4772012-06-01 03:12:54734 SuggestResults* suggest_results =
735 is_keyword ? &keyword_suggest_results_ : &default_suggest_results_;
736 NavigationResults* navigation_results =
737 is_keyword ? &keyword_navigation_results_ : &default_navigation_results_;
initial.commit09911bf2008-07-26 23:55:29738
[email protected]d1f0a7f2012-06-05 10:26:42739 // Clear the previous results now that new results are available.
740 suggest_results->clear();
741 navigation_results->clear();
742
743 string16 result, title;
744 std::string type;
745 int relevance = -1;
[email protected]d7ad4772012-06-01 03:12:54746 for (size_t index = 0; results->GetString(index, &result); ++index) {
[email protected]8e81f5092010-09-29 23:19:40747 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:08748 // they make no sense at all and can cause problems in our code.
[email protected]d7ad4772012-06-01 03:12:54749 if (result.empty())
[email protected]8e81f5092010-09-29 23:19:40750 continue;
751
[email protected]d1f0a7f2012-06-05 10:26:42752 // Apply valid suggested relevance scores; discard invalid lists.
753 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
754 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:54755 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:42756 // Do not blindly trust the URL coming from the server to be valid.
757 GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(result), std::string()));
758 if (url.is_valid()) {
759 if (descriptions != NULL)
760 descriptions->GetString(index, &title);
761 navigation_results->push_back(NavigationResult(url, title, relevance));
initial.commit09911bf2008-07-26 23:55:29762 }
763 } else {
[email protected]d1f0a7f2012-06-05 10:26:42764 // TODO(kochi): Improve calculator result presentation.
765 suggest_results->push_back(SuggestResult(result, relevance));
initial.commit09911bf2008-07-26 23:55:29766 }
767 }
768
[email protected]d1f0a7f2012-06-05 10:26:42769 // Apply calculated relevance scores if a valid list was not provided.
770 if (relevances == NULL) {
771 ApplyCalculatedSuggestRelevance(suggest_results, is_keyword);
772 ApplyCalculatedNavigationRelevance(navigation_results, is_keyword);
773 } else if (!is_keyword) {
774 has_suggested_relevance_ = true;
775 }
776
[email protected]d7ad4772012-06-01 03:12:54777 have_suggest_results_ = true;
[email protected]d1f0a7f2012-06-05 10:26:42778 return true;
initial.commit09911bf2008-07-26 23:55:29779}
780
[email protected]344946a12012-12-20 12:03:42781void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29782 // Convert all the results to matches and add them to a map, so we can keep
783 // the most relevant match for each result.
784 MatchMap map;
[email protected]257ab712009-04-14 17:16:24785 const Time no_time;
786 int did_not_accept_keyword_suggestion = keyword_suggest_results_.empty() ?
initial.commit09911bf2008-07-26 23:55:29787 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
788 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]257ab712009-04-14 17:16:24789 // Keyword what you typed results are handled by the KeywordProvider.
initial.commit09911bf2008-07-26 23:55:29790
[email protected]382a0642012-06-06 06:13:52791 int verbatim_relevance = GetVerbatimRelevance();
[email protected]257ab712009-04-14 17:16:24792 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
[email protected]55ce8f12012-05-09 04:44:08793 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
794 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:42795 if (verbatim_relevance > 0) {
796 AddMatchToMap(input_.text(), input_.text(), verbatim_relevance,
797 AutocompleteMatch::SEARCH_WHAT_YOU_TYPED,
798 did_not_accept_default_suggestion, false, &map);
799 }
[email protected]b9ce8532012-05-24 20:51:15800 const size_t what_you_typed_size = map.size();
[email protected]93b73832012-10-18 20:18:38801 if (!default_provider_suggestion_.text.empty() &&
[email protected]2ac15ba2013-01-14 22:38:59802 default_provider_suggestion_.type == INSTANT_SUGGESTION_SEARCH &&
803 !input_.prevent_inline_autocomplete())
[email protected]93b73832012-10-18 20:18:38804 AddMatchToMap(input_.text() + default_provider_suggestion_.text,
[email protected]55ce8f12012-05-09 04:44:08805 input_.text(), verbatim_relevance + 1,
[email protected]85b8d6f2012-05-08 20:53:47806 AutocompleteMatch::SEARCH_SUGGEST,
[email protected]55ce8f12012-05-09 04:44:08807 did_not_accept_default_suggestion, false, &map);
initial.commit09911bf2008-07-26 23:55:29808
[email protected]257ab712009-04-14 17:16:24809 AddHistoryResultsToMap(keyword_history_results_, true,
810 did_not_accept_keyword_suggestion, &map);
811 AddHistoryResultsToMap(default_history_results_, false,
812 did_not_accept_default_suggestion, &map);
813
[email protected]55ce8f12012-05-09 04:44:08814 AddSuggestResultsToMap(keyword_suggest_results_, true, &map);
815 AddSuggestResultsToMap(default_suggest_results_, false, &map);
initial.commit09911bf2008-07-26 23:55:29816
817 // Now add the most relevant matches from the map to |matches_|.
818 matches_.clear();
819 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
820 matches_.push_back(i->second);
821
[email protected]93b73832012-10-18 20:18:38822 if (!default_provider_suggestion_.text.empty() &&
[email protected]2ac15ba2013-01-14 22:38:59823 default_provider_suggestion_.type == INSTANT_SUGGESTION_URL &&
[email protected]90fe2bb2013-01-15 03:42:13824 !input_.prevent_inline_autocomplete()) {
825 // See comment in FinalizeInstantQuery() for why we don't use
826 // |verbatim_relevance| here.
[email protected]93b73832012-10-18 20:18:38827 matches_.push_back(NavigationToMatch(
828 NavigationResult(GURL(UTF16ToUTF8(default_provider_suggestion_.text)),
829 string16(),
[email protected]90fe2bb2013-01-15 03:42:13830 kNonURLVerbatimRelevance + 1),
[email protected]93b73832012-10-18 20:18:38831 false));
[email protected]90fe2bb2013-01-15 03:42:13832 }
[email protected]257ab712009-04-14 17:16:24833 AddNavigationResultsToMatches(keyword_navigation_results_, true);
834 AddNavigationResultsToMatches(default_navigation_results_, false);
initial.commit09911bf2008-07-26 23:55:29835
[email protected]b9ce8532012-05-24 20:51:15836 // Allow an additional match for "what you typed" if it's present.
837 const size_t max_total_matches = kMaxMatches + what_you_typed_size;
initial.commit09911bf2008-07-26 23:55:29838 std::partial_sort(matches_.begin(),
839 matches_.begin() + std::min(max_total_matches, matches_.size()),
840 matches_.end(), &AutocompleteMatch::MoreRelevant);
[email protected]3723e6e2012-06-11 21:06:56841
842 // If the top match is effectively 'verbatim' but exceeds the calculated
843 // verbatim relevance, and REQUESTED_URL |input_| has a |desired_tld|
844 // (for example ".com" when the CTRL key is pressed for REQUESTED_URL input),
845 // promote a URL_WHAT_YOU_TYPED match to the top. Otherwise, these matches can
846 // stomp the HistoryURLProvider's similar transient URL_WHAT_YOU_TYPED match,
847 // and CTRL+ENTER will invoke the search instead of the expected navigation.
848 if ((has_suggested_relevance_ || verbatim_relevance_ >= 0) &&
849 input_.type() == AutocompleteInput::REQUESTED_URL &&
850 !input_.desired_tld().empty() && !matches_.empty() &&
851 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
852 matches_.front().fill_into_edit == input_.text()) {
853 AutocompleteMatch match = HistoryURLProvider::SuggestExactInput(
854 this, input_, !HasHTTPScheme(input_.text()));
855 match.relevance = matches_.front().relevance + 1;
856 matches_.insert(matches_.begin(), match);
857 }
858
initial.commit09911bf2008-07-26 23:55:29859 if (matches_.size() > max_total_matches)
[email protected]344946a12012-12-20 12:03:42860 matches_.resize(max_total_matches);
861}
862
863bool SearchProvider::IsTopMatchScoreTooLow() const {
864 return matches_.front().relevance < CalculateRelevanceForVerbatim();
865}
866
867bool SearchProvider::IsTopMatchHighRankSearchForURL() const {
868 return input_.type() == AutocompleteInput::URL &&
869 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
870 (matches_.front().type == AutocompleteMatch::SEARCH_SUGGEST ||
871 matches_.front().type == AutocompleteMatch::SEARCH_WHAT_YOU_TYPED);
872}
873
874bool SearchProvider::IsTopMatchNotInlinable() const {
875 return matches_.front().type != AutocompleteMatch::SEARCH_WHAT_YOU_TYPED &&
876 matches_.front().type != AutocompleteMatch::URL_WHAT_YOU_TYPED &&
877 matches_.front().inline_autocomplete_offset == string16::npos &&
878 matches_.front().fill_into_edit != input_.text();
879}
880
881void SearchProvider::UpdateMatches() {
882 ConvertResultsToAutocompleteMatches();
initial.commit09911bf2008-07-26 23:55:29883
[email protected]382a0642012-06-06 06:13:52884 // Check constraints that may be violated by suggested relevances.
[email protected]344946a12012-12-20 12:03:42885 if (!matches_.empty() &&
[email protected]e6acd002012-06-16 22:27:47886 (has_suggested_relevance_ || verbatim_relevance_ >= 0)) {
[email protected]344946a12012-12-20 12:03:42887 // These two blocks attempt to repair undesriable behavior by suggested
888 // relevances with minimal impact, preserving other suggested relevances.
889 if (IsTopMatchScoreTooLow()) {
[email protected]1beee342012-06-19 22:22:28890 // Disregard the suggested verbatim relevance if the top score is below
891 // the usual verbatim value. For example, a BarProvider may rely on
892 // SearchProvider's verbatim or inlineable matches for input "foo" to
893 // always outrank its own lowly-ranked non-inlineable "bar" match.
894 verbatim_relevance_ = -1;
[email protected]344946a12012-12-20 12:03:42895 ConvertResultsToAutocompleteMatches();
[email protected]e6acd002012-06-16 22:27:47896 }
[email protected]344946a12012-12-20 12:03:42897 if (IsTopMatchHighRankSearchForURL()) {
[email protected]e6acd002012-06-16 22:27:47898 // Disregard the suggested search and verbatim relevances if the input
899 // type is URL and the top match is a highly-ranked search suggestion.
900 // For example, prevent a search for "foo.com" from outranking another
901 // provider's navigation for "foo.com" or "foo.com/url_from_history".
[email protected]e6acd002012-06-16 22:27:47902 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_, true);
903 ApplyCalculatedSuggestRelevance(&default_suggest_results_, false);
[email protected]382a0642012-06-06 06:13:52904 verbatim_relevance_ = -1;
[email protected]344946a12012-12-20 12:03:42905 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:52906 }
[email protected]344946a12012-12-20 12:03:42907 if (IsTopMatchNotInlinable()) {
908 // Disregard suggested relevances if the top match is not SWYT, inlinable,
909 // or URL_WHAT_YOU_TYPED (which may be top match regardless of inlining).
910 // For example, input "foo" should not invoke a search for "bar", which
911 // would happen if the "bar" search match outranked all other matches.
912 ApplyCalculatedRelevance();
913 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:52914 }
[email protected]344946a12012-12-20 12:03:42915 DCHECK(!IsTopMatchScoreTooLow());
916 DCHECK(!IsTopMatchHighRankSearchForURL());
917 DCHECK(!IsTopMatchNotInlinable());
[email protected]d1f0a7f2012-06-05 10:26:42918 }
919
[email protected]cc63dea2008-08-21 20:56:31920 UpdateStarredStateOfMatches();
[email protected]4ab4c7c2010-11-24 04:49:34921 UpdateDone();
[email protected]257ab712009-04-14 17:16:24922}
923
924void SearchProvider::AddNavigationResultsToMatches(
925 const NavigationResults& navigation_results,
926 bool is_keyword) {
[email protected]c112f0fe72013-01-18 20:30:09927 if (navigation_results.empty())
928 return;
929
930 if (has_suggested_relevance_) {
931 for (NavigationResults::const_iterator it = navigation_results.begin();
932 it != navigation_results.end(); ++it)
933 matches_.push_back(NavigationToMatch(*it, is_keyword));
934 } else {
935 // Pick one element only in absence of the suggested relevance scores.
[email protected]6c535842012-05-15 05:20:55936 // TODO(kochi|msw): Add more navigational results if they get more
937 // meaningful relevance values; see http://b/1170574.
[email protected]d7ad4772012-06-01 03:12:54938 // CompareScoredResults sorts by descending relevance; so use min_element.
[email protected]6c535842012-05-15 05:20:55939 NavigationResults::const_iterator result(
[email protected]d7ad4772012-06-01 03:12:54940 std::min_element(navigation_results.begin(),
[email protected]6c535842012-05-15 05:20:55941 navigation_results.end(),
942 CompareScoredResults()));
943 matches_.push_back(NavigationToMatch(*result, is_keyword));
[email protected]257ab712009-04-14 17:16:24944 }
945}
946
947void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
948 bool is_keyword,
949 int did_not_accept_suggestion,
950 MatchMap* map) {
[email protected]51124552011-07-16 01:37:10951 if (results.empty())
952 return;
953
[email protected]d7ad4772012-06-01 03:12:54954 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
955 (input_.type() == AutocompleteInput::URL);
[email protected]14710852013-02-05 23:45:41956 const string16& input_text =
957 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:10958 bool input_multiple_words = HasMultipleWords(input_text);
959
[email protected]55ce8f12012-05-09 04:44:08960 SuggestResults scored_results;
961 if (!prevent_inline_autocomplete && input_multiple_words) {
962 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
963 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:10964 // autocompleting a multi-word, multi-visit query, and the current input is
965 // still a prefix of it, then changing the autocompletion suddenly feels
966 // wrong. To detect this case, first score as if only one word has been
967 // typed, then check for a best result that is an autocompleted, multi-word
968 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:08969 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
970 false, input_text, is_keyword);
971 if ((scored_results[0].relevance() <
972 AutocompleteResult::kLowestDefaultScore) ||
973 !HasMultipleWords(scored_results[0].suggestion()))
974 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:10975 }
[email protected]55ce8f12012-05-09 04:44:08976 if (scored_results.empty())
977 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
978 input_multiple_words, input_text,
979 is_keyword);
980 for (SuggestResults::const_iterator i(scored_results.begin());
981 i != scored_results.end(); ++i) {
982 AddMatchToMap(i->suggestion(), input_text, i->relevance(),
[email protected]51124552011-07-16 01:37:10983 AutocompleteMatch::SEARCH_HISTORY, did_not_accept_suggestion,
[email protected]55ce8f12012-05-09 04:44:08984 is_keyword, map);
[email protected]51124552011-07-16 01:37:10985 }
986}
987
[email protected]55ce8f12012-05-09 04:44:08988SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:10989 const HistoryResults& results,
990 bool base_prevent_inline_autocomplete,
991 bool input_multiple_words,
992 const string16& input_text,
993 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:48994 AutocompleteClassifier* classifier =
995 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:08996 SuggestResults scored_results;
[email protected]257ab712009-04-14 17:16:24997 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
998 ++i) {
[email protected]51124552011-07-16 01:37:10999 // Don't autocomplete multi-word queries that have only been seen once
1000 // unless the user has typed more than one word.
1001 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1002 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
1003
[email protected]ea3b9a502011-04-04 14:19:371004 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:101005 // when typed. For example, if the user searched for "google.com" and types
1006 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1007 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:481008 // NOTE: We don't check this in the following cases:
1009 // * When inline autocomplete is disabled, we won't be inline
1010 // autocompleting this term, so we don't need to worry about confusion as
1011 // much. This also prevents calling Classify() again from inside the
1012 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:101013 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:481014 // * When the user has typed the whole term, the "what you typed" history
1015 // match will outrank us for URL-like inputs anyway, so we need not do
1016 // anything special.
[email protected]51124552011-07-16 01:37:101017 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:371018 AutocompleteMatch match;
[email protected]72874a8d2011-05-11 03:48:541019 classifier->Classify(i->term, string16(), false, false, &match, NULL);
[email protected]2905f742011-10-13 03:51:581020 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:461021 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:371022 }
[email protected]51124552011-07-16 01:37:101023
1024 int relevance = CalculateRelevanceForHistory(i->time, is_keyword,
1025 prevent_inline_autocomplete);
[email protected]55ce8f12012-05-09 04:44:081026 scored_results.push_back(SuggestResult(i->term, relevance));
[email protected]257ab712009-04-14 17:16:241027 }
[email protected]51124552011-07-16 01:37:101028
1029 // History returns results sorted for us. However, we may have docked some
1030 // results' scores, so things are no longer in order. Do a stable sort to get
1031 // things back in order without otherwise disturbing results with equal
1032 // scores, then force the scores to be unique, so that the order in which
1033 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081034 std::stable_sort(scored_results.begin(), scored_results.end(),
1035 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101036 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081037 for (SuggestResults::iterator i(scored_results.begin());
1038 i != scored_results.end(); ++i) {
1039 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1040 i->set_relevance(last_relevance - 1);
1041 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101042 }
1043
[email protected]55ce8f12012-05-09 04:44:081044 return scored_results;
[email protected]257ab712009-04-14 17:16:241045}
1046
[email protected]55ce8f12012-05-09 04:44:081047void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
1048 bool is_keyword,
1049 MatchMap* map) {
[email protected]14710852013-02-05 23:45:411050 const string16& input_text =
1051 is_keyword ? keyword_input_.text() : input_.text();
[email protected]55ce8f12012-05-09 04:44:081052 for (size_t i = 0; i < results.size(); ++i) {
[email protected]d7ad4772012-06-01 03:12:541053 AddMatchToMap(results[i].suggestion(), input_text, results[i].relevance(),
[email protected]55ce8f12012-05-09 04:44:081054 AutocompleteMatch::SEARCH_SUGGEST, i, is_keyword, map);
[email protected]257ab712009-04-14 17:16:241055 }
initial.commit09911bf2008-07-26 23:55:291056}
1057
[email protected]382a0642012-06-06 06:13:521058int SearchProvider::GetVerbatimRelevance() const {
[email protected]dc6943b2012-06-19 06:39:561059 // Use the suggested verbatim relevance score if it is non-negative (valid),
1060 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281061 // and if it won't suppress verbatim, leaving no default provider matches.
1062 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561063 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281064 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561065 // Check for results on each verbatim calculation, as results from older
1066 // queries (on previous input) may be trimmed for failing to inline new input.
1067 if (verbatim_relevance_ >= 0 && !input_.prevent_inline_autocomplete() &&
[email protected]1beee342012-06-19 22:22:281068 (verbatim_relevance_ > 0 ||
1069 !default_suggest_results_.empty() ||
[email protected]dc6943b2012-06-19 06:39:561070 !default_navigation_results_.empty())) {
[email protected]d1f0a7f2012-06-05 10:26:421071 return verbatim_relevance_;
[email protected]dc6943b2012-06-19 06:39:561072 }
[email protected]382a0642012-06-06 06:13:521073 return CalculateRelevanceForVerbatim();
1074}
[email protected]d1f0a7f2012-06-05 10:26:421075
[email protected]382a0642012-06-06 06:13:521076int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471077 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361078 return 250;
1079
initial.commit09911bf2008-07-26 23:55:291080 switch (input_.type()) {
1081 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361082 case AutocompleteInput::QUERY:
1083 case AutocompleteInput::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131084 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291085
1086 case AutocompleteInput::REQUESTED_URL:
[email protected]52d08b12009-10-19 18:42:361087 return 1150;
initial.commit09911bf2008-07-26 23:55:291088
1089 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361090 return 850;
initial.commit09911bf2008-07-26 23:55:291091
1092 default:
1093 NOTREACHED();
1094 return 0;
1095 }
1096}
1097
[email protected]51124552011-07-16 01:37:101098int SearchProvider::CalculateRelevanceForHistory(
1099 const Time& time,
1100 bool is_keyword,
1101 bool prevent_inline_autocomplete) const {
[email protected]aa613d62010-11-09 20:40:181102 // The relevance of past searches falls off over time. There are two distinct
1103 // equations used. If the first equation is used (searches to the primary
[email protected]51124552011-07-16 01:37:101104 // provider that we want to inline autocomplete), the score starts at 1399 and
1105 // falls to 1300. If the second equation is used the relevance of a search 15
1106 // minutes ago is discounted 50 points, while the relevance of a search two
1107 // weeks ago is discounted 450 points.
[email protected]aa613d62010-11-09 20:40:181108 double elapsed_time = std::max((Time::Now() - time).InSecondsF(), 0.);
[email protected]51124552011-07-16 01:37:101109 bool is_primary_provider = providers_.is_primary_provider(is_keyword);
1110 if (is_primary_provider && !prevent_inline_autocomplete) {
[email protected]aa613d62010-11-09 20:40:181111 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101112 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181113 if (elapsed_time < autocomplete_time) {
[email protected]e17511f2011-07-13 14:09:181114 return (is_keyword ? 1599 : 1399) - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181115 std::pow(elapsed_time / autocomplete_time, 2.5));
1116 }
1117 elapsed_time -= autocomplete_time;
1118 }
1119
[email protected]c3a4bd992010-08-18 20:25:011120 const int score_discount =
1121 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291122
[email protected]6c85aa02009-02-27 12:08:091123 // Don't let scores go below 0. Negative relevance scores are meaningful in
1124 // a different way.
initial.commit09911bf2008-07-26 23:55:291125 int base_score;
[email protected]51124552011-07-16 01:37:101126 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361127 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101128 else
1129 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291130 return std::max(0, base_score - score_discount);
1131}
1132
[email protected]55ce8f12012-05-09 04:44:081133int SearchProvider::CalculateRelevanceForSuggestion(bool for_keyword) const {
1134 return !providers_.is_primary_provider(for_keyword) ? 100 :
1135 ((input_.type() == AutocompleteInput::URL) ? 300 : 600);
initial.commit09911bf2008-07-26 23:55:291136}
1137
[email protected]55ce8f12012-05-09 04:44:081138int SearchProvider::CalculateRelevanceForNavigation(bool for_keyword) const {
1139 return providers_.is_primary_provider(for_keyword) ? 800 : 150;
initial.commit09911bf2008-07-26 23:55:291140}
1141
[email protected]a2fedb1e2011-01-25 15:23:361142void SearchProvider::AddMatchToMap(const string16& query_string,
1143 const string16& input_text,
initial.commit09911bf2008-07-26 23:55:291144 int relevance,
[email protected]4c1fb7ec2008-11-13 00:19:001145 AutocompleteMatch::Type type,
initial.commit09911bf2008-07-26 23:55:291146 int accepted_suggestion,
[email protected]257ab712009-04-14 17:16:241147 bool is_keyword,
initial.commit09911bf2008-07-26 23:55:291148 MatchMap* map) {
[email protected]92513682011-09-01 06:16:521149 AutocompleteMatch match(this, relevance, false, type);
initial.commit09911bf2008-07-26 23:55:291150 std::vector<size_t> content_param_offsets;
[email protected]85b8d6f2012-05-08 20:53:471151 // Bail out now if we don't actually have a valid provider.
1152 match.keyword = is_keyword ?
[email protected]3954c3a2012-04-10 20:17:551153 providers_.keyword_provider() : providers_.default_provider();
[email protected]dbff446582012-10-30 00:20:261154 const TemplateURL* provider_url = match.GetTemplateURL(profile_, false);
[email protected]85b8d6f2012-05-08 20:53:471155 if (provider_url == NULL)
1156 return;
1157
[email protected]70833262011-01-05 23:40:441158 match.contents.assign(query_string);
[email protected]fb5153c52009-07-31 19:40:331159 // We do intra-string highlighting for suggestions - the suggested segment
1160 // will be highlighted, e.g. for input_text = "you" the suggestion may be
1161 // "youtube", so we'll bold the "tube" section: you*tube*.
1162 if (input_text != query_string) {
[email protected]fb5153c52009-07-31 19:40:331163 size_t input_position = match.contents.find(input_text);
[email protected]a2fedb1e2011-01-25 15:23:361164 if (input_position == string16::npos) {
[email protected]fb5153c52009-07-31 19:40:331165 // The input text is not a substring of the query string, e.g. input
1166 // text is "slasdot" and the query string is "slashdot", so we bold the
1167 // whole thing.
1168 match.contents_class.push_back(
1169 ACMatchClassification(0, ACMatchClassification::MATCH));
[email protected]ec2379162009-06-09 23:58:171170 } else {
[email protected]fb5153c52009-07-31 19:40:331171 // TODO(beng): ACMatchClassification::MATCH now seems to just mean
1172 // "bold" this. Consider modifying the terminology.
1173 // We don't iterate over the string here annotating all matches because
1174 // it looks odd to have every occurrence of a substring that may be as
1175 // short as a single character highlighted in a query suggestion result,
1176 // e.g. for input text "s" and query string "southwest airlines", it
1177 // looks odd if both the first and last s are highlighted.
1178 if (input_position != 0) {
1179 match.contents_class.push_back(
1180 ACMatchClassification(0, ACMatchClassification::NONE));
1181 }
1182 match.contents_class.push_back(
1183 ACMatchClassification(input_position, ACMatchClassification::DIM));
1184 size_t next_fragment_position = input_position + input_text.length();
1185 if (next_fragment_position < query_string.length()) {
1186 match.contents_class.push_back(
1187 ACMatchClassification(next_fragment_position,
1188 ACMatchClassification::NONE));
1189 }
[email protected]ec2379162009-06-09 23:58:171190 }
initial.commit09911bf2008-07-26 23:55:291191 } else {
[email protected]fb5153c52009-07-31 19:40:331192 // Otherwise, we're dealing with the "default search" result which has no
[email protected]70833262011-01-05 23:40:441193 // completion.
[email protected]fb5153c52009-07-31 19:40:331194 match.contents_class.push_back(
1195 ACMatchClassification(0, ACMatchClassification::NONE));
initial.commit09911bf2008-07-26 23:55:291196 }
1197
1198 // When the user forced a query, we need to make sure all the fill_into_edit
1199 // values preserve that property. Otherwise, if the user starts editing a
1200 // suggestion, non-Search results will suddenly appear.
[email protected]8f2249b2012-08-29 02:27:241201 if (input_.type() == AutocompleteInput::FORCED_QUERY)
[email protected]a2fedb1e2011-01-25 15:23:361202 match.fill_into_edit.assign(ASCIIToUTF16("?"));
[email protected]8f2249b2012-08-29 02:27:241203 if (is_keyword)
[email protected]033f3422012-03-13 21:24:181204 match.fill_into_edit.append(match.keyword + char16(' '));
[email protected]8f2249b2012-08-29 02:27:241205 if (!input_.prevent_inline_autocomplete() &&
1206 StartsWith(query_string, input_text, false)) {
1207 match.inline_autocomplete_offset =
1208 match.fill_into_edit.length() + input_text.length();
[email protected]c0048b42009-05-04 21:47:171209 }
initial.commit09911bf2008-07-26 23:55:291210 match.fill_into_edit.append(query_string);
initial.commit09911bf2008-07-26 23:55:291211
[email protected]85b8d6f2012-05-08 20:53:471212 const TemplateURLRef& search_url = provider_url->url_ref();
[email protected]360ba052012-04-04 17:26:131213 DCHECK(search_url.SupportsReplacement());
[email protected]bca359b2012-06-24 07:53:041214 match.search_terms_args.reset(
1215 new TemplateURLRef::SearchTermsArgs(query_string));
1216 match.search_terms_args->original_query = input_text;
1217 match.search_terms_args->accepted_suggestion = accepted_suggestion;
1218 // This is the destination URL sans assisted query stats. This must be set
1219 // so the AutocompleteController can properly de-dupe; the controller will
1220 // eventually overwrite it before it reaches the user.
1221 match.destination_url =
1222 GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get()));
initial.commit09911bf2008-07-26 23:55:291223
1224 // Search results don't look like URLs.
[email protected]2905f742011-10-13 03:51:581225 match.transition = is_keyword ?
1226 content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED;
initial.commit09911bf2008-07-26 23:55:291227
1228 // Try to add |match| to |map|. If a match for |query_string| is already in
1229 // |map|, replace it if |match| is more relevant.
1230 // NOTE: Keep this ToLower() call in sync with url_database.cc.
1231 const std::pair<MatchMap::iterator, bool> i = map->insert(
[email protected]a2fedb1e2011-01-25 15:23:361232 std::pair<string16, AutocompleteMatch>(
[email protected]503d03872011-05-06 08:36:261233 base::i18n::ToLower(query_string), match));
initial.commit09911bf2008-07-26 23:55:291234 // NOTE: We purposefully do a direct relevance comparison here instead of
1235 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items added
1236 // first" rather than "items alphabetically first" when the scores are equal.
1237 // The only case this matters is when a user has results with the same score
1238 // that differ only by capitalization; because the history system returns
1239 // results sorted by recency, this means we'll pick the most recent such
1240 // result even if the precision of our relevance score is too low to
1241 // distinguish the two.
1242 if (!i.second && (match.relevance > i.first->second.relevance))
1243 i.first->second = match;
1244}
1245
1246AutocompleteMatch SearchProvider::NavigationToMatch(
1247 const NavigationResult& navigation,
[email protected]257ab712009-04-14 17:16:241248 bool is_keyword) {
[email protected]14710852013-02-05 23:45:411249 const string16& input = is_keyword ? keyword_input_.text() : input_.text();
[email protected]55ce8f12012-05-09 04:44:081250 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]4c1fb7ec2008-11-13 00:19:001251 AutocompleteMatch::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081252 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551253
1254 // First look for the user's input inside the fill_into_edit as it would be
1255 // without trimming the scheme, so we can find matches at the beginning of the
1256 // scheme.
1257 const string16 untrimmed_fill_into_edit(
1258 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1259 StringForURLDisplay(navigation.url(), true, false)));
1260 const URLPrefix* prefix =
1261 URLPrefix::BestURLPrefix(untrimmed_fill_into_edit, input);
1262 size_t match_start = (prefix == NULL) ?
1263 untrimmed_fill_into_edit.find(input) : prefix->prefix.length();
1264 size_t inline_autocomplete_offset = (prefix == NULL) ?
1265 string16::npos : (match_start + input.length());
1266 bool trim_http = !HasHTTPScheme(input) && (!prefix || (match_start != 0));
1267
1268 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1269 // Otherwise, user edits to a suggestion would show non-Search results.
1270 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
1271 match.fill_into_edit = ASCIIToUTF16("?");
1272 if (inline_autocomplete_offset != string16::npos)
1273 ++inline_autocomplete_offset;
1274 }
1275
1276 const std::string languages(
1277 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1278 const net::FormatUrlTypes format_types =
1279 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1280 match.fill_into_edit +=
1281 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1282 net::FormatUrl(navigation.url(), languages, format_types,
1283 net::UnescapeRule::SPACES, NULL, NULL,
1284 &inline_autocomplete_offset));
1285 if (!input_.prevent_inline_autocomplete())
1286 match.inline_autocomplete_offset = inline_autocomplete_offset;
1287 DCHECK((match.inline_autocomplete_offset == string16::npos) ||
1288 (match.inline_autocomplete_offset <= match.fill_into_edit.length()));
1289
1290 match.contents = net::FormatUrl(navigation.url(), languages,
1291 format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1292 // If the first match in the untrimmed string was inside a scheme that we
1293 // trimmed, look for a subsequent match.
1294 if (match_start == string16::npos)
1295 match_start = match.contents.find(input);
1296 // Safe if |match_start| is npos; also safe if the input is longer than the
1297 // remaining contents after |match_start|.
1298 AutocompleteMatch::ClassifyLocationInString(match_start, input.length(),
1299 match.contents.length(), ACMatchClassification::URL,
1300 &match.contents_class);
initial.commit09911bf2008-07-26 23:55:291301
[email protected]55ce8f12012-05-09 04:44:081302 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551303 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1304 ACMatchClassification::NONE, &match.description_class);
initial.commit09911bf2008-07-26 23:55:291305 return match;
1306}
[email protected]4ab4c7c2010-11-24 04:49:341307
1308void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331309 // We're done when the timer isn't running, there are no suggest queries
1310 // pending, and we're not waiting on instant.
1311 done_ = (!timer_.IsRunning() && (suggest_results_pending_ == 0) &&
[email protected]b67d0a42012-09-04 20:57:351312 (instant_finalized_ ||
[email protected]249a0352012-11-26 21:06:191313 (!chrome::BrowserInstantController::IsInstantEnabled(profile_) &&
1314 !chrome::search::IsInstantExtendedAPIEnabled(profile_))));
[email protected]4ab4c7c2010-11-24 04:49:341315}