This source file includes following definitions.
- CreateOrPromoteMatch
- ConvertToHostOnly
- CompareHistoryMatch
- SortAndDedupMatches
- RecordAdditionalInfoFromUrlRow
- CalculateRelevanceUsingScoreBuckets
- ntp_is_themed_param_
- GoogleBaseURLValue
- GetApplicationLocale
- GetRlzParameterValue
- GetSearchClient
- NTPIsThemedParam
- type
- url_row
- type_
- search_terms_data
- search_url_database_
- Start
- Stop
- SuggestExactInput
- ExecuteWithDB
- DoAutocomplete
- QueryComplete
- CalculateRelevance
- RunAutocompletePasses
- FixupExactSuggestion
- CanFindIntranetURL
- PromoteMatchForInlineAutocomplete
- PromoteOrCreateShorterSuggestion
- CullPoorMatches
- CullRedirects
- RemoveSubsequentMatchesOf
- HistoryMatchToACMatch
- CalculateRelevanceScoreUsingScoringParams
- ClassifyDescription
#include "chrome/browser/autocomplete/history_url_provider.h"
#include <algorithm>
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
#include "chrome/browser/autocomplete/autocomplete_result.h"
#include "chrome/browser/history/history_backend.h"
#include "chrome/browser/history/history_database.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/history/history_types.h"
#include "chrome/browser/history/in_memory_url_index_types.h"
#include "chrome/browser/history/scored_history_match.h"
#include "chrome/browser/omnibox/omnibox_field_trial.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/url_fixer_upper.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "net/base/net_util.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "url/gurl.h"
#include "url/url_parse.h"
#include "url/url_util.h"
namespace {
bool CreateOrPromoteMatch(const history::URLRow& info,
size_t input_location,
bool match_in_scheme,
history::HistoryMatches* matches,
bool create_if_necessary,
bool promote) {
for (history::HistoryMatches::iterator i(matches->begin());
i != matches->end(); ++i) {
if (i->url_info.url() == info.url()) {
if (promote)
std::rotate(matches->begin(), i, i + 1);
return true;
}
}
if (!create_if_necessary)
return false;
history::HistoryMatch match(info, input_location, match_in_scheme, true);
if (promote)
matches->push_front(match);
else
matches->push_back(match);
return true;
}
GURL ConvertToHostOnly(const history::HistoryMatch& match,
const base::string16& input) {
const GURL& url = match.url_info.url();
if (!url.is_valid() || !url.IsStandard() || url.SchemeIsFile())
return GURL();
GURL host = url.GetWithEmptyPath();
if ((host.spec().length() < (match.input_location + input.length())))
return GURL();
const base::string16 spec = base::UTF8ToUTF16(host.spec());
if (spec.compare(match.input_location, input.length(), input))
return GURL();
return host;
}
bool CompareHistoryMatch(const history::HistoryMatch& a,
const history::HistoryMatch& b) {
if (a.promoted != b.promoted)
return a.promoted;
if (!a.url_info.typed_count() != !b.url_info.typed_count())
return a.url_info.typed_count() > b.url_info.typed_count();
if (a.innermost_match != b.innermost_match)
return a.innermost_match;
if (a.url_info.typed_count() != b.url_info.typed_count())
return a.url_info.typed_count() > b.url_info.typed_count();
if ((a.url_info.typed_count() == 1) && (a.IsHostOnly() != b.IsHostOnly()))
return a.IsHostOnly();
if (a.url_info.visit_count() != b.url_info.visit_count())
return a.url_info.visit_count() > b.url_info.visit_count();
return a.url_info.last_visit() > b.url_info.last_visit();
}
void SortAndDedupMatches(history::HistoryMatches* matches) {
std::sort(matches->begin(), matches->end(), &CompareHistoryMatch);
for (size_t i = 0; i < matches->size(); ++i) {
for (history::HistoryMatches::iterator j(matches->begin() + i + 1);
j != matches->end(); ) {
if ((*matches)[i].url_info.url() == j->url_info.url())
j = matches->erase(j);
else
++j;
}
}
}
void RecordAdditionalInfoFromUrlRow(const history::URLRow& info,
AutocompleteMatch* match) {
match->RecordAdditionalInfo("typed count", info.typed_count());
match->RecordAdditionalInfo("visit count", info.visit_count());
match->RecordAdditionalInfo("last visit", info.last_visit());
}
double CalculateRelevanceUsingScoreBuckets(
const HUPScoringParams::ScoreBuckets& score_buckets,
const base::TimeDelta& time_since_last_visit,
int undecayed_relevance,
int count) {
if ((score_buckets.relevance_cap() != -1) &&
(undecayed_relevance >= score_buckets.relevance_cap()))
return undecayed_relevance;
double decayed_count = count;
if (decayed_count > 0)
decayed_count *= score_buckets.HalfLifeTimeDecay(time_since_last_visit);
const HUPScoringParams::ScoreBuckets::CountMaxRelevance* score_bucket = NULL;
for (size_t i = 0; i < score_buckets.buckets().size(); ++i) {
score_bucket = &score_buckets.buckets()[i];
if (decayed_count >= score_bucket->first)
break;
}
return (score_bucket && (undecayed_relevance > score_bucket->second)) ?
score_bucket->second : undecayed_relevance;
}
}
class SearchTermsDataSnapshot : public SearchTermsData {
public:
explicit SearchTermsDataSnapshot(const SearchTermsData& search_terms_data);
virtual ~SearchTermsDataSnapshot();
virtual std::string GoogleBaseURLValue() const OVERRIDE;
virtual std::string GetApplicationLocale() const OVERRIDE;
virtual base::string16 GetRlzParameterValue() const OVERRIDE;
virtual std::string GetSearchClient() const OVERRIDE;
virtual std::string NTPIsThemedParam() const OVERRIDE;
private:
std::string google_base_url_value_;
std::string application_locale_;
base::string16 rlz_parameter_value_;
std::string search_client_;
std::string ntp_is_themed_param_;
DISALLOW_COPY_AND_ASSIGN(SearchTermsDataSnapshot);
};
SearchTermsDataSnapshot::SearchTermsDataSnapshot(
const SearchTermsData& search_terms_data)
: google_base_url_value_(search_terms_data.GoogleBaseURLValue()),
application_locale_(search_terms_data.GetApplicationLocale()),
rlz_parameter_value_(search_terms_data.GetRlzParameterValue()),
search_client_(search_terms_data.GetSearchClient()),
ntp_is_themed_param_(search_terms_data.NTPIsThemedParam()) {}
SearchTermsDataSnapshot::~SearchTermsDataSnapshot() {
}
std::string SearchTermsDataSnapshot::GoogleBaseURLValue() const {
return google_base_url_value_;
}
std::string SearchTermsDataSnapshot::GetApplicationLocale() const {
return application_locale_;
}
base::string16 SearchTermsDataSnapshot::GetRlzParameterValue() const {
return rlz_parameter_value_;
}
std::string SearchTermsDataSnapshot::GetSearchClient() const {
return search_client_;
}
std::string SearchTermsDataSnapshot::NTPIsThemedParam() const {
return ntp_is_themed_param_;
}
const int HistoryURLProvider::kScoreForBestInlineableResult = 1413;
const int HistoryURLProvider::kScoreForUnvisitedIntranetResult = 1403;
const int HistoryURLProvider::kScoreForWhatYouTypedResult = 1203;
const int HistoryURLProvider::kBaseScoreForNonInlineableResult = 900;
class HistoryURLProvider::VisitClassifier {
public:
enum Type {
INVALID,
UNVISITED_INTRANET,
VISITED,
};
VisitClassifier(HistoryURLProvider* provider,
const AutocompleteInput& input,
history::URLDatabase* db);
Type type() const { return type_; }
const history::URLRow& url_row() const { return url_row_; }
private:
HistoryURLProvider* provider_;
history::URLDatabase* db_;
Type type_;
history::URLRow url_row_;
DISALLOW_COPY_AND_ASSIGN(VisitClassifier);
};
HistoryURLProvider::VisitClassifier::VisitClassifier(
HistoryURLProvider* provider,
const AutocompleteInput& input,
history::URLDatabase* db)
: provider_(provider),
db_(db),
type_(INVALID) {
const GURL& url = input.canonicalized_url();
if (!url.is_valid() ||
((input.type() == AutocompleteInput::UNKNOWN) &&
input.parts().username.is_nonempty() &&
!input.parts().password.is_nonempty() &&
!input.parts().path.is_nonempty()))
return;
if (db_->GetRowForURL(url, &url_row_)) {
type_ = VISITED;
return;
}
if (provider_->CanFindIntranetURL(db_, input)) {
url_row_ = history::URLRow(url);
type_ = UNVISITED_INTRANET;
}
}
HistoryURLProviderParams::HistoryURLProviderParams(
const AutocompleteInput& input,
bool trim_http,
const std::string& languages,
TemplateURL* default_search_provider,
const SearchTermsData& search_terms_data)
: message_loop(base::MessageLoop::current()),
input(input),
prevent_inline_autocomplete(input.prevent_inline_autocomplete()),
trim_http(trim_http),
failed(false),
languages(languages),
dont_suggest_exact_input(false),
default_search_provider(default_search_provider ?
new TemplateURL(default_search_provider->profile(),
default_search_provider->data()) : NULL),
search_terms_data(new SearchTermsDataSnapshot(search_terms_data)) {
}
HistoryURLProviderParams::~HistoryURLProviderParams() {
}
HistoryURLProvider::HistoryURLProvider(AutocompleteProviderListener* listener,
Profile* profile)
: HistoryProvider(listener, profile,
AutocompleteProvider::TYPE_HISTORY_URL),
params_(NULL),
cull_redirects_(
!OmniboxFieldTrial::InHUPCullRedirectsFieldTrial() ||
!OmniboxFieldTrial::InHUPCullRedirectsFieldTrialExperimentGroup()),
create_shorter_match_(
!OmniboxFieldTrial::InHUPCreateShorterMatchFieldTrial() ||
!OmniboxFieldTrial::
InHUPCreateShorterMatchFieldTrialExperimentGroup()),
search_url_database_(true) {
OmniboxFieldTrial::GetExperimentalHUPScoringParams(&scoring_params_);
}
void HistoryURLProvider::Start(const AutocompleteInput& input,
bool minimal_changes) {
Stop(false);
RunAutocompletePasses(input, true);
}
void HistoryURLProvider::Stop(bool clear_cached_results) {
done_ = true;
if (params_)
params_->cancel_flag.Set();
}
AutocompleteMatch HistoryURLProvider::SuggestExactInput(
const base::string16& text,
const GURL& destination_url,
bool trim_http) {
AutocompleteMatch match(this, 0, false,
AutocompleteMatchType::URL_WHAT_YOU_TYPED);
if (destination_url.is_valid()) {
match.destination_url = destination_url;
DCHECK(!trim_http || !AutocompleteInput::HasHTTPScheme(text));
base::string16 display_string(
StringForURLDisplay(destination_url, false, false));
const size_t offset = trim_http ? TrimHttpPrefix(&display_string) : 0;
match.fill_into_edit =
AutocompleteInput::FormattedStringWithEquivalentMeaning(destination_url,
display_string);
match.allowed_to_be_default_match = true;
match.contents = display_string;
const URLPrefix* best_prefix = URLPrefix::BestURLPrefix(
base::UTF8ToUTF16(destination_url.spec()), text);
if (best_prefix == NULL) {
AutocompleteMatch::ClassifyMatchInString(text, match.contents,
ACMatchClassification::URL,
&match.contents_class);
} else {
AutocompleteMatch::ClassifyLocationInString(
best_prefix->prefix.length() - offset, text.length(),
match.contents.length(), ACMatchClassification::URL,
&match.contents_class);
}
match.is_history_what_you_typed_match = true;
}
return match;
}
void HistoryURLProvider::ExecuteWithDB(history::HistoryBackend* backend,
history::URLDatabase* db,
HistoryURLProviderParams* params) {
if (!db) {
params->failed = true;
} else if (!params->cancel_flag.IsSet()) {
base::TimeTicks beginning_time = base::TimeTicks::Now();
DoAutocomplete(backend, db, params);
UMA_HISTOGRAM_TIMES("Autocomplete.HistoryAsyncQueryTime",
base::TimeTicks::Now() - beginning_time);
}
params->message_loop->PostTask(FROM_HERE, base::Bind(
&HistoryURLProvider::QueryComplete, this, params));
}
void HistoryURLProvider::DoAutocomplete(history::HistoryBackend* backend,
history::URLDatabase* db,
HistoryURLProviderParams* params) {
VisitClassifier classifier(this, params->input, db);
bool have_what_you_typed_match =
params->input.canonicalized_url().is_valid() &&
(params->input.type() != AutocompleteInput::QUERY) &&
((params->input.type() != AutocompleteInput::UNKNOWN) ||
(classifier.type() == VisitClassifier::UNVISITED_INTRANET) ||
!params->trim_http ||
(AutocompleteInput::NumNonHostComponents(params->input.parts()) > 0));
AutocompleteMatch what_you_typed_match(SuggestExactInput(
params->input.text(), params->input.canonicalized_url(),
params->trim_http));
what_you_typed_match.relevance = CalculateRelevance(WHAT_YOU_TYPED, 0);
history::URLRows url_matches;
history::HistoryMatches history_matches;
if (search_url_database_) {
const URLPrefixes& prefixes = URLPrefix::GetURLPrefixes();
for (URLPrefixes::const_iterator i(prefixes.begin()); i != prefixes.end();
++i) {
if (params->cancel_flag.IsSet())
return;
db->AutocompleteForPrefix(
base::UTF16ToUTF8(i->prefix + params->input.text()),
kMaxMatches * 2,
(backend == NULL),
&url_matches);
for (history::URLRows::const_iterator j(url_matches.begin());
j != url_matches.end(); ++j) {
const URLPrefix* best_prefix =
URLPrefix::BestURLPrefix(base::UTF8ToUTF16(j->url().spec()),
base::string16());
DCHECK(best_prefix != NULL);
history_matches.push_back(history::HistoryMatch(*j, i->prefix.length(),
i->num_components == 0,
i->num_components >= best_prefix->num_components));
}
}
}
CullPoorMatches(*params, &history_matches);
SortAndDedupMatches(&history_matches);
PromoteOrCreateShorterSuggestion(db, *params, have_what_you_typed_match,
what_you_typed_match, &history_matches);
size_t first_match = 1;
size_t exact_suggestion = 0;
if (what_you_typed_match.is_history_what_you_typed_match &&
(!backend || !params->dont_suggest_exact_input) &&
FixupExactSuggestion(db, params->input, classifier, &what_you_typed_match,
&history_matches)) {
exact_suggestion = 1;
params->matches.push_back(what_you_typed_match);
} else if (params->prevent_inline_autocomplete ||
history_matches.empty() ||
!PromoteMatchForInlineAutocomplete(history_matches.front(), params)) {
first_match = 0;
if (have_what_you_typed_match)
params->matches.push_back(what_you_typed_match);
}
if (!backend)
return;
DCHECK(search_url_database_);
int relevance = -1;
for (ACMatches::const_iterator it = params->matches.begin();
it != params->matches.end(); ++it) {
relevance = std::max(relevance, it->relevance);
}
if (cull_redirects_) {
CullRedirects(backend, &history_matches, kMaxMatches + exact_suggestion);
} else {
if (history_matches.size() > kMaxMatches + exact_suggestion)
history_matches.resize(kMaxMatches + exact_suggestion);
}
for (size_t i = first_match; i < history_matches.size(); ++i) {
const history::HistoryMatch& match = history_matches[i];
DCHECK(!have_what_you_typed_match ||
(match.url_info.url() !=
GURL(params->matches.front().destination_url)));
relevance = (relevance > 0) ? (relevance - 1) :
CalculateRelevance(NORMAL, history_matches.size() - 1 - i);
AutocompleteMatch ac_match = HistoryMatchToACMatch(*params, match,
NORMAL, relevance);
if (!params->matches.empty()) {
relevance = CalculateRelevanceScoreUsingScoringParams(match, relevance);
ac_match.relevance = relevance;
}
params->matches.push_back(ac_match);
}
}
void HistoryURLProvider::QueryComplete(
HistoryURLProviderParams* params_gets_deleted) {
scoped_ptr<HistoryURLProviderParams> params(params_gets_deleted);
if (params_ == params_gets_deleted)
params_ = NULL;
if (params->cancel_flag.IsSet())
return;
if (!params->failed) {
matches_.swap(params->matches);
UpdateStarredStateOfMatches();
}
done_ = true;
listener_->OnProviderUpdate(true);
}
HistoryURLProvider::~HistoryURLProvider() {
}
int HistoryURLProvider::CalculateRelevance(MatchType match_type,
size_t match_number) const {
switch (match_type) {
case INLINE_AUTOCOMPLETE:
return kScoreForBestInlineableResult;
case UNVISITED_INTRANET:
return kScoreForUnvisitedIntranetResult;
case WHAT_YOU_TYPED:
return kScoreForWhatYouTypedResult;
default:
return kBaseScoreForNonInlineableResult +
static_cast<int>(match_number);
}
}
void HistoryURLProvider::RunAutocompletePasses(
const AutocompleteInput& input,
bool fixup_input_and_run_pass_1) {
matches_.clear();
if ((input.type() == AutocompleteInput::INVALID) ||
(input.type() == AutocompleteInput::FORCED_QUERY))
return;
const bool trim_http = !AutocompleteInput::HasHTTPScheme(input.text());
if ((input.type() != AutocompleteInput::QUERY) &&
input.canonicalized_url().is_valid()) {
AutocompleteMatch what_you_typed(SuggestExactInput(
input.text(), input.canonicalized_url(), trim_http));
what_you_typed.relevance = CalculateRelevance(WHAT_YOU_TYPED, 0);
matches_.push_back(what_you_typed);
}
if (!profile_)
return;
HistoryService* const history_service =
HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
if (!history_service)
return;
TemplateURLService* template_url_service =
TemplateURLServiceFactory::GetForProfile(profile_);
TemplateURL* default_search_provider = template_url_service ?
template_url_service->GetDefaultSearchProvider() : NULL;
UIThreadSearchTermsData data(profile_);
scoped_ptr<HistoryURLProviderParams> params(
new HistoryURLProviderParams(
input, trim_http,
profile_->GetPrefs()->GetString(prefs::kAcceptLanguages),
default_search_provider, data));
params->prevent_inline_autocomplete =
PreventInlineAutocomplete(input);
if (fixup_input_and_run_pass_1) {
if (!FixupUserInput(¶ms->input))
return;
history::URLDatabase* url_db = history_service->InMemoryDatabase();
if (url_db) {
DoAutocomplete(NULL, url_db, params.get());
matches_.clear();
matches_.swap(params->matches);
UpdateStarredStateOfMatches();
}
}
if (search_url_database_ &&
(input.matches_requested() == AutocompleteInput::ALL_MATCHES)) {
done_ = false;
params_ = params.release();
history_service->ScheduleAutocomplete(this, params_);
}
}
bool HistoryURLProvider::FixupExactSuggestion(
history::URLDatabase* db,
const AutocompleteInput& input,
const VisitClassifier& classifier,
AutocompleteMatch* match,
history::HistoryMatches* matches) const {
DCHECK(match != NULL);
DCHECK(matches != NULL);
MatchType type = INLINE_AUTOCOMPLETE;
switch (classifier.type()) {
case VisitClassifier::INVALID:
return false;
case VisitClassifier::UNVISITED_INTRANET:
type = UNVISITED_INTRANET;
break;
default:
DCHECK_EQ(VisitClassifier::VISITED, classifier.type());
match->deletable = true;
match->description = classifier.url_row().title();
RecordAdditionalInfoFromUrlRow(classifier.url_row(), match);
match->description_class =
ClassifyDescription(input.text(), match->description);
if (!classifier.url_row().typed_count()) {
type = CanFindIntranetURL(db, input) ?
UNVISITED_INTRANET : WHAT_YOU_TYPED;
}
break;
}
const GURL& url = match->destination_url;
const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
if ((type == UNVISITED_INTRANET) &&
(input.type() != AutocompleteInput::URL) &&
url.username().empty() && url.password().empty() && url.port().empty() &&
(url.path() == "/") && url.query().empty() &&
(parsed.CountCharactersBefore(url_parse::Parsed::REF, true) !=
parsed.CountCharactersBefore(url_parse::Parsed::REF, false))) {
return false;
}
match->relevance = CalculateRelevance(type, 0);
if (type == UNVISITED_INTRANET && !matches->empty())
return false;
CreateOrPromoteMatch(classifier.url_row(), base::string16::npos, false,
matches, true, true);
return true;
}
bool HistoryURLProvider::CanFindIntranetURL(
history::URLDatabase* db,
const AutocompleteInput& input) const {
if ((input.type() != AutocompleteInput::UNKNOWN) ||
!LowerCaseEqualsASCII(input.scheme(), content::kHttpScheme) ||
!input.parts().host.is_nonempty())
return false;
const std::string host(base::UTF16ToUTF8(
input.text().substr(input.parts().host.begin, input.parts().host.len)));
const size_t registry_length =
net::registry_controlled_domains::GetRegistryLength(
host,
net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
return registry_length == 0 && db->IsTypedHost(host);
}
bool HistoryURLProvider::PromoteMatchForInlineAutocomplete(
const history::HistoryMatch& match,
HistoryURLProviderParams* params) {
if (!match.promoted &&
(!match.url_info.typed_count() ||
((match.url_info.typed_count() == 1) &&
!match.IsHostOnly())))
return false;
if (params) {
params->dont_suggest_exact_input = true;
AutocompleteMatch ac_match = HistoryMatchToACMatch(
*params, match, INLINE_AUTOCOMPLETE,
CalculateRelevance(INLINE_AUTOCOMPLETE, 0));
params->matches.push_back(ac_match);
}
return true;
}
void HistoryURLProvider::PromoteOrCreateShorterSuggestion(
history::URLDatabase* db,
const HistoryURLProviderParams& params,
bool have_what_you_typed_match,
const AutocompleteMatch& what_you_typed_match,
history::HistoryMatches* matches) {
if (matches->empty())
return;
const history::HistoryMatch& match = matches->front();
GURL search_base = ConvertToHostOnly(match, params.input.text());
bool can_add_search_base_to_matches = !have_what_you_typed_match;
if (search_base.is_empty()) {
std::string new_match = match.url_info.url().possibly_invalid_spec().
substr(0, match.input_location + params.input.text().length());
search_base = GURL(new_match);
if (search_base.is_empty())
return;
} else if (!can_add_search_base_to_matches) {
can_add_search_base_to_matches =
(search_base != what_you_typed_match.destination_url);
}
if (search_base == match.url_info.url())
return;
history::URLRow info(search_base);
bool promote = true;
const int min_visit_count = ((match.url_info.visit_count() - 1) / 3) + 1;
const int min_typed_count = match.url_info.typed_count() ? 1 : 0;
if (!db->FindShortestURLFromBase(search_base.possibly_invalid_spec(),
match.url_info.url().possibly_invalid_spec(), min_visit_count,
min_typed_count, can_add_search_base_to_matches, &info)) {
if (!can_add_search_base_to_matches)
return;
db->GetRowForURL(search_base, &info);
promote = match.url_info.typed_count() <= 1;
}
bool ensure_can_inline =
promote && PromoteMatchForInlineAutocomplete(match, NULL);
ensure_can_inline &= CreateOrPromoteMatch(info, match.input_location,
match.match_in_scheme, matches, create_shorter_match_, promote);
if (ensure_can_inline)
matches->front().promoted = true;
}
void HistoryURLProvider::CullPoorMatches(
const HistoryURLProviderParams& params,
history::HistoryMatches* matches) const {
const base::Time& threshold(history::AutocompleteAgeThreshold());
for (history::HistoryMatches::iterator i(matches->begin());
i != matches->end(); ) {
if (RowQualifiesAsSignificant(i->url_info, threshold) &&
!(params.default_search_provider &&
params.default_search_provider->IsSearchURLUsingTermsData(
i->url_info.url(), *params.search_terms_data.get()))) {
++i;
} else {
i = matches->erase(i);
}
}
}
void HistoryURLProvider::CullRedirects(history::HistoryBackend* backend,
history::HistoryMatches* matches,
size_t max_results) const {
for (size_t source = 0;
(source < matches->size()) && (source < max_results); ) {
const GURL& url = (*matches)[source].url_info.url();
history::RedirectList redirects;
backend->GetMostRecentRedirectsFrom(url, &redirects);
if (!redirects.empty()) {
redirects.push_back(url);
source = RemoveSubsequentMatchesOf(matches, source, redirects);
} else {
source++;
}
}
if (matches->size() > max_results)
matches->resize(max_results);
}
size_t HistoryURLProvider::RemoveSubsequentMatchesOf(
history::HistoryMatches* matches,
size_t source_index,
const std::vector<GURL>& remove) const {
size_t next_index = source_index + 1;
history::HistoryMatches::iterator first(std::find_first_of(
matches->begin(), matches->end(), remove.begin(), remove.end(),
history::HistoryMatch::EqualsGURL));
DCHECK(first != matches->end()) << "We should have always found at least the "
"original URL.";
for (history::HistoryMatches::iterator next(std::find_first_of(first + 1,
matches->end(), remove.begin(), remove.end(),
history::HistoryMatch::EqualsGURL));
next != matches->end(); next = std::find_first_of(next, matches->end(),
remove.begin(), remove.end(), history::HistoryMatch::EqualsGURL)) {
next = matches->erase(next);
if (static_cast<size_t>(next - matches->begin()) < next_index)
--next_index;
}
return next_index;
}
AutocompleteMatch HistoryURLProvider::HistoryMatchToACMatch(
const HistoryURLProviderParams& params,
const history::HistoryMatch& history_match,
MatchType match_type,
int relevance) {
const history::URLRow& info = history_match.url_info;
AutocompleteMatch match(this, relevance,
!!info.visit_count(), AutocompleteMatchType::HISTORY_URL);
match.typed_count = info.typed_count();
match.destination_url = info.url();
DCHECK(match.destination_url.is_valid());
size_t inline_autocomplete_offset =
history_match.input_location + params.input.text().length();
std::string languages = (match_type == WHAT_YOU_TYPED) ?
std::string() : params.languages;
const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll &
~((params.trim_http && !history_match.match_in_scheme) ?
0 : net::kFormatUrlOmitHTTP);
match.fill_into_edit =
AutocompleteInput::FormattedStringWithEquivalentMeaning(info.url(),
net::FormatUrl(info.url(), languages, format_types,
net::UnescapeRule::SPACES, NULL, NULL,
&inline_autocomplete_offset));
if (!params.prevent_inline_autocomplete &&
(inline_autocomplete_offset != base::string16::npos)) {
DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
match.inline_autocompletion =
match.fill_into_edit.substr(inline_autocomplete_offset);
}
match.allowed_to_be_default_match = !params.prevent_inline_autocomplete ||
((inline_autocomplete_offset != base::string16::npos) &&
(inline_autocomplete_offset >= match.fill_into_edit.length()));
size_t match_start = history_match.input_location;
match.contents = net::FormatUrl(info.url(), languages,
format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
if ((match_start != base::string16::npos) &&
(inline_autocomplete_offset != base::string16::npos) &&
(inline_autocomplete_offset != match_start)) {
DCHECK(inline_autocomplete_offset > match_start);
AutocompleteMatch::ClassifyLocationInString(match_start,
inline_autocomplete_offset - match_start, match.contents.length(),
ACMatchClassification::URL, &match.contents_class);
} else {
AutocompleteMatch::ClassifyLocationInString(base::string16::npos, 0,
match.contents.length(), ACMatchClassification::URL,
&match.contents_class);
}
match.description = info.title();
match.description_class =
ClassifyDescription(params.input.text(), match.description);
RecordAdditionalInfoFromUrlRow(info, &match);
return match;
}
int HistoryURLProvider::CalculateRelevanceScoreUsingScoringParams(
const history::HistoryMatch& match,
int old_relevance) const {
if (!scoring_params_.experimental_scoring_enabled)
return old_relevance;
const base::TimeDelta time_since_last_visit =
base::Time::Now() - match.url_info.last_visit();
int relevance = CalculateRelevanceUsingScoreBuckets(
scoring_params_.typed_count_buckets, time_since_last_visit, old_relevance,
match.url_info.typed_count());
if (match.url_info.typed_count() == 0) {
relevance = CalculateRelevanceUsingScoreBuckets(
scoring_params_.visited_count_buckets, time_since_last_visit, relevance,
match.url_info.visit_count());
}
DCHECK_LE(relevance, old_relevance);
return relevance;
}
ACMatchClassifications HistoryURLProvider::ClassifyDescription(
const base::string16& input_text,
const base::string16& description) {
base::string16 clean_description = history::CleanUpTitleForMatching(
description);
history::TermMatches description_matches(SortAndDeoverlapMatches(
history::MatchTermInString(input_text, clean_description, 0)));
history::WordStarts description_word_starts;
history::String16VectorFromString16(
clean_description, false, &description_word_starts);
history::WordStarts offsets(1, 0u);
description_matches =
history::ScoredHistoryMatch::FilterTermMatchesByWordStarts(
description_matches, offsets, description_word_starts, 0,
std::string::npos);
return SpansFromTermMatch(
description_matches, clean_description.length(), false);
}