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