1// Copyright (c) 2011 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/message_loop.h"
11#include "base/metrics/histogram.h"
12#include "base/string_util.h"
13#include "base/utf_string_conversions.h"
14#include "chrome/browser/autocomplete/autocomplete_match.h"
15#include "chrome/browser/history/history.h"
16#include "chrome/browser/history/history_backend.h"
17#include "chrome/browser/history/history_database.h"
18#include "chrome/browser/history/history_types.h"
19#include "chrome/browser/net/url_fixer_upper.h"
20#include "chrome/browser/prefs/pref_service.h"
21#include "chrome/browser/profiles/profile.h"
22#include "chrome/common/pref_names.h"
23#include "chrome/common/url_constants.h"
24#include "googleurl/src/gurl.h"
25#include "googleurl/src/url_parse.h"
26#include "googleurl/src/url_util.h"
27#include "net/base/net_util.h"
28
29using base::Time;
30using base::TimeDelta;
31using base::TimeTicks;
32using history::Prefix;
33using history::Prefixes;
34using history::HistoryMatch;
35using history::HistoryMatches;
36
37namespace history {
38
39// Returns true if |url| is just a host (e.g. "http://www.google.com/") and
40// not some other subpage (e.g. "http://www.google.com/foo.html").
41bool IsHostOnly(const GURL& url) {
42  DCHECK(url.is_valid());
43  return (!url.has_path() || (url.path() == "/")) && !url.has_query() &&
44      !url.has_ref();
45}
46
47// Acts like the > operator for URLInfo classes.
48bool CompareHistoryMatch(const HistoryMatch& a, const HistoryMatch& b) {
49  // A URL that has been typed at all is better than one that has never been
50  // typed.  (Note "!"s on each side)
51  if (!a.url_info.typed_count() != !b.url_info.typed_count())
52    return a.url_info.typed_count() > b.url_info.typed_count();
53
54  // Innermost matches (matches after any scheme or "www.") are better than
55  // non-innermost matches.
56  if (a.innermost_match != b.innermost_match)
57    return a.innermost_match;
58
59  // URLs that have been typed more often are better.
60  if (a.url_info.typed_count() != b.url_info.typed_count())
61    return a.url_info.typed_count() > b.url_info.typed_count();
62
63  // For URLs that have each been typed once, a host (alone) is better than a
64  // page inside.
65  if (a.url_info.typed_count() == 1) {
66    const bool a_is_host_only = history::IsHostOnly(a.url_info.url());
67    if (a_is_host_only != history::IsHostOnly(b.url_info.url()))
68      return a_is_host_only;
69  }
70
71  // URLs that have been visited more often are better.
72  if (a.url_info.visit_count() != b.url_info.visit_count())
73    return a.url_info.visit_count() > b.url_info.visit_count();
74
75  // URLs that have been visited more recently are better.
76  return a.url_info.last_visit() > b.url_info.last_visit();
77}
78
79// Given the user's |input| and a |match| created from it, reduce the
80// match's URL to just a host.  If this host still matches the user input,
81// return it.  Returns the empty string on failure.
82GURL ConvertToHostOnly(const HistoryMatch& match, const string16& input) {
83  // See if we should try to do host-only suggestions for this URL. Nonstandard
84  // schemes means there's no authority section, so suggesting the host name
85  // is useless. File URLs are standard, but host suggestion is not useful for
86  // them either.
87  const GURL& url = match.url_info.url();
88  if (!url.is_valid() || !url.IsStandard() || url.SchemeIsFile())
89    return GURL();
90
91  // Transform to a host-only match.  Bail if the host no longer matches the
92  // user input (e.g. because the user typed more than just a host).
93  GURL host = url.GetWithEmptyPath();
94  if ((host.spec().length() < (match.input_location + input.length())))
95    return GURL();  // User typing is longer than this host suggestion.
96
97  const string16 spec = UTF8ToUTF16(host.spec());
98  if (spec.compare(match.input_location, input.length(), input))
99    return GURL();  // User typing is no longer a prefix.
100
101  return host;
102}
103
104}  // namespace history
105
106HistoryURLProviderParams::HistoryURLProviderParams(
107    const AutocompleteInput& input,
108    bool trim_http,
109    const std::string& languages)
110    : message_loop(MessageLoop::current()),
111      input(input),
112      trim_http(trim_http),
113      cancel(false),
114      failed(false),
115      languages(languages),
116      dont_suggest_exact_input(false) {
117}
118
119HistoryURLProviderParams::~HistoryURLProviderParams() {}
120
121HistoryURLProvider::HistoryURLProvider(ACProviderListener* listener,
122                                       Profile* profile)
123    : HistoryProvider(listener, profile, "HistoryURL"),
124      prefixes_(GetPrefixes()),
125      params_(NULL) {
126}
127
128void HistoryURLProvider::Start(const AutocompleteInput& input,
129                               bool minimal_changes) {
130  // NOTE: We could try hard to do less work in the |minimal_changes| case
131  // here; some clever caching would let us reuse the raw matches from the
132  // history DB without re-querying.  However, we'd still have to go back to
133  // the history thread to mark these up properly, and if pass 2 is currently
134  // running, we'd need to wait for it to return to the main thread before
135  // doing this (we can't just write new data for it to read due to thread
136  // safety issues).  At that point it's just as fast, and easier, to simply
137  // re-run the query from scratch and ignore |minimal_changes|.
138
139  // Cancel any in-progress query.
140  Stop();
141
142  RunAutocompletePasses(input, true);
143}
144
145void HistoryURLProvider::Stop() {
146  done_ = true;
147
148  if (params_)
149    params_->cancel = true;
150}
151
152// Called on the history thread.
153void HistoryURLProvider::ExecuteWithDB(history::HistoryBackend* backend,
154                                       history::URLDatabase* db,
155                                       HistoryURLProviderParams* params) {
156  // We may get called with a NULL database if it couldn't be properly
157  // initialized.
158  if (!db) {
159    params->failed = true;
160  } else if (!params->cancel) {
161    TimeTicks beginning_time = TimeTicks::Now();
162
163    DoAutocomplete(backend, db, params);
164
165    UMA_HISTOGRAM_TIMES("Autocomplete.HistoryAsyncQueryTime",
166                        TimeTicks::Now() - beginning_time);
167  }
168
169  // Return the results (if any) to the main thread.
170  params->message_loop->PostTask(FROM_HERE, NewRunnableMethod(
171      this, &HistoryURLProvider::QueryComplete, params));
172}
173
174// Used by both autocomplete passes, and therefore called on multiple different
175// threads (though not simultaneously).
176void HistoryURLProvider::DoAutocomplete(history::HistoryBackend* backend,
177                                        history::URLDatabase* db,
178                                        HistoryURLProviderParams* params) {
179  // Create a What You Typed match, which we'll need below.
180  //
181  // We display this to the user when there's a reasonable chance they actually
182  // care:
183  // * Their input can be opened as a URL, and
184  // * They hit ctrl-enter, or we parsed the input as a URL, or it starts with
185  //   an explicit "http:" or "https:".
186  // Otherwise, this is just low-quality noise.  In the cases where we've parsed
187  // as UNKNOWN, we'll still show an accidental search infobar if need be.
188  bool have_what_you_typed_match =
189      params->input.canonicalized_url().is_valid() &&
190      (params->input.type() != AutocompleteInput::QUERY) &&
191      ((params->input.type() != AutocompleteInput::UNKNOWN) ||
192          !params->trim_http ||
193          url_util::FindAndCompareScheme(UTF16ToUTF8(params->input.text()),
194                                         chrome::kHttpsScheme, NULL));
195  AutocompleteMatch what_you_typed_match(SuggestExactInput(params->input,
196                                                           params->trim_http));
197
198  // Get the matching URLs from the DB
199  typedef std::vector<history::URLRow> URLRowVector;
200  URLRowVector url_matches;
201  HistoryMatches history_matches;
202
203  for (Prefixes::const_iterator i(prefixes_.begin()); i != prefixes_.end();
204       ++i) {
205    if (params->cancel)
206      return;  // Canceled in the middle of a query, give up.
207    // We only need kMaxMatches results in the end, but before we get there we
208    // need to promote lower-quality matches that are prefixes of
209    // higher-quality matches, and remove lower-quality redirects.  So we ask
210    // for more results than we need, of every prefix type, in hopes this will
211    // give us far more than enough to work with.  CullRedirects() will then
212    // reduce the list to the best kMaxMatches results.
213    db->AutocompleteForPrefix(i->prefix + params->input.text(),
214                              kMaxMatches * 2, (backend == NULL), &url_matches);
215    for (URLRowVector::const_iterator j(url_matches.begin());
216         j != url_matches.end(); ++j) {
217      const Prefix* best_prefix = BestPrefix(j->url(), string16());
218      DCHECK(best_prefix != NULL);
219      history_matches.push_back(HistoryMatch(*j, i->prefix.length(),
220          !i->num_components,
221          i->num_components >= best_prefix->num_components));
222    }
223  }
224
225  // Create sorted list of suggestions.
226  CullPoorMatches(&history_matches);
227  SortMatches(&history_matches);
228  PromoteOrCreateShorterSuggestion(db, *params, have_what_you_typed_match,
229                                   what_you_typed_match, &history_matches);
230
231  // Try to promote a match as an exact/inline autocomplete match.  This also
232  // moves it to the front of |history_matches|, so skip over it when
233  // converting the rest of the matches.
234  size_t first_match = 1;
235  size_t exact_suggestion = 0;
236  // Checking |is_history_what_you_typed_match| tells us whether
237  // SuggestExactInput() succeeded in constructing a valid match.
238  if (what_you_typed_match.is_history_what_you_typed_match &&
239      (!backend || !params->dont_suggest_exact_input) &&
240      FixupExactSuggestion(db, params->input, &what_you_typed_match,
241                           &history_matches)) {
242    // Got an exact match for the user's input.  Treat it as the best match
243    // regardless of the input type.
244    exact_suggestion = 1;
245    params->matches.push_back(what_you_typed_match);
246  } else if (params->input.prevent_inline_autocomplete() ||
247      history_matches.empty() ||
248      !PromoteMatchForInlineAutocomplete(params, history_matches.front())) {
249    // Failed to promote any URLs for inline autocompletion.  Use the What You
250    // Typed match, if we have it.
251    first_match = 0;
252    if (have_what_you_typed_match)
253      params->matches.push_back(what_you_typed_match);
254  }
255
256  // This is the end of the synchronous pass.
257  if (!backend)
258    return;
259
260  // Remove redirects and trim list to size.  We want to provide up to
261  // kMaxMatches results plus the What You Typed result, if it was added to
262  // |history_matches| above.
263  CullRedirects(backend, &history_matches, kMaxMatches + exact_suggestion);
264
265  // Convert the history matches to autocomplete matches.
266  for (size_t i = first_match; i < history_matches.size(); ++i) {
267    const HistoryMatch& match = history_matches[i];
268    DCHECK(!have_what_you_typed_match ||
269           (match.url_info.url() !=
270            GURL(params->matches.front().destination_url)));
271    params->matches.push_back(HistoryMatchToACMatch(params, match, NORMAL,
272        history_matches.size() - 1 - i));
273  }
274}
275
276// Called on the main thread when the query is complete.
277void HistoryURLProvider::QueryComplete(
278    HistoryURLProviderParams* params_gets_deleted) {
279  // Ensure |params_gets_deleted| gets deleted on exit.
280  scoped_ptr<HistoryURLProviderParams> params(params_gets_deleted);
281
282  // If the user hasn't already started another query, clear our member pointer
283  // so we can't write into deleted memory.
284  if (params_ == params_gets_deleted)
285    params_ = NULL;
286
287  // Don't send responses for queries that have been canceled.
288  if (params->cancel)
289    return;  // Already set done_ when we canceled, no need to set it again.
290
291  // Don't modify |matches_| if the query failed, since it might have a default
292  // match in it, whereas |params->matches| will be empty.
293  if (!params->failed) {
294    matches_.swap(params->matches);
295    UpdateStarredStateOfMatches();
296  }
297
298  done_ = true;
299  listener_->OnProviderUpdate(true);
300}
301
302AutocompleteMatch HistoryURLProvider::SuggestExactInput(
303    const AutocompleteInput& input,
304    bool trim_http) {
305  AutocompleteMatch match(this,
306      CalculateRelevance(input.type(), WHAT_YOU_TYPED, 0), false,
307      AutocompleteMatch::URL_WHAT_YOU_TYPED);
308
309  const GURL& url = input.canonicalized_url();
310  if (url.is_valid()) {
311    match.destination_url = url;
312
313    // Trim off "http://" if the user didn't type it.
314    // NOTE: We use TrimHttpPrefix() here rather than StringForURLDisplay() to
315    // strip the scheme as we need to know the offset so we can adjust the
316    // |match_location| below.  StringForURLDisplay() and TrimHttpPrefix() have
317    // slightly different behavior as well (the latter will strip even without
318    // two slashes after the scheme).
319    string16 display_string(StringForURLDisplay(url, false, false));
320    const size_t offset = trim_http ? TrimHttpPrefix(&display_string) : 0;
321    match.fill_into_edit =
322        AutocompleteInput::FormattedStringWithEquivalentMeaning(url,
323                                                                display_string);
324    // NOTE: Don't set match.input_location (to allow inline autocompletion)
325    // here, it's surprising and annoying.
326
327    // Try to highlight "innermost" match location.  If we fix up "w" into
328    // "www.w.com", we want to highlight the fifth character, not the first.
329    // This relies on match.destination_url being the non-prefix-trimmed version
330    // of match.contents.
331    match.contents = display_string;
332    const Prefix* best_prefix = BestPrefix(match.destination_url, input.text());
333    // Because of the vagaries of GURL, it's possible for match.destination_url
334    // to not contain the user's input at all.  In this case don't mark anything
335    // as a match.
336    const size_t match_location = (best_prefix == NULL) ?
337        string16::npos : best_prefix->prefix.length() - offset;
338    AutocompleteMatch::ClassifyLocationInString(match_location,
339                                                input.text().length(),
340                                                match.contents.length(),
341                                                ACMatchClassification::URL,
342                                                &match.contents_class);
343
344    match.is_history_what_you_typed_match = true;
345  }
346
347  return match;
348}
349
350bool HistoryURLProvider::FixupExactSuggestion(history::URLDatabase* db,
351                                              const AutocompleteInput& input,
352                                              AutocompleteMatch* match,
353                                              HistoryMatches* matches) const {
354  DCHECK(match != NULL);
355  DCHECK(matches != NULL);
356
357  // Tricky corner case: The user has visited intranet site "foo", but not
358  // internet site "www.foo.com".  He types in foo (getting an exact match),
359  // then tries to hit ctrl-enter.  When pressing ctrl, the what-you-typed
360  // match ("www.foo.com") doesn't show up in history, and thus doesn't get a
361  // promoted relevance, but a different match from the input ("foo") does, and
362  // gets promoted for inline autocomplete.  Thus instead of getting
363  // "www.foo.com", the user still gets "foo" (and, before hitting enter,
364  // probably gets an odd-looking inline autocomplete of "/").
365  //
366  // We detect this crazy case as follows:
367  // * If the what-you-typed match is not in the history DB,
368  // * and the user has specified a TLD,
369  // * and the input _without_ the TLD _is_ in the history DB,
370  // * ...then just before pressing "ctrl" the best match we supplied was the
371  //   what-you-typed match, so stick with it by promoting this.
372  history::URLRow info;
373  MatchType type = INLINE_AUTOCOMPLETE;
374  if (!db->GetRowForURL(match->destination_url, &info)) {
375    if (input.desired_tld().empty())
376      return false;
377    GURL destination_url(URLFixerUpper::FixupURL(UTF16ToUTF8(input.text()),
378                                                 std::string()));
379    if (!db->GetRowForURL(destination_url, NULL))
380      return false;
381
382    // If we got here, then we hit the tricky corner case.  Make sure that
383    // |info| corresponds to the right URL.
384    info = history::URLRow(match->destination_url);
385  } else {
386    // We have data for this match, use it.
387    match->deletable = true;
388    match->description = info.title();
389    AutocompleteMatch::ClassifyMatchInString(input.text(),
390        info.title(),
391        ACMatchClassification::NONE, &match->description_class);
392    if (!info.typed_count()) {
393      // If we reach here, we must be in the second pass, and we must not have
394      // promoted this match as an exact match during the first pass.  That
395      // means it will have been outscored by the "search what you typed match".
396      // We need to maintain that ordering in order to not make the destination
397      // for the user's typing change depending on when they hit enter.  So
398      // lower the score here enough to let the search provider continue to
399      // outscore this match.
400      type = WHAT_YOU_TYPED;
401    }
402  }
403
404  // Promote as an exact match.
405  match->relevance = CalculateRelevance(input.type(), type, 0);
406
407  // Put it on the front of the HistoryMatches for redirect culling.
408  EnsureMatchPresent(info, string16::npos, false, matches, true);
409  return true;
410}
411
412bool HistoryURLProvider::PromoteMatchForInlineAutocomplete(
413    HistoryURLProviderParams* params,
414    const HistoryMatch& match) {
415  // Promote the first match if it's been typed at least n times, where n == 1
416  // for "simple" (host-only) URLs and n == 2 for others.  We set a higher bar
417  // for these long URLs because it's less likely that users will want to visit
418  // them again.  Even though we don't increment the typed_count for pasted-in
419  // URLs, if the user manually edits the URL or types some long thing in by
420  // hand, we wouldn't want to immediately start autocompleting it.
421  if (!match.url_info.typed_count() ||
422      ((match.url_info.typed_count() == 1) &&
423       !history::IsHostOnly(match.url_info.url())))
424    return false;
425
426  // In the case where the user has typed "foo.com" and visited (but not typed)
427  // "foo/", and the input is "foo", we can reach here for "foo.com" during the
428  // first pass but have the second pass suggest the exact input as a better
429  // URL.  Since we need both passes to agree, and since during the first pass
430  // there's no way to know about "foo/", make reaching this point prevent any
431  // future pass from suggesting the exact input as a better match.
432  params->dont_suggest_exact_input = true;
433  params->matches.push_back(HistoryMatchToACMatch(params, match,
434                                                  INLINE_AUTOCOMPLETE, 0));
435  return true;
436}
437
438HistoryURLProvider::~HistoryURLProvider() {}
439
440// static
441history::Prefixes HistoryURLProvider::GetPrefixes() {
442  // We'll complete text following these prefixes.
443  // NOTE: There's no requirement that these be in any particular order.
444  Prefixes prefixes;
445  prefixes.push_back(Prefix(ASCIIToUTF16("https://www."), 2));
446  prefixes.push_back(Prefix(ASCIIToUTF16("http://www."), 2));
447  prefixes.push_back(Prefix(ASCIIToUTF16("ftp://ftp."), 2));
448  prefixes.push_back(Prefix(ASCIIToUTF16("ftp://www."), 2));
449  prefixes.push_back(Prefix(ASCIIToUTF16("https://"), 1));
450  prefixes.push_back(Prefix(ASCIIToUTF16("http://"), 1));
451  prefixes.push_back(Prefix(ASCIIToUTF16("ftp://"), 1));
452  // Empty string catches within-scheme matches as well.
453  prefixes.push_back(Prefix(string16(), 0));
454  return prefixes;
455}
456
457// static
458int HistoryURLProvider::CalculateRelevance(AutocompleteInput::Type input_type,
459                                           MatchType match_type,
460                                           size_t match_number) {
461  switch (match_type) {
462    case INLINE_AUTOCOMPLETE:
463      return 1400;
464
465    case WHAT_YOU_TYPED:
466      return 1200;
467
468    default:
469      return 900 + static_cast<int>(match_number);
470  }
471}
472
473// static
474void HistoryURLProvider::PromoteOrCreateShorterSuggestion(
475    history::URLDatabase* db,
476    const HistoryURLProviderParams& params,
477    bool have_what_you_typed_match,
478    const AutocompleteMatch& what_you_typed_match,
479    HistoryMatches* matches) {
480  if (matches->empty())
481    return;  // No matches, nothing to do.
482
483  // Determine the base URL from which to search, and whether that URL could
484  // itself be added as a match.  We can add the base iff it's not "effectively
485  // the same" as any "what you typed" match.
486  const HistoryMatch& match = matches->front();
487  GURL search_base = history::ConvertToHostOnly(match, params.input.text());
488  bool can_add_search_base_to_matches = !have_what_you_typed_match;
489  if (search_base.is_empty()) {
490    // Search from what the user typed when we couldn't reduce the best match
491    // to a host.  Careful: use a substring of |match| here, rather than the
492    // first match in |params|, because they might have different prefixes.  If
493    // the user typed "google.com", |what_you_typed_match| will hold
494    // "http://google.com/", but |match| might begin with
495    // "http://www.google.com/".
496    // TODO: this should be cleaned up, and is probably incorrect for IDN.
497    std::string new_match = match.url_info.url().possibly_invalid_spec().
498        substr(0, match.input_location + params.input.text().length());
499    search_base = GURL(new_match);
500    // TODO(mrossetti): There is a degenerate case where the following may
501    // cause a failure: http://www/~someword/fubar.html. Diagnose.
502    // See: http://crbug.com/50101
503    if (search_base.is_empty())
504      return;  // Can't construct a valid URL from which to start a search.
505  } else if (!can_add_search_base_to_matches) {
506    can_add_search_base_to_matches =
507        (search_base != what_you_typed_match.destination_url);
508  }
509  if (search_base == match.url_info.url())
510    return;  // Couldn't shorten |match|, so no range of URLs to search over.
511
512  // Search the DB for short URLs between our base and |match|.
513  history::URLRow info(search_base);
514  bool promote = true;
515  // A short URL is only worth suggesting if it's been visited at least a third
516  // as often as the longer URL.
517  const int min_visit_count = ((match.url_info.visit_count() - 1) / 3) + 1;
518  // For stability between the in-memory and on-disk autocomplete passes, when
519  // the long URL has been typed before, only suggest shorter URLs that have
520  // also been typed.  Otherwise, the on-disk pass could suggest a shorter URL
521  // (which hasn't been typed) that the in-memory pass doesn't know about,
522  // thereby making the top match, and thus the behavior of inline
523  // autocomplete, unstable.
524  const int min_typed_count = match.url_info.typed_count() ? 1 : 0;
525  if (!db->FindShortestURLFromBase(search_base.possibly_invalid_spec(),
526          match.url_info.url().possibly_invalid_spec(), min_visit_count,
527          min_typed_count, can_add_search_base_to_matches, &info)) {
528    if (!can_add_search_base_to_matches)
529      return;  // Couldn't find anything and can't add the search base, bail.
530
531    // Try to get info on the search base itself.  Promote it to the top if the
532    // original best match isn't good enough to autocomplete.
533    db->GetRowForURL(search_base, &info);
534    promote = match.url_info.typed_count() <= 1;
535  }
536
537  // Promote or add the desired URL to the list of matches.
538  EnsureMatchPresent(info, match.input_location, match.match_in_scheme,
539                     matches, promote);
540}
541
542// static
543void HistoryURLProvider::EnsureMatchPresent(
544    const history::URLRow& info,
545    string16::size_type input_location,
546    bool match_in_scheme,
547    HistoryMatches* matches,
548    bool promote) {
549  // |matches| may already have an entry for this.
550  for (HistoryMatches::iterator i(matches->begin()); i != matches->end();
551       ++i) {
552    if (i->url_info.url() == info.url()) {
553      // Rotate it to the front if the caller wishes.
554      if (promote)
555        std::rotate(matches->begin(), i, i + 1);
556      return;
557    }
558  }
559
560  // No entry, so create one.
561  HistoryMatch match(info, input_location, match_in_scheme, true);
562  if (promote)
563    matches->push_front(match);
564  else
565    matches->push_back(match);
566}
567
568void HistoryURLProvider::RunAutocompletePasses(
569    const AutocompleteInput& input,
570    bool fixup_input_and_run_pass_1) {
571  matches_.clear();
572
573  if ((input.type() == AutocompleteInput::INVALID) ||
574      (input.type() == AutocompleteInput::FORCED_QUERY))
575    return;
576
577  // Create a match for exactly what the user typed.  This will only be used as
578  // a fallback in case we can't get the history service or URL DB; otherwise,
579  // we'll run this again in DoAutocomplete() and use that result instead.
580  const bool trim_http = !HasHTTPScheme(input.text());
581  // Don't do this for queries -- while we can sometimes mark up a match for
582  // this, it's not what the user wants, and just adds noise.
583  if ((input.type() != AutocompleteInput::QUERY) &&
584      input.canonicalized_url().is_valid())
585    matches_.push_back(SuggestExactInput(input, trim_http));
586
587  // We'll need the history service to run both passes, so try to obtain it.
588  if (!profile_)
589    return;
590  HistoryService* const history_service =
591      profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
592  if (!history_service)
593    return;
594
595  // Create the data structure for the autocomplete passes.  We'll save this off
596  // onto the |params_| member for later deletion below if we need to run pass
597  // 2.
598  std::string languages(languages_);
599  if (languages.empty()) {
600    languages =
601        profile_->GetPrefs()->GetString(prefs::kAcceptLanguages);
602  }
603  scoped_ptr<HistoryURLProviderParams> params(
604      new HistoryURLProviderParams(input, trim_http, languages));
605
606  if (fixup_input_and_run_pass_1) {
607    // Do some fixup on the user input before matching against it, so we provide
608    // good results for local file paths, input with spaces, etc.
609    // NOTE: This purposefully doesn't take input.desired_tld() into account; if
610    // it did, then holding "ctrl" would change all the results from the
611    // HistoryURLProvider provider, not just the What You Typed Result.
612    const string16 fixed_text(FixupUserInput(input));
613    if (fixed_text.empty()) {
614      // Conceivably fixup could result in an empty string (although I don't
615      // have cases where this happens offhand).  We can't do anything with
616      // empty input, so just bail; otherwise we'd crash later.
617      return;
618    }
619    params->input.set_text(fixed_text);
620
621    // Pass 1: Get the in-memory URL database, and use it to find and promote
622    // the inline autocomplete match, if any.
623    history::URLDatabase* url_db = history_service->InMemoryDatabase();
624    // url_db can be NULL if it hasn't finished initializing (or failed to
625    // initialize).  In this case all we can do is fall back on the second
626    // pass.
627    //
628    // TODO(pkasting): We should just block here until this loads.  Any time
629    // someone unloads the history backend, we'll get inconsistent inline
630    // autocomplete behavior here.
631    if (url_db) {
632      DoAutocomplete(NULL, url_db, params.get());
633      // params->matches now has the matches we should expose to the provider.
634      // Pass 2 expects a "clean slate" set of matches.
635      matches_.clear();
636      matches_.swap(params->matches);
637      UpdateStarredStateOfMatches();
638    }
639  }
640
641  // Pass 2: Ask the history service to call us back on the history thread,
642  // where we can read the full on-disk DB.
643  if (input.matches_requested() == AutocompleteInput::ALL_MATCHES) {
644    done_ = false;
645    params_ = params.release();  // This object will be destroyed in
646                                 // QueryComplete() once we're done with it.
647    history_service->ScheduleAutocomplete(this, params_);
648  }
649}
650
651const history::Prefix* HistoryURLProvider::BestPrefix(
652    const GURL& url,
653    const string16& prefix_suffix) const {
654  const Prefix* best_prefix = NULL;
655  const string16 text(UTF8ToUTF16(url.spec()));
656  for (Prefixes::const_iterator i(prefixes_.begin()); i != prefixes_.end();
657       ++i) {
658    if ((best_prefix == NULL) ||
659        (i->num_components > best_prefix->num_components)) {
660      string16 prefix_with_suffix(i->prefix + prefix_suffix);
661      if ((text.length() >= prefix_with_suffix.length()) &&
662          !text.compare(0, prefix_with_suffix.length(), prefix_with_suffix))
663        best_prefix = &(*i);
664    }
665  }
666  return best_prefix;
667}
668
669void HistoryURLProvider::SortMatches(HistoryMatches* matches) const {
670  // Sort by quality, best first.
671  std::sort(matches->begin(), matches->end(), &history::CompareHistoryMatch);
672
673  // Remove duplicate matches (caused by the search string appearing in one of
674  // the prefixes as well as after it).  Consider the following scenario:
675  //
676  // User has visited "http://http.com" once and "http://htaccess.com" twice.
677  // User types "http".  The autocomplete search with prefix "http://" returns
678  // the first host, while the search with prefix "" returns both hosts.  Now
679  // we sort them into rank order:
680  //   http://http.com     (innermost_match)
681  //   http://htaccess.com (!innermost_match, url_info.visit_count == 2)
682  //   http://http.com     (!innermost_match, url_info.visit_count == 1)
683  //
684  // The above scenario tells us we can't use std::unique(), since our
685  // duplicates are not always sequential.  It also tells us we should remove
686  // the lower-quality duplicate(s), since otherwise the returned results won't
687  // be ordered correctly.  This is easy to do: we just always remove the later
688  // element of a duplicate pair.
689  // Be careful!  Because the vector contents may change as we remove elements,
690  // we use an index instead of an iterator in the outer loop, and don't
691  // precalculate the ending position.
692  for (size_t i = 0; i < matches->size(); ++i) {
693    HistoryMatches::iterator j(matches->begin() + i + 1);
694    while (j != matches->end()) {
695      if ((*matches)[i].url_info.url() == j->url_info.url())
696        j = matches->erase(j);
697      else
698        ++j;
699    }
700  }
701}
702
703void HistoryURLProvider::CullPoorMatches(HistoryMatches* matches) const {
704  const base::Time& threshold(history::AutocompleteAgeThreshold());
705  for (HistoryMatches::iterator i(matches->begin()); i != matches->end();) {
706    if (RowQualifiesAsSignificant(i->url_info, threshold))
707      ++i;
708    else
709      i = matches->erase(i);
710  }
711}
712
713void HistoryURLProvider::CullRedirects(history::HistoryBackend* backend,
714                                       HistoryMatches* matches,
715                                       size_t max_results) const {
716  for (size_t source = 0;
717       (source < matches->size()) && (source < max_results); ) {
718    const GURL& url = (*matches)[source].url_info.url();
719    // TODO(brettw) this should go away when everything uses GURL.
720    history::RedirectList redirects;
721    backend->GetMostRecentRedirectsFrom(url, &redirects);
722    if (!redirects.empty()) {
723      // Remove all but the first occurrence of any of these redirects in the
724      // search results. We also must add the URL we queried for, since it may
725      // not be the first match and we'd want to remove it.
726      //
727      // For example, when A redirects to B and our matches are [A, X, B],
728      // we'll get B as the redirects from, and we want to remove the second
729      // item of that pair, removing B. If A redirects to B and our matches are
730      // [B, X, A], we'll want to remove A instead.
731      redirects.push_back(url);
732      source = RemoveSubsequentMatchesOf(matches, source, redirects);
733    } else {
734      // Advance to next item.
735      source++;
736    }
737  }
738
739  if (matches->size() > max_results)
740    matches->resize(max_results);
741}
742
743size_t HistoryURLProvider::RemoveSubsequentMatchesOf(
744    HistoryMatches* matches,
745    size_t source_index,
746    const std::vector<GURL>& remove) const {
747  size_t next_index = source_index + 1;  // return value = item after source
748
749  // Find the first occurrence of any URL in the redirect chain. We want to
750  // keep this one since it is rated the highest.
751  HistoryMatches::iterator first(std::find_first_of(
752      matches->begin(), matches->end(), remove.begin(), remove.end()));
753  DCHECK(first != matches->end()) <<
754      "We should have always found at least the original URL.";
755
756  // Find any following occurrences of any URL in the redirect chain, these
757  // should be deleted.
758  HistoryMatches::iterator next(first);
759  next++;  // Start searching immediately after the one we found already.
760  while (next != matches->end() &&
761         (next = std::find_first_of(next, matches->end(), remove.begin(),
762                                    remove.end())) != matches->end()) {
763    // Remove this item. When we remove an item before the source index, we
764    // need to shift it to the right and remember that so we can return it.
765    next = matches->erase(next);
766    if (static_cast<size_t>(next - matches->begin()) < next_index)
767      next_index--;
768  }
769  return next_index;
770}
771
772AutocompleteMatch HistoryURLProvider::HistoryMatchToACMatch(
773    HistoryURLProviderParams* params,
774    const HistoryMatch& history_match,
775    MatchType match_type,
776    size_t match_number) {
777  const history::URLRow& info = history_match.url_info;
778  AutocompleteMatch match(this,
779      CalculateRelevance(params->input.type(), match_type, match_number),
780      !!info.visit_count(), AutocompleteMatch::HISTORY_URL);
781  match.destination_url = info.url();
782  DCHECK(match.destination_url.is_valid());
783  size_t inline_autocomplete_offset =
784      history_match.input_location + params->input.text().length();
785  std::string languages = (match_type == WHAT_YOU_TYPED) ?
786      std::string() : params->languages;
787  const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll &
788      ~((params->trim_http && !history_match.match_in_scheme) ?
789          0 : net::kFormatUrlOmitHTTP);
790  match.fill_into_edit =
791      AutocompleteInput::FormattedStringWithEquivalentMeaning(info.url(),
792          net::FormatUrl(info.url(), languages, format_types,
793                         UnescapeRule::SPACES, NULL, NULL,
794                         &inline_autocomplete_offset));
795  if (!params->input.prevent_inline_autocomplete())
796    match.inline_autocomplete_offset = inline_autocomplete_offset;
797  DCHECK((match.inline_autocomplete_offset == string16::npos) ||
798         (match.inline_autocomplete_offset <= match.fill_into_edit.length()));
799
800  size_t match_start = history_match.input_location;
801  match.contents = net::FormatUrl(info.url(), languages,
802      format_types, UnescapeRule::SPACES, NULL, NULL, &match_start);
803  if ((match_start != string16::npos) &&
804      (inline_autocomplete_offset != string16::npos) &&
805      (inline_autocomplete_offset != match_start)) {
806    DCHECK(inline_autocomplete_offset > match_start);
807    AutocompleteMatch::ClassifyLocationInString(match_start,
808        inline_autocomplete_offset - match_start, match.contents.length(),
809        ACMatchClassification::URL, &match.contents_class);
810  } else {
811    AutocompleteMatch::ClassifyLocationInString(string16::npos, 0,
812        match.contents.length(), ACMatchClassification::URL,
813        &match.contents_class);
814  }
815  match.description = info.title();
816  AutocompleteMatch::ClassifyMatchInString(params->input.text(),
817                                           info.title(),
818                                           ACMatchClassification::NONE,
819                                           &match.description_class);
820
821  return match;
822}
823