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