This source file includes following definitions.
- LogOmniboxSuggestRequest
- HasMultipleWords
- GetDefaultProviderURL
- GetKeywordProviderURL
- providers_
- GetSuggestMetadata
- ResetSession
- RemoveStaleResults
- UpdateMatchContentsClass
- CalculateRelevanceForKeywordVerbatim
- Start
- SortResults
- GetTemplateURL
- GetInput
- GetResultsToFill
- ShouldAppendExtraParams
- StopSuggest
- ClearAllResults
- GetDefaultResultRelevance
- RecordDeletionResult
- LogFetchComplete
- IsKeywordFetcher
- UpdateMatches
- Run
- DoHistoryQuery
- StartOrStopSuggestQuery
- IsQuerySuitableForSuggest
- RemoveAllStaleResults
- ApplyCalculatedRelevance
- ApplyCalculatedSuggestRelevance
- ApplyCalculatedNavigationRelevance
- CreateSuggestFetcher
- ConvertResultsToAutocompleteMatches
- FindTopMatch
- IsTopMatchNavigationInKeywordMode
- HasKeywordDefaultMatchInKeywordMode
- IsTopMatchScoreTooLow
- IsTopMatchSearchWithURLInput
- HasValidDefaultMatch
- AddNavigationResultsToMatches
- AddHistoryResultsToMap
- ScoreHistoryResults
- AddSuggestResultsToMap
- GetVerbatimRelevance
- CalculateRelevanceForVerbatim
- CalculateRelevanceForVerbatimIgnoringKeywordModeState
- GetKeywordVerbatimRelevance
- CalculateRelevanceForHistory
- NavigationToMatch
- DemoteKeywordNavigationMatchesPastTopQuery
- UpdateDone
#include "chrome/browser/autocomplete/search_provider.h"
#include <algorithm>
#include <cmath>
#include "base/callback.h"
#include "base/i18n/break_iterator.h"
#include "base/i18n/case_conversion.h"
#include "base/json/json_string_value_serializer.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 "chrome/browser/autocomplete/autocomplete_classifier.h"
#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
#include "chrome/browser/autocomplete/autocomplete_result.h"
#include "chrome/browser/autocomplete/keyword_provider.h"
#include "chrome/browser/autocomplete/url_prefix.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/history/in_memory_database.h"
#include "chrome/browser/metrics/variations/variations_http_header_provider.h"
#include "chrome/browser/omnibox/omnibox_field_trial.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search/search.h"
#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/ui/search/instant_controller.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/user_metrics.h"
#include "grit/generated_resources.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/base/net_util.h"
#include "net/http/http_request_headers.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_request_status.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/url_util.h"
namespace {
enum SuggestRequestsHistogramValue {
REQUEST_SENT = 1,
REQUEST_INVALIDATED,
REPLY_RECEIVED,
MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
};
const int kNonURLVerbatimRelevance = 1300;
void LogOmniboxSuggestRequest(
SuggestRequestsHistogramValue request_value) {
UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
}
bool HasMultipleWords(const base::string16& text) {
base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
bool found_word = false;
if (i.Init()) {
while (i.Advance()) {
if (i.IsWord()) {
if (found_word)
return true;
found_word = true;
}
}
}
return false;
}
}
SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
: template_url_service_(template_url_service) {}
const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
return default_provider_.empty() ? NULL :
template_url_service_->GetTemplateURLForKeyword(default_provider_);
}
const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
return keyword_provider_.empty() ? NULL :
template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
}
class SearchProvider::CompareScoredResults {
public:
bool operator()(const Result& a, const Result& b) {
return a.relevance() > b.relevance();
}
};
int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
Profile* profile)
: BaseSearchProvider(listener, profile, AutocompleteProvider::TYPE_SEARCH),
providers_(TemplateURLServiceFactory::GetForProfile(profile)) {
}
std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
return match.GetAdditionalInfo(kSuggestMetadataKey);
}
void SearchProvider::ResetSession() {
field_trial_triggered_in_session_ = false;
}
SearchProvider::~SearchProvider() {
}
void SearchProvider::RemoveStaleResults(const base::string16& input,
int verbatim_relevance,
SuggestResults* suggest_results,
NavigationResults* navigation_results) {
DCHECK_GE(verbatim_relevance, 0);
SuggestResults::iterator sug_it = suggest_results->begin();
NavigationResults::iterator nav_it = navigation_results->begin();
while ((sug_it != suggest_results->end()) ||
(nav_it != navigation_results->end())) {
const int sug_rel =
(sug_it != suggest_results->end()) ? sug_it->relevance() : -1;
const int nav_rel =
(nav_it != navigation_results->end()) ? nav_it->relevance() : -1;
if (std::max(sug_rel, nav_rel) < verbatim_relevance)
break;
if (sug_rel > nav_rel) {
if (sug_it->IsInlineable(input))
break;
sug_it = suggest_results->erase(sug_it);
} else if (sug_rel == nav_rel) {
const bool sug_inlineable = sug_it->IsInlineable(input);
const bool nav_inlineable = nav_it->IsInlineable(input);
if (!sug_inlineable)
sug_it = suggest_results->erase(sug_it);
if (!nav_inlineable)
nav_it = navigation_results->erase(nav_it);
if (sug_inlineable || nav_inlineable)
break;
} else {
if (nav_it->IsInlineable(input))
break;
nav_it = navigation_results->erase(nav_it);
}
}
}
void SearchProvider::UpdateMatchContentsClass(const base::string16& input_text,
Results* results) {
for (SuggestResults::iterator sug_it = results->suggest_results.begin();
sug_it != results->suggest_results.end(); ++sug_it) {
sug_it->ClassifyMatchContents(false, input_text);
}
const std::string languages(
profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
for (NavigationResults::iterator nav_it = results->navigation_results.begin();
nav_it != results->navigation_results.end(); ++nav_it) {
nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
}
}
int SearchProvider::CalculateRelevanceForKeywordVerbatim(
AutocompleteInput::Type type,
bool prefer_keyword) {
if (prefer_keyword)
return 1500;
return (type == AutocompleteInput::QUERY) ? 1450 : 1100;
}
void SearchProvider::Start(const AutocompleteInput& input,
bool minimal_changes) {
TemplateURLService* model = providers_.template_url_service();
DCHECK(model);
model->Load();
matches_.clear();
field_trial_triggered_ = false;
if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
Stop(true);
return;
}
keyword_input_ = input;
const TemplateURL* keyword_provider =
KeywordProvider::GetSubstitutingTemplateURLForInput(model,
&keyword_input_);
if (keyword_provider == NULL)
keyword_input_.Clear();
else if (keyword_input_.text().empty())
keyword_provider = NULL;
const TemplateURL* default_provider = model->GetDefaultSearchProvider();
if (default_provider && !default_provider->SupportsReplacement())
default_provider = NULL;
if (keyword_provider == default_provider)
default_provider = NULL;
if (!default_provider && !keyword_provider) {
Stop(true);
return;
}
base::string16 default_provider_keyword(default_provider ?
default_provider->keyword() : base::string16());
base::string16 keyword_provider_keyword(keyword_provider ?
keyword_provider->keyword() : base::string16());
if (!minimal_changes ||
!providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
if (!done_)
Stop(false);
}
providers_.set(default_provider_keyword, keyword_provider_keyword);
if (input.text().empty()) {
if (default_provider) {
AutocompleteMatch match;
match.provider = this;
match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
match.contents_class.push_back(
ACMatchClassification(0, ACMatchClassification::NONE));
match.keyword = providers_.default_provider();
match.allowed_to_be_default_match = true;
matches_.push_back(match);
}
Stop(true);
return;
}
input_ = input;
DoHistoryQuery(minimal_changes);
StartOrStopSuggestQuery(minimal_changes);
UpdateMatches();
}
void SearchProvider::SortResults(bool is_keyword,
const base::ListValue* relevances,
Results* results) {
const bool abandon_suggested_scores =
!is_keyword && !providers_.keyword_provider().empty();
if ((relevances == NULL) || abandon_suggested_scores) {
ApplyCalculatedSuggestRelevance(&results->suggest_results);
ApplyCalculatedNavigationRelevance(&results->navigation_results);
if (abandon_suggested_scores)
results->verbatim_relevance = -1;
}
const CompareScoredResults comparator = CompareScoredResults();
std::stable_sort(results->suggest_results.begin(),
results->suggest_results.end(),
comparator);
std::stable_sort(results->navigation_results.begin(),
results->navigation_results.end(),
comparator);
}
const TemplateURL* SearchProvider::GetTemplateURL(bool is_keyword) const {
return is_keyword ? providers_.GetKeywordProviderURL()
: providers_.GetDefaultProviderURL();
}
const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
return is_keyword ? keyword_input_ : input_;
}
BaseSearchProvider::Results* SearchProvider::GetResultsToFill(bool is_keyword) {
return is_keyword ? &keyword_results_ : &default_results_;
}
bool SearchProvider::ShouldAppendExtraParams(
const SuggestResult& result) const {
return !result.from_keyword_provider() ||
providers_.default_provider().empty();
}
void SearchProvider::StopSuggest() {
for (int i = 0; i < suggest_results_pending_; ++i)
LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
suggest_results_pending_ = 0;
timer_.Stop();
keyword_fetcher_.reset();
default_fetcher_.reset();
}
void SearchProvider::ClearAllResults() {
keyword_results_.Clear();
default_results_.Clear();
}
int SearchProvider::GetDefaultResultRelevance() const {
return -1;
}
void SearchProvider::RecordDeletionResult(bool success) {
if (success) {
content::RecordAction(
base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
} else {
content::RecordAction(
base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
}
}
void SearchProvider::LogFetchComplete(bool success, bool is_keyword) {
LogOmniboxSuggestRequest(REPLY_RECEIVED);
const TemplateURL* default_url = providers_.GetDefaultProviderURL();
if (!is_keyword && default_url &&
(TemplateURLPrepopulateData::GetEngineType(*default_url) ==
SEARCH_ENGINE_GOOGLE)) {
const base::TimeDelta elapsed_time =
base::TimeTicks::Now() - time_suggest_request_sent_;
if (success) {
UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
elapsed_time);
} else {
UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
elapsed_time);
}
}
}
bool SearchProvider::IsKeywordFetcher(const net::URLFetcher* fetcher) const {
return fetcher == keyword_fetcher_.get();
}
void SearchProvider::UpdateMatches() {
base::TimeTicks update_matches_start_time(base::TimeTicks::Now());
ConvertResultsToAutocompleteMatches();
if (!matches_.empty() &&
(default_results_.HasServerProvidedScores() ||
keyword_results_.HasServerProvidedScores())) {
const bool omnibox_will_reorder_for_legal_default_match =
OmniboxFieldTrial::ReorderForLegalDefaultMatch(
input_.current_page_classification());
if (IsTopMatchNavigationInKeywordMode(
omnibox_will_reorder_for_legal_default_match)) {
DCHECK(!omnibox_will_reorder_for_legal_default_match);
DemoteKeywordNavigationMatchesPastTopQuery();
ConvertResultsToAutocompleteMatches();
DCHECK(!IsTopMatchNavigationInKeywordMode(
omnibox_will_reorder_for_legal_default_match));
}
if (!HasKeywordDefaultMatchInKeywordMode()) {
keyword_results_.verbatim_relevance = -1;
ConvertResultsToAutocompleteMatches();
}
if (IsTopMatchScoreTooLow(omnibox_will_reorder_for_legal_default_match)) {
default_results_.verbatim_relevance = -1;
keyword_results_.verbatim_relevance = -1;
ConvertResultsToAutocompleteMatches();
}
if (IsTopMatchSearchWithURLInput(
omnibox_will_reorder_for_legal_default_match)) {
ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
default_results_.verbatim_relevance = -1;
keyword_results_.verbatim_relevance = -1;
ConvertResultsToAutocompleteMatches();
}
if (!HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match)) {
ApplyCalculatedRelevance();
ConvertResultsToAutocompleteMatches();
}
DCHECK(!IsTopMatchNavigationInKeywordMode(
omnibox_will_reorder_for_legal_default_match));
DCHECK(HasKeywordDefaultMatchInKeywordMode());
DCHECK(!IsTopMatchScoreTooLow(
omnibox_will_reorder_for_legal_default_match));
DCHECK(!IsTopMatchSearchWithURLInput(
omnibox_will_reorder_for_legal_default_match));
DCHECK(HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match));
}
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
if ((keyword_url != NULL) && HasKeywordDefaultMatchInKeywordMode()) {
for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
++it) {
if (it->keyword != keyword_url->keyword())
it->allowed_to_be_default_match = false;
}
}
base::TimeTicks update_starred_start_time(base::TimeTicks::Now());
UpdateStarredStateOfMatches();
UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateStarredTime",
base::TimeTicks::Now() - update_starred_start_time);
UpdateDone();
UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateMatchesTime",
base::TimeTicks::Now() - update_matches_start_time);
}
void SearchProvider::Run() {
suggest_results_pending_ = 0;
time_suggest_request_sent_ = base::TimeTicks::Now();
default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
providers_.GetDefaultProviderURL(), input_));
keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
providers_.GetKeywordProviderURL(), keyword_input_));
if (suggest_results_pending_ == 0) {
UpdateDone();
if (done_)
listener_->OnProviderUpdate(false);
}
}
void SearchProvider::DoHistoryQuery(bool minimal_changes) {
if (minimal_changes)
return;
base::TimeTicks do_history_query_start_time(base::TimeTicks::Now());
keyword_history_results_.clear();
default_history_results_.clear();
if (OmniboxFieldTrial::SearchHistoryDisable(
input_.current_page_classification()))
return;
base::TimeTicks start_time(base::TimeTicks::Now());
HistoryService* const history_service =
HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
base::TimeTicks now(base::TimeTicks::Now());
UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.GetHistoryServiceTime",
now - start_time);
start_time = now;
history::URLDatabase* url_db = history_service ?
history_service->InMemoryDatabase() : NULL;
UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.InMemoryDatabaseTime",
base::TimeTicks::Now() - start_time);
if (!url_db)
return;
int num_matches = kMaxMatches * 5;
const TemplateURL* default_url = providers_.GetDefaultProviderURL();
if (default_url) {
start_time = base::TimeTicks::Now();
url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
num_matches, &default_history_results_);
UMA_HISTOGRAM_TIMES(
"Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
base::TimeTicks::Now() - start_time);
}
const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
if (keyword_url) {
url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
keyword_input_.text(), num_matches, &keyword_history_results_);
}
UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.DoHistoryQueryTime",
base::TimeTicks::Now() - do_history_query_start_time);
}
void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
if (!IsQuerySuitableForSuggest()) {
StopSuggest();
ClearAllResults();
return;
}
if (minimal_changes &&
(!default_results_.suggest_results.empty() ||
!default_results_.navigation_results.empty() ||
!keyword_results_.suggest_results.empty() ||
!keyword_results_.navigation_results.empty() ||
(!done_ &&
input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
return;
StopSuggest();
RemoveAllStaleResults();
UpdateMatchContentsClass(input_.text(), &default_results_);
if (!keyword_input_.text().empty())
UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
return;
base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
base::TimeTicks now(base::TimeTicks::Now());
if (now >= next_suggest_time) {
Run();
return;
}
timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
}
bool SearchProvider::IsQuerySuitableForSuggest() const {
const TemplateURL* default_url = providers_.GetDefaultProviderURL();
const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
if (profile_->IsOffTheRecord() ||
((!default_url || default_url->suggestions_url().empty()) &&
(!keyword_url || keyword_url->suggestions_url().empty())) ||
!profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
return false;
if (input_.type() == AutocompleteInput::FORCED_QUERY)
return true;
if (!LowerCaseEqualsASCII(input_.scheme(), content::kHttpScheme) &&
!LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
!LowerCaseEqualsASCII(input_.scheme(), content::kFtpScheme))
return (input_.type() == AutocompleteInput::QUERY);
const url_parse::Parsed& parts = input_.parts();
if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
parts.query.is_nonempty() ||
(parts.ref.is_nonempty() && (input_.type() == AutocompleteInput::URL)))
return false;
if (LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
parts.path.is_nonempty())
return false;
return true;
}
void SearchProvider::RemoveAllStaleResults() {
const bool omnibox_will_reorder_for_legal_default_match =
OmniboxFieldTrial::ReorderForLegalDefaultMatch(
input_.current_page_classification());
if (!omnibox_will_reorder_for_legal_default_match) {
RemoveStaleResults(input_.text(), GetVerbatimRelevance(NULL),
&default_results_.suggest_results,
&default_results_.navigation_results);
if (!keyword_input_.text().empty()) {
RemoveStaleResults(keyword_input_.text(),
GetKeywordVerbatimRelevance(NULL),
&keyword_results_.suggest_results,
&keyword_results_.navigation_results);
}
}
if (keyword_input_.text().empty()) {
keyword_results_.Clear();
}
}
void SearchProvider::ApplyCalculatedRelevance() {
ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
default_results_.verbatim_relevance = -1;
keyword_results_.verbatim_relevance = -1;
}
void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
for (size_t i = 0; i < list->size(); ++i) {
SuggestResult& result = (*list)[i];
result.set_relevance(
result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
(list->size() - i - 1));
result.set_relevance_from_server(false);
}
}
void SearchProvider::ApplyCalculatedNavigationRelevance(
NavigationResults* list) {
for (size_t i = 0; i < list->size(); ++i) {
NavigationResult& result = (*list)[i];
result.set_relevance(
result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
(list->size() - i - 1));
result.set_relevance_from_server(false);
}
}
net::URLFetcher* SearchProvider::CreateSuggestFetcher(
int id,
const TemplateURL* template_url,
const AutocompleteInput& input) {
if (!template_url || template_url->suggestions_url().empty())
return NULL;
TemplateURLRef::SearchTermsArgs search_term_args(input.text());
search_term_args.cursor_position = input.cursor_position();
search_term_args.page_classification = input.current_page_classification();
GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
search_term_args));
if (!suggest_url.is_valid())
return NULL;
if (CanSendURL(current_page_url_, suggest_url, template_url,
input.current_page_classification(), profile_) &&
OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
search_term_args.current_page_url = current_page_url_.spec();
suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
search_term_args));
}
suggest_results_pending_++;
LogOmniboxSuggestRequest(REQUEST_SENT);
net::URLFetcher* fetcher =
net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
fetcher->SetRequestContext(profile_->GetRequestContext());
fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
net::HttpRequestHeaders headers;
chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
fetcher->SetExtraRequestHeaders(headers.ToString());
fetcher->Start();
return fetcher;
}
void SearchProvider::ConvertResultsToAutocompleteMatches() {
base::TimeTicks start_time(base::TimeTicks::Now());
MatchMap map;
const base::Time no_time;
int did_not_accept_keyword_suggestion =
keyword_results_.suggest_results.empty() ?
TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
TemplateURLRef::NO_SUGGESTION_CHOSEN;
bool relevance_from_server;
int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
int did_not_accept_default_suggestion =
default_results_.suggest_results.empty() ?
TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
TemplateURLRef::NO_SUGGESTION_CHOSEN;
if (verbatim_relevance > 0) {
const base::string16& trimmed_verbatim =
base::CollapseWhitespace(input_.text(), false);
SuggestResult verbatim(
trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
trimmed_verbatim, base::string16(), base::string16(), std::string(),
std::string(), false, verbatim_relevance, relevance_from_server, false,
trimmed_verbatim);
AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
false, &map);
}
if (!keyword_input_.text().empty()) {
const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
if (keyword_url &&
(keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
bool keyword_relevance_from_server;
const int keyword_verbatim_relevance =
GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
if (keyword_verbatim_relevance > 0) {
const base::string16& trimmed_verbatim =
base::CollapseWhitespace(keyword_input_.text(), false);
SuggestResult verbatim(
trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
trimmed_verbatim, base::string16(), base::string16(),
std::string(), std::string(), true, keyword_verbatim_relevance,
keyword_relevance_from_server, false, trimmed_verbatim);
AddMatchToMap(verbatim, std::string(),
did_not_accept_keyword_suggestion, false, &map);
}
}
}
AddHistoryResultsToMap(keyword_history_results_, true,
did_not_accept_keyword_suggestion, &map);
AddHistoryResultsToMap(default_history_results_, false,
did_not_accept_default_suggestion, &map);
AddSuggestResultsToMap(keyword_results_.suggest_results,
keyword_results_.metadata, &map);
AddSuggestResultsToMap(default_results_.suggest_results,
default_results_.metadata, &map);
ACMatches matches;
for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
matches.push_back(i->second);
AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Omnibox.SearchProvider.NumMatchesToSort", matches.size(), 1, 50, 20);
std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
matches_.clear();
size_t num_suggestions = 0;
for (ACMatches::const_iterator i(matches.begin());
(i != matches.end()) &&
(matches_.size() < AutocompleteResult::kMaxMatches);
++i) {
if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
(i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
if ((num_suggestions >= kMaxMatches) &&
(!chrome::IsInstantExtendedAPIEnabled() ||
(i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
continue;
}
++num_suggestions;
}
matches_.push_back(*i);
}
UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
base::TimeTicks::Now() - start_time);
}
ACMatches::const_iterator SearchProvider::FindTopMatch(
bool autocomplete_result_will_reorder_for_default_match) const {
if (!autocomplete_result_will_reorder_for_default_match)
return matches_.begin();
ACMatches::const_iterator it = matches_.begin();
while ((it != matches_.end()) && !it->allowed_to_be_default_match)
++it;
return it;
}
bool SearchProvider::IsTopMatchNavigationInKeywordMode(
bool autocomplete_result_will_reorder_for_default_match) const {
ACMatches::const_iterator first_match =
FindTopMatch(autocomplete_result_will_reorder_for_default_match);
return !providers_.keyword_provider().empty() &&
(first_match != matches_.end()) &&
(first_match->type == AutocompleteMatchType::NAVSUGGEST);
}
bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const {
const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
if (keyword_url == NULL)
return true;
for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
++it) {
if ((it->keyword == keyword_url->keyword()) &&
it->allowed_to_be_default_match)
return true;
}
return false;
}
bool SearchProvider::IsTopMatchScoreTooLow(
bool autocomplete_result_will_reorder_for_default_match) const {
if (autocomplete_result_will_reorder_for_default_match)
return false;
return matches_.front().relevance <
CalculateRelevanceForVerbatimIgnoringKeywordModeState();
}
bool SearchProvider::IsTopMatchSearchWithURLInput(
bool autocomplete_result_will_reorder_for_default_match) const {
ACMatches::const_iterator first_match =
FindTopMatch(autocomplete_result_will_reorder_for_default_match);
return (input_.type() == AutocompleteInput::URL) &&
(first_match != matches_.end()) &&
(first_match->relevance > CalculateRelevanceForVerbatim()) &&
(first_match->type != AutocompleteMatchType::NAVSUGGEST);
}
bool SearchProvider::HasValidDefaultMatch(
bool autocomplete_result_will_reorder_for_default_match) const {
for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
++it) {
if (it->allowed_to_be_default_match)
return true;
if (!autocomplete_result_will_reorder_for_default_match)
return false;
}
return false;
}
void SearchProvider::AddNavigationResultsToMatches(
const NavigationResults& navigation_results,
ACMatches* matches) {
for (NavigationResults::const_iterator it = navigation_results.begin();
it != navigation_results.end(); ++it) {
matches->push_back(NavigationToMatch(*it));
if (!it->relevance_from_server())
return;
}
}
void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
bool is_keyword,
int did_not_accept_suggestion,
MatchMap* map) {
if (results.empty())
return;
base::TimeTicks start_time(base::TimeTicks::Now());
bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
(input_.type() == AutocompleteInput::URL);
const base::string16& input_text =
is_keyword ? keyword_input_.text() : input_.text();
bool input_multiple_words = HasMultipleWords(input_text);
SuggestResults scored_results;
if (!prevent_inline_autocomplete && input_multiple_words) {
scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
false, input_text, is_keyword);
if ((scored_results.front().relevance() <
AutocompleteResult::kLowestDefaultScore) ||
!HasMultipleWords(scored_results.front().suggestion()))
scored_results.clear();
}
if (scored_results.empty())
scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
input_multiple_words, input_text,
is_keyword);
for (SuggestResults::const_iterator i(scored_results.begin());
i != scored_results.end(); ++i) {
AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true, map);
}
UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
base::TimeTicks::Now() - start_time);
}
SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
const HistoryResults& results,
bool base_prevent_inline_autocomplete,
bool input_multiple_words,
const base::string16& input_text,
bool is_keyword) {
AutocompleteClassifier* classifier =
AutocompleteClassifierFactory::GetForProfile(profile_);
SuggestResults scored_results;
const bool prevent_search_history_inlining =
OmniboxFieldTrial::SearchHistoryPreventInlining(
input_.current_page_classification());
const base::string16& trimmed_input =
base::CollapseWhitespace(input_text, false);
for (HistoryResults::const_iterator i(results.begin()); i != results.end();
++i) {
const base::string16& trimmed_suggestion =
base::CollapseWhitespace(i->term, false);
bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
(!input_multiple_words && (i->visits < 2) &&
HasMultipleWords(trimmed_suggestion));
if (!prevent_inline_autocomplete && classifier &&
(trimmed_suggestion != trimmed_input)) {
AutocompleteMatch match;
classifier->Classify(trimmed_suggestion, false, false,
input_.current_page_classification(), &match, NULL);
prevent_inline_autocomplete =
!AutocompleteMatch::IsSearchType(match.type);
}
int relevance = CalculateRelevanceForHistory(
i->time, is_keyword, !prevent_inline_autocomplete,
prevent_search_history_inlining);
scored_results.push_back(SuggestResult(
trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
trimmed_suggestion, base::string16(), base::string16(), std::string(),
std::string(), is_keyword, relevance, false, false, trimmed_input));
}
std::stable_sort(scored_results.begin(), scored_results.end(),
CompareScoredResults());
int last_relevance = 0;
for (SuggestResults::iterator i(scored_results.begin());
i != scored_results.end(); ++i) {
if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
i->set_relevance(last_relevance - 1);
last_relevance = i->relevance();
}
return scored_results;
}
void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
const std::string& metadata,
MatchMap* map) {
for (size_t i = 0; i < results.size(); ++i)
AddMatchToMap(results[i], metadata, i, false, map);
}
int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
bool use_server_relevance =
(default_results_.verbatim_relevance >= 0) &&
!input_.prevent_inline_autocomplete() &&
((default_results_.verbatim_relevance > 0) ||
!default_results_.suggest_results.empty() ||
!default_results_.navigation_results.empty());
if (relevance_from_server)
*relevance_from_server = use_server_relevance;
return use_server_relevance ?
default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
}
int SearchProvider::CalculateRelevanceForVerbatim() const {
if (!providers_.keyword_provider().empty())
return 250;
return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
}
int SearchProvider::
CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
switch (input_.type()) {
case AutocompleteInput::UNKNOWN:
case AutocompleteInput::QUERY:
case AutocompleteInput::FORCED_QUERY:
return kNonURLVerbatimRelevance;
case AutocompleteInput::URL:
return 850;
default:
NOTREACHED();
return 0;
}
}
int SearchProvider::GetKeywordVerbatimRelevance(
bool* relevance_from_server) const {
bool use_server_relevance =
(keyword_results_.verbatim_relevance >= 0) &&
!input_.prevent_inline_autocomplete() &&
((keyword_results_.verbatim_relevance > 0) ||
!keyword_results_.suggest_results.empty() ||
!keyword_results_.navigation_results.empty());
if (relevance_from_server)
*relevance_from_server = use_server_relevance;
return use_server_relevance ?
keyword_results_.verbatim_relevance :
CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
keyword_input_.prefer_keyword());
}
int SearchProvider::CalculateRelevanceForHistory(
const base::Time& time,
bool is_keyword,
bool use_aggressive_method,
bool prevent_search_history_inlining) const {
double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
if (is_primary_provider && use_aggressive_method) {
const double autocomplete_time = 2 * 24 * 60 * 60;
if (elapsed_time < autocomplete_time) {
int max_score = is_keyword ? 1599 : 1399;
if (prevent_search_history_inlining)
max_score = 1299;
return max_score - static_cast<int>(99 *
std::pow(elapsed_time / autocomplete_time, 2.5));
}
elapsed_time -= autocomplete_time;
}
const int score_discount =
static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
int base_score;
if (is_primary_provider)
base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
else
base_score = 200;
return std::max(0, base_score - score_discount);
}
AutocompleteMatch SearchProvider::NavigationToMatch(
const NavigationResult& navigation) {
base::string16 input;
const bool trimmed_whitespace = base::TrimWhitespace(
navigation.from_keyword_provider() ?
keyword_input_.text() : input_.text(),
base::TRIM_TRAILING, &input) != base::TRIM_NONE;
AutocompleteMatch match(this, navigation.relevance(), false,
AutocompleteMatchType::NAVSUGGEST);
match.destination_url = navigation.url();
const URLPrefix* prefix =
URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
size_t match_start = (prefix == NULL) ?
navigation.formatted_url().find(input) : prefix->prefix.length();
bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
(!prefix || (match_start != 0));
const net::FormatUrlTypes format_types =
net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
const std::string languages(
profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
size_t inline_autocomplete_offset = (prefix == NULL) ?
base::string16::npos : (match_start + input.length());
match.fill_into_edit +=
AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
net::FormatUrl(navigation.url(), languages, format_types,
net::UnescapeRule::SPACES, NULL, NULL,
&inline_autocomplete_offset));
if (input_.type() == AutocompleteInput::FORCED_QUERY) {
match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
if (inline_autocomplete_offset != base::string16::npos)
++inline_autocomplete_offset;
}
if (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 = navigation.IsInlineable(input) &&
(providers_.GetKeywordProviderURL() == NULL) &&
(match.inline_autocompletion.empty() ||
(!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
match.contents = navigation.match_contents();
match.contents_class = navigation.match_contents_class();
match.description = navigation.description();
AutocompleteMatch::ClassifyMatchInString(input, match.description,
ACMatchClassification::NONE, &match.description_class);
match.RecordAdditionalInfo(
kRelevanceFromServerKey,
navigation.relevance_from_server() ? kTrue : kFalse);
match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
return match;
}
void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
bool relevance_from_server;
int max_query_relevance = GetKeywordVerbatimRelevance(&relevance_from_server);
if (!keyword_results_.suggest_results.empty()) {
const SuggestResult& top_keyword = keyword_results_.suggest_results.front();
const int suggest_relevance = top_keyword.relevance();
if (suggest_relevance > max_query_relevance) {
max_query_relevance = suggest_relevance;
relevance_from_server = top_keyword.relevance_from_server();
} else if (suggest_relevance == max_query_relevance) {
relevance_from_server |= top_keyword.relevance_from_server();
}
}
if (max_query_relevance == 0) {
ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
keyword_results_.verbatim_relevance = -1;
default_results_.verbatim_relevance = -1;
return;
}
for (NavigationResults::iterator it =
keyword_results_.navigation_results.begin();
it != keyword_results_.navigation_results.end(); ++it) {
if (it->relevance() < max_query_relevance)
return;
max_query_relevance = std::max(max_query_relevance - 1, 0);
it->set_relevance(max_query_relevance);
it->set_relevance_from_server(relevance_from_server);
}
}
void SearchProvider::UpdateDone() {
done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
}