Home | History | Annotate | Download | only in autocomplete
      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_quick_provider.h"
      6 
      7 #include <vector>
      8 
      9 #include "base/basictypes.h"
     10 #include "base/command_line.h"
     11 #include "base/i18n/break_iterator.h"
     12 #include "base/logging.h"
     13 #include "base/metrics/field_trial.h"
     14 #include "base/metrics/histogram.h"
     15 #include "base/prefs/pref_service.h"
     16 #include "base/strings/string_number_conversions.h"
     17 #include "base/strings/string_util.h"
     18 #include "base/strings/utf_string_conversions.h"
     19 #include "base/time/time.h"
     20 #include "chrome/browser/autocomplete/autocomplete_result.h"
     21 #include "chrome/browser/autocomplete/history_url_provider.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/in_memory_url_index.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/search.h"
     31 #include "chrome/browser/search_engines/template_url.h"
     32 #include "chrome/browser/search_engines/template_url_service.h"
     33 #include "chrome/browser/search_engines/template_url_service_factory.h"
     34 #include "chrome/common/autocomplete_match_type.h"
     35 #include "chrome/common/chrome_switches.h"
     36 #include "chrome/common/pref_names.h"
     37 #include "chrome/common/url_constants.h"
     38 #include "components/metrics/proto/omnibox_input_type.pb.h"
     39 #include "content/public/browser/notification_source.h"
     40 #include "content/public/browser/notification_types.h"
     41 #include "net/base/escape.h"
     42 #include "net/base/net_util.h"
     43 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
     44 #include "url/url_parse.h"
     45 #include "url/url_util.h"
     46 
     47 using history::InMemoryURLIndex;
     48 using history::ScoredHistoryMatch;
     49 using history::ScoredHistoryMatches;
     50 
     51 bool HistoryQuickProvider::disabled_ = false;
     52 
     53 HistoryQuickProvider::HistoryQuickProvider(
     54     AutocompleteProviderListener* listener,
     55     Profile* profile)
     56     : HistoryProvider(listener, profile,
     57           AutocompleteProvider::TYPE_HISTORY_QUICK),
     58       languages_(profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)) {
     59 }
     60 
     61 void HistoryQuickProvider::Start(const AutocompleteInput& input,
     62                                  bool minimal_changes) {
     63   matches_.clear();
     64   if (disabled_)
     65     return;
     66 
     67   // Don't bother with INVALID and FORCED_QUERY.
     68   if ((input.type() == metrics::OmniboxInputType::INVALID) ||
     69       (input.type() == metrics::OmniboxInputType::FORCED_QUERY))
     70     return;
     71 
     72   autocomplete_input_ = input;
     73 
     74   // TODO(pkasting): We should just block here until this loads.  Any time
     75   // someone unloads the history backend, we'll get inconsistent inline
     76   // autocomplete behavior here.
     77   if (GetIndex()) {
     78     base::TimeTicks start_time = base::TimeTicks::Now();
     79     DoAutocomplete();
     80     if (input.text().length() < 6) {
     81       base::TimeTicks end_time = base::TimeTicks::Now();
     82       std::string name = "HistoryQuickProvider.QueryIndexTime." +
     83           base::IntToString(input.text().length());
     84       base::HistogramBase* counter = base::Histogram::FactoryGet(
     85           name, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag);
     86       counter->Add(static_cast<int>((end_time - start_time).InMilliseconds()));
     87     }
     88     UpdateStarredStateOfMatches();
     89   }
     90 }
     91 
     92 HistoryQuickProvider::~HistoryQuickProvider() {}
     93 
     94 void HistoryQuickProvider::DoAutocomplete() {
     95   // Get the matching URLs from the DB.
     96   ScoredHistoryMatches matches = GetIndex()->HistoryItemsForTerms(
     97       autocomplete_input_.text(),
     98       autocomplete_input_.cursor_position(),
     99       AutocompleteProvider::kMaxMatches);
    100   if (matches.empty())
    101     return;
    102 
    103   // Figure out if HistoryURL provider has a URL-what-you-typed match
    104   // that ought to go first and what its score will be.
    105   bool will_have_url_what_you_typed_match_first = false;
    106   int url_what_you_typed_match_score = -1;  // undefined
    107   // These are necessary (but not sufficient) conditions for the omnibox
    108   // input to be a URL-what-you-typed match.  The username test checks that
    109   // either the username does not exist (a regular URL such as http://site/)
    110   // or, if the username exists (http://user@site/), there must be either
    111   // a password or a port.  Together these exclude pure username@site
    112   // inputs because these are likely to be an e-mail address.  HistoryURL
    113   // provider won't promote the URL-what-you-typed match to first
    114   // for these inputs.
    115   const bool can_have_url_what_you_typed_match_first =
    116       (autocomplete_input_.type() != metrics::OmniboxInputType::QUERY) &&
    117       (!autocomplete_input_.parts().username.is_nonempty() ||
    118        autocomplete_input_.parts().password.is_nonempty() ||
    119        autocomplete_input_.parts().path.is_nonempty());
    120   if (can_have_url_what_you_typed_match_first) {
    121     HistoryService* const history_service =
    122         HistoryServiceFactory::GetForProfile(profile_,
    123                                              Profile::EXPLICIT_ACCESS);
    124     // We expect HistoryService to be available.  In case it's not,
    125     // (e.g., due to Profile corruption) we let HistoryQuick provider
    126     // completions (which may be available because it's a different
    127     // data structure) compete with the URL-what-you-typed match as
    128     // normal.
    129     if (history_service) {
    130       history::URLDatabase* url_db = history_service->InMemoryDatabase();
    131       // url_db can be NULL if it hasn't finished initializing (or
    132       // failed to to initialize).  In this case, we let HistoryQuick
    133       // provider completions compete with the URL-what-you-typed
    134       // match as normal.
    135       if (url_db) {
    136         const std::string host(base::UTF16ToUTF8(
    137             autocomplete_input_.text().substr(
    138                 autocomplete_input_.parts().host.begin,
    139                 autocomplete_input_.parts().host.len)));
    140         // We want to put the URL-what-you-typed match first if either
    141         // * the user visited the URL before (intranet or internet).
    142         // * it's a URL on a host that user visited before and this
    143         //   is the root path of the host.  (If the user types some
    144         //   of a path--more than a simple "/"--we let autocomplete compete
    145         //   normally with the URL-what-you-typed match.)
    146         // TODO(mpearson): Remove this hacky code and simply score URL-what-
    147         // you-typed in some sane way relative to possible completions:
    148         // URL-what-you-typed should get some sort of a boost relative
    149         // to completions, but completions should naturally win if
    150         // they're a lot more popular.  In this process, if the input
    151         // is a bare intranet hostname that has been visited before, we
    152         // may want to enforce that the only completions that can outscore
    153         // the URL-what-you-typed match are on the same host (i.e., aren't
    154         // from a longer internet hostname for which the omnibox input is
    155         // a prefix).
    156         if (url_db->GetRowForURL(
    157             autocomplete_input_.canonicalized_url(), NULL) != 0) {
    158           // We visited this URL before.
    159           will_have_url_what_you_typed_match_first = true;
    160           // HistoryURLProvider gives visited what-you-typed URLs a high score.
    161           url_what_you_typed_match_score =
    162               HistoryURLProvider::kScoreForBestInlineableResult;
    163         } else if (url_db->IsTypedHost(host) &&
    164              (!autocomplete_input_.parts().path.is_nonempty() ||
    165               ((autocomplete_input_.parts().path.len == 1) &&
    166                (autocomplete_input_.text()[
    167                    autocomplete_input_.parts().path.begin] == '/'))) &&
    168              !autocomplete_input_.parts().query.is_nonempty() &&
    169              !autocomplete_input_.parts().ref.is_nonempty()) {
    170           // Not visited, but we've seen the host before.
    171           will_have_url_what_you_typed_match_first = true;
    172           const size_t registry_length =
    173               net::registry_controlled_domains::GetRegistryLength(
    174                   host,
    175                   net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
    176                   net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
    177           if (registry_length == 0) {
    178             // Known intranet hosts get one score.
    179             url_what_you_typed_match_score =
    180                 HistoryURLProvider::kScoreForUnvisitedIntranetResult;
    181           } else {
    182             // Known internet hosts get another.
    183             url_what_you_typed_match_score =
    184                 HistoryURLProvider::kScoreForWhatYouTypedResult;
    185           }
    186         }
    187       }
    188     }
    189   }
    190 
    191   // Loop over every result and add it to matches_.  In the process,
    192   // guarantee that scores are decreasing.  |max_match_score| keeps
    193   // track of the highest score we can assign to any later results we
    194   // see.  Also, reduce |max_match_score| if we think there will be
    195   // a URL-what-you-typed match.  (We want URL-what-you-typed matches for
    196   // visited URLs to beat out any longer URLs, no matter how frequently
    197   // they're visited.)  The strength of this reduction depends on the
    198   // likely score for the URL-what-you-typed result.
    199 
    200   // |template_url_service| or |template_url| can be NULL in unit tests.
    201   TemplateURLService* template_url_service =
    202       TemplateURLServiceFactory::GetForProfile(profile_);
    203   TemplateURL* template_url = template_url_service ?
    204       template_url_service->GetDefaultSearchProvider() : NULL;
    205   int max_match_score = matches.begin()->raw_score();
    206   if (will_have_url_what_you_typed_match_first) {
    207     max_match_score = std::min(max_match_score,
    208         url_what_you_typed_match_score - 1);
    209   }
    210   for (ScoredHistoryMatches::const_iterator match_iter = matches.begin();
    211        match_iter != matches.end(); ++match_iter) {
    212     const ScoredHistoryMatch& history_match(*match_iter);
    213     // Culls results corresponding to queries from the default search engine.
    214     // These are low-quality, difficult-to-understand matches for users, and the
    215     // SearchProvider should surface past queries in a better way anyway.
    216     if (!template_url ||
    217         !template_url->IsSearchURL(history_match.url_info.url(),
    218                                    template_url_service->search_terms_data())) {
    219       // Set max_match_score to the score we'll assign this result:
    220       max_match_score = std::min(max_match_score, history_match.raw_score());
    221       matches_.push_back(QuickMatchToACMatch(history_match, max_match_score));
    222       // Mark this max_match_score as being used:
    223       max_match_score--;
    224     }
    225   }
    226 }
    227 
    228 AutocompleteMatch HistoryQuickProvider::QuickMatchToACMatch(
    229     const ScoredHistoryMatch& history_match,
    230     int score) {
    231   const history::URLRow& info = history_match.url_info;
    232   AutocompleteMatch match(
    233       this, score, !!info.visit_count(),
    234       history_match.url_matches().empty() ?
    235           AutocompleteMatchType::HISTORY_TITLE :
    236           AutocompleteMatchType::HISTORY_URL);
    237   match.typed_count = info.typed_count();
    238   match.destination_url = info.url();
    239   DCHECK(match.destination_url.is_valid());
    240 
    241   // Format the URL autocomplete presentation.
    242   const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll &
    243       ~(!history_match.match_in_scheme ? 0 : net::kFormatUrlOmitHTTP);
    244   match.fill_into_edit =
    245       AutocompleteInput::FormattedStringWithEquivalentMeaning(
    246           info.url(),
    247           net::FormatUrl(info.url(), languages_, format_types,
    248                          net::UnescapeRule::SPACES, NULL, NULL, NULL));
    249   std::vector<size_t> offsets =
    250       OffsetsFromTermMatches(history_match.url_matches());
    251   base::OffsetAdjuster::Adjustments adjustments;
    252   match.contents = net::FormatUrlWithAdjustments(
    253       info.url(), languages_, format_types, net::UnescapeRule::SPACES, NULL,
    254       NULL, &adjustments);
    255   base::OffsetAdjuster::AdjustOffsets(adjustments, &offsets);
    256   history::TermMatches new_matches =
    257       ReplaceOffsetsInTermMatches(history_match.url_matches(), offsets);
    258   match.contents_class =
    259       SpansFromTermMatch(new_matches, match.contents.length(), true);
    260 
    261   // Set |inline_autocompletion| and |allowed_to_be_default_match| if possible.
    262   if (history_match.can_inline()) {
    263     DCHECK(!new_matches.empty());
    264     size_t inline_autocomplete_offset = new_matches[0].offset +
    265         new_matches[0].length;
    266     // |inline_autocomplete_offset| may be beyond the end of the
    267     // |fill_into_edit| if the user has typed an URL with a scheme and the
    268     // last character typed is a slash.  That slash is removed by the
    269     // FormatURLWithOffsets call above.
    270     if (inline_autocomplete_offset < match.fill_into_edit.length()) {
    271       match.inline_autocompletion =
    272           match.fill_into_edit.substr(inline_autocomplete_offset);
    273     }
    274     match.allowed_to_be_default_match = match.inline_autocompletion.empty() ||
    275         !PreventInlineAutocomplete(autocomplete_input_);
    276   }
    277 
    278   // Format the description autocomplete presentation.
    279   match.description = info.title();
    280   match.description_class = SpansFromTermMatch(
    281       history_match.title_matches(), match.description.length(), false);
    282 
    283   match.RecordAdditionalInfo("typed count", info.typed_count());
    284   match.RecordAdditionalInfo("visit count", info.visit_count());
    285   match.RecordAdditionalInfo("last visit", info.last_visit());
    286 
    287   return match;
    288 }
    289 
    290 history::InMemoryURLIndex* HistoryQuickProvider::GetIndex() {
    291   if (index_for_testing_.get())
    292     return index_for_testing_.get();
    293 
    294   HistoryService* const history_service =
    295       HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
    296   if (!history_service)
    297     return NULL;
    298 
    299   return history_service->InMemoryIndex();
    300 }
    301