This source file includes following definitions.
- ScopedEndExtensionKeywordMode
- ScopedEndExtensionKeywordMode
- StayInKeywordMode
- current_input_id_
- current_input_id_
- SplitKeywordFromInput
- SplitReplacementStringFromInput
- GetSubstitutingTemplateURLForInput
- GetKeywordForText
- CreateVerbatimMatch
- Start
- Stop
- ExtractKeywordFromInput
- CalculateRelevance
- CreateAutocompleteMatch
- FillInURLAndContents
- Observe
- GetTemplateURLService
- EnterExtensionKeywordMode
- MaybeEndExtensionKeywordMode
#include "chrome/browser/autocomplete/keyword_provider.h"
#include <algorithm>
#include <vector>
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/extensions/api/omnibox/omnibox_api.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "extensions/browser/extension_system.h"
#include "grit/generated_resources.h"
#include "net/base/escape.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"
namespace omnibox_api = extensions::api::omnibox;
class KeywordProvider::ScopedEndExtensionKeywordMode {
public:
explicit ScopedEndExtensionKeywordMode(KeywordProvider* provider)
: provider_(provider) { }
~ScopedEndExtensionKeywordMode() {
if (provider_)
provider_->MaybeEndExtensionKeywordMode();
}
void StayInKeywordMode() {
provider_ = NULL;
}
private:
KeywordProvider* provider_;
};
KeywordProvider::KeywordProvider(AutocompleteProviderListener* listener,
Profile* profile)
: AutocompleteProvider(listener, profile,
AutocompleteProvider::TYPE_KEYWORD),
model_(NULL),
current_input_id_(0) {
registrar_.Add(this,
chrome::NOTIFICATION_EXTENSION_OMNIBOX_SUGGESTIONS_READY,
content::Source<Profile>(profile->GetOriginalProfile()));
registrar_.Add(
this, chrome::NOTIFICATION_EXTENSION_OMNIBOX_DEFAULT_SUGGESTION_CHANGED,
content::Source<Profile>(profile->GetOriginalProfile()));
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_OMNIBOX_INPUT_ENTERED,
content::Source<Profile>(profile));
}
KeywordProvider::KeywordProvider(AutocompleteProviderListener* listener,
TemplateURLService* model)
: AutocompleteProvider(listener, NULL, AutocompleteProvider::TYPE_KEYWORD),
model_(model),
current_input_id_(0) {
}
namespace {
class CompareQuality {
public:
bool operator()(const TemplateURL* t_url1, const TemplateURL* t_url2) const {
return t_url1->keyword().length() < t_url2->keyword().length();
}
};
static int global_input_uid_;
}
base::string16 KeywordProvider::SplitKeywordFromInput(
const base::string16& input,
bool trim_leading_whitespace,
base::string16* remaining_input) {
const size_t first_white(input.find_first_of(base::kWhitespaceUTF16));
DCHECK_NE(0U, first_white);
if (first_white == base::string16::npos)
return input;
DCHECK(remaining_input != NULL);
const size_t remaining_start = trim_leading_whitespace ?
input.find_first_not_of(base::kWhitespaceUTF16, first_white) :
first_white + 1;
if (remaining_start < input.length())
remaining_input->assign(input.begin() + remaining_start, input.end());
return input.substr(0, first_white);
}
base::string16 KeywordProvider::SplitReplacementStringFromInput(
const base::string16& input,
bool trim_leading_whitespace) {
base::string16 trimmed_input;
base::TrimWhitespace(input, base::TRIM_LEADING, &trimmed_input);
base::string16 remaining_input;
SplitKeywordFromInput(trimmed_input, trim_leading_whitespace,
&remaining_input);
return remaining_input;
}
const TemplateURL* KeywordProvider::GetSubstitutingTemplateURLForInput(
TemplateURLService* model,
AutocompleteInput* input) {
if (!input->allow_exact_keyword_match())
return NULL;
base::string16 keyword, remaining_input;
if (!ExtractKeywordFromInput(*input, &keyword, &remaining_input))
return NULL;
DCHECK(model);
const TemplateURL* template_url = model->GetTemplateURLForKeyword(keyword);
if (template_url && template_url->SupportsReplacement()) {
size_t cursor_position = base::string16::npos;
if (input->cursor_position() != base::string16::npos &&
!remaining_input.empty() &&
EndsWith(input->text(), remaining_input, true)) {
int offset = input->text().length() - input->cursor_position();
DCHECK_GE(offset, 0);
DCHECK_LE(offset, static_cast<int>(input->text().length()));
if (offset <= 0) {
cursor_position = remaining_input.length();
} else {
cursor_position = offset > static_cast<int>(remaining_input.length()) ?
0u : remaining_input.length() - offset;
}
}
input->UpdateText(remaining_input, cursor_position, input->parts());
return template_url;
}
return NULL;
}
base::string16 KeywordProvider::GetKeywordForText(
const base::string16& text) const {
const base::string16 keyword(TemplateURLService::CleanUserInputKeyword(text));
if (keyword.empty())
return keyword;
TemplateURLService* url_service = GetTemplateURLService();
if (!url_service)
return base::string16();
const TemplateURL* const template_url =
url_service->GetTemplateURLForKeyword(keyword);
if (!template_url || !template_url->SupportsReplacement())
return base::string16();
if (template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION) {
ExtensionService* extension_service =
extensions::ExtensionSystem::Get(profile_)->extension_service();
const extensions::Extension* extension = extension_service->
GetExtensionById(template_url->GetExtensionId(), false);
if (!extension ||
(profile_->IsOffTheRecord() &&
!extensions::util::IsIncognitoEnabled(extension->id(), profile_)))
return base::string16();
}
return keyword;
}
AutocompleteMatch KeywordProvider::CreateVerbatimMatch(
const base::string16& text,
const base::string16& keyword,
const AutocompleteInput& input) {
return CreateAutocompleteMatch(
GetTemplateURLService()->GetTemplateURLForKeyword(keyword), input,
keyword.length(), SplitReplacementStringFromInput(text, true), true, 0);
}
void KeywordProvider::Start(const AutocompleteInput& input,
bool minimal_changes) {
ScopedEndExtensionKeywordMode keyword_mode_toggle(this);
matches_.clear();
if (!minimal_changes) {
done_ = true;
current_input_id_ = ++global_input_uid_;
}
base::string16 keyword, remaining_input;
if (!ExtractKeywordFromInput(input, &keyword, &remaining_input))
return;
TemplateURLService::TemplateURLVector matches;
GetTemplateURLService()->FindMatchingKeywords(
keyword, !remaining_input.empty(), &matches);
for (TemplateURLService::TemplateURLVector::iterator i(matches.begin());
i != matches.end(); ) {
const TemplateURL* template_url = *i;
if (profile_ &&
(template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION)) {
ExtensionService* service = extensions::ExtensionSystem::Get(profile_)->
extension_service();
const extensions::Extension* extension =
service->GetExtensionById(template_url->GetExtensionId(), false);
bool enabled =
extension && (!profile_->IsOffTheRecord() ||
extensions::util::IsIncognitoEnabled(
extension->id(), profile_));
if (!enabled) {
i = matches.erase(i);
continue;
}
}
if (template_url->SupportsReplacement() && remaining_input.empty() &&
!input.allow_exact_keyword_match()) {
i = matches.erase(i);
continue;
}
++i;
}
if (matches.empty())
return;
std::sort(matches.begin(), matches.end(), CompareQuality());
if (matches.front()->keyword() == keyword) {
const TemplateURL* template_url = matches.front();
const bool is_extension_keyword =
template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
if (!remaining_input.empty() && !is_extension_keyword)
return;
matches_.push_back(CreateAutocompleteMatch(
template_url, input, keyword.length(), remaining_input, true, -1));
if (profile_ && is_extension_keyword) {
if (input.matches_requested() == AutocompleteInput::ALL_MATCHES) {
if (template_url->GetExtensionId() != current_keyword_extension_id_)
MaybeEndExtensionKeywordMode();
if (current_keyword_extension_id_.empty())
EnterExtensionKeywordMode(template_url->GetExtensionId());
keyword_mode_toggle.StayInKeywordMode();
}
extensions::ApplyDefaultSuggestionForExtensionKeyword(
profile_, template_url,
remaining_input,
&matches_[0]);
if (minimal_changes &&
(input.matches_requested() != AutocompleteInput::BEST_MATCH)) {
for (size_t i = 0; i < extension_suggest_matches_.size(); ++i) {
matches_.push_back(extension_suggest_matches_[i]);
matches_.back().relevance = matches_[0].relevance - (i + 1);
}
} else if (input.matches_requested() == AutocompleteInput::ALL_MATCHES) {
extension_suggest_last_input_ = input;
extension_suggest_matches_.clear();
bool have_listeners =
extensions::ExtensionOmniboxEventRouter::OnInputChanged(
profile_, template_url->GetExtensionId(),
base::UTF16ToUTF8(remaining_input), current_input_id_);
if (have_listeners)
done_ = false;
}
}
} else {
if (matches.size() > kMaxMatches)
matches.erase(matches.begin() + kMaxMatches, matches.end());
for (TemplateURLService::TemplateURLVector::const_iterator i(
matches.begin()); i != matches.end(); ++i) {
matches_.push_back(CreateAutocompleteMatch(
*i, input, keyword.length(), remaining_input, false, -1));
}
}
}
void KeywordProvider::Stop(bool clear_cached_results) {
done_ = true;
MaybeEndExtensionKeywordMode();
}
KeywordProvider::~KeywordProvider() {}
bool KeywordProvider::ExtractKeywordFromInput(const AutocompleteInput& input,
base::string16* keyword,
base::string16* remaining_input) {
if ((input.type() == AutocompleteInput::INVALID) ||
(input.type() == AutocompleteInput::FORCED_QUERY))
return false;
*keyword = TemplateURLService::CleanUserInputKeyword(
SplitKeywordFromInput(input.text(), true, remaining_input));
return !keyword->empty();
}
int KeywordProvider::CalculateRelevance(AutocompleteInput::Type type,
bool complete,
bool supports_replacement,
bool prefer_keyword,
bool allow_exact_keyword_match) {
if (!complete)
return (type == AutocompleteInput::URL) ? 700 : 450;
if (!supports_replacement || (allow_exact_keyword_match && prefer_keyword))
return 1500;
return (allow_exact_keyword_match && (type == AutocompleteInput::QUERY)) ?
1450 : 1100;
}
AutocompleteMatch KeywordProvider::CreateAutocompleteMatch(
const TemplateURL* template_url,
const AutocompleteInput& input,
size_t prefix_length,
const base::string16& remaining_input,
bool allowed_to_be_default_match,
int relevance) {
DCHECK(template_url);
const bool supports_replacement =
template_url->url_ref().SupportsReplacement();
const base::string16& keyword = template_url->keyword();
const bool keyword_complete = (prefix_length == keyword.length());
if (relevance < 0) {
relevance =
CalculateRelevance(input.type(), keyword_complete,
supports_replacement, input.prefer_keyword(),
input.allow_exact_keyword_match());
}
AutocompleteMatch match(this, relevance, false,
supports_replacement ? AutocompleteMatchType::SEARCH_OTHER_ENGINE :
AutocompleteMatchType::HISTORY_KEYWORD);
match.allowed_to_be_default_match = allowed_to_be_default_match;
match.fill_into_edit = keyword;
if (!remaining_input.empty() || supports_replacement)
match.fill_into_edit.push_back(L' ');
match.fill_into_edit.append(remaining_input);
FillInURLAndContents(remaining_input, template_url, &match);
match.keyword = keyword;
match.transition = content::PAGE_TRANSITION_KEYWORD;
return match;
}
void KeywordProvider::FillInURLAndContents(
const base::string16& remaining_input,
const TemplateURL* element,
AutocompleteMatch* match) const {
DCHECK(!element->short_name().empty());
const TemplateURLRef& element_ref = element->url_ref();
DCHECK(element_ref.IsValid());
int message_id = (element->GetType() == TemplateURL::OMNIBOX_API_EXTENSION) ?
IDS_EXTENSION_KEYWORD_COMMAND : IDS_KEYWORD_SEARCH;
if (remaining_input.empty()) {
if (element_ref.SupportsReplacement() &&
(element->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
match->contents.assign(
l10n_util::GetStringFUTF16(message_id,
element->AdjustedShortNameForLocaleDirection(),
l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE)));
match->contents_class.push_back(
ACMatchClassification(0, ACMatchClassification::DIM));
} else {
match->destination_url = GURL(element->url());
match->contents.assign(element->short_name());
AutocompleteMatch::ClassifyLocationInString(0, match->contents.length(),
match->contents.length(), ACMatchClassification::NONE,
&match->contents_class);
}
} else {
DCHECK(element_ref.SupportsReplacement());
TemplateURLRef::SearchTermsArgs search_terms_args(remaining_input);
search_terms_args.append_extra_query_params =
element == GetTemplateURLService()->GetDefaultSearchProvider();
match->destination_url =
GURL(element_ref.ReplaceSearchTerms(search_terms_args));
std::vector<size_t> content_param_offsets;
match->contents.assign(l10n_util::GetStringFUTF16(message_id,
element->short_name(),
remaining_input,
&content_param_offsets));
DCHECK_EQ(2U, content_param_offsets.size());
AutocompleteMatch::ClassifyLocationInString(content_param_offsets[1],
remaining_input.length(), match->contents.length(),
ACMatchClassification::NONE, &match->contents_class);
}
}
void KeywordProvider::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
TemplateURLService* model = GetTemplateURLService();
const AutocompleteInput& input = extension_suggest_last_input_;
switch (type) {
case chrome::NOTIFICATION_EXTENSION_OMNIBOX_INPUT_ENTERED:
current_keyword_extension_id_.clear();
current_input_id_ = 0;
return;
case chrome::NOTIFICATION_EXTENSION_OMNIBOX_DEFAULT_SUGGESTION_CHANGED: {
base::string16 keyword, remaining_input;
if (matches_.empty() || current_keyword_extension_id_.empty() ||
!ExtractKeywordFromInput(input, &keyword, &remaining_input))
return;
const TemplateURL* template_url(
model->GetTemplateURLForKeyword(keyword));
extensions::ApplyDefaultSuggestionForExtensionKeyword(
profile_, template_url,
remaining_input,
&matches_[0]);
listener_->OnProviderUpdate(true);
return;
}
case chrome::NOTIFICATION_EXTENSION_OMNIBOX_SUGGESTIONS_READY: {
const omnibox_api::SendSuggestions::Params& suggestions =
*content::Details<
omnibox_api::SendSuggestions::Params>(details).ptr();
if (suggestions.request_id != current_input_id_)
return;
base::string16 keyword, remaining_input;
bool result = ExtractKeywordFromInput(input, &keyword, &remaining_input);
DCHECK(result);
const TemplateURL* template_url =
model->GetTemplateURLForKeyword(keyword);
for (size_t i = 0; i < suggestions.suggest_results.size(); ++i) {
const omnibox_api::SuggestResult& suggestion =
*suggestions.suggest_results[i];
int first_relevance = CalculateRelevance(input.type(), true, true,
input.prefer_keyword(), input.allow_exact_keyword_match());
extension_suggest_matches_.push_back(CreateAutocompleteMatch(
template_url, input, keyword.length(),
base::UTF8ToUTF16(suggestion.content), false,
first_relevance - (i + 1)));
AutocompleteMatch* match = &extension_suggest_matches_.back();
match->contents.assign(base::UTF8ToUTF16(suggestion.description));
match->contents_class =
extensions::StyleTypesToACMatchClassifications(suggestion);
}
done_ = true;
matches_.insert(matches_.end(), extension_suggest_matches_.begin(),
extension_suggest_matches_.end());
listener_->OnProviderUpdate(!extension_suggest_matches_.empty());
return;
}
default:
NOTREACHED();
return;
}
}
TemplateURLService* KeywordProvider::GetTemplateURLService() const {
TemplateURLService* service = profile_ ?
TemplateURLServiceFactory::GetForProfile(profile_) : model_;
DCHECK(service);
service->Load();
return service;
}
void KeywordProvider::EnterExtensionKeywordMode(
const std::string& extension_id) {
DCHECK(current_keyword_extension_id_.empty());
current_keyword_extension_id_ = extension_id;
extensions::ExtensionOmniboxEventRouter::OnInputStarted(
profile_, current_keyword_extension_id_);
}
void KeywordProvider::MaybeEndExtensionKeywordMode() {
if (!current_keyword_extension_id_.empty()) {
extensions::ExtensionOmniboxEventRouter::OnInputCancelled(
profile_, current_keyword_extension_id_);
current_keyword_extension_id_.clear();
}
}