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_util.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "chrome/app/chrome_command_ids.h"
17 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
18 #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
19 #include "chrome/browser/autocomplete/autocomplete_input.h"
20 #include "chrome/browser/autocomplete/autocomplete_provider.h"
21 #include "chrome/browser/autocomplete/extension_app_provider.h"
22 #include "chrome/browser/autocomplete/history_url_provider.h"
23 #include "chrome/browser/autocomplete/keyword_provider.h"
24 #include "chrome/browser/autocomplete/search_provider.h"
25 #include "chrome/browser/bookmarks/bookmark_stats.h"
26 #include "chrome/browser/chrome_notification_types.h"
27 #include "chrome/browser/command_updater.h"
28 #include "chrome/browser/extensions/api/omnibox/omnibox_api.h"
29 #include "chrome/browser/favicon/favicon_tab_helper.h"
30 #include "chrome/browser/google/google_url_tracker.h"
31 #include "chrome/browser/net/predictor.h"
32 #include "chrome/browser/omnibox/omnibox_log.h"
33 #include "chrome/browser/predictors/autocomplete_action_predictor.h"
34 #include "chrome/browser/predictors/autocomplete_action_predictor_factory.h"
35 #include "chrome/browser/prerender/prerender_field_trial.h"
36 #include "chrome/browser/prerender/prerender_manager.h"
37 #include "chrome/browser/prerender/prerender_manager_factory.h"
38 #include "chrome/browser/profiles/profile.h"
39 #include "chrome/browser/search/search.h"
40 #include "chrome/browser/search_engines/template_url.h"
41 #include "chrome/browser/search_engines/template_url_prepopulate_data.h"
42 #include "chrome/browser/search_engines/template_url_service.h"
43 #include "chrome/browser/search_engines/template_url_service_factory.h"
44 #include "chrome/browser/sessions/session_tab_helper.h"
45 #include "chrome/browser/ui/browser_list.h"
46 #include "chrome/browser/ui/omnibox/omnibox_current_page_delegate_impl.h"
47 #include "chrome/browser/ui/omnibox/omnibox_edit_controller.h"
48 #include "chrome/browser/ui/omnibox/omnibox_navigation_observer.h"
49 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
50 #include "chrome/browser/ui/omnibox/omnibox_popup_view.h"
51 #include "chrome/browser/ui/omnibox/omnibox_view.h"
52 #include "chrome/browser/ui/search/instant_controller.h"
53 #include "chrome/browser/ui/search/search_tab_helper.h"
54 #include "chrome/browser/ui/toolbar/toolbar_model.h"
55 #include "chrome/common/chrome_switches.h"
56 #include "chrome/common/net/url_fixer_upper.h"
57 #include "chrome/common/pref_names.h"
58 #include "chrome/common/url_constants.h"
59 #include "content/public/browser/navigation_controller.h"
60 #include "content/public/browser/navigation_entry.h"
61 #include "content/public/browser/notification_service.h"
62 #include "content/public/browser/render_view_host.h"
63 #include "content/public/browser/user_metrics.h"
64 #include "extensions/common/constants.h"
65 #include "ui/gfx/image/image.h"
66 #include "url/url_util.h"
68 using predictors::AutocompleteActionPredictor;
71 // Helpers --------------------------------------------------------------------
75 // Histogram name which counts the number of times that the user text is
76 // cleared. IME users are sometimes in the situation that IME was
77 // unintentionally turned on and failed to input latin alphabets (ASCII
78 // characters) or the opposite case. In that case, users may delete all
79 // the text and the user text gets cleared. We'd like to measure how often
80 // this scenario happens.
82 // Note that since we don't currently correlate "text cleared" events with
83 // IME usage, this also captures many other cases where users clear the text;
84 // though it explicitly doesn't log deleting all the permanent text as
85 // the first action of an editing sequence (see comments in
86 // OnAfterPossibleChange()).
87 const char kOmniboxUserTextClearedHistogram[] = "Omnibox.UserTextCleared";
89 enum UserTextClearedType {
90 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING = 0,
91 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE = 1,
92 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS,
95 // Histogram name which counts the number of times the user enters
96 // keyword hint mode and via what method. The possible values are listed
97 // in the EnteredKeywordModeMethod enum which is defined in the .h file.
98 const char kEnteredKeywordModeHistogram[] = "Omnibox.EnteredKeywordMode";
100 // Histogram name which counts the number of milliseconds a user takes
101 // between focusing and editing the omnibox.
102 const char kFocusToEditTimeHistogram[] = "Omnibox.FocusToEditTime";
104 // Histogram name which counts the number of milliseconds a user takes
105 // between focusing and opening an omnibox match.
106 const char kFocusToOpenTimeHistogram[] = "Omnibox.FocusToOpenTime";
108 void RecordPercentageMatchHistogram(const string16& old_text,
109 const string16& new_text,
110 bool search_term_replacement_active,
111 content::PageTransition transition) {
112 size_t avg_length = (old_text.length() + new_text.length()) / 2;
115 if (!old_text.empty() && !new_text.empty()) {
116 size_t shorter_length = std::min(old_text.length(), new_text.length());
117 string16::const_iterator end(old_text.begin() + shorter_length);
118 string16::const_iterator mismatch(
119 std::mismatch(old_text.begin(), end, new_text.begin()).first);
120 size_t matching_characters = mismatch - old_text.begin();
121 percent = static_cast<float>(matching_characters) / avg_length * 100;
124 if (search_term_replacement_active) {
125 if (transition == content::PAGE_TRANSITION_TYPED) {
126 UMA_HISTOGRAM_PERCENTAGE(
127 "InstantExtended.PercentageMatchV2_QuerytoURL", percent);
129 UMA_HISTOGRAM_PERCENTAGE(
130 "InstantExtended.PercentageMatchV2_QuerytoQuery", percent);
133 if (transition == content::PAGE_TRANSITION_TYPED) {
134 UMA_HISTOGRAM_PERCENTAGE(
135 "InstantExtended.PercentageMatchV2_URLtoURL", percent);
137 UMA_HISTOGRAM_PERCENTAGE(
138 "InstantExtended.PercentageMatchV2_URLtoQuery", percent);
146 // OmniboxEditModel::State ----------------------------------------------------
148 OmniboxEditModel::State::State(bool user_input_in_progress,
149 const string16& user_text,
150 const string16& gray_text,
151 const string16& keyword,
152 bool is_keyword_hint,
153 bool search_term_replacement_enabled,
154 OmniboxFocusState focus_state,
155 FocusSource focus_source)
156 : user_input_in_progress(user_input_in_progress),
157 user_text(user_text),
158 gray_text(gray_text),
160 is_keyword_hint(is_keyword_hint),
161 search_term_replacement_enabled(search_term_replacement_enabled),
162 focus_state(focus_state),
163 focus_source(focus_source) {
166 OmniboxEditModel::State::~State() {
170 // OmniboxEditModel -----------------------------------------------------------
172 OmniboxEditModel::OmniboxEditModel(OmniboxView* view,
173 OmniboxEditController* controller,
176 controller_(controller),
177 focus_state_(OMNIBOX_FOCUS_NONE),
178 focus_source_(INVALID),
179 user_input_in_progress_(false),
180 user_input_since_focus_(true),
181 just_deleted_text_(false),
182 has_temporary_text_(false),
184 control_key_state_(UP),
185 is_keyword_hint_(false),
188 allow_exact_keyword_match_(false) {
189 omnibox_controller_.reset(new OmniboxController(this, profile));
190 delegate_.reset(new OmniboxCurrentPageDelegateImpl(controller, profile));
193 OmniboxEditModel::~OmniboxEditModel() {
196 const OmniboxEditModel::State OmniboxEditModel::GetStateForTabSwitch() {
197 // Like typing, switching tabs "accepts" the temporary text as the user
198 // text, because it makes little sense to have temporary text when the
200 if (user_input_in_progress_) {
201 // Weird edge case to match other browsers: if the edit is empty, revert to
202 // the permanent text (so the user can get it back easily) but select it (so
203 // on switching back, typing will "just work").
204 const string16 user_text(UserTextFromDisplayText(view_->GetText()));
205 if (user_text.empty()) {
206 base::AutoReset<bool> tmp(&in_revert_, true);
208 view_->SelectAll(true);
210 InternalSetUserText(user_text);
215 user_input_in_progress_, user_text_, view_->GetGrayTextAutocompletion(),
216 keyword_, is_keyword_hint_,
217 controller_->GetToolbarModel()->search_term_replacement_enabled(),
218 focus_state_, focus_source_);
221 void OmniboxEditModel::RestoreState(const State* state) {
222 // We need to update the permanent text correctly and revert the view
223 // regardless of whether there is saved state.
224 controller_->GetToolbarModel()->set_search_term_replacement_enabled(
225 !state || state->search_term_replacement_enabled);
226 permanent_text_ = controller_->GetToolbarModel()->GetText(true);
227 // Don't muck with the search term replacement state, as we've just set it
229 view_->RevertWithoutResettingSearchTermReplacement();
233 SetFocusState(state->focus_state, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH);
234 focus_source_ = state->focus_source;
235 // Restore any user editing.
236 if (state->user_input_in_progress) {
237 // NOTE: Be sure and set keyword-related state BEFORE invoking
238 // DisplayTextFromUserText(), as its result depends upon this state.
239 keyword_ = state->keyword;
240 is_keyword_hint_ = state->is_keyword_hint;
241 view_->SetUserText(state->user_text,
242 DisplayTextFromUserText(state->user_text), false);
243 view_->SetGrayTextAutocompletion(state->gray_text);
247 AutocompleteMatch OmniboxEditModel::CurrentMatch(
248 GURL* alternate_nav_url) const {
249 // If we have a valid match use it. Otherwise get one for the current text.
250 AutocompleteMatch match = omnibox_controller_->current_match();
252 if (!match.destination_url.is_valid()) {
253 GetInfoForCurrentText(&match, alternate_nav_url);
254 } else if (alternate_nav_url) {
255 *alternate_nav_url = AutocompleteResult::ComputeAlternateNavUrl(
256 autocomplete_controller()->input(), match);
261 bool OmniboxEditModel::UpdatePermanentText() {
262 // When there's new permanent text, and the user isn't interacting with the
263 // omnibox, we want to revert the edit to show the new text. We could simply
264 // define "interacting" as "the omnibox has focus", but we still allow updates
265 // when the omnibox has focus as long as the user hasn't begun editing, isn't
266 // seeing zerosuggestions (because changing this text would require changing
267 // or hiding those suggestions), and hasn't toggled on "Show URL" (because
268 // this update will re-enable search term replacement, which will be annoying
269 // if the user is trying to copy the URL). When the omnibox doesn't have
270 // focus, we assume the user may have abandoned their interaction and it's
271 // always safe to change the text; this also prevents someone toggling "Show
272 // URL" (which sounds as if it might be persistent) from seeing just that URL
273 // forever afterwards.
275 // If the page is auto-committing gray text, however, we generally don't want
276 // to make any change to the edit. While auto-commits modify the underlying
277 // permanent URL, they're intended to have no effect on the user's editing
278 // process -- before and after the auto-commit, the omnibox should show the
279 // same user text and the same instant suggestion, even if the auto-commit
280 // happens while the edit doesn't have focus.
281 string16 new_permanent_text = controller_->GetToolbarModel()->GetText(true);
282 string16 gray_text = view_->GetGrayTextAutocompletion();
283 const bool visibly_changed_permanent_text =
284 (permanent_text_ != new_permanent_text) &&
286 (!user_input_in_progress_ && !popup_model()->IsOpen() &&
287 controller_->GetToolbarModel()->search_term_replacement_enabled())) &&
288 (gray_text.empty() ||
289 new_permanent_text != user_text_ + gray_text);
291 permanent_text_ = new_permanent_text;
292 return visibly_changed_permanent_text;
295 GURL OmniboxEditModel::PermanentURL() {
296 return URLFixerUpper::FixupURL(UTF16ToUTF8(permanent_text_), std::string());
299 void OmniboxEditModel::SetUserText(const string16& text) {
300 SetInputInProgress(true);
301 InternalSetUserText(text);
302 omnibox_controller_->InvalidateCurrentMatch();
304 has_temporary_text_ = false;
307 bool OmniboxEditModel::CommitSuggestedText() {
308 const string16 suggestion = view_->GetGrayTextAutocompletion();
309 if (suggestion.empty())
312 const string16 final_text = view_->GetText() + suggestion;
313 view_->OnBeforePossibleChange();
314 view_->SetWindowTextAndCaretPos(final_text, final_text.length(), false,
316 view_->OnAfterPossibleChange();
320 void OmniboxEditModel::OnChanged() {
321 // Don't call CurrentMatch() when there's no editing, as in this case we'll
322 // never actually use it. This avoids running the autocomplete providers (and
323 // any systems they then spin up) during startup.
324 const AutocompleteMatch& current_match = user_input_in_progress_ ?
325 CurrentMatch(NULL) : AutocompleteMatch();
327 AutocompleteActionPredictor::Action recommended_action =
328 AutocompleteActionPredictor::ACTION_NONE;
329 AutocompleteActionPredictor* action_predictor = user_input_in_progress_ ?
330 predictors::AutocompleteActionPredictorFactory::GetForProfile(profile_) :
332 if (action_predictor) {
333 action_predictor->RegisterTransitionalMatches(user_text_, result());
334 // Confer with the AutocompleteActionPredictor to determine what action, if
335 // any, we should take. Get the recommended action here even if we don't
336 // need it so we can get stats for anyone who is opted in to UMA, but only
337 // get it if the user has actually typed something to avoid constructing it
338 // before it's needed. Note: This event is triggered as part of startup when
339 // the initial tab transitions to the start page.
341 action_predictor->RecommendAction(user_text_, current_match);
344 UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.Action",
346 AutocompleteActionPredictor::LAST_PREDICT_ACTION);
348 // Hide any suggestions we might be showing.
349 view_->SetGrayTextAutocompletion(string16());
351 switch (recommended_action) {
352 case AutocompleteActionPredictor::ACTION_PRERENDER:
353 // It's possible that there is no current page, for instance if the tab
354 // has been closed or on return from a sleep state.
355 // (http://crbug.com/105689)
356 if (!delegate_->CurrentPageExists())
358 // Ask for prerendering if the destination URL is different than the
360 if (current_match.destination_url != PermanentURL())
361 delegate_->DoPrerender(current_match);
363 case AutocompleteActionPredictor::ACTION_PRECONNECT:
364 omnibox_controller_->DoPreconnect(current_match);
366 case AutocompleteActionPredictor::ACTION_NONE:
370 controller_->OnChanged();
373 void OmniboxEditModel::GetDataForURLExport(GURL* url,
375 gfx::Image* favicon) {
376 *url = CurrentMatch(NULL).destination_url;
377 if (*url == URLFixerUpper::FixupURL(UTF16ToUTF8(permanent_text_),
379 content::WebContents* web_contents = controller_->GetWebContents();
380 *title = web_contents->GetTitle();
381 *favicon = FaviconTabHelper::FromWebContents(web_contents)->GetFavicon();
385 bool OmniboxEditModel::CurrentTextIsURL() const {
386 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(false))
389 // If current text is not composed of replaced search terms and
390 // !user_input_in_progress_, then permanent text is showing and should be a
391 // URL, so no further checking is needed. By avoiding checking in this case,
392 // we avoid calling into the autocomplete providers, and thus initializing the
393 // history system, as long as possible, which speeds startup.
394 if (!user_input_in_progress_)
397 return !AutocompleteMatch::IsSearchType(CurrentMatch(NULL).type);
400 AutocompleteMatch::Type OmniboxEditModel::CurrentTextType() const {
401 return CurrentMatch(NULL).type;
404 void OmniboxEditModel::AdjustTextForCopy(int sel_min,
405 bool is_all_selected,
411 // Do not adjust if selection did not start at the beginning of the field, or
412 // if the URL was replaced by search terms.
413 if ((sel_min != 0) ||
414 controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(false))
417 if (!user_input_in_progress_ && is_all_selected) {
418 // The user selected all the text and has not edited it. Use the url as the
419 // text so that if the scheme was stripped it's added back, and the url
420 // is unescaped (we escape parts of the url for display).
421 *url = PermanentURL();
422 *text = UTF8ToUTF16(url->spec());
427 // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now
428 // the user is probably holding down control to cause the copy, which will
429 // screw up our calculation of the desired_tld.
430 AutocompleteMatch match;
431 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(*text,
432 KeywordIsSelected(), true, &match, NULL);
433 if (AutocompleteMatch::IsSearchType(match.type))
435 *url = match.destination_url;
437 // Prefix the text with 'http://' if the text doesn't start with 'http://',
438 // the text parses as a url with a scheme of http, the user selected the
439 // entire host, and the user hasn't edited the host or manually removed the
441 GURL perm_url(PermanentURL());
442 if (perm_url.SchemeIs(content::kHttpScheme) &&
443 url->SchemeIs(content::kHttpScheme) && perm_url.host() == url->host()) {
445 string16 http = ASCIIToUTF16(content::kHttpScheme) +
446 ASCIIToUTF16(content::kStandardSchemeSeparator);
447 if (text->compare(0, http.length(), http) != 0)
448 *text = http + *text;
452 void OmniboxEditModel::SetInputInProgress(bool in_progress) {
453 if (in_progress && !user_input_since_focus_) {
454 base::TimeTicks now = base::TimeTicks::Now();
455 DCHECK(last_omnibox_focus_ <= now);
456 UMA_HISTOGRAM_TIMES(kFocusToEditTimeHistogram, now - last_omnibox_focus_);
457 user_input_since_focus_ = true;
460 if (user_input_in_progress_ == in_progress)
463 user_input_in_progress_ = in_progress;
464 if (user_input_in_progress_) {
465 time_user_first_modified_omnibox_ = base::TimeTicks::Now();
466 content::RecordAction(content::UserMetricsAction("OmniboxInputInProgress"));
467 autocomplete_controller()->ResetSession();
468 // Once the user starts editing, re-enable search term replacement, so that
469 // it will kick in if applicable once the edit is committed or reverted.
470 // (While the edit is in progress, this won't have a visible effect.)
471 controller_->GetToolbarModel()->set_search_term_replacement_enabled(true);
474 controller_->GetToolbarModel()->set_input_in_progress(in_progress);
475 controller_->Update(NULL);
477 delegate_->NotifySearchTabHelper(user_input_in_progress_, !in_revert_);
480 void OmniboxEditModel::Revert() {
481 SetInputInProgress(false);
483 InternalSetUserText(string16());
485 is_keyword_hint_ = false;
486 has_temporary_text_ = false;
487 view_->SetWindowTextAndCaretPos(permanent_text_,
488 has_focus() ? permanent_text_.length() : 0,
490 AutocompleteActionPredictor* action_predictor =
491 predictors::AutocompleteActionPredictorFactory::GetForProfile(profile_);
492 if (action_predictor)
493 action_predictor->ClearTransitionalMatches();
496 void OmniboxEditModel::StartAutocomplete(
497 bool has_selected_text,
498 bool prevent_inline_autocomplete) const {
499 size_t cursor_position;
500 if (inline_autocomplete_text_.empty()) {
501 // Cursor position is equivalent to the current selection's end.
503 view_->GetSelectionBounds(&start, &cursor_position);
504 // Adjust cursor position taking into account possible keyword in the user
505 // text. We rely on DisplayTextFromUserText() method which is consistent
506 // with keyword extraction done in KeywordProvider/SearchProvider.
507 const size_t cursor_offset =
508 user_text_.length() - DisplayTextFromUserText(user_text_).length();
509 cursor_position += cursor_offset;
511 // There are some cases where StartAutocomplete() may be called
512 // with non-empty |inline_autocomplete_text_|. In such cases, we cannot
513 // use the current selection, because it could result with the cursor
514 // position past the last character from the user text. Instead,
515 // we assume that the cursor is simply at the end of input.
516 // One example is when user presses Ctrl key while having a highlighted
517 // inline autocomplete text.
518 // TODO: Rethink how we are going to handle this case to avoid
519 // inconsistent behavior when user presses Ctrl key.
520 // See http://crbug.com/165961 and http://crbug.com/165968 for more details.
521 cursor_position = user_text_.length();
525 (delegate_->CurrentPageExists() && view_->IsIndicatingQueryRefinement()) ?
526 delegate_->GetURL() : GURL();
527 bool keyword_is_selected = KeywordIsSelected();
528 omnibox_controller_->StartAutocomplete(
533 prevent_inline_autocomplete || just_deleted_text_ ||
534 (has_selected_text && inline_autocomplete_text_.empty()) ||
535 (paste_state_ != NONE),
537 keyword_is_selected || allow_exact_keyword_match_);
540 void OmniboxEditModel::StopAutocomplete() {
541 autocomplete_controller()->Stop(true);
544 bool OmniboxEditModel::CanPasteAndGo(const string16& text) const {
545 if (!view_->command_updater()->IsCommandEnabled(IDC_OPEN_CURRENT_URL))
548 AutocompleteMatch match;
549 ClassifyStringForPasteAndGo(text, &match, NULL);
550 return match.destination_url.is_valid();
553 void OmniboxEditModel::PasteAndGo(const string16& text) {
554 DCHECK(CanPasteAndGo(text));
556 AutocompleteMatch match;
557 GURL alternate_nav_url;
558 ClassifyStringForPasteAndGo(text, &match, &alternate_nav_url);
559 view_->OpenMatch(match, CURRENT_TAB, alternate_nav_url,
560 OmniboxPopupModel::kNoMatch);
563 bool OmniboxEditModel::IsPasteAndSearch(const string16& text) const {
564 AutocompleteMatch match;
565 ClassifyStringForPasteAndGo(text, &match, NULL);
566 return AutocompleteMatch::IsSearchType(match.type);
569 void OmniboxEditModel::AcceptInput(WindowOpenDisposition disposition,
571 // Get the URL and transition type for the selected entry.
572 GURL alternate_nav_url;
573 AutocompleteMatch match = CurrentMatch(&alternate_nav_url);
575 // If CTRL is down it means the user wants to append ".com" to the text he
576 // typed. If we can successfully generate a URL_WHAT_YOU_TYPED match doing
577 // that, then we use this. These matches are marked as generated by the
578 // HistoryURLProvider so we only generate them if this provider is present.
579 if (control_key_state_ == DOWN_WITHOUT_CHANGE && !KeywordIsSelected() &&
580 autocomplete_controller()->history_url_provider()) {
581 // Generate a new AutocompleteInput, copying the latest one but using "com"
582 // as the desired TLD. Then use this autocomplete input to generate a
583 // URL_WHAT_YOU_TYPED AutocompleteMatch. Note that using the most recent
584 // input instead of the currently visible text means we'll ignore any
585 // visible inline autocompletion: if a user types "foo" and is autocompleted
586 // to "foodnetwork.com", ctrl-enter will navigate to "foo.com", not
587 // "foodnetwork.com". At the time of writing, this behavior matches
588 // Internet Explorer, but not Firefox.
589 const AutocompleteInput& old_input = autocomplete_controller()->input();
590 AutocompleteInput input(
591 has_temporary_text_ ?
592 UserTextFromDisplayText(view_->GetText()) : old_input.text(),
593 old_input.cursor_position(), ASCIIToUTF16("com"),
594 GURL(), old_input.current_page_classification(),
595 old_input.prevent_inline_autocomplete(), old_input.prefer_keyword(),
596 old_input.allow_exact_keyword_match(), old_input.matches_requested());
597 AutocompleteMatch url_match(
598 autocomplete_controller()->history_url_provider()->SuggestExactInput(
599 input.text(), input.canonicalized_url(), false));
601 if (url_match.destination_url.is_valid()) {
602 // We have a valid URL, we use this newly generated AutocompleteMatch.
604 alternate_nav_url = GURL();
608 if (!match.destination_url.is_valid())
611 if ((match.transition == content::PAGE_TRANSITION_TYPED) &&
612 (match.destination_url ==
613 URLFixerUpper::FixupURL(UTF16ToUTF8(permanent_text_), std::string()))) {
614 // When the user hit enter on the existing permanent URL, treat it like a
615 // reload for scoring purposes. We could detect this by just checking
616 // user_input_in_progress_, but it seems better to treat "edits" that end
617 // up leaving the URL unchanged (e.g. deleting the last character and then
618 // retyping it) as reloads too. We exclude non-TYPED transitions because if
619 // the transition is GENERATED, the user input something that looked
620 // different from the current URL, even if it wound up at the same place
621 // (e.g. manually retyping the same search query), and it seems wrong to
622 // treat this as a reload.
623 match.transition = content::PAGE_TRANSITION_RELOAD;
624 } else if (for_drop || ((paste_state_ != NONE) &&
625 match.is_history_what_you_typed_match)) {
626 // When the user pasted in a URL and hit enter, score it like a link click
627 // rather than a normal typed URL, so it doesn't get inline autocompleted
628 // as aggressively later.
629 match.transition = content::PAGE_TRANSITION_LINK;
632 const TemplateURL* template_url = match.GetTemplateURL(profile_, false);
633 if (template_url && template_url->url_ref().HasGoogleBaseURLs())
634 GoogleURLTracker::GoogleURLSearchCommitted(profile_);
636 view_->OpenMatch(match, disposition, alternate_nav_url,
637 OmniboxPopupModel::kNoMatch);
640 void OmniboxEditModel::OpenMatch(const AutocompleteMatch& match,
641 WindowOpenDisposition disposition,
642 const GURL& alternate_nav_url,
644 const string16& user_text =
645 user_input_in_progress_ ? user_text_ : permanent_text_;
646 scoped_ptr<OmniboxNavigationObserver> observer(
647 new OmniboxNavigationObserver(profile_, user_text, match,
650 // We only care about cases where there is a selection (i.e. the popup is
652 if (popup_model()->IsOpen()) {
653 const base::TimeTicks& now(base::TimeTicks::Now());
654 base::TimeDelta elapsed_time_since_user_first_modified_omnibox(
655 now - time_user_first_modified_omnibox_);
656 base::TimeDelta elapsed_time_since_last_change_to_default_match(
657 now - autocomplete_controller()->last_time_default_match_changed());
658 // These elapsed times don't really make sense for ZeroSuggest matches
659 // (because the user does not modify the omnibox for ZeroSuggest), so for
660 // those we set the elapsed times to something that will be ignored by
662 if (match.provider &&
663 match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST) {
664 elapsed_time_since_user_first_modified_omnibox =
665 base::TimeDelta::FromMilliseconds(-1);
666 elapsed_time_since_last_change_to_default_match =
667 base::TimeDelta::FromMilliseconds(-1);
672 autocomplete_controller()->input().type(),
673 popup_model()->selected_line(),
674 -1, // don't yet know tab ID; set later if appropriate
676 elapsed_time_since_user_first_modified_omnibox,
677 match.inline_autocompletion.length(),
678 elapsed_time_since_last_change_to_default_match,
681 DCHECK(user_input_in_progress_ || (match.provider &&
682 match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST))
683 << "We didn't get here through the expected series of calls. "
684 << "time_user_first_modified_omnibox_ is not set correctly and other "
685 << "things may be wrong. Match provider: "
686 << (match.provider ? match.provider->GetName() : "NULL");
687 DCHECK(log.elapsed_time_since_user_first_modified_omnibox >=
688 log.elapsed_time_since_last_change_to_default_match)
689 << "We should've got the notification that the user modified the "
690 << "omnibox text at same time or before the most recent time the "
691 << "default match changed.";
693 if (index != OmniboxPopupModel::kNoMatch)
694 log.selected_index = index;
696 if ((disposition == CURRENT_TAB) && delegate_->CurrentPageExists()) {
697 // If we know the destination is being opened in the current tab,
698 // we can easily get the tab ID. (If it's being opened in a new
699 // tab, we don't know the tab ID yet.)
700 log.tab_id = delegate_->GetSessionID().id();
702 autocomplete_controller()->AddProvidersInfo(&log.providers_info);
703 content::NotificationService::current()->Notify(
704 chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
705 content::Source<Profile>(profile_),
706 content::Details<OmniboxLog>(&log));
707 HISTOGRAM_ENUMERATION("Omnibox.EventCount", 1, 2);
708 DCHECK(!last_omnibox_focus_.is_null())
709 << "An omnibox focus should have occurred before opening a match.";
710 UMA_HISTOGRAM_TIMES(kFocusToOpenTimeHistogram, now - last_omnibox_focus_);
713 TemplateURL* template_url = match.GetTemplateURL(profile_, false);
715 if (match.transition == content::PAGE_TRANSITION_KEYWORD) {
716 // The user is using a non-substituting keyword or is explicitly in
719 // Don't increment usage count for extension keywords.
720 if (delegate_->ProcessExtensionKeyword(template_url, match,
722 observer->OnSuccessfulNavigation();
723 if (disposition != NEW_BACKGROUND_TAB)
728 content::RecordAction(content::UserMetricsAction("AcceptedKeyword"));
729 TemplateURLServiceFactory::GetForProfile(profile_)->IncrementUsageCount(
732 DCHECK_EQ(content::PAGE_TRANSITION_GENERATED, match.transition);
733 // NOTE: We purposefully don't increment the usage count of the default
734 // search engine here like we do for explicit keywords above; see comments
735 // in template_url.h.
738 // TODO(pkasting): This histogram obsoletes the next one. Remove the next
739 // one in Chrome 32 or later.
740 UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngineType",
741 TemplateURLPrepopulateData::GetEngineType(*template_url),
743 // NOTE: Non-prepopulated engines will all have ID 0, which is fine as
744 // the prepopulate IDs start at 1. Distribution-specific engines will
745 // all have IDs above the maximum, and will be automatically lumped
746 // together in an "overflow" bucket in the histogram.
747 UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngine",
748 template_url->prepopulate_id(),
749 TemplateURLPrepopulateData::kMaxPrepopulatedEngineID);
752 // Get the current text before we call RevertAll() which will clear it.
753 string16 current_text = GetViewText();
755 if (disposition != NEW_BACKGROUND_TAB) {
756 base::AutoReset<bool> tmp(&in_revert_, true);
757 view_->RevertAll(); // Revert the box to its unedited state.
760 if (match.type == AutocompleteMatchType::EXTENSION_APP) {
761 ExtensionAppProvider::LaunchAppFromOmnibox(match, profile_, disposition);
762 observer->OnSuccessfulNavigation();
764 base::TimeDelta query_formulation_time =
765 base::TimeTicks::Now() - time_user_first_modified_omnibox_;
766 const GURL destination_url = autocomplete_controller()->
767 GetDestinationURL(match, query_formulation_time);
769 RecordPercentageMatchHistogram(
770 permanent_text_, current_text,
771 controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(
775 // Track whether the destination URL sends us to a search results page
776 // using the default search provider.
777 if (TemplateURLServiceFactory::GetForProfile(profile_)->
778 IsSearchResultsPageFromDefaultSearchProvider(destination_url)) {
779 content::RecordAction(
780 content::UserMetricsAction("OmniboxDestinationURLIsSearchOnDSP"));
783 if (destination_url.is_valid()) {
784 // This calls RevertAll again.
785 base::AutoReset<bool> tmp(&in_revert_, true);
786 controller_->OnAutocompleteAccept(
787 destination_url, disposition,
788 content::PageTransitionFromInt(
789 match.transition | content::PAGE_TRANSITION_FROM_ADDRESS_BAR));
790 if (observer->load_state() != OmniboxNavigationObserver::LOAD_NOT_SEEN)
791 ignore_result(observer.release()); // The observer will delete itself.
796 RecordBookmarkLaunch(NULL, BOOKMARK_LAUNCH_LOCATION_OMNIBOX);
799 bool OmniboxEditModel::AcceptKeyword(EnteredKeywordModeMethod entered_method) {
800 DCHECK(is_keyword_hint_ && !keyword_.empty());
802 autocomplete_controller()->Stop(false);
803 is_keyword_hint_ = false;
805 if (popup_model()->IsOpen())
806 popup_model()->SetSelectedLineState(OmniboxPopupModel::KEYWORD);
808 StartAutocomplete(false, true);
810 // Ensure the current selection is saved before showing keyword mode
811 // so that moving to another line and then reverting the text will restore
812 // the current state properly.
813 bool save_original_selection = !has_temporary_text_;
814 has_temporary_text_ = true;
815 view_->OnTemporaryTextMaybeChanged(
816 DisplayTextFromUserText(CurrentMatch(NULL).fill_into_edit),
817 save_original_selection, true);
819 content::RecordAction(content::UserMetricsAction("AcceptedKeywordHint"));
820 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram, entered_method,
821 ENTERED_KEYWORD_MODE_NUM_ITEMS);
826 void OmniboxEditModel::AcceptTemporaryTextAsUserText() {
827 InternalSetUserText(UserTextFromDisplayText(view_->GetText()));
828 has_temporary_text_ = false;
829 delegate_->NotifySearchTabHelper(user_input_in_progress_, !in_revert_);
832 void OmniboxEditModel::ClearKeyword(const string16& visible_text) {
833 autocomplete_controller()->Stop(false);
834 omnibox_controller_->ClearPopupKeywordMode();
836 const string16 window_text(keyword_ + visible_text);
838 // Only reset the result if the edit text has changed since the
839 // keyword was accepted, or if the popup is closed.
840 if (just_deleted_text_ || !visible_text.empty() || !popup_model()->IsOpen()) {
841 view_->OnBeforePossibleChange();
842 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
845 is_keyword_hint_ = false;
846 view_->OnAfterPossibleChange();
847 just_deleted_text_ = true; // OnAfterPossibleChange() fails to clear this
848 // since the edit contents have actually grown
851 is_keyword_hint_ = true;
852 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
857 void OmniboxEditModel::OnSetFocus(bool control_down) {
858 last_omnibox_focus_ = base::TimeTicks::Now();
859 user_input_since_focus_ = false;
861 // If the omnibox lost focus while the caret was hidden and then regained
862 // focus, OnSetFocus() is called and should restore visibility. Note that
863 // focus can be regained without an accompanying call to
864 // OmniboxView::SetFocus(), e.g. by tabbing in.
865 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_EXPLICIT);
866 control_key_state_ = control_down ? DOWN_WITHOUT_CHANGE : UP;
868 // Try to get ZeroSuggest suggestions if a page is loaded and the user has
869 // not been typing in the omnibox. The |user_input_in_progress_| check is
870 // used to detect the case where this function is called after right-clicking
871 // in the omnibox and selecting paste in Linux (in which case we actually get
872 // the OnSetFocus() call after the process of handling the paste has kicked
874 // TODO(hfung): Remove this when crbug/271590 is fixed.
875 if (delegate_->CurrentPageExists() && !user_input_in_progress_) {
876 // TODO(jered): We may want to merge this into Start() and just call that
877 // here rather than having a special entry point for zero-suggest. Note
878 // that we avoid PermanentURL() here because it's not guaranteed to give us
879 // the actual underlying current URL, e.g. if we're on the NTP and the
880 // |permanent_text_| is empty.
881 autocomplete_controller()->StartZeroSuggest(delegate_->GetURL(),
886 delegate_->NotifySearchTabHelper(user_input_in_progress_, !in_revert_);
889 void OmniboxEditModel::SetCaretVisibility(bool visible) {
890 // Caret visibility only matters if the omnibox has focus.
891 if (focus_state_ != OMNIBOX_FOCUS_NONE) {
892 SetFocusState(visible ? OMNIBOX_FOCUS_VISIBLE : OMNIBOX_FOCUS_INVISIBLE,
893 OMNIBOX_FOCUS_CHANGE_EXPLICIT);
897 void OmniboxEditModel::OnWillKillFocus(gfx::NativeView view_gaining_focus) {
898 InstantController* instant = GetInstantController();
900 instant->OmniboxFocusChanged(OMNIBOX_FOCUS_NONE,
901 OMNIBOX_FOCUS_CHANGE_EXPLICIT,
905 // TODO(jered): Rip this out along with StartZeroSuggest.
906 autocomplete_controller()->StopZeroSuggest();
907 delegate_->NotifySearchTabHelper(user_input_in_progress_, !in_revert_);
910 void OmniboxEditModel::OnKillFocus() {
911 // TODO(samarth): determine if it is safe to move the call to
912 // OmniboxFocusChanged() from OnWillKillFocus() to here, which would let us
913 // just call SetFocusState() to handle the state change.
914 focus_state_ = OMNIBOX_FOCUS_NONE;
915 focus_source_ = INVALID;
916 control_key_state_ = UP;
920 bool OmniboxEditModel::OnEscapeKeyPressed() {
921 const AutocompleteMatch& match = CurrentMatch(NULL);
922 if (has_temporary_text_) {
923 if (match.destination_url != original_url_) {
924 RevertTemporaryText(true);
929 // We do not clear the pending entry from the omnibox when a load is first
930 // stopped. If the user presses Escape while stopped, we clear it.
931 if (delegate_->CurrentPageExists() && !delegate_->IsLoading()) {
932 delegate_->GetNavigationController().DiscardNonCommittedEntries();
936 // If the user wasn't editing, but merely had focus in the edit, allow <esc>
937 // to be processed as an accelerator, so it can still be used to stop a load.
938 // When the permanent text isn't all selected we still fall through to the
939 // SelectAll() call below so users can arrow around in the text and then hit
940 // <esc> to quickly replace all the text; this matches IE.
941 const bool has_zero_suggest_match = match.provider &&
942 (match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST);
943 if (!has_zero_suggest_match && !user_input_in_progress_ &&
944 view_->IsSelectAll())
947 if (!user_text_.empty()) {
948 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
949 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE,
950 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
953 view_->SelectAll(true);
957 void OmniboxEditModel::OnControlKeyChanged(bool pressed) {
958 if (pressed == (control_key_state_ == UP))
959 control_key_state_ = pressed ? DOWN_WITHOUT_CHANGE : UP;
962 void OmniboxEditModel::OnUpOrDownKeyPressed(int count) {
963 // NOTE: This purposefully doesn't trigger any code that resets paste_state_.
964 if (popup_model()->IsOpen()) {
965 // The popup is open, so the user should be able to interact with it
967 popup_model()->Move(count);
971 if (!query_in_progress()) {
972 // The popup is neither open nor working on a query already. So, start an
973 // autocomplete query for the current text. This also sets
974 // user_input_in_progress_ to true, which we want: if the user has started
975 // to interact with the popup, changing the permanent_text_ shouldn't change
976 // the displayed text.
977 // Note: This does not force the popup to open immediately.
978 // TODO(pkasting): We should, in fact, force this particular query to open
979 // the popup immediately.
980 if (!user_input_in_progress_)
981 InternalSetUserText(permanent_text_);
982 view_->UpdatePopup();
986 // TODO(pkasting): The popup is working on a query but is not open. We should
987 // force it to open immediately.
990 void OmniboxEditModel::OnPopupDataChanged(
991 const string16& text,
992 GURL* destination_for_temporary_text_change,
993 const string16& keyword,
994 bool is_keyword_hint) {
995 // The popup changed its data, the match in the controller is no longer valid.
996 omnibox_controller_->InvalidateCurrentMatch();
998 // Update keyword/hint-related local state.
999 bool keyword_state_changed = (keyword_ != keyword) ||
1000 ((is_keyword_hint_ != is_keyword_hint) && !keyword.empty());
1001 if (keyword_state_changed) {
1003 is_keyword_hint_ = is_keyword_hint;
1005 // |is_keyword_hint_| should always be false if |keyword_| is empty.
1006 DCHECK(!keyword_.empty() || !is_keyword_hint_);
1009 // Handle changes to temporary text.
1010 if (destination_for_temporary_text_change != NULL) {
1011 const bool save_original_selection = !has_temporary_text_;
1012 if (save_original_selection) {
1013 // Save the original selection and URL so it can be reverted later.
1014 has_temporary_text_ = true;
1015 original_url_ = *destination_for_temporary_text_change;
1016 inline_autocomplete_text_.clear();
1018 if (control_key_state_ == DOWN_WITHOUT_CHANGE) {
1019 // Arrowing around the popup cancels control-enter.
1020 control_key_state_ = DOWN_WITH_CHANGE;
1021 // Now things are a bit screwy: the desired_tld has changed, but if we
1022 // update the popup, the new order of entries won't match the old, so the
1023 // user's selection gets screwy; and if we don't update the popup, and the
1024 // user reverts, then the selected item will be as if control is still
1025 // pressed, even though maybe it isn't any more. There is no obvious
1026 // right answer here :(
1028 view_->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text),
1029 save_original_selection, true);
1033 bool call_controller_onchanged = true;
1034 inline_autocomplete_text_ = text;
1036 string16 user_text = user_input_in_progress_ ? user_text_ : permanent_text_;
1037 if (keyword_state_changed && KeywordIsSelected()) {
1038 // If we reach here, the user most likely entered keyword mode by inserting
1039 // a space between a keyword name and a search string (as pressing space or
1040 // tab after the keyword name alone would have been be handled in
1041 // MaybeAcceptKeywordBySpace() by calling AcceptKeyword(), which won't reach
1042 // here). In this case, we don't want to call
1043 // OnInlineAutocompleteTextMaybeChanged() as normal, because that will
1044 // correctly change the text (to the search string alone) but move the caret
1045 // to the end of the string; instead we want the caret at the start of the
1046 // search string since that's where it was in the original input. So we set
1047 // the text and caret position directly.
1049 // It may also be possible to reach here if we're reverting from having
1050 // temporary text back to a default match that's a keyword search, but in
1051 // that case the RevertTemporaryText() call below will reset the caret or
1052 // selection correctly so the caret positioning we do here won't matter.
1053 view_->SetWindowTextAndCaretPos(DisplayTextFromUserText(user_text), 0,
1055 } else if (view_->OnInlineAutocompleteTextMaybeChanged(
1056 DisplayTextFromUserText(user_text + inline_autocomplete_text_),
1057 DisplayTextFromUserText(user_text).length())) {
1058 call_controller_onchanged = false;
1061 // If |has_temporary_text_| is true, then we previously had a manual selection
1062 // but now don't (or |destination_for_temporary_text_change| would have been
1063 // non-NULL). This can happen when deleting the selected item in the popup.
1064 // In this case, we've already reverted the popup to the default match, so we
1065 // need to revert ourselves as well.
1066 if (has_temporary_text_) {
1067 RevertTemporaryText(false);
1068 call_controller_onchanged = false;
1071 // We need to invoke OnChanged in case the destination url changed (as could
1072 // happen when control is toggled).
1073 if (call_controller_onchanged)
1077 bool OmniboxEditModel::OnAfterPossibleChange(const string16& old_text,
1078 const string16& new_text,
1079 size_t selection_start,
1080 size_t selection_end,
1081 bool selection_differs,
1083 bool just_deleted_text,
1084 bool allow_keyword_ui_change) {
1085 // Update the paste state as appropriate: if we're just finishing a paste
1086 // that replaced all the text, preserve that information; otherwise, if we've
1087 // made some other edit, clear paste tracking.
1088 if (paste_state_ == PASTING)
1089 paste_state_ = PASTED;
1090 else if (text_differs)
1091 paste_state_ = NONE;
1093 if (text_differs || selection_differs) {
1094 // Record current focus state for this input if we haven't already.
1095 if (focus_source_ == INVALID) {
1096 // We should generally expect the omnibox to have focus at this point, but
1097 // it doesn't always on Linux. This is because, unlike other platforms,
1098 // right clicking in the omnibox on Linux doesn't focus it. So pasting via
1099 // right-click can change the contents without focusing the omnibox.
1100 // TODO(samarth): fix Linux focus behavior and add a DCHECK here to
1101 // check that the omnibox does have focus.
1102 focus_source_ = (focus_state_ == OMNIBOX_FOCUS_INVISIBLE) ?
1106 // Restore caret visibility whenever the user changes text or selection in
1108 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_TYPING);
1111 // Modifying the selection counts as accepting the autocompleted text.
1112 const bool user_text_changed =
1113 text_differs || (selection_differs && !inline_autocomplete_text_.empty());
1115 // If something has changed while the control key is down, prevent
1116 // "ctrl-enter" until the control key is released.
1117 if ((text_differs || selection_differs) &&
1118 (control_key_state_ == DOWN_WITHOUT_CHANGE))
1119 control_key_state_ = DOWN_WITH_CHANGE;
1121 if (!user_text_changed)
1124 // If the user text has not changed, we do not want to change the model's
1125 // state associated with the text. Otherwise, we can get surprising behavior
1126 // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983
1127 InternalSetUserText(UserTextFromDisplayText(new_text));
1128 has_temporary_text_ = false;
1130 // Track when the user has deleted text so we won't allow inline
1132 just_deleted_text_ = just_deleted_text;
1134 if (user_input_in_progress_ && user_text_.empty()) {
1135 // Log cases where the user started editing and then subsequently cleared
1136 // all the text. Note that this explicitly doesn't catch cases like
1137 // "hit ctrl-l to select whole edit contents, then hit backspace", because
1138 // in such cases, |user_input_in_progress| won't be true here.
1139 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
1140 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING,
1141 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
1144 const bool no_selection = selection_start == selection_end;
1146 // Update the popup for the change, in the process changing to keyword mode
1147 // if the user hit space in mid-string after a keyword.
1148 // |allow_exact_keyword_match_| will be used by StartAutocomplete() method,
1149 // which will be called by |view_->UpdatePopup()|; so after that returns we
1150 // can safely reset this flag.
1151 allow_exact_keyword_match_ = text_differs && allow_keyword_ui_change &&
1152 !just_deleted_text && no_selection &&
1153 CreatedKeywordSearchByInsertingSpaceInMiddle(old_text, user_text_,
1155 if (allow_exact_keyword_match_) {
1156 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram,
1157 ENTERED_KEYWORD_MODE_VIA_SPACE_IN_MIDDLE,
1158 ENTERED_KEYWORD_MODE_NUM_ITEMS);
1160 view_->UpdatePopup();
1161 allow_exact_keyword_match_ = false;
1163 // Change to keyword mode if the user is now pressing space after a keyword
1164 // name. Note that if this is the case, then even if there was no keyword
1165 // hint when we entered this function (e.g. if the user has used space to
1166 // replace some selected text that was adjoined to this keyword), there will
1167 // be one now because of the call to UpdatePopup() above; so it's safe for
1168 // MaybeAcceptKeywordBySpace() to look at |keyword_| and |is_keyword_hint_| to
1169 // determine what keyword, if any, is applicable.
1171 // If MaybeAcceptKeywordBySpace() accepts the keyword and returns true, that
1172 // will have updated our state already, so in that case we don't also return
1173 // true from this function.
1174 return !(text_differs && allow_keyword_ui_change && !just_deleted_text &&
1175 no_selection && (selection_start == user_text_.length()) &&
1176 MaybeAcceptKeywordBySpace(user_text_));
1179 // TODO(beaudoin): Merge OnPopupDataChanged with this method once the popup
1180 // handling has completely migrated to omnibox_controller.
1181 void OmniboxEditModel::OnCurrentMatchChanged() {
1182 has_temporary_text_ = false;
1184 const AutocompleteMatch& match = omnibox_controller_->current_match();
1186 // We store |keyword| and |is_keyword_hint| in temporary variables since
1187 // OnPopupDataChanged use their previous state to detect changes.
1189 bool is_keyword_hint;
1190 match.GetKeywordUIState(profile_, &keyword, &is_keyword_hint);
1191 popup_model()->OnResultChanged();
1192 // OnPopupDataChanged() resets OmniboxController's |current_match_| early
1193 // on. Therefore, copy match.inline_autocompletion to a temp to preserve
1194 // its value across the entire call.
1195 const string16 inline_autocompletion(match.inline_autocompletion);
1196 OnPopupDataChanged(inline_autocompletion, NULL, keyword, is_keyword_hint);
1199 string16 OmniboxEditModel::GetViewText() const {
1200 return view_->GetText();
1203 InstantController* OmniboxEditModel::GetInstantController() const {
1204 return controller_->GetInstant();
1207 bool OmniboxEditModel::query_in_progress() const {
1208 return !autocomplete_controller()->done();
1211 void OmniboxEditModel::InternalSetUserText(const string16& text) {
1213 just_deleted_text_ = false;
1214 inline_autocomplete_text_.clear();
1217 bool OmniboxEditModel::KeywordIsSelected() const {
1218 return !is_keyword_hint_ && !keyword_.empty();
1221 void OmniboxEditModel::ClearPopupKeywordMode() const {
1222 omnibox_controller_->ClearPopupKeywordMode();
1225 string16 OmniboxEditModel::DisplayTextFromUserText(const string16& text) const {
1226 return KeywordIsSelected() ?
1227 KeywordProvider::SplitReplacementStringFromInput(text, false) : text;
1230 string16 OmniboxEditModel::UserTextFromDisplayText(const string16& text) const {
1231 return KeywordIsSelected() ? (keyword_ + char16(' ') + text) : text;
1234 void OmniboxEditModel::GetInfoForCurrentText(AutocompleteMatch* match,
1235 GURL* alternate_nav_url) const {
1236 DCHECK(match != NULL);
1238 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(
1240 // Any time the user hits enter on the unchanged omnibox, we should reload.
1241 // When we're not extracting search terms, AcceptInput() will take care of
1242 // this (see code referring to PAGE_TRANSITION_RELOAD there), but when we're
1243 // extracting search terms, the conditionals there won't fire, so we
1244 // explicitly set up a match that will reload here.
1246 // It's important that we fetch the current visible URL to reload instead of
1247 // just getting a "search what you typed" URL from
1248 // SearchProvider::CreateSearchSuggestion(), since the user may be in a
1249 // non-default search mode such as image search.
1250 match->type = AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED;
1251 match->destination_url =
1252 delegate_->GetNavigationController().GetVisibleEntry()->GetURL();
1253 match->transition = content::PAGE_TRANSITION_RELOAD;
1254 } else if (popup_model()->IsOpen() || query_in_progress()) {
1255 if (query_in_progress()) {
1256 // It's technically possible for |result| to be empty if no provider
1257 // returns a synchronous result but the query has not completed
1258 // synchronously; pratically, however, that should never actually happen.
1259 if (result().empty())
1261 // The user cannot have manually selected a match, or the query would have
1262 // stopped. So the default match must be the desired selection.
1263 *match = *result().default_match();
1265 // If there are no results, the popup should be closed, so we shouldn't
1266 // have gotten here.
1267 CHECK(!result().empty());
1268 CHECK(popup_model()->selected_line() < result().size());
1269 *match = result().match_at(popup_model()->selected_line());
1271 if (alternate_nav_url && popup_model()->manually_selected_match().empty())
1272 *alternate_nav_url = result().alternate_nav_url();
1274 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
1275 UserTextFromDisplayText(view_->GetText()), KeywordIsSelected(), true,
1276 match, alternate_nav_url);
1280 void OmniboxEditModel::RevertTemporaryText(bool revert_popup) {
1281 // The user typed something, then selected a different item. Restore the
1282 // text they typed and change back to the default item.
1283 // NOTE: This purposefully does not reset paste_state_.
1284 just_deleted_text_ = false;
1285 has_temporary_text_ = false;
1288 popup_model()->ResetToDefaultMatch();
1289 view_->OnRevertTemporaryText();
1292 bool OmniboxEditModel::MaybeAcceptKeywordBySpace(const string16& new_text) {
1293 size_t keyword_length = new_text.length() - 1;
1294 return (paste_state_ == NONE) && is_keyword_hint_ && !keyword_.empty() &&
1295 inline_autocomplete_text_.empty() &&
1296 (keyword_.length() == keyword_length) &&
1297 IsSpaceCharForAcceptingKeyword(new_text[keyword_length]) &&
1298 !new_text.compare(0, keyword_length, keyword_, 0, keyword_length) &&
1299 AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_SPACE_AT_END);
1302 bool OmniboxEditModel::CreatedKeywordSearchByInsertingSpaceInMiddle(
1303 const string16& old_text,
1304 const string16& new_text,
1305 size_t caret_position) const {
1306 DCHECK_GE(new_text.length(), caret_position);
1308 // Check simple conditions first.
1309 if ((paste_state_ != NONE) || (caret_position < 2) ||
1310 (old_text.length() < caret_position) ||
1311 (new_text.length() == caret_position))
1313 size_t space_position = caret_position - 1;
1314 if (!IsSpaceCharForAcceptingKeyword(new_text[space_position]) ||
1315 IsWhitespace(new_text[space_position - 1]) ||
1316 new_text.compare(0, space_position, old_text, 0, space_position) ||
1317 !new_text.compare(space_position, new_text.length() - space_position,
1318 old_text, space_position,
1319 old_text.length() - space_position)) {
1323 // Then check if the text before the inserted space matches a keyword.
1325 TrimWhitespace(new_text.substr(0, space_position), TRIM_LEADING, &keyword);
1326 return !keyword.empty() && !autocomplete_controller()->keyword_provider()->
1327 GetKeywordForText(keyword).empty();
1331 bool OmniboxEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c) {
1333 case 0x0020: // Space
1334 case 0x3000: // Ideographic Space
1341 AutocompleteInput::PageClassification OmniboxEditModel::ClassifyPage() const {
1342 if (!delegate_->CurrentPageExists())
1343 return AutocompleteInput::OTHER;
1344 if (delegate_->IsInstantNTP()) {
1345 // Note that we treat OMNIBOX as the source if focus_source_ is INVALID,
1346 // i.e., if input isn't actually in progress.
1347 return (focus_source_ == FAKEBOX) ?
1348 AutocompleteInput::INSTANT_NEW_TAB_PAGE_WITH_FAKEBOX_AS_STARTING_FOCUS :
1349 AutocompleteInput::INSTANT_NEW_TAB_PAGE_WITH_OMNIBOX_AS_STARTING_FOCUS;
1351 const GURL& gurl = delegate_->GetURL();
1352 if (!gurl.is_valid())
1353 return AutocompleteInput::INVALID_SPEC;
1354 const std::string& url = gurl.spec();
1355 if (url == chrome::kChromeUINewTabURL)
1356 return AutocompleteInput::NEW_TAB_PAGE;
1357 if (url == content::kAboutBlankURL)
1358 return AutocompleteInput::BLANK;
1359 if (url == profile()->GetPrefs()->GetString(prefs::kHomePage))
1360 return AutocompleteInput::HOME_PAGE;
1361 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(true))
1362 return AutocompleteInput::SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT;
1363 if (delegate_->IsSearchResultsPage())
1364 return AutocompleteInput::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT;
1365 return AutocompleteInput::OTHER;
1368 void OmniboxEditModel::ClassifyStringForPasteAndGo(
1369 const string16& text,
1370 AutocompleteMatch* match,
1371 GURL* alternate_nav_url) const {
1373 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(text,
1374 false, false, match, alternate_nav_url);
1377 void OmniboxEditModel::SetFocusState(OmniboxFocusState state,
1378 OmniboxFocusChangeReason reason) {
1379 if (state == focus_state_)
1382 InstantController* instant = GetInstantController();
1384 instant->OmniboxFocusChanged(state, reason, NULL);
1386 // Update state and notify view if the omnibox has focus and the caret
1387 // visibility changed.
1388 const bool was_caret_visible = is_caret_visible();
1389 focus_state_ = state;
1390 if (focus_state_ != OMNIBOX_FOCUS_NONE &&
1391 is_caret_visible() != was_caret_visible)
1392 view_->ApplyCaretVisibility();