This source file includes following definitions.
- BestURLPrefixWithWWWCase
- initialized_
- Start
- DeleteMatch
- OnShortcutsLoaded
- GetMatches
- ShortcutToACMatch
- CreateWordMapForString
- ClassifyAllMatchesInString
- FindFirstMatch
- CalculateScore
#include "chrome/browser/autocomplete/shortcuts_provider.h"
#include <algorithm>
#include <cmath>
#include <map>
#include <vector>
#include "base/i18n/break_iterator.h"
#include "base/i18n/case_conversion.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "chrome/browser/autocomplete/autocomplete_input.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/autocomplete/history_provider.h"
#include "chrome/browser/autocomplete/shortcuts_backend_factory.h"
#include "chrome/browser/autocomplete/url_prefix.h"
#include "chrome/browser/history/history_notifications.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/omnibox/omnibox_field_trial.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/net/url_fixer_upper.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "url/url_parse.h"
namespace {
class DestinationURLEqualsURL {
public:
explicit DestinationURLEqualsURL(const GURL& url) : url_(url) {}
bool operator()(const AutocompleteMatch& match) const {
return match.destination_url == url_;
}
private:
const GURL url_;
};
const URLPrefix* BestURLPrefixWithWWWCase(
const base::string16& text,
const base::string16& prefix_suffix) {
CR_DEFINE_STATIC_LOCAL(URLPrefix, www_prefix,
(base::ASCIIToUTF16("www."), 1));
const URLPrefix* best_prefix = URLPrefix::BestURLPrefix(text, prefix_suffix);
if ((best_prefix == NULL) ||
(best_prefix->num_components < www_prefix.num_components)) {
if (URLPrefix::PrefixMatch(www_prefix, text, prefix_suffix))
best_prefix = &www_prefix;
}
return best_prefix;
}
}
ShortcutsProvider::ShortcutsProvider(AutocompleteProviderListener* listener,
Profile* profile)
: AutocompleteProvider(listener, profile,
AutocompleteProvider::TYPE_SHORTCUTS),
languages_(profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)),
initialized_(false) {
scoped_refptr<ShortcutsBackend> backend =
ShortcutsBackendFactory::GetForProfile(profile_);
if (backend.get()) {
backend->AddObserver(this);
if (backend->initialized())
initialized_ = true;
}
}
void ShortcutsProvider::Start(const AutocompleteInput& input,
bool minimal_changes) {
matches_.clear();
if ((input.type() == AutocompleteInput::INVALID) ||
(input.type() == AutocompleteInput::FORCED_QUERY))
return;
if (input.text().empty())
return;
if (!initialized_)
return;
base::TimeTicks start_time = base::TimeTicks::Now();
GetMatches(input);
if (input.text().length() < 6) {
base::TimeTicks end_time = base::TimeTicks::Now();
std::string name = "ShortcutsProvider.QueryIndexTime." +
base::IntToString(input.text().size());
base::HistogramBase* counter = base::Histogram::FactoryGet(
name, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag);
counter->Add(static_cast<int>((end_time - start_time).InMilliseconds()));
}
UpdateStarredStateOfMatches();
}
void ShortcutsProvider::DeleteMatch(const AutocompleteMatch& match) {
GURL url(match.destination_url);
DCHECK(url.is_valid());
scoped_refptr<ShortcutsBackend> backend =
ShortcutsBackendFactory::GetForProfileIfExists(profile_);
if (backend)
backend->DeleteShortcutsWithURL(url);
matches_.erase(std::remove_if(matches_.begin(), matches_.end(),
DestinationURLEqualsURL(url)),
matches_.end());
HistoryService* const history_service =
HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
DCHECK(history_service);
history_service->DeleteURL(url);
}
ShortcutsProvider::~ShortcutsProvider() {
scoped_refptr<ShortcutsBackend> backend =
ShortcutsBackendFactory::GetForProfileIfExists(profile_);
if (backend.get())
backend->RemoveObserver(this);
}
void ShortcutsProvider::OnShortcutsLoaded() {
initialized_ = true;
}
void ShortcutsProvider::GetMatches(const AutocompleteInput& input) {
scoped_refptr<ShortcutsBackend> backend =
ShortcutsBackendFactory::GetForProfileIfExists(profile_);
if (!backend.get())
return;
base::string16 term_string(base::i18n::ToLower(input.text()));
DCHECK(!term_string.empty());
base::string16 fixed_up_term_string(term_string);
AutocompleteInput fixed_up_input(input);
if (FixupUserInput(&fixed_up_input))
fixed_up_term_string = fixed_up_input.text();
const GURL& term_string_as_gurl = URLFixerUpper::FixupURL(
base::UTF16ToUTF8(term_string), std::string());
int max_relevance;
if (!OmniboxFieldTrial::ShortcutsScoringMaxRelevance(
input.current_page_classification(), &max_relevance))
max_relevance = AutocompleteResult::kLowestDefaultScore - 1;
for (ShortcutsBackend::ShortcutMap::const_iterator it =
FindFirstMatch(term_string, backend.get());
it != backend->shortcuts_map().end() &&
StartsWith(it->first, term_string, true); ++it) {
int relevance = CalculateScore(term_string, it->second, max_relevance);
if (relevance) {
matches_.push_back(ShortcutToACMatch(
it->second, relevance, term_string, fixed_up_term_string,
term_string_as_gurl, input.prevent_inline_autocomplete()));
matches_.back().ComputeStrippedDestinationURL(profile_);
}
}
std::sort(matches_.begin(), matches_.end(),
&AutocompleteMatch::DestinationSortFunc);
matches_.erase(std::unique(matches_.begin(), matches_.end(),
&AutocompleteMatch::DestinationsEqual),
matches_.end());
std::partial_sort(matches_.begin(),
matches_.begin() +
std::min(AutocompleteProvider::kMaxMatches, matches_.size()),
matches_.end(), &AutocompleteMatch::MoreRelevant);
if (matches_.size() > AutocompleteProvider::kMaxMatches) {
matches_.erase(matches_.begin() + AutocompleteProvider::kMaxMatches,
matches_.end());
}
if (!OmniboxFieldTrial::ReorderForLegalDefaultMatch(
input.current_page_classification()) &&
(matches_.empty() || !matches_.front().allowed_to_be_default_match)) {
max_relevance = std::min(max_relevance,
AutocompleteResult::kLowestDefaultScore - 1);
}
for (ACMatches::iterator it = matches_.begin(); it != matches_.end(); ++it) {
max_relevance = std::min(max_relevance, it->relevance);
it->relevance = max_relevance;
if (max_relevance > 1)
--max_relevance;
}
}
AutocompleteMatch ShortcutsProvider::ShortcutToACMatch(
const history::ShortcutsDatabase::Shortcut& shortcut,
int relevance,
const base::string16& term_string,
const base::string16& fixed_up_term_string,
const GURL& term_string_as_gurl,
const bool prevent_inline_autocomplete) {
DCHECK(!term_string.empty());
AutocompleteMatch match;
match.provider = this;
match.relevance = relevance;
match.deletable = true;
match.fill_into_edit = shortcut.match_core.fill_into_edit;
match.destination_url = shortcut.match_core.destination_url;
DCHECK(match.destination_url.is_valid());
match.contents = shortcut.match_core.contents;
match.contents_class = AutocompleteMatch::ClassificationsFromString(
shortcut.match_core.contents_class);
match.description = shortcut.match_core.description;
match.description_class = AutocompleteMatch::ClassificationsFromString(
shortcut.match_core.description_class);
match.transition =
static_cast<content::PageTransition>(shortcut.match_core.transition);
match.type = static_cast<AutocompleteMatch::Type>(shortcut.match_core.type);
match.keyword = shortcut.match_core.keyword;
match.RecordAdditionalInfo("number of hits", shortcut.number_of_hits);
match.RecordAdditionalInfo("last access time", shortcut.last_access_time);
match.RecordAdditionalInfo("original input text",
base::UTF16ToUTF8(shortcut.text));
if (AutocompleteMatch::IsSearchType(match.type)) {
if (StartsWith(match.fill_into_edit, term_string, false)) {
match.inline_autocompletion =
match.fill_into_edit.substr(term_string.length());
match.allowed_to_be_default_match =
!prevent_inline_autocomplete || match.inline_autocompletion.empty();
}
} else {
const URLPrefix* best_prefix =
BestURLPrefixWithWWWCase(match.fill_into_edit, term_string);
const base::string16* matching_string = &term_string;
if ((best_prefix == NULL) && !fixed_up_term_string.empty() &&
(fixed_up_term_string != term_string)) {
best_prefix = BestURLPrefixWithWWWCase(
match.fill_into_edit, fixed_up_term_string);
matching_string = &fixed_up_term_string;
}
if (best_prefix != NULL) {
match.inline_autocompletion = match.fill_into_edit.substr(
best_prefix->prefix.length() + matching_string->length());
match.allowed_to_be_default_match =
!prevent_inline_autocomplete || match.inline_autocompletion.empty();
} else {
match.allowed_to_be_default_match = (term_string_as_gurl ==
URLFixerUpper::FixupURL(base::UTF16ToUTF8(match.fill_into_edit),
std::string()));
}
}
WordMap terms_map(CreateWordMapForString(term_string));
if (!terms_map.empty()) {
match.contents_class = ClassifyAllMatchesInString(term_string, terms_map,
match.contents, match.contents_class);
match.description_class = ClassifyAllMatchesInString(term_string, terms_map,
match.description, match.description_class);
}
return match;
}
ShortcutsProvider::WordMap ShortcutsProvider::CreateWordMapForString(
const base::string16& text) {
WordMap word_map;
base::i18n::BreakIterator word_iter(text,
base::i18n::BreakIterator::BREAK_WORD);
if (!word_iter.Init())
return word_map;
std::vector<base::string16> words;
while (word_iter.Advance()) {
if (word_iter.IsWord())
words.push_back(word_iter.GetString());
}
if (words.empty())
return word_map;
std::sort(words.begin(), words.end());
words.erase(std::unique(words.begin(), words.end()), words.end());
std::reverse(words.begin(), words.end());
for (std::vector<base::string16>::const_iterator i(words.begin());
i != words.end(); ++i)
word_map.insert(std::make_pair((*i)[0], *i));
return word_map;
}
ACMatchClassifications ShortcutsProvider::ClassifyAllMatchesInString(
const base::string16& find_text,
const WordMap& find_words,
const base::string16& text,
const ACMatchClassifications& original_class) {
DCHECK(!find_text.empty());
DCHECK(!find_words.empty());
if (text.empty())
return original_class;
base::string16 text_lowercase(base::i18n::ToLower(text));
ACMatchClassifications match_class;
size_t last_position = 0;
if (StartsWith(text_lowercase, find_text, true)) {
match_class.push_back(
ACMatchClassification(0, ACMatchClassification::MATCH));
last_position = find_text.length();
if (last_position < text_lowercase.length()) {
match_class.push_back(
ACMatchClassification(last_position, ACMatchClassification::NONE));
}
} else {
match_class.push_back(
ACMatchClassification(0, ACMatchClassification::NONE));
}
while (last_position < text_lowercase.length()) {
std::pair<WordMap::const_iterator, WordMap::const_iterator> range(
find_words.equal_range(text_lowercase[last_position]));
size_t next_character = last_position + 1;
for (WordMap::const_iterator i(range.first); i != range.second; ++i) {
const base::string16& word = i->second;
size_t word_end = last_position + word.length();
if ((word_end <= text_lowercase.length()) &&
!text_lowercase.compare(last_position, word.length(), word)) {
if (match_class.back().offset == last_position)
match_class.pop_back();
AutocompleteMatch::AddLastClassificationIfNecessary(&match_class,
last_position, ACMatchClassification::MATCH);
if (word_end < text_lowercase.length()) {
match_class.push_back(
ACMatchClassification(word_end, ACMatchClassification::NONE));
}
last_position = word_end;
break;
}
}
last_position = std::max(last_position, next_character);
}
return AutocompleteMatch::MergeClassifications(original_class, match_class);
}
ShortcutsBackend::ShortcutMap::const_iterator
ShortcutsProvider::FindFirstMatch(const base::string16& keyword,
ShortcutsBackend* backend) {
DCHECK(backend);
ShortcutsBackend::ShortcutMap::const_iterator it =
backend->shortcuts_map().lower_bound(keyword);
return ((it == backend->shortcuts_map().end()) ||
StartsWith(it->first, keyword, true)) ? it :
backend->shortcuts_map().end();
}
int ShortcutsProvider::CalculateScore(
const base::string16& terms,
const history::ShortcutsDatabase::Shortcut& shortcut,
int max_relevance) {
DCHECK(!terms.empty());
DCHECK_LE(terms.length(), shortcut.text.length());
double base_score = max_relevance *
sqrt(static_cast<double>(terms.length()) / shortcut.text.length());
const double kLn2 = 0.6931471805599453;
base::TimeDelta time_passed = base::Time::Now() - shortcut.last_access_time;
double decay_exponent = std::max(0.0, kLn2 * static_cast<double>(
time_passed.InMicroseconds()) / base::Time::kMicrosecondsPerWeek);
const double kMaxDecaySpeedDivisor = 5.0;
const double kNumUsesPerDecaySpeedDivisorIncrement = 5.0;
double decay_divisor = std::min(kMaxDecaySpeedDivisor,
(shortcut.number_of_hits + kNumUsesPerDecaySpeedDivisorIncrement - 1) /
kNumUsesPerDecaySpeedDivisorIncrement);
return static_cast<int>((base_score / exp(decay_exponent / decay_divisor)) +
0.5);
}