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