autocomplete.cc revision 513209b27ff55e2841eac0e4120199c23acce758
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/autocomplete.h"
6
7#include <algorithm>
8
9#include "app/l10n_util.h"
10#include "base/basictypes.h"
11#include "base/command_line.h"
12#include "base/i18n/number_formatting.h"
13#include "base/string_number_conversions.h"
14#include "base/string_util.h"
15#include "base/utf_string_conversions.h"
16#include "chrome/browser/autocomplete/autocomplete_match.h"
17#include "chrome/browser/autocomplete/history_quick_provider.h"
18#include "chrome/browser/autocomplete/history_url_provider.h"
19#include "chrome/browser/autocomplete/history_contents_provider.h"
20#include "chrome/browser/autocomplete/keyword_provider.h"
21#include "chrome/browser/autocomplete/search_provider.h"
22#include "chrome/browser/bookmarks/bookmark_model.h"
23#include "chrome/browser/dom_ui/history_ui.h"
24#include "chrome/browser/external_protocol_handler.h"
25#include "chrome/browser/net/url_fixer_upper.h"
26#include "chrome/browser/prefs/pref_service.h"
27#include "chrome/browser/profile.h"
28#include "chrome/common/chrome_switches.h"
29#include "chrome/common/notification_service.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_canon_ip.h"
34#include "googleurl/src/url_util.h"
35#include "grit/generated_resources.h"
36#include "grit/theme_resources.h"
37#include "net/base/net_util.h"
38#include "net/base/registry_controlled_domain.h"
39#include "net/url_request/url_request.h"
40
41using base::TimeDelta;
42
43// AutocompleteInput ----------------------------------------------------------
44
45AutocompleteInput::AutocompleteInput()
46  : type_(INVALID),
47    prevent_inline_autocomplete_(false),
48    prefer_keyword_(false),
49    synchronous_only_(false) {
50}
51
52AutocompleteInput::AutocompleteInput(const std::wstring& text,
53                                     const std::wstring& desired_tld,
54                                     bool prevent_inline_autocomplete,
55                                     bool prefer_keyword,
56                                     bool synchronous_only)
57    : desired_tld_(desired_tld),
58      prevent_inline_autocomplete_(prevent_inline_autocomplete),
59      prefer_keyword_(prefer_keyword),
60      synchronous_only_(synchronous_only) {
61  // Trim whitespace from edges of input; don't inline autocomplete if there
62  // was trailing whitespace.
63  if (TrimWhitespace(text, TRIM_ALL, &text_) & TRIM_TRAILING)
64    prevent_inline_autocomplete_ = true;
65
66  type_ = Parse(text_, desired_tld, &parts_, &scheme_);
67
68  if (type_ == INVALID)
69    return;
70
71  if ((type_ == UNKNOWN) || (type_ == REQUESTED_URL) || (type_ == URL)) {
72    GURL canonicalized_url(URLFixerUpper::FixupURL(WideToUTF8(text_),
73                                                   WideToUTF8(desired_tld_)));
74    if (canonicalized_url.is_valid() &&
75        (!canonicalized_url.IsStandard() || canonicalized_url.SchemeIsFile() ||
76         !canonicalized_url.host().empty()))
77      canonicalized_url_ = canonicalized_url;
78  }
79
80  if (type_ == FORCED_QUERY && text_[0] == L'?')
81    text_.erase(0, 1);
82}
83
84AutocompleteInput::~AutocompleteInput() {
85}
86
87// static
88std::string AutocompleteInput::TypeToString(Type type) {
89  switch (type) {
90    case INVALID:       return "invalid";
91    case UNKNOWN:       return "unknown";
92    case REQUESTED_URL: return "requested-url";
93    case URL:           return "url";
94    case QUERY:         return "query";
95    case FORCED_QUERY:  return "forced-query";
96
97    default:
98      NOTREACHED();
99      return std::string();
100  }
101}
102
103// static
104AutocompleteInput::Type AutocompleteInput::Parse(
105    const std::wstring& text,
106    const std::wstring& desired_tld,
107    url_parse::Parsed* parts,
108    std::wstring* scheme) {
109  const size_t first_non_white = text.find_first_not_of(kWhitespaceWide, 0);
110  if (first_non_white == std::wstring::npos)
111    return INVALID;  // All whitespace.
112
113  if (text.at(first_non_white) == L'?') {
114    // If the first non-whitespace character is a '?', we magically treat this
115    // as a query.
116    return FORCED_QUERY;
117  }
118
119  // Ask our parsing back-end to help us understand what the user typed.  We
120  // use the URLFixerUpper here because we want to be smart about what we
121  // consider a scheme.  For example, we shouldn't consider www.google.com:80
122  // to have a scheme.
123  url_parse::Parsed local_parts;
124  if (!parts)
125    parts = &local_parts;
126  const std::wstring parsed_scheme(URLFixerUpper::SegmentURL(text, parts));
127  if (scheme)
128    *scheme = parsed_scheme;
129
130  if (parsed_scheme == L"file") {
131    // A user might or might not type a scheme when entering a file URL.  In
132    // either case, |parsed_scheme| will tell us that this is a file URL, but
133    // |parts->scheme| might be empty, e.g. if the user typed "C:\foo".
134    return URL;
135  }
136
137  // If the user typed a scheme, and it's HTTP or HTTPS, we know how to parse it
138  // well enough that we can fall through to the heuristics below.  If it's
139  // something else, we can just determine our action based on what we do with
140  // any input of this scheme.  In theory we could do better with some schemes
141  // (e.g. "ftp" or "view-source") but I'll wait to spend the effort on that
142  // until I run into some cases that really need it.
143  if (parts->scheme.is_nonempty() &&
144      (parsed_scheme != L"http") && (parsed_scheme != L"https")) {
145    // See if we know how to handle the URL internally.
146    if (URLRequest::IsHandledProtocol(WideToASCII(parsed_scheme)))
147      return URL;
148
149    // There are also some schemes that we convert to other things before they
150    // reach the renderer or else the renderer handles internally without
151    // reaching the URLRequest logic.  We thus won't catch these above, but we
152    // should still claim to handle them.
153    if (LowerCaseEqualsASCII(parsed_scheme, chrome::kViewSourceScheme) ||
154        LowerCaseEqualsASCII(parsed_scheme, chrome::kJavaScriptScheme) ||
155        LowerCaseEqualsASCII(parsed_scheme, chrome::kDataScheme))
156      return URL;
157
158    // Finally, check and see if the user has explicitly opened this scheme as
159    // a URL before.  We need to do this last because some schemes may be in
160    // here as "blocked" (e.g. "javascript") because we don't want pages to open
161    // them, but users still can.
162    // TODO(viettrungluu): get rid of conversion.
163    switch (ExternalProtocolHandler::GetBlockState(WideToUTF8(parsed_scheme))) {
164      case ExternalProtocolHandler::DONT_BLOCK:
165        return URL;
166
167      case ExternalProtocolHandler::BLOCK:
168        // If we don't want the user to open the URL, don't let it be navigated
169        // to at all.
170        return QUERY;
171
172      default:
173        // We don't know about this scheme.  It's likely to be a search operator
174        // like "site:" or "link:".  We classify it as UNKNOWN so the user has
175        // the option of treating it as a URL if we're wrong.
176        // Note that SegmentURL() is smart so we aren't tricked by "c:\foo" or
177        // "www.example.com:81" in this case.
178        return UNKNOWN;
179    }
180  }
181
182  // Either the user didn't type a scheme, in which case we need to distinguish
183  // between an HTTP URL and a query, or the scheme is HTTP or HTTPS, in which
184  // case we should reject invalid formulations.
185
186  // If we have an empty host it can't be a URL.
187  if (!parts->host.is_nonempty())
188    return QUERY;
189
190  // Likewise, the RCDS can reject certain obviously-invalid hosts.  (We also
191  // use the registry length later below.)
192  const std::wstring host(text.substr(parts->host.begin, parts->host.len));
193  const size_t registry_length =
194      net::RegistryControlledDomainService::GetRegistryLength(host, false);
195  if (registry_length == std::wstring::npos) {
196    // Try to append the desired_tld.
197    if (!desired_tld.empty()) {
198      std::wstring host_with_tld(host);
199      if (host[host.length() - 1] != '.')
200        host_with_tld += '.';
201      host_with_tld += desired_tld;
202      if (net::RegistryControlledDomainService::GetRegistryLength(
203          host_with_tld, false) != std::wstring::npos)
204        return REQUESTED_URL;  // Something like "99999999999" that looks like a
205                               // bad IP address, but becomes valid on attaching
206                               // a TLD.
207    }
208    return QUERY;  // Could be a broken IP address, etc.
209  }
210
211
212  // See if the hostname is valid.  While IE and GURL allow hostnames to contain
213  // many other characters (perhaps for weird intranet machines), it's extremely
214  // unlikely that a user would be trying to type those in for anything other
215  // than a search query.
216  url_canon::CanonHostInfo host_info;
217  const std::string canonicalized_host(net::CanonicalizeHost(host, &host_info));
218  if ((host_info.family == url_canon::CanonHostInfo::NEUTRAL) &&
219      !net::IsCanonicalizedHostCompliant(canonicalized_host,
220                                         WideToUTF8(desired_tld))) {
221    // Invalid hostname.  There are several possible cases:
222    // * Our checker is too strict and the user pasted in a real-world URL
223    //   that's "invalid" but resolves.  To catch these, we return UNKNOWN when
224    //   the user explicitly typed a scheme, so we'll still search by default
225    //   but we'll show the accidental search infobar if necessary.
226    // * The user is typing a multi-word query.  If we see a space anywhere in
227    //   the hostname we assume this is a search and return QUERY.
228    // * Our checker is too strict and the user is typing a real-world hostname
229    //   that's "invalid" but resolves.  We return UNKNOWN if the TLD is known.
230    //   Note that we explicitly excluded hosts with spaces above so that
231    //   "toys at amazon.com" will be treated as a search.
232    // * The user is typing some garbage string.  Return QUERY.
233    //
234    // Thus we fall down in the following cases:
235    // * Trying to navigate to a hostname with spaces
236    // * Trying to navigate to a hostname with invalid characters and an unknown
237    //   TLD
238    // These are rare, though probably possible in intranets.
239    return (parts->scheme.is_nonempty() ||
240           ((registry_length != 0) && (host.find(' ') == std::wstring::npos))) ?
241        UNKNOWN : QUERY;
242  }
243
244  // A port number is a good indicator that this is a URL.  However, it might
245  // also be a query like "1.66:1" that looks kind of like an IP address and
246  // port number. So here we only check for "port numbers" that are illegal and
247  // thus mean this can't be navigated to (e.g. "1.2.3.4:garbage"), and we save
248  // handling legal port numbers until after the "IP address" determination
249  // below.
250  if (parts->port.is_nonempty()) {
251    int port;
252    if (!base::StringToInt(WideToUTF8(
253            text.substr(parts->port.begin, parts->port.len)), &port) ||
254        (port < 0) || (port > 65535))
255      return QUERY;
256  }
257
258  // Now that we've ruled out all schemes other than http or https and done a
259  // little more sanity checking, the presence of a scheme means this is likely
260  // a URL.
261  if (parts->scheme.is_nonempty())
262    return URL;
263
264  // See if the host is an IP address.
265  if (host_info.family == url_canon::CanonHostInfo::IPV4) {
266    // If the user originally typed a host that looks like an IP address (a
267    // dotted quad), they probably want to open it.  If the original input was
268    // something else (like a single number), they probably wanted to search for
269    // it, unless they explicitly typed a scheme.  This is true even if the URL
270    // appears to have a path: "1.2/45" is more likely a search (for the answer
271    // to a math problem) than a URL.
272    if (host_info.num_ipv4_components == 4)
273      return URL;
274    return desired_tld.empty() ? UNKNOWN : REQUESTED_URL;
275  }
276  if (host_info.family == url_canon::CanonHostInfo::IPV6)
277    return URL;
278
279  // Now that we've ruled out invalid ports and queries that look like they have
280  // a port, the presence of a port means this is likely a URL.
281  if (parts->port.is_nonempty())
282    return URL;
283
284  // Presence of a password means this is likely a URL.  Note that unless the
285  // user has typed an explicit "http://" or similar, we'll probably think that
286  // the username is some unknown scheme, and bail out in the scheme-handling
287  // code above.
288  if (parts->password.is_nonempty())
289    return URL;
290
291  // The host doesn't look like a number, so see if the user's given us a path.
292  if (parts->path.is_nonempty()) {
293    // Most inputs with paths are URLs, even ones without known registries (e.g.
294    // intranet URLs).  However, if there's no known registry and the path has
295    // a space, this is more likely a query with a slash in the first term
296    // (e.g. "ps/2 games") than a URL.  We can still open URLs with spaces in
297    // the path by escaping the space, and we will still inline autocomplete
298    // them if users have typed them in the past, but we default to searching
299    // since that's the common case.
300    return ((registry_length == 0) &&
301            (text.substr(parts->path.begin, parts->path.len).find(' ') !=
302                std::wstring::npos)) ? UNKNOWN : URL;
303  }
304
305  // If we reach here with a username, our input looks like "user@host".
306  // Because there is no scheme explicitly specified, we think this is more
307  // likely an email address than an HTTP auth attempt.  Hence, we search by
308  // default and let users correct us on a case-by-case basis.
309  if (parts->username.is_nonempty())
310    return UNKNOWN;
311
312  // We have a bare host string.  If it has a known TLD, it's probably a URL.
313  if (registry_length != 0)
314    return URL;
315
316  // No TLD that we know about.  This could be:
317  // * A string that the user wishes to add a desired_tld to to get a URL.  If
318  //   we reach this point, we know there's no known TLD on the string, so the
319  //   fixup code will be willing to add one; thus this is a URL.
320  // * A single word "foo"; possibly an intranet site, but more likely a search.
321  //   This is ideally an UNKNOWN, and we can let the Alternate Nav URL code
322  //   catch our mistakes.
323  // * A URL with a valid TLD we don't know about yet.  If e.g. a registrar adds
324  //   "xxx" as a TLD, then until we add it to our data file, Chrome won't know
325  //   "foo.xxx" is a real URL.  So ideally this is a URL, but we can't really
326  //   distinguish this case from:
327  // * A "URL-like" string that's not really a URL (like
328  //   "browser.tabs.closeButtons" or "java.awt.event.*").  This is ideally a
329  //   QUERY.  Since the above case and this one are indistinguishable, and this
330  //   case is likely to be much more common, just say these are both UNKNOWN,
331  //   which should default to the right thing and let users correct us on a
332  //   case-by-case basis.
333  return desired_tld.empty() ? UNKNOWN : REQUESTED_URL;
334}
335
336// static
337void AutocompleteInput::ParseForEmphasizeComponents(
338    const std::wstring& text,
339    const std::wstring& desired_tld,
340    url_parse::Component* scheme,
341    url_parse::Component* host) {
342  url_parse::Parsed parts;
343  std::wstring scheme_str;
344  Parse(text, desired_tld, &parts, &scheme_str);
345
346  *scheme = parts.scheme;
347  *host = parts.host;
348
349  int after_scheme_and_colon = parts.scheme.end() + 1;
350  // For the view-source scheme, we should emphasize the scheme and host of the
351  // URL qualified by the view-source prefix.
352  if (LowerCaseEqualsASCII(scheme_str, chrome::kViewSourceScheme) &&
353      (static_cast<int>(text.length()) > after_scheme_and_colon)) {
354    // Obtain the URL prefixed by view-source and parse it.
355    std::wstring real_url(text.substr(after_scheme_and_colon));
356    url_parse::Parsed real_parts;
357    AutocompleteInput::Parse(real_url, desired_tld, &real_parts, NULL);
358    if (real_parts.scheme.is_nonempty() || real_parts.host.is_nonempty()) {
359      if (real_parts.scheme.is_nonempty()) {
360        *scheme = url_parse::Component(
361            after_scheme_and_colon + real_parts.scheme.begin,
362            real_parts.scheme.len);
363      } else {
364        scheme->reset();
365      }
366      if (real_parts.host.is_nonempty()) {
367        *host = url_parse::Component(
368            after_scheme_and_colon + real_parts.host.begin,
369            real_parts.host.len);
370      } else {
371        host->reset();
372      }
373    }
374  }
375}
376
377// static
378std::wstring AutocompleteInput::FormattedStringWithEquivalentMeaning(
379    const GURL& url,
380    const std::wstring& formatted_url) {
381  if (!net::CanStripTrailingSlash(url))
382    return formatted_url;
383  const std::wstring url_with_path(formatted_url + L"/");
384  return (AutocompleteInput::Parse(formatted_url, std::wstring(), NULL, NULL) ==
385          AutocompleteInput::Parse(url_with_path, std::wstring(), NULL, NULL)) ?
386      formatted_url : url_with_path;
387}
388
389
390bool AutocompleteInput::Equals(const AutocompleteInput& other) const {
391  return (text_ == other.text_) &&
392         (type_ == other.type_) &&
393         (desired_tld_ == other.desired_tld_) &&
394         (scheme_ == other.scheme_) &&
395         (prevent_inline_autocomplete_ == other.prevent_inline_autocomplete_) &&
396         (prefer_keyword_ == other.prefer_keyword_) &&
397         (synchronous_only_ == other.synchronous_only_);
398}
399
400void AutocompleteInput::Clear() {
401  text_.clear();
402  type_ = INVALID;
403  parts_ = url_parse::Parsed();
404  scheme_.clear();
405  desired_tld_.clear();
406  prevent_inline_autocomplete_ = false;
407  prefer_keyword_ = false;
408}
409
410// AutocompleteProvider -------------------------------------------------------
411
412// static
413const size_t AutocompleteProvider::kMaxMatches = 3;
414
415AutocompleteProvider::ACProviderListener::~ACProviderListener() {
416}
417
418AutocompleteProvider::AutocompleteProvider(ACProviderListener* listener,
419                                           Profile* profile,
420                                           const char* name)
421    : profile_(profile),
422      listener_(listener),
423      done_(true),
424      name_(name) {
425}
426
427void AutocompleteProvider::SetProfile(Profile* profile) {
428  DCHECK(profile);
429  DCHECK(done_);  // The controller should have already stopped us.
430  profile_ = profile;
431}
432
433void AutocompleteProvider::Stop() {
434  done_ = true;
435}
436
437void AutocompleteProvider::DeleteMatch(const AutocompleteMatch& match) {
438}
439
440AutocompleteProvider::~AutocompleteProvider() {
441  Stop();
442}
443
444// static
445bool AutocompleteProvider::HasHTTPScheme(const std::wstring& input) {
446  std::string utf8_input(WideToUTF8(input));
447  url_parse::Component scheme;
448  if (url_util::FindAndCompareScheme(utf8_input, chrome::kViewSourceScheme,
449                                     &scheme))
450    utf8_input.erase(0, scheme.end() + 1);
451  return url_util::FindAndCompareScheme(utf8_input, chrome::kHttpScheme, NULL);
452}
453
454void AutocompleteProvider::UpdateStarredStateOfMatches() {
455  if (matches_.empty())
456    return;
457
458  if (!profile_)
459    return;
460  BookmarkModel* bookmark_model = profile_->GetBookmarkModel();
461  if (!bookmark_model || !bookmark_model->IsLoaded())
462    return;
463
464  for (ACMatches::iterator i = matches_.begin(); i != matches_.end(); ++i)
465    i->starred = bookmark_model->IsBookmarked(GURL(i->destination_url));
466}
467
468std::wstring AutocompleteProvider::StringForURLDisplay(const GURL& url,
469                                                       bool check_accept_lang,
470                                                       bool trim_http) const {
471  std::string languages = (check_accept_lang && profile_) ?
472      profile_->GetPrefs()->GetString(prefs::kAcceptLanguages) : std::string();
473  return UTF16ToWideHack(net::FormatUrl(
474      url,
475      languages,
476      net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP),
477      UnescapeRule::SPACES, NULL, NULL, NULL));
478}
479
480// AutocompleteResult ---------------------------------------------------------
481
482// static
483const size_t AutocompleteResult::kMaxMatches = 6;
484
485void AutocompleteResult::Selection::Clear() {
486  destination_url = GURL();
487  provider_affinity = NULL;
488  is_history_what_you_typed_match = false;
489}
490
491AutocompleteResult::AutocompleteResult() {
492  // Reserve space for the max number of matches we'll show. The +1 accounts
493  // for the history shortcut match as it isn't included in max_matches.
494  matches_.reserve(kMaxMatches + 1);
495
496  // It's probably safe to do this in the initializer list, but there's little
497  // penalty to doing it here and it ensures our object is fully constructed
498  // before calling member functions.
499  default_match_ = end();
500}
501
502AutocompleteResult::~AutocompleteResult() {}
503
504void AutocompleteResult::CopyFrom(const AutocompleteResult& rhs) {
505  if (this == &rhs)
506    return;
507
508  matches_ = rhs.matches_;
509  // Careful!  You can't just copy iterators from another container, you have to
510  // reconstruct them.
511  default_match_ = (rhs.default_match_ == rhs.end()) ?
512      end() : (begin() + (rhs.default_match_ - rhs.begin()));
513
514  alternate_nav_url_ = rhs.alternate_nav_url_;
515}
516
517void AutocompleteResult::AppendMatches(const ACMatches& matches) {
518  std::copy(matches.begin(), matches.end(), std::back_inserter(matches_));
519  default_match_ = end();
520  alternate_nav_url_ = GURL();
521}
522
523void AutocompleteResult::AddMatch(const AutocompleteMatch& match) {
524  DCHECK(default_match_ != end());
525  ACMatches::iterator insertion_point =
526      std::upper_bound(begin(), end(), match, &AutocompleteMatch::MoreRelevant);
527  ACMatches::iterator::difference_type default_offset =
528      default_match_ - begin();
529  if ((insertion_point - begin()) <= default_offset)
530    ++default_offset;
531  matches_.insert(insertion_point, match);
532  default_match_ = begin() + default_offset;
533}
534
535void AutocompleteResult::SortAndCull(const AutocompleteInput& input) {
536  // Remove duplicates.
537  std::sort(matches_.begin(), matches_.end(),
538            &AutocompleteMatch::DestinationSortFunc);
539  matches_.erase(std::unique(matches_.begin(), matches_.end(),
540                             &AutocompleteMatch::DestinationsEqual),
541                 matches_.end());
542
543  // Find the top |kMaxMatches| matches.
544  if (matches_.size() > kMaxMatches) {
545    std::partial_sort(matches_.begin(), matches_.begin() + kMaxMatches,
546                      matches_.end(), &AutocompleteMatch::MoreRelevant);
547    matches_.erase(matches_.begin() + kMaxMatches, matches_.end());
548  }
549
550  // HistoryContentsProvider uses a negative relevance as a way to avoid
551  // starving out other provider matches, yet we may end up using this match. To
552  // make sure such matches are sorted correctly we search for all
553  // relevances < 0 and negate them. If we change our relevance algorithm to
554  // properly mix different providers' matches, this can go away.
555  for (ACMatches::iterator i = matches_.begin(); i != matches_.end(); ++i) {
556    if (i->relevance < 0)
557      i->relevance = -i->relevance;
558  }
559
560  // Put the final result set in order.
561  std::sort(matches_.begin(), matches_.end(), &AutocompleteMatch::MoreRelevant);
562  default_match_ = begin();
563
564  // Set the alternate nav URL.
565  alternate_nav_url_ = GURL();
566  if (((input.type() == AutocompleteInput::UNKNOWN) ||
567       (input.type() == AutocompleteInput::REQUESTED_URL)) &&
568      (default_match_ != end()) &&
569      (default_match_->transition != PageTransition::TYPED) &&
570      (default_match_->transition != PageTransition::KEYWORD) &&
571      (input.canonicalized_url() != default_match_->destination_url))
572    alternate_nav_url_ = input.canonicalized_url();
573}
574
575size_t AutocompleteResult::size() const {
576  return matches_.size();
577}
578
579bool AutocompleteResult::empty() const {
580  return matches_.empty();
581}
582
583AutocompleteResult::const_iterator AutocompleteResult::begin() const {
584  return matches_.begin();
585}
586
587AutocompleteResult::iterator AutocompleteResult::begin() {
588  return matches_.begin();
589}
590
591AutocompleteResult::const_iterator AutocompleteResult::end() const {
592  return matches_.end();
593}
594
595AutocompleteResult::iterator AutocompleteResult::end() {
596  return matches_.end();
597}
598
599// Returns the match at the given index.
600const AutocompleteMatch& AutocompleteResult::match_at(size_t index) const {
601  DCHECK(index < matches_.size());
602  return matches_[index];
603}
604
605void AutocompleteResult::Reset() {
606  matches_.clear();
607  default_match_ = end();
608}
609
610#ifndef NDEBUG
611void AutocompleteResult::Validate() const {
612  for (const_iterator i(begin()); i != end(); ++i)
613    i->Validate();
614}
615#endif
616
617// AutocompleteController -----------------------------------------------------
618
619const int AutocompleteController::kNoItemSelected = -1;
620
621namespace {
622// The time we'll wait between sending updates to our observers (balances
623// flicker against lag).
624const int kUpdateDelayMs = 350;
625};
626
627AutocompleteController::AutocompleteController(Profile* profile)
628    : updated_latest_result_(false),
629      delay_interval_has_passed_(false),
630      have_committed_during_this_query_(false),
631      done_(true) {
632  providers_.push_back(new SearchProvider(this, profile));
633  if (!CommandLine::ForCurrentProcess()->HasSwitch(
634      switches::kDisableHistoryQuickProvider))
635    providers_.push_back(new HistoryQuickProvider(this, profile));
636  if (!CommandLine::ForCurrentProcess()->HasSwitch(
637      switches::kDisableHistoryURLProvider))
638    providers_.push_back(new HistoryURLProvider(this, profile));
639  providers_.push_back(new KeywordProvider(this, profile));
640  history_contents_provider_ = new HistoryContentsProvider(this, profile);
641  providers_.push_back(history_contents_provider_);
642  for (ACProviders::iterator i(providers_.begin()); i != providers_.end(); ++i)
643    (*i)->AddRef();
644}
645
646AutocompleteController::~AutocompleteController() {
647  // The providers may have tasks outstanding that hold refs to them.  We need
648  // to ensure they won't call us back if they outlive us.  (Practically,
649  // calling Stop() should also cancel those tasks and make it so that we hold
650  // the only refs.)  We also don't want to bother notifying anyone of our
651  // result changes here, because the notification observer is in the midst of
652  // shutdown too, so we don't ask Stop() to clear |result_| (and notify).
653  result_.Reset();  // Not really necessary.
654  Stop(false);
655
656  for (ACProviders::iterator i(providers_.begin()); i != providers_.end(); ++i)
657    (*i)->Release();
658
659  providers_.clear();  // Not really necessary.
660}
661
662void AutocompleteController::SetProfile(Profile* profile) {
663  Stop(true);
664  for (ACProviders::iterator i(providers_.begin()); i != providers_.end(); ++i)
665    (*i)->SetProfile(profile);
666  input_.Clear();  // Ensure we don't try to do a "minimal_changes" query on a
667                   // different profile.
668}
669
670void AutocompleteController::Start(const std::wstring& text,
671                                   const std::wstring& desired_tld,
672                                   bool prevent_inline_autocomplete,
673                                   bool prefer_keyword,
674                                   bool synchronous_only) {
675  const std::wstring old_input_text(input_.text());
676  const bool old_synchronous_only = input_.synchronous_only();
677  input_ = AutocompleteInput(text, desired_tld, prevent_inline_autocomplete,
678                             prefer_keyword, synchronous_only);
679
680  // See if we can avoid rerunning autocomplete when the query hasn't changed
681  // much.  When the user presses or releases the ctrl key, the desired_tld
682  // changes, and when the user finishes an IME composition, inline autocomplete
683  // may no longer be prevented.  In both these cases the text itself hasn't
684  // changed since the last query, and some providers can do much less work (and
685  // get matches back more quickly).  Taking advantage of this reduces flicker.
686  //
687  // NOTE: This comes after constructing |input_| above since that construction
688  // can change the text string (e.g. by stripping off a leading '?').
689  const bool minimal_changes = (input_.text() == old_input_text) &&
690      (input_.synchronous_only() == old_synchronous_only);
691
692  // If we're interrupting an old query, and committing its result won't shrink
693  // the visible set (which would probably re-expand soon, thus looking very
694  // flickery), then go ahead and commit what we've got, in order to feel more
695  // responsive when the user is typing rapidly.  In this case it's important
696  // that we don't update the edit, as the user has already changed its contents
697  // and anything we might do with it (e.g. inline autocomplete) likely no
698  // longer applies.
699  if (!minimal_changes && !done_ && (latest_result_.size() >= result_.size()))
700    CommitResult(false);
701
702  // If the timer is already running, it could fire shortly after starting this
703  // query, when we're likely to only have the synchronous results back, thus
704  // almost certainly causing flicker.  Reset it, except when we haven't
705  // committed anything for the past query, in which case the user is typing
706  // quickly and we need to keep running the timer lest we lag too far behind.
707  if (have_committed_during_this_query_) {
708    update_delay_timer_.Stop();
709    delay_interval_has_passed_ = false;
710  }
711
712  // Start the new query.
713  have_committed_during_this_query_ = false;
714  for (ACProviders::iterator i(providers_.begin()); i != providers_.end();
715       ++i) {
716    (*i)->Start(input_, minimal_changes);
717    if (synchronous_only)
718      DCHECK((*i)->done());
719  }
720  CheckIfDone();
721  UpdateLatestResult(true);
722}
723
724void AutocompleteController::Stop(bool clear_result) {
725  for (ACProviders::const_iterator i(providers_.begin()); i != providers_.end();
726       ++i) {
727    (*i)->Stop();
728  }
729
730  update_delay_timer_.Stop();
731  updated_latest_result_ = false;
732  delay_interval_has_passed_ = false;
733  done_ = true;
734  if (clear_result && !result_.empty()) {
735    result_.Reset();
736    NotificationService::current()->Notify(
737        NotificationType::AUTOCOMPLETE_CONTROLLER_RESULT_UPDATED,
738        Source<AutocompleteController>(this),
739        Details<const AutocompleteResult>(&result_));
740    // NOTE: We don't notify AUTOCOMPLETE_CONTROLLER_DEFAULT_MATCH_UPDATED since
741    // we're trying to only clear the popup, not touch the edit... this is all
742    // a mess and should be cleaned up :(
743  }
744  latest_result_.CopyFrom(result_);
745}
746
747void AutocompleteController::DeleteMatch(const AutocompleteMatch& match) {
748  DCHECK(match.deletable);
749  match.provider->DeleteMatch(match);  // This may synchronously call back to
750                                       // OnProviderUpdate().
751  CommitResult(true);  // Ensure any new result gets committed immediately.  If
752                       // it was committed already or hasn't been modified, this
753                       // is harmless.
754}
755
756void AutocompleteController::CommitIfQueryHasNeverBeenCommitted() {
757  if (!have_committed_during_this_query_)
758    CommitResult(true);
759}
760
761void AutocompleteController::OnProviderUpdate(bool updated_matches) {
762  CheckIfDone();
763  if (updated_matches || done_)
764    UpdateLatestResult(false);
765}
766
767void AutocompleteController::UpdateLatestResult(bool is_synchronous_pass) {
768  // Add all providers' matches.
769  latest_result_.Reset();
770  for (ACProviders::const_iterator i(providers_.begin()); i != providers_.end();
771       ++i)
772    latest_result_.AppendMatches((*i)->matches());
773  updated_latest_result_ = true;
774
775  // Sort the matches and trim to a small number of "best" matches.
776  latest_result_.SortAndCull(input_);
777
778  if (history_contents_provider_)
779    AddHistoryContentsShortcut();
780
781#ifndef NDEBUG
782  latest_result_.Validate();
783#endif
784
785  if (is_synchronous_pass) {
786    if (!update_delay_timer_.IsRunning()) {
787      update_delay_timer_.Start(
788          TimeDelta::FromMilliseconds(kUpdateDelayMs),
789          this, &AutocompleteController::DelayTimerFired);
790    }
791
792    NotificationService::current()->Notify(
793        NotificationType::AUTOCOMPLETE_CONTROLLER_DEFAULT_MATCH_UPDATED,
794        Source<AutocompleteController>(this),
795        Details<const AutocompleteResult>(&latest_result_));
796  }
797
798  // If nothing is visible, commit immediately so that the first character the
799  // user types produces an instant response.  If the query has finished and we
800  // haven't ever committed a result set, commit immediately to minimize lag.
801  // Otherwise, only commit when it's been at least one delay interval since the
802  // last commit, to minimize flicker.
803  if (result_.empty() || (done_ && !have_committed_during_this_query_) ||
804      delay_interval_has_passed_)
805    CommitResult(true);
806}
807
808void AutocompleteController::DelayTimerFired() {
809  delay_interval_has_passed_ = true;
810  CommitResult(true);
811}
812
813void AutocompleteController::CommitResult(bool notify_default_match) {
814  if (done_) {
815    update_delay_timer_.Stop();
816    delay_interval_has_passed_ = false;
817  }
818
819  // Don't send update notifications when nothing's actually changed.
820  if (!updated_latest_result_)
821    return;
822
823  updated_latest_result_ = false;
824  delay_interval_has_passed_ = false;
825  have_committed_during_this_query_ = true;
826  result_.CopyFrom(latest_result_);
827  NotificationService::current()->Notify(
828      NotificationType::AUTOCOMPLETE_CONTROLLER_RESULT_UPDATED,
829      Source<AutocompleteController>(this),
830      Details<const AutocompleteResult>(&result_));
831  if (notify_default_match) {
832    // This notification must be sent after the other so the popup has time to
833    // update its state before the edit calls into it.
834    // TODO(pkasting): Eliminate this ordering requirement.
835    NotificationService::current()->Notify(
836        NotificationType::AUTOCOMPLETE_CONTROLLER_DEFAULT_MATCH_UPDATED,
837        Source<AutocompleteController>(this),
838        Details<const AutocompleteResult>(&result_));
839  }
840  if (!done_)
841    update_delay_timer_.Reset();
842}
843
844ACMatches AutocompleteController::GetMatchesNotInLatestResult(
845    const AutocompleteProvider* provider) const {
846  DCHECK(provider);
847
848  // Determine the set of destination URLs.
849  std::set<GURL> destination_urls;
850  for (AutocompleteResult::const_iterator i(latest_result_.begin());
851       i != latest_result_.end(); ++i)
852    destination_urls.insert(i->destination_url);
853
854  ACMatches matches;
855  const ACMatches& provider_matches = provider->matches();
856  for (ACMatches::const_iterator i = provider_matches.begin();
857       i != provider_matches.end(); ++i) {
858    if (destination_urls.find(i->destination_url) == destination_urls.end())
859      matches.push_back(*i);
860  }
861
862  return matches;
863}
864
865void AutocompleteController::AddHistoryContentsShortcut() {
866  DCHECK(history_contents_provider_);
867  // Only check the history contents provider if the history contents provider
868  // is done and has matches.
869  if (!history_contents_provider_->done() ||
870      !history_contents_provider_->db_match_count()) {
871    return;
872  }
873
874  if ((history_contents_provider_->db_match_count() <=
875          (latest_result_.size() + 1)) ||
876      (history_contents_provider_->db_match_count() == 1)) {
877    // We only want to add a shortcut if we're not already showing the matches.
878    ACMatches matches(GetMatchesNotInLatestResult(history_contents_provider_));
879    if (matches.empty())
880      return;
881    if (matches.size() == 1) {
882      // Only one match not shown, add it. The relevance may be negative,
883      // which means we need to negate it to get the true relevance.
884      AutocompleteMatch& match = matches.front();
885      if (match.relevance < 0)
886        match.relevance = -match.relevance;
887      latest_result_.AddMatch(match);
888      return;
889    } // else, fall through and add item.
890  }
891
892  AutocompleteMatch match(NULL, 0, false, AutocompleteMatch::OPEN_HISTORY_PAGE);
893  match.fill_into_edit = input_.text();
894
895  // Mark up the text such that the user input text is bold.
896  size_t keyword_offset = std::wstring::npos;  // Offset into match.contents.
897  if (history_contents_provider_->db_match_count() ==
898      history_contents_provider_->kMaxMatchCount) {
899    // History contents searcher has maxed out.
900    match.contents = l10n_util::GetStringF(IDS_OMNIBOX_RECENT_HISTORY_MANY,
901                                           input_.text(),
902                                           &keyword_offset);
903  } else {
904    // We can report exact matches when there aren't too many.
905    std::vector<size_t> content_param_offsets;
906    match.contents = l10n_util::GetStringF(
907        IDS_OMNIBOX_RECENT_HISTORY,
908        UTF16ToWide(base::FormatNumber(history_contents_provider_->
909                                           db_match_count())),
910        input_.text(),
911        &content_param_offsets);
912
913    // content_param_offsets is ordered based on supplied params, we expect
914    // that the second one contains the query (first is the number).
915    if (content_param_offsets.size() == 2) {
916      keyword_offset = content_param_offsets[1];
917    } else {
918      // See comments on an identical NOTREACHED() in search_provider.cc.
919      NOTREACHED();
920    }
921  }
922
923  // NOTE: This comparison succeeds when keyword_offset == std::wstring::npos.
924  if (keyword_offset > 0) {
925    match.contents_class.push_back(
926        ACMatchClassification(0, ACMatchClassification::NONE));
927  }
928  match.contents_class.push_back(
929      ACMatchClassification(keyword_offset, ACMatchClassification::MATCH));
930  if (keyword_offset + input_.text().size() < match.contents.size()) {
931    match.contents_class.push_back(
932        ACMatchClassification(keyword_offset + input_.text().size(),
933                              ACMatchClassification::NONE));
934  }
935  match.destination_url =
936      HistoryUI::GetHistoryURLWithSearchText(WideToUTF16(input_.text()));
937  match.transition = PageTransition::AUTO_BOOKMARK;
938  match.provider = history_contents_provider_;
939  latest_result_.AddMatch(match);
940}
941
942void AutocompleteController::CheckIfDone() {
943  for (ACProviders::const_iterator i(providers_.begin()); i != providers_.end();
944       ++i) {
945    if (!(*i)->done()) {
946      done_ = false;
947      return;
948    }
949  }
950  done_ = true;
951}
952