• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/autocomplete_controller.h"
6 
7 #include <set>
8 #include <string>
9 
10 #include "base/format_macros.h"
11 #include "base/logging.h"
12 #include "base/metrics/histogram.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/time/time.h"
16 #include "chrome/browser/autocomplete/autocomplete_controller_delegate.h"
17 #include "chrome/browser/autocomplete/bookmark_provider.h"
18 #include "chrome/browser/autocomplete/builtin_provider.h"
19 #include "chrome/browser/autocomplete/extension_app_provider.h"
20 #include "chrome/browser/autocomplete/history_quick_provider.h"
21 #include "chrome/browser/autocomplete/history_url_provider.h"
22 #include "chrome/browser/autocomplete/keyword_provider.h"
23 #include "chrome/browser/autocomplete/search_provider.h"
24 #include "chrome/browser/autocomplete/shortcuts_provider.h"
25 #include "chrome/browser/autocomplete/zero_suggest_provider.h"
26 #include "chrome/browser/chrome_notification_types.h"
27 #include "chrome/browser/omnibox/omnibox_field_trial.h"
28 #include "chrome/browser/profiles/profile.h"
29 #include "chrome/browser/search/search.h"
30 #include "chrome/browser/search_engines/template_url.h"
31 #include "chrome/browser/search_engines/ui_thread_search_terms_data.h"
32 #include "content/public/browser/notification_service.h"
33 #include "grit/generated_resources.h"
34 #include "grit/theme_resources.h"
35 #include "ui/base/l10n/l10n_util.h"
36 
37 namespace {
38 
39 // Converts the given match to a type (and possibly subtype) based on the AQS
40 // specification. For more details, see
41 // http://goto.google.com/binary-clients-logging.
AutocompleteMatchToAssistedQuery(const AutocompleteMatch::Type & match,const AutocompleteProvider * provider,size_t * type,size_t * subtype)42 void AutocompleteMatchToAssistedQuery(
43     const AutocompleteMatch::Type& match,
44     const AutocompleteProvider* provider,
45     size_t* type,
46     size_t* subtype) {
47   // This type indicates a native chrome suggestion.
48   *type = 69;
49   // Default value, indicating no subtype.
50   *subtype = base::string16::npos;
51 
52   // If provider is TYPE_ZERO_SUGGEST, set the subtype accordingly.
53   // Type will be set in the switch statement below where we'll enter one of
54   // SEARCH_SUGGEST or NAVSUGGEST.
55   if (provider &&
56       (provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST)) {
57     DCHECK((match == AutocompleteMatchType::SEARCH_SUGGEST) ||
58            (match == AutocompleteMatchType::NAVSUGGEST));
59     *subtype = 66;
60   }
61 
62   switch (match) {
63     case AutocompleteMatchType::SEARCH_SUGGEST: {
64       // Do not set subtype here; subtype may have been set above.
65       *type = 0;
66       return;
67     }
68     case AutocompleteMatchType::SEARCH_SUGGEST_ENTITY: {
69       *subtype = 46;
70       return;
71     }
72     case AutocompleteMatchType::SEARCH_SUGGEST_INFINITE: {
73       *subtype = 33;
74       return;
75     }
76     case AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED: {
77       *subtype = 35;
78       return;
79     }
80     case AutocompleteMatchType::SEARCH_SUGGEST_PROFILE: {
81       *subtype = 44;
82       return;
83     }
84     case AutocompleteMatchType::SEARCH_SUGGEST_ANSWER: {
85       *subtype = 70;
86       return;
87     }
88     case AutocompleteMatchType::NAVSUGGEST: {
89       // Do not set subtype here; subtype may have been set above.
90       *type = 5;
91       return;
92     }
93     case AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED: {
94       *subtype = 57;
95       return;
96     }
97     case AutocompleteMatchType::URL_WHAT_YOU_TYPED: {
98       *subtype = 58;
99       return;
100     }
101     case AutocompleteMatchType::SEARCH_HISTORY: {
102       *subtype = 59;
103       return;
104     }
105     case AutocompleteMatchType::HISTORY_URL: {
106       *subtype = 60;
107       return;
108     }
109     case AutocompleteMatchType::HISTORY_TITLE: {
110       *subtype = 61;
111       return;
112     }
113     case AutocompleteMatchType::HISTORY_BODY: {
114       *subtype = 62;
115       return;
116     }
117     case AutocompleteMatchType::HISTORY_KEYWORD: {
118       *subtype = 63;
119       return;
120     }
121     case AutocompleteMatchType::BOOKMARK_TITLE: {
122       *subtype = 65;
123       return;
124     }
125     case AutocompleteMatchType::NAVSUGGEST_PERSONALIZED: {
126       *subtype = 39;
127       return;
128     }
129     default: {
130       // This value indicates a native chrome suggestion with no named subtype
131       // (yet).
132       *subtype = 64;
133     }
134   }
135 }
136 
137 // Appends available autocompletion of the given type, subtype, and number to
138 // the existing available autocompletions string, encoding according to the
139 // spec.
AppendAvailableAutocompletion(size_t type,size_t subtype,int count,std::string * autocompletions)140 void AppendAvailableAutocompletion(size_t type,
141                                    size_t subtype,
142                                    int count,
143                                    std::string* autocompletions) {
144   if (!autocompletions->empty())
145     autocompletions->append("j");
146   base::StringAppendF(autocompletions, "%" PRIuS, type);
147   // Subtype is optional - base::string16::npos indicates no subtype.
148   if (subtype != base::string16::npos)
149     base::StringAppendF(autocompletions, "i%" PRIuS, subtype);
150   if (count > 1)
151     base::StringAppendF(autocompletions, "l%d", count);
152 }
153 
154 // Returns whether the autocompletion is trivial enough that we consider it
155 // an autocompletion for which the omnibox autocompletion code did not add
156 // any value.
IsTrivialAutocompletion(const AutocompleteMatch & match)157 bool IsTrivialAutocompletion(const AutocompleteMatch& match) {
158   return match.type == AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED ||
159       match.type == AutocompleteMatchType::URL_WHAT_YOU_TYPED ||
160       match.type == AutocompleteMatchType::SEARCH_OTHER_ENGINE;
161 }
162 
163 // Whether this autocomplete match type supports custom descriptions.
AutocompleteMatchHasCustomDescription(const AutocompleteMatch & match)164 bool AutocompleteMatchHasCustomDescription(const AutocompleteMatch& match) {
165   return match.type == AutocompleteMatchType::SEARCH_SUGGEST_ENTITY ||
166       match.type == AutocompleteMatchType::SEARCH_SUGGEST_PROFILE;
167 }
168 
169 }  // namespace
170 
AutocompleteController(Profile * profile,AutocompleteControllerDelegate * delegate,int provider_types)171 AutocompleteController::AutocompleteController(
172     Profile* profile,
173     AutocompleteControllerDelegate* delegate,
174     int provider_types)
175     : delegate_(delegate),
176       history_url_provider_(NULL),
177       keyword_provider_(NULL),
178       search_provider_(NULL),
179       zero_suggest_provider_(NULL),
180       stop_timer_duration_(OmniboxFieldTrial::StopTimerFieldTrialDuration()),
181       done_(true),
182       in_start_(false),
183       profile_(profile) {
184   provider_types &= ~OmniboxFieldTrial::GetDisabledProviderTypes();
185   if (provider_types & AutocompleteProvider::TYPE_BOOKMARK)
186     providers_.push_back(new BookmarkProvider(this, profile));
187   if (provider_types & AutocompleteProvider::TYPE_BUILTIN)
188     providers_.push_back(new BuiltinProvider(this, profile));
189   if (provider_types & AutocompleteProvider::TYPE_EXTENSION_APP)
190     providers_.push_back(new ExtensionAppProvider(this, profile));
191   if (provider_types & AutocompleteProvider::TYPE_HISTORY_QUICK)
192     providers_.push_back(new HistoryQuickProvider(this, profile));
193   if (provider_types & AutocompleteProvider::TYPE_HISTORY_URL) {
194     history_url_provider_ = new HistoryURLProvider(this, profile);
195     providers_.push_back(history_url_provider_);
196   }
197   // "Tab to search" can be used on all platforms other than Android.
198 #if !defined(OS_ANDROID)
199   if (provider_types & AutocompleteProvider::TYPE_KEYWORD) {
200     keyword_provider_ = new KeywordProvider(this, profile);
201     providers_.push_back(keyword_provider_);
202   }
203 #endif
204   if (provider_types & AutocompleteProvider::TYPE_SEARCH) {
205     search_provider_ = new SearchProvider(this, profile);
206     providers_.push_back(search_provider_);
207   }
208   if (provider_types & AutocompleteProvider::TYPE_SHORTCUTS)
209     providers_.push_back(new ShortcutsProvider(this, profile));
210   if (provider_types & AutocompleteProvider::TYPE_ZERO_SUGGEST) {
211     zero_suggest_provider_ = ZeroSuggestProvider::Create(this, profile);
212     if (zero_suggest_provider_)
213       providers_.push_back(zero_suggest_provider_);
214   }
215 
216   for (ACProviders::iterator i(providers_.begin()); i != providers_.end(); ++i)
217     (*i)->AddRef();
218 }
219 
~AutocompleteController()220 AutocompleteController::~AutocompleteController() {
221   // The providers may have tasks outstanding that hold refs to them.  We need
222   // to ensure they won't call us back if they outlive us.  (Practically,
223   // calling Stop() should also cancel those tasks and make it so that we hold
224   // the only refs.)  We also don't want to bother notifying anyone of our
225   // result changes here, because the notification observer is in the midst of
226   // shutdown too, so we don't ask Stop() to clear |result_| (and notify).
227   result_.Reset();  // Not really necessary.
228   Stop(false);
229 
230   for (ACProviders::iterator i(providers_.begin()); i != providers_.end(); ++i)
231     (*i)->Release();
232 
233   providers_.clear();  // Not really necessary.
234 }
235 
Start(const AutocompleteInput & input)236 void AutocompleteController::Start(const AutocompleteInput& input) {
237   const base::string16 old_input_text(input_.text());
238   const bool old_want_asynchronous_matches = input_.want_asynchronous_matches();
239   input_ = input;
240 
241   // See if we can avoid rerunning autocomplete when the query hasn't changed
242   // much.  When the user presses or releases the ctrl key, the desired_tld
243   // changes, and when the user finishes an IME composition, inline autocomplete
244   // may no longer be prevented.  In both these cases the text itself hasn't
245   // changed since the last query, and some providers can do much less work (and
246   // get matches back more quickly).  Taking advantage of this reduces flicker.
247   //
248   // NOTE: This comes after constructing |input_| above since that construction
249   // can change the text string (e.g. by stripping off a leading '?').
250   const bool minimal_changes = (input_.text() == old_input_text) &&
251       (input_.want_asynchronous_matches() == old_want_asynchronous_matches);
252 
253   expire_timer_.Stop();
254   stop_timer_.Stop();
255 
256   // Start the new query.
257   in_start_ = true;
258   base::TimeTicks start_time = base::TimeTicks::Now();
259   for (ACProviders::iterator i(providers_.begin()); i != providers_.end();
260        ++i) {
261     // TODO(mpearson): Remove timing code once bugs 178705 / 237703 / 168933
262     // are resolved.
263     base::TimeTicks provider_start_time = base::TimeTicks::Now();
264 
265     // Call Start() on ZeroSuggestProvider with an INVALID AutocompleteInput
266     // to clear out zero-suggest |matches_|.
267     if (*i == zero_suggest_provider_)
268       (*i)->Start(AutocompleteInput(), minimal_changes);
269     else
270       (*i)->Start(input_, minimal_changes);
271 
272     if (!input.want_asynchronous_matches())
273       DCHECK((*i)->done());
274     base::TimeTicks provider_end_time = base::TimeTicks::Now();
275     std::string name = std::string("Omnibox.ProviderTime.") + (*i)->GetName();
276     base::HistogramBase* counter = base::Histogram::FactoryGet(
277         name, 1, 5000, 20, base::Histogram::kUmaTargetedHistogramFlag);
278     counter->Add(static_cast<int>(
279         (provider_end_time - provider_start_time).InMilliseconds()));
280   }
281   if (input.want_asynchronous_matches() && (input.text().length() < 6)) {
282     base::TimeTicks end_time = base::TimeTicks::Now();
283     std::string name = "Omnibox.QueryTime." + base::IntToString(
284         input.text().length());
285     base::HistogramBase* counter = base::Histogram::FactoryGet(
286         name, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag);
287     counter->Add(static_cast<int>((end_time - start_time).InMilliseconds()));
288   }
289   in_start_ = false;
290   CheckIfDone();
291   // The second true forces saying the default match has changed.
292   // This triggers the edit model to update things such as the inline
293   // autocomplete state.  In particular, if the user has typed a key
294   // since the last notification, and we're now re-running
295   // autocomplete, then we need to update the inline autocompletion
296   // even if the current match is for the same URL as the last run's
297   // default match.  Likewise, the controller doesn't know what's
298   // happened in the edit since the last time it ran autocomplete.
299   // The user might have selected all the text and hit delete, then
300   // typed a new character.  The selection and delete won't send any
301   // signals to the controller so it doesn't realize that anything was
302   // cleared or changed.  Even if the default match hasn't changed, we
303   // need the edit model to update the display.
304   UpdateResult(false, true);
305 
306   if (!done_) {
307     StartExpireTimer();
308     StartStopTimer();
309   }
310 }
311 
Stop(bool clear_result)312 void AutocompleteController::Stop(bool clear_result) {
313   for (ACProviders::const_iterator i(providers_.begin()); i != providers_.end();
314        ++i) {
315     (*i)->Stop(clear_result);
316   }
317 
318   expire_timer_.Stop();
319   stop_timer_.Stop();
320   done_ = true;
321   if (clear_result && !result_.empty()) {
322     result_.Reset();
323     // NOTE: We pass in false since we're trying to only clear the popup, not
324     // touch the edit... this is all a mess and should be cleaned up :(
325     NotifyChanged(false);
326   }
327 }
328 
StartZeroSuggest(const AutocompleteInput & input)329 void AutocompleteController::StartZeroSuggest(const AutocompleteInput& input) {
330   if (zero_suggest_provider_ == NULL)
331     return;
332 
333   DCHECK(!in_start_);  // We should not be already running a query.
334 
335   // Call Start() on all prefix-based providers with an INVALID
336   // AutocompleteInput to clear out cached |matches_|, which ensures that
337   // they aren't used with zero suggest.
338   for (ACProviders::iterator i(providers_.begin()); i != providers_.end();
339       ++i) {
340     if (*i == zero_suggest_provider_)
341       (*i)->Start(input, false);
342     else
343       (*i)->Start(AutocompleteInput(), false);
344   }
345 
346   if (!zero_suggest_provider_->matches().empty())
347     UpdateResult(false, false);
348 }
349 
DeleteMatch(const AutocompleteMatch & match)350 void AutocompleteController::DeleteMatch(const AutocompleteMatch& match) {
351   DCHECK(match.SupportsDeletion());
352 
353   // Delete duplicate matches attached to the main match first.
354   for (ACMatches::const_iterator it(match.duplicate_matches.begin());
355        it != match.duplicate_matches.end(); ++it) {
356     if (it->deletable)
357       it->provider->DeleteMatch(*it);
358   }
359 
360   if (match.deletable)
361     match.provider->DeleteMatch(match);
362 
363   OnProviderUpdate(true);
364 
365   // If we're not done, we might attempt to redisplay the deleted match. Make
366   // sure we aren't displaying it by removing any old entries.
367   ExpireCopiedEntries();
368 }
369 
ExpireCopiedEntries()370 void AutocompleteController::ExpireCopiedEntries() {
371   // The first true makes UpdateResult() clear out the results and
372   // regenerate them, thus ensuring that no results from the previous
373   // result set remain.
374   UpdateResult(true, false);
375 }
376 
OnProviderUpdate(bool updated_matches)377 void AutocompleteController::OnProviderUpdate(bool updated_matches) {
378   CheckIfDone();
379   // Multiple providers may provide synchronous results, so we only update the
380   // results if we're not in Start().
381   if (!in_start_ && (updated_matches || done_))
382     UpdateResult(false, false);
383 }
384 
AddProvidersInfo(ProvidersInfo * provider_info) const385 void AutocompleteController::AddProvidersInfo(
386     ProvidersInfo* provider_info) const {
387   provider_info->clear();
388   for (ACProviders::const_iterator i(providers_.begin()); i != providers_.end();
389        ++i) {
390     // Add per-provider info, if any.
391     (*i)->AddProviderInfo(provider_info);
392 
393     // This is also a good place to put code to add info that you want to
394     // add for every provider.
395   }
396 }
397 
ResetSession()398 void AutocompleteController::ResetSession() {
399   for (ACProviders::const_iterator i(providers_.begin()); i != providers_.end();
400        ++i)
401     (*i)->ResetSession();
402 }
403 
UpdateMatchDestinationURL(base::TimeDelta query_formulation_time,AutocompleteMatch * match) const404 void AutocompleteController::UpdateMatchDestinationURL(
405     base::TimeDelta query_formulation_time,
406     AutocompleteMatch* match) const {
407   TemplateURL* template_url = match->GetTemplateURL(profile_, false);
408   if (!template_url || !match->search_terms_args.get() ||
409       match->search_terms_args->assisted_query_stats.empty())
410     return;
411 
412   // Append the query formulation time (time from when the user first typed a
413   // character into the omnibox to when the user selected a query) and whether
414   // a field trial has triggered to the AQS parameter.
415   TemplateURLRef::SearchTermsArgs search_terms_args(*match->search_terms_args);
416   search_terms_args.assisted_query_stats += base::StringPrintf(
417       ".%" PRId64 "j%dj%d",
418       query_formulation_time.InMilliseconds(),
419       (search_provider_ &&
420        search_provider_->field_trial_triggered_in_session()) ||
421       (zero_suggest_provider_ &&
422        zero_suggest_provider_->field_trial_triggered_in_session()),
423       input_.current_page_classification());
424   match->destination_url = GURL(template_url->url_ref().ReplaceSearchTerms(
425       search_terms_args, UIThreadSearchTermsData(profile_)));
426 }
427 
UpdateResult(bool regenerate_result,bool force_notify_default_match_changed)428 void AutocompleteController::UpdateResult(
429     bool regenerate_result,
430     bool force_notify_default_match_changed) {
431   const bool last_default_was_valid = result_.default_match() != result_.end();
432   // The following three variables are only set and used if
433   // |last_default_was_valid|.
434   base::string16 last_default_fill_into_edit, last_default_keyword,
435       last_default_associated_keyword;
436   if (last_default_was_valid) {
437     last_default_fill_into_edit = result_.default_match()->fill_into_edit;
438     last_default_keyword = result_.default_match()->keyword;
439     if (result_.default_match()->associated_keyword != NULL)
440       last_default_associated_keyword =
441           result_.default_match()->associated_keyword->keyword;
442   }
443 
444   if (regenerate_result)
445     result_.Reset();
446 
447   AutocompleteResult last_result;
448   last_result.Swap(&result_);
449 
450   for (ACProviders::const_iterator i(providers_.begin());
451        i != providers_.end(); ++i)
452     result_.AppendMatches((*i)->matches());
453 
454   // Sort the matches and trim to a small number of "best" matches.
455   result_.SortAndCull(input_, profile_);
456 
457   // Need to validate before invoking CopyOldMatches as the old matches are not
458   // valid against the current input.
459 #ifndef NDEBUG
460   result_.Validate();
461 #endif
462 
463   if (!done_) {
464     // This conditional needs to match the conditional in Start that invokes
465     // StartExpireTimer.
466     result_.CopyOldMatches(input_, last_result, profile_);
467   }
468 
469   UpdateKeywordDescriptions(&result_);
470   UpdateAssociatedKeywords(&result_);
471   UpdateAssistedQueryStats(&result_);
472 
473   const bool default_is_valid = result_.default_match() != result_.end();
474   base::string16 default_associated_keyword;
475   if (default_is_valid &&
476       (result_.default_match()->associated_keyword != NULL)) {
477     default_associated_keyword =
478         result_.default_match()->associated_keyword->keyword;
479   }
480   // We've gotten async results. Send notification that the default match
481   // updated if fill_into_edit, associated_keyword, or keyword differ.  (The
482   // second can change if we've just started Chrome and the keyword database
483   // finishes loading while processing this request.  The third can change
484   // if we swapped from interpreting the input as a search--which gets
485   // labeled with the default search provider's keyword--to a URL.)
486   // We don't check the URL as that may change for the default match
487   // even though the fill into edit hasn't changed (see SearchProvider
488   // for one case of this).
489   const bool notify_default_match =
490       (last_default_was_valid != default_is_valid) ||
491       (last_default_was_valid &&
492        ((result_.default_match()->fill_into_edit !=
493           last_default_fill_into_edit) ||
494         (default_associated_keyword != last_default_associated_keyword) ||
495         (result_.default_match()->keyword != last_default_keyword)));
496   if (notify_default_match)
497     last_time_default_match_changed_ = base::TimeTicks::Now();
498 
499   NotifyChanged(force_notify_default_match_changed || notify_default_match);
500 }
501 
UpdateAssociatedKeywords(AutocompleteResult * result)502 void AutocompleteController::UpdateAssociatedKeywords(
503     AutocompleteResult* result) {
504   if (!keyword_provider_)
505     return;
506 
507   std::set<base::string16> keywords;
508   for (ACMatches::iterator match(result->begin()); match != result->end();
509        ++match) {
510     base::string16 keyword(
511         match->GetSubstitutingExplicitlyInvokedKeyword(profile_));
512     if (!keyword.empty()) {
513       keywords.insert(keyword);
514       continue;
515     }
516 
517     // Only add the keyword if the match does not have a duplicate keyword with
518     // a more relevant match.
519     keyword = match->associated_keyword.get() ?
520         match->associated_keyword->keyword :
521         keyword_provider_->GetKeywordForText(match->fill_into_edit);
522     if (!keyword.empty() && !keywords.count(keyword)) {
523       keywords.insert(keyword);
524 
525       if (!match->associated_keyword.get())
526         match->associated_keyword.reset(new AutocompleteMatch(
527             keyword_provider_->CreateVerbatimMatch(match->fill_into_edit,
528                                                    keyword, input_)));
529     } else {
530       match->associated_keyword.reset();
531     }
532   }
533 }
534 
UpdateKeywordDescriptions(AutocompleteResult * result)535 void AutocompleteController::UpdateKeywordDescriptions(
536     AutocompleteResult* result) {
537   base::string16 last_keyword;
538   for (AutocompleteResult::iterator i(result->begin()); i != result->end();
539        ++i) {
540     if (AutocompleteMatch::IsSearchType(i->type)) {
541       if (AutocompleteMatchHasCustomDescription(*i))
542         continue;
543       i->description.clear();
544       i->description_class.clear();
545       DCHECK(!i->keyword.empty());
546       if (i->keyword != last_keyword) {
547         const TemplateURL* template_url = i->GetTemplateURL(profile_, false);
548         if (template_url) {
549           // For extension keywords, just make the description the extension
550           // name -- don't assume that the normal search keyword description is
551           // applicable.
552           i->description = template_url->AdjustedShortNameForLocaleDirection();
553           if (template_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION) {
554             i->description = l10n_util::GetStringFUTF16(
555                 IDS_AUTOCOMPLETE_SEARCH_DESCRIPTION, i->description);
556           }
557           i->description_class.push_back(
558               ACMatchClassification(0, ACMatchClassification::DIM));
559         }
560         last_keyword = i->keyword;
561       }
562     } else {
563       last_keyword.clear();
564     }
565   }
566 }
567 
UpdateAssistedQueryStats(AutocompleteResult * result)568 void AutocompleteController::UpdateAssistedQueryStats(
569     AutocompleteResult* result) {
570   if (result->empty())
571     return;
572 
573   // Build the impressions string (the AQS part after ".").
574   std::string autocompletions;
575   int count = 0;
576   size_t last_type = base::string16::npos;
577   size_t last_subtype = base::string16::npos;
578   for (ACMatches::iterator match(result->begin()); match != result->end();
579        ++match) {
580     size_t type = base::string16::npos;
581     size_t subtype = base::string16::npos;
582     AutocompleteMatchToAssistedQuery(
583         match->type, match->provider, &type, &subtype);
584     if (last_type != base::string16::npos &&
585         (type != last_type || subtype != last_subtype)) {
586       AppendAvailableAutocompletion(
587           last_type, last_subtype, count, &autocompletions);
588       count = 1;
589     } else {
590       count++;
591     }
592     last_type = type;
593     last_subtype = subtype;
594   }
595   AppendAvailableAutocompletion(
596       last_type, last_subtype, count, &autocompletions);
597   // Go over all matches and set AQS if the match supports it.
598   for (size_t index = 0; index < result->size(); ++index) {
599     AutocompleteMatch* match = result->match_at(index);
600     const TemplateURL* template_url = match->GetTemplateURL(profile_, false);
601     if (!template_url || !match->search_terms_args.get())
602       continue;
603     std::string selected_index;
604     // Prevent trivial suggestions from getting credit for being selected.
605     if (!IsTrivialAutocompletion(*match))
606       selected_index = base::StringPrintf("%" PRIuS, index);
607     match->search_terms_args->assisted_query_stats =
608         base::StringPrintf("chrome.%s.%s",
609                            selected_index.c_str(),
610                            autocompletions.c_str());
611     match->destination_url = GURL(template_url->url_ref().ReplaceSearchTerms(
612         *match->search_terms_args, UIThreadSearchTermsData(profile_)));
613   }
614 }
615 
NotifyChanged(bool notify_default_match)616 void AutocompleteController::NotifyChanged(bool notify_default_match) {
617   if (delegate_)
618     delegate_->OnResultChanged(notify_default_match);
619   if (done_) {
620     content::NotificationService::current()->Notify(
621         chrome::NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY,
622         content::Source<AutocompleteController>(this),
623         content::NotificationService::NoDetails());
624   }
625 }
626 
CheckIfDone()627 void AutocompleteController::CheckIfDone() {
628   for (ACProviders::const_iterator i(providers_.begin()); i != providers_.end();
629        ++i) {
630     if (!(*i)->done()) {
631       done_ = false;
632       return;
633     }
634   }
635   done_ = true;
636 }
637 
StartExpireTimer()638 void AutocompleteController::StartExpireTimer() {
639   // Amount of time (in ms) between when the user stops typing and
640   // when we remove any copied entries. We do this from the time the
641   // user stopped typing as some providers (such as SearchProvider)
642   // wait for the user to stop typing before they initiate a query.
643   const int kExpireTimeMS = 500;
644 
645   if (result_.HasCopiedMatches())
646     expire_timer_.Start(FROM_HERE,
647                         base::TimeDelta::FromMilliseconds(kExpireTimeMS),
648                         this, &AutocompleteController::ExpireCopiedEntries);
649 }
650 
StartStopTimer()651 void AutocompleteController::StartStopTimer() {
652   stop_timer_.Start(FROM_HERE,
653                     stop_timer_duration_,
654                     base::Bind(&AutocompleteController::Stop,
655                                base::Unretained(this),
656                                false));
657 }
658