Home | History | Annotate | Download | only in omnibox
      1 // Copyright 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/ui/omnibox/omnibox_edit_model.h"
      6 
      7 #include <algorithm>
      8 #include <string>
      9 
     10 #include "base/auto_reset.h"
     11 #include "base/format_macros.h"
     12 #include "base/metrics/histogram.h"
     13 #include "base/prefs/pref_service.h"
     14 #include "base/strings/string_number_conversions.h"
     15 #include "base/strings/string_util.h"
     16 #include "base/strings/stringprintf.h"
     17 #include "base/strings/utf_string_conversions.h"
     18 #include "chrome/app/chrome_command_ids.h"
     19 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
     20 #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
     21 #include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
     22 #include "chrome/browser/autocomplete/history_url_provider.h"
     23 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
     24 #include "chrome/browser/bookmarks/bookmark_stats.h"
     25 #include "chrome/browser/chrome_notification_types.h"
     26 #include "chrome/browser/command_updater.h"
     27 #include "chrome/browser/extensions/api/omnibox/omnibox_api.h"
     28 #include "chrome/browser/favicon/favicon_tab_helper.h"
     29 #include "chrome/browser/google/google_url_tracker_factory.h"
     30 #include "chrome/browser/net/predictor.h"
     31 #include "chrome/browser/omnibox/omnibox_log.h"
     32 #include "chrome/browser/predictors/autocomplete_action_predictor.h"
     33 #include "chrome/browser/predictors/autocomplete_action_predictor_factory.h"
     34 #include "chrome/browser/prerender/prerender_field_trial.h"
     35 #include "chrome/browser/prerender/prerender_manager.h"
     36 #include "chrome/browser/prerender/prerender_manager_factory.h"
     37 #include "chrome/browser/profiles/profile.h"
     38 #include "chrome/browser/search/search.h"
     39 #include "chrome/browser/search_engines/template_url_service_factory.h"
     40 #include "chrome/browser/search_engines/ui_thread_search_terms_data.h"
     41 #include "chrome/browser/sessions/session_tab_helper.h"
     42 #include "chrome/browser/ui/browser_list.h"
     43 #include "chrome/browser/ui/omnibox/omnibox_current_page_delegate_impl.h"
     44 #include "chrome/browser/ui/omnibox/omnibox_edit_controller.h"
     45 #include "chrome/browser/ui/omnibox/omnibox_navigation_observer.h"
     46 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
     47 #include "chrome/browser/ui/omnibox/omnibox_popup_view.h"
     48 #include "chrome/browser/ui/omnibox/omnibox_view.h"
     49 #include "chrome/browser/ui/search/instant_search_prerenderer.h"
     50 #include "chrome/browser/ui/search/search_tab_helper.h"
     51 #include "chrome/browser/ui/toolbar/toolbar_model.h"
     52 #include "chrome/common/chrome_switches.h"
     53 #include "chrome/common/pref_names.h"
     54 #include "chrome/common/url_constants.h"
     55 #include "components/bookmarks/browser/bookmark_model.h"
     56 #include "components/google/core/browser/google_url_tracker.h"
     57 #include "components/metrics/proto/omnibox_event.pb.h"
     58 #include "components/omnibox/autocomplete_provider.h"
     59 #include "components/omnibox/keyword_provider.h"
     60 #include "components/omnibox/search_provider.h"
     61 #include "components/search_engines/template_url.h"
     62 #include "components/search_engines/template_url_prepopulate_data.h"
     63 #include "components/search_engines/template_url_service.h"
     64 #include "components/url_fixer/url_fixer.h"
     65 #include "content/public/browser/navigation_controller.h"
     66 #include "content/public/browser/navigation_entry.h"
     67 #include "content/public/browser/notification_service.h"
     68 #include "content/public/browser/render_view_host.h"
     69 #include "content/public/browser/user_metrics.h"
     70 #include "extensions/common/constants.h"
     71 #include "ui/gfx/image/image.h"
     72 #include "url/url_util.h"
     73 
     74 using metrics::OmniboxEventProto;
     75 using predictors::AutocompleteActionPredictor;
     76 
     77 
     78 // Helpers --------------------------------------------------------------------
     79 
     80 namespace {
     81 
     82 // Histogram name which counts the number of times that the user text is
     83 // cleared.  IME users are sometimes in the situation that IME was
     84 // unintentionally turned on and failed to input latin alphabets (ASCII
     85 // characters) or the opposite case.  In that case, users may delete all
     86 // the text and the user text gets cleared.  We'd like to measure how often
     87 // this scenario happens.
     88 //
     89 // Note that since we don't currently correlate "text cleared" events with
     90 // IME usage, this also captures many other cases where users clear the text;
     91 // though it explicitly doesn't log deleting all the permanent text as
     92 // the first action of an editing sequence (see comments in
     93 // OnAfterPossibleChange()).
     94 const char kOmniboxUserTextClearedHistogram[] = "Omnibox.UserTextCleared";
     95 
     96 enum UserTextClearedType {
     97   OMNIBOX_USER_TEXT_CLEARED_BY_EDITING = 0,
     98   OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE = 1,
     99   OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS,
    100 };
    101 
    102 // Histogram name which counts the number of times the user enters
    103 // keyword hint mode and via what method.  The possible values are listed
    104 // in the EnteredKeywordModeMethod enum which is defined in the .h file.
    105 const char kEnteredKeywordModeHistogram[] = "Omnibox.EnteredKeywordMode";
    106 
    107 // Histogram name which counts the number of milliseconds a user takes
    108 // between focusing and editing the omnibox.
    109 const char kFocusToEditTimeHistogram[] = "Omnibox.FocusToEditTime";
    110 
    111 // Histogram name which counts the number of milliseconds a user takes
    112 // between focusing and opening an omnibox match.
    113 const char kFocusToOpenTimeHistogram[] = "Omnibox.FocusToOpenTimeAnyPopupState";
    114 
    115 // Split the percentage match histograms into buckets based on the width of the
    116 // omnibox.
    117 const int kPercentageMatchHistogramWidthBuckets[] = { 400, 700, 1200 };
    118 
    119 void RecordPercentageMatchHistogram(const base::string16& old_text,
    120                                     const base::string16& new_text,
    121                                     bool url_replacement_active,
    122                                     ui::PageTransition transition,
    123                                     int omnibox_width) {
    124   size_t avg_length = (old_text.length() + new_text.length()) / 2;
    125 
    126   int percent = 0;
    127   if (!old_text.empty() && !new_text.empty()) {
    128     size_t shorter_length = std::min(old_text.length(), new_text.length());
    129     base::string16::const_iterator end(old_text.begin() + shorter_length);
    130     base::string16::const_iterator mismatch(
    131         std::mismatch(old_text.begin(), end, new_text.begin()).first);
    132     size_t matching_characters = mismatch - old_text.begin();
    133     percent = static_cast<float>(matching_characters) / avg_length * 100;
    134   }
    135 
    136   std::string histogram_name;
    137   if (url_replacement_active) {
    138     if (transition == ui::PAGE_TRANSITION_TYPED) {
    139       histogram_name = "InstantExtended.PercentageMatchV2_QuerytoURL";
    140       UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
    141     } else {
    142       histogram_name = "InstantExtended.PercentageMatchV2_QuerytoQuery";
    143       UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
    144     }
    145   } else {
    146     if (transition == ui::PAGE_TRANSITION_TYPED) {
    147       histogram_name = "InstantExtended.PercentageMatchV2_URLtoURL";
    148       UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
    149     } else {
    150       histogram_name = "InstantExtended.PercentageMatchV2_URLtoQuery";
    151       UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
    152     }
    153   }
    154 
    155   std::string suffix = "large";
    156   for (size_t i = 0; i < arraysize(kPercentageMatchHistogramWidthBuckets);
    157        ++i) {
    158     if (omnibox_width < kPercentageMatchHistogramWidthBuckets[i]) {
    159       suffix = base::IntToString(kPercentageMatchHistogramWidthBuckets[i]);
    160       break;
    161     }
    162   }
    163 
    164   // Cannot rely on UMA histograms macro because the name of the histogram is
    165   // generated dynamically.
    166   base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
    167       histogram_name + "_" + suffix, 1, 101, 102,
    168       base::Histogram::kUmaTargetedHistogramFlag);
    169   counter->Add(percent);
    170 }
    171 
    172 }  // namespace
    173 
    174 
    175 // OmniboxEditModel::State ----------------------------------------------------
    176 
    177 OmniboxEditModel::State::State(bool user_input_in_progress,
    178                                const base::string16& user_text,
    179                                const base::string16& gray_text,
    180                                const base::string16& keyword,
    181                                bool is_keyword_hint,
    182                                bool url_replacement_enabled,
    183                                OmniboxFocusState focus_state,
    184                                FocusSource focus_source,
    185                                const AutocompleteInput& autocomplete_input)
    186     : user_input_in_progress(user_input_in_progress),
    187       user_text(user_text),
    188       gray_text(gray_text),
    189       keyword(keyword),
    190       is_keyword_hint(is_keyword_hint),
    191       url_replacement_enabled(url_replacement_enabled),
    192       focus_state(focus_state),
    193       focus_source(focus_source),
    194       autocomplete_input(autocomplete_input) {
    195 }
    196 
    197 OmniboxEditModel::State::~State() {
    198 }
    199 
    200 
    201 // OmniboxEditModel -----------------------------------------------------------
    202 
    203 OmniboxEditModel::OmniboxEditModel(OmniboxView* view,
    204                                    OmniboxEditController* controller,
    205                                    Profile* profile)
    206     : view_(view),
    207       controller_(controller),
    208       focus_state_(OMNIBOX_FOCUS_NONE),
    209       focus_source_(INVALID),
    210       user_input_in_progress_(false),
    211       user_input_since_focus_(true),
    212       just_deleted_text_(false),
    213       has_temporary_text_(false),
    214       paste_state_(NONE),
    215       control_key_state_(UP),
    216       is_keyword_hint_(false),
    217       profile_(profile),
    218       in_revert_(false),
    219       allow_exact_keyword_match_(false) {
    220   omnibox_controller_.reset(new OmniboxController(this, profile));
    221   delegate_.reset(new OmniboxCurrentPageDelegateImpl(controller, profile));
    222 }
    223 
    224 OmniboxEditModel::~OmniboxEditModel() {
    225 }
    226 
    227 const OmniboxEditModel::State OmniboxEditModel::GetStateForTabSwitch() {
    228   // Like typing, switching tabs "accepts" the temporary text as the user
    229   // text, because it makes little sense to have temporary text when the
    230   // popup is closed.
    231   if (user_input_in_progress_) {
    232     // Weird edge case to match other browsers: if the edit is empty, revert to
    233     // the permanent text (so the user can get it back easily) but select it (so
    234     // on switching back, typing will "just work").
    235     const base::string16 user_text(UserTextFromDisplayText(view_->GetText()));
    236     if (user_text.empty()) {
    237       base::AutoReset<bool> tmp(&in_revert_, true);
    238       view_->RevertAll();
    239       view_->SelectAll(true);
    240     } else {
    241       InternalSetUserText(user_text);
    242     }
    243   }
    244 
    245   UMA_HISTOGRAM_BOOLEAN("Omnibox.SaveStateForTabSwitch.UserInputInProgress",
    246                         user_input_in_progress_);
    247   return State(
    248       user_input_in_progress_, user_text_, view_->GetGrayTextAutocompletion(),
    249       keyword_, is_keyword_hint_,
    250       controller_->GetToolbarModel()->url_replacement_enabled(),
    251       focus_state_, focus_source_, input_);
    252 }
    253 
    254 void OmniboxEditModel::RestoreState(const State* state) {
    255   // We need to update the permanent text correctly and revert the view
    256   // regardless of whether there is saved state.
    257   bool url_replacement_enabled = !state || state->url_replacement_enabled;
    258   controller_->GetToolbarModel()->set_url_replacement_enabled(
    259       url_replacement_enabled);
    260   controller_->GetToolbarModel()->set_origin_chip_enabled(
    261       url_replacement_enabled);
    262   permanent_text_ = controller_->GetToolbarModel()->GetText();
    263   // Don't muck with the search term replacement state, as we've just set it
    264   // correctly.
    265   view_->RevertWithoutResettingSearchTermReplacement();
    266   // Restore the autocomplete controller's input, or clear it if this is a new
    267   // tab.
    268   input_ = state ? state->autocomplete_input : AutocompleteInput();
    269   if (!state)
    270     return;
    271 
    272   SetFocusState(state->focus_state, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH);
    273   focus_source_ = state->focus_source;
    274   // Restore any user editing.
    275   if (state->user_input_in_progress) {
    276     // NOTE: Be sure and set keyword-related state BEFORE invoking
    277     // DisplayTextFromUserText(), as its result depends upon this state.
    278     keyword_ = state->keyword;
    279     is_keyword_hint_ = state->is_keyword_hint;
    280     view_->SetUserText(state->user_text,
    281         DisplayTextFromUserText(state->user_text), false);
    282     view_->SetGrayTextAutocompletion(state->gray_text);
    283   }
    284 }
    285 
    286 AutocompleteMatch OmniboxEditModel::CurrentMatch(
    287     GURL* alternate_nav_url) const {
    288   // If we have a valid match use it. Otherwise get one for the current text.
    289   AutocompleteMatch match = omnibox_controller_->current_match();
    290 
    291   if (!match.destination_url.is_valid()) {
    292     GetInfoForCurrentText(&match, alternate_nav_url);
    293   } else if (alternate_nav_url) {
    294     *alternate_nav_url = AutocompleteResult::ComputeAlternateNavUrl(
    295         input_, match);
    296   }
    297   return match;
    298 }
    299 
    300 bool OmniboxEditModel::UpdatePermanentText() {
    301   SearchProvider* search_provider =
    302       autocomplete_controller()->search_provider();
    303   if (search_provider && delegate_->CurrentPageExists())
    304     search_provider->set_current_page_url(delegate_->GetURL());
    305 
    306   // When there's new permanent text, and the user isn't interacting with the
    307   // omnibox, we want to revert the edit to show the new text.  We could simply
    308   // define "interacting" as "the omnibox has focus", but we still allow updates
    309   // when the omnibox has focus as long as the user hasn't begun editing, isn't
    310   // seeing zerosuggestions (because changing this text would require changing
    311   // or hiding those suggestions), and hasn't toggled on "Show URL" (because
    312   // this update will re-enable search term replacement, which will be annoying
    313   // if the user is trying to copy the URL).  When the omnibox doesn't have
    314   // focus, we assume the user may have abandoned their interaction and it's
    315   // always safe to change the text; this also prevents someone toggling "Show
    316   // URL" (which sounds as if it might be persistent) from seeing just that URL
    317   // forever afterwards.
    318   //
    319   // If the page is auto-committing gray text, however, we generally don't want
    320   // to make any change to the edit.  While auto-commits modify the underlying
    321   // permanent URL, they're intended to have no effect on the user's editing
    322   // process -- before and after the auto-commit, the omnibox should show the
    323   // same user text and the same instant suggestion, even if the auto-commit
    324   // happens while the edit doesn't have focus.
    325   base::string16 new_permanent_text = controller_->GetToolbarModel()->GetText();
    326   base::string16 gray_text = view_->GetGrayTextAutocompletion();
    327   const bool visibly_changed_permanent_text =
    328       (permanent_text_ != new_permanent_text) &&
    329       (!has_focus() ||
    330        (!user_input_in_progress_ &&
    331         !(popup_model() && popup_model()->IsOpen()) &&
    332         controller_->GetToolbarModel()->url_replacement_enabled())) &&
    333       (gray_text.empty() ||
    334        new_permanent_text != user_text_ + gray_text);
    335 
    336   permanent_text_ = new_permanent_text;
    337   return visibly_changed_permanent_text;
    338 }
    339 
    340 GURL OmniboxEditModel::PermanentURL() {
    341   return url_fixer::FixupURL(base::UTF16ToUTF8(permanent_text_), std::string());
    342 }
    343 
    344 void OmniboxEditModel::SetUserText(const base::string16& text) {
    345   SetInputInProgress(true);
    346   InternalSetUserText(text);
    347   omnibox_controller_->InvalidateCurrentMatch();
    348   paste_state_ = NONE;
    349   has_temporary_text_ = false;
    350 }
    351 
    352 bool OmniboxEditModel::CommitSuggestedText() {
    353   const base::string16 suggestion = view_->GetGrayTextAutocompletion();
    354   if (suggestion.empty())
    355     return false;
    356 
    357   const base::string16 final_text = view_->GetText() + suggestion;
    358   view_->OnBeforePossibleChange();
    359   view_->SetWindowTextAndCaretPos(final_text, final_text.length(), false,
    360       false);
    361   view_->OnAfterPossibleChange();
    362   return true;
    363 }
    364 
    365 void OmniboxEditModel::OnChanged() {
    366   // Don't call CurrentMatch() when there's no editing, as in this case we'll
    367   // never actually use it.  This avoids running the autocomplete providers (and
    368   // any systems they then spin up) during startup.
    369   const AutocompleteMatch& current_match = user_input_in_progress_ ?
    370       CurrentMatch(NULL) : AutocompleteMatch();
    371 
    372   AutocompleteActionPredictor::Action recommended_action =
    373       AutocompleteActionPredictor::ACTION_NONE;
    374   if (user_input_in_progress_) {
    375     InstantSearchPrerenderer* prerenderer =
    376         InstantSearchPrerenderer::GetForProfile(profile_);
    377     if (prerenderer &&
    378         prerenderer->IsAllowed(current_match, controller_->GetWebContents()) &&
    379         popup_model()->IsOpen() && has_focus()) {
    380       recommended_action = AutocompleteActionPredictor::ACTION_PRERENDER;
    381     } else {
    382       AutocompleteActionPredictor* action_predictor =
    383           predictors::AutocompleteActionPredictorFactory::GetForProfile(
    384               profile_);
    385       action_predictor->RegisterTransitionalMatches(user_text_, result());
    386       // Confer with the AutocompleteActionPredictor to determine what action,
    387       // if any, we should take. Get the recommended action here even if we
    388       // don't need it so we can get stats for anyone who is opted in to UMA,
    389       // but only get it if the user has actually typed something to avoid
    390       // constructing it before it's needed. Note: This event is triggered as
    391       // part of startup when the initial tab transitions to the start page.
    392       recommended_action =
    393           action_predictor->RecommendAction(user_text_, current_match);
    394     }
    395   }
    396 
    397   UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.Action",
    398                             recommended_action,
    399                             AutocompleteActionPredictor::LAST_PREDICT_ACTION);
    400 
    401   // Hide any suggestions we might be showing.
    402   view_->SetGrayTextAutocompletion(base::string16());
    403 
    404   switch (recommended_action) {
    405     case AutocompleteActionPredictor::ACTION_PRERENDER:
    406       // It's possible that there is no current page, for instance if the tab
    407       // has been closed or on return from a sleep state.
    408       // (http://crbug.com/105689)
    409       if (!delegate_->CurrentPageExists())
    410         break;
    411       // Ask for prerendering if the destination URL is different than the
    412       // current URL.
    413       if (current_match.destination_url != delegate_->GetURL())
    414         delegate_->DoPrerender(current_match);
    415       break;
    416     case AutocompleteActionPredictor::ACTION_PRECONNECT:
    417       omnibox_controller_->DoPreconnect(current_match);
    418       break;
    419     case AutocompleteActionPredictor::ACTION_NONE:
    420       break;
    421   }
    422 
    423   controller_->OnChanged();
    424 }
    425 
    426 void OmniboxEditModel::GetDataForURLExport(GURL* url,
    427                                            base::string16* title,
    428                                            gfx::Image* favicon) {
    429   *url = CurrentMatch(NULL).destination_url;
    430   if (*url == delegate_->GetURL()) {
    431     content::WebContents* web_contents = controller_->GetWebContents();
    432     *title = web_contents->GetTitle();
    433     *favicon = FaviconTabHelper::FromWebContents(web_contents)->GetFavicon();
    434   }
    435 }
    436 
    437 bool OmniboxEditModel::CurrentTextIsURL() const {
    438   if (controller_->GetToolbarModel()->WouldReplaceURL())
    439     return false;
    440 
    441   // If current text is not composed of replaced search terms and
    442   // !user_input_in_progress_, then permanent text is showing and should be a
    443   // URL, so no further checking is needed.  By avoiding checking in this case,
    444   // we avoid calling into the autocomplete providers, and thus initializing the
    445   // history system, as long as possible, which speeds startup.
    446   if (!user_input_in_progress_)
    447     return true;
    448 
    449   return !AutocompleteMatch::IsSearchType(CurrentMatch(NULL).type);
    450 }
    451 
    452 AutocompleteMatch::Type OmniboxEditModel::CurrentTextType() const {
    453   return CurrentMatch(NULL).type;
    454 }
    455 
    456 void OmniboxEditModel::AdjustTextForCopy(int sel_min,
    457                                          bool is_all_selected,
    458                                          base::string16* text,
    459                                          GURL* url,
    460                                          bool* write_url) {
    461   *write_url = false;
    462 
    463   // Do not adjust if selection did not start at the beginning of the field, or
    464   // if the URL was omitted.
    465   if ((sel_min != 0) || controller_->GetToolbarModel()->WouldReplaceURL())
    466     return;
    467 
    468   if (!user_input_in_progress_ && is_all_selected) {
    469     // The user selected all the text and has not edited it. Use the url as the
    470     // text so that if the scheme was stripped it's added back, and the url
    471     // is unescaped (we escape parts of the url for display).
    472     *url = PermanentURL();
    473     *text = base::UTF8ToUTF16(url->spec());
    474     *write_url = true;
    475     return;
    476   }
    477 
    478   // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now
    479   // the user is probably holding down control to cause the copy, which will
    480   // screw up our calculation of the desired_tld.
    481   AutocompleteMatch match;
    482   AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
    483       *text, is_keyword_selected(), true, ClassifyPage(), &match, NULL);
    484   if (AutocompleteMatch::IsSearchType(match.type))
    485     return;
    486   *url = match.destination_url;
    487 
    488   // Prefix the text with 'http://' if the text doesn't start with 'http://',
    489   // the text parses as a url with a scheme of http, the user selected the
    490   // entire host, and the user hasn't edited the host or manually removed the
    491   // scheme.
    492   GURL perm_url(PermanentURL());
    493   if (perm_url.SchemeIs(url::kHttpScheme) &&
    494       url->SchemeIs(url::kHttpScheme) && perm_url.host() == url->host()) {
    495     *write_url = true;
    496     base::string16 http = base::ASCIIToUTF16(url::kHttpScheme) +
    497         base::ASCIIToUTF16(url::kStandardSchemeSeparator);
    498     if (text->compare(0, http.length(), http) != 0)
    499       *text = http + *text;
    500   }
    501 }
    502 
    503 void OmniboxEditModel::SetInputInProgress(bool in_progress) {
    504   if (in_progress && !user_input_since_focus_) {
    505     base::TimeTicks now = base::TimeTicks::Now();
    506     DCHECK(last_omnibox_focus_ <= now);
    507     UMA_HISTOGRAM_TIMES(kFocusToEditTimeHistogram, now - last_omnibox_focus_);
    508     user_input_since_focus_ = true;
    509   }
    510 
    511   if (user_input_in_progress_ == in_progress)
    512     return;
    513 
    514   user_input_in_progress_ = in_progress;
    515   if (user_input_in_progress_) {
    516     time_user_first_modified_omnibox_ = base::TimeTicks::Now();
    517     content::RecordAction(base::UserMetricsAction("OmniboxInputInProgress"));
    518     autocomplete_controller()->ResetSession();
    519   }
    520 
    521   // The following code handles two cases:
    522   // * For HIDE_ON_USER_INPUT and ON_SRP, it hides the chip when user input
    523   //   begins.
    524   // * For HIDE_ON_MOUSE_RELEASE, which only hides the chip on mouse release if
    525   //   the omnibox is empty, it handles the "omnibox was not empty" case by
    526   //   acting like HIDE_ON_USER_INPUT.
    527   if (chrome::ShouldDisplayOriginChip() && in_progress)
    528     controller()->GetToolbarModel()->set_origin_chip_enabled(false);
    529 
    530   controller_->GetToolbarModel()->set_input_in_progress(in_progress);
    531   controller_->EndOriginChipAnimations(true);
    532   controller_->Update(NULL);
    533 
    534   if (user_input_in_progress_ || !in_revert_)
    535     delegate_->OnInputStateChanged();
    536 }
    537 
    538 void OmniboxEditModel::Revert() {
    539   SetInputInProgress(false);
    540   paste_state_ = NONE;
    541   InternalSetUserText(base::string16());
    542   keyword_.clear();
    543   is_keyword_hint_ = false;
    544   has_temporary_text_ = false;
    545   view_->SetWindowTextAndCaretPos(permanent_text_,
    546                                   has_focus() ? permanent_text_.length() : 0,
    547                                   false, true);
    548   AutocompleteActionPredictor* action_predictor =
    549       predictors::AutocompleteActionPredictorFactory::GetForProfile(profile_);
    550   action_predictor->ClearTransitionalMatches();
    551   action_predictor->CancelPrerender();
    552 }
    553 
    554 void OmniboxEditModel::StartAutocomplete(
    555     bool has_selected_text,
    556     bool prevent_inline_autocomplete) {
    557   size_t cursor_position;
    558   if (inline_autocomplete_text_.empty()) {
    559     // Cursor position is equivalent to the current selection's end.
    560     size_t start;
    561     view_->GetSelectionBounds(&start, &cursor_position);
    562     // Adjust cursor position taking into account possible keyword in the user
    563     // text.  We rely on DisplayTextFromUserText() method which is consistent
    564     // with keyword extraction done in KeywordProvider/SearchProvider.
    565     const size_t cursor_offset =
    566         user_text_.length() - DisplayTextFromUserText(user_text_).length();
    567     cursor_position += cursor_offset;
    568   } else {
    569     // There are some cases where StartAutocomplete() may be called
    570     // with non-empty |inline_autocomplete_text_|.  In such cases, we cannot
    571     // use the current selection, because it could result with the cursor
    572     // position past the last character from the user text.  Instead,
    573     // we assume that the cursor is simply at the end of input.
    574     // One example is when user presses Ctrl key while having a highlighted
    575     // inline autocomplete text.
    576     // TODO: Rethink how we are going to handle this case to avoid
    577     // inconsistent behavior when user presses Ctrl key.
    578     // See http://crbug.com/165961 and http://crbug.com/165968 for more details.
    579     cursor_position = user_text_.length();
    580   }
    581 
    582   GURL current_url =
    583       (delegate_->CurrentPageExists() && view_->IsIndicatingQueryRefinement()) ?
    584       delegate_->GetURL() : GURL();
    585   input_ = AutocompleteInput(
    586       user_text_, cursor_position, base::string16(), current_url,
    587       ClassifyPage(),
    588       prevent_inline_autocomplete || just_deleted_text_ ||
    589           (has_selected_text && inline_autocomplete_text_.empty()) ||
    590           (paste_state_ != NONE),
    591       is_keyword_selected(),
    592       is_keyword_selected() || allow_exact_keyword_match_,
    593       true, ChromeAutocompleteSchemeClassifier(profile_));
    594 
    595   omnibox_controller_->StartAutocomplete(input_);
    596 }
    597 
    598 void OmniboxEditModel::StopAutocomplete() {
    599   autocomplete_controller()->Stop(true);
    600 }
    601 
    602 bool OmniboxEditModel::CanPasteAndGo(const base::string16& text) const {
    603   if (!view_->command_updater()->IsCommandEnabled(IDC_OPEN_CURRENT_URL))
    604     return false;
    605 
    606   AutocompleteMatch match;
    607   ClassifyStringForPasteAndGo(text, &match, NULL);
    608   return match.destination_url.is_valid();
    609 }
    610 
    611 void OmniboxEditModel::PasteAndGo(const base::string16& text) {
    612   DCHECK(CanPasteAndGo(text));
    613   UMA_HISTOGRAM_COUNTS("Omnibox.PasteAndGo", 1);
    614 
    615   view_->RevertAll();
    616   AutocompleteMatch match;
    617   GURL alternate_nav_url;
    618   ClassifyStringForPasteAndGo(text, &match, &alternate_nav_url);
    619   view_->OpenMatch(match, CURRENT_TAB, alternate_nav_url, text,
    620                    OmniboxPopupModel::kNoMatch);
    621 }
    622 
    623 bool OmniboxEditModel::IsPasteAndSearch(const base::string16& text) const {
    624   AutocompleteMatch match;
    625   ClassifyStringForPasteAndGo(text, &match, NULL);
    626   return AutocompleteMatch::IsSearchType(match.type);
    627 }
    628 
    629 void OmniboxEditModel::AcceptInput(WindowOpenDisposition disposition,
    630                                    bool for_drop) {
    631   // Get the URL and transition type for the selected entry.
    632   GURL alternate_nav_url;
    633   AutocompleteMatch match = CurrentMatch(&alternate_nav_url);
    634 
    635   // If CTRL is down it means the user wants to append ".com" to the text he
    636   // typed. If we can successfully generate a URL_WHAT_YOU_TYPED match doing
    637   // that, then we use this. These matches are marked as generated by the
    638   // HistoryURLProvider so we only generate them if this provider is present.
    639   if (control_key_state_ == DOWN_WITHOUT_CHANGE && !is_keyword_selected() &&
    640       autocomplete_controller()->history_url_provider()) {
    641     // Generate a new AutocompleteInput, copying the latest one but using "com"
    642     // as the desired TLD. Then use this autocomplete input to generate a
    643     // URL_WHAT_YOU_TYPED AutocompleteMatch. Note that using the most recent
    644     // input instead of the currently visible text means we'll ignore any
    645     // visible inline autocompletion: if a user types "foo" and is autocompleted
    646     // to "foodnetwork.com", ctrl-enter will navigate to "foo.com", not
    647     // "foodnetwork.com".  At the time of writing, this behavior matches
    648     // Internet Explorer, but not Firefox.
    649     input_ = AutocompleteInput(
    650       has_temporary_text_ ?
    651           UserTextFromDisplayText(view_->GetText())  : input_.text(),
    652       input_.cursor_position(), base::ASCIIToUTF16("com"), GURL(),
    653       input_.current_page_classification(),
    654       input_.prevent_inline_autocomplete(), input_.prefer_keyword(),
    655       input_.allow_exact_keyword_match(), input_.want_asynchronous_matches(),
    656       ChromeAutocompleteSchemeClassifier(profile_));
    657     AutocompleteMatch url_match(
    658         autocomplete_controller()->history_url_provider()->SuggestExactInput(
    659             input_.text(), input_.canonicalized_url(), false));
    660 
    661 
    662     if (url_match.destination_url.is_valid()) {
    663       // We have a valid URL, we use this newly generated AutocompleteMatch.
    664       match = url_match;
    665       alternate_nav_url = GURL();
    666     }
    667   }
    668 
    669   if (!match.destination_url.is_valid())
    670     return;
    671 
    672   if ((match.transition == ui::PAGE_TRANSITION_TYPED) &&
    673       (match.destination_url == PermanentURL())) {
    674     // When the user hit enter on the existing permanent URL, treat it like a
    675     // reload for scoring purposes.  We could detect this by just checking
    676     // user_input_in_progress_, but it seems better to treat "edits" that end
    677     // up leaving the URL unchanged (e.g. deleting the last character and then
    678     // retyping it) as reloads too.  We exclude non-TYPED transitions because if
    679     // the transition is GENERATED, the user input something that looked
    680     // different from the current URL, even if it wound up at the same place
    681     // (e.g. manually retyping the same search query), and it seems wrong to
    682     // treat this as a reload.
    683     match.transition = ui::PAGE_TRANSITION_RELOAD;
    684   } else if (for_drop || ((paste_state_ != NONE) &&
    685                           match.is_history_what_you_typed_match)) {
    686     // When the user pasted in a URL and hit enter, score it like a link click
    687     // rather than a normal typed URL, so it doesn't get inline autocompleted
    688     // as aggressively later.
    689     match.transition = ui::PAGE_TRANSITION_LINK;
    690   }
    691 
    692   TemplateURLService* service =
    693       TemplateURLServiceFactory::GetForProfile(profile_);
    694   const TemplateURL* template_url = match.GetTemplateURL(service, false);
    695   if (template_url && template_url->url_ref().HasGoogleBaseURLs(
    696           UIThreadSearchTermsData(profile_))) {
    697     GoogleURLTracker* tracker =
    698         GoogleURLTrackerFactory::GetForProfile(profile_);
    699     if (tracker)
    700       tracker->SearchCommitted();
    701   }
    702 
    703   DCHECK(popup_model());
    704   view_->OpenMatch(match, disposition, alternate_nav_url, base::string16(),
    705                    popup_model()->selected_line());
    706 }
    707 
    708 void OmniboxEditModel::OpenMatch(AutocompleteMatch match,
    709                                  WindowOpenDisposition disposition,
    710                                  const GURL& alternate_nav_url,
    711                                  const base::string16& pasted_text,
    712                                  size_t index) {
    713   const base::TimeTicks& now(base::TimeTicks::Now());
    714   base::TimeDelta elapsed_time_since_user_first_modified_omnibox(
    715       now - time_user_first_modified_omnibox_);
    716   autocomplete_controller()->UpdateMatchDestinationURLWithQueryFormulationTime(
    717       elapsed_time_since_user_first_modified_omnibox, &match);
    718 
    719   base::string16 input_text(pasted_text);
    720   if (input_text.empty())
    721       input_text = user_input_in_progress_ ? user_text_ : permanent_text_;
    722   scoped_ptr<OmniboxNavigationObserver> observer(
    723       new OmniboxNavigationObserver(
    724           profile_, input_text, match,
    725           autocomplete_controller()->history_url_provider()->SuggestExactInput(
    726               input_text, alternate_nav_url,
    727               AutocompleteInput::HasHTTPScheme(input_text))));
    728 
    729   base::TimeDelta elapsed_time_since_last_change_to_default_match(
    730       now - autocomplete_controller()->last_time_default_match_changed());
    731   DCHECK(match.provider);
    732   // These elapsed times don't really make sense for ZeroSuggest matches
    733   // (because the user does not modify the omnibox for ZeroSuggest), so for
    734   // those we set the elapsed times to something that will be ignored by
    735   // metrics_log.cc.  They also don't necessarily make sense if the omnibox
    736   // dropdown is closed or the user used a paste-and-go action.  (In most
    737   // cases when this happens, the user never modified the omnibox.)
    738   if ((match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST) ||
    739       !popup_model()->IsOpen() || !pasted_text.empty()) {
    740     const base::TimeDelta default_time_delta =
    741         base::TimeDelta::FromMilliseconds(-1);
    742     elapsed_time_since_user_first_modified_omnibox = default_time_delta;
    743     elapsed_time_since_last_change_to_default_match = default_time_delta;
    744   }
    745   // If the popup is closed or this is a paste-and-go action (meaning the
    746   // contents of the dropdown are ignored regardless), we record for logging
    747   // purposes a selected_index of 0 and a suggestion list as having a single
    748   // entry of the match used.
    749   ACMatches fake_single_entry_matches;
    750   fake_single_entry_matches.push_back(match);
    751   AutocompleteResult fake_single_entry_result;
    752   fake_single_entry_result.AppendMatches(fake_single_entry_matches);
    753   OmniboxLog log(
    754       input_text,
    755       just_deleted_text_,
    756       input_.type(),
    757       popup_model()->IsOpen(),
    758       (!popup_model()->IsOpen() || !pasted_text.empty()) ? 0 : index,
    759       !pasted_text.empty(),
    760       -1,  // don't yet know tab ID; set later if appropriate
    761       ClassifyPage(),
    762       elapsed_time_since_user_first_modified_omnibox,
    763       match.allowed_to_be_default_match ? match.inline_autocompletion.length() :
    764           base::string16::npos,
    765       elapsed_time_since_last_change_to_default_match,
    766       (!popup_model()->IsOpen() || !pasted_text.empty()) ?
    767           fake_single_entry_result : result());
    768   DCHECK(!popup_model()->IsOpen() || !pasted_text.empty() ||
    769          (log.elapsed_time_since_user_first_modified_omnibox >=
    770           log.elapsed_time_since_last_change_to_default_match))
    771       << "We should've got the notification that the user modified the "
    772       << "omnibox text at same time or before the most recent time the "
    773       << "default match changed.";
    774 
    775   if ((disposition == CURRENT_TAB) && delegate_->CurrentPageExists()) {
    776     // If we know the destination is being opened in the current tab,
    777     // we can easily get the tab ID.  (If it's being opened in a new
    778     // tab, we don't know the tab ID yet.)
    779     log.tab_id = delegate_->GetSessionID().id();
    780   }
    781   autocomplete_controller()->AddProvidersInfo(&log.providers_info);
    782   content::NotificationService::current()->Notify(
    783       chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
    784       content::Source<Profile>(profile_),
    785       content::Details<OmniboxLog>(&log));
    786   LOCAL_HISTOGRAM_BOOLEAN("Omnibox.EventCount", true);
    787   DCHECK(!last_omnibox_focus_.is_null())
    788       << "An omnibox focus should have occurred before opening a match.";
    789   UMA_HISTOGRAM_TIMES(kFocusToOpenTimeHistogram, now - last_omnibox_focus_);
    790 
    791   TemplateURLService* service =
    792       TemplateURLServiceFactory::GetForProfile(profile_);
    793   TemplateURL* template_url = match.GetTemplateURL(service, false);
    794   if (template_url) {
    795     if (match.transition == ui::PAGE_TRANSITION_KEYWORD) {
    796       // The user is using a non-substituting keyword or is explicitly in
    797       // keyword mode.
    798 
    799       // Don't increment usage count for extension keywords.
    800       if (delegate_->ProcessExtensionKeyword(template_url, match,
    801                                              disposition)) {
    802         observer->OnSuccessfulNavigation();
    803         if (disposition != NEW_BACKGROUND_TAB)
    804           view_->RevertAll();
    805         return;
    806       }
    807 
    808       content::RecordAction(base::UserMetricsAction("AcceptedKeyword"));
    809       TemplateURLServiceFactory::GetForProfile(profile_)->IncrementUsageCount(
    810           template_url);
    811     } else {
    812       DCHECK_EQ(ui::PAGE_TRANSITION_GENERATED, match.transition);
    813       // NOTE: We purposefully don't increment the usage count of the default
    814       // search engine here like we do for explicit keywords above; see comments
    815       // in template_url.h.
    816     }
    817 
    818     UMA_HISTOGRAM_ENUMERATION(
    819         "Omnibox.SearchEngineType",
    820         TemplateURLPrepopulateData::GetEngineType(
    821             *template_url, UIThreadSearchTermsData(profile_)),
    822         SEARCH_ENGINE_MAX);
    823   }
    824 
    825   // Get the current text before we call RevertAll() which will clear it.
    826   base::string16 current_text = view_->GetText();
    827 
    828   if (disposition != NEW_BACKGROUND_TAB) {
    829     base::AutoReset<bool> tmp(&in_revert_, true);
    830     view_->RevertAll();  // Revert the box to its unedited state.
    831   }
    832 
    833   RecordPercentageMatchHistogram(
    834       permanent_text_, current_text,
    835       controller_->GetToolbarModel()->WouldReplaceURL(),
    836       match.transition, view_->GetWidth());
    837 
    838   // Track whether the destination URL sends us to a search results page
    839   // using the default search provider.
    840   if (TemplateURLServiceFactory::GetForProfile(profile_)->
    841       IsSearchResultsPageFromDefaultSearchProvider(match.destination_url)) {
    842     content::RecordAction(
    843         base::UserMetricsAction("OmniboxDestinationURLIsSearchOnDSP"));
    844   }
    845 
    846   if (match.destination_url.is_valid()) {
    847     // This calls RevertAll again.
    848     base::AutoReset<bool> tmp(&in_revert_, true);
    849     controller_->OnAutocompleteAccept(
    850         match.destination_url, disposition,
    851         ui::PageTransitionFromInt(
    852             match.transition | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR));
    853     if (observer->load_state() != OmniboxNavigationObserver::LOAD_NOT_SEEN)
    854       ignore_result(observer.release());  // The observer will delete itself.
    855   }
    856 
    857   BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(profile_);
    858   if (bookmark_model && bookmark_model->IsBookmarked(match.destination_url))
    859     RecordBookmarkLaunch(NULL, BOOKMARK_LAUNCH_LOCATION_OMNIBOX);
    860 }
    861 
    862 bool OmniboxEditModel::AcceptKeyword(EnteredKeywordModeMethod entered_method) {
    863   DCHECK(is_keyword_hint_ && !keyword_.empty());
    864 
    865   autocomplete_controller()->Stop(false);
    866   is_keyword_hint_ = false;
    867 
    868   if (popup_model() && popup_model()->IsOpen())
    869     popup_model()->SetSelectedLineState(OmniboxPopupModel::KEYWORD);
    870   else
    871     StartAutocomplete(false, true);
    872 
    873   // Ensure the current selection is saved before showing keyword mode
    874   // so that moving to another line and then reverting the text will restore
    875   // the current state properly.
    876   bool save_original_selection = !has_temporary_text_;
    877   has_temporary_text_ = true;
    878   view_->OnTemporaryTextMaybeChanged(
    879       DisplayTextFromUserText(CurrentMatch(NULL).fill_into_edit),
    880       save_original_selection, true);
    881 
    882   view_->UpdatePlaceholderText();
    883 
    884   content::RecordAction(base::UserMetricsAction("AcceptedKeywordHint"));
    885   UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram, entered_method,
    886                             ENTERED_KEYWORD_MODE_NUM_ITEMS);
    887 
    888   return true;
    889 }
    890 
    891 void OmniboxEditModel::AcceptTemporaryTextAsUserText() {
    892   InternalSetUserText(UserTextFromDisplayText(view_->GetText()));
    893   has_temporary_text_ = false;
    894 
    895   if (user_input_in_progress_ || !in_revert_)
    896     delegate_->OnInputStateChanged();
    897 }
    898 
    899 void OmniboxEditModel::ClearKeyword(const base::string16& visible_text) {
    900   autocomplete_controller()->Stop(false);
    901   omnibox_controller_->ClearPopupKeywordMode();
    902 
    903   const base::string16 window_text(keyword_ + visible_text);
    904 
    905   // Only reset the result if the edit text has changed since the
    906   // keyword was accepted, or if the popup is closed.
    907   if (just_deleted_text_ || !visible_text.empty() ||
    908       !(popup_model() && popup_model()->IsOpen())) {
    909     view_->OnBeforePossibleChange();
    910     view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
    911         false, false);
    912     keyword_.clear();
    913     is_keyword_hint_ = false;
    914     view_->OnAfterPossibleChange();
    915     just_deleted_text_ = true;  // OnAfterPossibleChange() fails to clear this
    916                                 // since the edit contents have actually grown
    917                                 // longer.
    918   } else {
    919     is_keyword_hint_ = true;
    920     view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
    921         false, true);
    922   }
    923 
    924   view_->UpdatePlaceholderText();
    925 }
    926 
    927 void OmniboxEditModel::OnSetFocus(bool control_down) {
    928   last_omnibox_focus_ = base::TimeTicks::Now();
    929   user_input_since_focus_ = false;
    930 
    931   // If the omnibox lost focus while the caret was hidden and then regained
    932   // focus, OnSetFocus() is called and should restore visibility. Note that
    933   // focus can be regained without an accompanying call to
    934   // OmniboxView::SetFocus(), e.g. by tabbing in.
    935   SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_EXPLICIT);
    936   control_key_state_ = control_down ? DOWN_WITHOUT_CHANGE : UP;
    937 
    938   // Try to get ZeroSuggest suggestions if a page is loaded and the user has
    939   // not been typing in the omnibox.  The |user_input_in_progress_| check is
    940   // used to detect the case where this function is called after right-clicking
    941   // in the omnibox and selecting paste in Linux (in which case we actually get
    942   // the OnSetFocus() call after the process of handling the paste has kicked
    943   // off).
    944   // TODO(hfung): Remove this when crbug/271590 is fixed.
    945   if (delegate_->CurrentPageExists() && !user_input_in_progress_) {
    946     // TODO(jered): We may want to merge this into Start() and just call that
    947     // here rather than having a special entry point for zero-suggest.  Note
    948     // that we avoid PermanentURL() here because it's not guaranteed to give us
    949     // the actual underlying current URL, e.g. if we're on the NTP and the
    950     // |permanent_text_| is empty.
    951     autocomplete_controller()->StartZeroSuggest(AutocompleteInput(
    952         permanent_text_, base::string16::npos, base::string16(),
    953         delegate_->GetURL(), ClassifyPage(), false, false, true, true,
    954         ChromeAutocompleteSchemeClassifier(profile_)));
    955   }
    956 
    957   if (user_input_in_progress_ || !in_revert_)
    958     delegate_->OnInputStateChanged();
    959 }
    960 
    961 void OmniboxEditModel::SetCaretVisibility(bool visible) {
    962   // Caret visibility only matters if the omnibox has focus.
    963   if (focus_state_ != OMNIBOX_FOCUS_NONE) {
    964     SetFocusState(visible ? OMNIBOX_FOCUS_VISIBLE : OMNIBOX_FOCUS_INVISIBLE,
    965                   OMNIBOX_FOCUS_CHANGE_EXPLICIT);
    966   }
    967 }
    968 
    969 void OmniboxEditModel::OnWillKillFocus(gfx::NativeView view_gaining_focus) {
    970   if (user_input_in_progress_ || !in_revert_)
    971     delegate_->OnInputStateChanged();
    972 }
    973 
    974 void OmniboxEditModel::OnKillFocus() {
    975   SetFocusState(OMNIBOX_FOCUS_NONE, OMNIBOX_FOCUS_CHANGE_EXPLICIT);
    976   focus_source_ = INVALID;
    977   control_key_state_ = UP;
    978   paste_state_ = NONE;
    979 }
    980 
    981 bool OmniboxEditModel::OnEscapeKeyPressed() {
    982   const AutocompleteMatch& match = CurrentMatch(NULL);
    983   if (has_temporary_text_) {
    984     if (match.destination_url != original_url_) {
    985       RevertTemporaryText(true);
    986       return true;
    987     }
    988   }
    989 
    990   // We do not clear the pending entry from the omnibox when a load is first
    991   // stopped.  If the user presses Escape while stopped, we clear it.
    992   if (delegate_->CurrentPageExists() && !delegate_->IsLoading()) {
    993     delegate_->GetNavigationController().DiscardNonCommittedEntries();
    994     view_->Update();
    995   }
    996 
    997   // When using the origin chip, hitting escape to revert all should either
    998   // display the URL (when search term replacement would not be performed for
    999   // this page) or the search terms (when it would).  To accomplish this,
   1000   // we'll need to disable URL replacement iff it's currently enabled and
   1001   // search term replacement wouldn't normally happen.
   1002   bool should_disable_url_replacement =
   1003       controller_->GetToolbarModel()->url_replacement_enabled() &&
   1004       !controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(true);
   1005 
   1006   // If the user wasn't editing, but merely had focus in the edit, allow <esc>
   1007   // to be processed as an accelerator, so it can still be used to stop a load.
   1008   // When the permanent text isn't all selected we still fall through to the
   1009   // SelectAll() call below so users can arrow around in the text and then hit
   1010   // <esc> to quickly replace all the text; this matches IE.
   1011   const bool has_zero_suggest_match = match.provider &&
   1012       (match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST);
   1013   if (!has_zero_suggest_match && !should_disable_url_replacement &&
   1014       !user_input_in_progress_ && view_->IsSelectAll())
   1015     return false;
   1016 
   1017   if (!user_text_.empty()) {
   1018     UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
   1019                               OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE,
   1020                               OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
   1021   }
   1022 
   1023   if (should_disable_url_replacement) {
   1024     controller_->GetToolbarModel()->set_url_replacement_enabled(false);
   1025     UpdatePermanentText();
   1026   }
   1027   view_->RevertWithoutResettingSearchTermReplacement();
   1028   view_->SelectAll(true);
   1029   return true;
   1030 }
   1031 
   1032 void OmniboxEditModel::OnControlKeyChanged(bool pressed) {
   1033   if (pressed == (control_key_state_ == UP))
   1034     control_key_state_ = pressed ? DOWN_WITHOUT_CHANGE : UP;
   1035 }
   1036 
   1037 void OmniboxEditModel::OnPaste() {
   1038   UMA_HISTOGRAM_COUNTS("Omnibox.Paste", 1);
   1039   paste_state_ = PASTING;
   1040 }
   1041 
   1042 void OmniboxEditModel::OnUpOrDownKeyPressed(int count) {
   1043   // NOTE: This purposefully doesn't trigger any code that resets paste_state_.
   1044   if (popup_model() && popup_model()->IsOpen()) {
   1045     // The popup is open, so the user should be able to interact with it
   1046     // normally.
   1047     popup_model()->Move(count);
   1048     return;
   1049   }
   1050 
   1051   if (!query_in_progress()) {
   1052     // The popup is neither open nor working on a query already.  So, start an
   1053     // autocomplete query for the current text.  This also sets
   1054     // user_input_in_progress_ to true, which we want: if the user has started
   1055     // to interact with the popup, changing the permanent_text_ shouldn't change
   1056     // the displayed text.
   1057     // Note: This does not force the popup to open immediately.
   1058     // TODO(pkasting): We should, in fact, force this particular query to open
   1059     // the popup immediately.
   1060     if (!user_input_in_progress_)
   1061       InternalSetUserText(permanent_text_);
   1062     view_->UpdatePopup();
   1063     return;
   1064   }
   1065 
   1066   // TODO(pkasting): The popup is working on a query but is not open.  We should
   1067   // force it to open immediately.
   1068 }
   1069 
   1070 void OmniboxEditModel::OnPopupDataChanged(
   1071     const base::string16& text,
   1072     GURL* destination_for_temporary_text_change,
   1073     const base::string16& keyword,
   1074     bool is_keyword_hint) {
   1075   // The popup changed its data, the match in the controller is no longer valid.
   1076   omnibox_controller_->InvalidateCurrentMatch();
   1077 
   1078   // Update keyword/hint-related local state.
   1079   bool keyword_state_changed = (keyword_ != keyword) ||
   1080       ((is_keyword_hint_ != is_keyword_hint) && !keyword.empty());
   1081   if (keyword_state_changed) {
   1082     keyword_ = keyword;
   1083     is_keyword_hint_ = is_keyword_hint;
   1084 
   1085     // |is_keyword_hint_| should always be false if |keyword_| is empty.
   1086     DCHECK(!keyword_.empty() || !is_keyword_hint_);
   1087   }
   1088 
   1089   // Handle changes to temporary text.
   1090   if (destination_for_temporary_text_change != NULL) {
   1091     const bool save_original_selection = !has_temporary_text_;
   1092     if (save_original_selection) {
   1093       // Save the original selection and URL so it can be reverted later.
   1094       has_temporary_text_ = true;
   1095       original_url_ = *destination_for_temporary_text_change;
   1096       inline_autocomplete_text_.clear();
   1097       view_->OnInlineAutocompleteTextCleared();
   1098     }
   1099     if (control_key_state_ == DOWN_WITHOUT_CHANGE) {
   1100       // Arrowing around the popup cancels control-enter.
   1101       control_key_state_ = DOWN_WITH_CHANGE;
   1102       // Now things are a bit screwy: the desired_tld has changed, but if we
   1103       // update the popup, the new order of entries won't match the old, so the
   1104       // user's selection gets screwy; and if we don't update the popup, and the
   1105       // user reverts, then the selected item will be as if control is still
   1106       // pressed, even though maybe it isn't any more.  There is no obvious
   1107       // right answer here :(
   1108     }
   1109     view_->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text),
   1110                                        save_original_selection, true);
   1111     return;
   1112   }
   1113 
   1114   bool call_controller_onchanged = true;
   1115   inline_autocomplete_text_ = text;
   1116   if (inline_autocomplete_text_.empty())
   1117     view_->OnInlineAutocompleteTextCleared();
   1118 
   1119   const base::string16& user_text =
   1120       user_input_in_progress_ ? user_text_ : permanent_text_;
   1121   if (keyword_state_changed && is_keyword_selected()) {
   1122     // If we reach here, the user most likely entered keyword mode by inserting
   1123     // a space between a keyword name and a search string (as pressing space or
   1124     // tab after the keyword name alone would have been be handled in
   1125     // MaybeAcceptKeywordBySpace() by calling AcceptKeyword(), which won't reach
   1126     // here).  In this case, we don't want to call
   1127     // OnInlineAutocompleteTextMaybeChanged() as normal, because that will
   1128     // correctly change the text (to the search string alone) but move the caret
   1129     // to the end of the string; instead we want the caret at the start of the
   1130     // search string since that's where it was in the original input.  So we set
   1131     // the text and caret position directly.
   1132     //
   1133     // It may also be possible to reach here if we're reverting from having
   1134     // temporary text back to a default match that's a keyword search, but in
   1135     // that case the RevertTemporaryText() call below will reset the caret or
   1136     // selection correctly so the caret positioning we do here won't matter.
   1137     view_->SetWindowTextAndCaretPos(DisplayTextFromUserText(user_text), 0,
   1138                                                             false, false);
   1139   } else if (view_->OnInlineAutocompleteTextMaybeChanged(
   1140              DisplayTextFromUserText(user_text + inline_autocomplete_text_),
   1141              DisplayTextFromUserText(user_text).length())) {
   1142     call_controller_onchanged = false;
   1143   }
   1144 
   1145   // If |has_temporary_text_| is true, then we previously had a manual selection
   1146   // but now don't (or |destination_for_temporary_text_change| would have been
   1147   // non-NULL). This can happen when deleting the selected item in the popup.
   1148   // In this case, we've already reverted the popup to the default match, so we
   1149   // need to revert ourselves as well.
   1150   if (has_temporary_text_) {
   1151     RevertTemporaryText(false);
   1152     call_controller_onchanged = false;
   1153   }
   1154 
   1155   // We need to invoke OnChanged in case the destination url changed (as could
   1156   // happen when control is toggled).
   1157   if (call_controller_onchanged)
   1158     OnChanged();
   1159 }
   1160 
   1161 bool OmniboxEditModel::OnAfterPossibleChange(const base::string16& old_text,
   1162                                              const base::string16& new_text,
   1163                                              size_t selection_start,
   1164                                              size_t selection_end,
   1165                                              bool selection_differs,
   1166                                              bool text_differs,
   1167                                              bool just_deleted_text,
   1168                                              bool allow_keyword_ui_change) {
   1169   // Update the paste state as appropriate: if we're just finishing a paste
   1170   // that replaced all the text, preserve that information; otherwise, if we've
   1171   // made some other edit, clear paste tracking.
   1172   if (paste_state_ == PASTING)
   1173     paste_state_ = PASTED;
   1174   else if (text_differs)
   1175     paste_state_ = NONE;
   1176 
   1177   if (text_differs || selection_differs) {
   1178     // Record current focus state for this input if we haven't already.
   1179     if (focus_source_ == INVALID) {
   1180       // We should generally expect the omnibox to have focus at this point, but
   1181       // it doesn't always on Linux. This is because, unlike other platforms,
   1182       // right clicking in the omnibox on Linux doesn't focus it. So pasting via
   1183       // right-click can change the contents without focusing the omnibox.
   1184       // TODO(samarth): fix Linux focus behavior and add a DCHECK here to
   1185       // check that the omnibox does have focus.
   1186       focus_source_ = (focus_state_ == OMNIBOX_FOCUS_INVISIBLE) ?
   1187           FAKEBOX : OMNIBOX;
   1188     }
   1189 
   1190     // Restore caret visibility whenever the user changes text or selection in
   1191     // the omnibox.
   1192     SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_TYPING);
   1193   }
   1194 
   1195   // Modifying the selection counts as accepting the autocompleted text.
   1196   const bool user_text_changed =
   1197       text_differs || (selection_differs && !inline_autocomplete_text_.empty());
   1198 
   1199   // If something has changed while the control key is down, prevent
   1200   // "ctrl-enter" until the control key is released.
   1201   if ((text_differs || selection_differs) &&
   1202       (control_key_state_ == DOWN_WITHOUT_CHANGE))
   1203     control_key_state_ = DOWN_WITH_CHANGE;
   1204 
   1205   if (!user_text_changed)
   1206     return false;
   1207 
   1208   // If the user text has not changed, we do not want to change the model's
   1209   // state associated with the text.  Otherwise, we can get surprising behavior
   1210   // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983
   1211   InternalSetUserText(UserTextFromDisplayText(new_text));
   1212   has_temporary_text_ = false;
   1213 
   1214   // Track when the user has deleted text so we won't allow inline
   1215   // autocomplete.
   1216   just_deleted_text_ = just_deleted_text;
   1217 
   1218   if (user_input_in_progress_ && user_text_.empty()) {
   1219     // Log cases where the user started editing and then subsequently cleared
   1220     // all the text.  Note that this explicitly doesn't catch cases like
   1221     // "hit ctrl-l to select whole edit contents, then hit backspace", because
   1222     // in such cases, |user_input_in_progress| won't be true here.
   1223     UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
   1224                               OMNIBOX_USER_TEXT_CLEARED_BY_EDITING,
   1225                               OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
   1226   }
   1227 
   1228   const bool no_selection = selection_start == selection_end;
   1229 
   1230   // Update the popup for the change, in the process changing to keyword mode
   1231   // if the user hit space in mid-string after a keyword.
   1232   // |allow_exact_keyword_match_| will be used by StartAutocomplete() method,
   1233   // which will be called by |view_->UpdatePopup()|; so after that returns we
   1234   // can safely reset this flag.
   1235   allow_exact_keyword_match_ = text_differs && allow_keyword_ui_change &&
   1236       !just_deleted_text && no_selection &&
   1237       CreatedKeywordSearchByInsertingSpaceInMiddle(old_text, user_text_,
   1238                                                    selection_start);
   1239   view_->UpdatePopup();
   1240   if (allow_exact_keyword_match_) {
   1241     view_->UpdatePlaceholderText();
   1242     UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram,
   1243                               ENTERED_KEYWORD_MODE_VIA_SPACE_IN_MIDDLE,
   1244                               ENTERED_KEYWORD_MODE_NUM_ITEMS);
   1245     allow_exact_keyword_match_ = false;
   1246   }
   1247 
   1248   // Change to keyword mode if the user is now pressing space after a keyword
   1249   // name.  Note that if this is the case, then even if there was no keyword
   1250   // hint when we entered this function (e.g. if the user has used space to
   1251   // replace some selected text that was adjoined to this keyword), there will
   1252   // be one now because of the call to UpdatePopup() above; so it's safe for
   1253   // MaybeAcceptKeywordBySpace() to look at |keyword_| and |is_keyword_hint_| to
   1254   // determine what keyword, if any, is applicable.
   1255   //
   1256   // If MaybeAcceptKeywordBySpace() accepts the keyword and returns true, that
   1257   // will have updated our state already, so in that case we don't also return
   1258   // true from this function.
   1259   return !(text_differs && allow_keyword_ui_change && !just_deleted_text &&
   1260            no_selection && (selection_start == user_text_.length()) &&
   1261            MaybeAcceptKeywordBySpace(user_text_));
   1262 }
   1263 
   1264 // TODO(beaudoin): Merge OnPopupDataChanged with this method once the popup
   1265 // handling has completely migrated to omnibox_controller.
   1266 void OmniboxEditModel::OnCurrentMatchChanged() {
   1267   has_temporary_text_ = false;
   1268 
   1269   const AutocompleteMatch& match = omnibox_controller_->current_match();
   1270 
   1271   // We store |keyword| and |is_keyword_hint| in temporary variables since
   1272   // OnPopupDataChanged use their previous state to detect changes.
   1273   base::string16 keyword;
   1274   bool is_keyword_hint;
   1275   TemplateURLService* service =
   1276       TemplateURLServiceFactory::GetForProfile(profile_);
   1277   match.GetKeywordUIState(service, &keyword, &is_keyword_hint);
   1278   if (popup_model())
   1279     popup_model()->OnResultChanged();
   1280   // OnPopupDataChanged() resets OmniboxController's |current_match_| early
   1281   // on.  Therefore, copy match.inline_autocompletion to a temp to preserve
   1282   // its value across the entire call.
   1283   const base::string16 inline_autocompletion(match.inline_autocompletion);
   1284   OnPopupDataChanged(inline_autocompletion, NULL, keyword, is_keyword_hint);
   1285 }
   1286 
   1287 void OmniboxEditModel::SetSuggestionToPrefetch(
   1288     const InstantSuggestion& suggestion) {
   1289   delegate_->SetSuggestionToPrefetch(suggestion);
   1290 }
   1291 
   1292 // static
   1293 const char OmniboxEditModel::kCutOrCopyAllTextHistogram[] =
   1294     "Omnibox.CutOrCopyAllText";
   1295 
   1296 bool OmniboxEditModel::query_in_progress() const {
   1297   return !autocomplete_controller()->done();
   1298 }
   1299 
   1300 void OmniboxEditModel::InternalSetUserText(const base::string16& text) {
   1301   user_text_ = text;
   1302   just_deleted_text_ = false;
   1303   inline_autocomplete_text_.clear();
   1304   view_->OnInlineAutocompleteTextCleared();
   1305 }
   1306 
   1307 void OmniboxEditModel::ClearPopupKeywordMode() const {
   1308   omnibox_controller_->ClearPopupKeywordMode();
   1309 }
   1310 
   1311 base::string16 OmniboxEditModel::DisplayTextFromUserText(
   1312     const base::string16& text) const {
   1313   return is_keyword_selected() ?
   1314       KeywordProvider::SplitReplacementStringFromInput(text, false) : text;
   1315 }
   1316 
   1317 base::string16 OmniboxEditModel::UserTextFromDisplayText(
   1318     const base::string16& text) const {
   1319   return is_keyword_selected() ? (keyword_ + base::char16(' ') + text) : text;
   1320 }
   1321 
   1322 void OmniboxEditModel::GetInfoForCurrentText(AutocompleteMatch* match,
   1323                                              GURL* alternate_nav_url) const {
   1324   DCHECK(match != NULL);
   1325 
   1326   if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(
   1327       false)) {
   1328     // Any time the user hits enter on the unchanged omnibox, we should reload.
   1329     // When we're not extracting search terms, AcceptInput() will take care of
   1330     // this (see code referring to PAGE_TRANSITION_RELOAD there), but when we're
   1331     // extracting search terms, the conditionals there won't fire, so we
   1332     // explicitly set up a match that will reload here.
   1333 
   1334     // It's important that we fetch the current visible URL to reload instead of
   1335     // just getting a "search what you typed" URL from
   1336     // SearchProvider::CreateSearchSuggestion(), since the user may be in a
   1337     // non-default search mode such as image search.
   1338     match->type = AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED;
   1339     match->provider = autocomplete_controller()->search_provider();
   1340     match->destination_url =
   1341         delegate_->GetNavigationController().GetVisibleEntry()->GetURL();
   1342     match->transition = ui::PAGE_TRANSITION_RELOAD;
   1343   } else if (query_in_progress() ||
   1344              (popup_model() && popup_model()->IsOpen())) {
   1345     if (query_in_progress()) {
   1346       // It's technically possible for |result| to be empty if no provider
   1347       // returns a synchronous result but the query has not completed
   1348       // synchronously; pratically, however, that should never actually happen.
   1349       if (result().empty())
   1350         return;
   1351       // The user cannot have manually selected a match, or the query would have
   1352       // stopped. So the default match must be the desired selection.
   1353       *match = *result().default_match();
   1354     } else {
   1355       // If there are no results, the popup should be closed, so we shouldn't
   1356       // have gotten here.
   1357       CHECK(!result().empty());
   1358       CHECK(popup_model()->selected_line() < result().size());
   1359       *match = result().match_at(popup_model()->selected_line());
   1360     }
   1361     if (alternate_nav_url &&
   1362         (!popup_model() || popup_model()->manually_selected_match().empty()))
   1363       *alternate_nav_url = result().alternate_nav_url();
   1364   } else {
   1365     AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
   1366         UserTextFromDisplayText(view_->GetText()), is_keyword_selected(), true,
   1367         ClassifyPage(), match, alternate_nav_url);
   1368   }
   1369 }
   1370 
   1371 void OmniboxEditModel::RevertTemporaryText(bool revert_popup) {
   1372   // The user typed something, then selected a different item.  Restore the
   1373   // text they typed and change back to the default item.
   1374   // NOTE: This purposefully does not reset paste_state_.
   1375   just_deleted_text_ = false;
   1376   has_temporary_text_ = false;
   1377 
   1378   if (revert_popup && popup_model())
   1379     popup_model()->ResetToDefaultMatch();
   1380   view_->OnRevertTemporaryText();
   1381 }
   1382 
   1383 bool OmniboxEditModel::MaybeAcceptKeywordBySpace(
   1384     const base::string16& new_text) {
   1385   size_t keyword_length = new_text.length() - 1;
   1386   return (paste_state_ == NONE) && is_keyword_hint_ && !keyword_.empty() &&
   1387       inline_autocomplete_text_.empty() &&
   1388       (keyword_.length() == keyword_length) &&
   1389       IsSpaceCharForAcceptingKeyword(new_text[keyword_length]) &&
   1390       !new_text.compare(0, keyword_length, keyword_, 0, keyword_length) &&
   1391       AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_SPACE_AT_END);
   1392 }
   1393 
   1394 bool OmniboxEditModel::CreatedKeywordSearchByInsertingSpaceInMiddle(
   1395     const base::string16& old_text,
   1396     const base::string16& new_text,
   1397     size_t caret_position) const {
   1398   DCHECK_GE(new_text.length(), caret_position);
   1399 
   1400   // Check simple conditions first.
   1401   if ((paste_state_ != NONE) || (caret_position < 2) ||
   1402       (old_text.length() < caret_position) ||
   1403       (new_text.length() == caret_position))
   1404     return false;
   1405   size_t space_position = caret_position - 1;
   1406   if (!IsSpaceCharForAcceptingKeyword(new_text[space_position]) ||
   1407       IsWhitespace(new_text[space_position - 1]) ||
   1408       new_text.compare(0, space_position, old_text, 0, space_position) ||
   1409       !new_text.compare(space_position, new_text.length() - space_position,
   1410                         old_text, space_position,
   1411                         old_text.length() - space_position)) {
   1412     return false;
   1413   }
   1414 
   1415   // Then check if the text before the inserted space matches a keyword.
   1416   base::string16 keyword;
   1417   base::TrimWhitespace(new_text.substr(0, space_position), base::TRIM_LEADING,
   1418                        &keyword);
   1419   return !keyword.empty() && !autocomplete_controller()->keyword_provider()->
   1420       GetKeywordForText(keyword).empty();
   1421 }
   1422 
   1423 //  static
   1424 bool OmniboxEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c) {
   1425   switch (c) {
   1426     case 0x0020:  // Space
   1427     case 0x3000:  // Ideographic Space
   1428       return true;
   1429     default:
   1430       return false;
   1431   }
   1432 }
   1433 
   1434 OmniboxEventProto::PageClassification OmniboxEditModel::ClassifyPage() const {
   1435   if (!delegate_->CurrentPageExists())
   1436     return OmniboxEventProto::OTHER;
   1437   if (delegate_->IsInstantNTP()) {
   1438     // Note that we treat OMNIBOX as the source if focus_source_ is INVALID,
   1439     // i.e., if input isn't actually in progress.
   1440     return (focus_source_ == FAKEBOX) ?
   1441         OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS :
   1442         OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS;
   1443   }
   1444   const GURL& gurl = delegate_->GetURL();
   1445   if (!gurl.is_valid())
   1446     return OmniboxEventProto::INVALID_SPEC;
   1447   const std::string& url = gurl.spec();
   1448   if (url == chrome::kChromeUINewTabURL)
   1449     return OmniboxEventProto::NTP;
   1450   if (url == url::kAboutBlankURL)
   1451     return OmniboxEventProto::BLANK;
   1452   if (url == profile()->GetPrefs()->GetString(prefs::kHomePage))
   1453     return OmniboxEventProto::HOME_PAGE;
   1454   if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(true))
   1455     return OmniboxEventProto::SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT;
   1456   if (delegate_->IsSearchResultsPage())
   1457     return OmniboxEventProto::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT;
   1458   return OmniboxEventProto::OTHER;
   1459 }
   1460 
   1461 void OmniboxEditModel::ClassifyStringForPasteAndGo(
   1462     const base::string16& text,
   1463     AutocompleteMatch* match,
   1464     GURL* alternate_nav_url) const {
   1465   DCHECK(match);
   1466   AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
   1467       text, false, false, ClassifyPage(), match, alternate_nav_url);
   1468 }
   1469 
   1470 void OmniboxEditModel::SetFocusState(OmniboxFocusState state,
   1471                                      OmniboxFocusChangeReason reason) {
   1472   if (state == focus_state_)
   1473     return;
   1474 
   1475   // Update state and notify view if the omnibox has focus and the caret
   1476   // visibility changed.
   1477   const bool was_caret_visible = is_caret_visible();
   1478   focus_state_ = state;
   1479   if (focus_state_ != OMNIBOX_FOCUS_NONE &&
   1480       is_caret_visible() != was_caret_visible)
   1481     view_->ApplyCaretVisibility();
   1482 
   1483   delegate_->OnFocusChanged(focus_state_, reason);
   1484 }
   1485