Check USB device path access when prompting users to select a device.
[chromium-blink-merge.git] / chrome / browser / autocomplete / history_url_provider.cc
blobb11014ee63a67c257122cb258ce4f3cd7efc036d
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.
5 #include "chrome/browser/autocomplete/history_url_provider.h"
7 #include <algorithm>
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/autocomplete/in_memory_url_index_types.h"
20 #include "chrome/browser/autocomplete/scored_history_match.h"
21 #include "chrome/browser/history/history_service_factory.h"
22 #include "chrome/browser/profiles/profile.h"
23 #include "chrome/browser/search_engines/template_url_service_factory.h"
24 #include "chrome/browser/search_engines/ui_thread_search_terms_data.h"
25 #include "chrome/common/chrome_switches.h"
26 #include "chrome/common/pref_names.h"
27 #include "chrome/common/url_constants.h"
28 #include "components/bookmarks/browser/bookmark_utils.h"
29 #include "components/history/core/browser/history_backend.h"
30 #include "components/history/core/browser/history_database.h"
31 #include "components/history/core/browser/history_service.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"
48 namespace {
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();
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;
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();
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();
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();
76 // URLs that have been visited more recently are better.
77 return a.url_info.last_visit() > b.url_info.last_visit();
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);
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:
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)
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;
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;
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);
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.
142 return (score_bucket && (undecayed_relevance > score_bucket->second)) ?
143 score_bucket->second : undecayed_relevance;
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;
158 const base::TimeDelta time_since_last_visit =
159 base::Time::Now() - match.url_info.last_visit();
161 int relevance = CalculateRelevanceUsingScoreBuckets(
162 scoring_params.typed_count_buckets, time_since_last_visit, old_relevance,
163 match.url_info.typed_count());
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());
173 DCHECK_LE(relevance, old_relevance);
174 return relevance;
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());
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|).
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.
196 // It's OK to call this function with both |create_if_necessary| and |promote|
197 // false, in which case we'll do nothing.
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;
217 if (!create_if_necessary)
218 return false;
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);
227 return true;
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());
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();
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.
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.
265 return host;
268 } // namespace
270 // -----------------------------------------------------------------
271 // SearchTermsDataSnapshot
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;
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;
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_;
308 DISALLOW_COPY_AND_ASSIGN(SearchTermsDataSnapshot);
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()) {
332 SearchTermsDataSnapshot::~SearchTermsDataSnapshot() {
335 std::string SearchTermsDataSnapshot::GoogleBaseURLValue() const {
336 return google_base_url_value_;
339 std::string SearchTermsDataSnapshot::GetApplicationLocale() const {
340 return application_locale_;
343 base::string16 SearchTermsDataSnapshot::GetRlzParameterValue(
344 bool from_app_list) const {
345 return rlz_parameter_value_;
348 std::string SearchTermsDataSnapshot::GetSearchClient() const {
349 return search_client_;
352 bool SearchTermsDataSnapshot::EnableAnswersInSuggest() const {
353 return enable_answers_in_suggest_;
356 bool SearchTermsDataSnapshot::IsShowingSearchTermsOnSearchResultsPages() const {
357 return is_showing_search_terms_on_search_results_pages_;
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_;
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_;
372 std::string SearchTermsDataSnapshot::NTPIsThemedParam() const {
373 return ntp_is_themed_param_;
376 std::string SearchTermsDataSnapshot::GoogleImageSearchSource() const {
377 return google_image_search_source_;
380 // -----------------------------------------------------------------
381 // HistoryURLProvider
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;
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.
400 VisitClassifier(HistoryURLProvider* provider,
401 const AutocompleteInput& input,
402 history::URLDatabase* db);
404 // Returns the type of visit for the specified input.
405 Type type() const { return type_; }
407 // Returns the URLRow for the visit.
408 const history::URLRow& url_row() const { return url_row_; }
410 private:
411 HistoryURLProvider* provider_;
412 history::URLDatabase* db_;
413 Type type_;
414 history::URLRow url_row_;
416 DISALLOW_COPY_AND_ASSIGN(VisitClassifier);
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;
437 if (db_->GetRowForURL(url, &url_row_)) {
438 type_ = VISITED;
439 return;
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;
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)) {
471 HistoryURLProviderParams::~HistoryURLProviderParams() {
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_);
483 void HistoryURLProvider::Start(const AutocompleteInput& input,
484 bool minimal_changes,
485 bool called_due_to_focus) {
486 // NOTE: We could try hard to do less work in the |minimal_changes| case
487 // here; some clever caching would let us reuse the raw matches from the
488 // history DB without re-querying. However, we'd still have to go back to
489 // the history thread to mark these up properly, and if pass 2 is currently
490 // running, we'd need to wait for it to return to the main thread before
491 // doing this (we can't just write new data for it to read due to thread
492 // safety issues). At that point it's just as fast, and easier, to simply
493 // re-run the query from scratch and ignore |minimal_changes|.
495 // Cancel any in-progress query.
496 Stop(false, false);
498 matches_.clear();
500 if (called_due_to_focus ||
501 (input.type() == metrics::OmniboxInputType::INVALID) ||
502 (input.type() == metrics::OmniboxInputType::FORCED_QUERY))
503 return;
505 // Do some fixup on the user input before matching against it, so we provide
506 // good results for local file paths, input with spaces, etc.
507 const FixupReturn fixup_return(FixupUserInput(input));
508 if (!fixup_return.first)
509 return;
510 url::Parsed parts;
511 url_fixer::SegmentURL(fixup_return.second, &parts);
512 AutocompleteInput fixed_up_input(input);
513 fixed_up_input.UpdateText(fixup_return.second, base::string16::npos, parts);
515 // Create a match for what the user typed.
516 const bool trim_http = !AutocompleteInput::HasHTTPScheme(input.text());
517 AutocompleteMatch what_you_typed_match(SuggestExactInput(
518 fixed_up_input.text(), fixed_up_input.canonicalized_url(), trim_http));
519 what_you_typed_match.relevance = CalculateRelevance(WHAT_YOU_TYPED, 0);
521 // Add the WYT match as a fallback in case we can't get the history service or
522 // URL DB; otherwise, we'll replace this match lower down. Don't do this for
523 // queries, though -- while we can sometimes mark up a match for them, it's
524 // not what the user wants, and just adds noise.
525 if (fixed_up_input.type() != metrics::OmniboxInputType::QUERY)
526 matches_.push_back(what_you_typed_match);
528 // We'll need the history service to run both passes, so try to obtain it.
529 if (!profile_)
530 return;
531 history::HistoryService* const history_service =
532 HistoryServiceFactory::GetForProfile(profile_,
533 ServiceAccessType::EXPLICIT_ACCESS);
534 if (!history_service)
535 return;
537 // Get the default search provider and search terms data now since we have to
538 // retrieve these on the UI thread, and the second pass runs on the history
539 // thread. |template_url_service| can be NULL when testing.
540 TemplateURLService* template_url_service =
541 TemplateURLServiceFactory::GetForProfile(profile_);
542 TemplateURL* default_search_provider = template_url_service ?
543 template_url_service->GetDefaultSearchProvider() : NULL;
544 UIThreadSearchTermsData data(profile_);
546 // Create the data structure for the autocomplete passes. We'll save this off
547 // onto the |params_| member for later deletion below if we need to run pass
548 // 2.
549 scoped_ptr<HistoryURLProviderParams> params(
550 new HistoryURLProviderParams(
551 fixed_up_input, trim_http, what_you_typed_match,
552 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages),
553 default_search_provider, data));
554 // Note that we use the non-fixed-up input here, since fixup may strip
555 // trailing whitespace.
556 params->prevent_inline_autocomplete = PreventInlineAutocomplete(input);
558 // Pass 1: Get the in-memory URL database, and use it to find and promote
559 // the inline autocomplete match, if any.
560 history::URLDatabase* url_db = history_service->InMemoryDatabase();
561 // url_db can be NULL if it hasn't finished initializing (or failed to
562 // initialize). In this case all we can do is fall back on the second
563 // pass.
565 // TODO(pkasting): We should just block here until this loads. Any time
566 // someone unloads the history backend, we'll get inconsistent inline
567 // autocomplete behavior here.
568 if (url_db) {
569 DoAutocomplete(NULL, url_db, params.get());
570 matches_.clear();
571 PromoteMatchesIfNecessary(*params);
572 // NOTE: We don't reset |params| here since at least the |promote_type|
573 // field on it will be read by the second pass -- see comments in
574 // DoAutocomplete().
577 // Pass 2: Ask the history service to call us back on the history thread,
578 // where we can read the full on-disk DB.
579 if (input.want_asynchronous_matches()) {
580 done_ = false;
581 params_ = params.release(); // This object will be destroyed in
582 // QueryComplete() once we're done with it.
583 history_service->ScheduleAutocomplete(
584 base::Bind(&HistoryURLProvider::ExecuteWithDB, this, params_));
588 void HistoryURLProvider::Stop(bool clear_cached_results,
589 bool due_to_user_inactivity) {
590 done_ = true;
592 if (params_)
593 params_->cancel_flag.Set();
596 AutocompleteMatch HistoryURLProvider::SuggestExactInput(
597 const base::string16& text,
598 const GURL& destination_url,
599 bool trim_http) {
600 // The FormattedStringWithEquivalentMeaning() call below requires callers to
601 // be on the UI thread.
602 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI) ||
603 !content::BrowserThread::IsThreadInitialized(content::BrowserThread::UI));
605 AutocompleteMatch match(this, 0, false,
606 AutocompleteMatchType::URL_WHAT_YOU_TYPED);
608 if (destination_url.is_valid()) {
609 match.destination_url = destination_url;
611 // Trim off "http://" if the user didn't type it.
612 DCHECK(!trim_http || !AutocompleteInput::HasHTTPScheme(text));
613 base::string16 display_string(
614 net::FormatUrl(destination_url, std::string(),
615 net::kFormatUrlOmitAll & ~net::kFormatUrlOmitHTTP,
616 net::UnescapeRule::SPACES, NULL, NULL, NULL));
617 const size_t offset = trim_http ? TrimHttpPrefix(&display_string) : 0;
618 match.fill_into_edit =
619 AutocompleteInput::FormattedStringWithEquivalentMeaning(
620 destination_url,
621 display_string,
622 ChromeAutocompleteSchemeClassifier(profile_));
623 match.allowed_to_be_default_match = true;
624 // NOTE: Don't set match.inline_autocompletion to something non-empty here;
625 // it's surprising and annoying.
627 // Try to highlight "innermost" match location. If we fix up "w" into
628 // "www.w.com", we want to highlight the fifth character, not the first.
629 // This relies on match.destination_url being the non-prefix-trimmed version
630 // of match.contents.
631 match.contents = display_string;
632 const URLPrefix* best_prefix = URLPrefix::BestURLPrefix(
633 base::UTF8ToUTF16(destination_url.spec()), text);
634 // It's possible for match.destination_url to not contain the user's input
635 // at all (so |best_prefix| is NULL), for example if the input is
636 // "view-source:x" and |destination_url| has an inserted "http://" in the
637 // middle.
638 if (best_prefix == NULL) {
639 AutocompleteMatch::ClassifyMatchInString(text, match.contents,
640 ACMatchClassification::URL,
641 &match.contents_class);
642 } else {
643 AutocompleteMatch::ClassifyLocationInString(
644 best_prefix->prefix.length() - offset, text.length(),
645 match.contents.length(), ACMatchClassification::URL,
646 &match.contents_class);
649 match.is_history_what_you_typed_match = true;
652 return match;
655 void HistoryURLProvider::ExecuteWithDB(HistoryURLProviderParams* params,
656 history::HistoryBackend* backend,
657 history::URLDatabase* db) {
658 // We may get called with a NULL database if it couldn't be properly
659 // initialized.
660 if (!db) {
661 params->failed = true;
662 } else if (!params->cancel_flag.IsSet()) {
663 base::TimeTicks beginning_time = base::TimeTicks::Now();
665 DoAutocomplete(backend, db, params);
667 UMA_HISTOGRAM_TIMES("Autocomplete.HistoryAsyncQueryTime",
668 base::TimeTicks::Now() - beginning_time);
671 // Return the results (if any) to the main thread.
672 params->message_loop->PostTask(FROM_HERE, base::Bind(
673 &HistoryURLProvider::QueryComplete, this, params));
676 HistoryURLProvider::~HistoryURLProvider() {
677 // Note: This object can get leaked on shutdown if there are pending
678 // requests on the database (which hold a reference to us). Normally, these
679 // messages get flushed for each thread. We do a round trip from main, to
680 // history, back to main while holding a reference. If the main thread
681 // completes before the history thread, the message to delegate back to the
682 // main thread will not run and the reference will leak. Therefore, don't do
683 // anything on destruction.
686 // static
687 int HistoryURLProvider::CalculateRelevance(MatchType match_type,
688 int match_number) {
689 switch (match_type) {
690 case INLINE_AUTOCOMPLETE:
691 return kScoreForBestInlineableResult;
693 case UNVISITED_INTRANET:
694 return kScoreForUnvisitedIntranetResult;
696 case WHAT_YOU_TYPED:
697 return kScoreForWhatYouTypedResult;
699 default: // NORMAL
700 return kBaseScoreForNonInlineableResult + match_number;
704 // static
705 ACMatchClassifications HistoryURLProvider::ClassifyDescription(
706 const base::string16& input_text,
707 const base::string16& description) {
708 base::string16 clean_description =
709 bookmarks::CleanUpTitleForMatching(description);
710 TermMatches description_matches(SortAndDeoverlapMatches(
711 MatchTermInString(input_text, clean_description, 0)));
712 WordStarts description_word_starts;
713 String16VectorFromString16(clean_description, false,
714 &description_word_starts);
715 // If HistoryURL retrieves any matches (and hence we reach this code), we
716 // are guaranteed that the beginning of input_text must be a word break.
717 WordStarts offsets(1, 0u);
718 description_matches = ScoredHistoryMatch::FilterTermMatchesByWordStarts(
719 description_matches, offsets, description_word_starts, 0,
720 std::string::npos);
721 return SpansFromTermMatch(
722 description_matches, clean_description.length(), false);
725 void HistoryURLProvider::DoAutocomplete(history::HistoryBackend* backend,
726 history::URLDatabase* db,
727 HistoryURLProviderParams* params) {
728 // Get the matching URLs from the DB.
729 params->matches.clear();
730 history::URLRows url_matches;
731 const URLPrefixes& prefixes = URLPrefix::GetURLPrefixes();
732 for (URLPrefixes::const_iterator i(prefixes.begin()); i != prefixes.end();
733 ++i) {
734 if (params->cancel_flag.IsSet())
735 return; // Canceled in the middle of a query, give up.
737 // We only need kMaxMatches results in the end, but before we get there we
738 // need to promote lower-quality matches that are prefixes of higher-quality
739 // matches, and remove lower-quality redirects. So we ask for more results
740 // than we need, of every prefix type, in hopes this will give us far more
741 // than enough to work with. CullRedirects() will then reduce the list to
742 // the best kMaxMatches results.
743 db->AutocompleteForPrefix(
744 base::UTF16ToUTF8(i->prefix + params->input.text()), kMaxMatches * 2,
745 !backend, &url_matches);
746 for (history::URLRows::const_iterator j(url_matches.begin());
747 j != url_matches.end(); ++j) {
748 const URLPrefix* best_prefix = URLPrefix::BestURLPrefix(
749 base::UTF8ToUTF16(j->url().spec()), base::string16());
750 DCHECK(best_prefix);
751 params->matches.push_back(history::HistoryMatch(
752 *j, i->prefix.length(), !i->num_components,
753 i->num_components >= best_prefix->num_components));
757 // Create sorted list of suggestions.
758 CullPoorMatches(params);
759 SortAndDedupMatches(&params->matches);
761 // Try to create a shorter suggestion from the best match.
762 // We consider the what you typed match eligible for display when it's
763 // navigable and there's a reasonable chance the user intended to do
764 // something other than search. We use a variety of heuristics to determine
765 // this, e.g. whether the user explicitly typed a scheme, or if omnibox
766 // searching has been disabled by policy. In the cases where we've parsed as
767 // UNKNOWN, we'll still show an accidental search infobar if need be.
768 VisitClassifier classifier(this, params->input, db);
769 params->have_what_you_typed_match =
770 (params->input.type() != metrics::OmniboxInputType::QUERY) &&
771 ((params->input.type() != metrics::OmniboxInputType::UNKNOWN) ||
772 (classifier.type() == VisitClassifier::UNVISITED_INTRANET) ||
773 !params->trim_http ||
774 (AutocompleteInput::NumNonHostComponents(params->input.parts()) > 0) ||
775 !params->default_search_provider);
776 const bool have_shorter_suggestion_suitable_for_inline_autocomplete =
777 PromoteOrCreateShorterSuggestion(db, params);
779 // Check whether what the user typed appears in history.
780 const bool can_check_history_for_exact_match =
781 // Checking what_you_typed_match.is_history_what_you_typed_match tells us
782 // whether SuggestExactInput() succeeded in constructing a valid match.
783 params->what_you_typed_match.is_history_what_you_typed_match &&
784 // Additionally, in the case where the user has typed "foo.com" and
785 // visited (but not typed) "foo/", and the input is "foo", the first pass
786 // will fall into the FRONT_HISTORY_MATCH case for "foo.com" but the
787 // second pass can suggest the exact input as a better URL. Since we need
788 // both passes to agree, and since during the first pass there's no way to
789 // know about "foo/", ensure that if the promote type was set to
790 // FRONT_HISTORY_MATCH during the first pass, the second pass will not
791 // consider the exact suggestion to be in history and therefore will not
792 // suggest the exact input as a better match. (Note that during the first
793 // pass, this conditional will always succeed since |promote_type| is
794 // initialized to NEITHER.)
795 (params->promote_type != HistoryURLProviderParams::FRONT_HISTORY_MATCH);
796 params->exact_suggestion_is_in_history = can_check_history_for_exact_match &&
797 FixupExactSuggestion(db, classifier, params);
799 // If we succeeded in fixing up the exact match based on the user's history,
800 // we should treat it as the best match regardless of input type. If not,
801 // then we check whether there's an inline autocompletion we can create from
802 // this input, so we can promote that as the best match.
803 if (params->exact_suggestion_is_in_history) {
804 params->promote_type = HistoryURLProviderParams::WHAT_YOU_TYPED_MATCH;
805 } else if (!params->matches.empty() &&
806 (have_shorter_suggestion_suitable_for_inline_autocomplete ||
807 CanPromoteMatchForInlineAutocomplete(params->matches[0]))) {
808 // Note that we promote this inline-autocompleted match even when
809 // params->prevent_inline_autocomplete is true. This is safe because in
810 // this case the match will be marked as "not allowed to be default", and
811 // a non-inlined match that is "allowed to be default" will be reordered
812 // above it by the controller/AutocompleteResult. We ensure there is such
813 // a match in two ways:
814 // * If params->have_what_you_typed_match is true, we force the
815 // what-you-typed match to be added in this case. See comments in
816 // PromoteMatchesIfNecessary().
817 // * Otherwise, we should have some sort of QUERY or UNKNOWN input that
818 // the SearchProvider will provide a defaultable WYT match for.
819 params->promote_type = HistoryURLProviderParams::FRONT_HISTORY_MATCH;
820 } else {
821 // Failed to promote any URLs. Use the What You Typed match, if we have it.
822 params->promote_type = params->have_what_you_typed_match ?
823 HistoryURLProviderParams::WHAT_YOU_TYPED_MATCH :
824 HistoryURLProviderParams::NEITHER;
827 const size_t max_results =
828 kMaxMatches + (params->exact_suggestion_is_in_history ? 1 : 0);
829 if (backend) {
830 // Remove redirects and trim list to size. We want to provide up to
831 // kMaxMatches results plus the What You Typed result, if it was added to
832 // params->matches above.
833 CullRedirects(backend, &params->matches, max_results);
834 } else if (params->matches.size() > max_results) {
835 // Simply trim the list to size.
836 params->matches.resize(max_results);
840 void HistoryURLProvider::PromoteMatchesIfNecessary(
841 const HistoryURLProviderParams& params) {
842 if (params.promote_type == HistoryURLProviderParams::NEITHER)
843 return;
844 if (params.promote_type == HistoryURLProviderParams::FRONT_HISTORY_MATCH) {
845 matches_.push_back(
846 HistoryMatchToACMatch(params, 0, INLINE_AUTOCOMPLETE,
847 CalculateRelevance(INLINE_AUTOCOMPLETE, 0)));
849 // There are two cases where we need to add the what-you-typed-match:
850 // * If params.promote_type is WHAT_YOU_TYPED_MATCH, we're being explicitly
851 // directed to.
852 // * If params.have_what_you_typed_match is true, then params.promote_type
853 // can't be NEITHER (see code near the end of DoAutocomplete()), so if
854 // it's not WHAT_YOU_TYPED_MATCH, it must be FRONT_HISTORY_MATCH, and
855 // we'll have promoted the history match above. If
856 // params.prevent_inline_autocomplete is also true, then this match
857 // will be marked "not allowed to be default", and we need to add the
858 // what-you-typed match to ensure there's a legal default match for the
859 // controller/AutocompleteResult to promote. (If
860 // params.have_what_you_typed_match is false, the SearchProvider should
861 // take care of adding this defaultable match.)
862 if ((params.promote_type == HistoryURLProviderParams::WHAT_YOU_TYPED_MATCH) ||
863 (params.prevent_inline_autocomplete &&
864 params.have_what_you_typed_match)) {
865 matches_.push_back(params.what_you_typed_match);
869 void HistoryURLProvider::QueryComplete(
870 HistoryURLProviderParams* params_gets_deleted) {
871 // Ensure |params_gets_deleted| gets deleted on exit.
872 scoped_ptr<HistoryURLProviderParams> params(params_gets_deleted);
874 // If the user hasn't already started another query, clear our member pointer
875 // so we can't write into deleted memory.
876 if (params_ == params_gets_deleted)
877 params_ = NULL;
879 // Don't send responses for queries that have been canceled.
880 if (params->cancel_flag.IsSet())
881 return; // Already set done_ when we canceled, no need to set it again.
883 // Don't modify |matches_| if the query failed, since it might have a default
884 // match in it, whereas |params->matches| will be empty.
885 if (!params->failed) {
886 matches_.clear();
887 PromoteMatchesIfNecessary(*params);
889 // Determine relevance of highest scoring match, if any.
890 int relevance = matches_.empty() ?
891 CalculateRelevance(NORMAL,
892 static_cast<int>(params->matches.size() - 1)) :
893 matches_[0].relevance;
895 // Convert the history matches to autocomplete matches. If we promoted the
896 // first match, skip over it.
897 const size_t first_match =
898 (params->exact_suggestion_is_in_history ||
899 (params->promote_type ==
900 HistoryURLProviderParams::FRONT_HISTORY_MATCH)) ? 1 : 0;
901 for (size_t i = first_match; i < params->matches.size(); ++i) {
902 // All matches score one less than the previous match.
903 --relevance;
904 // The experimental scoring must not change the top result's score.
905 if (!matches_.empty()) {
906 relevance = CalculateRelevanceScoreUsingScoringParams(
907 params->matches[i], relevance, scoring_params_);
909 matches_.push_back(HistoryMatchToACMatch(*params, i, NORMAL, relevance));
913 done_ = true;
914 listener_->OnProviderUpdate(true);
917 bool HistoryURLProvider::FixupExactSuggestion(
918 history::URLDatabase* db,
919 const VisitClassifier& classifier,
920 HistoryURLProviderParams* params) const {
921 MatchType type = INLINE_AUTOCOMPLETE;
922 switch (classifier.type()) {
923 case VisitClassifier::INVALID:
924 return false;
925 case VisitClassifier::UNVISITED_INTRANET:
926 type = UNVISITED_INTRANET;
927 break;
928 default:
929 DCHECK_EQ(VisitClassifier::VISITED, classifier.type());
930 // We have data for this match, use it.
931 params->what_you_typed_match.deletable = true;
932 params->what_you_typed_match.description = classifier.url_row().title();
933 RecordAdditionalInfoFromUrlRow(classifier.url_row(),
934 &params->what_you_typed_match);
935 params->what_you_typed_match.description_class = ClassifyDescription(
936 params->input.text(), params->what_you_typed_match.description);
937 if (!classifier.url_row().typed_count()) {
938 // If we reach here, we must be in the second pass, and we must not have
939 // this row's data available during the first pass. That means we
940 // either scored it as WHAT_YOU_TYPED or UNVISITED_INTRANET, and to
941 // maintain the ordering between passes consistent, we need to score it
942 // the same way here.
943 type = CanFindIntranetURL(db, params->input) ?
944 UNVISITED_INTRANET : WHAT_YOU_TYPED;
946 break;
949 params->what_you_typed_match.relevance = CalculateRelevance(type, 0);
951 // If there are any other matches, then don't promote this match here, in
952 // hopes the caller will be able to inline autocomplete a better suggestion.
953 // DoAutocomplete() will fall back on this match if inline autocompletion
954 // fails. This matches how we react to never-visited URL inputs in the non-
955 // intranet case.
956 if (type == UNVISITED_INTRANET && !params->matches.empty())
957 return false;
959 // Put it on the front of the HistoryMatches for redirect culling.
960 CreateOrPromoteMatch(classifier.url_row(), base::string16::npos, false,
961 &params->matches, true, true);
962 return true;
965 bool HistoryURLProvider::CanFindIntranetURL(
966 history::URLDatabase* db,
967 const AutocompleteInput& input) const {
968 // Normally passing the first two conditions below ought to guarantee the
969 // third condition, but because FixupUserInput() can run and modify the
970 // input's text and parts between Parse() and here, it seems better to be
971 // paranoid and check.
972 if ((input.type() != metrics::OmniboxInputType::UNKNOWN) ||
973 !LowerCaseEqualsASCII(input.scheme(), url::kHttpScheme) ||
974 !input.parts().host.is_nonempty())
975 return false;
976 const std::string host(base::UTF16ToUTF8(
977 input.text().substr(input.parts().host.begin, input.parts().host.len)));
978 const size_t registry_length =
979 net::registry_controlled_domains::GetRegistryLength(
980 host,
981 net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
982 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
983 return registry_length == 0 && db->IsTypedHost(host);
986 bool HistoryURLProvider::PromoteOrCreateShorterSuggestion(
987 history::URLDatabase* db,
988 HistoryURLProviderParams* params) {
989 if (params->matches.empty())
990 return false; // No matches, nothing to do.
992 // Determine the base URL from which to search, and whether that URL could
993 // itself be added as a match. We can add the base iff it's not "effectively
994 // the same" as any "what you typed" match.
995 const history::HistoryMatch& match = params->matches[0];
996 GURL search_base = ConvertToHostOnly(match, params->input.text());
997 bool can_add_search_base_to_matches = !params->have_what_you_typed_match;
998 if (search_base.is_empty()) {
999 // Search from what the user typed when we couldn't reduce the best match
1000 // to a host. Careful: use a substring of |match| here, rather than the
1001 // first match in |params|, because they might have different prefixes. If
1002 // the user typed "google.com", params->what_you_typed_match will hold
1003 // "http://google.com/", but |match| might begin with
1004 // "http://www.google.com/".
1005 // TODO: this should be cleaned up, and is probably incorrect for IDN.
1006 std::string new_match = match.url_info.url().possibly_invalid_spec().
1007 substr(0, match.input_location + params->input.text().length());
1008 search_base = GURL(new_match);
1009 if (search_base.is_empty())
1010 return false; // Can't construct a URL from which to start a search.
1011 } else if (!can_add_search_base_to_matches) {
1012 can_add_search_base_to_matches =
1013 (search_base != params->what_you_typed_match.destination_url);
1015 if (search_base == match.url_info.url())
1016 return false; // Couldn't shorten |match|, so no URLs to search over.
1018 // Search the DB for short URLs between our base and |match|.
1019 history::URLRow info(search_base);
1020 bool promote = true;
1021 // A short URL is only worth suggesting if it's been visited at least a third
1022 // as often as the longer URL.
1023 const int min_visit_count = ((match.url_info.visit_count() - 1) / 3) + 1;
1024 // For stability between the in-memory and on-disk autocomplete passes, when
1025 // the long URL has been typed before, only suggest shorter URLs that have
1026 // also been typed. Otherwise, the on-disk pass could suggest a shorter URL
1027 // (which hasn't been typed) that the in-memory pass doesn't know about,
1028 // thereby making the top match, and thus the behavior of inline
1029 // autocomplete, unstable.
1030 const int min_typed_count = match.url_info.typed_count() ? 1 : 0;
1031 if (!db->FindShortestURLFromBase(search_base.possibly_invalid_spec(),
1032 match.url_info.url().possibly_invalid_spec(), min_visit_count,
1033 min_typed_count, can_add_search_base_to_matches, &info)) {
1034 if (!can_add_search_base_to_matches)
1035 return false; // Couldn't find anything and can't add the search base.
1037 // Try to get info on the search base itself. Promote it to the top if the
1038 // original best match isn't good enough to autocomplete.
1039 db->GetRowForURL(search_base, &info);
1040 promote = match.url_info.typed_count() <= 1;
1043 // Promote or add the desired URL to the list of matches.
1044 const bool ensure_can_inline =
1045 promote && CanPromoteMatchForInlineAutocomplete(match);
1046 return CreateOrPromoteMatch(info, match.input_location, match.match_in_scheme,
1047 &params->matches, true, promote) &&
1048 ensure_can_inline;
1051 void HistoryURLProvider::CullPoorMatches(
1052 HistoryURLProviderParams* params) const {
1053 const base::Time& threshold(history::AutocompleteAgeThreshold());
1054 for (history::HistoryMatches::iterator i(params->matches.begin());
1055 i != params->matches.end(); ) {
1056 if (RowQualifiesAsSignificant(i->url_info, threshold) &&
1057 (!params->default_search_provider ||
1058 !params->default_search_provider->IsSearchURL(
1059 i->url_info.url(), *params->search_terms_data))) {
1060 ++i;
1061 } else {
1062 i = params->matches.erase(i);
1067 void HistoryURLProvider::CullRedirects(history::HistoryBackend* backend,
1068 history::HistoryMatches* matches,
1069 size_t max_results) const {
1070 for (size_t source = 0;
1071 (source < matches->size()) && (source < max_results); ) {
1072 const GURL& url = (*matches)[source].url_info.url();
1073 // TODO(brettw) this should go away when everything uses GURL.
1074 history::RedirectList redirects;
1075 backend->QueryRedirectsFrom(url, &redirects);
1076 if (!redirects.empty()) {
1077 // Remove all but the first occurrence of any of these redirects in the
1078 // search results. We also must add the URL we queried for, since it may
1079 // not be the first match and we'd want to remove it.
1081 // For example, when A redirects to B and our matches are [A, X, B],
1082 // we'll get B as the redirects from, and we want to remove the second
1083 // item of that pair, removing B. If A redirects to B and our matches are
1084 // [B, X, A], we'll want to remove A instead.
1085 redirects.push_back(url);
1086 source = RemoveSubsequentMatchesOf(matches, source, redirects);
1087 } else {
1088 // Advance to next item.
1089 source++;
1093 if (matches->size() > max_results)
1094 matches->resize(max_results);
1097 size_t HistoryURLProvider::RemoveSubsequentMatchesOf(
1098 history::HistoryMatches* matches,
1099 size_t source_index,
1100 const std::vector<GURL>& remove) const {
1101 size_t next_index = source_index + 1; // return value = item after source
1103 // Find the first occurrence of any URL in the redirect chain. We want to
1104 // keep this one since it is rated the highest.
1105 history::HistoryMatches::iterator first(std::find_first_of(
1106 matches->begin(), matches->end(), remove.begin(), remove.end(),
1107 history::HistoryMatch::EqualsGURL));
1108 DCHECK(first != matches->end()) << "We should have always found at least the "
1109 "original URL.";
1111 // Find any following occurrences of any URL in the redirect chain, these
1112 // should be deleted.
1113 for (history::HistoryMatches::iterator next(std::find_first_of(first + 1,
1114 matches->end(), remove.begin(), remove.end(),
1115 history::HistoryMatch::EqualsGURL));
1116 next != matches->end(); next = std::find_first_of(next, matches->end(),
1117 remove.begin(), remove.end(), history::HistoryMatch::EqualsGURL)) {
1118 // Remove this item. When we remove an item before the source index, we
1119 // need to shift it to the right and remember that so we can return it.
1120 next = matches->erase(next);
1121 if (static_cast<size_t>(next - matches->begin()) < next_index)
1122 --next_index;
1124 return next_index;
1127 AutocompleteMatch HistoryURLProvider::HistoryMatchToACMatch(
1128 const HistoryURLProviderParams& params,
1129 size_t match_number,
1130 MatchType match_type,
1131 int relevance) {
1132 // The FormattedStringWithEquivalentMeaning() call below requires callers to
1133 // be on the UI thread.
1134 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI) ||
1135 !content::BrowserThread::IsThreadInitialized(content::BrowserThread::UI));
1137 const history::HistoryMatch& history_match = params.matches[match_number];
1138 const history::URLRow& info = history_match.url_info;
1139 AutocompleteMatch match(this, relevance,
1140 !!info.visit_count(), AutocompleteMatchType::HISTORY_URL);
1141 match.typed_count = info.typed_count();
1142 match.destination_url = info.url();
1143 DCHECK(match.destination_url.is_valid());
1144 size_t inline_autocomplete_offset =
1145 history_match.input_location + params.input.text().length();
1146 std::string languages = (match_type == WHAT_YOU_TYPED) ?
1147 std::string() : params.languages;
1148 const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll &
1149 ~((params.trim_http && !history_match.match_in_scheme) ?
1150 0 : net::kFormatUrlOmitHTTP);
1151 match.fill_into_edit =
1152 AutocompleteInput::FormattedStringWithEquivalentMeaning(
1153 info.url(),
1154 net::FormatUrl(info.url(), languages, format_types,
1155 net::UnescapeRule::SPACES, NULL, NULL,
1156 &inline_autocomplete_offset),
1157 ChromeAutocompleteSchemeClassifier(profile_));
1158 if (!params.prevent_inline_autocomplete &&
1159 (inline_autocomplete_offset != base::string16::npos)) {
1160 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1161 match.inline_autocompletion =
1162 match.fill_into_edit.substr(inline_autocomplete_offset);
1164 // The latter part of the test effectively asks "is the inline completion
1165 // empty?" (i.e., is this match effectively the what-you-typed match?).
1166 match.allowed_to_be_default_match = !params.prevent_inline_autocomplete ||
1167 ((inline_autocomplete_offset != base::string16::npos) &&
1168 (inline_autocomplete_offset >= match.fill_into_edit.length()));
1170 size_t match_start = history_match.input_location;
1171 match.contents = net::FormatUrl(info.url(), languages,
1172 format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1173 if ((match_start != base::string16::npos) &&
1174 (inline_autocomplete_offset != base::string16::npos) &&
1175 (inline_autocomplete_offset != match_start)) {
1176 DCHECK(inline_autocomplete_offset > match_start);
1177 AutocompleteMatch::ClassifyLocationInString(match_start,
1178 inline_autocomplete_offset - match_start, match.contents.length(),
1179 ACMatchClassification::URL, &match.contents_class);
1180 } else {
1181 AutocompleteMatch::ClassifyLocationInString(base::string16::npos, 0,
1182 match.contents.length(), ACMatchClassification::URL,
1183 &match.contents_class);
1185 match.description = info.title();
1186 match.description_class =
1187 ClassifyDescription(params.input.text(), match.description);
1188 RecordAdditionalInfoFromUrlRow(info, &match);
1189 return match;