history_quick_provider.cc revision 731df977c0511bca2206b5f333555b1205ff1f43
1// Copyright (c) 2010 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 "base/basictypes.h"
8#include "base/i18n/word_iterator.h"
9#include "base/string_util.h"
10#include "base/logging.h"
11#include "base/utf_string_conversions.h"
12#include "chrome/browser/history/history.h"
13#include "chrome/browser/prefs/pref_service.h"
14#include "chrome/browser/profile.h"
15#include "chrome/browser/history/in_memory_url_index.h"
16#include "chrome/browser/net/url_fixer_upper.h"
17#include "chrome/browser/plugin_service.h"
18#include "chrome/common/notification_source.h"
19#include "chrome/common/notification_type.h"
20#include "chrome/common/pref_names.h"
21#include "chrome/common/url_constants.h"
22#include "googleurl/src/url_util.h"
23#include "net/base/escape.h"
24#include "net/base/net_util.h"
25
26using history::InMemoryURLIndex;
27using history::ScoredHistoryMatch;
28using history::ScoredHistoryMatches;
29
30HistoryQuickProvider::HistoryQuickProvider(ACProviderListener* listener,
31                                           Profile* profile)
32    : HistoryProvider(listener, profile, "HistoryQuickProvider"),
33      trim_http_(false),
34      languages_(profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)) {}
35
36HistoryQuickProvider::~HistoryQuickProvider() {}
37
38void HistoryQuickProvider::Start(const AutocompleteInput& input,
39                                 bool minimal_changes) {
40  matches_.clear();
41
42  if ((input.type() == AutocompleteInput::INVALID) ||
43      (input.type() == AutocompleteInput::FORCED_QUERY))
44    return;
45
46  autocomplete_input_ = input;
47  trim_http_ = !HasHTTPScheme(input.text());
48
49  // Do some fixup on the user input before matching against it, so we provide
50  // good results for local file paths, input with spaces, etc.
51  // NOTE: This purposefully doesn't take input.desired_tld() into account; if
52  // it did, then holding "ctrl" would change all the results from the
53  // HistoryQuickProvider provider, not just the What You Typed Result.
54  const std::wstring fixed_text(FixupUserInput(input));
55  if (fixed_text.empty()) {
56    // Conceivably fixup could result in an empty string (although I don't
57    // have cases where this happens offhand).  We can't do anything with
58    // empty input, so just bail; otherwise we'd crash later.
59    return;
60  }
61  autocomplete_input_.set_text(fixed_text);
62
63  // TODO(pkasting): We should just block here until this loads.  Any time
64  // someone unloads the history backend, we'll get inconsistent inline
65  // autocomplete behavior here.
66  if (GetIndex()) {
67    DoAutocomplete();
68    UpdateStarredStateOfMatches();
69  }
70}
71
72void HistoryQuickProvider::DoAutocomplete() {
73  // Get the matching URLs from the DB.
74  string16 term_string(WideToUTF16(autocomplete_input_.text()));
75  term_string = UnescapeURLComponent(term_string,
76      UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS);
77  history::InMemoryURLIndex::String16Vector terms(
78      HistoryQuickProvider::WordVectorFromString16(term_string));
79  ScoredHistoryMatches matches = GetIndex()->HistoryItemsForTerms(terms);
80
81  size_t match_num = matches.size() - 1;
82  for (ScoredHistoryMatches::const_iterator match_iter = matches.begin();
83       match_iter != matches.end(); ++match_iter, --match_num) {
84    const ScoredHistoryMatch& history_match(*match_iter);
85    AutocompleteMatch ac_match =
86        QuickMatchToACMatch(history_match, NORMAL, match_num);
87    matches_.push_back(ac_match);
88  }
89}
90
91AutocompleteMatch HistoryQuickProvider::QuickMatchToACMatch(
92    const ScoredHistoryMatch& history_match,
93    MatchType match_type,
94    size_t match_number) {
95  const history::URLRow& info = history_match.url_info;
96  int score = CalculateRelevance(history_match.raw_score,
97                                 autocomplete_input_.type(),
98                                 match_type, match_number);
99  AutocompleteMatch match(this, score, !!info.visit_count(),
100                          AutocompleteMatch::HISTORY_URL);
101  match.destination_url = info.url();
102  DCHECK(match.destination_url.is_valid());
103  size_t inline_autocomplete_offset =
104      history_match.input_location + autocomplete_input_.text().length();
105  const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll &
106      ~((trim_http_ && !history_match.match_in_scheme) ?
107          0 : net::kFormatUrlOmitHTTP);
108  std::string languages =
109      match_type == WHAT_YOU_TYPED ? std::string() : languages_;
110  match.fill_into_edit =
111      AutocompleteInput::FormattedStringWithEquivalentMeaning(info.url(),
112          UTF16ToWide(net::FormatUrl(info.url(), languages, format_types,
113                                     UnescapeRule::SPACES, NULL, NULL,
114                                     &inline_autocomplete_offset)));
115  if (!autocomplete_input_.prevent_inline_autocomplete())
116    match.inline_autocomplete_offset = inline_autocomplete_offset;
117  DCHECK((match.inline_autocomplete_offset == std::wstring::npos) ||
118         (match.inline_autocomplete_offset <= match.fill_into_edit.length()));
119
120  size_t match_start = history_match.input_location;
121  match.contents =
122      UTF16ToWide(net::FormatUrl(info.url(), languages, format_types,
123                                 UnescapeRule::SPACES, NULL, NULL,
124                                 &match_start));
125  if ((match_start != std::wstring::npos) &&
126      (inline_autocomplete_offset != std::wstring::npos) &&
127      (inline_autocomplete_offset != match_start)) {
128    DCHECK(inline_autocomplete_offset > match_start);
129    AutocompleteMatch::ClassifyLocationInString(match_start,
130        inline_autocomplete_offset - match_start, match.contents.length(),
131        ACMatchClassification::URL, &match.contents_class);
132  } else {
133    AutocompleteMatch::ClassifyLocationInString(std::wstring::npos, 0,
134        match.contents.length(), ACMatchClassification::URL,
135        &match.contents_class);
136  }
137  match.description = UTF16ToWide(info.title());
138  AutocompleteMatch::ClassifyMatchInString(autocomplete_input_.text(),
139                                           UTF16ToWide(info.title()),
140                                           ACMatchClassification::NONE,
141                                           &match.description_class);
142
143  return match;
144}
145
146history::InMemoryURLIndex* HistoryQuickProvider::GetIndex() {
147  if (index_for_testing_.get())
148    return index_for_testing_.get();
149
150  HistoryService* const history_service =
151      profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
152  if (!history_service)
153    return NULL;
154
155  return history_service->InMemoryIndex();
156}
157
158void HistoryQuickProvider::SetIndexForTesting(
159    history::InMemoryURLIndex* index) {
160  DCHECK(index);
161  index_for_testing_.reset(index);
162}
163
164// Utility Functions
165
166history::InMemoryURLIndex::String16Vector
167    HistoryQuickProvider::WordVectorFromString16(const string16& uni_string) {
168  history::InMemoryURLIndex::String16Vector words;
169  WordIterator iter(&uni_string, WordIterator::BREAK_WORD);
170  if (iter.Init()) {
171    while (iter.Advance()) {
172      if (iter.IsWord())
173        words.push_back(iter.GetWord());
174    }
175  }
176  return words;
177}
178
179// static
180int HistoryQuickProvider::CalculateRelevance(int raw_score,
181                                             AutocompleteInput::Type input_type,
182                                             MatchType match_type,
183                                             size_t match_number) {
184  switch (match_type) {
185    case INLINE_AUTOCOMPLETE:
186      return 1400;
187
188    case WHAT_YOU_TYPED:
189      return 1200;
190
191    default:
192      return 900 + static_cast<int>(match_number);
193  }
194}
195
196