history_url_provider.h revision 2a99a7e74a7f215066514fe81d2bfa6639d9eddd
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. 4 5#ifndef CHROME_BROWSER_AUTOCOMPLETE_HISTORY_URL_PROVIDER_H_ 6#define CHROME_BROWSER_AUTOCOMPLETE_HISTORY_URL_PROVIDER_H_ 7 8#include <string> 9#include <vector> 10 11#include "base/compiler_specific.h" 12#include "base/synchronization/cancellation_flag.h" 13#include "chrome/browser/autocomplete/autocomplete_input.h" 14#include "chrome/browser/autocomplete/history_provider.h" 15#include "chrome/browser/autocomplete/history_provider_util.h" 16#include "chrome/browser/autocomplete/url_prefix.h" 17#include "chrome/browser/search_engines/search_terms_data.h" 18#include "chrome/browser/search_engines/template_url.h" 19 20class MessageLoop; 21class Profile; 22 23namespace history { 24class HistoryBackend; 25class URLDatabase; 26} 27 28// How history autocomplete works 29// ============================== 30// 31// Read down this diagram for temporal ordering. 32// 33// Main thread History thread 34// ----------- -------------- 35// AutocompleteController::Start 36// -> HistoryURLProvider::Start 37// -> RunAutocompletePasses 38// -> SuggestExactInput 39// [params_ allocated] 40// -> DoAutocomplete (for inline autocomplete) 41// -> URLDatabase::AutocompleteForPrefix (on in-memory DB) 42// -> HistoryService::ScheduleAutocomplete 43// (return to controller) ---- 44// / 45// HistoryBackend::ScheduleAutocomplete 46// -> HistoryURLProvider::ExecuteWithDB 47// -> DoAutocomplete 48// -> URLDatabase::AutocompleteForPrefix 49// / 50// HistoryService::QueryComplete 51// [params_ destroyed] 52// -> AutocompleteProviderListener::OnProviderUpdate 53// 54// The autocomplete controller calls us, and must be called back, on the main 55// thread. When called, we run two autocomplete passes. The first pass runs 56// synchronously on the main thread and queries the in-memory URL database. 57// This pass promotes matches for inline autocomplete if applicable. We do 58// this synchronously so that users get consistent behavior when they type 59// quickly and hit enter, no matter how loaded the main history database is. 60// Doing this synchronously also prevents inline autocomplete from being 61// "flickery" in the AutocompleteEdit. Because the in-memory DB does not have 62// redirect data, results other than the top match might change between the 63// two passes, so we can't just decide to use this pass' matches as the final 64// results. 65// 66// The second autocomplete pass uses the full history database, which must be 67// queried on the history thread. Start() asks the history service schedule to 68// callback on the history thread with a pointer to the main database. When we 69// are done doing queries, we schedule a task on the main thread that notifies 70// the AutocompleteController that we're done. 71// 72// The communication between these threads is done using a 73// HistoryURLProviderParams object. This is allocated in the main thread, and 74// normally deleted in QueryComplete(). So that both autocomplete passes can 75// use the same code, we also use this to hold results during the first 76// autocomplete pass. 77// 78// While the second pass is running, the AutocompleteController may cancel the 79// request. This can happen frequently when the user is typing quickly. In 80// this case, the main thread sets params_->cancel, which the background thread 81// checks periodically. If it finds the flag set, it stops what it's doing 82// immediately and calls back to the main thread. (We don't delete the params 83// on the history thread, because we should only do that when we can safely 84// NULL out params_, and that must be done on the main thread.) 85 86// Used to communicate autocomplete parameters between threads via the history 87// service. 88struct HistoryURLProviderParams { 89 HistoryURLProviderParams(const AutocompleteInput& input, 90 bool trim_http, 91 const std::string& languages, 92 TemplateURL* default_search_provider, 93 const SearchTermsData& search_terms_data); 94 ~HistoryURLProviderParams(); 95 96 MessageLoop* message_loop; 97 98 // A copy of the autocomplete input. We need the copy since this object will 99 // live beyond the original query while it runs on the history thread. 100 AutocompleteInput input; 101 102 // Should inline autocompletion be disabled? This is initalized from 103 // |input.prevent_inline_autocomplete()|, but set to false is the input 104 // contains trailing white space. 105 bool prevent_inline_autocomplete; 106 107 // Set when "http://" should be trimmed from the beginning of the URLs. 108 bool trim_http; 109 110 // Set by the main thread to cancel this request. If this flag is set when 111 // the query runs, the query will be abandoned. This allows us to avoid 112 // running queries that are no longer needed. Since we don't care if we run 113 // the extra queries, the lack of signaling is not a problem. 114 base::CancellationFlag cancel_flag; 115 116 // Set by ExecuteWithDB() on the history thread when the query could not be 117 // performed because the history system failed to properly init the database. 118 // If this is set when the main thread is called back, it avoids changing 119 // |matches_| at all, so it won't delete the default match 120 // RunAutocompletePasses() creates. 121 bool failed; 122 123 // List of matches written by the history thread. We keep this separate list 124 // to avoid having the main thread read the provider's matches while the 125 // history thread is manipulating them. The provider copies this list back 126 // to matches_ on the main thread in QueryComplete(). 127 ACMatches matches; 128 129 // Languages we should pass to gfx::GetCleanStringFromUrl. 130 std::string languages; 131 132 // When true, we should avoid calling SuggestExactInput(). 133 bool dont_suggest_exact_input; 134 135 // The default search provider and search terms data necessary to cull results 136 // that correspond to searches (on the default engine). These can only be 137 // obtained on the UI thread, so we have to copy them into here to pass them 138 // to the history thread. We use a scoped_ptr<TemplateURL> for the DSP since 139 // TemplateURLs can't be copied by value. We use a scoped_ptr<SearchTermsData> 140 // so that we can store a snapshot of the SearchTermsData accessible from the 141 // history thread. 142 scoped_ptr<TemplateURL> default_search_provider; 143 scoped_ptr<SearchTermsData> search_terms_data; 144 145 private: 146 DISALLOW_COPY_AND_ASSIGN(HistoryURLProviderParams); 147}; 148 149// This class is an autocomplete provider and is also a pseudo-internal 150// component of the history system. See comments above. 151class HistoryURLProvider : public HistoryProvider { 152 public: 153 // Various values used in scoring, made public so other providers 154 // can insert results in appropriate ranges relative to these. 155 static const int kScoreForBestInlineableResult; 156 static const int kScoreForUnvisitedIntranetResult; 157 static const int kScoreForWhatYouTypedResult; 158 static const int kBaseScoreForNonInlineableResult; 159 160 HistoryURLProvider(AutocompleteProviderListener* listener, Profile* profile); 161 162#ifdef UNIT_TEST 163 HistoryURLProvider(AutocompleteProviderListener* listener, 164 Profile* profile, 165 const std::string& languages) 166 : HistoryProvider(listener, profile, 167 AutocompleteProvider::TYPE_HISTORY_URL), 168 params_(NULL), 169 cull_redirects_(true), 170 create_shorter_match_(true), 171 search_url_database_(true), 172 languages_(languages) {} 173#endif 174 175 // Returns a match corresponding to exactly what the user has typed. 176 // NOTE: This does not set the relevance of the returned match, as different 177 // callers want different behavior. Callers must set this manually. 178 // This function is static so SearchProvider may construct similar matches. 179 static AutocompleteMatch SuggestExactInput(AutocompleteProvider* provider, 180 const AutocompleteInput& input, 181 bool trim_http); 182 183 // AutocompleteProvider 184 virtual void Start(const AutocompleteInput& input, 185 bool minimal_changes) OVERRIDE; 186 virtual void Stop(bool clear_cached_results) OVERRIDE; 187 188 // Runs the history query on the history thread, called by the history 189 // system. The history database MAY BE NULL in which case it is not 190 // available and we should return no data. Also schedules returning the 191 // results to the main thread 192 void ExecuteWithDB(history::HistoryBackend* backend, 193 history::URLDatabase* db, 194 HistoryURLProviderParams* params); 195 196 // Actually runs the autocomplete job on the given database, which is 197 // guaranteed not to be NULL. 198 void DoAutocomplete(history::HistoryBackend* backend, 199 history::URLDatabase* db, 200 HistoryURLProviderParams* params); 201 202 // Dispatches the results to the autocomplete controller. Called on the 203 // main thread by ExecuteWithDB when the results are available. 204 // Frees params_gets_deleted on exit. 205 void QueryComplete(HistoryURLProviderParams* params_gets_deleted); 206 207 private: 208 enum MatchType { 209 NORMAL, 210 WHAT_YOU_TYPED, 211 INLINE_AUTOCOMPLETE, 212 UNVISITED_INTRANET, // An intranet site that has never been visited. 213 }; 214 class VisitClassifier; 215 216 ~HistoryURLProvider(); 217 218 // Determines the relevance for a match, given its type. If 219 // |match_type| is NORMAL, |match_number| is a number [0, 220 // kMaxSuggestions) indicating the relevance of the match (higher == 221 // more relevant). For other values of |match_type|, |match_number| 222 // is ignored. Only called some of the time; for some matches, 223 // relevancy scores are assigned consecutively decreasing (1416, 224 // 1415, 1414, ...). 225 int CalculateRelevance(MatchType match_type, size_t match_number) const; 226 227 // Helper function that actually launches the two autocomplete passes. 228 void RunAutocompletePasses(const AutocompleteInput& input, 229 bool fixup_input_and_run_pass_1); 230 231 // Given a |match| containing the "what you typed" suggestion created by 232 // SuggestExactInput(), looks up its info in the DB. If found, fills in the 233 // title from the DB, promotes the match's priority to that of an inline 234 // autocomplete match (maybe it should be slightly better?), and places it on 235 // the front of |matches| (so we pick the right matches to throw away 236 // when culling redirects to/from it). Returns whether a match was promoted. 237 bool FixupExactSuggestion(history::URLDatabase* db, 238 const AutocompleteInput& input, 239 const VisitClassifier& classifier, 240 AutocompleteMatch* match, 241 history::HistoryMatches* matches) const; 242 243 // Helper function for FixupExactSuggestion, this returns true if the input 244 // corresponds to some intranet URL where the user has previously visited the 245 // host in question. In this case the input should be treated as a URL. 246 bool CanFindIntranetURL(history::URLDatabase* db, 247 const AutocompleteInput& input) const; 248 249 // Determines if |match| is suitable for inline autocomplete. If so, and if 250 // |params| is non-NULL, promotes the match. Returns whether |match| is 251 // suitable for inline autocomplete. 252 bool PromoteMatchForInlineAutocomplete(HistoryURLProviderParams* params, 253 const history::HistoryMatch& match); 254 255 // Sees if a shorter version of the best match should be created, and if so 256 // places it at the front of |matches|. This can suggest history URLs that 257 // are prefixes of the best match (if they've been visited enough, compared to 258 // the best match), or create host-only suggestions even when they haven't 259 // been visited before: if the user visited http://example.com/asdf once, 260 // we'll suggest http://example.com/ even if they've never been to it. 261 void PromoteOrCreateShorterSuggestion( 262 history::URLDatabase* db, 263 const HistoryURLProviderParams& params, 264 bool have_what_you_typed_match, 265 const AutocompleteMatch& what_you_typed_match, 266 history::HistoryMatches* matches); 267 268 // Sorts the given list of matches. 269 void SortMatches(history::HistoryMatches* matches) const; 270 271 // Removes results that have been rarely typed or visited, and not any time 272 // recently. The exact parameters for this heuristic can be found in the 273 // function body. Also culls results corresponding to queries from the default 274 // search engine. These are low-quality, difficult-to-understand matches for 275 // users, and the SearchProvider should surface past queries in a better way 276 // anyway. 277 void CullPoorMatches(history::HistoryMatches* matches, 278 HistoryURLProviderParams* params) const; 279 280 // Removes results that redirect to each other, leaving at most |max_results| 281 // results. 282 void CullRedirects(history::HistoryBackend* backend, 283 history::HistoryMatches* matches, 284 size_t max_results) const; 285 286 // Helper function for CullRedirects, this removes all but the first 287 // occurance of [any of the set of strings in |remove|] from the |matches| 288 // list. 289 // 290 // The return value is the index of the item that is after the item in the 291 // input identified by |source_index|. If |source_index| or an item before 292 // is removed, the next item will be shifted, and this allows the caller to 293 // pick up on the next one when this happens. 294 size_t RemoveSubsequentMatchesOf(history::HistoryMatches* matches, 295 size_t source_index, 296 const std::vector<GURL>& remove) const; 297 298 // Converts a line from the database into an autocomplete match for display. 299 AutocompleteMatch HistoryMatchToACMatch( 300 HistoryURLProviderParams* params, 301 const history::HistoryMatch& history_match, 302 MatchType match_type, 303 int relevance); 304 305 // Params for the current query. The provider should not free this directly; 306 // instead, it is passed as a parameter through the history backend, and the 307 // parameter itself is freed once it's no longer needed. The only reason we 308 // keep this member is so we can set the cancel bit on it. 309 HistoryURLProviderParams* params_; 310 311 // If true, HistoryURL provider should lookup and cull redirects. If 312 // false, it returns matches that may be redirects to each other and 313 // simply hopes the default AutoCompleteController behavior to remove 314 // URLs that are likely duplicates (http://google.com <-> 315 // https://www.google.com/, etc.) will do a good enough job. 316 bool cull_redirects_; 317 318 // Used in PromoteOrCreateShorterSuggestion(). If true, we may create 319 // shorter suggestions even when they haven't been visited before: 320 // if the user visited http://example.com/asdf once, we'll suggest 321 // http://example.com/ even if they've never been to it. 322 bool create_shorter_match_; 323 324 // Whether to query the history URL database to match. Even if 325 // false, we still use the URL database to decide if the 326 // URL-what-you-typed was visited before or not. If false, the only 327 // possible result that HistoryURL provider can return is 328 // URL-what-you-typed. This variable is not part of params_ because 329 // it never changes after the HistoryURLProvider is initialized. 330 // It's used to aid the transition to get all URLs from history to 331 // be scored in the HistoryQuick provider only. 332 bool search_url_database_; 333 334 // Only used by unittests; if non-empty, overrides accept-languages in the 335 // profile's pref system. 336 std::string languages_; 337}; 338 339#endif // CHROME_BROWSER_AUTOCOMPLETE_HISTORY_URL_PROVIDER_H_ 340