1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/autocomplete/autocomplete_match.h"
7 #include "base/i18n/time_formatting.h"
8 #include "base/logging.h"
9 #include "base/strings/string16.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/time/time.h"
14 #include "chrome/browser/autocomplete/autocomplete_provider.h"
15 #include "chrome/browser/search_engines/template_url.h"
16 #include "chrome/browser/search_engines/template_url_service.h"
17 #include "chrome/browser/search_engines/template_url_service_factory.h"
18 #include "content/public/common/url_constants.h"
19 #include "grit/theme_resources.h"
23 bool IsTrivialClassification(const ACMatchClassifications
& classifications
) {
24 return classifications
.empty() ||
25 ((classifications
.size() == 1) &&
26 (classifications
.back().style
== ACMatchClassification::NONE
));
31 // AutocompleteMatch ----------------------------------------------------------
34 const base::char16
AutocompleteMatch::kInvalidChars
[] = {
36 0x2028, // Line separator
37 0x2029, // Paragraph separator
41 AutocompleteMatch::AutocompleteMatch()
46 allowed_to_be_default_match(false),
47 transition(content::PAGE_TRANSITION_GENERATED
),
48 is_history_what_you_typed_match(false),
49 type(AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED
),
51 from_previous(false) {
54 AutocompleteMatch::AutocompleteMatch(AutocompleteProvider
* provider
,
62 allowed_to_be_default_match(false),
63 transition(content::PAGE_TRANSITION_TYPED
),
64 is_history_what_you_typed_match(false),
67 from_previous(false) {
70 AutocompleteMatch::AutocompleteMatch(const AutocompleteMatch
& match
)
71 : provider(match
.provider
),
72 relevance(match
.relevance
),
73 typed_count(match
.typed_count
),
74 deletable(match
.deletable
),
75 fill_into_edit(match
.fill_into_edit
),
76 inline_autocompletion(match
.inline_autocompletion
),
77 allowed_to_be_default_match(match
.allowed_to_be_default_match
),
78 destination_url(match
.destination_url
),
79 stripped_destination_url(match
.stripped_destination_url
),
80 contents(match
.contents
),
81 contents_class(match
.contents_class
),
82 description(match
.description
),
83 description_class(match
.description_class
),
84 transition(match
.transition
),
85 is_history_what_you_typed_match(match
.is_history_what_you_typed_match
),
87 associated_keyword(match
.associated_keyword
.get() ?
88 new AutocompleteMatch(*match
.associated_keyword
) : NULL
),
89 keyword(match
.keyword
),
90 starred(match
.starred
),
91 from_previous(match
.from_previous
),
92 search_terms_args(match
.search_terms_args
.get() ?
93 new TemplateURLRef::SearchTermsArgs(*match
.search_terms_args
) :
95 additional_info(match
.additional_info
),
96 duplicate_matches(match
.duplicate_matches
) {
99 AutocompleteMatch::~AutocompleteMatch() {
102 AutocompleteMatch
& AutocompleteMatch::operator=(
103 const AutocompleteMatch
& match
) {
107 provider
= match
.provider
;
108 relevance
= match
.relevance
;
109 typed_count
= match
.typed_count
;
110 deletable
= match
.deletable
;
111 fill_into_edit
= match
.fill_into_edit
;
112 inline_autocompletion
= match
.inline_autocompletion
;
113 allowed_to_be_default_match
= match
.allowed_to_be_default_match
;
114 destination_url
= match
.destination_url
;
115 stripped_destination_url
= match
.stripped_destination_url
;
116 contents
= match
.contents
;
117 contents_class
= match
.contents_class
;
118 description
= match
.description
;
119 description_class
= match
.description_class
;
120 transition
= match
.transition
;
121 is_history_what_you_typed_match
= match
.is_history_what_you_typed_match
;
123 associated_keyword
.reset(match
.associated_keyword
.get() ?
124 new AutocompleteMatch(*match
.associated_keyword
) : NULL
);
125 keyword
= match
.keyword
;
126 starred
= match
.starred
;
127 from_previous
= match
.from_previous
;
128 search_terms_args
.reset(match
.search_terms_args
.get() ?
129 new TemplateURLRef::SearchTermsArgs(*match
.search_terms_args
) : NULL
);
130 additional_info
= match
.additional_info
;
131 duplicate_matches
= match
.duplicate_matches
;
136 int AutocompleteMatch::TypeToIcon(Type type
) {
152 IDR_OMNIBOX_EXTENSION_APP
,
156 COMPILE_ASSERT(arraysize(icons
) == AutocompleteMatchType::NUM_TYPES
,
157 icons_array_must_match_type_enum
);
162 int AutocompleteMatch::TypeToLocationBarIcon(Type type
) {
163 int id
= TypeToIcon(type
);
164 if (id
== IDR_OMNIBOX_HTTP
)
165 return IDR_LOCATION_BAR_HTTP
;
170 bool AutocompleteMatch::MoreRelevant(const AutocompleteMatch
& elem1
,
171 const AutocompleteMatch
& elem2
) {
172 // For equal-relevance matches, we sort alphabetically, so that providers
173 // who return multiple elements at the same priority get a "stable" sort
174 // across multiple updates.
175 return (elem1
.relevance
== elem2
.relevance
) ?
176 (elem1
.contents
< elem2
.contents
) : (elem1
.relevance
> elem2
.relevance
);
180 bool AutocompleteMatch::DestinationsEqual(const AutocompleteMatch
& elem1
,
181 const AutocompleteMatch
& elem2
) {
182 if (elem1
.stripped_destination_url
.is_empty() &&
183 elem2
.stripped_destination_url
.is_empty())
185 return elem1
.stripped_destination_url
== elem2
.stripped_destination_url
;
189 void AutocompleteMatch::ClassifyMatchInString(
190 const base::string16
& find_text
,
191 const base::string16
& text
,
193 ACMatchClassifications
* classification
) {
194 ClassifyLocationInString(text
.find(find_text
), find_text
.length(),
195 text
.length(), style
, classification
);
199 void AutocompleteMatch::ClassifyLocationInString(
200 size_t match_location
,
202 size_t overall_length
,
204 ACMatchClassifications
* classification
) {
205 classification
->clear();
207 // Don't classify anything about an empty string
208 // (AutocompleteMatch::Validate() checks this).
209 if (overall_length
== 0)
212 // Mark pre-match portion of string (if any).
213 if (match_location
!= 0) {
214 classification
->push_back(ACMatchClassification(0, style
));
217 // Mark matching portion of string.
218 if (match_location
== base::string16::npos
) {
219 // No match, above classification will suffice for whole string.
222 // Classifying an empty match makes no sense and will lead to validation
224 DCHECK_GT(match_length
, 0U);
225 classification
->push_back(ACMatchClassification(match_location
,
226 (style
| ACMatchClassification::MATCH
) & ~ACMatchClassification::DIM
));
228 // Mark post-match portion of string (if any).
229 const size_t after_match(match_location
+ match_length
);
230 if (after_match
< overall_length
) {
231 classification
->push_back(ACMatchClassification(after_match
, style
));
236 AutocompleteMatch::ACMatchClassifications
237 AutocompleteMatch::MergeClassifications(
238 const ACMatchClassifications
& classifications1
,
239 const ACMatchClassifications
& classifications2
) {
240 // We must return the empty vector only if both inputs are truly empty.
241 // The result of merging an empty vector with a single (0, NONE)
242 // classification is the latter one-entry vector.
243 if (IsTrivialClassification(classifications1
))
244 return classifications2
.empty() ? classifications1
: classifications2
;
245 if (IsTrivialClassification(classifications2
))
246 return classifications1
;
248 ACMatchClassifications output
;
249 for (ACMatchClassifications::const_iterator i
= classifications1
.begin(),
250 j
= classifications2
.begin(); i
!= classifications1
.end();) {
251 AutocompleteMatch::AddLastClassificationIfNecessary(&output
,
252 std::max(i
->offset
, j
->offset
), i
->style
| j
->style
);
253 const size_t next_i_offset
= (i
+ 1) == classifications1
.end() ?
254 static_cast<size_t>(-1) : (i
+ 1)->offset
;
255 const size_t next_j_offset
= (j
+ 1) == classifications2
.end() ?
256 static_cast<size_t>(-1) : (j
+ 1)->offset
;
257 if (next_i_offset
>= next_j_offset
)
259 if (next_j_offset
>= next_i_offset
)
267 std::string
AutocompleteMatch::ClassificationsToString(
268 const ACMatchClassifications
& classifications
) {
269 std::string serialized_classifications
;
270 for (size_t i
= 0; i
< classifications
.size(); ++i
) {
272 serialized_classifications
+= ',';
273 serialized_classifications
+= base::IntToString(classifications
[i
].offset
) +
274 ',' + base::IntToString(classifications
[i
].style
);
276 return serialized_classifications
;
280 ACMatchClassifications
AutocompleteMatch::ClassificationsFromString(
281 const std::string
& serialized_classifications
) {
282 ACMatchClassifications classifications
;
283 std::vector
<std::string
> tokens
;
284 Tokenize(serialized_classifications
, ",", &tokens
);
285 DCHECK(!(tokens
.size() & 1)); // The number of tokens should be even.
286 for (size_t i
= 0; i
< tokens
.size(); i
+= 2) {
287 int classification_offset
= 0;
288 int classification_style
= ACMatchClassification::NONE
;
289 if (!base::StringToInt(tokens
[i
], &classification_offset
) ||
290 !base::StringToInt(tokens
[i
+ 1], &classification_style
)) {
292 return classifications
;
294 classifications
.push_back(ACMatchClassification(classification_offset
,
295 classification_style
));
297 return classifications
;
301 void AutocompleteMatch::AddLastClassificationIfNecessary(
302 ACMatchClassifications
* classifications
,
305 DCHECK(classifications
);
306 if (classifications
->empty() || classifications
->back().style
!= style
) {
307 DCHECK(classifications
->empty() ||
308 (offset
> classifications
->back().offset
));
309 classifications
->push_back(ACMatchClassification(offset
, style
));
314 base::string16
AutocompleteMatch::SanitizeString(const base::string16
& text
) {
315 // NOTE: This logic is mirrored by |sanitizeString()| in
316 // omnibox_custom_bindings.js.
317 base::string16 result
;
318 base::TrimWhitespace(text
, base::TRIM_LEADING
, &result
);
319 base::RemoveChars(result
, kInvalidChars
, &result
);
324 bool AutocompleteMatch::IsSearchType(Type type
) {
325 return type
== AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED
||
326 type
== AutocompleteMatchType::SEARCH_HISTORY
||
327 type
== AutocompleteMatchType::SEARCH_SUGGEST
||
328 type
== AutocompleteMatchType::SEARCH_OTHER_ENGINE
||
329 IsSpecializedSearchType(type
);
333 bool AutocompleteMatch::IsSpecializedSearchType(Type type
) {
334 return type
== AutocompleteMatchType::SEARCH_SUGGEST_ENTITY
||
335 type
== AutocompleteMatchType::SEARCH_SUGGEST_INFINITE
||
336 type
== AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED
||
337 type
== AutocompleteMatchType::SEARCH_SUGGEST_PROFILE
;
340 void AutocompleteMatch::ComputeStrippedDestinationURL(Profile
* profile
) {
341 stripped_destination_url
= destination_url
;
342 if (!stripped_destination_url
.is_valid())
345 // If the destination URL looks like it was generated from a TemplateURL,
346 // remove all substitutions other than the search terms. This allows us
347 // to eliminate cases like past search URLs from history that differ only
348 // by some obscure query param from each other or from the search/keyword
350 TemplateURL
* template_url
= GetTemplateURL(profile
, true);
351 if (template_url
!= NULL
&& template_url
->SupportsReplacement()) {
352 base::string16 search_terms
;
353 if (template_url
->ExtractSearchTermsFromURL(stripped_destination_url
,
355 stripped_destination_url
=
356 GURL(template_url
->url_ref().ReplaceSearchTerms(
357 TemplateURLRef::SearchTermsArgs(search_terms
)));
361 // |replacements| keeps all the substitions we're going to make to
362 // from {destination_url} to {stripped_destination_url}. |need_replacement|
363 // is a helper variable that helps us keep track of whether we need
364 // to apply the replacement.
365 bool needs_replacement
= false;
366 GURL::Replacements replacements
;
368 // Remove the www. prefix from the host.
369 static const char prefix
[] = "www.";
370 static const size_t prefix_len
= arraysize(prefix
) - 1;
371 std::string host
= stripped_destination_url
.host();
372 if (host
.compare(0, prefix_len
, prefix
) == 0) {
373 host
= host
.substr(prefix_len
);
374 replacements
.SetHostStr(host
);
375 needs_replacement
= true;
378 // Replace https protocol with http protocol.
379 if (stripped_destination_url
.SchemeIs(content::kHttpsScheme
)) {
380 replacements
.SetScheme(content::kHttpScheme
,
381 url::Component(0, strlen(content::kHttpScheme
)));
382 needs_replacement
= true;
385 if (needs_replacement
)
386 stripped_destination_url
= stripped_destination_url
.ReplaceComponents(
390 void AutocompleteMatch::GetKeywordUIState(Profile
* profile
,
391 base::string16
* keyword
,
392 bool* is_keyword_hint
) const {
393 *is_keyword_hint
= associated_keyword
.get() != NULL
;
394 keyword
->assign(*is_keyword_hint
? associated_keyword
->keyword
:
395 GetSubstitutingExplicitlyInvokedKeyword(profile
));
398 base::string16
AutocompleteMatch::GetSubstitutingExplicitlyInvokedKeyword(
399 Profile
* profile
) const {
400 if (transition
!= content::PAGE_TRANSITION_KEYWORD
)
401 return base::string16();
402 const TemplateURL
* t_url
= GetTemplateURL(profile
, false);
403 return (t_url
&& t_url
->SupportsReplacement()) ? keyword
: base::string16();
406 TemplateURL
* AutocompleteMatch::GetTemplateURL(
407 Profile
* profile
, bool allow_fallback_to_destination_host
) const {
409 TemplateURLService
* template_url_service
=
410 TemplateURLServiceFactory::GetForProfile(profile
);
411 if (template_url_service
== NULL
)
413 TemplateURL
* template_url
= keyword
.empty() ? NULL
:
414 template_url_service
->GetTemplateURLForKeyword(keyword
);
415 if (template_url
== NULL
&& allow_fallback_to_destination_host
) {
416 template_url
= template_url_service
->GetTemplateURLForHost(
417 destination_url
.host());
422 void AutocompleteMatch::RecordAdditionalInfo(const std::string
& property
,
423 const std::string
& value
) {
424 DCHECK(!property
.empty());
425 DCHECK(!value
.empty());
426 additional_info
[property
] = value
;
429 void AutocompleteMatch::RecordAdditionalInfo(const std::string
& property
,
431 RecordAdditionalInfo(property
, base::IntToString(value
));
434 void AutocompleteMatch::RecordAdditionalInfo(const std::string
& property
,
435 const base::Time
& value
) {
436 RecordAdditionalInfo(property
,
438 base::TimeFormatShortDateAndTime(value
)));
441 std::string
AutocompleteMatch::GetAdditionalInfo(
442 const std::string
& property
) const {
443 AdditionalInfo::const_iterator
i(additional_info
.find(property
));
444 return (i
== additional_info
.end()) ? std::string() : i
->second
;
447 bool AutocompleteMatch::IsVerbatimType() const {
448 const bool is_keyword_verbatim_match
=
449 (type
== AutocompleteMatchType::SEARCH_OTHER_ENGINE
&&
451 provider
->type() == AutocompleteProvider::TYPE_SEARCH
);
452 return type
== AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED
||
453 type
== AutocompleteMatchType::URL_WHAT_YOU_TYPED
||
454 is_keyword_verbatim_match
;
457 bool AutocompleteMatch::SupportsDeletion() const {
461 for (ACMatches::const_iterator
it(duplicate_matches
.begin());
462 it
!= duplicate_matches
.end(); ++it
) {
470 void AutocompleteMatch::Validate() const {
471 ValidateClassifications(contents
, contents_class
);
472 ValidateClassifications(description
, description_class
);
475 void AutocompleteMatch::ValidateClassifications(
476 const base::string16
& text
,
477 const ACMatchClassifications
& classifications
) const {
479 DCHECK(classifications
.empty());
483 // The classifications should always cover the whole string.
484 DCHECK(!classifications
.empty()) << "No classification for \"" << text
<< '"';
485 DCHECK_EQ(0U, classifications
[0].offset
)
486 << "Classification misses beginning for \"" << text
<< '"';
487 if (classifications
.size() == 1)
490 // The classifications should always be sorted.
491 size_t last_offset
= classifications
[0].offset
;
492 for (ACMatchClassifications::const_iterator
i(classifications
.begin() + 1);
493 i
!= classifications
.end(); ++i
) {
494 const char* provider_name
= provider
? provider
->GetName() : "None";
495 DCHECK_GT(i
->offset
, last_offset
)
496 << " Classification for \"" << text
<< "\" with offset of " << i
->offset
497 << " is unsorted in relation to last offset of " << last_offset
498 << ". Provider: " << provider_name
<< ".";
499 DCHECK_LT(i
->offset
, text
.length())
500 << " Classification of [" << i
->offset
<< "," << text
.length()
501 << "] is out of bounds for \"" << text
<< "\". Provider: "
502 << provider_name
<< ".";
503 last_offset
= i
->offset
;