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