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