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_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/net/url_fixer_upper.h"
58 #include "chrome/common/pref_names.h"
59 #include "chrome/common/url_constants.h"
60 #include "content/public/browser/navigation_controller.h"
61 #include "content/public/browser/navigation_entry.h"
62 #include "content/public/browser/notification_service.h"
63 #include "content/public/browser/render_view_host.h"
64 #include "content/public/browser/user_metrics.h"
65 #include "extensions/common/constants.h"
66 #include "ui/gfx/image/image.h"
67 #include "url/url_util.h"
69 using predictors::AutocompleteActionPredictor;
72 // Helpers --------------------------------------------------------------------
76 // Histogram name which counts the number of times that the user text is
77 // cleared. IME users are sometimes in the situation that IME was
78 // unintentionally turned on and failed to input latin alphabets (ASCII
79 // characters) or the opposite case. In that case, users may delete all
80 // the text and the user text gets cleared. We'd like to measure how often
81 // this scenario happens.
83 // Note that since we don't currently correlate "text cleared" events with
84 // IME usage, this also captures many other cases where users clear the text;
85 // though it explicitly doesn't log deleting all the permanent text as
86 // the first action of an editing sequence (see comments in
87 // OnAfterPossibleChange()).
88 const char kOmniboxUserTextClearedHistogram[] = "Omnibox.UserTextCleared";
90 enum UserTextClearedType {
91 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING = 0,
92 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE = 1,
93 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS,
96 // Histogram name which counts the number of times the user enters
97 // keyword hint mode and via what method. The possible values are listed
98 // in the EnteredKeywordModeMethod enum which is defined in the .h file.
99 const char kEnteredKeywordModeHistogram[] = "Omnibox.EnteredKeywordMode";
101 // Histogram name which counts the number of milliseconds a user takes
102 // between focusing and editing the omnibox.
103 const char kFocusToEditTimeHistogram[] = "Omnibox.FocusToEditTime";
105 // Histogram name which counts the number of milliseconds a user takes
106 // between focusing and opening an omnibox match.
107 const char kFocusToOpenTimeHistogram[] = "Omnibox.FocusToOpenTime";
109 // Split the percentage match histograms into buckets based on the width of the
111 const int kPercentageMatchHistogramWidthBuckets[] = { 400, 700, 1200 };
113 void RecordPercentageMatchHistogram(const base::string16& old_text,
114 const base::string16& new_text,
115 bool url_replacement_active,
116 content::PageTransition transition,
118 size_t avg_length = (old_text.length() + new_text.length()) / 2;
121 if (!old_text.empty() && !new_text.empty()) {
122 size_t shorter_length = std::min(old_text.length(), new_text.length());
123 base::string16::const_iterator end(old_text.begin() + shorter_length);
124 base::string16::const_iterator mismatch(
125 std::mismatch(old_text.begin(), end, new_text.begin()).first);
126 size_t matching_characters = mismatch - old_text.begin();
127 percent = static_cast<float>(matching_characters) / avg_length * 100;
130 std::string histogram_name;
131 if (url_replacement_active) {
132 if (transition == content::PAGE_TRANSITION_TYPED) {
133 histogram_name = "InstantExtended.PercentageMatchV2_QuerytoURL";
134 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
136 histogram_name = "InstantExtended.PercentageMatchV2_QuerytoQuery";
137 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
140 if (transition == content::PAGE_TRANSITION_TYPED) {
141 histogram_name = "InstantExtended.PercentageMatchV2_URLtoURL";
142 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
144 histogram_name = "InstantExtended.PercentageMatchV2_URLtoQuery";
145 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
149 std::string suffix = "large";
150 for (size_t i = 0; i < arraysize(kPercentageMatchHistogramWidthBuckets);
152 if (omnibox_width < kPercentageMatchHistogramWidthBuckets[i]) {
153 suffix = base::IntToString(kPercentageMatchHistogramWidthBuckets[i]);
158 // Cannot rely on UMA histograms macro because the name of the histogram is
159 // generated dynamically.
160 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
161 histogram_name + "_" + suffix, 1, 101, 102,
162 base::Histogram::kUmaTargetedHistogramFlag);
163 counter->Add(percent);
169 // OmniboxEditModel::State ----------------------------------------------------
171 OmniboxEditModel::State::State(bool user_input_in_progress,
172 const base::string16& user_text,
173 const base::string16& gray_text,
174 const base::string16& keyword,
175 bool is_keyword_hint,
176 bool url_replacement_enabled,
177 OmniboxFocusState focus_state,
178 FocusSource focus_source)
179 : user_input_in_progress(user_input_in_progress),
180 user_text(user_text),
181 gray_text(gray_text),
183 is_keyword_hint(is_keyword_hint),
184 url_replacement_enabled(url_replacement_enabled),
185 focus_state(focus_state),
186 focus_source(focus_source) {
189 OmniboxEditModel::State::~State() {
193 // OmniboxEditModel -----------------------------------------------------------
195 OmniboxEditModel::OmniboxEditModel(OmniboxView* view,
196 OmniboxEditController* controller,
199 controller_(controller),
200 focus_state_(OMNIBOX_FOCUS_NONE),
201 focus_source_(INVALID),
202 user_input_in_progress_(false),
203 user_input_since_focus_(true),
204 just_deleted_text_(false),
205 has_temporary_text_(false),
207 control_key_state_(UP),
208 is_keyword_hint_(false),
211 allow_exact_keyword_match_(false) {
212 omnibox_controller_.reset(new OmniboxController(this, profile));
213 delegate_.reset(new OmniboxCurrentPageDelegateImpl(controller, profile));
216 OmniboxEditModel::~OmniboxEditModel() {
219 const OmniboxEditModel::State OmniboxEditModel::GetStateForTabSwitch() {
220 // Like typing, switching tabs "accepts" the temporary text as the user
221 // text, because it makes little sense to have temporary text when the
223 if (user_input_in_progress_) {
224 // Weird edge case to match other browsers: if the edit is empty, revert to
225 // the permanent text (so the user can get it back easily) but select it (so
226 // on switching back, typing will "just work").
227 const base::string16 user_text(UserTextFromDisplayText(view_->GetText()));
228 if (user_text.empty()) {
229 base::AutoReset<bool> tmp(&in_revert_, true);
231 view_->SelectAll(true);
233 InternalSetUserText(user_text);
238 user_input_in_progress_, user_text_, view_->GetGrayTextAutocompletion(),
239 keyword_, is_keyword_hint_,
240 controller_->GetToolbarModel()->url_replacement_enabled(),
241 focus_state_, focus_source_);
244 void OmniboxEditModel::RestoreState(const State* state) {
245 // We need to update the permanent text correctly and revert the view
246 // regardless of whether there is saved state.
247 controller_->GetToolbarModel()->set_url_replacement_enabled(
248 !state || state->url_replacement_enabled);
249 permanent_text_ = controller_->GetToolbarModel()->GetText();
250 // Don't muck with the search term replacement state, as we've just set it
252 view_->RevertWithoutResettingSearchTermReplacement();
256 SetFocusState(state->focus_state, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH);
257 focus_source_ = state->focus_source;
258 // Restore any user editing.
259 if (state->user_input_in_progress) {
260 // NOTE: Be sure and set keyword-related state BEFORE invoking
261 // DisplayTextFromUserText(), as its result depends upon this state.
262 keyword_ = state->keyword;
263 is_keyword_hint_ = state->is_keyword_hint;
264 view_->SetUserText(state->user_text,
265 DisplayTextFromUserText(state->user_text), false);
266 view_->SetGrayTextAutocompletion(state->gray_text);
270 AutocompleteMatch OmniboxEditModel::CurrentMatch(
271 GURL* alternate_nav_url) const {
272 // If we have a valid match use it. Otherwise get one for the current text.
273 AutocompleteMatch match = omnibox_controller_->current_match();
275 if (!match.destination_url.is_valid()) {
276 GetInfoForCurrentText(&match, alternate_nav_url);
277 } else if (alternate_nav_url) {
278 *alternate_nav_url = AutocompleteResult::ComputeAlternateNavUrl(
279 autocomplete_controller()->input(), match);
284 bool OmniboxEditModel::UpdatePermanentText() {
285 SearchProvider* search_provider =
286 autocomplete_controller()->search_provider();
287 if (search_provider && delegate_->CurrentPageExists())
288 search_provider->set_current_page_url(delegate_->GetURL());
290 // When there's new permanent text, and the user isn't interacting with the
291 // omnibox, we want to revert the edit to show the new text. We could simply
292 // define "interacting" as "the omnibox has focus", but we still allow updates
293 // when the omnibox has focus as long as the user hasn't begun editing, isn't
294 // seeing zerosuggestions (because changing this text would require changing
295 // or hiding those suggestions), and hasn't toggled on "Show URL" (because
296 // this update will re-enable search term replacement, which will be annoying
297 // if the user is trying to copy the URL). When the omnibox doesn't have
298 // focus, we assume the user may have abandoned their interaction and it's
299 // always safe to change the text; this also prevents someone toggling "Show
300 // URL" (which sounds as if it might be persistent) from seeing just that URL
301 // forever afterwards.
303 // If the page is auto-committing gray text, however, we generally don't want
304 // to make any change to the edit. While auto-commits modify the underlying
305 // permanent URL, they're intended to have no effect on the user's editing
306 // process -- before and after the auto-commit, the omnibox should show the
307 // same user text and the same instant suggestion, even if the auto-commit
308 // happens while the edit doesn't have focus.
309 base::string16 new_permanent_text = controller_->GetToolbarModel()->GetText();
310 base::string16 gray_text = view_->GetGrayTextAutocompletion();
311 const bool visibly_changed_permanent_text =
312 (permanent_text_ != new_permanent_text) &&
314 (!user_input_in_progress_ &&
315 !(popup_model() && popup_model()->IsOpen()) &&
316 controller_->GetToolbarModel()->url_replacement_enabled())) &&
317 (gray_text.empty() ||
318 new_permanent_text != user_text_ + gray_text);
320 permanent_text_ = new_permanent_text;
321 return visibly_changed_permanent_text;
324 GURL OmniboxEditModel::PermanentURL() {
325 return URLFixerUpper::FixupURL(base::UTF16ToUTF8(permanent_text_),
329 void OmniboxEditModel::SetUserText(const base::string16& text) {
330 SetInputInProgress(true);
331 InternalSetUserText(text);
332 omnibox_controller_->InvalidateCurrentMatch();
334 has_temporary_text_ = false;
337 bool OmniboxEditModel::CommitSuggestedText() {
338 const base::string16 suggestion = view_->GetGrayTextAutocompletion();
339 if (suggestion.empty())
342 const base::string16 final_text = view_->GetText() + suggestion;
343 view_->OnBeforePossibleChange();
344 view_->SetWindowTextAndCaretPos(final_text, final_text.length(), false,
346 view_->OnAfterPossibleChange();
350 void OmniboxEditModel::OnChanged() {
351 // Don't call CurrentMatch() when there's no editing, as in this case we'll
352 // never actually use it. This avoids running the autocomplete providers (and
353 // any systems they then spin up) during startup.
354 const AutocompleteMatch& current_match = user_input_in_progress_ ?
355 CurrentMatch(NULL) : AutocompleteMatch();
357 AutocompleteActionPredictor::Action recommended_action =
358 AutocompleteActionPredictor::ACTION_NONE;
359 if (user_input_in_progress_) {
360 InstantSearchPrerenderer* prerenderer =
361 InstantSearchPrerenderer::GetForProfile(profile_);
363 prerenderer->IsAllowed(current_match, controller_->GetWebContents()) &&
364 popup_model()->IsOpen() && has_focus()) {
365 recommended_action = AutocompleteActionPredictor::ACTION_PRERENDER;
367 AutocompleteActionPredictor* action_predictor =
368 predictors::AutocompleteActionPredictorFactory::GetForProfile(
370 action_predictor->RegisterTransitionalMatches(user_text_, result());
371 // Confer with the AutocompleteActionPredictor to determine what action,
372 // if any, we should take. Get the recommended action here even if we
373 // don't need it so we can get stats for anyone who is opted in to UMA,
374 // but only get it if the user has actually typed something to avoid
375 // constructing it before it's needed. Note: This event is triggered as
376 // part of startup when the initial tab transitions to the start page.
378 action_predictor->RecommendAction(user_text_, current_match);
382 UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.Action",
384 AutocompleteActionPredictor::LAST_PREDICT_ACTION);
386 // Hide any suggestions we might be showing.
387 view_->SetGrayTextAutocompletion(base::string16());
389 switch (recommended_action) {
390 case AutocompleteActionPredictor::ACTION_PRERENDER:
391 // It's possible that there is no current page, for instance if the tab
392 // has been closed or on return from a sleep state.
393 // (http://crbug.com/105689)
394 if (!delegate_->CurrentPageExists())
396 // Ask for prerendering if the destination URL is different than the
398 if (current_match.destination_url != delegate_->GetURL())
399 delegate_->DoPrerender(current_match);
401 case AutocompleteActionPredictor::ACTION_PRECONNECT:
402 omnibox_controller_->DoPreconnect(current_match);
404 case AutocompleteActionPredictor::ACTION_NONE:
408 controller_->OnChanged();
411 void OmniboxEditModel::GetDataForURLExport(GURL* url,
412 base::string16* title,
413 gfx::Image* favicon) {
414 *url = CurrentMatch(NULL).destination_url;
415 if (*url == delegate_->GetURL()) {
416 content::WebContents* web_contents = controller_->GetWebContents();
417 *title = web_contents->GetTitle();
418 *favicon = FaviconTabHelper::FromWebContents(web_contents)->GetFavicon();
422 bool OmniboxEditModel::CurrentTextIsURL() const {
423 if (controller_->GetToolbarModel()->WouldReplaceURL())
426 // If current text is not composed of replaced search terms and
427 // !user_input_in_progress_, then permanent text is showing and should be a
428 // URL, so no further checking is needed. By avoiding checking in this case,
429 // we avoid calling into the autocomplete providers, and thus initializing the
430 // history system, as long as possible, which speeds startup.
431 if (!user_input_in_progress_)
434 return !AutocompleteMatch::IsSearchType(CurrentMatch(NULL).type);
437 AutocompleteMatch::Type OmniboxEditModel::CurrentTextType() const {
438 return CurrentMatch(NULL).type;
441 void OmniboxEditModel::AdjustTextForCopy(int sel_min,
442 bool is_all_selected,
443 base::string16* text,
448 // Do not adjust if selection did not start at the beginning of the field, or
449 // if the URL was omitted.
450 if ((sel_min != 0) || controller_->GetToolbarModel()->WouldReplaceURL())
453 if (!user_input_in_progress_ && is_all_selected) {
454 // The user selected all the text and has not edited it. Use the url as the
455 // text so that if the scheme was stripped it's added back, and the url
456 // is unescaped (we escape parts of the url for display).
457 *url = PermanentURL();
458 *text = base::UTF8ToUTF16(url->spec());
463 // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now
464 // the user is probably holding down control to cause the copy, which will
465 // screw up our calculation of the desired_tld.
466 AutocompleteMatch match;
467 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
468 *text, KeywordIsSelected(), true, ClassifyPage(), &match, NULL);
469 if (AutocompleteMatch::IsSearchType(match.type))
471 *url = match.destination_url;
473 // Prefix the text with 'http://' if the text doesn't start with 'http://',
474 // the text parses as a url with a scheme of http, the user selected the
475 // entire host, and the user hasn't edited the host or manually removed the
477 GURL perm_url(PermanentURL());
478 if (perm_url.SchemeIs(content::kHttpScheme) &&
479 url->SchemeIs(content::kHttpScheme) && perm_url.host() == url->host()) {
481 base::string16 http = base::ASCIIToUTF16(content::kHttpScheme) +
482 base::ASCIIToUTF16(content::kStandardSchemeSeparator);
483 if (text->compare(0, http.length(), http) != 0)
484 *text = http + *text;
488 void OmniboxEditModel::SetInputInProgress(bool in_progress) {
489 if (in_progress && !user_input_since_focus_) {
490 base::TimeTicks now = base::TimeTicks::Now();
491 DCHECK(last_omnibox_focus_ <= now);
492 UMA_HISTOGRAM_TIMES(kFocusToEditTimeHistogram, now - last_omnibox_focus_);
493 user_input_since_focus_ = true;
496 if (user_input_in_progress_ == in_progress)
499 user_input_in_progress_ = in_progress;
500 if (user_input_in_progress_) {
501 time_user_first_modified_omnibox_ = base::TimeTicks::Now();
502 content::RecordAction(base::UserMetricsAction("OmniboxInputInProgress"));
503 autocomplete_controller()->ResetSession();
506 // The following code handles two cases:
507 // * For HIDE_ON_USER_INPUT, it hides the chip when user input begins.
508 // * For HIDE_ON_MOUSE_RELEASE, which only hides the chip on mouse release if
509 // the omnibox is empty, it handles the "omnibox was not empty" case by
510 // acting like HIDE_ON_USER_INPUT.
511 if (chrome::ShouldDisplayOriginChipV2() && in_progress)
512 controller()->GetToolbarModel()->set_origin_chip_enabled(false);
514 controller_->GetToolbarModel()->set_input_in_progress(in_progress);
515 controller_->Update(NULL);
517 if (user_input_in_progress_ || !in_revert_)
518 delegate_->OnInputStateChanged();
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 UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngineType",
788 TemplateURLPrepopulateData::GetEngineType(*template_url),
792 // Get the current text before we call RevertAll() which will clear it.
793 base::string16 current_text = view_->GetText();
795 if (disposition != NEW_BACKGROUND_TAB) {
796 base::AutoReset<bool> tmp(&in_revert_, true);
797 view_->RevertAll(); // Revert the box to its unedited state.
800 if (match.type == AutocompleteMatchType::EXTENSION_APP) {
801 ExtensionAppProvider::LaunchAppFromOmnibox(match, profile_, disposition);
802 observer->OnSuccessfulNavigation();
804 RecordPercentageMatchHistogram(
805 permanent_text_, current_text,
806 controller_->GetToolbarModel()->WouldReplaceURL(),
807 match.transition, view_->GetWidth());
809 // Track whether the destination URL sends us to a search results page
810 // using the default search provider.
811 if (TemplateURLServiceFactory::GetForProfile(profile_)->
812 IsSearchResultsPageFromDefaultSearchProvider(match.destination_url)) {
813 content::RecordAction(
814 base::UserMetricsAction("OmniboxDestinationURLIsSearchOnDSP"));
817 if (match.destination_url.is_valid()) {
818 // This calls RevertAll again.
819 base::AutoReset<bool> tmp(&in_revert_, true);
820 controller_->OnAutocompleteAccept(
821 match.destination_url, disposition,
822 content::PageTransitionFromInt(
823 match.transition | content::PAGE_TRANSITION_FROM_ADDRESS_BAR));
824 if (observer->load_state() != OmniboxNavigationObserver::LOAD_NOT_SEEN)
825 ignore_result(observer.release()); // The observer will delete itself.
830 RecordBookmarkLaunch(NULL, BOOKMARK_LAUNCH_LOCATION_OMNIBOX);
833 bool OmniboxEditModel::AcceptKeyword(EnteredKeywordModeMethod entered_method) {
834 DCHECK(is_keyword_hint_ && !keyword_.empty());
836 autocomplete_controller()->Stop(false);
837 is_keyword_hint_ = false;
839 if (popup_model() && popup_model()->IsOpen())
840 popup_model()->SetSelectedLineState(OmniboxPopupModel::KEYWORD);
842 StartAutocomplete(false, true);
844 // Ensure the current selection is saved before showing keyword mode
845 // so that moving to another line and then reverting the text will restore
846 // the current state properly.
847 bool save_original_selection = !has_temporary_text_;
848 has_temporary_text_ = true;
849 view_->OnTemporaryTextMaybeChanged(
850 DisplayTextFromUserText(CurrentMatch(NULL).fill_into_edit),
851 save_original_selection, true);
853 content::RecordAction(base::UserMetricsAction("AcceptedKeywordHint"));
854 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram, entered_method,
855 ENTERED_KEYWORD_MODE_NUM_ITEMS);
860 void OmniboxEditModel::AcceptTemporaryTextAsUserText() {
861 InternalSetUserText(UserTextFromDisplayText(view_->GetText()));
862 has_temporary_text_ = false;
864 if (user_input_in_progress_ || !in_revert_)
865 delegate_->OnInputStateChanged();
868 void OmniboxEditModel::ClearKeyword(const base::string16& visible_text) {
869 autocomplete_controller()->Stop(false);
870 omnibox_controller_->ClearPopupKeywordMode();
872 const base::string16 window_text(keyword_ + visible_text);
874 // Only reset the result if the edit text has changed since the
875 // keyword was accepted, or if the popup is closed.
876 if (just_deleted_text_ || !visible_text.empty() ||
877 !(popup_model() && popup_model()->IsOpen())) {
878 view_->OnBeforePossibleChange();
879 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
882 is_keyword_hint_ = false;
883 view_->OnAfterPossibleChange();
884 just_deleted_text_ = true; // OnAfterPossibleChange() fails to clear this
885 // since the edit contents have actually grown
888 is_keyword_hint_ = true;
889 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
894 void OmniboxEditModel::OnSetFocus(bool control_down) {
895 last_omnibox_focus_ = base::TimeTicks::Now();
896 user_input_since_focus_ = false;
898 // If the omnibox lost focus while the caret was hidden and then regained
899 // focus, OnSetFocus() is called and should restore visibility. Note that
900 // focus can be regained without an accompanying call to
901 // OmniboxView::SetFocus(), e.g. by tabbing in.
902 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_EXPLICIT);
903 control_key_state_ = control_down ? DOWN_WITHOUT_CHANGE : UP;
905 // Try to get ZeroSuggest suggestions if a page is loaded and the user has
906 // not been typing in the omnibox. The |user_input_in_progress_| check is
907 // used to detect the case where this function is called after right-clicking
908 // in the omnibox and selecting paste in Linux (in which case we actually get
909 // the OnSetFocus() call after the process of handling the paste has kicked
911 // TODO(hfung): Remove this when crbug/271590 is fixed.
912 if (delegate_->CurrentPageExists() && !user_input_in_progress_) {
913 // TODO(jered): We may want to merge this into Start() and just call that
914 // here rather than having a special entry point for zero-suggest. Note
915 // that we avoid PermanentURL() here because it's not guaranteed to give us
916 // the actual underlying current URL, e.g. if we're on the NTP and the
917 // |permanent_text_| is empty.
918 autocomplete_controller()->StartZeroSuggest(AutocompleteInput(
919 permanent_text_, base::string16::npos, base::string16(),
920 delegate_->GetURL(), ClassifyPage(), false, false, true,
921 AutocompleteInput::ALL_MATCHES));
924 if (user_input_in_progress_ || !in_revert_)
925 delegate_->OnInputStateChanged();
928 void OmniboxEditModel::SetCaretVisibility(bool visible) {
929 // Caret visibility only matters if the omnibox has focus.
930 if (focus_state_ != OMNIBOX_FOCUS_NONE) {
931 SetFocusState(visible ? OMNIBOX_FOCUS_VISIBLE : OMNIBOX_FOCUS_INVISIBLE,
932 OMNIBOX_FOCUS_CHANGE_EXPLICIT);
936 void OmniboxEditModel::OnWillKillFocus(gfx::NativeView view_gaining_focus) {
937 if (user_input_in_progress_ || !in_revert_)
938 delegate_->OnInputStateChanged();
941 void OmniboxEditModel::OnKillFocus() {
942 SetFocusState(OMNIBOX_FOCUS_NONE, OMNIBOX_FOCUS_CHANGE_EXPLICIT);
943 focus_source_ = INVALID;
944 control_key_state_ = UP;
948 bool OmniboxEditModel::OnEscapeKeyPressed() {
949 const AutocompleteMatch& match = CurrentMatch(NULL);
950 if (has_temporary_text_) {
951 if (match.destination_url != original_url_) {
952 RevertTemporaryText(true);
957 // We do not clear the pending entry from the omnibox when a load is first
958 // stopped. If the user presses Escape while stopped, we clear it.
959 if (delegate_->CurrentPageExists() && !delegate_->IsLoading()) {
960 delegate_->GetNavigationController().DiscardNonCommittedEntries();
964 // When using the origin chip, hitting escape to revert all should either
965 // display the URL (when search term replacement would not be performed for
966 // this page) or the search terms (when it would). To accomplish this,
967 // we'll need to disable URL replacement iff it's currently enabled and
968 // search term replacement wouldn't normally happen.
969 bool should_disable_url_replacement =
970 controller_->GetToolbarModel()->url_replacement_enabled() &&
971 !controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(true);
973 // If the user wasn't editing, but merely had focus in the edit, allow <esc>
974 // to be processed as an accelerator, so it can still be used to stop a load.
975 // When the permanent text isn't all selected we still fall through to the
976 // SelectAll() call below so users can arrow around in the text and then hit
977 // <esc> to quickly replace all the text; this matches IE.
978 const bool has_zero_suggest_match = match.provider &&
979 (match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST);
980 if (!has_zero_suggest_match && !should_disable_url_replacement &&
981 !user_input_in_progress_ && view_->IsSelectAll())
984 if (!user_text_.empty()) {
985 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
986 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE,
987 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
990 if (should_disable_url_replacement) {
991 controller_->GetToolbarModel()->set_url_replacement_enabled(false);
992 UpdatePermanentText();
994 view_->RevertWithoutResettingSearchTermReplacement();
995 view_->SelectAll(true);
999 void OmniboxEditModel::OnControlKeyChanged(bool pressed) {
1000 if (pressed == (control_key_state_ == UP))
1001 control_key_state_ = pressed ? DOWN_WITHOUT_CHANGE : UP;
1004 void OmniboxEditModel::OnPaste() {
1005 UMA_HISTOGRAM_COUNTS("Omnibox.Paste", 1);
1006 paste_state_ = PASTING;
1009 void OmniboxEditModel::OnUpOrDownKeyPressed(int count) {
1010 // NOTE: This purposefully doesn't trigger any code that resets paste_state_.
1011 if (popup_model() && popup_model()->IsOpen()) {
1012 // The popup is open, so the user should be able to interact with it
1014 popup_model()->Move(count);
1018 if (!query_in_progress()) {
1019 // The popup is neither open nor working on a query already. So, start an
1020 // autocomplete query for the current text. This also sets
1021 // user_input_in_progress_ to true, which we want: if the user has started
1022 // to interact with the popup, changing the permanent_text_ shouldn't change
1023 // the displayed text.
1024 // Note: This does not force the popup to open immediately.
1025 // TODO(pkasting): We should, in fact, force this particular query to open
1026 // the popup immediately.
1027 if (!user_input_in_progress_)
1028 InternalSetUserText(permanent_text_);
1029 view_->UpdatePopup();
1033 // TODO(pkasting): The popup is working on a query but is not open. We should
1034 // force it to open immediately.
1037 void OmniboxEditModel::OnPopupDataChanged(
1038 const base::string16& text,
1039 GURL* destination_for_temporary_text_change,
1040 const base::string16& keyword,
1041 bool is_keyword_hint) {
1042 // The popup changed its data, the match in the controller is no longer valid.
1043 omnibox_controller_->InvalidateCurrentMatch();
1045 // Update keyword/hint-related local state.
1046 bool keyword_state_changed = (keyword_ != keyword) ||
1047 ((is_keyword_hint_ != is_keyword_hint) && !keyword.empty());
1048 if (keyword_state_changed) {
1050 is_keyword_hint_ = is_keyword_hint;
1052 // |is_keyword_hint_| should always be false if |keyword_| is empty.
1053 DCHECK(!keyword_.empty() || !is_keyword_hint_);
1056 // Handle changes to temporary text.
1057 if (destination_for_temporary_text_change != NULL) {
1058 const bool save_original_selection = !has_temporary_text_;
1059 if (save_original_selection) {
1060 // Save the original selection and URL so it can be reverted later.
1061 has_temporary_text_ = true;
1062 original_url_ = *destination_for_temporary_text_change;
1063 inline_autocomplete_text_.clear();
1064 view_->OnInlineAutocompleteTextCleared();
1066 if (control_key_state_ == DOWN_WITHOUT_CHANGE) {
1067 // Arrowing around the popup cancels control-enter.
1068 control_key_state_ = DOWN_WITH_CHANGE;
1069 // Now things are a bit screwy: the desired_tld has changed, but if we
1070 // update the popup, the new order of entries won't match the old, so the
1071 // user's selection gets screwy; and if we don't update the popup, and the
1072 // user reverts, then the selected item will be as if control is still
1073 // pressed, even though maybe it isn't any more. There is no obvious
1074 // right answer here :(
1076 view_->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text),
1077 save_original_selection, true);
1081 bool call_controller_onchanged = true;
1082 inline_autocomplete_text_ = text;
1083 if (inline_autocomplete_text_.empty())
1084 view_->OnInlineAutocompleteTextCleared();
1086 const base::string16& user_text =
1087 user_input_in_progress_ ? user_text_ : permanent_text_;
1088 if (keyword_state_changed && KeywordIsSelected()) {
1089 // If we reach here, the user most likely entered keyword mode by inserting
1090 // a space between a keyword name and a search string (as pressing space or
1091 // tab after the keyword name alone would have been be handled in
1092 // MaybeAcceptKeywordBySpace() by calling AcceptKeyword(), which won't reach
1093 // here). In this case, we don't want to call
1094 // OnInlineAutocompleteTextMaybeChanged() as normal, because that will
1095 // correctly change the text (to the search string alone) but move the caret
1096 // to the end of the string; instead we want the caret at the start of the
1097 // search string since that's where it was in the original input. So we set
1098 // the text and caret position directly.
1100 // It may also be possible to reach here if we're reverting from having
1101 // temporary text back to a default match that's a keyword search, but in
1102 // that case the RevertTemporaryText() call below will reset the caret or
1103 // selection correctly so the caret positioning we do here won't matter.
1104 view_->SetWindowTextAndCaretPos(DisplayTextFromUserText(user_text), 0,
1106 } else if (view_->OnInlineAutocompleteTextMaybeChanged(
1107 DisplayTextFromUserText(user_text + inline_autocomplete_text_),
1108 DisplayTextFromUserText(user_text).length())) {
1109 call_controller_onchanged = false;
1112 // If |has_temporary_text_| is true, then we previously had a manual selection
1113 // but now don't (or |destination_for_temporary_text_change| would have been
1114 // non-NULL). This can happen when deleting the selected item in the popup.
1115 // In this case, we've already reverted the popup to the default match, so we
1116 // need to revert ourselves as well.
1117 if (has_temporary_text_) {
1118 RevertTemporaryText(false);
1119 call_controller_onchanged = false;
1122 // We need to invoke OnChanged in case the destination url changed (as could
1123 // happen when control is toggled).
1124 if (call_controller_onchanged)
1128 bool OmniboxEditModel::OnAfterPossibleChange(const base::string16& old_text,
1129 const base::string16& new_text,
1130 size_t selection_start,
1131 size_t selection_end,
1132 bool selection_differs,
1134 bool just_deleted_text,
1135 bool allow_keyword_ui_change) {
1136 // Update the paste state as appropriate: if we're just finishing a paste
1137 // that replaced all the text, preserve that information; otherwise, if we've
1138 // made some other edit, clear paste tracking.
1139 if (paste_state_ == PASTING)
1140 paste_state_ = PASTED;
1141 else if (text_differs)
1142 paste_state_ = NONE;
1144 if (text_differs || selection_differs) {
1145 // Record current focus state for this input if we haven't already.
1146 if (focus_source_ == INVALID) {
1147 // We should generally expect the omnibox to have focus at this point, but
1148 // it doesn't always on Linux. This is because, unlike other platforms,
1149 // right clicking in the omnibox on Linux doesn't focus it. So pasting via
1150 // right-click can change the contents without focusing the omnibox.
1151 // TODO(samarth): fix Linux focus behavior and add a DCHECK here to
1152 // check that the omnibox does have focus.
1153 focus_source_ = (focus_state_ == OMNIBOX_FOCUS_INVISIBLE) ?
1157 // Restore caret visibility whenever the user changes text or selection in
1159 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_TYPING);
1162 // Modifying the selection counts as accepting the autocompleted text.
1163 const bool user_text_changed =
1164 text_differs || (selection_differs && !inline_autocomplete_text_.empty());
1166 // If something has changed while the control key is down, prevent
1167 // "ctrl-enter" until the control key is released.
1168 if ((text_differs || selection_differs) &&
1169 (control_key_state_ == DOWN_WITHOUT_CHANGE))
1170 control_key_state_ = DOWN_WITH_CHANGE;
1172 if (!user_text_changed)
1175 // If the user text has not changed, we do not want to change the model's
1176 // state associated with the text. Otherwise, we can get surprising behavior
1177 // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983
1178 InternalSetUserText(UserTextFromDisplayText(new_text));
1179 has_temporary_text_ = false;
1181 // Track when the user has deleted text so we won't allow inline
1183 just_deleted_text_ = just_deleted_text;
1185 if (user_input_in_progress_ && user_text_.empty()) {
1186 // Log cases where the user started editing and then subsequently cleared
1187 // all the text. Note that this explicitly doesn't catch cases like
1188 // "hit ctrl-l to select whole edit contents, then hit backspace", because
1189 // in such cases, |user_input_in_progress| won't be true here.
1190 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
1191 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING,
1192 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
1195 const bool no_selection = selection_start == selection_end;
1197 // Update the popup for the change, in the process changing to keyword mode
1198 // if the user hit space in mid-string after a keyword.
1199 // |allow_exact_keyword_match_| will be used by StartAutocomplete() method,
1200 // which will be called by |view_->UpdatePopup()|; so after that returns we
1201 // can safely reset this flag.
1202 allow_exact_keyword_match_ = text_differs && allow_keyword_ui_change &&
1203 !just_deleted_text && no_selection &&
1204 CreatedKeywordSearchByInsertingSpaceInMiddle(old_text, user_text_,
1206 if (allow_exact_keyword_match_) {
1207 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram,
1208 ENTERED_KEYWORD_MODE_VIA_SPACE_IN_MIDDLE,
1209 ENTERED_KEYWORD_MODE_NUM_ITEMS);
1211 view_->UpdatePopup();
1212 allow_exact_keyword_match_ = false;
1214 // Change to keyword mode if the user is now pressing space after a keyword
1215 // name. Note that if this is the case, then even if there was no keyword
1216 // hint when we entered this function (e.g. if the user has used space to
1217 // replace some selected text that was adjoined to this keyword), there will
1218 // be one now because of the call to UpdatePopup() above; so it's safe for
1219 // MaybeAcceptKeywordBySpace() to look at |keyword_| and |is_keyword_hint_| to
1220 // determine what keyword, if any, is applicable.
1222 // If MaybeAcceptKeywordBySpace() accepts the keyword and returns true, that
1223 // will have updated our state already, so in that case we don't also return
1224 // true from this function.
1225 return !(text_differs && allow_keyword_ui_change && !just_deleted_text &&
1226 no_selection && (selection_start == user_text_.length()) &&
1227 MaybeAcceptKeywordBySpace(user_text_));
1230 // TODO(beaudoin): Merge OnPopupDataChanged with this method once the popup
1231 // handling has completely migrated to omnibox_controller.
1232 void OmniboxEditModel::OnCurrentMatchChanged() {
1233 has_temporary_text_ = false;
1235 const AutocompleteMatch& match = omnibox_controller_->current_match();
1237 // We store |keyword| and |is_keyword_hint| in temporary variables since
1238 // OnPopupDataChanged use their previous state to detect changes.
1239 base::string16 keyword;
1240 bool is_keyword_hint;
1241 match.GetKeywordUIState(profile_, &keyword, &is_keyword_hint);
1243 popup_model()->OnResultChanged();
1244 // OnPopupDataChanged() resets OmniboxController's |current_match_| early
1245 // on. Therefore, copy match.inline_autocompletion to a temp to preserve
1246 // its value across the entire call.
1247 const base::string16 inline_autocompletion(match.inline_autocompletion);
1248 OnPopupDataChanged(inline_autocompletion, NULL, keyword, is_keyword_hint);
1251 InstantController* OmniboxEditModel::GetInstantController() const {
1252 return controller_->GetInstant();
1256 const char OmniboxEditModel::kCutOrCopyAllTextHistogram[] =
1257 "Omnibox.CutOrCopyAllText";
1259 bool OmniboxEditModel::query_in_progress() const {
1260 return !autocomplete_controller()->done();
1263 void OmniboxEditModel::InternalSetUserText(const base::string16& text) {
1265 just_deleted_text_ = false;
1266 inline_autocomplete_text_.clear();
1267 view_->OnInlineAutocompleteTextCleared();
1270 bool OmniboxEditModel::KeywordIsSelected() const {
1271 return !is_keyword_hint_ && !keyword_.empty();
1274 void OmniboxEditModel::ClearPopupKeywordMode() const {
1275 omnibox_controller_->ClearPopupKeywordMode();
1278 base::string16 OmniboxEditModel::DisplayTextFromUserText(
1279 const base::string16& text) const {
1280 return KeywordIsSelected() ?
1281 KeywordProvider::SplitReplacementStringFromInput(text, false) : text;
1284 base::string16 OmniboxEditModel::UserTextFromDisplayText(
1285 const base::string16& text) const {
1286 return KeywordIsSelected() ? (keyword_ + base::char16(' ') + text) : text;
1289 void OmniboxEditModel::GetInfoForCurrentText(AutocompleteMatch* match,
1290 GURL* alternate_nav_url) const {
1291 DCHECK(match != NULL);
1293 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(
1295 // Any time the user hits enter on the unchanged omnibox, we should reload.
1296 // When we're not extracting search terms, AcceptInput() will take care of
1297 // this (see code referring to PAGE_TRANSITION_RELOAD there), but when we're
1298 // extracting search terms, the conditionals there won't fire, so we
1299 // explicitly set up a match that will reload here.
1301 // It's important that we fetch the current visible URL to reload instead of
1302 // just getting a "search what you typed" URL from
1303 // SearchProvider::CreateSearchSuggestion(), since the user may be in a
1304 // non-default search mode such as image search.
1305 match->type = AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED;
1306 match->destination_url =
1307 delegate_->GetNavigationController().GetVisibleEntry()->GetURL();
1308 match->transition = content::PAGE_TRANSITION_RELOAD;
1309 } else if (query_in_progress() ||
1310 (popup_model() && popup_model()->IsOpen())) {
1311 if (query_in_progress()) {
1312 // It's technically possible for |result| to be empty if no provider
1313 // returns a synchronous result but the query has not completed
1314 // synchronously; pratically, however, that should never actually happen.
1315 if (result().empty())
1317 // The user cannot have manually selected a match, or the query would have
1318 // stopped. So the default match must be the desired selection.
1319 *match = *result().default_match();
1321 // If there are no results, the popup should be closed, so we shouldn't
1322 // have gotten here.
1323 CHECK(!result().empty());
1324 CHECK(popup_model()->selected_line() < result().size());
1325 *match = result().match_at(popup_model()->selected_line());
1327 if (alternate_nav_url &&
1328 (!popup_model() || popup_model()->manually_selected_match().empty()))
1329 *alternate_nav_url = result().alternate_nav_url();
1331 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
1332 UserTextFromDisplayText(view_->GetText()), KeywordIsSelected(), true,
1333 ClassifyPage(), match, alternate_nav_url);
1337 void OmniboxEditModel::RevertTemporaryText(bool revert_popup) {
1338 // The user typed something, then selected a different item. Restore the
1339 // text they typed and change back to the default item.
1340 // NOTE: This purposefully does not reset paste_state_.
1341 just_deleted_text_ = false;
1342 has_temporary_text_ = false;
1344 if (revert_popup && popup_model())
1345 popup_model()->ResetToDefaultMatch();
1346 view_->OnRevertTemporaryText();
1349 bool OmniboxEditModel::MaybeAcceptKeywordBySpace(
1350 const base::string16& new_text) {
1351 size_t keyword_length = new_text.length() - 1;
1352 return (paste_state_ == NONE) && is_keyword_hint_ && !keyword_.empty() &&
1353 inline_autocomplete_text_.empty() &&
1354 (keyword_.length() == keyword_length) &&
1355 IsSpaceCharForAcceptingKeyword(new_text[keyword_length]) &&
1356 !new_text.compare(0, keyword_length, keyword_, 0, keyword_length) &&
1357 AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_SPACE_AT_END);
1360 bool OmniboxEditModel::CreatedKeywordSearchByInsertingSpaceInMiddle(
1361 const base::string16& old_text,
1362 const base::string16& new_text,
1363 size_t caret_position) const {
1364 DCHECK_GE(new_text.length(), caret_position);
1366 // Check simple conditions first.
1367 if ((paste_state_ != NONE) || (caret_position < 2) ||
1368 (old_text.length() < caret_position) ||
1369 (new_text.length() == caret_position))
1371 size_t space_position = caret_position - 1;
1372 if (!IsSpaceCharForAcceptingKeyword(new_text[space_position]) ||
1373 IsWhitespace(new_text[space_position - 1]) ||
1374 new_text.compare(0, space_position, old_text, 0, space_position) ||
1375 !new_text.compare(space_position, new_text.length() - space_position,
1376 old_text, space_position,
1377 old_text.length() - space_position)) {
1381 // Then check if the text before the inserted space matches a keyword.
1382 base::string16 keyword;
1383 base::TrimWhitespace(new_text.substr(0, space_position), base::TRIM_LEADING,
1385 return !keyword.empty() && !autocomplete_controller()->keyword_provider()->
1386 GetKeywordForText(keyword).empty();
1390 bool OmniboxEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c) {
1392 case 0x0020: // Space
1393 case 0x3000: // Ideographic Space
1400 AutocompleteInput::PageClassification OmniboxEditModel::ClassifyPage() const {
1401 if (!delegate_->CurrentPageExists())
1402 return AutocompleteInput::OTHER;
1403 if (delegate_->IsInstantNTP()) {
1404 // Note that we treat OMNIBOX as the source if focus_source_ is INVALID,
1405 // i.e., if input isn't actually in progress.
1406 return (focus_source_ == FAKEBOX) ?
1407 AutocompleteInput::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS :
1408 AutocompleteInput::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS;
1410 const GURL& gurl = delegate_->GetURL();
1411 if (!gurl.is_valid())
1412 return AutocompleteInput::INVALID_SPEC;
1413 const std::string& url = gurl.spec();
1414 if (url == chrome::kChromeUINewTabURL)
1415 return AutocompleteInput::NTP;
1416 if (url == content::kAboutBlankURL)
1417 return AutocompleteInput::BLANK;
1418 if (url == profile()->GetPrefs()->GetString(prefs::kHomePage))
1419 return AutocompleteInput::HOME_PAGE;
1420 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(true))
1421 return AutocompleteInput::SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT;
1422 if (delegate_->IsSearchResultsPage())
1423 return AutocompleteInput::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT;
1424 return AutocompleteInput::OTHER;
1427 void OmniboxEditModel::ClassifyStringForPasteAndGo(
1428 const base::string16& text,
1429 AutocompleteMatch* match,
1430 GURL* alternate_nav_url) const {
1432 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
1433 text, false, false, ClassifyPage(), match, alternate_nav_url);
1436 void OmniboxEditModel::SetFocusState(OmniboxFocusState state,
1437 OmniboxFocusChangeReason reason) {
1438 if (state == focus_state_)
1441 // Update state and notify view if the omnibox has focus and the caret
1442 // visibility changed.
1443 const bool was_caret_visible = is_caret_visible();
1444 focus_state_ = state;
1445 if (focus_state_ != OMNIBOX_FOCUS_NONE &&
1446 is_caret_visible() != was_caret_visible)
1447 view_->ApplyCaretVisibility();
1449 delegate_->OnFocusChanged(focus_state_, reason);