Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(696)

Side by Side Diff: chrome/browser/autocomplete/base_search_provider.h

Issue 131433003: Refactor search and zero suggest providers to use common base class. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: More style + zero-suggest logic fixes Created 6 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « no previous file | chrome/browser/autocomplete/base_search_provider.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 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 derive from this
7 // class which contains common methods for parsing search results and making
8 // deletion requests.
9
10 #ifndef CHROME_BROWSER_AUTOCOMPLETE_BASE_SEARCH_PROVIDER_H_
11 #define CHROME_BROWSER_AUTOCOMPLETE_BASE_SEARCH_PROVIDER_H_
12
13 #include <map>
14 #include <string>
15 #include <vector>
16
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/scoped_vector.h"
19 #include "chrome/browser/autocomplete/autocomplete_input.h"
20 #include "chrome/browser/autocomplete/autocomplete_provider.h"
21 #include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
22 #include "chrome/browser/profiles/profile.h"
23 #include "net/url_request/url_fetcher_delegate.h"
24
25 class SuggestionDeletionHandler;
26
27 namespace net {
28 class URLFetcher;
29 }
30
31 // Base functionality for receiving suggestions from a search engine.
32 // This class is abstract and should only be used as a base for other
33 // autocomplete providers utilizing the functionality.
34 class BaseSearchProvider : public AutocompleteProvider,
35 public net::URLFetcherDelegate {
36 public:
37 // ID used in creating URLFetcher for deleting suggestion results.
38 static const int kDeletionURLFetcherID;
39
40 BaseSearchProvider(AutocompleteProviderListener* listener,
41 Profile* profile,
42 AutocompleteProvider::Type type);
43
44 // AutocompleteProvider:
45 virtual void Stop(bool clear_cached_results) OVERRIDE;
46 virtual void AddProviderInfo(ProvidersInfo* provider_info) const OVERRIDE;
47 virtual void DeleteMatch(const AutocompleteMatch& match) OVERRIDE;
48 virtual void ResetSession() OVERRIDE;
49
50 // Returns whether the SearchProvider previously flagged |match| as a query
51 // that should be prefetched.
52 static bool ShouldPrefetch(const AutocompleteMatch& match);
53
54 bool field_trial_triggered_in_session() const {
55 return field_trial_triggered_in_session_;
56 }
57
58 protected:
59 // The Result classes are intermediate representations of
60 // AutocompleteMatches, simply containing relevance-ranked search and
61 // navigation suggestions. They may be cached to provide some synchronous
62 // matches while requests for new suggestions from updated input are in
63 // flight.
64 // TODO(msw) Extend these classes to generate their corresponding matches
65 // and other requisite data, in order to consolidate and simplify
66 // the highly fragmented SearchProvider logic for each Result
67 // type.
68 class Result {
69 public:
70 Result(bool from_keyword_provider,
71 int relevance,
72 bool relevance_from_server);
73 virtual ~Result();
74
75 bool from_keyword_provider() const { return from_keyword_provider_; }
76
77 const base::string16& match_contents() const { return match_contents_; }
78 const ACMatchClassifications& match_contents_class() const {
79 return match_contents_class_;
80 }
81
82 int relevance() const { return relevance_; }
83 void set_relevance(int relevance) { relevance_ = relevance; }
84
85 bool relevance_from_server() const { return relevance_from_server_; }
86 void set_relevance_from_server(bool relevance_from_server) {
87 relevance_from_server_ = relevance_from_server;
88 }
89
90 // Returns if this result is inlineable against the current input |input|.
91 // Non-inlineable results are stale.
92 virtual bool IsInlineable(const base::string16& input) const = 0;
93
94 // Returns the default relevance value for this result (which may
95 // be left over from a previous omnibox input) given the current
96 // input and whether the current input caused a keyword provider
97 // to be active.
98 virtual int CalculateRelevance(const AutocompleteInput& input,
99 bool keyword_provider_requested) const = 0;
100
101 protected:
102 // The contents to be displayed and its style info.
103 base::string16 match_contents_;
104 ACMatchClassifications match_contents_class_;
105
106 // True if the result came from the keyword provider.
107 bool from_keyword_provider_;
108
109 // The relevance score.
110 int relevance_;
111
112 private:
113 // Whether this result's relevance score was fully or partly calculated
114 // based on server information, and thus is assumed to be more accurate.
115 // This is ultimately used in
116 // SearchProvider::ConvertResultsToAutocompleteMatches(), see comments
117 // there.
118 bool relevance_from_server_;
119 };
120
121 class SuggestResult : public Result {
122 public:
123 SuggestResult(const base::string16& suggestion,
124 AutocompleteMatchType::Type type,
125 const base::string16& match_contents,
126 const base::string16& annotation,
127 const std::string& suggest_query_params,
128 const std::string& deletion_url,
129 bool from_keyword_provider,
130 int relevance,
131 bool relevance_from_server,
132 bool should_prefetch,
133 const base::string16& input_text);
134 virtual ~SuggestResult();
135
136 const base::string16& suggestion() const { return suggestion_; }
137 AutocompleteMatchType::Type type() const { return type_; }
138 const base::string16& annotation() const { return annotation_; }
139 const std::string& suggest_query_params() const {
140 return suggest_query_params_;
141 }
142 const std::string& deletion_url() const { return deletion_url_; }
143 bool should_prefetch() const { return should_prefetch_; }
144
145 // Fills in |match_contents_class_| to reflect how |match_contents_| should
146 // be displayed and bolded against the current |input_text|. If
147 // |allow_bolding_all| is false and |match_contents_class_| would have all
148 // of |match_contents_| bolded, do nothing.
149 void ClassifyMatchContents(const bool allow_bolding_all,
150 const base::string16& input_text);
151
152 // Result:
153 virtual bool IsInlineable(const base::string16& input) const OVERRIDE;
154 virtual int CalculateRelevance(const AutocompleteInput& input,
155 bool keyword_provider_requested)
156 const OVERRIDE;
157
158 private:
159 // The search terms to be used for this suggestion.
160 base::string16 suggestion_;
161
162 AutocompleteMatchType::Type type_;
163
164 // Optional annotation for the |match_contents_| for disambiguation.
165 // This may be displayed in the autocomplete match contents, but is defined
166 // separately to facilitate different formatting.
167 base::string16 annotation_;
168
169 // Optional additional parameters to be added to the search URL.
170 std::string suggest_query_params_;
171
172 // Optional deletion URL provided with suggestions. Fetching this URL
173 // should result in some reasonable deletion behaviour on the server,
174 // e.g. deleting this term out of a user's server-side search history.
175 std::string deletion_url_;
176
177 // Should this result be prefetched?
178 bool should_prefetch_;
179 };
180
181 class NavigationResult : public Result {
182 public:
183 // |provider| is necessary to use StringForURLDisplay() in order to
184 // compute |formatted_url_|.
185 NavigationResult(const AutocompleteProvider& provider,
186 const GURL& url,
187 const base::string16& description,
188 bool from_keyword_provider,
189 int relevance,
190 bool relevance_from_server,
191 const base::string16& input_text,
192 const std::string& languages);
193 virtual ~NavigationResult();
194
195 const GURL& url() const { return url_; }
196 const base::string16& description() const { return description_; }
197 const base::string16& formatted_url() const { return formatted_url_; }
198
199 // Fills in |match_contents_| and |match_contents_class_| to reflect how
200 // the URL should be displayed and bolded against the current |input_text|
201 // and user |languages|. If |allow_bolding_nothing| is false and
202 // |match_contents_class_| would result in an entirely unbolded
203 // |match_contents_|, do nothing.
204 void CalculateAndClassifyMatchContents(const bool allow_bolding_nothing,
205 const base::string16& input_text,
206 const std::string& languages);
207
208 // Result:
209 virtual bool IsInlineable(const base::string16& input) const OVERRIDE;
210 virtual int CalculateRelevance(const AutocompleteInput& input,
211 bool keyword_provider_requested)
212 const OVERRIDE;
213
214 private:
215 // The suggested url for navigation.
216 GURL url_;
217
218 // The properly formatted ("fixed up") URL string with equivalent meaning
219 // to the one in |url_|.
220 base::string16 formatted_url_;
221
222 // The suggested navigational result description; generally the site name.
223 base::string16 description_;
224 };
225
226 typedef std::vector<SuggestResult> SuggestResults;
227 typedef std::vector<NavigationResult> NavigationResults;
228 typedef std::pair<base::string16, std::string> MatchKey;
229 typedef std::map<MatchKey, AutocompleteMatch> MatchMap;
230 typedef ScopedVector<SuggestionDeletionHandler> SuggestionDeletionHandlers;
231
232 // A simple structure bundling most of the information (including
233 // both SuggestResults and NavigationResults) returned by a call to
234 // the suggest server.
235 //
236 // This has to be declared after the typedefs since it relies on some
237 // of them.
238 struct Results {
239 Results();
240 ~Results();
241
242 // Clears |suggest_results| and |navigation_results| and resets
243 // |verbatim_relevance| to -1 (implies unset).
244 void Clear();
245
246 // Returns whether any of the results (including verbatim) have
247 // server-provided scores.
248 bool HasServerProvidedScores() const;
249
250 // Query suggestions sorted by relevance score.
251 SuggestResults suggest_results;
252
253 // Navigational suggestions sorted by relevance score.
254 NavigationResults navigation_results;
255
256 // The server supplied verbatim relevance scores. Negative values
257 // indicate that there is no suggested score; a value of 0
258 // suppresses the verbatim result.
259 int verbatim_relevance;
260
261 // The JSON metadata associated with this server response.
262 std::string metadata;
263
264 private:
265 DISALLOW_COPY_AND_ASSIGN(Results);
266 };
267
268 // The following keys are used to record additional information on matches.
269
270 // Used to store a deletion request url for server-provided suggestions.
271 static const char kDeletionUrlKey[];
272
273 // We annotate our AutocompleteMatches with whether their relevance scores
274 // were server-provided using this key in the |additional_info| field.
275 static const char kRelevanceFromServerKey[];
276
277 // Indicates whether the server said a match should be prefetched.
278 static const char kShouldPrefetchKey[];
279
280 // Used to store metadata from the server response, which is needed for
281 // prefetching.
282 static const char kSuggestMetadataKey[];
283
284 // These are the values for the above keys.
285 static const char kTrue[];
286 static const char kFalse[];
287
288 virtual ~BaseSearchProvider();
289
290 // Returns an AutocompleteMatch with the given |autocomplete_provider|
291 // for the search |suggestion|, which represents a search via |template_url|.
292 // If |template_url| is NULL, returns a match with an invalid destination URL.
293 //
294 // |input_text| is the original user input. This is used to highlight
295 // portions of the match contents to distinguish locally-typed text from
296 // suggested text.
297 //
298 // |input| is necessary for various other details, like whether we should
299 // allow inline autocompletion and what the transition type should be.
300 // |accepted_suggestion| and |omnibox_start_margin| are used along with
301 // |input_text| to generate Assisted Query Stats.
302 // |append_extra_query_params| should be set if |template_url| is the default
303 // search engine, so the destination URL will contain any
304 // command-line-specified query params.
305 static AutocompleteMatch CreateSearchSuggestion(
306 AutocompleteProvider* autocomplete_provider,
307 const AutocompleteInput& input,
308 const base::string16& input_text,
309 const SuggestResult& suggestion,
310 const TemplateURL* template_url,
311 int accepted_suggestion,
312 int omnibox_start_margin,
313 bool append_extra_query_params);
314
315 // Returns whether we can send the URL of the current page in any suggest
316 // requests. Doing this requires that all the following hold:
317 // * The user has suggest enabled in their settings and is not in incognito
318 // mode. (Incognito disables suggest entirely.)
319 // * The current URL is HTTP, or HTTPS with the same domain as the suggest
320 // server. Non-HTTP[S] URLs (e.g. FTP/file URLs) may contain sensitive
321 // information. HTTPS URLs may also contain sensitive information, but if
322 // they're on the same domain as the suggest server, then the relevant
323 // entity could have already seen/logged this data.
324 // * The suggest request is sent over HTTPS. This avoids leaking the current
325 // page URL in world-readable network traffic.
326 // * The user's suggest provider is Google. We might want to allow other
327 // providers to see this data someday, but for now this has only been
328 // implemented for Google. Also see next bullet.
329 // * The user is OK in principle with sending URLs of current pages to their
330 // provider. Today, there is no explicit setting that controls this, but if
331 // the user has tab sync enabled and tab sync is unencrypted, then they're
332 // already sending this data to Google for sync purposes. Thus we use this
333 // setting as a proxy for "it's OK to send such data". In the future,
334 // especially if we want to support suggest providers other than Google, we
335 // may change this to be a standalone setting or part of some explicit
336 // general opt-in.
337 static bool CanSendURL(
338 const GURL& current_page_url,
339 const GURL& suggest_url,
340 const TemplateURL* template_url,
341 AutocompleteInput::PageClassification page_classification,
342 Profile* profile);
343
344 // AutocompleteProvider:
345 virtual void Start(const AutocompleteInput& input,
346 bool minimal_changes) OVERRIDE;
347
348 // net::URLFetcherDelegate
349 virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE;
350
351 // Stops the suggest query.
352 // NOTE: This does not update |done_|. Callers must do so.
353 virtual void StopSuggest() = 0;
354
355 // Clears the current results.
356 virtual void ClearAllResults() = 0;
357
358 // Allows derived classes to record metrics about the request after
359 // OnURLFetchComplete is called.
360 virtual void LogFetchComplete(const net::URLFetcher* source) = 0;
361
362 // Check whether the request from the given |source| succeeded.
363 virtual bool IsRequestSuccessful(const net::URLFetcher* source);
364
365 // Check whether the request from the given |source| is a keyword request.
366 virtual bool IsKeywordRequest(const net::URLFetcher* source);
367
368 // Parses search results from the server.
369 virtual bool ParseSuggestResults(const base::Value& root_val,
370 const net::URLFetcher* source,
371 Results* results);
372
373 // Returns a Results object which will be used to store the return value of
374 // ParseSuggestResults call.
375 virtual Results* GetResultsObjectToFill(const net::URLFetcher* source) = 0;
376
377 // Returns the default relevance value to use in computing search result
378 // relevance.
379 virtual int GetDefaultRelevance() = 0;
380
381 // Returns the input text
382 virtual const base::string16 GetInputText(const net::URLFetcher* source) = 0;
383
384 // Checks whether the query matches the user's input
385 virtual bool IsValidQuery(const base::string16 query,
386 const net::URLFetcher* source) = 0;
387
388 // Whether navigation suggestions are accepted.
389 virtual bool ShouldAllowNavSuggest(const net::URLFetcher* source);
390
391 // Sort the parsed results.
392 virtual void SortResults(const net::URLFetcher* source,
393 const base::ListValue* relevances,
394 Results* results);
395
396 // Computes whether we should call update on the autocomplete provider based
397 // on the recently processed server response. |results_updated| indicates
398 // whether we successfully parsed suggest results.
399 virtual bool ShouldSendProviderUpdate(bool results_updated) = 0;
400
401 // Updates |matches_| from the latest results; applies calculated relevances
402 // if suggested relevances cause undesriable behavior. Updates |done_|.
403 virtual void UpdateMatches() = 0;
404
405 // Creates an AutocompleteMatch for "Search <engine> for |query_string|" with
406 // the supplied details. Adds this match to |map|; if such a match already
407 // exists, whichever one has lower relevance is eliminated.
408 void AddMatchToMap(const SuggestResult& result,
409 const AutocompleteInput input,
410 const base::string16& input_text,
411 const TemplateURL* template_url,
412 const std::string& metadata,
413 int accepted_suggestion,
414 bool append_extra_query_params,
415 MatchMap* map);
416
417 // Allows derived classes to record in UMA whether the deletion request
418 // resulted in success.
419 virtual void RecordDeletionResult(bool success) = 0;
420
421 // Whether a field trial, if any, has triggered in the most recent
422 // autocomplete query. This field is set to false in Start() and may be set
423 // to true if either the default provider or keyword provider has completed
424 // and their corresponding suggest response contained
425 // '"google:fieldtrialtriggered":true'.
426 // If the autocomplete query has not returned, this field is set to false.
427 bool field_trial_triggered_;
428
429 // Same as above except that it is maintained across the current Omnibox
430 // session.
431 bool field_trial_triggered_in_session_;
432
433 // Number of suggest results that haven't yet arrived. If greater than 0 it
434 // indicates one of the URLFetchers is still running.
435 int suggest_results_pending_;
436
437 private:
438 friend class SearchProviderTest;
439 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest, TestDeleteMatch);
440
441 // Parses JSON response received from the provider, stripping XSSI
442 // protection if needed. Returns the parsed data if successful, NULL
443 // otherwise.
444 scoped_ptr<base::Value> DeserializeJsonData(std::string json_data);
445
446 // This gets called when we have requested a suggestion deletion from the
447 // server to handle the results of the deletion.
448 void OnDeletionComplete(bool success, SuggestionDeletionHandler* handler);
449
450 // Removes the deleted match from the list of |matches_|.
451 void DeleteMatchFromMatches(const AutocompleteMatch& match);
452
453 // Each deletion handler in this vector corresponds to an outstanding request
454 // that a server delete a personalized suggestion. Making this a ScopedVector
455 // causes us to auto-cancel all such requests on shutdown.
456 SuggestionDeletionHandlers deletion_handlers_;
457
458 DISALLOW_COPY_AND_ASSIGN(BaseSearchProvider);
459 };
460
461 #endif // CHROME_BROWSER_AUTOCOMPLETE_BASE_SEARCH_PROVIDER_H_
OLDNEW
« no previous file with comments | « no previous file | chrome/browser/autocomplete/base_search_provider.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698