Automated Commit: Committing new LKGM version 6953.0.0 for chromeos.
[chromium-blink-merge.git] / components / omnibox / autocomplete_match.h
blob93c509741c901163ee66bb30ca67af3ae61c4194
1 // Copyright 2014 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 #ifndef COMPONENTS_OMNIBOX_AUTOCOMPLETE_MATCH_H_
6 #define COMPONENTS_OMNIBOX_AUTOCOMPLETE_MATCH_H_
8 #include <map>
9 #include <string>
10 #include <vector>
12 #include "base/memory/scoped_ptr.h"
13 #include "components/omnibox/autocomplete_match_type.h"
14 #include "components/search_engines/template_url.h"
15 #include "ui/base/page_transition_types.h"
16 #include "url/gurl.h"
18 class AutocompleteProvider;
19 class SuggestionAnswer;
20 class TemplateURL;
21 class TemplateURLService;
23 namespace base {
24 class Time;
25 } // namespace base
27 const char kACMatchPropertyInputText[] = "input text";
28 const char kACMatchPropertyContentsPrefix[] = "match contents prefix";
29 const char kACMatchPropertyContentsStartIndex[] = "match contents start index";
31 // AutocompleteMatch ----------------------------------------------------------
33 // A single result line with classified spans. The autocomplete popup displays
34 // the 'contents' and the 'description' (the description is optional) in the
35 // autocomplete dropdown, and fills in 'fill_into_edit' into the textbox when
36 // that line is selected. fill_into_edit may be the same as 'description' for
37 // things like URLs, but may be different for searches or other providers. For
38 // example, a search result may say "Search for asdf" as the description, but
39 // "asdf" should appear in the box.
40 struct AutocompleteMatch {
41 // Autocomplete matches contain strings that are classified according to a
42 // separate vector of styles. This vector associates flags with particular
43 // string segments, and must be in sorted order. All text must be associated
44 // with some kind of classification. Even if a match has no distinct
45 // segments, its vector should contain an entry at offset 0 with no flags.
47 // Example: The user typed "goog"
48 // http://www.google.com/ Google
49 // ^ ^ ^ ^ ^
50 // 0, | 15, | 4,
51 // 11,match 0,match
53 // This structure holds the classification information for each span.
54 struct ACMatchClassification {
55 // The values in here are not mutually exclusive -- use them like a
56 // bitfield. This also means we use "int" instead of this enum type when
57 // passing the values around, so the compiler doesn't complain.
58 enum Style {
59 NONE = 0,
60 URL = 1 << 0, // A URL
61 MATCH = 1 << 1, // A match for the user's search term
62 DIM = 1 << 2, // "Helper text"
65 ACMatchClassification(size_t offset, int style)
66 : offset(offset),
67 style(style) {
70 // Offset within the string that this classification starts
71 size_t offset;
73 int style;
76 typedef std::vector<ACMatchClassification> ACMatchClassifications;
78 // Type used by providers to attach additional, optional information to
79 // an AutocompleteMatch.
80 typedef std::map<std::string, std::string> AdditionalInfo;
82 // The type of this match.
83 typedef AutocompleteMatchType::Type Type;
85 // Null-terminated array of characters that are not valid within |contents|
86 // and |description| strings.
87 static const base::char16 kInvalidChars[];
89 AutocompleteMatch();
90 AutocompleteMatch(AutocompleteProvider* provider,
91 int relevance,
92 bool deletable,
93 Type type);
94 AutocompleteMatch(const AutocompleteMatch& match);
95 ~AutocompleteMatch();
97 // Converts |type| to a string representation. Used in logging and debugging.
98 AutocompleteMatch& operator=(const AutocompleteMatch& match);
100 // Converts |type| to a resource identifier for the appropriate icon for this
101 // type to show in the completion popup.
102 static int TypeToIcon(Type type);
104 // Comparison function for determining when one match is better than another.
105 static bool MoreRelevant(const AutocompleteMatch& elem1,
106 const AutocompleteMatch& elem2);
108 // Comparison function for removing matches with duplicate destinations.
109 // Destinations are compared using |stripped_destination_url|. Pairs of
110 // matches with empty destinations are treated as differing, since empty
111 // destinations are expected for non-navigable matches.
112 static bool DestinationsEqual(const AutocompleteMatch& elem1,
113 const AutocompleteMatch& elem2);
115 // Helper functions for classes creating matches:
116 // Fills in the classifications for |text|, using |style| as the base style
117 // and marking the first instance of |find_text| as a match. (This match
118 // will also not be dimmed, if |style| has DIM set.)
119 static void ClassifyMatchInString(const base::string16& find_text,
120 const base::string16& text,
121 int style,
122 ACMatchClassifications* classifications);
124 // Similar to ClassifyMatchInString(), but for cases where the range to mark
125 // as matching is already known (avoids calling find()). This can be helpful
126 // when find() would be misleading (e.g. you want to mark the second match in
127 // a string instead of the first).
128 static void ClassifyLocationInString(size_t match_location,
129 size_t match_length,
130 size_t overall_length,
131 int style,
132 ACMatchClassifications* classifications);
134 // Returns a new vector of classifications containing the merged contents of
135 // |classifications1| and |classifications2|.
136 static ACMatchClassifications MergeClassifications(
137 const ACMatchClassifications& classifications1,
138 const ACMatchClassifications& classifications2);
140 // Converts classifications to and from a serialized string representation
141 // (using comma-separated integers to sequentially list positions and styles).
142 static std::string ClassificationsToString(
143 const ACMatchClassifications& classifications);
144 static ACMatchClassifications ClassificationsFromString(
145 const std::string& serialized_classifications);
147 // Adds a classification to the end of |classifications| iff its style is
148 // different from the last existing classification. |offset| must be larger
149 // than the offset of the last classification in |classifications|.
150 static void AddLastClassificationIfNecessary(
151 ACMatchClassifications* classifications,
152 size_t offset,
153 int style);
155 // Removes invalid characters from |text|. Should be called on strings coming
156 // from external sources (such as extensions) before assigning to |contents|
157 // or |description|.
158 static base::string16 SanitizeString(const base::string16& text);
160 // Convenience function to check if |type| is a search (as opposed to a URL or
161 // an extension).
162 static bool IsSearchType(Type type);
164 // Convenience function to check if |type| is a special search suggest type -
165 // like entity, personalized, profile or postfix.
166 static bool IsSpecializedSearchType(Type type);
168 // A static version GetTemplateURL() that takes the match's keyword and
169 // match's hostname as parameters. In short, returns the TemplateURL
170 // associated with |keyword| if it exists; otherwise returns the TemplateURL
171 // associated with |host| if it exists.
172 static TemplateURL* GetTemplateURLWithKeyword(
173 TemplateURLService* template_url_service,
174 const base::string16& keyword,
175 const std::string& host);
177 // Returns |url| altered by stripping off "www.", converting https protocol
178 // to http, and stripping excess query parameters. These conversions are
179 // merely to allow comparisons to remove likely duplicates; these URLs are
180 // not used as actual destination URLs. If |template_url_service| is not
181 // NULL, it is used to get a template URL corresponding to this match. If
182 // the match's keyword is known, it can be passed in. Otherwise, it can be
183 // left empty and the template URL (if any) is determined from the
184 // destination's hostname. The template URL is used to strip off query args
185 // other than the search terms themselves that would otherwise prevent doing
186 // proper deduping.
187 static GURL GURLToStrippedGURL(const GURL& url,
188 TemplateURLService* template_url_service,
189 const base::string16& keyword);
191 // Computes the stripped destination URL (via GURLToStrippedGURL()) and
192 // stores the result in |stripped_destination_url|.
193 void ComputeStrippedDestinationURL(TemplateURLService* template_url_service);
195 // Sets |allowed_to_be_default_match| to true if this match is effectively
196 // the URL-what-you-typed match (i.e., would be dupped against the UWYT
197 // match when AutocompleteResult merges matches). |canonical_input_url| is
198 // the AutocompleteInput interpreted as a URL (i.e.,
199 // AutocompleteInput::canonicalized_url()).
200 void EnsureUWYTIsAllowedToBeDefault(const GURL& canonical_input_url,
201 TemplateURLService* template_url_service);
203 // Gets data relevant to whether there should be any special keyword-related
204 // UI shown for this match. If this match represents a selected keyword, i.e.
205 // the UI should be "in keyword mode", |keyword| will be set to the keyword
206 // and |is_keyword_hint| will be set to false. If this match has a non-NULL
207 // |associated_keyword|, i.e. we should show a "Press [tab] to search ___"
208 // hint and allow the user to toggle into keyword mode, |keyword| will be set
209 // to the associated keyword and |is_keyword_hint| will be set to true. Note
210 // that only one of these states can be in effect at once. In all other
211 // cases, |keyword| will be cleared, even when our member variable |keyword|
212 // is non-empty -- such as with non-substituting keywords or matches that
213 // represent searches using the default search engine. See also
214 // GetSubstitutingExplicitlyInvokedKeyword().
215 void GetKeywordUIState(TemplateURLService* template_url_service,
216 base::string16* keyword,
217 bool* is_keyword_hint) const;
219 // Returns |keyword|, but only if it represents a substituting keyword that
220 // the user has explicitly invoked. If for example this match represents a
221 // search with the default search engine (and the user didn't explicitly
222 // invoke its keyword), this returns the empty string. The result is that
223 // this function returns a non-empty string in the same cases as when the UI
224 // should show up as being "in keyword mode".
225 base::string16 GetSubstitutingExplicitlyInvokedKeyword(
226 TemplateURLService* template_url_service) const;
228 // Returns the TemplateURL associated with this match. This may be NULL if
229 // the match has no keyword OR if the keyword no longer corresponds to a valid
230 // TemplateURL. See comments on |keyword| below.
231 // If |allow_fallback_to_destination_host| is true and the keyword does
232 // not map to a valid TemplateURL, we'll then check for a TemplateURL that
233 // corresponds to the destination_url's hostname.
234 TemplateURL* GetTemplateURL(TemplateURLService* template_url_service,
235 bool allow_fallback_to_destination_host) const;
237 // Adds optional information to the |additional_info| dictionary.
238 void RecordAdditionalInfo(const std::string& property,
239 const std::string& value);
240 void RecordAdditionalInfo(const std::string& property, int value);
241 void RecordAdditionalInfo(const std::string& property,
242 const base::Time& value);
244 // Returns the value recorded for |property| in the |additional_info|
245 // dictionary. Returns the empty string if no such value exists.
246 std::string GetAdditionalInfo(const std::string& property) const;
248 // Returns whether this match is a "verbatim" match: a URL navigation directly
249 // to the user's input, a search for the user's input with the default search
250 // engine, or a "keyword mode" search for the query portion of the user's
251 // input. Note that rare or unusual types that could be considered verbatim,
252 // such as keyword engine matches or extension-provided matches, aren't
253 // detected by this IsVerbatimType, as the user will not be able to infer
254 // what will happen when he or she presses enter in those cases if the match
255 // is not shown.
256 bool IsVerbatimType() const;
258 // Returns whether this match or any duplicate of this match can be deleted.
259 // This is used to decide whether we should call DeleteMatch().
260 bool SupportsDeletion() const;
262 // The provider of this match, used to remember which provider the user had
263 // selected when the input changes. This may be NULL, in which case there is
264 // no provider (or memory of the user's selection).
265 AutocompleteProvider* provider;
267 // The relevance of this match. See table in autocomplete.h for scores
268 // returned by various providers. This is used to rank matches among all
269 // responding providers, so different providers must be carefully tuned to
270 // supply matches with appropriate relevance.
272 // TODO(pkasting): http://b/1111299 This should be calculated algorithmically,
273 // rather than being a fairly fixed value defined by the table above.
274 int relevance;
276 // How many times this result was typed in / selected from the omnibox.
277 // Only set for some providers and result_types. If it is not set,
278 // its value is -1. At the time of writing this comment, it is only
279 // set for matches from HistoryURL and HistoryQuickProvider.
280 int typed_count;
282 // True if the user should be able to delete this match.
283 bool deletable;
285 // This string is loaded into the location bar when the item is selected
286 // by pressing the arrow keys. This may be different than a URL, for example,
287 // for search suggestions, this would just be the search terms.
288 base::string16 fill_into_edit;
290 // The inline autocompletion to display after the user's typing in the
291 // omnibox, if this match becomes the default match. It may be empty.
292 base::string16 inline_autocompletion;
294 // If false, the omnibox should prevent this match from being the
295 // default match. Providers should set this to true only if the
296 // user's input, plus any inline autocompletion on this match, would
297 // lead the user to expect a navigation to this match's destination.
298 // For example, with input "foo", a search for "bar" or navigation
299 // to "bar.com" should not set this flag; a navigation to "foo.com"
300 // should only set this flag if ".com" will be inline autocompleted;
301 // and a navigation to "foo/" (an intranet host) or search for "foo"
302 // should set this flag.
303 bool allowed_to_be_default_match;
305 // The URL to actually load when the autocomplete item is selected. This URL
306 // should be canonical so we can compare URLs with strcmp to avoid dupes.
307 // It may be empty if there is no possible navigation.
308 GURL destination_url;
310 // The destination URL with "www." stripped off for better dupe finding.
311 GURL stripped_destination_url;
313 // The main text displayed in the address bar dropdown.
314 base::string16 contents;
315 ACMatchClassifications contents_class;
317 // Additional helper text for each entry, such as a title or description.
318 base::string16 description;
319 ACMatchClassifications description_class;
321 // TODO(jdonnelly): Remove the first two properties once the downstream
322 // clients are using the SuggestionAnswer.
323 // A rich-format version of the display for the dropdown.
324 base::string16 answer_contents;
325 base::string16 answer_type;
326 scoped_ptr<SuggestionAnswer> answer;
328 // The transition type to use when the user opens this match. By default
329 // this is TYPED. Providers whose matches do not look like URLs should set
330 // it to GENERATED.
331 ui::PageTransition transition;
333 // True when this match is the "what you typed" match from the history
334 // system.
335 bool is_history_what_you_typed_match;
337 // Type of this match.
338 Type type;
340 // Set with a keyword provider match if this match can show a keyword hint.
341 // For example, if this is a SearchProvider match for "www.amazon.com",
342 // |associated_keyword| could be a KeywordProvider match for "amazon.com".
343 scoped_ptr<AutocompleteMatch> associated_keyword;
345 // The keyword of the TemplateURL the match originated from. This is nonempty
346 // for both explicit "keyword mode" matches as well as matches for the default
347 // search provider (so, any match for which we're doing substitution); it
348 // doesn't imply (alone) that the UI is going to show a keyword hint or
349 // keyword mode. For that, see GetKeywordUIState() or
350 // GetSubstitutingExplicitlyInvokedKeyword().
352 // CAUTION: The TemplateURL associated with this keyword may be deleted or
353 // modified while the AutocompleteMatch is alive. This means anyone who
354 // accesses it must perform any necessary sanity checks before blindly using
355 // it!
356 base::string16 keyword;
358 // True if this match is from a previous result.
359 bool from_previous;
361 // Optional search terms args. If present,
362 // AutocompleteController::UpdateAssistedQueryStats() will incorporate this
363 // data with additional data it calculates and pass the completed struct to
364 // TemplateURLRef::ReplaceSearchTerms() to reset the match's |destination_url|
365 // after the complete set of matches in the AutocompleteResult has been chosen
366 // and sorted. Most providers will leave this as NULL, which will cause the
367 // AutocompleteController to do no additional transformations.
368 scoped_ptr<TemplateURLRef::SearchTermsArgs> search_terms_args;
370 // Information dictionary into which each provider can optionally record a
371 // property and associated value and which is presented in chrome://omnibox.
372 AdditionalInfo additional_info;
374 // A list of matches culled during de-duplication process, retained to
375 // ensure if a match is deleted, the duplicates are deleted as well.
376 std::vector<AutocompleteMatch> duplicate_matches;
378 #ifndef NDEBUG
379 // Does a data integrity check on this match.
380 void Validate() const;
382 // Checks one text/classifications pair for valid values.
383 void ValidateClassifications(
384 const base::string16& text,
385 const ACMatchClassifications& classifications) const;
386 #endif
389 typedef AutocompleteMatch::ACMatchClassification ACMatchClassification;
390 typedef std::vector<ACMatchClassification> ACMatchClassifications;
391 typedef std::vector<AutocompleteMatch> ACMatches;
393 #endif // COMPONENTS_OMNIBOX_AUTOCOMPLETE_MATCH_H_