Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / autocomplete / keyword_provider.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/autocomplete/keyword_provider.h"
6
7 #include <algorithm>
8 #include <vector>
9
10 #include "base/strings/string16.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "chrome/browser/autocomplete/autocomplete_match.h"
14 #include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
15 #include "chrome/browser/chrome_notification_types.h"
16 #include "chrome/browser/extensions/api/omnibox/omnibox_api.h"
17 #include "chrome/browser/extensions/extension_service.h"
18 #include "chrome/browser/extensions/extension_util.h"
19 #include "chrome/browser/profiles/profile.h"
20 #include "chrome/browser/search_engines/template_url.h"
21 #include "chrome/browser/search_engines/template_url_service.h"
22 #include "chrome/browser/search_engines/template_url_service_factory.h"
23 #include "content/public/browser/notification_details.h"
24 #include "content/public/browser/notification_source.h"
25 #include "extensions/browser/extension_system.h"
26 #include "grit/generated_resources.h"
27 #include "net/base/escape.h"
28 #include "net/base/net_util.h"
29 #include "ui/base/l10n/l10n_util.h"
30
31 namespace omnibox_api = extensions::api::omnibox;
32
33 // Helper functor for Start(), for ending keyword mode unless explicitly told
34 // otherwise.
35 class KeywordProvider::ScopedEndExtensionKeywordMode {
36  public:
37   explicit ScopedEndExtensionKeywordMode(KeywordProvider* provider)
38       : provider_(provider) { }
39   ~ScopedEndExtensionKeywordMode() {
40     if (provider_)
41       provider_->MaybeEndExtensionKeywordMode();
42   }
43
44   void StayInKeywordMode() {
45     provider_ = NULL;
46   }
47  private:
48   KeywordProvider* provider_;
49 };
50
51 KeywordProvider::KeywordProvider(AutocompleteProviderListener* listener,
52                                  Profile* profile)
53     : AutocompleteProvider(listener, profile,
54           AutocompleteProvider::TYPE_KEYWORD),
55       model_(NULL),
56       current_input_id_(0) {
57   // Extension suggestions always come from the original profile, since that's
58   // where extensions run. We use the input ID to distinguish whether the
59   // suggestions are meant for us.
60   registrar_.Add(this,
61                  chrome::NOTIFICATION_EXTENSION_OMNIBOX_SUGGESTIONS_READY,
62                  content::Source<Profile>(profile->GetOriginalProfile()));
63   registrar_.Add(
64       this, chrome::NOTIFICATION_EXTENSION_OMNIBOX_DEFAULT_SUGGESTION_CHANGED,
65       content::Source<Profile>(profile->GetOriginalProfile()));
66   registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_OMNIBOX_INPUT_ENTERED,
67                  content::Source<Profile>(profile));
68 }
69
70 KeywordProvider::KeywordProvider(AutocompleteProviderListener* listener,
71                                  TemplateURLService* model)
72     : AutocompleteProvider(listener, NULL, AutocompleteProvider::TYPE_KEYWORD),
73       model_(model),
74       current_input_id_(0) {
75 }
76
77
78 namespace {
79
80 // Helper functor for Start(), for sorting keyword matches by quality.
81 class CompareQuality {
82  public:
83   // A keyword is of higher quality when a greater fraction of it has been
84   // typed, that is, when it is shorter.
85   //
86   // TODO(pkasting): Most recent and most frequent keywords are probably
87   // better rankings than the fraction of the keyword typed.  We should
88   // always put any exact matches first no matter what, since the code in
89   // Start() assumes this (and it makes sense).
90   bool operator()(const TemplateURL* t_url1, const TemplateURL* t_url2) const {
91     return t_url1->keyword().length() < t_url2->keyword().length();
92   }
93 };
94
95 // We need our input IDs to be unique across all profiles, so we keep a global
96 // UID that each provider uses.
97 static int global_input_uid_;
98
99 }  // namespace
100
101 // static
102 base::string16 KeywordProvider::SplitKeywordFromInput(
103     const base::string16& input,
104     bool trim_leading_whitespace,
105     base::string16* remaining_input) {
106   // Find end of first token.  The AutocompleteController has trimmed leading
107   // whitespace, so we need not skip over that.
108   const size_t first_white(input.find_first_of(base::kWhitespaceUTF16));
109   DCHECK_NE(0U, first_white);
110   if (first_white == base::string16::npos)
111     return input;  // Only one token provided.
112
113   // Set |remaining_input| to everything after the first token.
114   DCHECK(remaining_input != NULL);
115   const size_t remaining_start = trim_leading_whitespace ?
116       input.find_first_not_of(base::kWhitespaceUTF16, first_white) :
117       first_white + 1;
118
119   if (remaining_start < input.length())
120     remaining_input->assign(input.begin() + remaining_start, input.end());
121
122   // Return first token as keyword.
123   return input.substr(0, first_white);
124 }
125
126 // static
127 base::string16 KeywordProvider::SplitReplacementStringFromInput(
128     const base::string16& input,
129     bool trim_leading_whitespace) {
130   // The input may contain leading whitespace, strip it.
131   base::string16 trimmed_input;
132   base::TrimWhitespace(input, base::TRIM_LEADING, &trimmed_input);
133
134   // And extract the replacement string.
135   base::string16 remaining_input;
136   SplitKeywordFromInput(trimmed_input, trim_leading_whitespace,
137       &remaining_input);
138   return remaining_input;
139 }
140
141 // static
142 const TemplateURL* KeywordProvider::GetSubstitutingTemplateURLForInput(
143     TemplateURLService* model,
144     AutocompleteInput* input) {
145   if (!input->allow_exact_keyword_match())
146     return NULL;
147
148   base::string16 keyword, remaining_input;
149   if (!ExtractKeywordFromInput(*input, &keyword, &remaining_input))
150     return NULL;
151
152   DCHECK(model);
153   const TemplateURL* template_url = model->GetTemplateURLForKeyword(keyword);
154   if (template_url && template_url->SupportsReplacement()) {
155     // Adjust cursor position iff it was set before, otherwise leave it as is.
156     size_t cursor_position = base::string16::npos;
157     // The adjustment assumes that the keyword was stripped from the beginning
158     // of the original input.
159     if (input->cursor_position() != base::string16::npos &&
160         !remaining_input.empty() &&
161         EndsWith(input->text(), remaining_input, true)) {
162       int offset = input->text().length() - input->cursor_position();
163       // The cursor should never be past the last character or before the
164       // first character.
165       DCHECK_GE(offset, 0);
166       DCHECK_LE(offset, static_cast<int>(input->text().length()));
167       if (offset <= 0) {
168         // Normalize the cursor to be exactly after the last character.
169         cursor_position = remaining_input.length();
170       } else {
171         // If somehow the cursor was before the remaining text, set it to 0,
172         // otherwise adjust it relative to the remaining text.
173         cursor_position = offset > static_cast<int>(remaining_input.length()) ?
174             0u : remaining_input.length() - offset;
175       }
176     }
177     input->UpdateText(remaining_input, cursor_position, input->parts());
178     return template_url;
179   }
180
181   return NULL;
182 }
183
184 base::string16 KeywordProvider::GetKeywordForText(
185     const base::string16& text) const {
186   const base::string16 keyword(TemplateURLService::CleanUserInputKeyword(text));
187
188   if (keyword.empty())
189     return keyword;
190
191   TemplateURLService* url_service = GetTemplateURLService();
192   if (!url_service)
193     return base::string16();
194
195   // Don't provide a keyword if it doesn't support replacement.
196   const TemplateURL* const template_url =
197       url_service->GetTemplateURLForKeyword(keyword);
198   if (!template_url || !template_url->SupportsReplacement())
199     return base::string16();
200
201   // Don't provide a keyword for inactive/disabled extension keywords.
202   if (template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION) {
203     ExtensionService* extension_service =
204         extensions::ExtensionSystem::Get(profile_)->extension_service();
205     const extensions::Extension* extension = extension_service->
206         GetExtensionById(template_url->GetExtensionId(), false);
207     if (!extension ||
208         (profile_->IsOffTheRecord() &&
209         !extensions::util::IsIncognitoEnabled(extension->id(), profile_)))
210       return base::string16();
211   }
212
213   return keyword;
214 }
215
216 AutocompleteMatch KeywordProvider::CreateVerbatimMatch(
217     const base::string16& text,
218     const base::string16& keyword,
219     const AutocompleteInput& input) {
220   // A verbatim match is allowed to be the default match.
221   return CreateAutocompleteMatch(
222       GetTemplateURLService()->GetTemplateURLForKeyword(keyword), input,
223       keyword.length(), SplitReplacementStringFromInput(text, true), true, 0);
224 }
225
226 void KeywordProvider::Start(const AutocompleteInput& input,
227                             bool minimal_changes) {
228   // This object ensures we end keyword mode if we exit the function without
229   // toggling keyword mode to on.
230   ScopedEndExtensionKeywordMode keyword_mode_toggle(this);
231
232   matches_.clear();
233
234   if (!minimal_changes) {
235     done_ = true;
236
237     // Input has changed. Increment the input ID so that we can discard any
238     // stale extension suggestions that may be incoming.
239     current_input_id_ = ++global_input_uid_;
240   }
241
242   // Split user input into a keyword and some query input.
243   //
244   // We want to suggest keywords even when users have started typing URLs, on
245   // the assumption that they might not realize they no longer need to go to a
246   // site to be able to search it.  So we call CleanUserInputKeyword() to strip
247   // any initial scheme and/or "www.".  NOTE: Any heuristics or UI used to
248   // automatically/manually create keywords will need to be in sync with
249   // whatever we do here!
250   //
251   // TODO(pkasting): http://crbug/347744 If someday we remember usage frequency
252   // for keywords, we might suggest keywords that haven't even been partially
253   // typed, if the user uses them enough and isn't obviously typing something
254   // else.  In this case we'd consider all input here to be query input.
255   base::string16 keyword, remaining_input;
256   if (!ExtractKeywordFromInput(input, &keyword, &remaining_input))
257     return;
258
259   // Get the best matches for this keyword.
260   //
261   // NOTE: We could cache the previous keywords and reuse them here in the
262   // |minimal_changes| case, but since we'd still have to recalculate their
263   // relevances and we can just recreate the results synchronously anyway, we
264   // don't bother.
265   TemplateURLService::TemplateURLVector matches;
266   GetTemplateURLService()->FindMatchingKeywords(
267       keyword, !remaining_input.empty(), &matches);
268
269   for (TemplateURLService::TemplateURLVector::iterator i(matches.begin());
270        i != matches.end(); ) {
271     const TemplateURL* template_url = *i;
272
273     // Prune any extension keywords that are disallowed in incognito mode (if
274     // we're incognito), or disabled.
275     if (profile_ &&
276         (template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION)) {
277       ExtensionService* service = extensions::ExtensionSystem::Get(profile_)->
278           extension_service();
279       const extensions::Extension* extension =
280           service->GetExtensionById(template_url->GetExtensionId(), false);
281       bool enabled =
282           extension && (!profile_->IsOffTheRecord() ||
283                         extensions::util::IsIncognitoEnabled(
284                             extension->id(), profile_));
285       if (!enabled) {
286         i = matches.erase(i);
287         continue;
288       }
289     }
290
291     // Prune any substituting keywords if there is no substitution.
292     if (template_url->SupportsReplacement() && remaining_input.empty() &&
293         !input.allow_exact_keyword_match()) {
294       i = matches.erase(i);
295       continue;
296     }
297
298     ++i;
299   }
300   if (matches.empty())
301     return;
302   std::sort(matches.begin(), matches.end(), CompareQuality());
303
304   // Limit to one exact or three inexact matches, and mark them up for display
305   // in the autocomplete popup.
306   // Any exact match is going to be the highest quality match, and thus at the
307   // front of our vector.
308   if (matches.front()->keyword() == keyword) {
309     const TemplateURL* template_url = matches.front();
310     const bool is_extension_keyword =
311         template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
312
313     // Only create an exact match if |remaining_input| is empty or if
314     // this is an extension keyword.  If |remaining_input| is a
315     // non-empty non-extension keyword (i.e., a regular keyword that
316     // supports replacement and that has extra text following it),
317     // then SearchProvider creates the exact (a.k.a. verbatim) match.
318     if (!remaining_input.empty() && !is_extension_keyword)
319       return;
320
321     // TODO(pkasting): We should probably check that if the user explicitly
322     // typed a scheme, that scheme matches the one in |template_url|.
323
324     // When creating an exact match (either for the keyword itself, no
325     // remaining query or an extension keyword, possibly with remaining
326     // input), allow the match to be the default match.
327     matches_.push_back(CreateAutocompleteMatch(
328         template_url, input, keyword.length(), remaining_input, true, -1));
329
330     if (profile_ && is_extension_keyword) {
331       if (input.want_asynchronous_matches()) {
332         if (template_url->GetExtensionId() != current_keyword_extension_id_)
333           MaybeEndExtensionKeywordMode();
334         if (current_keyword_extension_id_.empty())
335           EnterExtensionKeywordMode(template_url->GetExtensionId());
336         keyword_mode_toggle.StayInKeywordMode();
337       }
338
339       extensions::ApplyDefaultSuggestionForExtensionKeyword(
340           profile_, template_url,
341           remaining_input,
342           &matches_[0]);
343
344       if (minimal_changes) {
345         // If the input hasn't significantly changed, we can just use the
346         // suggestions from last time. We need to readjust the relevance to
347         // ensure it is less than the main match's relevance.
348         for (size_t i = 0; i < extension_suggest_matches_.size(); ++i) {
349           matches_.push_back(extension_suggest_matches_[i]);
350           matches_.back().relevance = matches_[0].relevance - (i + 1);
351         }
352       } else if (input.want_asynchronous_matches()) {
353         extension_suggest_last_input_ = input;
354         extension_suggest_matches_.clear();
355
356         bool have_listeners =
357           extensions::ExtensionOmniboxEventRouter::OnInputChanged(
358               profile_, template_url->GetExtensionId(),
359               base::UTF16ToUTF8(remaining_input), current_input_id_);
360
361         // We only have to wait for suggest results if there are actually
362         // extensions listening for input changes.
363         if (have_listeners)
364           done_ = false;
365       }
366     }
367   } else {
368     if (matches.size() > kMaxMatches)
369       matches.erase(matches.begin() + kMaxMatches, matches.end());
370     for (TemplateURLService::TemplateURLVector::const_iterator i(
371          matches.begin()); i != matches.end(); ++i) {
372       matches_.push_back(CreateAutocompleteMatch(
373           *i, input, keyword.length(), remaining_input, false, -1));
374     }
375   }
376 }
377
378 void KeywordProvider::Stop(bool clear_cached_results) {
379   done_ = true;
380   MaybeEndExtensionKeywordMode();
381 }
382
383 KeywordProvider::~KeywordProvider() {}
384
385 // static
386 bool KeywordProvider::ExtractKeywordFromInput(const AutocompleteInput& input,
387                                               base::string16* keyword,
388                                               base::string16* remaining_input) {
389   if ((input.type() == AutocompleteInput::INVALID) ||
390       (input.type() == AutocompleteInput::FORCED_QUERY))
391     return false;
392
393   *keyword = TemplateURLService::CleanUserInputKeyword(
394       SplitKeywordFromInput(input.text(), true, remaining_input));
395   return !keyword->empty();
396 }
397
398 // static
399 int KeywordProvider::CalculateRelevance(AutocompleteInput::Type type,
400                                         bool complete,
401                                         bool supports_replacement,
402                                         bool prefer_keyword,
403                                         bool allow_exact_keyword_match) {
404   // This function is responsible for scoring suggestions of keywords
405   // themselves and the suggestion of the verbatim query on an
406   // extension keyword.  SearchProvider::CalculateRelevanceForKeywordVerbatim()
407   // scores verbatim query suggestions for non-extension keywords.
408   // These two functions are currently in sync, but there's no reason
409   // we couldn't decide in the future to score verbatim matches
410   // differently for extension and non-extension keywords.  If you
411   // make such a change, however, you should update this comment to
412   // describe it, so it's clear why the functions diverge.
413   if (!complete)
414     return (type == AutocompleteInput::URL) ? 700 : 450;
415   if (!supports_replacement || (allow_exact_keyword_match && prefer_keyword))
416     return 1500;
417   return (allow_exact_keyword_match && (type == AutocompleteInput::QUERY)) ?
418       1450 : 1100;
419 }
420
421 AutocompleteMatch KeywordProvider::CreateAutocompleteMatch(
422     const TemplateURL* template_url,
423     const AutocompleteInput& input,
424     size_t prefix_length,
425     const base::string16& remaining_input,
426     bool allowed_to_be_default_match,
427     int relevance) {
428   DCHECK(template_url);
429   const bool supports_replacement =
430       template_url->url_ref().SupportsReplacement();
431
432   // Create an edit entry of "[keyword] [remaining input]".  This is helpful
433   // even when [remaining input] is empty, as the user can select the popup
434   // choice and immediately begin typing in query input.
435   const base::string16& keyword = template_url->keyword();
436   const bool keyword_complete = (prefix_length == keyword.length());
437   if (relevance < 0) {
438     relevance =
439         CalculateRelevance(input.type(), keyword_complete,
440                            // When the user wants keyword matches to take
441                            // preference, score them highly regardless of
442                            // whether the input provides query text.
443                            supports_replacement, input.prefer_keyword(),
444                            input.allow_exact_keyword_match());
445   }
446   AutocompleteMatch match(this, relevance, false,
447       supports_replacement ? AutocompleteMatchType::SEARCH_OTHER_ENGINE :
448                              AutocompleteMatchType::HISTORY_KEYWORD);
449   match.allowed_to_be_default_match = allowed_to_be_default_match;
450   match.fill_into_edit = keyword;
451   if (!remaining_input.empty() || supports_replacement)
452     match.fill_into_edit.push_back(L' ');
453   match.fill_into_edit.append(remaining_input);
454   // If we wanted to set |result.inline_autocompletion| correctly, we'd need
455   // CleanUserInputKeyword() to return the amount of adjustment it's made to
456   // the user's input.  Because right now inexact keyword matches can't score
457   // more highly than a "what you typed" match from one of the other providers,
458   // we just don't bother to do this, and leave inline autocompletion off.
459
460   // Create destination URL and popup entry content by substituting user input
461   // into keyword templates.
462   FillInURLAndContents(remaining_input, template_url, &match);
463
464   match.keyword = keyword;
465   match.transition = content::PAGE_TRANSITION_KEYWORD;
466
467   return match;
468 }
469
470 void KeywordProvider::FillInURLAndContents(
471     const base::string16& remaining_input,
472     const TemplateURL* element,
473     AutocompleteMatch* match) const {
474   DCHECK(!element->short_name().empty());
475   const TemplateURLRef& element_ref = element->url_ref();
476   DCHECK(element_ref.IsValid());
477   int message_id = (element->GetType() == TemplateURL::OMNIBOX_API_EXTENSION) ?
478       IDS_EXTENSION_KEYWORD_COMMAND : IDS_KEYWORD_SEARCH;
479   if (remaining_input.empty()) {
480     // Allow extension keyword providers to accept empty string input. This is
481     // useful to allow extensions to do something in the case where no input is
482     // entered.
483     if (element_ref.SupportsReplacement() &&
484         (element->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
485       // No query input; return a generic, no-destination placeholder.
486       match->contents.assign(
487           l10n_util::GetStringFUTF16(message_id,
488               element->AdjustedShortNameForLocaleDirection(),
489               l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE)));
490       match->contents_class.push_back(
491           ACMatchClassification(0, ACMatchClassification::DIM));
492     } else {
493       // Keyword that has no replacement text (aka a shorthand for a URL).
494       match->destination_url = GURL(element->url());
495       match->contents.assign(element->short_name());
496       AutocompleteMatch::ClassifyLocationInString(0, match->contents.length(),
497           match->contents.length(), ACMatchClassification::NONE,
498           &match->contents_class);
499     }
500   } else {
501     // Create destination URL by escaping user input and substituting into
502     // keyword template URL.  The escaping here handles whitespace in user
503     // input, but we rely on later canonicalization functions to do more
504     // fixup to make the URL valid if necessary.
505     DCHECK(element_ref.SupportsReplacement());
506     TemplateURLRef::SearchTermsArgs search_terms_args(remaining_input);
507     search_terms_args.append_extra_query_params =
508         element == GetTemplateURLService()->GetDefaultSearchProvider();
509     match->destination_url =
510         GURL(element_ref.ReplaceSearchTerms(search_terms_args));
511     std::vector<size_t> content_param_offsets;
512     match->contents.assign(l10n_util::GetStringFUTF16(message_id,
513                                                       element->short_name(),
514                                                       remaining_input,
515                                                       &content_param_offsets));
516     DCHECK_EQ(2U, content_param_offsets.size());
517     AutocompleteMatch::ClassifyLocationInString(content_param_offsets[1],
518         remaining_input.length(), match->contents.length(),
519         ACMatchClassification::NONE, &match->contents_class);
520   }
521 }
522
523 void KeywordProvider::Observe(int type,
524                               const content::NotificationSource& source,
525                               const content::NotificationDetails& details) {
526   TemplateURLService* model = GetTemplateURLService();
527   const AutocompleteInput& input = extension_suggest_last_input_;
528
529   switch (type) {
530     case chrome::NOTIFICATION_EXTENSION_OMNIBOX_INPUT_ENTERED:
531       // Input has been accepted, so we're done with this input session. Ensure
532       // we don't send the OnInputCancelled event, or handle any more stray
533       // suggestions_ready events.
534       current_keyword_extension_id_.clear();
535       current_input_id_ = 0;
536       return;
537
538     case chrome::NOTIFICATION_EXTENSION_OMNIBOX_DEFAULT_SUGGESTION_CHANGED: {
539       // It's possible to change the default suggestion while not in an editing
540       // session.
541       base::string16 keyword, remaining_input;
542       if (matches_.empty() || current_keyword_extension_id_.empty() ||
543           !ExtractKeywordFromInput(input, &keyword, &remaining_input))
544         return;
545
546       const TemplateURL* template_url(
547           model->GetTemplateURLForKeyword(keyword));
548       extensions::ApplyDefaultSuggestionForExtensionKeyword(
549           profile_, template_url,
550           remaining_input,
551           &matches_[0]);
552       listener_->OnProviderUpdate(true);
553       return;
554     }
555
556     case chrome::NOTIFICATION_EXTENSION_OMNIBOX_SUGGESTIONS_READY: {
557       const omnibox_api::SendSuggestions::Params& suggestions =
558           *content::Details<
559               omnibox_api::SendSuggestions::Params>(details).ptr();
560       if (suggestions.request_id != current_input_id_)
561         return;  // This is an old result. Just ignore.
562
563       base::string16 keyword, remaining_input;
564       bool result = ExtractKeywordFromInput(input, &keyword, &remaining_input);
565       DCHECK(result);
566       const TemplateURL* template_url =
567           model->GetTemplateURLForKeyword(keyword);
568
569       // TODO(mpcomplete): consider clamping the number of suggestions to
570       // AutocompleteProvider::kMaxMatches.
571       for (size_t i = 0; i < suggestions.suggest_results.size(); ++i) {
572         const omnibox_api::SuggestResult& suggestion =
573             *suggestions.suggest_results[i];
574         // We want to order these suggestions in descending order, so start with
575         // the relevance of the first result (added synchronously in Start()),
576         // and subtract 1 for each subsequent suggestion from the extension.
577         // We recompute the first match's relevance; we know that |complete|
578         // is true, because we wouldn't get results from the extension unless
579         // the full keyword had been typed.
580         int first_relevance = CalculateRelevance(input.type(), true, true,
581             input.prefer_keyword(), input.allow_exact_keyword_match());
582         // Because these matches are async, we should never let them become the
583         // default match, lest we introduce race conditions in the omnibox user
584         // interaction.
585         extension_suggest_matches_.push_back(CreateAutocompleteMatch(
586             template_url, input, keyword.length(),
587             base::UTF8ToUTF16(suggestion.content), false,
588             first_relevance - (i + 1)));
589
590         AutocompleteMatch* match = &extension_suggest_matches_.back();
591         match->contents.assign(base::UTF8ToUTF16(suggestion.description));
592         match->contents_class =
593             extensions::StyleTypesToACMatchClassifications(suggestion);
594       }
595
596       done_ = true;
597       matches_.insert(matches_.end(), extension_suggest_matches_.begin(),
598                       extension_suggest_matches_.end());
599       listener_->OnProviderUpdate(!extension_suggest_matches_.empty());
600       return;
601     }
602
603     default:
604       NOTREACHED();
605       return;
606   }
607 }
608
609 TemplateURLService* KeywordProvider::GetTemplateURLService() const {
610   TemplateURLService* service = profile_ ?
611       TemplateURLServiceFactory::GetForProfile(profile_) : model_;
612   // Make sure the model is loaded. This is cheap and quickly bails out if
613   // the model is already loaded.
614   DCHECK(service);
615   service->Load();
616   return service;
617 }
618
619 void KeywordProvider::EnterExtensionKeywordMode(
620     const std::string& extension_id) {
621   DCHECK(current_keyword_extension_id_.empty());
622   current_keyword_extension_id_ = extension_id;
623
624   extensions::ExtensionOmniboxEventRouter::OnInputStarted(
625       profile_, current_keyword_extension_id_);
626 }
627
628 void KeywordProvider::MaybeEndExtensionKeywordMode() {
629   if (!current_keyword_extension_id_.empty()) {
630     extensions::ExtensionOmniboxEventRouter::OnInputCancelled(
631         profile_, current_keyword_extension_id_);
632
633     current_keyword_extension_id_.clear();
634   }
635 }