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