Upstream version 10.38.222.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / autocomplete / base_search_provider.h
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.
4 //
5 // This class contains common functionality for search-based autocomplete
6 // providers. Search provider and zero suggest provider both use it for common
7 // functionality.
8
9 #ifndef CHROME_BROWSER_AUTOCOMPLETE_BASE_SEARCH_PROVIDER_H_
10 #define CHROME_BROWSER_AUTOCOMPLETE_BASE_SEARCH_PROVIDER_H_
11
12 #include <map>
13 #include <string>
14 #include <utility>
15 #include <vector>
16
17 #include "base/memory/scoped_vector.h"
18 #include "base/strings/string16.h"
19 #include "components/metrics/proto/omnibox_event.pb.h"
20 #include "components/omnibox/autocomplete_input.h"
21 #include "components/omnibox/autocomplete_match.h"
22 #include "components/omnibox/autocomplete_provider.h"
23 #include "components/omnibox/search_suggestion_parser.h"
24
25 class GURL;
26 class Profile;
27 class SearchTermsData;
28 class SuggestionDeletionHandler;
29 class TemplateURL;
30 class TemplateURLService;
31
32 namespace base {
33 class DictionaryValue;
34 class ListValue;
35 class Value;
36 }
37
38 // Base functionality for receiving suggestions from a search engine.
39 // This class is abstract and should only be used as a base for other
40 // autocomplete providers utilizing its functionality.
41 class BaseSearchProvider : public AutocompleteProvider {
42  public:
43   // ID used in creating URLFetcher for default provider's suggest results.
44   static const int kDefaultProviderURLFetcherID;
45
46   // ID used in creating URLFetcher for keyword provider's suggest results.
47   static const int kKeywordProviderURLFetcherID;
48
49   // ID used in creating URLFetcher for deleting suggestion results.
50   static const int kDeletionURLFetcherID;
51
52   BaseSearchProvider(TemplateURLService* template_url_service,
53                      Profile* profile,
54                      AutocompleteProvider::Type type);
55
56   // Returns whether |match| is flagged as a query that should be prefetched.
57   static bool ShouldPrefetch(const AutocompleteMatch& match);
58
59   // Returns a simpler AutocompleteMatch suitable for persistence like in
60   // ShortcutsDatabase.  This wrapper function uses a number of default values
61   // that may or may not be appropriate for your needs.
62   // NOTE: Use with care. Most likely you want the other CreateSearchSuggestion
63   // with protected access.
64   static AutocompleteMatch CreateSearchSuggestion(
65       const base::string16& suggestion,
66       AutocompleteMatchType::Type type,
67       bool from_keyword_provider,
68       const TemplateURL* template_url,
69       const SearchTermsData& search_terms_data);
70
71   // AutocompleteProvider:
72   virtual void Stop(bool clear_cached_results) OVERRIDE;
73   virtual void DeleteMatch(const AutocompleteMatch& match) OVERRIDE;
74   virtual void AddProviderInfo(ProvidersInfo* provider_info) const OVERRIDE;
75
76   bool field_trial_triggered_in_session() const {
77     return field_trial_triggered_in_session_;
78   }
79
80  protected:
81   // The following keys are used to record additional information on matches.
82
83   // We annotate our AutocompleteMatches with whether their relevance scores
84   // were server-provided using this key in the |additional_info| field.
85   static const char kRelevanceFromServerKey[];
86
87   // Indicates whether the server said a match should be prefetched.
88   static const char kShouldPrefetchKey[];
89
90   // Used to store metadata from the server response, which is needed for
91   // prefetching.
92   static const char kSuggestMetadataKey[];
93
94   // Used to store a deletion request url for server-provided suggestions.
95   static const char kDeletionUrlKey[];
96
97   // These are the values for the above keys.
98   static const char kTrue[];
99   static const char kFalse[];
100
101   virtual ~BaseSearchProvider();
102
103   typedef std::pair<base::string16, std::string> MatchKey;
104   typedef std::map<MatchKey, AutocompleteMatch> MatchMap;
105   typedef ScopedVector<SuggestionDeletionHandler> SuggestionDeletionHandlers;
106
107   // Returns an AutocompleteMatch with the given |autocomplete_provider|
108   // for the search |suggestion|, which represents a search via |template_url|.
109   // If |template_url| is NULL, returns a match with an invalid destination URL.
110   //
111   // |input| is the original user input. Text in the input is used to highlight
112   // portions of the match contents to distinguish locally-typed text from
113   // suggested text.
114   //
115   // |input| is also necessary for various other details, like whether we should
116   // allow inline autocompletion and what the transition type should be.
117   // |in_keyword_mode| helps guarantee a non-keyword suggestion does not
118   // appear as the default match when the user is in keyword mode.
119   // |accepted_suggestion| is used to generate Assisted Query Stats.
120   // |append_extra_query_params| should be set if |template_url| is the default
121   // search engine, so the destination URL will contain any
122   // command-line-specified query params.
123   static AutocompleteMatch CreateSearchSuggestion(
124       AutocompleteProvider* autocomplete_provider,
125       const AutocompleteInput& input,
126       const bool in_keyword_mode,
127       const SearchSuggestionParser::SuggestResult& suggestion,
128       const TemplateURL* template_url,
129       const SearchTermsData& search_terms_data,
130       int accepted_suggestion,
131       bool append_extra_query_params);
132
133   // Returns whether the requirements for requesting zero suggest results
134   // are met. The requirements are
135   // * The user is enrolled in a zero suggest experiment.
136   // * The user is not on the NTP.
137   // * The suggest request is sent over HTTPS.  This avoids leaking the current
138   //   page URL or personal data in unencrypted network traffic.
139   // * The user has suggest enabled in their settings and is not in incognito
140   //   mode.  (Incognito disables suggest entirely.)
141   // * The user's suggest provider is Google.  We might want to allow other
142   //   providers to see this data someday, but for now this has only been
143   //   implemented for Google.
144   static bool ZeroSuggestEnabled(
145      const GURL& suggest_url,
146      const TemplateURL* template_url,
147      metrics::OmniboxEventProto::PageClassification page_classification,
148      const SearchTermsData& search_terms_data,
149      Profile* profile);
150
151   // Returns whether we can send the URL of the current page in any suggest
152   // requests.  Doing this requires that all the following hold:
153   // * ZeroSuggestEnabled() is true, so we meet the requirements above.
154   // * The current URL is HTTP, or HTTPS with the same domain as the suggest
155   //   server.  Non-HTTP[S] URLs (e.g. FTP/file URLs) may contain sensitive
156   //   information.  HTTPS URLs may also contain sensitive information, but if
157   //   they're on the same domain as the suggest server, then the relevant
158   //   entity could have already seen/logged this data.
159   // * The user is OK in principle with sending URLs of current pages to their
160   //   provider.  Today, there is no explicit setting that controls this, but if
161   //   the user has tab sync enabled and tab sync is unencrypted, then they're
162   //   already sending this data to Google for sync purposes.  Thus we use this
163   //   setting as a proxy for "it's OK to send such data".  In the future,
164   //   especially if we want to support suggest providers other than Google, we
165   //   may change this to be a standalone setting or part of some explicit
166   //   general opt-in.
167   static bool CanSendURL(
168       const GURL& current_page_url,
169       const GURL& suggest_url,
170       const TemplateURL* template_url,
171       metrics::OmniboxEventProto::PageClassification page_classification,
172       const SearchTermsData& search_terms_data,
173       Profile* profile);
174
175   // If the |deletion_url| is valid, then set |match.deletable| to true and
176   // save the |deletion_url| into the |match|'s additional info under
177   // the key |kDeletionUrlKey|.
178   void SetDeletionURL(const std::string& deletion_url,
179                       AutocompleteMatch* match);
180
181   // Creates an AutocompleteMatch from |result| to search for the query in
182   // |result|. Adds the created match to |map|; if such a match
183   // already exists, whichever one has lower relevance is eliminated.
184   // |metadata| and |accepted_suggestion| are used for generating an
185   // AutocompleteMatch.
186   // |mark_as_deletable| indicates whether the match should be marked deletable.
187   // |in_keyword_mode| helps guarantee a non-keyword suggestion does not
188   // appear as the default match when the user is in keyword mode.
189   // NOTE: Any result containing a deletion URL is always marked deletable.
190   void AddMatchToMap(const SearchSuggestionParser::SuggestResult& result,
191                      const std::string& metadata,
192                      int accepted_suggestion,
193                      bool mark_as_deletable,
194                      bool in_keyword_mode,
195                      MatchMap* map);
196
197   // Parses results from the suggest server and updates the appropriate suggest
198   // and navigation result lists in |results|. |default_result_relevance| is
199   // the relevance to use if it was not explicitly set by the server.
200   // |is_keyword_result| indicates whether the response was received from the
201   // keyword provider.
202   // Returns whether the appropriate result list members were updated.
203   bool ParseSuggestResults(const base::Value& root_val,
204                            int default_result_relevance,
205                            bool is_keyword_result,
206                            SearchSuggestionParser::Results* results);
207
208   // Returns the TemplateURL corresponding to the keyword or default
209   // provider based on the value of |is_keyword|.
210   virtual const TemplateURL* GetTemplateURL(bool is_keyword) const = 0;
211
212   // Returns the AutocompleteInput for keyword provider or default provider
213   // based on the value of |is_keyword|.
214   virtual const AutocompleteInput GetInput(bool is_keyword) const = 0;
215
216   // Returns whether the destination URL corresponding to the given |result|
217   // should contain command-line-specified query params.
218   virtual bool ShouldAppendExtraParams(
219       const SearchSuggestionParser::SuggestResult& result) const = 0;
220
221   // Stops the suggest query.
222   // NOTE: This does not update |done_|.  Callers must do so.
223   virtual void StopSuggest() = 0;
224
225   // Clears the current results.
226   virtual void ClearAllResults() = 0;
227
228   // Records in UMA whether the deletion request resulted in success.
229   virtual void RecordDeletionResult(bool success) = 0;
230
231   // Modify provider-specific UMA statistics.
232   virtual void ModifyProviderInfo(
233       metrics::OmniboxEventProto_ProviderInfo* provider_info) const;
234
235   TemplateURLService* template_url_service_;
236   Profile* profile_;
237
238   // Whether a field trial, if any, has triggered in the most recent
239   // autocomplete query. This field is set to true only if the suggestion
240   // provider has completed and the response contained
241   // '"google:fieldtrialtriggered":true'.
242   bool field_trial_triggered_;
243
244   // Same as above except that it is maintained across the current Omnibox
245   // session.
246   bool field_trial_triggered_in_session_;
247
248  private:
249   friend class SearchProviderTest;
250   FRIEND_TEST_ALL_PREFIXES(SearchProviderTest, TestDeleteMatch);
251
252   // Removes the deleted |match| from the list of |matches_|.
253   void DeleteMatchFromMatches(const AutocompleteMatch& match);
254
255   // This gets called when we have requested a suggestion deletion from the
256   // server to handle the results of the deletion. It will be called after the
257   // deletion request completes.
258   void OnDeletionComplete(bool success,
259                           SuggestionDeletionHandler* handler);
260
261   // Each deletion handler in this vector corresponds to an outstanding request
262   // that a server delete a personalized suggestion. Making this a ScopedVector
263   // causes us to auto-cancel all such requests on shutdown.
264   SuggestionDeletionHandlers deletion_handlers_;
265
266   DISALLOW_COPY_AND_ASSIGN(BaseSearchProvider);
267 };
268
269 #endif  // CHROME_BROWSER_AUTOCOMPLETE_BASE_SEARCH_PROVIDER_H_