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