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.
5 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
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_input.h"
21 #include "chrome/browser/autocomplete/autocomplete_provider.h"
22 #include "chrome/browser/autocomplete/extension_app_provider.h"
23 #include "chrome/browser/autocomplete/history_url_provider.h"
24 #include "chrome/browser/autocomplete/keyword_provider.h"
25 #include "chrome/browser/autocomplete/search_provider.h"
26 #include "chrome/browser/bookmarks/bookmark_stats.h"
27 #include "chrome/browser/chrome_notification_types.h"
28 #include "chrome/browser/command_updater.h"
29 #include "chrome/browser/extensions/api/omnibox/omnibox_api.h"
30 #include "chrome/browser/favicon/favicon_tab_helper.h"
31 #include "chrome/browser/google/google_url_tracker.h"
32 #include "chrome/browser/net/predictor.h"
33 #include "chrome/browser/omnibox/omnibox_log.h"
34 #include "chrome/browser/predictors/autocomplete_action_predictor.h"
35 #include "chrome/browser/predictors/autocomplete_action_predictor_factory.h"
36 #include "chrome/browser/prerender/prerender_field_trial.h"
37 #include "chrome/browser/prerender/prerender_manager.h"
38 #include "chrome/browser/prerender/prerender_manager_factory.h"
39 #include "chrome/browser/profiles/profile.h"
40 #include "chrome/browser/search/search.h"
41 #include "chrome/browser/search_engines/template_url.h"
42 #include "chrome/browser/search_engines/template_url_prepopulate_data.h"
43 #include "chrome/browser/search_engines/template_url_service.h"
44 #include "chrome/browser/search_engines/template_url_service_factory.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_controller.h"
54 #include "chrome/browser/ui/search/instant_search_prerenderer.h"
55 #include "chrome/browser/ui/search/search_tab_helper.h"
56 #include "chrome/browser/ui/toolbar/toolbar_model.h"
57 #include "chrome/common/chrome_switches.h"
58 #include "chrome/common/net/url_fixer_upper.h"
59 #include "chrome/common/pref_names.h"
60 #include "chrome/common/url_constants.h"
61 #include "content/public/browser/navigation_controller.h"
62 #include "content/public/browser/navigation_entry.h"
63 #include "content/public/browser/notification_service.h"
64 #include "content/public/browser/render_view_host.h"
65 #include "content/public/browser/user_metrics.h"
66 #include "extensions/common/constants.h"
67 #include "ui/gfx/image/image.h"
68 #include "url/url_util.h"
70 using predictors::AutocompleteActionPredictor;
73 // Helpers --------------------------------------------------------------------
77 // Histogram name which counts the number of times that the user text is
78 // cleared. IME users are sometimes in the situation that IME was
79 // unintentionally turned on and failed to input latin alphabets (ASCII
80 // characters) or the opposite case. In that case, users may delete all
81 // the text and the user text gets cleared. We'd like to measure how often
82 // this scenario happens.
84 // Note that since we don't currently correlate "text cleared" events with
85 // IME usage, this also captures many other cases where users clear the text;
86 // though it explicitly doesn't log deleting all the permanent text as
87 // the first action of an editing sequence (see comments in
88 // OnAfterPossibleChange()).
89 const char kOmniboxUserTextClearedHistogram[] = "Omnibox.UserTextCleared";
91 enum UserTextClearedType {
92 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING = 0,
93 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE = 1,
94 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS,
97 // Histogram name which counts the number of times the user enters
98 // keyword hint mode and via what method. The possible values are listed
99 // in the EnteredKeywordModeMethod enum which is defined in the .h file.
100 const char kEnteredKeywordModeHistogram[] = "Omnibox.EnteredKeywordMode";
102 // Histogram name which counts the number of milliseconds a user takes
103 // between focusing and editing the omnibox.
104 const char kFocusToEditTimeHistogram[] = "Omnibox.FocusToEditTime";
106 // Histogram name which counts the number of milliseconds a user takes
107 // between focusing and opening an omnibox match.
108 const char kFocusToOpenTimeHistogram[] = "Omnibox.FocusToOpenTime";
110 // Split the percentage match histograms into buckets based on the width of the
112 const int kPercentageMatchHistogramWidthBuckets[] = { 400, 700, 1200 };
114 void RecordPercentageMatchHistogram(const base::string16& old_text,
115 const base::string16& new_text,
116 bool url_replacement_active,
117 content::PageTransition transition,
119 size_t avg_length = (old_text.length() + new_text.length()) / 2;
122 if (!old_text.empty() && !new_text.empty()) {
123 size_t shorter_length = std::min(old_text.length(), new_text.length());
124 base::string16::const_iterator end(old_text.begin() + shorter_length);
125 base::string16::const_iterator mismatch(
126 std::mismatch(old_text.begin(), end, new_text.begin()).first);
127 size_t matching_characters = mismatch - old_text.begin();
128 percent = static_cast<float>(matching_characters) / avg_length * 100;
131 std::string histogram_name;
132 if (url_replacement_active) {
133 if (transition == content::PAGE_TRANSITION_TYPED) {
134 histogram_name = "InstantExtended.PercentageMatchV2_QuerytoURL";
135 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
137 histogram_name = "InstantExtended.PercentageMatchV2_QuerytoQuery";
138 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
141 if (transition == content::PAGE_TRANSITION_TYPED) {
142 histogram_name = "InstantExtended.PercentageMatchV2_URLtoURL";
143 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
145 histogram_name = "InstantExtended.PercentageMatchV2_URLtoQuery";
146 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
150 std::string suffix = "large";
151 for (size_t i = 0; i < arraysize(kPercentageMatchHistogramWidthBuckets);
153 if (omnibox_width < kPercentageMatchHistogramWidthBuckets[i]) {
154 suffix = base::IntToString(kPercentageMatchHistogramWidthBuckets[i]);
159 // Cannot rely on UMA histograms macro because the name of the histogram is
160 // generated dynamically.
161 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
162 histogram_name + "_" + suffix, 1, 101, 102,
163 base::Histogram::kUmaTargetedHistogramFlag);
164 counter->Add(percent);
170 // OmniboxEditModel::State ----------------------------------------------------
172 OmniboxEditModel::State::State(bool user_input_in_progress,
173 const base::string16& user_text,
174 const base::string16& gray_text,
175 const base::string16& keyword,
176 bool is_keyword_hint,
177 bool url_replacement_enabled,
178 OmniboxFocusState focus_state,
179 FocusSource focus_source)
180 : user_input_in_progress(user_input_in_progress),
181 user_text(user_text),
182 gray_text(gray_text),
184 is_keyword_hint(is_keyword_hint),
185 url_replacement_enabled(url_replacement_enabled),
186 focus_state(focus_state),
187 focus_source(focus_source) {
190 OmniboxEditModel::State::~State() {
194 // OmniboxEditModel -----------------------------------------------------------
196 OmniboxEditModel::OmniboxEditModel(OmniboxView* view,
197 OmniboxEditController* controller,
200 controller_(controller),
201 focus_state_(OMNIBOX_FOCUS_NONE),
202 focus_source_(INVALID),
203 user_input_in_progress_(false),
204 user_input_since_focus_(true),
205 just_deleted_text_(false),
206 has_temporary_text_(false),
208 control_key_state_(UP),
209 is_keyword_hint_(false),
212 allow_exact_keyword_match_(false) {
213 omnibox_controller_.reset(new OmniboxController(this, profile));
214 delegate_.reset(new OmniboxCurrentPageDelegateImpl(controller, profile));
217 OmniboxEditModel::~OmniboxEditModel() {
220 const OmniboxEditModel::State OmniboxEditModel::GetStateForTabSwitch() {
221 // Like typing, switching tabs "accepts" the temporary text as the user
222 // text, because it makes little sense to have temporary text when the
224 if (user_input_in_progress_) {
225 // Weird edge case to match other browsers: if the edit is empty, revert to
226 // the permanent text (so the user can get it back easily) but select it (so
227 // on switching back, typing will "just work").
228 const base::string16 user_text(UserTextFromDisplayText(view_->GetText()));
229 if (user_text.empty()) {
230 base::AutoReset<bool> tmp(&in_revert_, true);
232 view_->SelectAll(true);
234 InternalSetUserText(user_text);
239 user_input_in_progress_, user_text_, view_->GetGrayTextAutocompletion(),
240 keyword_, is_keyword_hint_,
241 controller_->GetToolbarModel()->url_replacement_enabled(),
242 focus_state_, focus_source_);
245 void OmniboxEditModel::RestoreState(const State* state) {
246 // We need to update the permanent text correctly and revert the view
247 // regardless of whether there is saved state.
248 controller_->GetToolbarModel()->set_url_replacement_enabled(
249 !state || state->url_replacement_enabled);
250 permanent_text_ = controller_->GetToolbarModel()->GetText();
251 // Don't muck with the search term replacement state, as we've just set it
253 view_->RevertWithoutResettingSearchTermReplacement();
257 SetFocusState(state->focus_state, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH);
258 focus_source_ = state->focus_source;
259 // Restore any user editing.
260 if (state->user_input_in_progress) {
261 // NOTE: Be sure and set keyword-related state BEFORE invoking
262 // DisplayTextFromUserText(), as its result depends upon this state.
263 keyword_ = state->keyword;
264 is_keyword_hint_ = state->is_keyword_hint;
265 view_->SetUserText(state->user_text,
266 DisplayTextFromUserText(state->user_text), false);
267 view_->SetGrayTextAutocompletion(state->gray_text);
271 AutocompleteMatch OmniboxEditModel::CurrentMatch(
272 GURL* alternate_nav_url) const {
273 // If we have a valid match use it. Otherwise get one for the current text.
274 AutocompleteMatch match = omnibox_controller_->current_match();
276 if (!match.destination_url.is_valid()) {
277 GetInfoForCurrentText(&match, alternate_nav_url);
278 } else if (alternate_nav_url) {
279 *alternate_nav_url = AutocompleteResult::ComputeAlternateNavUrl(
280 autocomplete_controller()->input(), match);
285 bool OmniboxEditModel::UpdatePermanentText() {
286 SearchProvider* search_provider =
287 autocomplete_controller()->search_provider();
288 if (search_provider && delegate_->CurrentPageExists())
289 search_provider->set_current_page_url(delegate_->GetURL());
291 // When there's new permanent text, and the user isn't interacting with the
292 // omnibox, we want to revert the edit to show the new text. We could simply
293 // define "interacting" as "the omnibox has focus", but we still allow updates
294 // when the omnibox has focus as long as the user hasn't begun editing, isn't
295 // seeing zerosuggestions (because changing this text would require changing
296 // or hiding those suggestions), and hasn't toggled on "Show URL" (because
297 // this update will re-enable search term replacement, which will be annoying
298 // if the user is trying to copy the URL). When the omnibox doesn't have
299 // focus, we assume the user may have abandoned their interaction and it's
300 // always safe to change the text; this also prevents someone toggling "Show
301 // URL" (which sounds as if it might be persistent) from seeing just that URL
302 // forever afterwards.
304 // If the page is auto-committing gray text, however, we generally don't want
305 // to make any change to the edit. While auto-commits modify the underlying
306 // permanent URL, they're intended to have no effect on the user's editing
307 // process -- before and after the auto-commit, the omnibox should show the
308 // same user text and the same instant suggestion, even if the auto-commit
309 // happens while the edit doesn't have focus.
310 base::string16 new_permanent_text = controller_->GetToolbarModel()->GetText();
311 base::string16 gray_text = view_->GetGrayTextAutocompletion();
312 const bool visibly_changed_permanent_text =
313 (permanent_text_ != new_permanent_text) &&
315 (!user_input_in_progress_ &&
316 !(popup_model() && popup_model()->IsOpen()) &&
317 controller_->GetToolbarModel()->url_replacement_enabled())) &&
318 (gray_text.empty() ||
319 new_permanent_text != user_text_ + gray_text);
321 permanent_text_ = new_permanent_text;
322 return visibly_changed_permanent_text;
325 GURL OmniboxEditModel::PermanentURL() {
326 return URLFixerUpper::FixupURL(base::UTF16ToUTF8(permanent_text_),
330 void OmniboxEditModel::SetUserText(const base::string16& text) {
331 SetInputInProgress(true);
332 InternalSetUserText(text);
333 omnibox_controller_->InvalidateCurrentMatch();
335 has_temporary_text_ = false;
338 bool OmniboxEditModel::CommitSuggestedText() {
339 const base::string16 suggestion = view_->GetGrayTextAutocompletion();
340 if (suggestion.empty())
343 const base::string16 final_text = view_->GetText() + suggestion;
344 view_->OnBeforePossibleChange();
345 view_->SetWindowTextAndCaretPos(final_text, final_text.length(), false,
347 view_->OnAfterPossibleChange();
351 void OmniboxEditModel::OnChanged() {
352 // Don't call CurrentMatch() when there's no editing, as in this case we'll
353 // never actually use it. This avoids running the autocomplete providers (and
354 // any systems they then spin up) during startup.
355 const AutocompleteMatch& current_match = user_input_in_progress_ ?
356 CurrentMatch(NULL) : AutocompleteMatch();
358 AutocompleteActionPredictor::Action recommended_action =
359 AutocompleteActionPredictor::ACTION_NONE;
360 if (user_input_in_progress_) {
361 InstantSearchPrerenderer* prerenderer =
362 InstantSearchPrerenderer::GetForProfile(profile_);
364 prerenderer->IsAllowed(current_match, controller_->GetWebContents()) &&
365 popup_model()->IsOpen() && has_focus()) {
366 recommended_action = AutocompleteActionPredictor::ACTION_PRERENDER;
368 AutocompleteActionPredictor* action_predictor =
369 predictors::AutocompleteActionPredictorFactory::GetForProfile(
371 action_predictor->RegisterTransitionalMatches(user_text_, result());
372 // Confer with the AutocompleteActionPredictor to determine what action,
373 // if any, we should take. Get the recommended action here even if we
374 // don't need it so we can get stats for anyone who is opted in to UMA,
375 // but only get it if the user has actually typed something to avoid
376 // constructing it before it's needed. Note: This event is triggered as
377 // part of startup when the initial tab transitions to the start page.
379 action_predictor->RecommendAction(user_text_, current_match);
383 UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.Action",
385 AutocompleteActionPredictor::LAST_PREDICT_ACTION);
387 // Hide any suggestions we might be showing.
388 view_->SetGrayTextAutocompletion(base::string16());
390 switch (recommended_action) {
391 case AutocompleteActionPredictor::ACTION_PRERENDER:
392 // It's possible that there is no current page, for instance if the tab
393 // has been closed or on return from a sleep state.
394 // (http://crbug.com/105689)
395 if (!delegate_->CurrentPageExists())
397 // Ask for prerendering if the destination URL is different than the
399 if (current_match.destination_url != delegate_->GetURL())
400 delegate_->DoPrerender(current_match);
402 case AutocompleteActionPredictor::ACTION_PRECONNECT:
403 omnibox_controller_->DoPreconnect(current_match);
405 case AutocompleteActionPredictor::ACTION_NONE:
409 controller_->OnChanged();
412 void OmniboxEditModel::GetDataForURLExport(GURL* url,
413 base::string16* title,
414 gfx::Image* favicon) {
415 *url = CurrentMatch(NULL).destination_url;
416 if (*url == delegate_->GetURL()) {
417 content::WebContents* web_contents = controller_->GetWebContents();
418 *title = web_contents->GetTitle();
419 *favicon = FaviconTabHelper::FromWebContents(web_contents)->GetFavicon();
423 bool OmniboxEditModel::CurrentTextIsURL() const {
424 if (controller_->GetToolbarModel()->WouldReplaceURL())
427 // If current text is not composed of replaced search terms and
428 // !user_input_in_progress_, then permanent text is showing and should be a
429 // URL, so no further checking is needed. By avoiding checking in this case,
430 // we avoid calling into the autocomplete providers, and thus initializing the
431 // history system, as long as possible, which speeds startup.
432 if (!user_input_in_progress_)
435 return !AutocompleteMatch::IsSearchType(CurrentMatch(NULL).type);
438 AutocompleteMatch::Type OmniboxEditModel::CurrentTextType() const {
439 return CurrentMatch(NULL).type;
442 void OmniboxEditModel::AdjustTextForCopy(int sel_min,
443 bool is_all_selected,
444 base::string16* text,
449 // Do not adjust if selection did not start at the beginning of the field, or
450 // if the URL was omitted.
451 if ((sel_min != 0) || controller_->GetToolbarModel()->WouldReplaceURL())
454 if (!user_input_in_progress_ && is_all_selected) {
455 // The user selected all the text and has not edited it. Use the url as the
456 // text so that if the scheme was stripped it's added back, and the url
457 // is unescaped (we escape parts of the url for display).
458 *url = PermanentURL();
459 *text = base::UTF8ToUTF16(url->spec());
464 // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now
465 // the user is probably holding down control to cause the copy, which will
466 // screw up our calculation of the desired_tld.
467 AutocompleteMatch match;
468 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
469 *text, KeywordIsSelected(), true, ClassifyPage(), &match, NULL);
470 if (AutocompleteMatch::IsSearchType(match.type))
472 *url = match.destination_url;
474 // Prefix the text with 'http://' if the text doesn't start with 'http://',
475 // the text parses as a url with a scheme of http, the user selected the
476 // entire host, and the user hasn't edited the host or manually removed the
478 GURL perm_url(PermanentURL());
479 if (perm_url.SchemeIs(content::kHttpScheme) &&
480 url->SchemeIs(content::kHttpScheme) && perm_url.host() == url->host()) {
482 base::string16 http = base::ASCIIToUTF16(content::kHttpScheme) +
483 base::ASCIIToUTF16(content::kStandardSchemeSeparator);
484 if (text->compare(0, http.length(), http) != 0)
485 *text = http + *text;
489 void OmniboxEditModel::SetInputInProgress(bool in_progress) {
490 if (in_progress && !user_input_since_focus_) {
491 base::TimeTicks now = base::TimeTicks::Now();
492 DCHECK(last_omnibox_focus_ <= now);
493 UMA_HISTOGRAM_TIMES(kFocusToEditTimeHistogram, now - last_omnibox_focus_);
494 user_input_since_focus_ = true;
497 if (user_input_in_progress_ == in_progress)
500 user_input_in_progress_ = in_progress;
501 if (user_input_in_progress_) {
502 time_user_first_modified_omnibox_ = base::TimeTicks::Now();
503 content::RecordAction(base::UserMetricsAction("OmniboxInputInProgress"));
504 autocomplete_controller()->ResetSession();
505 // Once the user starts editing, re-enable URL replacement, so that it will
506 // kick in if applicable once the edit is committed or reverted. (While the
507 // edit is in progress, this won't have a visible effect.)
508 controller_->GetToolbarModel()->set_url_replacement_enabled(true);
511 if (chrome::GetOriginChipV2HideTrigger() ==
512 chrome::ORIGIN_CHIP_V2_HIDE_ON_USER_INPUT)
513 controller()->GetToolbarModel()->set_origin_chip_enabled(!in_progress);
515 controller_->GetToolbarModel()->set_input_in_progress(in_progress);
516 controller_->Update(NULL);
518 delegate_->NotifySearchTabHelper(user_input_in_progress_, !in_revert_);
521 void OmniboxEditModel::Revert() {
522 SetInputInProgress(false);
524 InternalSetUserText(base::string16());
526 is_keyword_hint_ = false;
527 has_temporary_text_ = false;
528 view_->SetWindowTextAndCaretPos(permanent_text_,
529 has_focus() ? permanent_text_.length() : 0,
531 AutocompleteActionPredictor* action_predictor =
532 predictors::AutocompleteActionPredictorFactory::GetForProfile(profile_);
533 action_predictor->ClearTransitionalMatches();
536 void OmniboxEditModel::StartAutocomplete(
537 bool has_selected_text,
538 bool prevent_inline_autocomplete) const {
539 size_t cursor_position;
540 if (inline_autocomplete_text_.empty()) {
541 // Cursor position is equivalent to the current selection's end.
543 view_->GetSelectionBounds(&start, &cursor_position);
544 // Adjust cursor position taking into account possible keyword in the user
545 // text. We rely on DisplayTextFromUserText() method which is consistent
546 // with keyword extraction done in KeywordProvider/SearchProvider.
547 const size_t cursor_offset =
548 user_text_.length() - DisplayTextFromUserText(user_text_).length();
549 cursor_position += cursor_offset;
551 // There are some cases where StartAutocomplete() may be called
552 // with non-empty |inline_autocomplete_text_|. In such cases, we cannot
553 // use the current selection, because it could result with the cursor
554 // position past the last character from the user text. Instead,
555 // we assume that the cursor is simply at the end of input.
556 // One example is when user presses Ctrl key while having a highlighted
557 // inline autocomplete text.
558 // TODO: Rethink how we are going to handle this case to avoid
559 // inconsistent behavior when user presses Ctrl key.
560 // See http://crbug.com/165961 and http://crbug.com/165968 for more details.
561 cursor_position = user_text_.length();
565 (delegate_->CurrentPageExists() && view_->IsIndicatingQueryRefinement()) ?
566 delegate_->GetURL() : GURL();
567 bool keyword_is_selected = KeywordIsSelected();
568 omnibox_controller_->StartAutocomplete(
573 prevent_inline_autocomplete || just_deleted_text_ ||
574 (has_selected_text && inline_autocomplete_text_.empty()) ||
575 (paste_state_ != NONE),
577 keyword_is_selected || allow_exact_keyword_match_);
580 void OmniboxEditModel::StopAutocomplete() {
581 autocomplete_controller()->Stop(true);
584 bool OmniboxEditModel::CanPasteAndGo(const base::string16& text) const {
585 if (!view_->command_updater()->IsCommandEnabled(IDC_OPEN_CURRENT_URL))
588 AutocompleteMatch match;
589 ClassifyStringForPasteAndGo(text, &match, NULL);
590 return match.destination_url.is_valid();
593 void OmniboxEditModel::PasteAndGo(const base::string16& text) {
594 DCHECK(CanPasteAndGo(text));
595 UMA_HISTOGRAM_COUNTS("Omnibox.PasteAndGo", 1);
598 AutocompleteMatch match;
599 GURL alternate_nav_url;
600 ClassifyStringForPasteAndGo(text, &match, &alternate_nav_url);
601 view_->OpenMatch(match, CURRENT_TAB, alternate_nav_url, text,
602 OmniboxPopupModel::kNoMatch);
605 bool OmniboxEditModel::IsPasteAndSearch(const base::string16& text) const {
606 AutocompleteMatch match;
607 ClassifyStringForPasteAndGo(text, &match, NULL);
608 return AutocompleteMatch::IsSearchType(match.type);
611 void OmniboxEditModel::AcceptInput(WindowOpenDisposition disposition,
613 // Get the URL and transition type for the selected entry.
614 GURL alternate_nav_url;
615 AutocompleteMatch match = CurrentMatch(&alternate_nav_url);
617 // If CTRL is down it means the user wants to append ".com" to the text he
618 // typed. If we can successfully generate a URL_WHAT_YOU_TYPED match doing
619 // that, then we use this. These matches are marked as generated by the
620 // HistoryURLProvider so we only generate them if this provider is present.
621 if (control_key_state_ == DOWN_WITHOUT_CHANGE && !KeywordIsSelected() &&
622 autocomplete_controller()->history_url_provider()) {
623 // Generate a new AutocompleteInput, copying the latest one but using "com"
624 // as the desired TLD. Then use this autocomplete input to generate a
625 // URL_WHAT_YOU_TYPED AutocompleteMatch. Note that using the most recent
626 // input instead of the currently visible text means we'll ignore any
627 // visible inline autocompletion: if a user types "foo" and is autocompleted
628 // to "foodnetwork.com", ctrl-enter will navigate to "foo.com", not
629 // "foodnetwork.com". At the time of writing, this behavior matches
630 // Internet Explorer, but not Firefox.
631 const AutocompleteInput& old_input = autocomplete_controller()->input();
632 AutocompleteInput input(
633 has_temporary_text_ ?
634 UserTextFromDisplayText(view_->GetText()) : old_input.text(),
635 old_input.cursor_position(), base::ASCIIToUTF16("com"),
636 GURL(), old_input.current_page_classification(),
637 old_input.prevent_inline_autocomplete(), old_input.prefer_keyword(),
638 old_input.allow_exact_keyword_match(), old_input.matches_requested());
639 AutocompleteMatch url_match(
640 autocomplete_controller()->history_url_provider()->SuggestExactInput(
641 input.text(), input.canonicalized_url(), false));
643 if (url_match.destination_url.is_valid()) {
644 // We have a valid URL, we use this newly generated AutocompleteMatch.
646 alternate_nav_url = GURL();
650 if (!match.destination_url.is_valid())
653 if ((match.transition == content::PAGE_TRANSITION_TYPED) &&
654 (match.destination_url == PermanentURL())) {
655 // When the user hit enter on the existing permanent URL, treat it like a
656 // reload for scoring purposes. We could detect this by just checking
657 // user_input_in_progress_, but it seems better to treat "edits" that end
658 // up leaving the URL unchanged (e.g. deleting the last character and then
659 // retyping it) as reloads too. We exclude non-TYPED transitions because if
660 // the transition is GENERATED, the user input something that looked
661 // different from the current URL, even if it wound up at the same place
662 // (e.g. manually retyping the same search query), and it seems wrong to
663 // treat this as a reload.
664 match.transition = content::PAGE_TRANSITION_RELOAD;
665 } else if (for_drop || ((paste_state_ != NONE) &&
666 match.is_history_what_you_typed_match)) {
667 // When the user pasted in a URL and hit enter, score it like a link click
668 // rather than a normal typed URL, so it doesn't get inline autocompleted
669 // as aggressively later.
670 match.transition = content::PAGE_TRANSITION_LINK;
673 const TemplateURL* template_url = match.GetTemplateURL(profile_, false);
674 if (template_url && template_url->url_ref().HasGoogleBaseURLs())
675 GoogleURLTracker::GoogleURLSearchCommitted(profile_);
677 view_->OpenMatch(match, disposition, alternate_nav_url, base::string16(),
678 OmniboxPopupModel::kNoMatch);
681 void OmniboxEditModel::OpenMatch(AutocompleteMatch match,
682 WindowOpenDisposition disposition,
683 const GURL& alternate_nav_url,
684 const base::string16& pasted_text,
686 const base::TimeTicks& now(base::TimeTicks::Now());
687 base::TimeDelta elapsed_time_since_user_first_modified_omnibox(
688 now - time_user_first_modified_omnibox_);
689 autocomplete_controller()->UpdateMatchDestinationURL(
690 elapsed_time_since_user_first_modified_omnibox, &match);
692 base::string16 input_text(pasted_text);
693 if (input_text.empty())
694 input_text = user_input_in_progress_ ? user_text_ : permanent_text_;
695 scoped_ptr<OmniboxNavigationObserver> observer(
696 new OmniboxNavigationObserver(
697 profile_, input_text, match,
698 autocomplete_controller()->history_url_provider()->SuggestExactInput(
699 input_text, alternate_nav_url,
700 AutocompleteInput::HasHTTPScheme(input_text))));
702 // We only care about cases where there is a selection (i.e. the popup is
704 if (popup_model() && popup_model()->IsOpen()) {
705 base::TimeDelta elapsed_time_since_last_change_to_default_match(
706 now - autocomplete_controller()->last_time_default_match_changed());
707 // These elapsed times don't really make sense for ZeroSuggest matches
708 // (because the user does not modify the omnibox for ZeroSuggest), so for
709 // those we set the elapsed times to something that will be ignored by
711 if (match.provider &&
712 (match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST)) {
713 elapsed_time_since_user_first_modified_omnibox =
714 base::TimeDelta::FromMilliseconds(-1);
715 elapsed_time_since_last_change_to_default_match =
716 base::TimeDelta::FromMilliseconds(-1);
721 autocomplete_controller()->input().type(),
722 popup_model()->selected_line(),
723 -1, // don't yet know tab ID; set later if appropriate
725 elapsed_time_since_user_first_modified_omnibox,
726 match.inline_autocompletion.length(),
727 elapsed_time_since_last_change_to_default_match,
730 DCHECK(user_input_in_progress_ || (match.provider &&
731 (match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST)))
732 << "We didn't get here through the expected series of calls. "
733 << "time_user_first_modified_omnibox_ is not set correctly and other "
734 << "things may be wrong. Match provider: "
735 << (match.provider ? match.provider->GetName() : "NULL");
736 DCHECK(log.elapsed_time_since_user_first_modified_omnibox >=
737 log.elapsed_time_since_last_change_to_default_match)
738 << "We should've got the notification that the user modified the "
739 << "omnibox text at same time or before the most recent time the "
740 << "default match changed.";
742 if (index != OmniboxPopupModel::kNoMatch)
743 log.selected_index = index;
745 if ((disposition == CURRENT_TAB) && delegate_->CurrentPageExists()) {
746 // If we know the destination is being opened in the current tab,
747 // we can easily get the tab ID. (If it's being opened in a new
748 // tab, we don't know the tab ID yet.)
749 log.tab_id = delegate_->GetSessionID().id();
751 autocomplete_controller()->AddProvidersInfo(&log.providers_info);
752 content::NotificationService::current()->Notify(
753 chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
754 content::Source<Profile>(profile_),
755 content::Details<OmniboxLog>(&log));
756 HISTOGRAM_ENUMERATION("Omnibox.EventCount", 1, 2);
757 DCHECK(!last_omnibox_focus_.is_null())
758 << "An omnibox focus should have occurred before opening a match.";
759 UMA_HISTOGRAM_TIMES(kFocusToOpenTimeHistogram, now - last_omnibox_focus_);
762 TemplateURL* template_url = match.GetTemplateURL(profile_, false);
764 if (match.transition == content::PAGE_TRANSITION_KEYWORD) {
765 // The user is using a non-substituting keyword or is explicitly in
768 // Don't increment usage count for extension keywords.
769 if (delegate_->ProcessExtensionKeyword(template_url, match,
771 observer->OnSuccessfulNavigation();
772 if (disposition != NEW_BACKGROUND_TAB)
777 content::RecordAction(base::UserMetricsAction("AcceptedKeyword"));
778 TemplateURLServiceFactory::GetForProfile(profile_)->IncrementUsageCount(
781 DCHECK_EQ(content::PAGE_TRANSITION_GENERATED, match.transition);
782 // NOTE: We purposefully don't increment the usage count of the default
783 // search engine here like we do for explicit keywords above; see comments
784 // in template_url.h.
787 // TODO(pkasting): This histogram obsoletes the next one. Remove the next
788 // one in Chrome 32 or later.
789 UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngineType",
790 TemplateURLPrepopulateData::GetEngineType(*template_url),
792 // NOTE: Non-prepopulated engines will all have ID 0, which is fine as
793 // the prepopulate IDs start at 1. Distribution-specific engines will
794 // all have IDs above the maximum, and will be automatically lumped
795 // together in an "overflow" bucket in the histogram.
796 UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngine",
797 template_url->prepopulate_id(),
798 TemplateURLPrepopulateData::kMaxPrepopulatedEngineID);
801 // Get the current text before we call RevertAll() which will clear it.
802 base::string16 current_text = view_->GetText();
804 if (disposition != NEW_BACKGROUND_TAB) {
805 base::AutoReset<bool> tmp(&in_revert_, true);
806 view_->RevertAll(); // Revert the box to its unedited state.
809 if (match.type == AutocompleteMatchType::EXTENSION_APP) {
810 ExtensionAppProvider::LaunchAppFromOmnibox(match, profile_, disposition);
811 observer->OnSuccessfulNavigation();
813 RecordPercentageMatchHistogram(
814 permanent_text_, current_text,
815 controller_->GetToolbarModel()->WouldReplaceURL(),
816 match.transition, view_->GetWidth());
818 // Track whether the destination URL sends us to a search results page
819 // using the default search provider.
820 if (TemplateURLServiceFactory::GetForProfile(profile_)->
821 IsSearchResultsPageFromDefaultSearchProvider(match.destination_url)) {
822 content::RecordAction(
823 base::UserMetricsAction("OmniboxDestinationURLIsSearchOnDSP"));
826 if (match.destination_url.is_valid()) {
827 // This calls RevertAll again.
828 base::AutoReset<bool> tmp(&in_revert_, true);
829 controller_->OnAutocompleteAccept(
830 match.destination_url, disposition,
831 content::PageTransitionFromInt(
832 match.transition | content::PAGE_TRANSITION_FROM_ADDRESS_BAR));
833 if (observer->load_state() != OmniboxNavigationObserver::LOAD_NOT_SEEN)
834 ignore_result(observer.release()); // The observer will delete itself.
839 RecordBookmarkLaunch(NULL, BOOKMARK_LAUNCH_LOCATION_OMNIBOX);
842 bool OmniboxEditModel::AcceptKeyword(EnteredKeywordModeMethod entered_method) {
843 DCHECK(is_keyword_hint_ && !keyword_.empty());
845 autocomplete_controller()->Stop(false);
846 is_keyword_hint_ = false;
848 if (popup_model() && popup_model()->IsOpen())
849 popup_model()->SetSelectedLineState(OmniboxPopupModel::KEYWORD);
851 StartAutocomplete(false, true);
853 // Ensure the current selection is saved before showing keyword mode
854 // so that moving to another line and then reverting the text will restore
855 // the current state properly.
856 bool save_original_selection = !has_temporary_text_;
857 has_temporary_text_ = true;
858 view_->OnTemporaryTextMaybeChanged(
859 DisplayTextFromUserText(CurrentMatch(NULL).fill_into_edit),
860 save_original_selection, true);
862 content::RecordAction(base::UserMetricsAction("AcceptedKeywordHint"));
863 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram, entered_method,
864 ENTERED_KEYWORD_MODE_NUM_ITEMS);
869 void OmniboxEditModel::AcceptTemporaryTextAsUserText() {
870 InternalSetUserText(UserTextFromDisplayText(view_->GetText()));
871 has_temporary_text_ = false;
872 delegate_->NotifySearchTabHelper(user_input_in_progress_, !in_revert_);
875 void OmniboxEditModel::ClearKeyword(const base::string16& visible_text) {
876 autocomplete_controller()->Stop(false);
877 omnibox_controller_->ClearPopupKeywordMode();
879 const base::string16 window_text(keyword_ + visible_text);
881 // Only reset the result if the edit text has changed since the
882 // keyword was accepted, or if the popup is closed.
883 if (just_deleted_text_ || !visible_text.empty() ||
884 !(popup_model() && popup_model()->IsOpen())) {
885 view_->OnBeforePossibleChange();
886 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
889 is_keyword_hint_ = false;
890 view_->OnAfterPossibleChange();
891 just_deleted_text_ = true; // OnAfterPossibleChange() fails to clear this
892 // since the edit contents have actually grown
895 is_keyword_hint_ = true;
896 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
901 void OmniboxEditModel::OnSetFocus(bool control_down) {
902 last_omnibox_focus_ = base::TimeTicks::Now();
903 user_input_since_focus_ = false;
905 // If the omnibox lost focus while the caret was hidden and then regained
906 // focus, OnSetFocus() is called and should restore visibility. Note that
907 // focus can be regained without an accompanying call to
908 // OmniboxView::SetFocus(), e.g. by tabbing in.
909 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_EXPLICIT);
910 control_key_state_ = control_down ? DOWN_WITHOUT_CHANGE : UP;
912 // Try to get ZeroSuggest suggestions if a page is loaded and the user has
913 // not been typing in the omnibox. The |user_input_in_progress_| check is
914 // used to detect the case where this function is called after right-clicking
915 // in the omnibox and selecting paste in Linux (in which case we actually get
916 // the OnSetFocus() call after the process of handling the paste has kicked
918 // TODO(hfung): Remove this when crbug/271590 is fixed.
919 if (delegate_->CurrentPageExists() && !user_input_in_progress_) {
920 // TODO(jered): We may want to merge this into Start() and just call that
921 // here rather than having a special entry point for zero-suggest. Note
922 // that we avoid PermanentURL() here because it's not guaranteed to give us
923 // the actual underlying current URL, e.g. if we're on the NTP and the
924 // |permanent_text_| is empty.
925 autocomplete_controller()->StartZeroSuggest(delegate_->GetURL(),
930 delegate_->NotifySearchTabHelper(user_input_in_progress_, !in_revert_);
933 void OmniboxEditModel::SetCaretVisibility(bool visible) {
934 // Caret visibility only matters if the omnibox has focus.
935 if (focus_state_ != OMNIBOX_FOCUS_NONE) {
936 SetFocusState(visible ? OMNIBOX_FOCUS_VISIBLE : OMNIBOX_FOCUS_INVISIBLE,
937 OMNIBOX_FOCUS_CHANGE_EXPLICIT);
941 void OmniboxEditModel::OnWillKillFocus(gfx::NativeView view_gaining_focus) {
942 InstantController* instant = GetInstantController();
944 instant->OmniboxFocusChanged(OMNIBOX_FOCUS_NONE,
945 OMNIBOX_FOCUS_CHANGE_EXPLICIT,
949 // TODO(jered): Rip this out along with StartZeroSuggest.
950 autocomplete_controller()->StopZeroSuggest();
951 delegate_->NotifySearchTabHelper(user_input_in_progress_, !in_revert_);
954 void OmniboxEditModel::OnKillFocus() {
955 // TODO(samarth): determine if it is safe to move the call to
956 // OmniboxFocusChanged() from OnWillKillFocus() to here, which would let us
957 // just call SetFocusState() to handle the state change.
958 focus_state_ = OMNIBOX_FOCUS_NONE;
959 focus_source_ = INVALID;
960 control_key_state_ = UP;
964 bool OmniboxEditModel::OnEscapeKeyPressed() {
965 const AutocompleteMatch& match = CurrentMatch(NULL);
966 if (has_temporary_text_) {
967 if (match.destination_url != original_url_) {
968 RevertTemporaryText(true);
973 // We do not clear the pending entry from the omnibox when a load is first
974 // stopped. If the user presses Escape while stopped, we clear it.
975 if (delegate_->CurrentPageExists() && !delegate_->IsLoading()) {
976 delegate_->GetNavigationController().DiscardNonCommittedEntries();
980 // If the user wasn't editing, but merely had focus in the edit, allow <esc>
981 // to be processed as an accelerator, so it can still be used to stop a load.
982 // When the permanent text isn't all selected we still fall through to the
983 // SelectAll() call below so users can arrow around in the text and then hit
984 // <esc> to quickly replace all the text; this matches IE.
985 const bool has_zero_suggest_match = match.provider &&
986 (match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST);
987 if (!has_zero_suggest_match && !user_input_in_progress_ &&
988 view_->IsSelectAll())
991 if (!user_text_.empty()) {
992 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
993 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE,
994 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
997 view_->SelectAll(true);
1001 void OmniboxEditModel::OnControlKeyChanged(bool pressed) {
1002 if (pressed == (control_key_state_ == UP))
1003 control_key_state_ = pressed ? DOWN_WITHOUT_CHANGE : UP;
1006 void OmniboxEditModel::OnPaste() {
1007 UMA_HISTOGRAM_COUNTS("Omnibox.Paste", 1);
1008 paste_state_ = PASTING;
1011 void OmniboxEditModel::OnUpOrDownKeyPressed(int count) {
1012 // NOTE: This purposefully doesn't trigger any code that resets paste_state_.
1013 if (popup_model() && popup_model()->IsOpen()) {
1014 // The popup is open, so the user should be able to interact with it
1016 popup_model()->Move(count);
1020 if (!query_in_progress()) {
1021 // The popup is neither open nor working on a query already. So, start an
1022 // autocomplete query for the current text. This also sets
1023 // user_input_in_progress_ to true, which we want: if the user has started
1024 // to interact with the popup, changing the permanent_text_ shouldn't change
1025 // the displayed text.
1026 // Note: This does not force the popup to open immediately.
1027 // TODO(pkasting): We should, in fact, force this particular query to open
1028 // the popup immediately.
1029 if (!user_input_in_progress_)
1030 InternalSetUserText(permanent_text_);
1031 view_->UpdatePopup();
1035 // TODO(pkasting): The popup is working on a query but is not open. We should
1036 // force it to open immediately.
1039 void OmniboxEditModel::OnPopupDataChanged(
1040 const base::string16& text,
1041 GURL* destination_for_temporary_text_change,
1042 const base::string16& keyword,
1043 bool is_keyword_hint) {
1044 // The popup changed its data, the match in the controller is no longer valid.
1045 omnibox_controller_->InvalidateCurrentMatch();
1047 // Update keyword/hint-related local state.
1048 bool keyword_state_changed = (keyword_ != keyword) ||
1049 ((is_keyword_hint_ != is_keyword_hint) && !keyword.empty());
1050 if (keyword_state_changed) {
1052 is_keyword_hint_ = is_keyword_hint;
1054 // |is_keyword_hint_| should always be false if |keyword_| is empty.
1055 DCHECK(!keyword_.empty() || !is_keyword_hint_);
1058 // Handle changes to temporary text.
1059 if (destination_for_temporary_text_change != NULL) {
1060 const bool save_original_selection = !has_temporary_text_;
1061 if (save_original_selection) {
1062 // Save the original selection and URL so it can be reverted later.
1063 has_temporary_text_ = true;
1064 original_url_ = *destination_for_temporary_text_change;
1065 inline_autocomplete_text_.clear();
1066 view_->OnInlineAutocompleteTextCleared();
1068 if (control_key_state_ == DOWN_WITHOUT_CHANGE) {
1069 // Arrowing around the popup cancels control-enter.
1070 control_key_state_ = DOWN_WITH_CHANGE;
1071 // Now things are a bit screwy: the desired_tld has changed, but if we
1072 // update the popup, the new order of entries won't match the old, so the
1073 // user's selection gets screwy; and if we don't update the popup, and the
1074 // user reverts, then the selected item will be as if control is still
1075 // pressed, even though maybe it isn't any more. There is no obvious
1076 // right answer here :(
1078 view_->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text),
1079 save_original_selection, true);
1083 bool call_controller_onchanged = true;
1084 inline_autocomplete_text_ = text;
1085 if (inline_autocomplete_text_.empty())
1086 view_->OnInlineAutocompleteTextCleared();
1088 const base::string16& user_text =
1089 user_input_in_progress_ ? user_text_ : permanent_text_;
1090 if (keyword_state_changed && KeywordIsSelected()) {
1091 // If we reach here, the user most likely entered keyword mode by inserting
1092 // a space between a keyword name and a search string (as pressing space or
1093 // tab after the keyword name alone would have been be handled in
1094 // MaybeAcceptKeywordBySpace() by calling AcceptKeyword(), which won't reach
1095 // here). In this case, we don't want to call
1096 // OnInlineAutocompleteTextMaybeChanged() as normal, because that will
1097 // correctly change the text (to the search string alone) but move the caret
1098 // to the end of the string; instead we want the caret at the start of the
1099 // search string since that's where it was in the original input. So we set
1100 // the text and caret position directly.
1102 // It may also be possible to reach here if we're reverting from having
1103 // temporary text back to a default match that's a keyword search, but in
1104 // that case the RevertTemporaryText() call below will reset the caret or
1105 // selection correctly so the caret positioning we do here won't matter.
1106 view_->SetWindowTextAndCaretPos(DisplayTextFromUserText(user_text), 0,
1108 } else if (view_->OnInlineAutocompleteTextMaybeChanged(
1109 DisplayTextFromUserText(user_text + inline_autocomplete_text_),
1110 DisplayTextFromUserText(user_text).length())) {
1111 call_controller_onchanged = false;
1114 // If |has_temporary_text_| is true, then we previously had a manual selection
1115 // but now don't (or |destination_for_temporary_text_change| would have been
1116 // non-NULL). This can happen when deleting the selected item in the popup.
1117 // In this case, we've already reverted the popup to the default match, so we
1118 // need to revert ourselves as well.
1119 if (has_temporary_text_) {
1120 RevertTemporaryText(false);
1121 call_controller_onchanged = false;
1124 // We need to invoke OnChanged in case the destination url changed (as could
1125 // happen when control is toggled).
1126 if (call_controller_onchanged)
1130 bool OmniboxEditModel::OnAfterPossibleChange(const base::string16& old_text,
1131 const base::string16& new_text,
1132 size_t selection_start,
1133 size_t selection_end,
1134 bool selection_differs,
1136 bool just_deleted_text,
1137 bool allow_keyword_ui_change) {
1138 // Update the paste state as appropriate: if we're just finishing a paste
1139 // that replaced all the text, preserve that information; otherwise, if we've
1140 // made some other edit, clear paste tracking.
1141 if (paste_state_ == PASTING)
1142 paste_state_ = PASTED;
1143 else if (text_differs)
1144 paste_state_ = NONE;
1146 if (text_differs || selection_differs) {
1147 // Record current focus state for this input if we haven't already.
1148 if (focus_source_ == INVALID) {
1149 // We should generally expect the omnibox to have focus at this point, but
1150 // it doesn't always on Linux. This is because, unlike other platforms,
1151 // right clicking in the omnibox on Linux doesn't focus it. So pasting via
1152 // right-click can change the contents without focusing the omnibox.
1153 // TODO(samarth): fix Linux focus behavior and add a DCHECK here to
1154 // check that the omnibox does have focus.
1155 focus_source_ = (focus_state_ == OMNIBOX_FOCUS_INVISIBLE) ?
1159 // Restore caret visibility whenever the user changes text or selection in
1161 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_TYPING);
1164 // Modifying the selection counts as accepting the autocompleted text.
1165 const bool user_text_changed =
1166 text_differs || (selection_differs && !inline_autocomplete_text_.empty());
1168 // If something has changed while the control key is down, prevent
1169 // "ctrl-enter" until the control key is released.
1170 if ((text_differs || selection_differs) &&
1171 (control_key_state_ == DOWN_WITHOUT_CHANGE))
1172 control_key_state_ = DOWN_WITH_CHANGE;
1174 if (!user_text_changed)
1177 // If the user text has not changed, we do not want to change the model's
1178 // state associated with the text. Otherwise, we can get surprising behavior
1179 // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983
1180 InternalSetUserText(UserTextFromDisplayText(new_text));
1181 has_temporary_text_ = false;
1183 // Track when the user has deleted text so we won't allow inline
1185 just_deleted_text_ = just_deleted_text;
1187 if (user_input_in_progress_ && user_text_.empty()) {
1188 // Log cases where the user started editing and then subsequently cleared
1189 // all the text. Note that this explicitly doesn't catch cases like
1190 // "hit ctrl-l to select whole edit contents, then hit backspace", because
1191 // in such cases, |user_input_in_progress| won't be true here.
1192 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
1193 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING,
1194 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
1197 const bool no_selection = selection_start == selection_end;
1199 // Update the popup for the change, in the process changing to keyword mode
1200 // if the user hit space in mid-string after a keyword.
1201 // |allow_exact_keyword_match_| will be used by StartAutocomplete() method,
1202 // which will be called by |view_->UpdatePopup()|; so after that returns we
1203 // can safely reset this flag.
1204 allow_exact_keyword_match_ = text_differs && allow_keyword_ui_change &&
1205 !just_deleted_text && no_selection &&
1206 CreatedKeywordSearchByInsertingSpaceInMiddle(old_text, user_text_,
1208 if (allow_exact_keyword_match_) {
1209 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram,
1210 ENTERED_KEYWORD_MODE_VIA_SPACE_IN_MIDDLE,
1211 ENTERED_KEYWORD_MODE_NUM_ITEMS);
1213 view_->UpdatePopup();
1214 allow_exact_keyword_match_ = false;
1216 // Change to keyword mode if the user is now pressing space after a keyword
1217 // name. Note that if this is the case, then even if there was no keyword
1218 // hint when we entered this function (e.g. if the user has used space to
1219 // replace some selected text that was adjoined to this keyword), there will
1220 // be one now because of the call to UpdatePopup() above; so it's safe for
1221 // MaybeAcceptKeywordBySpace() to look at |keyword_| and |is_keyword_hint_| to
1222 // determine what keyword, if any, is applicable.
1224 // If MaybeAcceptKeywordBySpace() accepts the keyword and returns true, that
1225 // will have updated our state already, so in that case we don't also return
1226 // true from this function.
1227 return !(text_differs && allow_keyword_ui_change && !just_deleted_text &&
1228 no_selection && (selection_start == user_text_.length()) &&
1229 MaybeAcceptKeywordBySpace(user_text_));
1232 // TODO(beaudoin): Merge OnPopupDataChanged with this method once the popup
1233 // handling has completely migrated to omnibox_controller.
1234 void OmniboxEditModel::OnCurrentMatchChanged() {
1235 has_temporary_text_ = false;
1237 const AutocompleteMatch& match = omnibox_controller_->current_match();
1239 // We store |keyword| and |is_keyword_hint| in temporary variables since
1240 // OnPopupDataChanged use their previous state to detect changes.
1241 base::string16 keyword;
1242 bool is_keyword_hint;
1243 match.GetKeywordUIState(profile_, &keyword, &is_keyword_hint);
1245 popup_model()->OnResultChanged();
1246 // OnPopupDataChanged() resets OmniboxController's |current_match_| early
1247 // on. Therefore, copy match.inline_autocompletion to a temp to preserve
1248 // its value across the entire call.
1249 const base::string16 inline_autocompletion(match.inline_autocompletion);
1250 OnPopupDataChanged(inline_autocompletion, NULL, keyword, is_keyword_hint);
1253 InstantController* OmniboxEditModel::GetInstantController() const {
1254 return controller_->GetInstant();
1258 const char OmniboxEditModel::kCutOrCopyAllTextHistogram[] =
1259 "Omnibox.CutOrCopyAllText";
1261 bool OmniboxEditModel::query_in_progress() const {
1262 return !autocomplete_controller()->done();
1265 void OmniboxEditModel::InternalSetUserText(const base::string16& text) {
1267 just_deleted_text_ = false;
1268 inline_autocomplete_text_.clear();
1269 view_->OnInlineAutocompleteTextCleared();
1272 bool OmniboxEditModel::KeywordIsSelected() const {
1273 return !is_keyword_hint_ && !keyword_.empty();
1276 void OmniboxEditModel::ClearPopupKeywordMode() const {
1277 omnibox_controller_->ClearPopupKeywordMode();
1280 base::string16 OmniboxEditModel::DisplayTextFromUserText(
1281 const base::string16& text) const {
1282 return KeywordIsSelected() ?
1283 KeywordProvider::SplitReplacementStringFromInput(text, false) : text;
1286 base::string16 OmniboxEditModel::UserTextFromDisplayText(
1287 const base::string16& text) const {
1288 return KeywordIsSelected() ? (keyword_ + base::char16(' ') + text) : text;
1291 void OmniboxEditModel::GetInfoForCurrentText(AutocompleteMatch* match,
1292 GURL* alternate_nav_url) const {
1293 DCHECK(match != NULL);
1295 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(
1297 // Any time the user hits enter on the unchanged omnibox, we should reload.
1298 // When we're not extracting search terms, AcceptInput() will take care of
1299 // this (see code referring to PAGE_TRANSITION_RELOAD there), but when we're
1300 // extracting search terms, the conditionals there won't fire, so we
1301 // explicitly set up a match that will reload here.
1303 // It's important that we fetch the current visible URL to reload instead of
1304 // just getting a "search what you typed" URL from
1305 // SearchProvider::CreateSearchSuggestion(), since the user may be in a
1306 // non-default search mode such as image search.
1307 match->type = AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED;
1308 match->destination_url =
1309 delegate_->GetNavigationController().GetVisibleEntry()->GetURL();
1310 match->transition = content::PAGE_TRANSITION_RELOAD;
1311 } else if (query_in_progress() ||
1312 (popup_model() && popup_model()->IsOpen())) {
1313 if (query_in_progress()) {
1314 // It's technically possible for |result| to be empty if no provider
1315 // returns a synchronous result but the query has not completed
1316 // synchronously; pratically, however, that should never actually happen.
1317 if (result().empty())
1319 // The user cannot have manually selected a match, or the query would have
1320 // stopped. So the default match must be the desired selection.
1321 *match = *result().default_match();
1323 // If there are no results, the popup should be closed, so we shouldn't
1324 // have gotten here.
1325 CHECK(!result().empty());
1326 CHECK(popup_model()->selected_line() < result().size());
1327 *match = result().match_at(popup_model()->selected_line());
1329 if (alternate_nav_url &&
1330 (!popup_model() || popup_model()->manually_selected_match().empty()))
1331 *alternate_nav_url = result().alternate_nav_url();
1333 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
1334 UserTextFromDisplayText(view_->GetText()), KeywordIsSelected(), true,
1335 ClassifyPage(), match, alternate_nav_url);
1339 void OmniboxEditModel::RevertTemporaryText(bool revert_popup) {
1340 // The user typed something, then selected a different item. Restore the
1341 // text they typed and change back to the default item.
1342 // NOTE: This purposefully does not reset paste_state_.
1343 just_deleted_text_ = false;
1344 has_temporary_text_ = false;
1346 if (revert_popup && popup_model())
1347 popup_model()->ResetToDefaultMatch();
1348 view_->OnRevertTemporaryText();
1351 bool OmniboxEditModel::MaybeAcceptKeywordBySpace(
1352 const base::string16& new_text) {
1353 size_t keyword_length = new_text.length() - 1;
1354 return (paste_state_ == NONE) && is_keyword_hint_ && !keyword_.empty() &&
1355 inline_autocomplete_text_.empty() &&
1356 (keyword_.length() == keyword_length) &&
1357 IsSpaceCharForAcceptingKeyword(new_text[keyword_length]) &&
1358 !new_text.compare(0, keyword_length, keyword_, 0, keyword_length) &&
1359 AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_SPACE_AT_END);
1362 bool OmniboxEditModel::CreatedKeywordSearchByInsertingSpaceInMiddle(
1363 const base::string16& old_text,
1364 const base::string16& new_text,
1365 size_t caret_position) const {
1366 DCHECK_GE(new_text.length(), caret_position);
1368 // Check simple conditions first.
1369 if ((paste_state_ != NONE) || (caret_position < 2) ||
1370 (old_text.length() < caret_position) ||
1371 (new_text.length() == caret_position))
1373 size_t space_position = caret_position - 1;
1374 if (!IsSpaceCharForAcceptingKeyword(new_text[space_position]) ||
1375 IsWhitespace(new_text[space_position - 1]) ||
1376 new_text.compare(0, space_position, old_text, 0, space_position) ||
1377 !new_text.compare(space_position, new_text.length() - space_position,
1378 old_text, space_position,
1379 old_text.length() - space_position)) {
1383 // Then check if the text before the inserted space matches a keyword.
1384 base::string16 keyword;
1385 TrimWhitespace(new_text.substr(0, space_position), TRIM_LEADING, &keyword);
1386 return !keyword.empty() && !autocomplete_controller()->keyword_provider()->
1387 GetKeywordForText(keyword).empty();
1391 bool OmniboxEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c) {
1393 case 0x0020: // Space
1394 case 0x3000: // Ideographic Space
1401 AutocompleteInput::PageClassification OmniboxEditModel::ClassifyPage() const {
1402 if (!delegate_->CurrentPageExists())
1403 return AutocompleteInput::OTHER;
1404 if (delegate_->IsInstantNTP()) {
1405 // Note that we treat OMNIBOX as the source if focus_source_ is INVALID,
1406 // i.e., if input isn't actually in progress.
1407 return (focus_source_ == FAKEBOX) ?
1408 AutocompleteInput::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS :
1409 AutocompleteInput::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS;
1411 const GURL& gurl = delegate_->GetURL();
1412 if (!gurl.is_valid())
1413 return AutocompleteInput::INVALID_SPEC;
1414 const std::string& url = gurl.spec();
1415 if (url == chrome::kChromeUINewTabURL)
1416 return AutocompleteInput::NTP;
1417 if (url == content::kAboutBlankURL)
1418 return AutocompleteInput::BLANK;
1419 if (url == profile()->GetPrefs()->GetString(prefs::kHomePage))
1420 return AutocompleteInput::HOME_PAGE;
1421 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(true))
1422 return AutocompleteInput::SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT;
1423 if (delegate_->IsSearchResultsPage())
1424 return AutocompleteInput::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT;
1425 return AutocompleteInput::OTHER;
1428 void OmniboxEditModel::ClassifyStringForPasteAndGo(
1429 const base::string16& text,
1430 AutocompleteMatch* match,
1431 GURL* alternate_nav_url) const {
1433 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
1434 text, false, false, ClassifyPage(), match, alternate_nav_url);
1437 void OmniboxEditModel::SetFocusState(OmniboxFocusState state,
1438 OmniboxFocusChangeReason reason) {
1439 if (state == focus_state_)
1442 InstantController* instant = GetInstantController();
1444 instant->OmniboxFocusChanged(state, reason, NULL);
1446 // Update state and notify view if the omnibox has focus and the caret
1447 // visibility changed.
1448 const bool was_caret_visible = is_caret_visible();
1449 focus_state_ = state;
1450 if (focus_state_ != OMNIBOX_FOCUS_NONE &&
1451 is_caret_visible() != was_caret_visible)
1452 view_->ApplyCaretVisibility();