037904d917943affdaec4f67262e69ac4c67cd88
[platform/framework/web/crosswalk.git] / src / chrome / browser / autocomplete / history_url_provider.cc
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 #include "chrome/browser/autocomplete/history_url_provider.h"
6
7 #include <algorithm>
8
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/metrics/histogram.h"
14 #include "base/prefs/pref_service.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/time/time.h"
18 #include "chrome/browser/autocomplete/autocomplete_match.h"
19 #include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
20 #include "chrome/browser/autocomplete/autocomplete_result.h"
21 #include "chrome/browser/history/history_backend.h"
22 #include "chrome/browser/history/history_database.h"
23 #include "chrome/browser/history/history_service.h"
24 #include "chrome/browser/history/history_service_factory.h"
25 #include "chrome/browser/history/history_types.h"
26 #include "chrome/browser/history/in_memory_url_index_types.h"
27 #include "chrome/browser/history/scored_history_match.h"
28 #include "chrome/browser/omnibox/omnibox_field_trial.h"
29 #include "chrome/browser/profiles/profile.h"
30 #include "chrome/browser/search_engines/template_url_service.h"
31 #include "chrome/browser/search_engines/template_url_service_factory.h"
32 #include "chrome/common/chrome_switches.h"
33 #include "chrome/common/net/url_fixer_upper.h"
34 #include "chrome/common/pref_names.h"
35 #include "chrome/common/url_constants.h"
36 #include "net/base/net_util.h"
37 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
38 #include "url/gurl.h"
39 #include "url/url_parse.h"
40 #include "url/url_util.h"
41
42 namespace {
43
44 // If |create_if_necessary| is true, ensures that |matches| contains an
45 // entry for |info|, creating a new such entry if necessary (using
46 // |input_location| and |match_in_scheme|).
47 //
48 // If |promote| is true, this also ensures the entry is the first element in
49 // |matches|, moving or adding it to the front as appropriate.  When |promote|
50 // is false, existing matches are left in place, and newly added matches are
51 // placed at the back.
52 //
53 // It's OK to call this function with both |create_if_necessary| and
54 // |promote| false, in which case we'll do nothing.
55 //
56 // Returns whether the match exists regardless if it was promoted/created.
57 bool CreateOrPromoteMatch(const history::URLRow& info,
58                           size_t input_location,
59                           bool match_in_scheme,
60                           history::HistoryMatches* matches,
61                           bool create_if_necessary,
62                           bool promote) {
63   // |matches| may already have an entry for this.
64   for (history::HistoryMatches::iterator i(matches->begin());
65        i != matches->end(); ++i) {
66     if (i->url_info.url() == info.url()) {
67       // Rotate it to the front if the caller wishes.
68       if (promote)
69         std::rotate(matches->begin(), i, i + 1);
70       return true;
71     }
72   }
73
74   if (!create_if_necessary)
75     return false;
76
77   // No entry, so create one.
78   history::HistoryMatch match(info, input_location, match_in_scheme, true);
79   if (promote)
80     matches->push_front(match);
81   else
82     matches->push_back(match);
83
84   return true;
85 }
86
87 // Given the user's |input| and a |match| created from it, reduce the match's
88 // URL to just a host.  If this host still matches the user input, return it.
89 // Returns the empty string on failure.
90 GURL ConvertToHostOnly(const history::HistoryMatch& match,
91                        const base::string16& input) {
92   // See if we should try to do host-only suggestions for this URL. Nonstandard
93   // schemes means there's no authority section, so suggesting the host name
94   // is useless. File URLs are standard, but host suggestion is not useful for
95   // them either.
96   const GURL& url = match.url_info.url();
97   if (!url.is_valid() || !url.IsStandard() || url.SchemeIsFile())
98     return GURL();
99
100   // Transform to a host-only match.  Bail if the host no longer matches the
101   // user input (e.g. because the user typed more than just a host).
102   GURL host = url.GetWithEmptyPath();
103   if ((host.spec().length() < (match.input_location + input.length())))
104     return GURL();  // User typing is longer than this host suggestion.
105
106   const base::string16 spec = base::UTF8ToUTF16(host.spec());
107   if (spec.compare(match.input_location, input.length(), input))
108     return GURL();  // User typing is no longer a prefix.
109
110   return host;
111 }
112
113 // Acts like the > operator for URLInfo classes.
114 bool CompareHistoryMatch(const history::HistoryMatch& a,
115                          const history::HistoryMatch& b) {
116   // A promoted match is better than non-promoted.
117   if (a.promoted != b.promoted)
118     return a.promoted;
119
120   // A URL that has been typed at all is better than one that has never been
121   // typed.  (Note "!"s on each side)
122   if (!a.url_info.typed_count() != !b.url_info.typed_count())
123     return a.url_info.typed_count() > b.url_info.typed_count();
124
125   // Innermost matches (matches after any scheme or "www.") are better than
126   // non-innermost matches.
127   if (a.innermost_match != b.innermost_match)
128     return a.innermost_match;
129
130   // URLs that have been typed more often are better.
131   if (a.url_info.typed_count() != b.url_info.typed_count())
132     return a.url_info.typed_count() > b.url_info.typed_count();
133
134   // For URLs that have each been typed once, a host (alone) is better than a
135   // page inside.
136   if ((a.url_info.typed_count() == 1) && (a.IsHostOnly() != b.IsHostOnly()))
137     return a.IsHostOnly();
138
139   // URLs that have been visited more often are better.
140   if (a.url_info.visit_count() != b.url_info.visit_count())
141     return a.url_info.visit_count() > b.url_info.visit_count();
142
143   // URLs that have been visited more recently are better.
144   return a.url_info.last_visit() > b.url_info.last_visit();
145 }
146
147 // Sorts and dedups the given list of matches.
148 void SortAndDedupMatches(history::HistoryMatches* matches) {
149   // Sort by quality, best first.
150   std::sort(matches->begin(), matches->end(), &CompareHistoryMatch);
151
152   // Remove duplicate matches (caused by the search string appearing in one of
153   // the prefixes as well as after it).  Consider the following scenario:
154   //
155   // User has visited "http://http.com" once and "http://htaccess.com" twice.
156   // User types "http".  The autocomplete search with prefix "http://" returns
157   // the first host, while the search with prefix "" returns both hosts.  Now
158   // we sort them into rank order:
159   //   http://http.com     (innermost_match)
160   //   http://htaccess.com (!innermost_match, url_info.visit_count == 2)
161   //   http://http.com     (!innermost_match, url_info.visit_count == 1)
162   //
163   // The above scenario tells us we can't use std::unique(), since our
164   // duplicates are not always sequential.  It also tells us we should remove
165   // the lower-quality duplicate(s), since otherwise the returned results won't
166   // be ordered correctly.  This is easy to do: we just always remove the later
167   // element of a duplicate pair.
168   // Be careful!  Because the vector contents may change as we remove elements,
169   // we use an index instead of an iterator in the outer loop, and don't
170   // precalculate the ending position.
171   for (size_t i = 0; i < matches->size(); ++i) {
172     for (history::HistoryMatches::iterator j(matches->begin() + i + 1);
173          j != matches->end(); ) {
174       if ((*matches)[i].url_info.url() == j->url_info.url())
175         j = matches->erase(j);
176       else
177         ++j;
178     }
179   }
180 }
181
182 // Extracts typed_count, visit_count, and last_visited time from the
183 // URLRow and puts them in the additional info field of the |match|
184 // for display in about:omnibox.
185 void RecordAdditionalInfoFromUrlRow(const history::URLRow& info,
186                                     AutocompleteMatch* match) {
187   match->RecordAdditionalInfo("typed count", info.typed_count());
188   match->RecordAdditionalInfo("visit count", info.visit_count());
189   match->RecordAdditionalInfo("last visit", info.last_visit());
190 }
191
192 // Calculates a new relevance score applying half-life time decaying to |count|
193 // using |time_since_last_visit| and |score_buckets|.
194 // This function will never return a score higher than |undecayed_relevance|.
195 // In other words, it can only demote the old score.
196 double CalculateRelevanceUsingScoreBuckets(
197     const HUPScoringParams::ScoreBuckets& score_buckets,
198     const base::TimeDelta& time_since_last_visit,
199     int undecayed_relevance,
200     int count) {
201   // Back off if above relevance cap.
202   if ((score_buckets.relevance_cap() != -1) &&
203       (undecayed_relevance >= score_buckets.relevance_cap()))
204     return undecayed_relevance;
205
206   // Time based decay using half-life time.
207   double decayed_count = count;
208   if (decayed_count > 0)
209     decayed_count *= score_buckets.HalfLifeTimeDecay(time_since_last_visit);
210
211   // Find a threshold where decayed_count >= bucket.
212   const HUPScoringParams::ScoreBuckets::CountMaxRelevance* score_bucket = NULL;
213   for (size_t i = 0; i < score_buckets.buckets().size(); ++i) {
214     score_bucket = &score_buckets.buckets()[i];
215     if (decayed_count >= score_bucket->first)
216       break;  // Buckets are in descending order, so we can ignore the rest.
217   }
218
219   return (score_bucket && (undecayed_relevance > score_bucket->second)) ?
220       score_bucket->second : undecayed_relevance;
221 }
222
223 }  // namespace
224
225 // -----------------------------------------------------------------
226 // SearchTermsDataSnapshot
227
228 // Implementation of SearchTermsData that takes a snapshot of another
229 // SearchTermsData by copying all the responses to the different getters into
230 // member strings, then returning those strings when its own getters are called.
231 // This will typically be constructed on the UI thread from
232 // UIThreadSearchTermsData but is subsequently safe to use on any thread.
233 class SearchTermsDataSnapshot : public SearchTermsData {
234  public:
235   explicit SearchTermsDataSnapshot(const SearchTermsData& search_terms_data);
236   virtual ~SearchTermsDataSnapshot();
237
238   virtual std::string GoogleBaseURLValue() const OVERRIDE;
239   virtual std::string GetApplicationLocale() const OVERRIDE;
240   virtual base::string16 GetRlzParameterValue() const OVERRIDE;
241   virtual std::string GetSearchClient() const OVERRIDE;
242   virtual std::string ForceInstantResultsParam(
243       bool for_prerender) const OVERRIDE;
244   virtual std::string InstantExtendedEnabledParam() const OVERRIDE;
245   virtual std::string NTPIsThemedParam() const OVERRIDE;
246
247  private:
248   std::string google_base_url_value_;
249   std::string application_locale_;
250   base::string16 rlz_parameter_value_;
251   std::string search_client_;
252   std::string force_instant_results_param_;
253   std::string instant_extended_enabled_param_;
254   std::string ntp_is_themed_param_;
255
256   DISALLOW_COPY_AND_ASSIGN(SearchTermsDataSnapshot);
257 };
258
259 SearchTermsDataSnapshot::SearchTermsDataSnapshot(
260     const SearchTermsData& search_terms_data)
261     : google_base_url_value_(search_terms_data.GoogleBaseURLValue()),
262       application_locale_(search_terms_data.GetApplicationLocale()),
263       rlz_parameter_value_(search_terms_data.GetRlzParameterValue()),
264       search_client_(search_terms_data.GetSearchClient()),
265       force_instant_results_param_(
266           search_terms_data.ForceInstantResultsParam(false)),
267       instant_extended_enabled_param_(
268           search_terms_data.InstantExtendedEnabledParam()),
269       ntp_is_themed_param_(search_terms_data.NTPIsThemedParam()) {}
270
271 SearchTermsDataSnapshot::~SearchTermsDataSnapshot() {
272 }
273
274 std::string SearchTermsDataSnapshot::GoogleBaseURLValue() const {
275   return google_base_url_value_;
276 }
277
278 std::string SearchTermsDataSnapshot::GetApplicationLocale() const {
279   return application_locale_;
280 }
281
282 base::string16 SearchTermsDataSnapshot::GetRlzParameterValue() const {
283   return rlz_parameter_value_;
284 }
285
286 std::string SearchTermsDataSnapshot::GetSearchClient() const {
287   return search_client_;
288 }
289
290 std::string SearchTermsDataSnapshot::ForceInstantResultsParam(
291     bool for_prerender) const {
292   return force_instant_results_param_;
293 }
294
295 std::string SearchTermsDataSnapshot::InstantExtendedEnabledParam() const {
296   return instant_extended_enabled_param_;
297 }
298
299 std::string SearchTermsDataSnapshot::NTPIsThemedParam() const {
300   return ntp_is_themed_param_;
301 }
302
303 // -----------------------------------------------------------------
304 // HistoryURLProvider
305
306 // These ugly magic numbers will go away once we switch all scoring
307 // behavior (including URL-what-you-typed) to HistoryQuick provider.
308 const int HistoryURLProvider::kScoreForBestInlineableResult = 1413;
309 const int HistoryURLProvider::kScoreForUnvisitedIntranetResult = 1403;
310 const int HistoryURLProvider::kScoreForWhatYouTypedResult = 1203;
311 const int HistoryURLProvider::kBaseScoreForNonInlineableResult = 900;
312
313 // VisitClassifier is used to classify the type of visit to a particular url.
314 class HistoryURLProvider::VisitClassifier {
315  public:
316   enum Type {
317     INVALID,             // Navigations to the URL are not allowed.
318     UNVISITED_INTRANET,  // A navigable URL for which we have no visit data but
319                          // which is known to refer to a visited intranet host.
320     VISITED,             // The site has been previously visited.
321   };
322
323   VisitClassifier(HistoryURLProvider* provider,
324                   const AutocompleteInput& input,
325                   history::URLDatabase* db);
326
327   // Returns the type of visit for the specified input.
328   Type type() const { return type_; }
329
330   // Returns the URLRow for the visit.
331   const history::URLRow& url_row() const { return url_row_; }
332
333  private:
334   HistoryURLProvider* provider_;
335   history::URLDatabase* db_;
336   Type type_;
337   history::URLRow url_row_;
338
339   DISALLOW_COPY_AND_ASSIGN(VisitClassifier);
340 };
341
342 HistoryURLProvider::VisitClassifier::VisitClassifier(
343     HistoryURLProvider* provider,
344     const AutocompleteInput& input,
345     history::URLDatabase* db)
346     : provider_(provider),
347       db_(db),
348       type_(INVALID) {
349   const GURL& url = input.canonicalized_url();
350   // Detect email addresses.  These cases will look like "http://user@site/",
351   // and because the history backend strips auth creds, we'll get a bogus exact
352   // match below if the user has visited "site".
353   if (!url.is_valid() ||
354       ((input.type() == AutocompleteInput::UNKNOWN) &&
355        input.parts().username.is_nonempty() &&
356        !input.parts().password.is_nonempty() &&
357        !input.parts().path.is_nonempty()))
358     return;
359
360   if (db_->GetRowForURL(url, &url_row_)) {
361     type_ = VISITED;
362     return;
363   }
364
365   if (provider_->CanFindIntranetURL(db_, input)) {
366     // The user typed an intranet hostname that they've visited (albeit with a
367     // different port and/or path) before.
368     url_row_ = history::URLRow(url);
369     type_ = UNVISITED_INTRANET;
370   }
371 }
372
373 HistoryURLProviderParams::HistoryURLProviderParams(
374     const AutocompleteInput& input,
375     bool trim_http,
376     const std::string& languages,
377     TemplateURL* default_search_provider,
378     const SearchTermsData& search_terms_data)
379     : message_loop(base::MessageLoop::current()),
380       input(input),
381       prevent_inline_autocomplete(input.prevent_inline_autocomplete()),
382       trim_http(trim_http),
383       failed(false),
384       languages(languages),
385       dont_suggest_exact_input(false),
386       default_search_provider(default_search_provider ?
387           new TemplateURL(default_search_provider->profile(),
388                           default_search_provider->data()) : NULL),
389       search_terms_data(new SearchTermsDataSnapshot(search_terms_data)) {
390 }
391
392 HistoryURLProviderParams::~HistoryURLProviderParams() {
393 }
394
395 HistoryURLProvider::HistoryURLProvider(AutocompleteProviderListener* listener,
396                                        Profile* profile)
397     : HistoryProvider(listener, profile,
398           AutocompleteProvider::TYPE_HISTORY_URL),
399       params_(NULL),
400       cull_redirects_(
401           !OmniboxFieldTrial::InHUPCullRedirectsFieldTrial() ||
402           !OmniboxFieldTrial::InHUPCullRedirectsFieldTrialExperimentGroup()),
403       create_shorter_match_(
404           !OmniboxFieldTrial::InHUPCreateShorterMatchFieldTrial() ||
405           !OmniboxFieldTrial::
406               InHUPCreateShorterMatchFieldTrialExperimentGroup()),
407       search_url_database_(true) {
408   // Initialize HUP scoring params based on the current experiment.
409   OmniboxFieldTrial::GetExperimentalHUPScoringParams(&scoring_params_);
410 }
411
412 void HistoryURLProvider::Start(const AutocompleteInput& input,
413                                bool minimal_changes) {
414   // NOTE: We could try hard to do less work in the |minimal_changes| case
415   // here; some clever caching would let us reuse the raw matches from the
416   // history DB without re-querying.  However, we'd still have to go back to
417   // the history thread to mark these up properly, and if pass 2 is currently
418   // running, we'd need to wait for it to return to the main thread before
419   // doing this (we can't just write new data for it to read due to thread
420   // safety issues).  At that point it's just as fast, and easier, to simply
421   // re-run the query from scratch and ignore |minimal_changes|.
422
423   // Cancel any in-progress query.
424   Stop(false);
425
426   RunAutocompletePasses(input, true);
427 }
428
429 void HistoryURLProvider::Stop(bool clear_cached_results) {
430   done_ = true;
431
432   if (params_)
433     params_->cancel_flag.Set();
434 }
435
436 AutocompleteMatch HistoryURLProvider::SuggestExactInput(
437     const base::string16& text,
438     const GURL& destination_url,
439     bool trim_http) {
440   AutocompleteMatch match(this, 0, false,
441                           AutocompleteMatchType::URL_WHAT_YOU_TYPED);
442
443   if (destination_url.is_valid()) {
444     match.destination_url = destination_url;
445
446     // Trim off "http://" if the user didn't type it.
447     // NOTE: We use TrimHttpPrefix() here rather than StringForURLDisplay() to
448     // strip the scheme as we need to know the offset so we can adjust the
449     // |match_location| below.  StringForURLDisplay() and TrimHttpPrefix() have
450     // slightly different behavior as well (the latter will strip even without
451     // two slashes after the scheme).
452     DCHECK(!trim_http || !AutocompleteInput::HasHTTPScheme(text));
453     base::string16 display_string(
454         StringForURLDisplay(destination_url, false, false));
455     const size_t offset = trim_http ? TrimHttpPrefix(&display_string) : 0;
456     match.fill_into_edit =
457         AutocompleteInput::FormattedStringWithEquivalentMeaning(destination_url,
458                                                                 display_string);
459     match.allowed_to_be_default_match = true;
460     // NOTE: Don't set match.inline_autocompletion to something non-empty here;
461     // it's surprising and annoying.
462
463     // Try to highlight "innermost" match location.  If we fix up "w" into
464     // "www.w.com", we want to highlight the fifth character, not the first.
465     // This relies on match.destination_url being the non-prefix-trimmed version
466     // of match.contents.
467     match.contents = display_string;
468     const URLPrefix* best_prefix = URLPrefix::BestURLPrefix(
469         base::UTF8ToUTF16(destination_url.spec()), text);
470     // It's possible for match.destination_url to not contain the user's input
471     // at all (so |best_prefix| is NULL), for example if the input is
472     // "view-source:x" and |destination_url| has an inserted "http://" in the
473     // middle.
474     if (best_prefix == NULL) {
475       AutocompleteMatch::ClassifyMatchInString(text, match.contents,
476                                                ACMatchClassification::URL,
477                                                &match.contents_class);
478     } else {
479       AutocompleteMatch::ClassifyLocationInString(
480           best_prefix->prefix.length() - offset, text.length(),
481           match.contents.length(), ACMatchClassification::URL,
482           &match.contents_class);
483     }
484
485     match.is_history_what_you_typed_match = true;
486   }
487
488   return match;
489 }
490
491 // Called on the history thread.
492 void HistoryURLProvider::ExecuteWithDB(history::HistoryBackend* backend,
493                                        history::URLDatabase* db,
494                                        HistoryURLProviderParams* params) {
495   // We may get called with a NULL database if it couldn't be properly
496   // initialized.
497   if (!db) {
498     params->failed = true;
499   } else if (!params->cancel_flag.IsSet()) {
500     base::TimeTicks beginning_time = base::TimeTicks::Now();
501
502     DoAutocomplete(backend, db, params);
503
504     UMA_HISTOGRAM_TIMES("Autocomplete.HistoryAsyncQueryTime",
505                         base::TimeTicks::Now() - beginning_time);
506   }
507
508   // Return the results (if any) to the main thread.
509   params->message_loop->PostTask(FROM_HERE, base::Bind(
510       &HistoryURLProvider::QueryComplete, this, params));
511 }
512
513 // Used by both autocomplete passes, and therefore called on multiple different
514 // threads (though not simultaneously).
515 void HistoryURLProvider::DoAutocomplete(history::HistoryBackend* backend,
516                                         history::URLDatabase* db,
517                                         HistoryURLProviderParams* params) {
518   VisitClassifier classifier(this, params->input, db);
519   // Create a What You Typed match, which we'll need below.
520   //
521   // We display this to the user when there's a reasonable chance they actually
522   // care:
523   // * Their input can be opened as a URL, and
524   // * We parsed the input as a URL, or it starts with an explicit "http:" or
525   //   "https:".
526   //  that is when their input can be opened as a URL.
527   // Otherwise, this is just low-quality noise.  In the cases where we've parsed
528   // as UNKNOWN, we'll still show an accidental search infobar if need be.
529   bool have_what_you_typed_match =
530       params->input.canonicalized_url().is_valid() &&
531       (params->input.type() != AutocompleteInput::QUERY) &&
532       ((params->input.type() != AutocompleteInput::UNKNOWN) ||
533        (classifier.type() == VisitClassifier::UNVISITED_INTRANET) ||
534        !params->trim_http ||
535        (AutocompleteInput::NumNonHostComponents(params->input.parts()) > 0));
536   AutocompleteMatch what_you_typed_match(SuggestExactInput(
537       params->input.text(), params->input.canonicalized_url(),
538       params->trim_http));
539   what_you_typed_match.relevance = CalculateRelevance(WHAT_YOU_TYPED, 0);
540
541   // Get the matching URLs from the DB
542   history::URLRows url_matches;
543   history::HistoryMatches history_matches;
544
545   if (search_url_database_) {
546     const URLPrefixes& prefixes = URLPrefix::GetURLPrefixes();
547     for (URLPrefixes::const_iterator i(prefixes.begin()); i != prefixes.end();
548          ++i) {
549       if (params->cancel_flag.IsSet())
550         return;  // Canceled in the middle of a query, give up.
551       // We only need kMaxMatches results in the end, but before we
552       // get there we need to promote lower-quality matches that are
553       // prefixes of higher-quality matches, and remove lower-quality
554       // redirects.  So we ask for more results than we need, of every
555       // prefix type, in hopes this will give us far more than enough
556       // to work with.  CullRedirects() will then reduce the list to
557       // the best kMaxMatches results.
558       db->AutocompleteForPrefix(
559           base::UTF16ToUTF8(i->prefix + params->input.text()),
560           kMaxMatches * 2,
561           (backend == NULL),
562           &url_matches);
563       for (history::URLRows::const_iterator j(url_matches.begin());
564            j != url_matches.end(); ++j) {
565         const URLPrefix* best_prefix =
566             URLPrefix::BestURLPrefix(base::UTF8ToUTF16(j->url().spec()),
567                                      base::string16());
568         DCHECK(best_prefix != NULL);
569         history_matches.push_back(history::HistoryMatch(*j, i->prefix.length(),
570             i->num_components == 0,
571             i->num_components >= best_prefix->num_components));
572       }
573     }
574   }
575
576   // Create sorted list of suggestions.
577   CullPoorMatches(*params, &history_matches);
578   SortAndDedupMatches(&history_matches);
579   PromoteOrCreateShorterSuggestion(db, *params, have_what_you_typed_match,
580                                    what_you_typed_match, &history_matches);
581
582   // Try to promote a match as an exact/inline autocomplete match.  This also
583   // moves it to the front of |history_matches|, so skip over it when
584   // converting the rest of the matches.
585   size_t first_match = 1;
586   size_t exact_suggestion = 0;
587   // Checking |is_history_what_you_typed_match| tells us whether
588   // SuggestExactInput() succeeded in constructing a valid match.
589   if (what_you_typed_match.is_history_what_you_typed_match &&
590       (!backend || !params->dont_suggest_exact_input) &&
591       FixupExactSuggestion(db, params->input, classifier, &what_you_typed_match,
592                            &history_matches)) {
593     // Got an exact match for the user's input.  Treat it as the best match
594     // regardless of the input type.
595     exact_suggestion = 1;
596     params->matches.push_back(what_you_typed_match);
597   } else if (params->prevent_inline_autocomplete ||
598       history_matches.empty() ||
599       !PromoteMatchForInlineAutocomplete(history_matches.front(), params)) {
600     // Failed to promote any URLs for inline autocompletion.  Use the What You
601     // Typed match, if we have it.
602     first_match = 0;
603     if (have_what_you_typed_match)
604       params->matches.push_back(what_you_typed_match);
605   }
606
607   // This is the end of the synchronous pass.
608   if (!backend)
609     return;
610   // If search_url_database_ is false, we shouldn't have scheduled a second
611   // pass.
612   DCHECK(search_url_database_);
613
614   // Determine relevancy of highest scoring match, if any.
615   int relevance = -1;
616   for (ACMatches::const_iterator it = params->matches.begin();
617        it != params->matches.end(); ++it) {
618     relevance = std::max(relevance, it->relevance);
619   }
620
621   if (cull_redirects_) {
622     // Remove redirects and trim list to size.  We want to provide up to
623     // kMaxMatches results plus the What You Typed result, if it was added to
624     // |history_matches| above.
625     CullRedirects(backend, &history_matches, kMaxMatches + exact_suggestion);
626   } else {
627     // Simply trim the list to size.
628     if (history_matches.size() > kMaxMatches + exact_suggestion)
629       history_matches.resize(kMaxMatches + exact_suggestion);
630   }
631
632   // Convert the history matches to autocomplete matches.
633   for (size_t i = first_match; i < history_matches.size(); ++i) {
634     const history::HistoryMatch& match = history_matches[i];
635     DCHECK(!have_what_you_typed_match ||
636            (match.url_info.url() !=
637             GURL(params->matches.front().destination_url)));
638     // If we've assigned a score already, all later matches score one
639     // less than the previous match.
640     relevance = (relevance > 0) ? (relevance - 1) :
641        CalculateRelevance(NORMAL, history_matches.size() - 1 - i);
642     AutocompleteMatch ac_match = HistoryMatchToACMatch(*params, match,
643         NORMAL, relevance);
644     // The experimental scoring must not change the top result's score.
645     if (!params->matches.empty()) {
646       relevance = CalculateRelevanceScoreUsingScoringParams(match, relevance);
647       ac_match.relevance = relevance;
648     }
649     params->matches.push_back(ac_match);
650   }
651 }
652
653 // Called on the main thread when the query is complete.
654 void HistoryURLProvider::QueryComplete(
655     HistoryURLProviderParams* params_gets_deleted) {
656   // Ensure |params_gets_deleted| gets deleted on exit.
657   scoped_ptr<HistoryURLProviderParams> params(params_gets_deleted);
658
659   // If the user hasn't already started another query, clear our member pointer
660   // so we can't write into deleted memory.
661   if (params_ == params_gets_deleted)
662     params_ = NULL;
663
664   // Don't send responses for queries that have been canceled.
665   if (params->cancel_flag.IsSet())
666     return;  // Already set done_ when we canceled, no need to set it again.
667
668   // Don't modify |matches_| if the query failed, since it might have a default
669   // match in it, whereas |params->matches| will be empty.
670   if (!params->failed) {
671     matches_.swap(params->matches);
672     UpdateStarredStateOfMatches();
673   }
674
675   done_ = true;
676   listener_->OnProviderUpdate(true);
677 }
678
679 HistoryURLProvider::~HistoryURLProvider() {
680   // Note: This object can get leaked on shutdown if there are pending
681   // requests on the database (which hold a reference to us). Normally, these
682   // messages get flushed for each thread. We do a round trip from main, to
683   // history, back to main while holding a reference. If the main thread
684   // completes before the history thread, the message to delegate back to the
685   // main thread will not run and the reference will leak. Therefore, don't do
686   // anything on destruction.
687 }
688
689 int HistoryURLProvider::CalculateRelevance(MatchType match_type,
690                                            size_t match_number) const {
691   switch (match_type) {
692     case INLINE_AUTOCOMPLETE:
693       return kScoreForBestInlineableResult;
694
695     case UNVISITED_INTRANET:
696       return kScoreForUnvisitedIntranetResult;
697
698     case WHAT_YOU_TYPED:
699       return kScoreForWhatYouTypedResult;
700
701     default:  // NORMAL
702       return kBaseScoreForNonInlineableResult +
703           static_cast<int>(match_number);
704   }
705 }
706
707 void HistoryURLProvider::RunAutocompletePasses(
708     const AutocompleteInput& input,
709     bool fixup_input_and_run_pass_1) {
710   matches_.clear();
711
712   if ((input.type() == AutocompleteInput::INVALID) ||
713       (input.type() == AutocompleteInput::FORCED_QUERY))
714     return;
715
716   // Create a match for exactly what the user typed.  This will only be used as
717   // a fallback in case we can't get the history service or URL DB; otherwise,
718   // we'll run this again in DoAutocomplete() and use that result instead.
719   const bool trim_http = !AutocompleteInput::HasHTTPScheme(input.text());
720   // Don't do this for queries -- while we can sometimes mark up a match for
721   // this, it's not what the user wants, and just adds noise.
722   if ((input.type() != AutocompleteInput::QUERY) &&
723       input.canonicalized_url().is_valid()) {
724     AutocompleteMatch what_you_typed(SuggestExactInput(
725         input.text(), input.canonicalized_url(), trim_http));
726     what_you_typed.relevance = CalculateRelevance(WHAT_YOU_TYPED, 0);
727     matches_.push_back(what_you_typed);
728   }
729
730   // We'll need the history service to run both passes, so try to obtain it.
731   if (!profile_)
732     return;
733   HistoryService* const history_service =
734       HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
735   if (!history_service)
736     return;
737
738   // Get the default search provider and search terms data now since we have to
739   // retrieve these on the UI thread, and the second pass runs on the history
740   // thread. |template_url_service| can be NULL when testing.
741   TemplateURLService* template_url_service =
742       TemplateURLServiceFactory::GetForProfile(profile_);
743   TemplateURL* default_search_provider = template_url_service ?
744       template_url_service->GetDefaultSearchProvider() : NULL;
745   UIThreadSearchTermsData data(profile_);
746
747   // Create the data structure for the autocomplete passes.  We'll save this off
748   // onto the |params_| member for later deletion below if we need to run pass
749   // 2.
750   scoped_ptr<HistoryURLProviderParams> params(
751       new HistoryURLProviderParams(
752           input, trim_http,
753           profile_->GetPrefs()->GetString(prefs::kAcceptLanguages),
754           default_search_provider, data));
755
756   params->prevent_inline_autocomplete =
757       PreventInlineAutocomplete(input);
758
759   if (fixup_input_and_run_pass_1) {
760     // Do some fixup on the user input before matching against it, so we provide
761     // good results for local file paths, input with spaces, etc.
762     if (!FixupUserInput(&params->input))
763       return;
764
765     // Pass 1: Get the in-memory URL database, and use it to find and promote
766     // the inline autocomplete match, if any.
767     history::URLDatabase* url_db = history_service->InMemoryDatabase();
768     // url_db can be NULL if it hasn't finished initializing (or failed to
769     // initialize).  In this case all we can do is fall back on the second
770     // pass.
771     //
772     // TODO(pkasting): We should just block here until this loads.  Any time
773     // someone unloads the history backend, we'll get inconsistent inline
774     // autocomplete behavior here.
775     if (url_db) {
776       DoAutocomplete(NULL, url_db, params.get());
777       // params->matches now has the matches we should expose to the provider.
778       // Pass 2 expects a "clean slate" set of matches.
779       matches_.clear();
780       matches_.swap(params->matches);
781       UpdateStarredStateOfMatches();
782     }
783   }
784
785   // Pass 2: Ask the history service to call us back on the history thread,
786   // where we can read the full on-disk DB.
787   if (search_url_database_ &&
788       (input.matches_requested() == AutocompleteInput::ALL_MATCHES)) {
789     done_ = false;
790     params_ = params.release();  // This object will be destroyed in
791                                  // QueryComplete() once we're done with it.
792     history_service->ScheduleAutocomplete(this, params_);
793   }
794 }
795
796 bool HistoryURLProvider::FixupExactSuggestion(
797     history::URLDatabase* db,
798     const AutocompleteInput& input,
799     const VisitClassifier& classifier,
800     AutocompleteMatch* match,
801     history::HistoryMatches* matches) const {
802   DCHECK(match != NULL);
803   DCHECK(matches != NULL);
804
805   MatchType type = INLINE_AUTOCOMPLETE;
806   switch (classifier.type()) {
807     case VisitClassifier::INVALID:
808       return false;
809     case VisitClassifier::UNVISITED_INTRANET:
810       type = UNVISITED_INTRANET;
811       break;
812     default:
813       DCHECK_EQ(VisitClassifier::VISITED, classifier.type());
814       // We have data for this match, use it.
815       match->deletable = true;
816       match->description = classifier.url_row().title();
817       RecordAdditionalInfoFromUrlRow(classifier.url_row(), match);
818       match->description_class =
819           ClassifyDescription(input.text(), match->description);
820       if (!classifier.url_row().typed_count()) {
821         // If we reach here, we must be in the second pass, and we must not have
822         // this row's data available during the first pass.  That means we
823         // either scored it as WHAT_YOU_TYPED or UNVISITED_INTRANET, and to
824         // maintain the ordering between passes consistent, we need to score it
825         // the same way here.
826         type = CanFindIntranetURL(db, input) ?
827             UNVISITED_INTRANET : WHAT_YOU_TYPED;
828       }
829       break;
830   }
831
832   const GURL& url = match->destination_url;
833   const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
834   // If the what-you-typed result looks like a single word (which can be
835   // interpreted as an intranet address) followed by a pound sign ("#"),
836   // leave the score for the url-what-you-typed result as is.  It will be
837   // outscored by a search query from the SearchProvider. This test fixes
838   // cases such as "c#" and "c# foo" where the user has visited an intranet
839   // site "c".  We want the search-what-you-typed score to beat the
840   // URL-what-you-typed score in this case.  Most of the below test tries to
841   // make sure that this code does not trigger if the user did anything to
842   // indicate the desired match is a URL.  For instance, "c/# foo" will not
843   // pass the test because that will be classified as input type URL.  The
844   // parsed.CountCharactersBefore() in the test looks for the presence of a
845   // reference fragment in the URL by checking whether the position differs
846   // included the delimiter (pound sign) versus not including the delimiter.
847   // (One cannot simply check url.ref() because it will not distinguish
848   // between the input "c" and the input "c#", both of which will have empty
849   // reference fragments.)
850   if ((type == UNVISITED_INTRANET) &&
851       (input.type() != AutocompleteInput::URL) &&
852       url.username().empty() && url.password().empty() && url.port().empty() &&
853       (url.path() == "/") && url.query().empty() &&
854       (parsed.CountCharactersBefore(url_parse::Parsed::REF, true) !=
855        parsed.CountCharactersBefore(url_parse::Parsed::REF, false))) {
856     return false;
857   }
858
859   match->relevance = CalculateRelevance(type, 0);
860
861   // If there are any other matches, then don't promote this match here, in
862   // hopes the caller will be able to inline autocomplete a better suggestion.
863   // DoAutocomplete() will fall back on this match if inline autocompletion
864   // fails.  This matches how we react to never-visited URL inputs in the non-
865   // intranet case.
866   if (type == UNVISITED_INTRANET && !matches->empty())
867     return false;
868
869   // Put it on the front of the HistoryMatches for redirect culling.
870   CreateOrPromoteMatch(classifier.url_row(), base::string16::npos, false,
871                        matches, true, true);
872   return true;
873 }
874
875 bool HistoryURLProvider::CanFindIntranetURL(
876     history::URLDatabase* db,
877     const AutocompleteInput& input) const {
878   // Normally passing the first two conditions below ought to guarantee the
879   // third condition, but because FixupUserInput() can run and modify the
880   // input's text and parts between Parse() and here, it seems better to be
881   // paranoid and check.
882   if ((input.type() != AutocompleteInput::UNKNOWN) ||
883       !LowerCaseEqualsASCII(input.scheme(), content::kHttpScheme) ||
884       !input.parts().host.is_nonempty())
885     return false;
886   const std::string host(base::UTF16ToUTF8(
887       input.text().substr(input.parts().host.begin, input.parts().host.len)));
888   const size_t registry_length =
889       net::registry_controlled_domains::GetRegistryLength(
890           host,
891           net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
892           net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
893   return registry_length == 0 && db->IsTypedHost(host);
894 }
895
896 bool HistoryURLProvider::PromoteMatchForInlineAutocomplete(
897     const history::HistoryMatch& match,
898     HistoryURLProviderParams* params) {
899   // Promote the first match if it's been marked for promotion or typed at least
900   // n times, where n == 1 for "simple" (host-only) URLs and n == 2 for others.
901   // We set a higher bar for these long URLs because it's less likely that users
902   // will want to visit them again.  Even though we don't increment the
903   // typed_count for pasted-in URLs, if the user manually edits the URL or types
904   // some long thing in by hand, we wouldn't want to immediately start
905   // autocompleting it.
906   if (!match.promoted &&
907       (!match.url_info.typed_count() ||
908        ((match.url_info.typed_count() == 1) &&
909         !match.IsHostOnly())))
910     return false;
911
912   // In the case where the user has typed "foo.com" and visited (but not typed)
913   // "foo/", and the input is "foo", we can reach here for "foo.com" during the
914   // first pass but have the second pass suggest the exact input as a better
915   // URL.  Since we need both passes to agree, and since during the first pass
916   // there's no way to know about "foo/", make reaching this point prevent any
917   // future pass from suggesting the exact input as a better match.
918   if (params) {
919     params->dont_suggest_exact_input = true;
920     AutocompleteMatch ac_match = HistoryMatchToACMatch(
921         *params, match, INLINE_AUTOCOMPLETE,
922         CalculateRelevance(INLINE_AUTOCOMPLETE, 0));
923     params->matches.push_back(ac_match);
924   }
925   return true;
926 }
927
928 // See if a shorter version of the best match should be created, and if so place
929 // it at the front of |matches|.  This can suggest history URLs that are
930 // prefixes of the best match (if they've been visited enough, compared to the
931 // best match), or create host-only suggestions even when they haven't been
932 // visited before: if the user visited http://example.com/asdf once, we'll
933 // suggest http://example.com/ even if they've never been to it.
934 void HistoryURLProvider::PromoteOrCreateShorterSuggestion(
935     history::URLDatabase* db,
936     const HistoryURLProviderParams& params,
937     bool have_what_you_typed_match,
938     const AutocompleteMatch& what_you_typed_match,
939     history::HistoryMatches* matches) {
940   if (matches->empty())
941     return;  // No matches, nothing to do.
942
943   // Determine the base URL from which to search, and whether that URL could
944   // itself be added as a match.  We can add the base iff it's not "effectively
945   // the same" as any "what you typed" match.
946   const history::HistoryMatch& match = matches->front();
947   GURL search_base = ConvertToHostOnly(match, params.input.text());
948   bool can_add_search_base_to_matches = !have_what_you_typed_match;
949   if (search_base.is_empty()) {
950     // Search from what the user typed when we couldn't reduce the best match
951     // to a host.  Careful: use a substring of |match| here, rather than the
952     // first match in |params|, because they might have different prefixes.  If
953     // the user typed "google.com", |what_you_typed_match| will hold
954     // "http://google.com/", but |match| might begin with
955     // "http://www.google.com/".
956     // TODO: this should be cleaned up, and is probably incorrect for IDN.
957     std::string new_match = match.url_info.url().possibly_invalid_spec().
958         substr(0, match.input_location + params.input.text().length());
959     search_base = GURL(new_match);
960     // TODO(mrossetti): There is a degenerate case where the following may
961     // cause a failure: http://www/~someword/fubar.html. Diagnose.
962     // See: http://crbug.com/50101
963     if (search_base.is_empty())
964       return;  // Can't construct a valid URL from which to start a search.
965   } else if (!can_add_search_base_to_matches) {
966     can_add_search_base_to_matches =
967         (search_base != what_you_typed_match.destination_url);
968   }
969   if (search_base == match.url_info.url())
970     return;  // Couldn't shorten |match|, so no range of URLs to search over.
971
972   // Search the DB for short URLs between our base and |match|.
973   history::URLRow info(search_base);
974   bool promote = true;
975   // A short URL is only worth suggesting if it's been visited at least a third
976   // as often as the longer URL.
977   const int min_visit_count = ((match.url_info.visit_count() - 1) / 3) + 1;
978   // For stability between the in-memory and on-disk autocomplete passes, when
979   // the long URL has been typed before, only suggest shorter URLs that have
980   // also been typed.  Otherwise, the on-disk pass could suggest a shorter URL
981   // (which hasn't been typed) that the in-memory pass doesn't know about,
982   // thereby making the top match, and thus the behavior of inline
983   // autocomplete, unstable.
984   const int min_typed_count = match.url_info.typed_count() ? 1 : 0;
985   if (!db->FindShortestURLFromBase(search_base.possibly_invalid_spec(),
986           match.url_info.url().possibly_invalid_spec(), min_visit_count,
987           min_typed_count, can_add_search_base_to_matches, &info)) {
988     if (!can_add_search_base_to_matches)
989       return;  // Couldn't find anything and can't add the search base, bail.
990
991     // Try to get info on the search base itself.  Promote it to the top if the
992     // original best match isn't good enough to autocomplete.
993     db->GetRowForURL(search_base, &info);
994     promote = match.url_info.typed_count() <= 1;
995   }
996
997   // Promote or add the desired URL to the list of matches.
998   bool ensure_can_inline =
999       promote && PromoteMatchForInlineAutocomplete(match, NULL);
1000   ensure_can_inline &= CreateOrPromoteMatch(info, match.input_location,
1001       match.match_in_scheme, matches, create_shorter_match_, promote);
1002   if (ensure_can_inline)
1003     matches->front().promoted = true;
1004 }
1005
1006 void HistoryURLProvider::CullPoorMatches(
1007     const HistoryURLProviderParams& params,
1008     history::HistoryMatches* matches) const {
1009   const base::Time& threshold(history::AutocompleteAgeThreshold());
1010   for (history::HistoryMatches::iterator i(matches->begin());
1011        i != matches->end(); ) {
1012     if (RowQualifiesAsSignificant(i->url_info, threshold) &&
1013         !(params.default_search_provider &&
1014             params.default_search_provider->IsSearchURLUsingTermsData(
1015                 i->url_info.url(), *params.search_terms_data.get()))) {
1016       ++i;
1017     } else {
1018       i = matches->erase(i);
1019     }
1020   }
1021 }
1022
1023 void HistoryURLProvider::CullRedirects(history::HistoryBackend* backend,
1024                                        history::HistoryMatches* matches,
1025                                        size_t max_results) const {
1026   for (size_t source = 0;
1027        (source < matches->size()) && (source < max_results); ) {
1028     const GURL& url = (*matches)[source].url_info.url();
1029     // TODO(brettw) this should go away when everything uses GURL.
1030     history::RedirectList redirects;
1031     backend->GetMostRecentRedirectsFrom(url, &redirects);
1032     if (!redirects.empty()) {
1033       // Remove all but the first occurrence of any of these redirects in the
1034       // search results. We also must add the URL we queried for, since it may
1035       // not be the first match and we'd want to remove it.
1036       //
1037       // For example, when A redirects to B and our matches are [A, X, B],
1038       // we'll get B as the redirects from, and we want to remove the second
1039       // item of that pair, removing B. If A redirects to B and our matches are
1040       // [B, X, A], we'll want to remove A instead.
1041       redirects.push_back(url);
1042       source = RemoveSubsequentMatchesOf(matches, source, redirects);
1043     } else {
1044       // Advance to next item.
1045       source++;
1046     }
1047   }
1048
1049   if (matches->size() > max_results)
1050     matches->resize(max_results);
1051 }
1052
1053 size_t HistoryURLProvider::RemoveSubsequentMatchesOf(
1054     history::HistoryMatches* matches,
1055     size_t source_index,
1056     const std::vector<GURL>& remove) const {
1057   size_t next_index = source_index + 1;  // return value = item after source
1058
1059   // Find the first occurrence of any URL in the redirect chain. We want to
1060   // keep this one since it is rated the highest.
1061   history::HistoryMatches::iterator first(std::find_first_of(
1062       matches->begin(), matches->end(), remove.begin(), remove.end(),
1063       history::HistoryMatch::EqualsGURL));
1064   DCHECK(first != matches->end()) << "We should have always found at least the "
1065       "original URL.";
1066
1067   // Find any following occurrences of any URL in the redirect chain, these
1068   // should be deleted.
1069   for (history::HistoryMatches::iterator next(std::find_first_of(first + 1,
1070            matches->end(), remove.begin(), remove.end(),
1071            history::HistoryMatch::EqualsGURL));
1072        next != matches->end(); next = std::find_first_of(next, matches->end(),
1073            remove.begin(), remove.end(), history::HistoryMatch::EqualsGURL)) {
1074     // Remove this item. When we remove an item before the source index, we
1075     // need to shift it to the right and remember that so we can return it.
1076     next = matches->erase(next);
1077     if (static_cast<size_t>(next - matches->begin()) < next_index)
1078       --next_index;
1079   }
1080   return next_index;
1081 }
1082
1083 AutocompleteMatch HistoryURLProvider::HistoryMatchToACMatch(
1084     const HistoryURLProviderParams& params,
1085     const history::HistoryMatch& history_match,
1086     MatchType match_type,
1087     int relevance) {
1088   const history::URLRow& info = history_match.url_info;
1089   AutocompleteMatch match(this, relevance,
1090       !!info.visit_count(), AutocompleteMatchType::HISTORY_URL);
1091   match.typed_count = info.typed_count();
1092   match.destination_url = info.url();
1093   DCHECK(match.destination_url.is_valid());
1094   size_t inline_autocomplete_offset =
1095       history_match.input_location + params.input.text().length();
1096   std::string languages = (match_type == WHAT_YOU_TYPED) ?
1097       std::string() : params.languages;
1098   const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll &
1099       ~((params.trim_http && !history_match.match_in_scheme) ?
1100           0 : net::kFormatUrlOmitHTTP);
1101   match.fill_into_edit =
1102       AutocompleteInput::FormattedStringWithEquivalentMeaning(info.url(),
1103           net::FormatUrl(info.url(), languages, format_types,
1104                          net::UnescapeRule::SPACES, NULL, NULL,
1105                          &inline_autocomplete_offset));
1106   if (!params.prevent_inline_autocomplete &&
1107       (inline_autocomplete_offset != base::string16::npos)) {
1108     DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1109     match.inline_autocompletion =
1110         match.fill_into_edit.substr(inline_autocomplete_offset);
1111   }
1112   // The latter part of the test effectively asks "is the inline completion
1113   // empty?" (i.e., is this match effectively the what-you-typed match?).
1114   match.allowed_to_be_default_match = !params.prevent_inline_autocomplete ||
1115       ((inline_autocomplete_offset != base::string16::npos) &&
1116        (inline_autocomplete_offset >= match.fill_into_edit.length()));
1117
1118   size_t match_start = history_match.input_location;
1119   match.contents = net::FormatUrl(info.url(), languages,
1120       format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1121   if ((match_start != base::string16::npos) &&
1122       (inline_autocomplete_offset != base::string16::npos) &&
1123       (inline_autocomplete_offset != match_start)) {
1124     DCHECK(inline_autocomplete_offset > match_start);
1125     AutocompleteMatch::ClassifyLocationInString(match_start,
1126         inline_autocomplete_offset - match_start, match.contents.length(),
1127         ACMatchClassification::URL, &match.contents_class);
1128   } else {
1129     AutocompleteMatch::ClassifyLocationInString(base::string16::npos, 0,
1130         match.contents.length(), ACMatchClassification::URL,
1131         &match.contents_class);
1132   }
1133   match.description = info.title();
1134   match.description_class =
1135       ClassifyDescription(params.input.text(), match.description);
1136   RecordAdditionalInfoFromUrlRow(info, &match);
1137   return match;
1138 }
1139
1140 int HistoryURLProvider::CalculateRelevanceScoreUsingScoringParams(
1141     const history::HistoryMatch& match,
1142     int old_relevance) const {
1143   if (!scoring_params_.experimental_scoring_enabled)
1144     return old_relevance;
1145
1146   const base::TimeDelta time_since_last_visit =
1147       base::Time::Now() - match.url_info.last_visit();
1148
1149   int relevance = CalculateRelevanceUsingScoreBuckets(
1150       scoring_params_.typed_count_buckets, time_since_last_visit, old_relevance,
1151       match.url_info.typed_count());
1152
1153   // Additional demotion (on top of typed_count demotion) of URLs that were
1154   // never typed.
1155   if (match.url_info.typed_count() == 0) {
1156     relevance = CalculateRelevanceUsingScoreBuckets(
1157         scoring_params_.visited_count_buckets, time_since_last_visit, relevance,
1158         match.url_info.visit_count());
1159   }
1160
1161   DCHECK_LE(relevance, old_relevance);
1162   return relevance;
1163 }
1164
1165 // static
1166 ACMatchClassifications HistoryURLProvider::ClassifyDescription(
1167     const base::string16& input_text,
1168     const base::string16& description) {
1169   base::string16 clean_description = history::CleanUpTitleForMatching(
1170       description);
1171   history::TermMatches description_matches(SortAndDeoverlapMatches(
1172       history::MatchTermInString(input_text, clean_description, 0)));
1173   history::WordStarts description_word_starts;
1174   history::String16VectorFromString16(
1175       clean_description, false, &description_word_starts);
1176   description_matches =
1177       history::ScoredHistoryMatch::FilterTermMatchesByWordStarts(
1178           description_matches, description_word_starts, 0, std::string::npos);
1179   return SpansFromTermMatch(
1180       description_matches, clean_description.length(), false);
1181 }