Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / autocomplete / autocomplete_provider.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/autocomplete/autocomplete_provider.h"
6
7 #include "base/logging.h"
8 #include "base/prefs/pref_service.h"
9 #include "base/strings/utf_string_conversions.h"
10 #include "chrome/browser/autocomplete/autocomplete_match.h"
11 #include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
12 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
13 #include "chrome/browser/profiles/profile.h"
14 #include "chrome/common/net/url_fixer_upper.h"
15 #include "chrome/common/pref_names.h"
16 #include "components/bookmarks/core/browser/bookmark_model.h"
17 #include "content/public/common/url_constants.h"
18 #include "net/base/net_util.h"
19 #include "url/gurl.h"
20
21 // static
22 const size_t AutocompleteProvider::kMaxMatches = 3;
23
24 AutocompleteProvider::AutocompleteProvider(
25     AutocompleteProviderListener* listener,
26     Profile* profile,
27     Type type)
28     : profile_(profile),
29       listener_(listener),
30       done_(true),
31       type_(type) {
32 }
33
34 // static
35 const char* AutocompleteProvider::TypeToString(Type type) {
36   switch (type) {
37     case TYPE_BOOKMARK:
38       return "Bookmark";
39     case TYPE_BUILTIN:
40       return "Builtin";
41     case TYPE_EXTENSION_APP:
42       return "ExtensionApp";
43     case TYPE_HISTORY_QUICK:
44       return "HistoryQuick";
45     case TYPE_HISTORY_URL:
46       return "HistoryURL";
47     case TYPE_KEYWORD:
48       return "Keyword";
49     case TYPE_SEARCH:
50       return "Search";
51     case TYPE_SHORTCUTS:
52       return "Shortcuts";
53     case TYPE_ZERO_SUGGEST:
54       return "ZeroSuggest";
55     default:
56       NOTREACHED() << "Unhandled AutocompleteProvider::Type " << type;
57       return "Unknown";
58   }
59 }
60
61 void AutocompleteProvider::Stop(bool clear_cached_results) {
62   done_ = true;
63 }
64
65 const char* AutocompleteProvider::GetName() const {
66   return TypeToString(type_);
67 }
68
69 metrics::OmniboxEventProto_ProviderType AutocompleteProvider::
70     AsOmniboxEventProviderType() const {
71   switch (type_) {
72     case TYPE_BOOKMARK:
73       return metrics::OmniboxEventProto::BOOKMARK;
74     case TYPE_BUILTIN:
75       return metrics::OmniboxEventProto::BUILTIN;
76     case TYPE_EXTENSION_APP:
77       return metrics::OmniboxEventProto::EXTENSION_APPS;
78     case TYPE_HISTORY_QUICK:
79       return metrics::OmniboxEventProto::HISTORY_QUICK;
80     case TYPE_HISTORY_URL:
81       return metrics::OmniboxEventProto::HISTORY_URL;
82     case TYPE_KEYWORD:
83       return metrics::OmniboxEventProto::KEYWORD;
84     case TYPE_SEARCH:
85       return metrics::OmniboxEventProto::SEARCH;
86     case TYPE_SHORTCUTS:
87       return metrics::OmniboxEventProto::SHORTCUTS;
88     case TYPE_ZERO_SUGGEST:
89       return metrics::OmniboxEventProto::ZERO_SUGGEST;
90     default:
91       NOTREACHED() << "Unhandled AutocompleteProvider::Type " << type_;
92       return metrics::OmniboxEventProto::UNKNOWN_PROVIDER;
93   }
94 }
95
96 void AutocompleteProvider::DeleteMatch(const AutocompleteMatch& match) {
97   DLOG(WARNING) << "The AutocompleteProvider '" << GetName()
98                 << "' has not implemented DeleteMatch.";
99 }
100
101 void AutocompleteProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
102 }
103
104 void AutocompleteProvider::ResetSession() {
105 }
106
107 base::string16 AutocompleteProvider::StringForURLDisplay(const GURL& url,
108                                                    bool check_accept_lang,
109                                                    bool trim_http) const {
110   std::string languages = (check_accept_lang && profile_) ?
111       profile_->GetPrefs()->GetString(prefs::kAcceptLanguages) : std::string();
112   return net::FormatUrl(url, languages,
113       net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP),
114       net::UnescapeRule::SPACES, NULL, NULL, NULL);
115 }
116
117 AutocompleteProvider::~AutocompleteProvider() {
118   Stop(false);
119 }
120
121 void AutocompleteProvider::UpdateStarredStateOfMatches() {
122   if (matches_.empty())
123     return;
124
125   if (!profile_)
126     return;
127
128   BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(profile_);
129   if (!bookmark_model || !bookmark_model->loaded())
130     return;
131
132   for (ACMatches::iterator i(matches_.begin()); i != matches_.end(); ++i)
133     i->starred = bookmark_model->IsBookmarked(i->destination_url);
134 }
135
136 // static
137 bool AutocompleteProvider::FixupUserInput(AutocompleteInput* input) {
138   const base::string16& input_text = input->text();
139   // Fixup and canonicalize user input.
140   const GURL canonical_gurl(URLFixerUpper::FixupURL(
141       base::UTF16ToUTF8(input_text), std::string()));
142   std::string canonical_gurl_str(canonical_gurl.possibly_invalid_spec());
143   if (canonical_gurl_str.empty()) {
144     // This probably won't happen, but there are no guarantees.
145     return false;
146   }
147
148   // If the user types a number, GURL will convert it to a dotted quad.
149   // However, if the parser did not mark this as a URL, then the user probably
150   // didn't intend this interpretation.  Since this can break history matching
151   // for hostname beginning with numbers (e.g. input of "17173" will be matched
152   // against "0.0.67.21" instead of the original "17173", failing to find
153   // "17173.com"), swap the original hostname in for the fixed-up one.
154   if ((input->type() != AutocompleteInput::URL) &&
155       canonical_gurl.HostIsIPAddress()) {
156     std::string original_hostname =
157         base::UTF16ToUTF8(input_text.substr(input->parts().host.begin,
158                                             input->parts().host.len));
159     const url::Parsed& parts =
160         canonical_gurl.parsed_for_possibly_invalid_spec();
161     // parts.host must not be empty when HostIsIPAddress() is true.
162     DCHECK(parts.host.is_nonempty());
163     canonical_gurl_str.replace(parts.host.begin, parts.host.len,
164                                original_hostname);
165   }
166   base::string16 output = base::UTF8ToUTF16(canonical_gurl_str);
167   // Don't prepend a scheme when the user didn't have one.  Since the fixer
168   // upper only prepends the "http" scheme, that's all we need to check for.
169   if (!AutocompleteInput::HasHTTPScheme(input_text))
170     TrimHttpPrefix(&output);
171
172   // Make the number of trailing slashes on the output exactly match the input.
173   // Examples of why not doing this would matter:
174   // * The user types "a" and has this fixed up to "a/".  Now no other sites
175   //   beginning with "a" will match.
176   // * The user types "file:" and has this fixed up to "file://".  Now inline
177   //   autocomplete will append too few slashes, resulting in e.g. "file:/b..."
178   //   instead of "file:///b..."
179   // * The user types "http:/" and has this fixed up to "http:".  Now inline
180   //   autocomplete will append too many slashes, resulting in e.g.
181   //   "http:///c..." instead of "http://c...".
182   // NOTE: We do this after calling TrimHttpPrefix() since that can strip
183   // trailing slashes (if the scheme is the only thing in the input).  It's not
184   // clear that the result of fixup really matters in this case, but there's no
185   // harm in making sure.
186   const size_t last_input_nonslash =
187       input_text.find_last_not_of(base::ASCIIToUTF16("/\\"));
188   const size_t num_input_slashes =
189       (last_input_nonslash == base::string16::npos) ?
190       input_text.length() : (input_text.length() - 1 - last_input_nonslash);
191   const size_t last_output_nonslash =
192       output.find_last_not_of(base::ASCIIToUTF16("/\\"));
193   const size_t num_output_slashes =
194       (last_output_nonslash == base::string16::npos) ?
195       output.length() : (output.length() - 1 - last_output_nonslash);
196   if (num_output_slashes < num_input_slashes)
197     output.append(num_input_slashes - num_output_slashes, '/');
198   else if (num_output_slashes > num_input_slashes)
199     output.erase(output.length() - num_output_slashes + num_input_slashes);
200
201   url::Parsed parts;
202   URLFixerUpper::SegmentURL(output, &parts);
203   input->UpdateText(output, base::string16::npos, parts);
204   return !output.empty();
205 }
206
207 // static
208 size_t AutocompleteProvider::TrimHttpPrefix(base::string16* url) {
209   // Find any "http:".
210   if (!AutocompleteInput::HasHTTPScheme(*url))
211     return 0;
212   size_t scheme_pos =
213       url->find(base::ASCIIToUTF16(url::kHttpScheme) + base::char16(':'));
214   DCHECK_NE(base::string16::npos, scheme_pos);
215
216   // Erase scheme plus up to two slashes.
217   size_t prefix_end = scheme_pos + strlen(url::kHttpScheme) + 1;
218   const size_t after_slashes = std::min(url->length(), prefix_end + 2);
219   while ((prefix_end < after_slashes) && ((*url)[prefix_end] == '/'))
220     ++prefix_end;
221   url->erase(scheme_pos, prefix_end - scheme_pos);
222   return (scheme_pos == 0) ? prefix_end : 0;
223 }
224