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_provider.h"
21 #include "chrome/browser/autocomplete/extension_app_provider.h"
22 #include "chrome/browser/autocomplete/history_url_provider.h"
23 #include "chrome/browser/autocomplete/keyword_provider.h"
24 #include "chrome/browser/autocomplete/search_provider.h"
25 #include "chrome/browser/bookmarks/bookmark_stats.h"
26 #include "chrome/browser/chrome_notification_types.h"
27 #include "chrome/browser/command_updater.h"
28 #include "chrome/browser/extensions/api/omnibox/omnibox_api.h"
29 #include "chrome/browser/favicon/favicon_tab_helper.h"
30 #include "chrome/browser/google/google_url_tracker.h"
31 #include "chrome/browser/net/predictor.h"
32 #include "chrome/browser/omnibox/omnibox_log.h"
33 #include "chrome/browser/predictors/autocomplete_action_predictor.h"
34 #include "chrome/browser/predictors/autocomplete_action_predictor_factory.h"
35 #include "chrome/browser/prerender/prerender_field_trial.h"
36 #include "chrome/browser/prerender/prerender_manager.h"
37 #include "chrome/browser/prerender/prerender_manager_factory.h"
38 #include "chrome/browser/profiles/profile.h"
39 #include "chrome/browser/search/search.h"
40 #include "chrome/browser/search_engines/template_url.h"
41 #include "chrome/browser/search_engines/template_url_prepopulate_data.h"
42 #include "chrome/browser/search_engines/template_url_service.h"
43 #include "chrome/browser/search_engines/template_url_service_factory.h"
44 #include "chrome/browser/sessions/session_tab_helper.h"
45 #include "chrome/browser/ui/browser_list.h"
46 #include "chrome/browser/ui/omnibox/omnibox_current_page_delegate_impl.h"
47 #include "chrome/browser/ui/omnibox/omnibox_edit_controller.h"
48 #include "chrome/browser/ui/omnibox/omnibox_navigation_observer.h"
49 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
50 #include "chrome/browser/ui/omnibox/omnibox_popup_view.h"
51 #include "chrome/browser/ui/omnibox/omnibox_view.h"
52 #include "chrome/browser/ui/search/instant_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/net/url_fixer_upper.h"
57 #include "chrome/common/pref_names.h"
58 #include "chrome/common/url_constants.h"
59 #include "content/public/browser/navigation_controller.h"
60 #include "content/public/browser/navigation_entry.h"
61 #include "content/public/browser/notification_service.h"
62 #include "content/public/browser/render_view_host.h"
63 #include "content/public/browser/user_metrics.h"
64 #include "extensions/common/constants.h"
65 #include "ui/gfx/image/image.h"
66 #include "url/url_util.h"
68 using predictors::AutocompleteActionPredictor
;
71 // Helpers --------------------------------------------------------------------
75 // Histogram name which counts the number of times that the user text is
76 // cleared. IME users are sometimes in the situation that IME was
77 // unintentionally turned on and failed to input latin alphabets (ASCII
78 // characters) or the opposite case. In that case, users may delete all
79 // the text and the user text gets cleared. We'd like to measure how often
80 // this scenario happens.
82 // Note that since we don't currently correlate "text cleared" events with
83 // IME usage, this also captures many other cases where users clear the text;
84 // though it explicitly doesn't log deleting all the permanent text as
85 // the first action of an editing sequence (see comments in
86 // OnAfterPossibleChange()).
87 const char kOmniboxUserTextClearedHistogram
[] = "Omnibox.UserTextCleared";
89 enum UserTextClearedType
{
90 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING
= 0,
91 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE
= 1,
92 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS
,
95 // Histogram name which counts the number of times the user enters
96 // keyword hint mode and via what method. The possible values are listed
97 // in the EnteredKeywordModeMethod enum which is defined in the .h file.
98 const char kEnteredKeywordModeHistogram
[] = "Omnibox.EnteredKeywordMode";
100 // Histogram name which counts the number of milliseconds a user takes
101 // between focusing and editing the omnibox.
102 const char kFocusToEditTimeHistogram
[] = "Omnibox.FocusToEditTime";
104 // Histogram name which counts the number of milliseconds a user takes
105 // between focusing and opening an omnibox match.
106 const char kFocusToOpenTimeHistogram
[] = "Omnibox.FocusToOpenTimeAnyPopupState";
108 // Split the percentage match histograms into buckets based on the width of the
110 const int kPercentageMatchHistogramWidthBuckets
[] = { 400, 700, 1200 };
112 void RecordPercentageMatchHistogram(const base::string16
& old_text
,
113 const base::string16
& new_text
,
114 bool url_replacement_active
,
115 content::PageTransition transition
,
117 size_t avg_length
= (old_text
.length() + new_text
.length()) / 2;
120 if (!old_text
.empty() && !new_text
.empty()) {
121 size_t shorter_length
= std::min(old_text
.length(), new_text
.length());
122 base::string16::const_iterator
end(old_text
.begin() + shorter_length
);
123 base::string16::const_iterator
mismatch(
124 std::mismatch(old_text
.begin(), end
, new_text
.begin()).first
);
125 size_t matching_characters
= mismatch
- old_text
.begin();
126 percent
= static_cast<float>(matching_characters
) / avg_length
* 100;
129 std::string histogram_name
;
130 if (url_replacement_active
) {
131 if (transition
== content::PAGE_TRANSITION_TYPED
) {
132 histogram_name
= "InstantExtended.PercentageMatchV2_QuerytoURL";
133 UMA_HISTOGRAM_PERCENTAGE(histogram_name
, percent
);
135 histogram_name
= "InstantExtended.PercentageMatchV2_QuerytoQuery";
136 UMA_HISTOGRAM_PERCENTAGE(histogram_name
, percent
);
139 if (transition
== content::PAGE_TRANSITION_TYPED
) {
140 histogram_name
= "InstantExtended.PercentageMatchV2_URLtoURL";
141 UMA_HISTOGRAM_PERCENTAGE(histogram_name
, percent
);
143 histogram_name
= "InstantExtended.PercentageMatchV2_URLtoQuery";
144 UMA_HISTOGRAM_PERCENTAGE(histogram_name
, percent
);
148 std::string suffix
= "large";
149 for (size_t i
= 0; i
< arraysize(kPercentageMatchHistogramWidthBuckets
);
151 if (omnibox_width
< kPercentageMatchHistogramWidthBuckets
[i
]) {
152 suffix
= base::IntToString(kPercentageMatchHistogramWidthBuckets
[i
]);
157 // Cannot rely on UMA histograms macro because the name of the histogram is
158 // generated dynamically.
159 base::HistogramBase
* counter
= base::LinearHistogram::FactoryGet(
160 histogram_name
+ "_" + suffix
, 1, 101, 102,
161 base::Histogram::kUmaTargetedHistogramFlag
);
162 counter
->Add(percent
);
168 // OmniboxEditModel::State ----------------------------------------------------
170 OmniboxEditModel::State::State(bool user_input_in_progress
,
171 const base::string16
& user_text
,
172 const base::string16
& gray_text
,
173 const base::string16
& keyword
,
174 bool is_keyword_hint
,
175 bool url_replacement_enabled
,
176 OmniboxFocusState focus_state
,
177 FocusSource focus_source
,
178 const AutocompleteInput
& autocomplete_input
)
179 : user_input_in_progress(user_input_in_progress
),
180 user_text(user_text
),
181 gray_text(gray_text
),
183 is_keyword_hint(is_keyword_hint
),
184 url_replacement_enabled(url_replacement_enabled
),
185 focus_state(focus_state
),
186 focus_source(focus_source
),
187 autocomplete_input(autocomplete_input
) {
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
);
238 UMA_HISTOGRAM_BOOLEAN("Omnibox.SaveStateForTabSwitch.UserInputInProgress",
239 user_input_in_progress_
);
241 user_input_in_progress_
, user_text_
, view_
->GetGrayTextAutocompletion(),
242 keyword_
, is_keyword_hint_
,
243 controller_
->GetToolbarModel()->url_replacement_enabled(),
244 focus_state_
, focus_source_
, input_
);
247 void OmniboxEditModel::RestoreState(const State
* state
) {
248 // We need to update the permanent text correctly and revert the view
249 // regardless of whether there is saved state.
250 bool url_replacement_enabled
= !state
|| state
->url_replacement_enabled
;
251 controller_
->GetToolbarModel()->set_url_replacement_enabled(
252 url_replacement_enabled
);
253 controller_
->GetToolbarModel()->set_origin_chip_enabled(
254 url_replacement_enabled
);
255 permanent_text_
= controller_
->GetToolbarModel()->GetText();
256 // Don't muck with the search term replacement state, as we've just set it
258 view_
->RevertWithoutResettingSearchTermReplacement();
259 // Restore the autocomplete controller's input, or clear it if this is a new
261 input_
= state
? state
->autocomplete_input
: AutocompleteInput();
265 SetFocusState(state
->focus_state
, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH
);
266 focus_source_
= state
->focus_source
;
267 // Restore any user editing.
268 if (state
->user_input_in_progress
) {
269 // NOTE: Be sure and set keyword-related state BEFORE invoking
270 // DisplayTextFromUserText(), as its result depends upon this state.
271 keyword_
= state
->keyword
;
272 is_keyword_hint_
= state
->is_keyword_hint
;
273 view_
->SetUserText(state
->user_text
,
274 DisplayTextFromUserText(state
->user_text
), false);
275 view_
->SetGrayTextAutocompletion(state
->gray_text
);
279 AutocompleteMatch
OmniboxEditModel::CurrentMatch(
280 GURL
* alternate_nav_url
) const {
281 // If we have a valid match use it. Otherwise get one for the current text.
282 AutocompleteMatch match
= omnibox_controller_
->current_match();
284 if (!match
.destination_url
.is_valid()) {
285 GetInfoForCurrentText(&match
, alternate_nav_url
);
286 } else if (alternate_nav_url
) {
287 *alternate_nav_url
= AutocompleteResult::ComputeAlternateNavUrl(
293 bool OmniboxEditModel::UpdatePermanentText() {
294 SearchProvider
* search_provider
=
295 autocomplete_controller()->search_provider();
296 if (search_provider
&& delegate_
->CurrentPageExists())
297 search_provider
->set_current_page_url(delegate_
->GetURL());
299 // When there's new permanent text, and the user isn't interacting with the
300 // omnibox, we want to revert the edit to show the new text. We could simply
301 // define "interacting" as "the omnibox has focus", but we still allow updates
302 // when the omnibox has focus as long as the user hasn't begun editing, isn't
303 // seeing zerosuggestions (because changing this text would require changing
304 // or hiding those suggestions), and hasn't toggled on "Show URL" (because
305 // this update will re-enable search term replacement, which will be annoying
306 // if the user is trying to copy the URL). When the omnibox doesn't have
307 // focus, we assume the user may have abandoned their interaction and it's
308 // always safe to change the text; this also prevents someone toggling "Show
309 // URL" (which sounds as if it might be persistent) from seeing just that URL
310 // forever afterwards.
312 // If the page is auto-committing gray text, however, we generally don't want
313 // to make any change to the edit. While auto-commits modify the underlying
314 // permanent URL, they're intended to have no effect on the user's editing
315 // process -- before and after the auto-commit, the omnibox should show the
316 // same user text and the same instant suggestion, even if the auto-commit
317 // happens while the edit doesn't have focus.
318 base::string16 new_permanent_text
= controller_
->GetToolbarModel()->GetText();
319 base::string16 gray_text
= view_
->GetGrayTextAutocompletion();
320 const bool visibly_changed_permanent_text
=
321 (permanent_text_
!= new_permanent_text
) &&
323 (!user_input_in_progress_
&&
324 !(popup_model() && popup_model()->IsOpen()) &&
325 controller_
->GetToolbarModel()->url_replacement_enabled())) &&
326 (gray_text
.empty() ||
327 new_permanent_text
!= user_text_
+ gray_text
);
329 permanent_text_
= new_permanent_text
;
330 return visibly_changed_permanent_text
;
333 GURL
OmniboxEditModel::PermanentURL() {
334 return URLFixerUpper::FixupURL(base::UTF16ToUTF8(permanent_text_
),
338 void OmniboxEditModel::SetUserText(const base::string16
& text
) {
339 SetInputInProgress(true);
340 InternalSetUserText(text
);
341 omnibox_controller_
->InvalidateCurrentMatch();
343 has_temporary_text_
= false;
346 bool OmniboxEditModel::CommitSuggestedText() {
347 const base::string16 suggestion
= view_
->GetGrayTextAutocompletion();
348 if (suggestion
.empty())
351 const base::string16 final_text
= view_
->GetText() + suggestion
;
352 view_
->OnBeforePossibleChange();
353 view_
->SetWindowTextAndCaretPos(final_text
, final_text
.length(), false,
355 view_
->OnAfterPossibleChange();
359 void OmniboxEditModel::OnChanged() {
360 // Don't call CurrentMatch() when there's no editing, as in this case we'll
361 // never actually use it. This avoids running the autocomplete providers (and
362 // any systems they then spin up) during startup.
363 const AutocompleteMatch
& current_match
= user_input_in_progress_
?
364 CurrentMatch(NULL
) : AutocompleteMatch();
366 AutocompleteActionPredictor::Action recommended_action
=
367 AutocompleteActionPredictor::ACTION_NONE
;
368 if (user_input_in_progress_
) {
369 InstantSearchPrerenderer
* prerenderer
=
370 InstantSearchPrerenderer::GetForProfile(profile_
);
372 prerenderer
->IsAllowed(current_match
, controller_
->GetWebContents()) &&
373 popup_model()->IsOpen() && has_focus()) {
374 recommended_action
= AutocompleteActionPredictor::ACTION_PRERENDER
;
376 AutocompleteActionPredictor
* action_predictor
=
377 predictors::AutocompleteActionPredictorFactory::GetForProfile(
379 action_predictor
->RegisterTransitionalMatches(user_text_
, result());
380 // Confer with the AutocompleteActionPredictor to determine what action,
381 // if any, we should take. Get the recommended action here even if we
382 // don't need it so we can get stats for anyone who is opted in to UMA,
383 // but only get it if the user has actually typed something to avoid
384 // constructing it before it's needed. Note: This event is triggered as
385 // part of startup when the initial tab transitions to the start page.
387 action_predictor
->RecommendAction(user_text_
, current_match
);
391 UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.Action",
393 AutocompleteActionPredictor::LAST_PREDICT_ACTION
);
395 // Hide any suggestions we might be showing.
396 view_
->SetGrayTextAutocompletion(base::string16());
398 switch (recommended_action
) {
399 case AutocompleteActionPredictor::ACTION_PRERENDER
:
400 // It's possible that there is no current page, for instance if the tab
401 // has been closed or on return from a sleep state.
402 // (http://crbug.com/105689)
403 if (!delegate_
->CurrentPageExists())
405 // Ask for prerendering if the destination URL is different than the
407 if (current_match
.destination_url
!= delegate_
->GetURL())
408 delegate_
->DoPrerender(current_match
);
410 case AutocompleteActionPredictor::ACTION_PRECONNECT
:
411 omnibox_controller_
->DoPreconnect(current_match
);
413 case AutocompleteActionPredictor::ACTION_NONE
:
417 controller_
->OnChanged();
420 void OmniboxEditModel::GetDataForURLExport(GURL
* url
,
421 base::string16
* title
,
422 gfx::Image
* favicon
) {
423 *url
= CurrentMatch(NULL
).destination_url
;
424 if (*url
== delegate_
->GetURL()) {
425 content::WebContents
* web_contents
= controller_
->GetWebContents();
426 *title
= web_contents
->GetTitle();
427 *favicon
= FaviconTabHelper::FromWebContents(web_contents
)->GetFavicon();
431 bool OmniboxEditModel::CurrentTextIsURL() const {
432 if (controller_
->GetToolbarModel()->WouldReplaceURL())
435 // If current text is not composed of replaced search terms and
436 // !user_input_in_progress_, then permanent text is showing and should be a
437 // URL, so no further checking is needed. By avoiding checking in this case,
438 // we avoid calling into the autocomplete providers, and thus initializing the
439 // history system, as long as possible, which speeds startup.
440 if (!user_input_in_progress_
)
443 return !AutocompleteMatch::IsSearchType(CurrentMatch(NULL
).type
);
446 AutocompleteMatch::Type
OmniboxEditModel::CurrentTextType() const {
447 return CurrentMatch(NULL
).type
;
450 void OmniboxEditModel::AdjustTextForCopy(int sel_min
,
451 bool is_all_selected
,
452 base::string16
* text
,
457 // Do not adjust if selection did not start at the beginning of the field, or
458 // if the URL was omitted.
459 if ((sel_min
!= 0) || controller_
->GetToolbarModel()->WouldReplaceURL())
462 if (!user_input_in_progress_
&& is_all_selected
) {
463 // The user selected all the text and has not edited it. Use the url as the
464 // text so that if the scheme was stripped it's added back, and the url
465 // is unescaped (we escape parts of the url for display).
466 *url
= PermanentURL();
467 *text
= base::UTF8ToUTF16(url
->spec());
472 // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now
473 // the user is probably holding down control to cause the copy, which will
474 // screw up our calculation of the desired_tld.
475 AutocompleteMatch match
;
476 AutocompleteClassifierFactory::GetForProfile(profile_
)->Classify(
477 *text
, KeywordIsSelected(), true, ClassifyPage(), &match
, NULL
);
478 if (AutocompleteMatch::IsSearchType(match
.type
))
480 *url
= match
.destination_url
;
482 // Prefix the text with 'http://' if the text doesn't start with 'http://',
483 // the text parses as a url with a scheme of http, the user selected the
484 // entire host, and the user hasn't edited the host or manually removed the
486 GURL
perm_url(PermanentURL());
487 if (perm_url
.SchemeIs(url::kHttpScheme
) &&
488 url
->SchemeIs(url::kHttpScheme
) && perm_url
.host() == url
->host()) {
490 base::string16 http
= base::ASCIIToUTF16(url::kHttpScheme
) +
491 base::ASCIIToUTF16(content::kStandardSchemeSeparator
);
492 if (text
->compare(0, http
.length(), http
) != 0)
493 *text
= http
+ *text
;
497 void OmniboxEditModel::SetInputInProgress(bool in_progress
) {
498 if (in_progress
&& !user_input_since_focus_
) {
499 base::TimeTicks now
= base::TimeTicks::Now();
500 DCHECK(last_omnibox_focus_
<= now
);
501 UMA_HISTOGRAM_TIMES(kFocusToEditTimeHistogram
, now
- last_omnibox_focus_
);
502 user_input_since_focus_
= true;
505 if (user_input_in_progress_
== in_progress
)
508 user_input_in_progress_
= in_progress
;
509 if (user_input_in_progress_
) {
510 time_user_first_modified_omnibox_
= base::TimeTicks::Now();
511 content::RecordAction(base::UserMetricsAction("OmniboxInputInProgress"));
512 autocomplete_controller()->ResetSession();
515 // The following code handles two cases:
516 // * For HIDE_ON_USER_INPUT and ON_SRP, it hides the chip when user input
518 // * For HIDE_ON_MOUSE_RELEASE, which only hides the chip on mouse release if
519 // the omnibox is empty, it handles the "omnibox was not empty" case by
520 // acting like HIDE_ON_USER_INPUT.
521 if (chrome::ShouldDisplayOriginChip() && in_progress
)
522 controller()->GetToolbarModel()->set_origin_chip_enabled(false);
524 controller_
->GetToolbarModel()->set_input_in_progress(in_progress
);
525 controller_
->Update(NULL
);
527 if (user_input_in_progress_
|| !in_revert_
)
528 delegate_
->OnInputStateChanged();
531 void OmniboxEditModel::Revert() {
532 SetInputInProgress(false);
534 InternalSetUserText(base::string16());
536 is_keyword_hint_
= false;
537 has_temporary_text_
= false;
538 view_
->SetWindowTextAndCaretPos(permanent_text_
,
539 has_focus() ? permanent_text_
.length() : 0,
541 AutocompleteActionPredictor
* action_predictor
=
542 predictors::AutocompleteActionPredictorFactory::GetForProfile(profile_
);
543 action_predictor
->ClearTransitionalMatches();
544 action_predictor
->CancelPrerender();
547 void OmniboxEditModel::StartAutocomplete(
548 bool has_selected_text
,
549 bool prevent_inline_autocomplete
) {
550 size_t cursor_position
;
551 if (inline_autocomplete_text_
.empty()) {
552 // Cursor position is equivalent to the current selection's end.
554 view_
->GetSelectionBounds(&start
, &cursor_position
);
555 // Adjust cursor position taking into account possible keyword in the user
556 // text. We rely on DisplayTextFromUserText() method which is consistent
557 // with keyword extraction done in KeywordProvider/SearchProvider.
558 const size_t cursor_offset
=
559 user_text_
.length() - DisplayTextFromUserText(user_text_
).length();
560 cursor_position
+= cursor_offset
;
562 // There are some cases where StartAutocomplete() may be called
563 // with non-empty |inline_autocomplete_text_|. In such cases, we cannot
564 // use the current selection, because it could result with the cursor
565 // position past the last character from the user text. Instead,
566 // we assume that the cursor is simply at the end of input.
567 // One example is when user presses Ctrl key while having a highlighted
568 // inline autocomplete text.
569 // TODO: Rethink how we are going to handle this case to avoid
570 // inconsistent behavior when user presses Ctrl key.
571 // See http://crbug.com/165961 and http://crbug.com/165968 for more details.
572 cursor_position
= user_text_
.length();
576 (delegate_
->CurrentPageExists() && view_
->IsIndicatingQueryRefinement()) ?
577 delegate_
->GetURL() : GURL();
578 bool keyword_is_selected
= KeywordIsSelected();
579 input_
= AutocompleteInput(
585 prevent_inline_autocomplete
|| just_deleted_text_
||
586 (has_selected_text
&& inline_autocomplete_text_
.empty()) ||
587 (paste_state_
!= NONE
),
589 keyword_is_selected
|| allow_exact_keyword_match_
,
592 omnibox_controller_
->StartAutocomplete(input_
);
595 void OmniboxEditModel::StopAutocomplete() {
596 autocomplete_controller()->Stop(true);
599 bool OmniboxEditModel::CanPasteAndGo(const base::string16
& text
) const {
600 if (!view_
->command_updater()->IsCommandEnabled(IDC_OPEN_CURRENT_URL
))
603 AutocompleteMatch match
;
604 ClassifyStringForPasteAndGo(text
, &match
, NULL
);
605 return match
.destination_url
.is_valid();
608 void OmniboxEditModel::PasteAndGo(const base::string16
& text
) {
609 DCHECK(CanPasteAndGo(text
));
610 UMA_HISTOGRAM_COUNTS("Omnibox.PasteAndGo", 1);
613 AutocompleteMatch match
;
614 GURL alternate_nav_url
;
615 ClassifyStringForPasteAndGo(text
, &match
, &alternate_nav_url
);
616 view_
->OpenMatch(match
, CURRENT_TAB
, alternate_nav_url
, text
,
617 OmniboxPopupModel::kNoMatch
);
620 bool OmniboxEditModel::IsPasteAndSearch(const base::string16
& text
) const {
621 AutocompleteMatch match
;
622 ClassifyStringForPasteAndGo(text
, &match
, NULL
);
623 return AutocompleteMatch::IsSearchType(match
.type
);
626 void OmniboxEditModel::AcceptInput(WindowOpenDisposition disposition
,
628 // Get the URL and transition type for the selected entry.
629 GURL alternate_nav_url
;
630 AutocompleteMatch match
= CurrentMatch(&alternate_nav_url
);
632 // If CTRL is down it means the user wants to append ".com" to the text he
633 // typed. If we can successfully generate a URL_WHAT_YOU_TYPED match doing
634 // that, then we use this. These matches are marked as generated by the
635 // HistoryURLProvider so we only generate them if this provider is present.
636 if (control_key_state_
== DOWN_WITHOUT_CHANGE
&& !KeywordIsSelected() &&
637 autocomplete_controller()->history_url_provider()) {
638 // Generate a new AutocompleteInput, copying the latest one but using "com"
639 // as the desired TLD. Then use this autocomplete input to generate a
640 // URL_WHAT_YOU_TYPED AutocompleteMatch. Note that using the most recent
641 // input instead of the currently visible text means we'll ignore any
642 // visible inline autocompletion: if a user types "foo" and is autocompleted
643 // to "foodnetwork.com", ctrl-enter will navigate to "foo.com", not
644 // "foodnetwork.com". At the time of writing, this behavior matches
645 // Internet Explorer, but not Firefox.
646 input_
= AutocompleteInput(
647 has_temporary_text_
?
648 UserTextFromDisplayText(view_
->GetText()) : input_
.text(),
649 input_
.cursor_position(), base::ASCIIToUTF16("com"),
650 GURL(), input_
.current_page_classification(),
651 input_
.prevent_inline_autocomplete(), input_
.prefer_keyword(),
652 input_
.allow_exact_keyword_match(),
653 input_
.want_asynchronous_matches());
654 AutocompleteMatch
url_match(
655 autocomplete_controller()->history_url_provider()->SuggestExactInput(
656 input_
.text(), input_
.canonicalized_url(), false));
659 if (url_match
.destination_url
.is_valid()) {
660 // We have a valid URL, we use this newly generated AutocompleteMatch.
662 alternate_nav_url
= GURL();
666 if (!match
.destination_url
.is_valid())
669 if ((match
.transition
== content::PAGE_TRANSITION_TYPED
) &&
670 (match
.destination_url
== PermanentURL())) {
671 // When the user hit enter on the existing permanent URL, treat it like a
672 // reload for scoring purposes. We could detect this by just checking
673 // user_input_in_progress_, but it seems better to treat "edits" that end
674 // up leaving the URL unchanged (e.g. deleting the last character and then
675 // retyping it) as reloads too. We exclude non-TYPED transitions because if
676 // the transition is GENERATED, the user input something that looked
677 // different from the current URL, even if it wound up at the same place
678 // (e.g. manually retyping the same search query), and it seems wrong to
679 // treat this as a reload.
680 match
.transition
= content::PAGE_TRANSITION_RELOAD
;
681 } else if (for_drop
|| ((paste_state_
!= NONE
) &&
682 match
.is_history_what_you_typed_match
)) {
683 // When the user pasted in a URL and hit enter, score it like a link click
684 // rather than a normal typed URL, so it doesn't get inline autocompleted
685 // as aggressively later.
686 match
.transition
= content::PAGE_TRANSITION_LINK
;
689 const TemplateURL
* template_url
= match
.GetTemplateURL(profile_
, false);
690 if (template_url
&& template_url
->url_ref().HasGoogleBaseURLs())
691 GoogleURLTracker::GoogleURLSearchCommitted(profile_
);
693 DCHECK(popup_model());
694 view_
->OpenMatch(match
, disposition
, alternate_nav_url
, base::string16(),
695 popup_model()->selected_line());
698 void OmniboxEditModel::OpenMatch(AutocompleteMatch match
,
699 WindowOpenDisposition disposition
,
700 const GURL
& alternate_nav_url
,
701 const base::string16
& pasted_text
,
703 const base::TimeTicks
& now(base::TimeTicks::Now());
704 base::TimeDelta
elapsed_time_since_user_first_modified_omnibox(
705 now
- time_user_first_modified_omnibox_
);
706 autocomplete_controller()->UpdateMatchDestinationURL(
707 elapsed_time_since_user_first_modified_omnibox
, &match
);
709 base::string16
input_text(pasted_text
);
710 if (input_text
.empty())
711 input_text
= user_input_in_progress_
? user_text_
: permanent_text_
;
712 scoped_ptr
<OmniboxNavigationObserver
> observer(
713 new OmniboxNavigationObserver(
714 profile_
, input_text
, match
,
715 autocomplete_controller()->history_url_provider()->SuggestExactInput(
716 input_text
, alternate_nav_url
,
717 AutocompleteInput::HasHTTPScheme(input_text
))));
719 base::TimeDelta
elapsed_time_since_last_change_to_default_match(
720 now
- autocomplete_controller()->last_time_default_match_changed());
721 DCHECK(match
.provider
);
722 // These elapsed times don't really make sense for ZeroSuggest matches
723 // (because the user does not modify the omnibox for ZeroSuggest), so for
724 // those we set the elapsed times to something that will be ignored by
725 // metrics_log.cc. They also don't necessarily make sense if the omnibox
726 // dropdown is closed or the user used a paste-and-go action. (In most
727 // cases when this happens, the user never modified the omnibox.)
728 if ((match
.provider
->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST
) ||
729 !popup_model()->IsOpen() || !pasted_text
.empty()) {
730 const base::TimeDelta default_time_delta
=
731 base::TimeDelta::FromMilliseconds(-1);
732 elapsed_time_since_user_first_modified_omnibox
= default_time_delta
;
733 elapsed_time_since_last_change_to_default_match
= default_time_delta
;
735 // If the popup is closed or this is a paste-and-go action (meaning the
736 // contents of the dropdown are ignored regardless), we record for logging
737 // purposes a selected_index of 0 and a suggestion list as having a single
738 // entry of the match used.
739 ACMatches fake_single_entry_matches
;
740 fake_single_entry_matches
.push_back(match
);
741 AutocompleteResult fake_single_entry_result
;
742 fake_single_entry_result
.AppendMatches(fake_single_entry_matches
);
747 popup_model()->IsOpen(),
748 (!popup_model()->IsOpen() || !pasted_text
.empty()) ? 0 : index
,
749 !pasted_text
.empty(),
750 -1, // don't yet know tab ID; set later if appropriate
752 elapsed_time_since_user_first_modified_omnibox
,
753 match
.inline_autocompletion
.length(),
754 elapsed_time_since_last_change_to_default_match
,
755 (!popup_model()->IsOpen() || !pasted_text
.empty()) ?
756 fake_single_entry_result
: result());
757 DCHECK(!popup_model()->IsOpen() || !pasted_text
.empty() ||
758 (log
.elapsed_time_since_user_first_modified_omnibox
>=
759 log
.elapsed_time_since_last_change_to_default_match
))
760 << "We should've got the notification that the user modified the "
761 << "omnibox text at same time or before the most recent time the "
762 << "default match changed.";
764 if ((disposition
== CURRENT_TAB
) && delegate_
->CurrentPageExists()) {
765 // If we know the destination is being opened in the current tab,
766 // we can easily get the tab ID. (If it's being opened in a new
767 // tab, we don't know the tab ID yet.)
768 log
.tab_id
= delegate_
->GetSessionID().id();
770 autocomplete_controller()->AddProvidersInfo(&log
.providers_info
);
771 content::NotificationService::current()->Notify(
772 chrome::NOTIFICATION_OMNIBOX_OPENED_URL
,
773 content::Source
<Profile
>(profile_
),
774 content::Details
<OmniboxLog
>(&log
));
775 HISTOGRAM_ENUMERATION("Omnibox.EventCount", 1, 2);
776 DCHECK(!last_omnibox_focus_
.is_null())
777 << "An omnibox focus should have occurred before opening a match.";
778 UMA_HISTOGRAM_TIMES(kFocusToOpenTimeHistogram
, now
- last_omnibox_focus_
);
780 TemplateURL
* template_url
= match
.GetTemplateURL(profile_
, false);
782 if (match
.transition
== content::PAGE_TRANSITION_KEYWORD
) {
783 // The user is using a non-substituting keyword or is explicitly in
786 // Don't increment usage count for extension keywords.
787 if (delegate_
->ProcessExtensionKeyword(template_url
, match
,
789 observer
->OnSuccessfulNavigation();
790 if (disposition
!= NEW_BACKGROUND_TAB
)
795 content::RecordAction(base::UserMetricsAction("AcceptedKeyword"));
796 TemplateURLServiceFactory::GetForProfile(profile_
)->IncrementUsageCount(
799 DCHECK_EQ(content::PAGE_TRANSITION_GENERATED
, match
.transition
);
800 // NOTE: We purposefully don't increment the usage count of the default
801 // search engine here like we do for explicit keywords above; see comments
802 // in template_url.h.
805 UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngineType",
806 TemplateURLPrepopulateData::GetEngineType(*template_url
),
810 // Get the current text before we call RevertAll() which will clear it.
811 base::string16 current_text
= view_
->GetText();
813 if (disposition
!= NEW_BACKGROUND_TAB
) {
814 base::AutoReset
<bool> tmp(&in_revert_
, true);
815 view_
->RevertAll(); // Revert the box to its unedited state.
818 if (match
.type
== AutocompleteMatchType::EXTENSION_APP
) {
819 ExtensionAppProvider::LaunchAppFromOmnibox(match
, profile_
, disposition
);
820 observer
->OnSuccessfulNavigation();
822 RecordPercentageMatchHistogram(
823 permanent_text_
, current_text
,
824 controller_
->GetToolbarModel()->WouldReplaceURL(),
825 match
.transition
, view_
->GetWidth());
827 // Track whether the destination URL sends us to a search results page
828 // using the default search provider.
829 if (TemplateURLServiceFactory::GetForProfile(profile_
)->
830 IsSearchResultsPageFromDefaultSearchProvider(match
.destination_url
)) {
831 content::RecordAction(
832 base::UserMetricsAction("OmniboxDestinationURLIsSearchOnDSP"));
835 if (match
.destination_url
.is_valid()) {
836 // This calls RevertAll again.
837 base::AutoReset
<bool> tmp(&in_revert_
, true);
838 controller_
->OnAutocompleteAccept(
839 match
.destination_url
, disposition
,
840 content::PageTransitionFromInt(
841 match
.transition
| content::PAGE_TRANSITION_FROM_ADDRESS_BAR
));
842 if (observer
->load_state() != OmniboxNavigationObserver::LOAD_NOT_SEEN
)
843 ignore_result(observer
.release()); // The observer will delete itself.
848 RecordBookmarkLaunch(NULL
, BOOKMARK_LAUNCH_LOCATION_OMNIBOX
);
851 bool OmniboxEditModel::AcceptKeyword(EnteredKeywordModeMethod entered_method
) {
852 DCHECK(is_keyword_hint_
&& !keyword_
.empty());
854 autocomplete_controller()->Stop(false);
855 is_keyword_hint_
= false;
857 if (popup_model() && popup_model()->IsOpen())
858 popup_model()->SetSelectedLineState(OmniboxPopupModel::KEYWORD
);
860 StartAutocomplete(false, true);
862 // Ensure the current selection is saved before showing keyword mode
863 // so that moving to another line and then reverting the text will restore
864 // the current state properly.
865 bool save_original_selection
= !has_temporary_text_
;
866 has_temporary_text_
= true;
867 view_
->OnTemporaryTextMaybeChanged(
868 DisplayTextFromUserText(CurrentMatch(NULL
).fill_into_edit
),
869 save_original_selection
, true);
871 content::RecordAction(base::UserMetricsAction("AcceptedKeywordHint"));
872 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram
, entered_method
,
873 ENTERED_KEYWORD_MODE_NUM_ITEMS
);
878 void OmniboxEditModel::AcceptTemporaryTextAsUserText() {
879 InternalSetUserText(UserTextFromDisplayText(view_
->GetText()));
880 has_temporary_text_
= false;
882 if (user_input_in_progress_
|| !in_revert_
)
883 delegate_
->OnInputStateChanged();
886 void OmniboxEditModel::ClearKeyword(const base::string16
& visible_text
) {
887 autocomplete_controller()->Stop(false);
888 omnibox_controller_
->ClearPopupKeywordMode();
890 const base::string16
window_text(keyword_
+ visible_text
);
892 // Only reset the result if the edit text has changed since the
893 // keyword was accepted, or if the popup is closed.
894 if (just_deleted_text_
|| !visible_text
.empty() ||
895 !(popup_model() && popup_model()->IsOpen())) {
896 view_
->OnBeforePossibleChange();
897 view_
->SetWindowTextAndCaretPos(window_text
.c_str(), keyword_
.length(),
900 is_keyword_hint_
= false;
901 view_
->OnAfterPossibleChange();
902 just_deleted_text_
= true; // OnAfterPossibleChange() fails to clear this
903 // since the edit contents have actually grown
906 is_keyword_hint_
= true;
907 view_
->SetWindowTextAndCaretPos(window_text
.c_str(), keyword_
.length(),
912 void OmniboxEditModel::OnSetFocus(bool control_down
) {
913 last_omnibox_focus_
= base::TimeTicks::Now();
914 user_input_since_focus_
= false;
916 // If the omnibox lost focus while the caret was hidden and then regained
917 // focus, OnSetFocus() is called and should restore visibility. Note that
918 // focus can be regained without an accompanying call to
919 // OmniboxView::SetFocus(), e.g. by tabbing in.
920 SetFocusState(OMNIBOX_FOCUS_VISIBLE
, OMNIBOX_FOCUS_CHANGE_EXPLICIT
);
921 control_key_state_
= control_down
? DOWN_WITHOUT_CHANGE
: UP
;
923 // Try to get ZeroSuggest suggestions if a page is loaded and the user has
924 // not been typing in the omnibox. The |user_input_in_progress_| check is
925 // used to detect the case where this function is called after right-clicking
926 // in the omnibox and selecting paste in Linux (in which case we actually get
927 // the OnSetFocus() call after the process of handling the paste has kicked
929 // TODO(hfung): Remove this when crbug/271590 is fixed.
930 if (delegate_
->CurrentPageExists() && !user_input_in_progress_
) {
931 // TODO(jered): We may want to merge this into Start() and just call that
932 // here rather than having a special entry point for zero-suggest. Note
933 // that we avoid PermanentURL() here because it's not guaranteed to give us
934 // the actual underlying current URL, e.g. if we're on the NTP and the
935 // |permanent_text_| is empty.
936 autocomplete_controller()->StartZeroSuggest(AutocompleteInput(
937 permanent_text_
, base::string16::npos
, base::string16(),
938 delegate_
->GetURL(), ClassifyPage(), false, false, true, true));
941 if (user_input_in_progress_
|| !in_revert_
)
942 delegate_
->OnInputStateChanged();
945 void OmniboxEditModel::SetCaretVisibility(bool visible
) {
946 // Caret visibility only matters if the omnibox has focus.
947 if (focus_state_
!= OMNIBOX_FOCUS_NONE
) {
948 SetFocusState(visible
? OMNIBOX_FOCUS_VISIBLE
: OMNIBOX_FOCUS_INVISIBLE
,
949 OMNIBOX_FOCUS_CHANGE_EXPLICIT
);
953 void OmniboxEditModel::OnWillKillFocus(gfx::NativeView view_gaining_focus
) {
954 if (user_input_in_progress_
|| !in_revert_
)
955 delegate_
->OnInputStateChanged();
958 void OmniboxEditModel::OnKillFocus() {
959 SetFocusState(OMNIBOX_FOCUS_NONE
, OMNIBOX_FOCUS_CHANGE_EXPLICIT
);
960 focus_source_
= INVALID
;
961 control_key_state_
= UP
;
965 bool OmniboxEditModel::OnEscapeKeyPressed() {
966 const AutocompleteMatch
& match
= CurrentMatch(NULL
);
967 if (has_temporary_text_
) {
968 if (match
.destination_url
!= original_url_
) {
969 RevertTemporaryText(true);
974 // We do not clear the pending entry from the omnibox when a load is first
975 // stopped. If the user presses Escape while stopped, we clear it.
976 if (delegate_
->CurrentPageExists() && !delegate_
->IsLoading()) {
977 delegate_
->GetNavigationController().DiscardNonCommittedEntries();
981 // When using the origin chip, hitting escape to revert all should either
982 // display the URL (when search term replacement would not be performed for
983 // this page) or the search terms (when it would). To accomplish this,
984 // we'll need to disable URL replacement iff it's currently enabled and
985 // search term replacement wouldn't normally happen.
986 bool should_disable_url_replacement
=
987 controller_
->GetToolbarModel()->url_replacement_enabled() &&
988 !controller_
->GetToolbarModel()->WouldPerformSearchTermReplacement(true);
990 // If the user wasn't editing, but merely had focus in the edit, allow <esc>
991 // to be processed as an accelerator, so it can still be used to stop a load.
992 // When the permanent text isn't all selected we still fall through to the
993 // SelectAll() call below so users can arrow around in the text and then hit
994 // <esc> to quickly replace all the text; this matches IE.
995 const bool has_zero_suggest_match
= match
.provider
&&
996 (match
.provider
->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST
);
997 if (!has_zero_suggest_match
&& !should_disable_url_replacement
&&
998 !user_input_in_progress_
&& view_
->IsSelectAll())
1001 if (!user_text_
.empty()) {
1002 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram
,
1003 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE
,
1004 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS
);
1007 if (should_disable_url_replacement
) {
1008 controller_
->GetToolbarModel()->set_url_replacement_enabled(false);
1009 UpdatePermanentText();
1011 view_
->RevertWithoutResettingSearchTermReplacement();
1012 view_
->SelectAll(true);
1016 void OmniboxEditModel::OnControlKeyChanged(bool pressed
) {
1017 if (pressed
== (control_key_state_
== UP
))
1018 control_key_state_
= pressed
? DOWN_WITHOUT_CHANGE
: UP
;
1021 void OmniboxEditModel::OnPaste() {
1022 UMA_HISTOGRAM_COUNTS("Omnibox.Paste", 1);
1023 paste_state_
= PASTING
;
1026 void OmniboxEditModel::OnUpOrDownKeyPressed(int count
) {
1027 // NOTE: This purposefully doesn't trigger any code that resets paste_state_.
1028 if (popup_model() && popup_model()->IsOpen()) {
1029 // The popup is open, so the user should be able to interact with it
1031 popup_model()->Move(count
);
1035 if (!query_in_progress()) {
1036 // The popup is neither open nor working on a query already. So, start an
1037 // autocomplete query for the current text. This also sets
1038 // user_input_in_progress_ to true, which we want: if the user has started
1039 // to interact with the popup, changing the permanent_text_ shouldn't change
1040 // the displayed text.
1041 // Note: This does not force the popup to open immediately.
1042 // TODO(pkasting): We should, in fact, force this particular query to open
1043 // the popup immediately.
1044 if (!user_input_in_progress_
)
1045 InternalSetUserText(permanent_text_
);
1046 view_
->UpdatePopup();
1050 // TODO(pkasting): The popup is working on a query but is not open. We should
1051 // force it to open immediately.
1054 void OmniboxEditModel::OnPopupDataChanged(
1055 const base::string16
& text
,
1056 GURL
* destination_for_temporary_text_change
,
1057 const base::string16
& keyword
,
1058 bool is_keyword_hint
) {
1059 // The popup changed its data, the match in the controller is no longer valid.
1060 omnibox_controller_
->InvalidateCurrentMatch();
1062 // Update keyword/hint-related local state.
1063 bool keyword_state_changed
= (keyword_
!= keyword
) ||
1064 ((is_keyword_hint_
!= is_keyword_hint
) && !keyword
.empty());
1065 if (keyword_state_changed
) {
1067 is_keyword_hint_
= is_keyword_hint
;
1069 // |is_keyword_hint_| should always be false if |keyword_| is empty.
1070 DCHECK(!keyword_
.empty() || !is_keyword_hint_
);
1073 // Handle changes to temporary text.
1074 if (destination_for_temporary_text_change
!= NULL
) {
1075 const bool save_original_selection
= !has_temporary_text_
;
1076 if (save_original_selection
) {
1077 // Save the original selection and URL so it can be reverted later.
1078 has_temporary_text_
= true;
1079 original_url_
= *destination_for_temporary_text_change
;
1080 inline_autocomplete_text_
.clear();
1081 view_
->OnInlineAutocompleteTextCleared();
1083 if (control_key_state_
== DOWN_WITHOUT_CHANGE
) {
1084 // Arrowing around the popup cancels control-enter.
1085 control_key_state_
= DOWN_WITH_CHANGE
;
1086 // Now things are a bit screwy: the desired_tld has changed, but if we
1087 // update the popup, the new order of entries won't match the old, so the
1088 // user's selection gets screwy; and if we don't update the popup, and the
1089 // user reverts, then the selected item will be as if control is still
1090 // pressed, even though maybe it isn't any more. There is no obvious
1091 // right answer here :(
1093 view_
->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text
),
1094 save_original_selection
, true);
1098 bool call_controller_onchanged
= true;
1099 inline_autocomplete_text_
= text
;
1100 if (inline_autocomplete_text_
.empty())
1101 view_
->OnInlineAutocompleteTextCleared();
1103 const base::string16
& user_text
=
1104 user_input_in_progress_
? user_text_
: permanent_text_
;
1105 if (keyword_state_changed
&& KeywordIsSelected()) {
1106 // If we reach here, the user most likely entered keyword mode by inserting
1107 // a space between a keyword name and a search string (as pressing space or
1108 // tab after the keyword name alone would have been be handled in
1109 // MaybeAcceptKeywordBySpace() by calling AcceptKeyword(), which won't reach
1110 // here). In this case, we don't want to call
1111 // OnInlineAutocompleteTextMaybeChanged() as normal, because that will
1112 // correctly change the text (to the search string alone) but move the caret
1113 // to the end of the string; instead we want the caret at the start of the
1114 // search string since that's where it was in the original input. So we set
1115 // the text and caret position directly.
1117 // It may also be possible to reach here if we're reverting from having
1118 // temporary text back to a default match that's a keyword search, but in
1119 // that case the RevertTemporaryText() call below will reset the caret or
1120 // selection correctly so the caret positioning we do here won't matter.
1121 view_
->SetWindowTextAndCaretPos(DisplayTextFromUserText(user_text
), 0,
1123 } else if (view_
->OnInlineAutocompleteTextMaybeChanged(
1124 DisplayTextFromUserText(user_text
+ inline_autocomplete_text_
),
1125 DisplayTextFromUserText(user_text
).length())) {
1126 call_controller_onchanged
= false;
1129 // If |has_temporary_text_| is true, then we previously had a manual selection
1130 // but now don't (or |destination_for_temporary_text_change| would have been
1131 // non-NULL). This can happen when deleting the selected item in the popup.
1132 // In this case, we've already reverted the popup to the default match, so we
1133 // need to revert ourselves as well.
1134 if (has_temporary_text_
) {
1135 RevertTemporaryText(false);
1136 call_controller_onchanged
= false;
1139 // We need to invoke OnChanged in case the destination url changed (as could
1140 // happen when control is toggled).
1141 if (call_controller_onchanged
)
1145 bool OmniboxEditModel::OnAfterPossibleChange(const base::string16
& old_text
,
1146 const base::string16
& new_text
,
1147 size_t selection_start
,
1148 size_t selection_end
,
1149 bool selection_differs
,
1151 bool just_deleted_text
,
1152 bool allow_keyword_ui_change
) {
1153 // Update the paste state as appropriate: if we're just finishing a paste
1154 // that replaced all the text, preserve that information; otherwise, if we've
1155 // made some other edit, clear paste tracking.
1156 if (paste_state_
== PASTING
)
1157 paste_state_
= PASTED
;
1158 else if (text_differs
)
1159 paste_state_
= NONE
;
1161 if (text_differs
|| selection_differs
) {
1162 // Record current focus state for this input if we haven't already.
1163 if (focus_source_
== INVALID
) {
1164 // We should generally expect the omnibox to have focus at this point, but
1165 // it doesn't always on Linux. This is because, unlike other platforms,
1166 // right clicking in the omnibox on Linux doesn't focus it. So pasting via
1167 // right-click can change the contents without focusing the omnibox.
1168 // TODO(samarth): fix Linux focus behavior and add a DCHECK here to
1169 // check that the omnibox does have focus.
1170 focus_source_
= (focus_state_
== OMNIBOX_FOCUS_INVISIBLE
) ?
1174 // Restore caret visibility whenever the user changes text or selection in
1176 SetFocusState(OMNIBOX_FOCUS_VISIBLE
, OMNIBOX_FOCUS_CHANGE_TYPING
);
1179 // Modifying the selection counts as accepting the autocompleted text.
1180 const bool user_text_changed
=
1181 text_differs
|| (selection_differs
&& !inline_autocomplete_text_
.empty());
1183 // If something has changed while the control key is down, prevent
1184 // "ctrl-enter" until the control key is released.
1185 if ((text_differs
|| selection_differs
) &&
1186 (control_key_state_
== DOWN_WITHOUT_CHANGE
))
1187 control_key_state_
= DOWN_WITH_CHANGE
;
1189 if (!user_text_changed
)
1192 // If the user text has not changed, we do not want to change the model's
1193 // state associated with the text. Otherwise, we can get surprising behavior
1194 // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983
1195 InternalSetUserText(UserTextFromDisplayText(new_text
));
1196 has_temporary_text_
= false;
1198 // Track when the user has deleted text so we won't allow inline
1200 just_deleted_text_
= just_deleted_text
;
1202 if (user_input_in_progress_
&& user_text_
.empty()) {
1203 // Log cases where the user started editing and then subsequently cleared
1204 // all the text. Note that this explicitly doesn't catch cases like
1205 // "hit ctrl-l to select whole edit contents, then hit backspace", because
1206 // in such cases, |user_input_in_progress| won't be true here.
1207 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram
,
1208 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING
,
1209 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS
);
1212 const bool no_selection
= selection_start
== selection_end
;
1214 // Update the popup for the change, in the process changing to keyword mode
1215 // if the user hit space in mid-string after a keyword.
1216 // |allow_exact_keyword_match_| will be used by StartAutocomplete() method,
1217 // which will be called by |view_->UpdatePopup()|; so after that returns we
1218 // can safely reset this flag.
1219 allow_exact_keyword_match_
= text_differs
&& allow_keyword_ui_change
&&
1220 !just_deleted_text
&& no_selection
&&
1221 CreatedKeywordSearchByInsertingSpaceInMiddle(old_text
, user_text_
,
1223 if (allow_exact_keyword_match_
) {
1224 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram
,
1225 ENTERED_KEYWORD_MODE_VIA_SPACE_IN_MIDDLE
,
1226 ENTERED_KEYWORD_MODE_NUM_ITEMS
);
1228 view_
->UpdatePopup();
1229 allow_exact_keyword_match_
= false;
1231 // Change to keyword mode if the user is now pressing space after a keyword
1232 // name. Note that if this is the case, then even if there was no keyword
1233 // hint when we entered this function (e.g. if the user has used space to
1234 // replace some selected text that was adjoined to this keyword), there will
1235 // be one now because of the call to UpdatePopup() above; so it's safe for
1236 // MaybeAcceptKeywordBySpace() to look at |keyword_| and |is_keyword_hint_| to
1237 // determine what keyword, if any, is applicable.
1239 // If MaybeAcceptKeywordBySpace() accepts the keyword and returns true, that
1240 // will have updated our state already, so in that case we don't also return
1241 // true from this function.
1242 return !(text_differs
&& allow_keyword_ui_change
&& !just_deleted_text
&&
1243 no_selection
&& (selection_start
== user_text_
.length()) &&
1244 MaybeAcceptKeywordBySpace(user_text_
));
1247 // TODO(beaudoin): Merge OnPopupDataChanged with this method once the popup
1248 // handling has completely migrated to omnibox_controller.
1249 void OmniboxEditModel::OnCurrentMatchChanged() {
1250 has_temporary_text_
= false;
1252 const AutocompleteMatch
& match
= omnibox_controller_
->current_match();
1254 // We store |keyword| and |is_keyword_hint| in temporary variables since
1255 // OnPopupDataChanged use their previous state to detect changes.
1256 base::string16 keyword
;
1257 bool is_keyword_hint
;
1258 match
.GetKeywordUIState(profile_
, &keyword
, &is_keyword_hint
);
1260 popup_model()->OnResultChanged();
1261 // OnPopupDataChanged() resets OmniboxController's |current_match_| early
1262 // on. Therefore, copy match.inline_autocompletion to a temp to preserve
1263 // its value across the entire call.
1264 const base::string16
inline_autocompletion(match
.inline_autocompletion
);
1265 OnPopupDataChanged(inline_autocompletion
, NULL
, keyword
, is_keyword_hint
);
1268 void OmniboxEditModel::SetSuggestionToPrefetch(
1269 const InstantSuggestion
& suggestion
) {
1270 delegate_
->SetSuggestionToPrefetch(suggestion
);
1274 const char OmniboxEditModel::kCutOrCopyAllTextHistogram
[] =
1275 "Omnibox.CutOrCopyAllText";
1277 bool OmniboxEditModel::query_in_progress() const {
1278 return !autocomplete_controller()->done();
1281 void OmniboxEditModel::InternalSetUserText(const base::string16
& text
) {
1283 just_deleted_text_
= false;
1284 inline_autocomplete_text_
.clear();
1285 view_
->OnInlineAutocompleteTextCleared();
1288 bool OmniboxEditModel::KeywordIsSelected() const {
1289 return !is_keyword_hint_
&& !keyword_
.empty();
1292 void OmniboxEditModel::ClearPopupKeywordMode() const {
1293 omnibox_controller_
->ClearPopupKeywordMode();
1296 base::string16
OmniboxEditModel::DisplayTextFromUserText(
1297 const base::string16
& text
) const {
1298 return KeywordIsSelected() ?
1299 KeywordProvider::SplitReplacementStringFromInput(text
, false) : text
;
1302 base::string16
OmniboxEditModel::UserTextFromDisplayText(
1303 const base::string16
& text
) const {
1304 return KeywordIsSelected() ? (keyword_
+ base::char16(' ') + text
) : text
;
1307 void OmniboxEditModel::GetInfoForCurrentText(AutocompleteMatch
* match
,
1308 GURL
* alternate_nav_url
) const {
1309 DCHECK(match
!= NULL
);
1311 if (controller_
->GetToolbarModel()->WouldPerformSearchTermReplacement(
1313 // Any time the user hits enter on the unchanged omnibox, we should reload.
1314 // When we're not extracting search terms, AcceptInput() will take care of
1315 // this (see code referring to PAGE_TRANSITION_RELOAD there), but when we're
1316 // extracting search terms, the conditionals there won't fire, so we
1317 // explicitly set up a match that will reload here.
1319 // It's important that we fetch the current visible URL to reload instead of
1320 // just getting a "search what you typed" URL from
1321 // SearchProvider::CreateSearchSuggestion(), since the user may be in a
1322 // non-default search mode such as image search.
1323 match
->type
= AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED
;
1324 match
->provider
= autocomplete_controller()->search_provider();
1325 match
->destination_url
=
1326 delegate_
->GetNavigationController().GetVisibleEntry()->GetURL();
1327 match
->transition
= content::PAGE_TRANSITION_RELOAD
;
1328 } else if (query_in_progress() ||
1329 (popup_model() && popup_model()->IsOpen())) {
1330 if (query_in_progress()) {
1331 // It's technically possible for |result| to be empty if no provider
1332 // returns a synchronous result but the query has not completed
1333 // synchronously; pratically, however, that should never actually happen.
1334 if (result().empty())
1336 // The user cannot have manually selected a match, or the query would have
1337 // stopped. So the default match must be the desired selection.
1338 *match
= *result().default_match();
1340 // If there are no results, the popup should be closed, so we shouldn't
1341 // have gotten here.
1342 CHECK(!result().empty());
1343 CHECK(popup_model()->selected_line() < result().size());
1344 *match
= result().match_at(popup_model()->selected_line());
1346 if (alternate_nav_url
&&
1347 (!popup_model() || popup_model()->manually_selected_match().empty()))
1348 *alternate_nav_url
= result().alternate_nav_url();
1350 AutocompleteClassifierFactory::GetForProfile(profile_
)->Classify(
1351 UserTextFromDisplayText(view_
->GetText()), KeywordIsSelected(), true,
1352 ClassifyPage(), match
, alternate_nav_url
);
1356 void OmniboxEditModel::RevertTemporaryText(bool revert_popup
) {
1357 // The user typed something, then selected a different item. Restore the
1358 // text they typed and change back to the default item.
1359 // NOTE: This purposefully does not reset paste_state_.
1360 just_deleted_text_
= false;
1361 has_temporary_text_
= false;
1363 if (revert_popup
&& popup_model())
1364 popup_model()->ResetToDefaultMatch();
1365 view_
->OnRevertTemporaryText();
1368 bool OmniboxEditModel::MaybeAcceptKeywordBySpace(
1369 const base::string16
& new_text
) {
1370 size_t keyword_length
= new_text
.length() - 1;
1371 return (paste_state_
== NONE
) && is_keyword_hint_
&& !keyword_
.empty() &&
1372 inline_autocomplete_text_
.empty() &&
1373 (keyword_
.length() == keyword_length
) &&
1374 IsSpaceCharForAcceptingKeyword(new_text
[keyword_length
]) &&
1375 !new_text
.compare(0, keyword_length
, keyword_
, 0, keyword_length
) &&
1376 AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_SPACE_AT_END
);
1379 bool OmniboxEditModel::CreatedKeywordSearchByInsertingSpaceInMiddle(
1380 const base::string16
& old_text
,
1381 const base::string16
& new_text
,
1382 size_t caret_position
) const {
1383 DCHECK_GE(new_text
.length(), caret_position
);
1385 // Check simple conditions first.
1386 if ((paste_state_
!= NONE
) || (caret_position
< 2) ||
1387 (old_text
.length() < caret_position
) ||
1388 (new_text
.length() == caret_position
))
1390 size_t space_position
= caret_position
- 1;
1391 if (!IsSpaceCharForAcceptingKeyword(new_text
[space_position
]) ||
1392 IsWhitespace(new_text
[space_position
- 1]) ||
1393 new_text
.compare(0, space_position
, old_text
, 0, space_position
) ||
1394 !new_text
.compare(space_position
, new_text
.length() - space_position
,
1395 old_text
, space_position
,
1396 old_text
.length() - space_position
)) {
1400 // Then check if the text before the inserted space matches a keyword.
1401 base::string16 keyword
;
1402 base::TrimWhitespace(new_text
.substr(0, space_position
), base::TRIM_LEADING
,
1404 return !keyword
.empty() && !autocomplete_controller()->keyword_provider()->
1405 GetKeywordForText(keyword
).empty();
1409 bool OmniboxEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c
) {
1411 case 0x0020: // Space
1412 case 0x3000: // Ideographic Space
1419 AutocompleteInput::PageClassification
OmniboxEditModel::ClassifyPage() const {
1420 if (!delegate_
->CurrentPageExists())
1421 return AutocompleteInput::OTHER
;
1422 if (delegate_
->IsInstantNTP()) {
1423 // Note that we treat OMNIBOX as the source if focus_source_ is INVALID,
1424 // i.e., if input isn't actually in progress.
1425 return (focus_source_
== FAKEBOX
) ?
1426 AutocompleteInput::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS
:
1427 AutocompleteInput::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS
;
1429 const GURL
& gurl
= delegate_
->GetURL();
1430 if (!gurl
.is_valid())
1431 return AutocompleteInput::INVALID_SPEC
;
1432 const std::string
& url
= gurl
.spec();
1433 if (url
== chrome::kChromeUINewTabURL
)
1434 return AutocompleteInput::NTP
;
1435 if (url
== content::kAboutBlankURL
)
1436 return AutocompleteInput::BLANK
;
1437 if (url
== profile()->GetPrefs()->GetString(prefs::kHomePage
))
1438 return AutocompleteInput::HOME_PAGE
;
1439 if (controller_
->GetToolbarModel()->WouldPerformSearchTermReplacement(true))
1440 return AutocompleteInput::SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT
;
1441 if (delegate_
->IsSearchResultsPage())
1442 return AutocompleteInput::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT
;
1443 return AutocompleteInput::OTHER
;
1446 void OmniboxEditModel::ClassifyStringForPasteAndGo(
1447 const base::string16
& text
,
1448 AutocompleteMatch
* match
,
1449 GURL
* alternate_nav_url
) const {
1451 AutocompleteClassifierFactory::GetForProfile(profile_
)->Classify(
1452 text
, false, false, ClassifyPage(), match
, alternate_nav_url
);
1455 void OmniboxEditModel::SetFocusState(OmniboxFocusState state
,
1456 OmniboxFocusChangeReason reason
) {
1457 if (state
== focus_state_
)
1460 // Update state and notify view if the omnibox has focus and the caret
1461 // visibility changed.
1462 const bool was_caret_visible
= is_caret_visible();
1463 focus_state_
= state
;
1464 if (focus_state_
!= OMNIBOX_FOCUS_NONE
&&
1465 is_caret_visible() != was_caret_visible
)
1466 view_
->ApplyCaretVisibility();
1468 delegate_
->OnFocusChanged(focus_state_
, reason
);