1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
10 #include "base/auto_reset.h"
11 #include "base/format_macros.h"
12 #include "base/metrics/histogram.h"
13 #include "base/metrics/user_metrics.h"
14 #include "base/prefs/pref_service.h"
15 #include "base/profiler/scoped_tracker.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
21 #include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
22 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
23 #include "chrome/browser/bookmarks/bookmark_stats.h"
24 #include "chrome/browser/profiles/profile.h"
25 #include "chrome/browser/search_engines/template_url_service_factory.h"
26 #include "chrome/browser/search_engines/ui_thread_search_terms_data.h"
27 #include "chrome/browser/ui/omnibox/omnibox_navigation_observer.h"
28 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
29 #include "chrome/browser/ui/omnibox/omnibox_view.h"
30 #include "chrome/common/pref_names.h"
31 #include "chrome/common/url_constants.h"
32 #include "components/bookmarks/browser/bookmark_model.h"
33 #include "components/metrics/proto/omnibox_event.pb.h"
34 #include "components/omnibox/browser/autocomplete_classifier.h"
35 #include "components/omnibox/browser/autocomplete_match_type.h"
36 #include "components/omnibox/browser/autocomplete_provider.h"
37 #include "components/omnibox/browser/history_url_provider.h"
38 #include "components/omnibox/browser/keyword_provider.h"
39 #include "components/omnibox/browser/omnibox_client.h"
40 #include "components/omnibox/browser/omnibox_edit_controller.h"
41 #include "components/omnibox/browser/omnibox_log.h"
42 #include "components/omnibox/browser/omnibox_popup_view.h"
43 #include "components/omnibox/browser/search_provider.h"
44 #include "components/search_engines/template_url.h"
45 #include "components/search_engines/template_url_prepopulate_data.h"
46 #include "components/search_engines/template_url_service.h"
47 #include "components/toolbar/toolbar_model.h"
48 #include "components/url_fixer/url_fixer.h"
49 #include "ui/gfx/image/image.h"
50 #include "url/url_util.h"
52 using bookmarks::BookmarkModel
;
53 using metrics::OmniboxEventProto
;
56 // Helpers --------------------------------------------------------------------
60 // Histogram name which counts the number of times that the user text is
61 // cleared. IME users are sometimes in the situation that IME was
62 // unintentionally turned on and failed to input latin alphabets (ASCII
63 // characters) or the opposite case. In that case, users may delete all
64 // the text and the user text gets cleared. We'd like to measure how often
65 // this scenario happens.
67 // Note that since we don't currently correlate "text cleared" events with
68 // IME usage, this also captures many other cases where users clear the text;
69 // though it explicitly doesn't log deleting all the permanent text as
70 // the first action of an editing sequence (see comments in
71 // OnAfterPossibleChange()).
72 const char kOmniboxUserTextClearedHistogram
[] = "Omnibox.UserTextCleared";
74 enum UserTextClearedType
{
75 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING
= 0,
76 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE
= 1,
77 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS
,
80 // Histogram name which counts the number of times the user enters
81 // keyword hint mode and via what method. The possible values are listed
82 // in the EnteredKeywordModeMethod enum which is defined in the .h file.
83 const char kEnteredKeywordModeHistogram
[] = "Omnibox.EnteredKeywordMode";
85 // Histogram name which counts the number of milliseconds a user takes
86 // between focusing and editing the omnibox.
87 const char kFocusToEditTimeHistogram
[] = "Omnibox.FocusToEditTime";
89 // Histogram name which counts the number of milliseconds a user takes
90 // between focusing and opening an omnibox match.
91 const char kFocusToOpenTimeHistogram
[] = "Omnibox.FocusToOpenTimeAnyPopupState";
93 // Split the percentage match histograms into buckets based on the width of the
95 const int kPercentageMatchHistogramWidthBuckets
[] = { 400, 700, 1200 };
97 void RecordPercentageMatchHistogram(const base::string16
& old_text
,
98 const base::string16
& new_text
,
99 bool url_replacement_active
,
100 ui::PageTransition transition
,
102 size_t avg_length
= (old_text
.length() + new_text
.length()) / 2;
105 if (!old_text
.empty() && !new_text
.empty()) {
106 size_t shorter_length
= std::min(old_text
.length(), new_text
.length());
107 base::string16::const_iterator
end(old_text
.begin() + shorter_length
);
108 base::string16::const_iterator
mismatch(
109 std::mismatch(old_text
.begin(), end
, new_text
.begin()).first
);
110 size_t matching_characters
= mismatch
- old_text
.begin();
111 percent
= static_cast<float>(matching_characters
) / avg_length
* 100;
114 std::string histogram_name
;
115 if (url_replacement_active
) {
116 if (transition
== ui::PAGE_TRANSITION_TYPED
) {
117 histogram_name
= "InstantExtended.PercentageMatchV2_QuerytoURL";
118 UMA_HISTOGRAM_PERCENTAGE(histogram_name
, percent
);
120 histogram_name
= "InstantExtended.PercentageMatchV2_QuerytoQuery";
121 UMA_HISTOGRAM_PERCENTAGE(histogram_name
, percent
);
124 if (transition
== ui::PAGE_TRANSITION_TYPED
) {
125 histogram_name
= "InstantExtended.PercentageMatchV2_URLtoURL";
126 UMA_HISTOGRAM_PERCENTAGE(histogram_name
, percent
);
128 histogram_name
= "InstantExtended.PercentageMatchV2_URLtoQuery";
129 UMA_HISTOGRAM_PERCENTAGE(histogram_name
, percent
);
133 std::string suffix
= "large";
134 for (size_t i
= 0; i
< arraysize(kPercentageMatchHistogramWidthBuckets
);
136 if (omnibox_width
< kPercentageMatchHistogramWidthBuckets
[i
]) {
137 suffix
= base::IntToString(kPercentageMatchHistogramWidthBuckets
[i
]);
142 // Cannot rely on UMA histograms macro because the name of the histogram is
143 // generated dynamically.
144 base::HistogramBase
* counter
= base::LinearHistogram::FactoryGet(
145 histogram_name
+ "_" + suffix
, 1, 101, 102,
146 base::Histogram::kUmaTargetedHistogramFlag
);
147 counter
->Add(percent
);
153 // OmniboxEditModel::State ----------------------------------------------------
155 OmniboxEditModel::State::State(bool user_input_in_progress
,
156 const base::string16
& user_text
,
157 const base::string16
& gray_text
,
158 const base::string16
& keyword
,
159 bool is_keyword_hint
,
160 bool url_replacement_enabled
,
161 OmniboxFocusState focus_state
,
162 FocusSource focus_source
,
163 const AutocompleteInput
& autocomplete_input
)
164 : user_input_in_progress(user_input_in_progress
),
165 user_text(user_text
),
166 gray_text(gray_text
),
168 is_keyword_hint(is_keyword_hint
),
169 url_replacement_enabled(url_replacement_enabled
),
170 focus_state(focus_state
),
171 focus_source(focus_source
),
172 autocomplete_input(autocomplete_input
) {
175 OmniboxEditModel::State::~State() {
179 // OmniboxEditModel -----------------------------------------------------------
181 OmniboxEditModel::OmniboxEditModel(OmniboxView
* view
,
182 OmniboxEditController
* controller
,
183 scoped_ptr
<OmniboxClient
> client
,
185 : client_(client
.Pass()),
187 controller_(controller
),
188 focus_state_(OMNIBOX_FOCUS_NONE
),
189 focus_source_(INVALID
),
190 user_input_in_progress_(false),
191 user_input_since_focus_(true),
192 just_deleted_text_(false),
193 has_temporary_text_(false),
195 control_key_state_(UP
),
196 is_keyword_hint_(false),
199 allow_exact_keyword_match_(false) {
200 omnibox_controller_
.reset(new OmniboxController(this, client_
.get()));
203 OmniboxEditModel::~OmniboxEditModel() {
206 const OmniboxEditModel::State
OmniboxEditModel::GetStateForTabSwitch() {
207 // Like typing, switching tabs "accepts" the temporary text as the user
208 // text, because it makes little sense to have temporary text when the
210 if (user_input_in_progress_
) {
211 // Weird edge case to match other browsers: if the edit is empty, revert to
212 // the permanent text (so the user can get it back easily) but select it (so
213 // on switching back, typing will "just work").
214 const base::string16
user_text(UserTextFromDisplayText(view_
->GetText()));
215 if (user_text
.empty()) {
216 base::AutoReset
<bool> tmp(&in_revert_
, true);
218 view_
->SelectAll(true);
220 InternalSetUserText(user_text
);
224 UMA_HISTOGRAM_BOOLEAN("Omnibox.SaveStateForTabSwitch.UserInputInProgress",
225 user_input_in_progress_
);
227 user_input_in_progress_
, user_text_
, view_
->GetGrayTextAutocompletion(),
228 keyword_
, is_keyword_hint_
,
229 controller_
->GetToolbarModel()->url_replacement_enabled(),
230 focus_state_
, focus_source_
, input_
);
233 void OmniboxEditModel::RestoreState(const State
* state
) {
234 // We need to update the permanent text correctly and revert the view
235 // regardless of whether there is saved state.
236 bool url_replacement_enabled
= !state
|| state
->url_replacement_enabled
;
237 controller_
->GetToolbarModel()->set_url_replacement_enabled(
238 url_replacement_enabled
);
239 permanent_text_
= controller_
->GetToolbarModel()->GetText();
240 // Don't muck with the search term replacement state, as we've just set it
242 view_
->RevertWithoutResettingSearchTermReplacement();
243 // Restore the autocomplete controller's input, or clear it if this is a new
245 input_
= state
? state
->autocomplete_input
: AutocompleteInput();
249 SetFocusState(state
->focus_state
, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH
);
250 focus_source_
= state
->focus_source
;
251 // Restore any user editing.
252 if (state
->user_input_in_progress
) {
253 // NOTE: Be sure and set keyword-related state BEFORE invoking
254 // DisplayTextFromUserText(), as its result depends upon this state.
255 keyword_
= state
->keyword
;
256 is_keyword_hint_
= state
->is_keyword_hint
;
257 view_
->SetUserText(state
->user_text
,
258 DisplayTextFromUserText(state
->user_text
), false);
259 view_
->SetGrayTextAutocompletion(state
->gray_text
);
263 AutocompleteMatch
OmniboxEditModel::CurrentMatch(
264 GURL
* alternate_nav_url
) const {
265 // If we have a valid match use it. Otherwise get one for the current text.
266 AutocompleteMatch match
= omnibox_controller_
->current_match();
268 if (!match
.destination_url
.is_valid()) {
269 GetInfoForCurrentText(&match
, alternate_nav_url
);
270 } else if (alternate_nav_url
) {
271 *alternate_nav_url
= AutocompleteResult::ComputeAlternateNavUrl(
277 bool OmniboxEditModel::UpdatePermanentText() {
278 // When there's new permanent text, and the user isn't interacting with the
279 // omnibox, we want to revert the edit to show the new text. We could simply
280 // define "interacting" as "the omnibox has focus", but we still allow updates
281 // when the omnibox has focus as long as the user hasn't begun editing, isn't
282 // seeing zerosuggestions (because changing this text would require changing
283 // or hiding those suggestions), and hasn't toggled on "Show URL" (because
284 // this update will re-enable search term replacement, which will be annoying
285 // if the user is trying to copy the URL). When the omnibox doesn't have
286 // focus, we assume the user may have abandoned their interaction and it's
287 // always safe to change the text; this also prevents someone toggling "Show
288 // URL" (which sounds as if it might be persistent) from seeing just that URL
289 // forever afterwards.
291 // If the page is auto-committing gray text, however, we generally don't want
292 // to make any change to the edit. While auto-commits modify the underlying
293 // permanent URL, they're intended to have no effect on the user's editing
294 // process -- before and after the auto-commit, the omnibox should show the
295 // same user text and the same instant suggestion, even if the auto-commit
296 // happens while the edit doesn't have focus.
297 base::string16 new_permanent_text
= controller_
->GetToolbarModel()->GetText();
298 base::string16 gray_text
= view_
->GetGrayTextAutocompletion();
299 const bool visibly_changed_permanent_text
=
300 (permanent_text_
!= new_permanent_text
) &&
302 (!user_input_in_progress_
&&
303 !(popup_model() && popup_model()->IsOpen()) &&
304 controller_
->GetToolbarModel()->url_replacement_enabled())) &&
305 (gray_text
.empty() ||
306 new_permanent_text
!= user_text_
+ gray_text
);
308 permanent_text_
= new_permanent_text
;
309 return visibly_changed_permanent_text
;
312 GURL
OmniboxEditModel::PermanentURL() {
313 return url_fixer::FixupURL(base::UTF16ToUTF8(permanent_text_
), std::string());
316 void OmniboxEditModel::SetUserText(const base::string16
& text
) {
317 SetInputInProgress(true);
318 InternalSetUserText(text
);
319 omnibox_controller_
->InvalidateCurrentMatch();
321 has_temporary_text_
= false;
324 bool OmniboxEditModel::CommitSuggestedText() {
325 const base::string16 suggestion
= view_
->GetGrayTextAutocompletion();
326 if (suggestion
.empty())
329 const base::string16 final_text
= view_
->GetText() + suggestion
;
330 view_
->OnBeforePossibleChange();
331 view_
->SetWindowTextAndCaretPos(final_text
, final_text
.length(), false,
333 view_
->OnAfterPossibleChange();
337 void OmniboxEditModel::OnChanged() {
338 // Hide any suggestions we might be showing.
339 view_
->SetGrayTextAutocompletion(base::string16());
341 // Don't call CurrentMatch() when there's no editing, as in this case we'll
342 // never actually use it. This avoids running the autocomplete providers (and
343 // any systems they then spin up) during startup.
344 const AutocompleteMatch
& current_match
= user_input_in_progress_
?
345 CurrentMatch(NULL
) : AutocompleteMatch();
347 client_
->OnTextChanged(current_match
, user_input_in_progress_
, user_text_
,
348 result(), popup_model() && popup_model()->IsOpen(),
350 controller_
->OnChanged();
353 void OmniboxEditModel::GetDataForURLExport(GURL
* url
,
354 base::string16
* title
,
355 gfx::Image
* favicon
) {
356 *url
= CurrentMatch(NULL
).destination_url
;
357 if (*url
== client_
->GetURL()) {
358 *title
= client_
->GetTitle();
359 *favicon
= client_
->GetFavicon();
363 bool OmniboxEditModel::CurrentTextIsURL() const {
364 if (controller_
->GetToolbarModel()->WouldReplaceURL())
367 // If current text is not composed of replaced search terms and
368 // !user_input_in_progress_, then permanent text is showing and should be a
369 // URL, so no further checking is needed. By avoiding checking in this case,
370 // we avoid calling into the autocomplete providers, and thus initializing the
371 // history system, as long as possible, which speeds startup.
372 if (!user_input_in_progress_
)
375 return !AutocompleteMatch::IsSearchType(CurrentMatch(NULL
).type
);
378 AutocompleteMatch::Type
OmniboxEditModel::CurrentTextType() const {
379 return CurrentMatch(NULL
).type
;
382 void OmniboxEditModel::AdjustTextForCopy(int sel_min
,
383 bool is_all_selected
,
384 base::string16
* text
,
389 // Do not adjust if selection did not start at the beginning of the field, or
390 // if the URL was omitted.
391 if ((sel_min
!= 0) || controller_
->GetToolbarModel()->WouldReplaceURL())
394 // Check whether the user is trying to copy the current page's URL by
395 // selecting the whole thing without editing it.
397 // This is complicated by ZeroSuggest. When ZeroSuggest is active, the user
398 // may be selecting different items and thus changing the address bar text,
399 // even though !user_input_in_progress_; and the permanent URL may change
400 // without updating the visible text, just like when user input is in
401 // progress. In these cases, we don't want to copy the underlying URL, we
402 // want to copy what the user actually sees. However, if we simply never do
403 // this block when !popup_model()->IsOpen(), then just clicking into the
404 // address bar and trying to copy will always bypass this block on pages that
405 // trigger ZeroSuggest, which is too conservative. Instead, in the
406 // ZeroSuggest case, we check that (a) the user hasn't selected one of the
407 // other suggestions, and (b) the selected text is still the same as the
408 // permanent text. ((b) probably implies (a), but it doesn't hurt to be
409 // sure.) If these hold, then it's safe to copy the underlying URL.
410 if (!user_input_in_progress_
&& is_all_selected
&&
411 (!popup_model() || !popup_model()->IsOpen() ||
412 ((popup_model()->selected_line() == 0) && (*text
== permanent_text_
)))) {
413 // It's safe to copy the underlying URL. These lines ensure that if the
414 // scheme was stripped it's added back, and the URL is unescaped (we escape
415 // parts of it for display).
416 *url
= PermanentURL();
417 *text
= base::UTF8ToUTF16(url
->spec());
422 // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now
423 // the user is probably holding down control to cause the copy, which will
424 // screw up our calculation of the desired_tld.
425 AutocompleteMatch match
;
426 AutocompleteClassifierFactory::GetForProfile(profile_
)->Classify(
427 *text
, is_keyword_selected(), true, ClassifyPage(), &match
, NULL
);
428 if (AutocompleteMatch::IsSearchType(match
.type
))
430 *url
= match
.destination_url
;
432 // Prefix the text with 'http://' if the text doesn't start with 'http://',
433 // the text parses as a url with a scheme of http, the user selected the
434 // entire host, and the user hasn't edited the host or manually removed the
436 GURL
perm_url(PermanentURL());
437 if (perm_url
.SchemeIs(url::kHttpScheme
) &&
438 url
->SchemeIs(url::kHttpScheme
) && perm_url
.host() == url
->host()) {
440 base::string16 http
= base::ASCIIToUTF16(url::kHttpScheme
) +
441 base::ASCIIToUTF16(url::kStandardSchemeSeparator
);
442 if (text
->compare(0, http
.length(), http
) != 0)
443 *text
= http
+ *text
;
447 void OmniboxEditModel::SetInputInProgress(bool in_progress
) {
448 if (in_progress
&& !user_input_since_focus_
) {
449 base::TimeTicks now
= base::TimeTicks::Now();
450 DCHECK(last_omnibox_focus_
<= now
);
451 UMA_HISTOGRAM_TIMES(kFocusToEditTimeHistogram
, now
- last_omnibox_focus_
);
452 user_input_since_focus_
= true;
455 if (user_input_in_progress_
== in_progress
)
458 user_input_in_progress_
= in_progress
;
459 if (user_input_in_progress_
) {
460 time_user_first_modified_omnibox_
= base::TimeTicks::Now();
461 base::RecordAction(base::UserMetricsAction("OmniboxInputInProgress"));
462 autocomplete_controller()->ResetSession();
465 controller_
->GetToolbarModel()->set_input_in_progress(in_progress
);
466 controller_
->UpdateWithoutTabRestore();
468 if (user_input_in_progress_
|| !in_revert_
)
469 client_
->OnInputStateChanged();
472 void OmniboxEditModel::Revert() {
473 SetInputInProgress(false);
476 InternalSetUserText(base::string16());
478 is_keyword_hint_
= false;
479 has_temporary_text_
= false;
480 view_
->SetWindowTextAndCaretPos(permanent_text_
,
481 has_focus() ? permanent_text_
.length() : 0,
486 void OmniboxEditModel::StartAutocomplete(
487 bool has_selected_text
,
488 bool prevent_inline_autocomplete
,
489 bool entering_keyword_mode
) {
490 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
491 tracked_objects::ScopedTracker
tracking_profile(
492 FROM_HERE_WITH_EXPLICIT_FUNCTION(
493 "440919 OmniboxEditModel::StartAutocomplete"));
494 size_t cursor_position
;
495 if (inline_autocomplete_text_
.empty()) {
496 // Cursor position is equivalent to the current selection's end.
498 view_
->GetSelectionBounds(&start
, &cursor_position
);
499 // If we're in keyword mode, we're not displaying the full |user_text_|, so
500 // the cursor position we got from the view has to be adjusted later by the
501 // length of the undisplayed text. If we're just entering keyword mode,
502 // though, we have to avoid making this adjustment, because we haven't
503 // actually hidden any text yet, but the caller has already cleared
504 // |is_keyword_hint_|, so DisplayTextFromUserText() will believe we are
505 // already in keyword mode, and will thus mis-adjust the cursor position.
506 if (!entering_keyword_mode
) {
508 user_text_
.length() - DisplayTextFromUserText(user_text_
).length();
511 // There are some cases where StartAutocomplete() may be called
512 // with non-empty |inline_autocomplete_text_|. In such cases, we cannot
513 // use the current selection, because it could result with the cursor
514 // position past the last character from the user text. Instead,
515 // we assume that the cursor is simply at the end of input.
516 // One example is when user presses Ctrl key while having a highlighted
517 // inline autocomplete text.
518 // TODO: Rethink how we are going to handle this case to avoid
519 // inconsistent behavior when user presses Ctrl key.
520 // See http://crbug.com/165961 and http://crbug.com/165968 for more details.
521 cursor_position
= user_text_
.length();
525 if (client_
->CurrentPageExists() && view_
->IsIndicatingQueryRefinement())
526 current_url
= client_
->GetURL();
527 input_
= AutocompleteInput(
528 user_text_
, cursor_position
, std::string(), current_url
, ClassifyPage(),
529 prevent_inline_autocomplete
|| just_deleted_text_
||
530 (has_selected_text
&& inline_autocomplete_text_
.empty()) ||
531 (paste_state_
!= NONE
),
532 is_keyword_selected(),
533 is_keyword_selected() || allow_exact_keyword_match_
, true, false,
534 ChromeAutocompleteSchemeClassifier(profile_
));
536 omnibox_controller_
->StartAutocomplete(input_
);
539 void OmniboxEditModel::StopAutocomplete() {
540 autocomplete_controller()->Stop(true);
543 bool OmniboxEditModel::CanPasteAndGo(const base::string16
& text
) const {
544 if (!client_
->IsPasteAndGoEnabled())
547 AutocompleteMatch match
;
548 ClassifyStringForPasteAndGo(text
, &match
, NULL
);
549 return match
.destination_url
.is_valid();
552 void OmniboxEditModel::PasteAndGo(const base::string16
& text
) {
553 DCHECK(CanPasteAndGo(text
));
554 UMA_HISTOGRAM_COUNTS("Omnibox.PasteAndGo", 1);
557 AutocompleteMatch match
;
558 GURL alternate_nav_url
;
559 ClassifyStringForPasteAndGo(text
, &match
, &alternate_nav_url
);
560 view_
->OpenMatch(match
, CURRENT_TAB
, alternate_nav_url
, text
,
561 OmniboxPopupModel::kNoMatch
);
564 bool OmniboxEditModel::IsPasteAndSearch(const base::string16
& text
) const {
565 AutocompleteMatch match
;
566 ClassifyStringForPasteAndGo(text
, &match
, NULL
);
567 return AutocompleteMatch::IsSearchType(match
.type
);
570 void OmniboxEditModel::AcceptInput(WindowOpenDisposition disposition
,
572 // Get the URL and transition type for the selected entry.
573 GURL alternate_nav_url
;
574 AutocompleteMatch match
= CurrentMatch(&alternate_nav_url
);
576 // If CTRL is down it means the user wants to append ".com" to the text he
577 // typed. If we can successfully generate a URL_WHAT_YOU_TYPED match doing
578 // that, then we use this. These matches are marked as generated by the
579 // HistoryURLProvider so we only generate them if this provider is present.
580 if (control_key_state_
== DOWN_WITHOUT_CHANGE
&& !is_keyword_selected() &&
581 autocomplete_controller()->history_url_provider()) {
582 // Generate a new AutocompleteInput, copying the latest one but using "com"
583 // as the desired TLD. Then use this autocomplete input to generate a
584 // URL_WHAT_YOU_TYPED AutocompleteMatch. Note that using the most recent
585 // input instead of the currently visible text means we'll ignore any
586 // visible inline autocompletion: if a user types "foo" and is autocompleted
587 // to "foodnetwork.com", ctrl-enter will navigate to "foo.com", not
588 // "foodnetwork.com". At the time of writing, this behavior matches
589 // Internet Explorer, but not Firefox.
590 input_
= AutocompleteInput(
591 has_temporary_text_
? UserTextFromDisplayText(view_
->GetText())
593 input_
.cursor_position(), "com", GURL(),
594 input_
.current_page_classification(),
595 input_
.prevent_inline_autocomplete(), input_
.prefer_keyword(),
596 input_
.allow_exact_keyword_match(), input_
.want_asynchronous_matches(),
597 input_
.from_omnibox_focus(),
598 ChromeAutocompleteSchemeClassifier(profile_
));
599 AutocompleteMatch
url_match(
600 autocomplete_controller()->history_url_provider()->SuggestExactInput(
601 input_
, input_
.canonicalized_url(), false));
603 if (url_match
.destination_url
.is_valid()) {
604 // We have a valid URL, we use this newly generated AutocompleteMatch.
606 alternate_nav_url
= GURL();
610 if (!match
.destination_url
.is_valid())
613 if ((match
.transition
== ui::PAGE_TRANSITION_TYPED
) &&
614 (match
.destination_url
== PermanentURL())) {
615 // When the user hit enter on the existing permanent URL, treat it like a
616 // reload for scoring purposes. We could detect this by just checking
617 // user_input_in_progress_, but it seems better to treat "edits" that end
618 // up leaving the URL unchanged (e.g. deleting the last character and then
619 // retyping it) as reloads too. We exclude non-TYPED transitions because if
620 // the transition is GENERATED, the user input something that looked
621 // different from the current URL, even if it wound up at the same place
622 // (e.g. manually retyping the same search query), and it seems wrong to
623 // treat this as a reload.
624 match
.transition
= ui::PAGE_TRANSITION_RELOAD
;
625 } else if (for_drop
||
626 ((paste_state_
!= NONE
) &&
627 (match
.type
== AutocompleteMatchType::URL_WHAT_YOU_TYPED
))) {
628 // When the user pasted in a URL and hit enter, score it like a link click
629 // rather than a normal typed URL, so it doesn't get inline autocompleted
630 // as aggressively later.
631 match
.transition
= ui::PAGE_TRANSITION_LINK
;
634 client_
->OnInputAccepted(match
);
636 DCHECK(popup_model());
637 view_
->OpenMatch(match
, disposition
, alternate_nav_url
, base::string16(),
638 popup_model()->selected_line());
641 void OmniboxEditModel::OpenMatch(AutocompleteMatch match
,
642 WindowOpenDisposition disposition
,
643 const GURL
& alternate_nav_url
,
644 const base::string16
& pasted_text
,
646 const base::TimeTicks
& now(base::TimeTicks::Now());
647 base::TimeDelta
elapsed_time_since_user_first_modified_omnibox(
648 now
- time_user_first_modified_omnibox_
);
649 autocomplete_controller()->UpdateMatchDestinationURLWithQueryFormulationTime(
650 elapsed_time_since_user_first_modified_omnibox
, &match
);
652 base::string16
input_text(pasted_text
);
653 if (input_text
.empty())
654 input_text
= user_input_in_progress_
? user_text_
: permanent_text_
;
655 // Create a dummy AutocompleteInput for use in calling SuggestExactInput()
656 // to create an alternate navigational match.
657 AutocompleteInput
alternate_input(
658 input_text
, base::string16::npos
, std::string(),
659 // Somehow we can occasionally get here with no active tab. It's not
660 // clear why this happens.
661 client_
->CurrentPageExists() ? client_
->GetURL() : GURL(),
662 ClassifyPage(), false, false, true, true, false,
663 ChromeAutocompleteSchemeClassifier(profile_
));
664 scoped_ptr
<OmniboxNavigationObserver
> observer(
665 new OmniboxNavigationObserver(
666 profile_
, input_text
, match
,
667 autocomplete_controller()->history_url_provider()->SuggestExactInput(
668 alternate_input
, alternate_nav_url
,
669 AutocompleteInput::HasHTTPScheme(input_text
))));
671 base::TimeDelta
elapsed_time_since_last_change_to_default_match(
672 now
- autocomplete_controller()->last_time_default_match_changed());
673 DCHECK(match
.provider
);
674 // These elapsed times don't really make sense for ZeroSuggest matches
675 // (because the user does not modify the omnibox for ZeroSuggest), so for
676 // those we set the elapsed times to something that will be ignored by
677 // metrics_log.cc. They also don't necessarily make sense if the omnibox
678 // dropdown is closed or the user used a paste-and-go action. (In most
679 // cases when this happens, the user never modified the omnibox.)
680 if ((match
.provider
->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST
) ||
681 !popup_model()->IsOpen() || !pasted_text
.empty()) {
682 const base::TimeDelta default_time_delta
=
683 base::TimeDelta::FromMilliseconds(-1);
684 elapsed_time_since_user_first_modified_omnibox
= default_time_delta
;
685 elapsed_time_since_last_change_to_default_match
= default_time_delta
;
687 // If the popup is closed or this is a paste-and-go action (meaning the
688 // contents of the dropdown are ignored regardless), we record for logging
689 // purposes a selected_index of 0 and a suggestion list as having a single
690 // entry of the match used.
691 ACMatches fake_single_entry_matches
;
692 fake_single_entry_matches
.push_back(match
);
693 AutocompleteResult fake_single_entry_result
;
694 fake_single_entry_result
.AppendMatches(input_
, fake_single_entry_matches
);
699 popup_model()->IsOpen(),
700 (!popup_model()->IsOpen() || !pasted_text
.empty()) ? 0 : index
,
701 !pasted_text
.empty(),
702 -1, // don't yet know tab ID; set later if appropriate
704 elapsed_time_since_user_first_modified_omnibox
,
705 match
.allowed_to_be_default_match
? match
.inline_autocompletion
.length() :
706 base::string16::npos
,
707 elapsed_time_since_last_change_to_default_match
,
708 (!popup_model()->IsOpen() || !pasted_text
.empty()) ?
709 fake_single_entry_result
: result());
710 DCHECK(!popup_model()->IsOpen() || !pasted_text
.empty() ||
711 (log
.elapsed_time_since_user_first_modified_omnibox
>=
712 log
.elapsed_time_since_last_change_to_default_match
))
713 << "We should've got the notification that the user modified the "
714 << "omnibox text at same time or before the most recent time the "
715 << "default match changed.";
717 if ((disposition
== CURRENT_TAB
) && client_
->CurrentPageExists()) {
718 // If we know the destination is being opened in the current tab,
719 // we can easily get the tab ID. (If it's being opened in a new
720 // tab, we don't know the tab ID yet.)
721 log
.tab_id
= client_
->GetSessionID().id();
723 autocomplete_controller()->AddProvidersInfo(&log
.providers_info
);
724 client_
->OnURLOpenedFromOmnibox(&log
);
725 LOCAL_HISTOGRAM_BOOLEAN("Omnibox.EventCount", true);
726 DCHECK(!last_omnibox_focus_
.is_null())
727 << "An omnibox focus should have occurred before opening a match.";
728 UMA_HISTOGRAM_TIMES(kFocusToOpenTimeHistogram
, now
- last_omnibox_focus_
);
730 TemplateURLService
* service
=
731 TemplateURLServiceFactory::GetForProfile(profile_
);
732 TemplateURL
* template_url
= match
.GetTemplateURL(service
, false);
734 if (match
.transition
== ui::PAGE_TRANSITION_KEYWORD
) {
735 // The user is using a non-substituting keyword or is explicitly in
738 // Don't increment usage count for extension keywords.
739 if (client_
->ProcessExtensionKeyword(template_url
, match
,
741 observer
->OnSuccessfulNavigation();
742 if (disposition
!= NEW_BACKGROUND_TAB
)
747 base::RecordAction(base::UserMetricsAction("AcceptedKeyword"));
748 TemplateURLServiceFactory::GetForProfile(profile_
)->IncrementUsageCount(
751 DCHECK_EQ(ui::PAGE_TRANSITION_GENERATED
, match
.transition
);
752 // NOTE: We purposefully don't increment the usage count of the default
753 // search engine here like we do for explicit keywords above; see comments
754 // in template_url.h.
757 UMA_HISTOGRAM_ENUMERATION(
758 "Omnibox.SearchEngineType",
759 TemplateURLPrepopulateData::GetEngineType(
760 *template_url
, UIThreadSearchTermsData(profile_
)),
764 // Get the current text before we call RevertAll() which will clear it.
765 base::string16 current_text
= view_
->GetText();
767 if (disposition
!= NEW_BACKGROUND_TAB
) {
768 base::AutoReset
<bool> tmp(&in_revert_
, true);
769 view_
->RevertAll(); // Revert the box to its unedited state.
772 RecordPercentageMatchHistogram(
773 permanent_text_
, current_text
,
774 controller_
->GetToolbarModel()->WouldReplaceURL(),
775 match
.transition
, view_
->GetWidth());
777 // Track whether the destination URL sends us to a search results page
778 // using the default search provider.
779 if (TemplateURLServiceFactory::GetForProfile(profile_
)->
780 IsSearchResultsPageFromDefaultSearchProvider(match
.destination_url
)) {
782 base::UserMetricsAction("OmniboxDestinationURLIsSearchOnDSP"));
785 if (match
.destination_url
.is_valid()) {
786 // This calls RevertAll again.
787 base::AutoReset
<bool> tmp(&in_revert_
, true);
788 controller_
->OnAutocompleteAccept(
789 match
.destination_url
, disposition
,
790 ui::PageTransitionFromInt(
791 match
.transition
| ui::PAGE_TRANSITION_FROM_ADDRESS_BAR
));
792 if (observer
->load_state() != OmniboxNavigationObserver::LOAD_NOT_SEEN
)
793 ignore_result(observer
.release()); // The observer will delete itself.
796 BookmarkModel
* bookmark_model
= BookmarkModelFactory::GetForProfile(profile_
);
797 if (bookmark_model
&& bookmark_model
->IsBookmarked(match
.destination_url
))
798 RecordBookmarkLaunch(NULL
, BOOKMARK_LAUNCH_LOCATION_OMNIBOX
);
801 bool OmniboxEditModel::AcceptKeyword(EnteredKeywordModeMethod entered_method
) {
802 DCHECK(is_keyword_hint_
&& !keyword_
.empty());
804 autocomplete_controller()->Stop(false);
805 is_keyword_hint_
= false;
807 if (popup_model() && popup_model()->IsOpen())
808 popup_model()->SetSelectedLineState(OmniboxPopupModel::KEYWORD
);
810 StartAutocomplete(false, true, true);
812 // When entering keyword mode via tab, the new text to show is whatever the
813 // newly-selected match in the dropdown is. When entering via space, however,
814 // we should make sure to use the actual |user_text_| as the basis for the new
815 // text. This ensures that if the user types "<keyword><space>" and the
816 // default match would have inline autocompleted a further string (e.g.
817 // because there's a past multi-word search beginning with this keyword), the
818 // inline autocompletion doesn't get filled in as the keyword search query
821 // We also treat tabbing into keyword mode like tabbing through the popup in
822 // that we set |has_temporary_text_|, whereas pressing space is treated like
823 // a new keystroke that changes the current match instead of overlaying it
824 // with a temporary one. This is important because rerunning autocomplete
825 // after the user pressed space, which will have happened just before reaching
826 // here, may have generated a new match, which the user won't actually see and
827 // which we don't want to switch back to when existing keyword mode; see
828 // comments in ClearKeyword().
829 if (entered_method
== ENTERED_KEYWORD_MODE_VIA_TAB
) {
830 // Ensure the current selection is saved before showing keyword mode
831 // so that moving to another line and then reverting the text will restore
832 // the current state properly.
833 bool save_original_selection
= !has_temporary_text_
;
834 has_temporary_text_
= true;
835 const AutocompleteMatch
& match
= CurrentMatch(NULL
);
836 original_url_
= match
.destination_url
;
837 view_
->OnTemporaryTextMaybeChanged(
838 DisplayTextFromUserText(match
.fill_into_edit
),
839 save_original_selection
, true);
841 view_
->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(user_text_
),
845 base::RecordAction(base::UserMetricsAction("AcceptedKeywordHint"));
846 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram
, entered_method
,
847 ENTERED_KEYWORD_MODE_NUM_ITEMS
);
852 void OmniboxEditModel::AcceptTemporaryTextAsUserText() {
853 InternalSetUserText(UserTextFromDisplayText(view_
->GetText()));
854 has_temporary_text_
= false;
856 if (user_input_in_progress_
|| !in_revert_
)
857 client_
->OnInputStateChanged();
860 void OmniboxEditModel::ClearKeyword() {
861 autocomplete_controller()->Stop(false);
863 // While we're always in keyword mode upon reaching here, sometimes we've just
864 // toggled in via space or tab, and sometimes we're on a non-toggled line
865 // (usually because the user has typed a search string). Keep track of the
866 // difference, as we'll need it below.
867 bool was_toggled_into_keyword_mode
=
868 popup_model()->selected_line_state() == OmniboxPopupModel::KEYWORD
;
870 omnibox_controller_
->ClearPopupKeywordMode();
872 // There are several possible states we could have been in before the user hit
873 // backspace or shift-tab to enter this function:
874 // (1) was_toggled_into_keyword_mode == false, has_temporary_text_ == false
875 // The user typed a further key after being in keyword mode already, e.g.
877 // (2) was_toggled_into_keyword_mode == false, has_temporary_text_ == true
878 // The user tabbed away from a dropdown entry in keyword mode, then tabbed
879 // back to it, e.g. "google.com f<tab><shift-tab>".
880 // (3) was_toggled_into_keyword_mode == true, has_temporary_text_ == false
881 // The user had just typed space to enter keyword mode, e.g.
883 // (4) was_toggled_into_keyword_mode == true, has_temporary_text_ == true
884 // The user had just typed tab to enter keyword mode, e.g.
885 // "google.com<tab>".
887 // For states 1-3, we can safely handle the exit from keyword mode by using
888 // OnBefore/AfterPossibleChange() to do a complete state update of all
889 // objects. However, with state 4, if we do this, and if the user had tabbed
890 // into keyword mode on a line in the middle of the dropdown instead of the
891 // first line, then the state update will rerun autocompletion and reset the
892 // whole dropdown, and end up with the first line selected instead, instead of
893 // just "undoing" the keyword mode entry on the non-first line. So in this
894 // case we simply reset |is_keyword_hint_| to true and update the window text.
896 // You might wonder why we don't simply do this in all cases. In states 1-2,
897 // getting out of keyword mode likely shouldn't put us in keyword hint mode;
898 // if the user typed "google.com f" and then put the cursor before 'f' and hit
899 // backspace, the resulting text would be "google.comf", which is unlikely to
900 // be a keyword. Unconditionally putting things back in keyword hint mode is
901 // going to lead to internally inconsistent state, and possible future
902 // crashes. State 3 is more subtle; here we need to do the full state update
903 // because before entering keyword mode to begin with, we will have re-run
904 // autocomplete in ways that can produce surprising results if we just switch
905 // back out of keyword mode. For example, if a user has a keyword named "x",
906 // an inline-autocompletable history site "xyz.com", and a lower-ranked
907 // inline-autocompletable search "x y", then typing "x" will inline-
908 // autocomplete to "xyz.com", hitting space will toggle into keyword mode, but
909 // then hitting backspace could wind up with the default match as the "x y"
910 // search, which feels bizarre.
911 const base::string16
window_text(keyword_
+ view_
->GetText());
912 if (was_toggled_into_keyword_mode
&& has_temporary_text_
) {
914 is_keyword_hint_
= true;
915 view_
->SetWindowTextAndCaretPos(window_text
.c_str(), keyword_
.length(),
919 view_
->OnBeforePossibleChange();
920 view_
->SetWindowTextAndCaretPos(window_text
.c_str(), keyword_
.length(),
923 is_keyword_hint_
= false;
924 view_
->OnAfterPossibleChange();
928 void OmniboxEditModel::OnSetFocus(bool control_down
) {
929 last_omnibox_focus_
= base::TimeTicks::Now();
930 user_input_since_focus_
= false;
932 // If the omnibox lost focus while the caret was hidden and then regained
933 // focus, OnSetFocus() is called and should restore visibility. Note that
934 // focus can be regained without an accompanying call to
935 // OmniboxView::SetFocus(), e.g. by tabbing in.
936 SetFocusState(OMNIBOX_FOCUS_VISIBLE
, OMNIBOX_FOCUS_CHANGE_EXPLICIT
);
937 control_key_state_
= control_down
? DOWN_WITHOUT_CHANGE
: UP
;
939 // Try to get ZeroSuggest suggestions if a page is loaded and the user has
940 // not been typing in the omnibox. The |user_input_in_progress_| check is
941 // used to detect the case where this function is called after right-clicking
942 // in the omnibox and selecting paste in Linux (in which case we actually get
943 // the OnSetFocus() call after the process of handling the paste has kicked
945 // TODO(hfung): Remove this when crbug/271590 is fixed.
946 if (client_
->CurrentPageExists() && !user_input_in_progress_
) {
947 // We avoid PermanentURL() here because it's not guaranteed to give us the
948 // actual underlying current URL, e.g. if we're on the NTP and the
949 // |permanent_text_| is empty.
950 input_
= AutocompleteInput(permanent_text_
, base::string16::npos
,
951 std::string(), client_
->GetURL(),
952 ClassifyPage(), false, false, true, true, true,
953 ChromeAutocompleteSchemeClassifier(profile_
));
954 autocomplete_controller()->Start(input_
);
957 if (user_input_in_progress_
|| !in_revert_
)
958 client_
->OnInputStateChanged();
961 void OmniboxEditModel::SetCaretVisibility(bool visible
) {
962 // Caret visibility only matters if the omnibox has focus.
963 if (focus_state_
!= OMNIBOX_FOCUS_NONE
) {
964 SetFocusState(visible
? OMNIBOX_FOCUS_VISIBLE
: OMNIBOX_FOCUS_INVISIBLE
,
965 OMNIBOX_FOCUS_CHANGE_EXPLICIT
);
969 void OmniboxEditModel::OnWillKillFocus() {
970 if (user_input_in_progress_
|| !in_revert_
)
971 client_
->OnInputStateChanged();
974 void OmniboxEditModel::OnKillFocus() {
975 SetFocusState(OMNIBOX_FOCUS_NONE
, OMNIBOX_FOCUS_CHANGE_EXPLICIT
);
976 focus_source_
= INVALID
;
977 control_key_state_
= UP
;
981 bool OmniboxEditModel::WillHandleEscapeKey() const {
982 return user_input_in_progress_
||
983 (has_temporary_text_
&&
984 (CurrentMatch(NULL
).destination_url
!= original_url_
));
987 bool OmniboxEditModel::OnEscapeKeyPressed() {
988 if (has_temporary_text_
&&
989 (CurrentMatch(NULL
).destination_url
!= original_url_
)) {
990 RevertTemporaryText(true);
994 // We do not clear the pending entry from the omnibox when a load is first
995 // stopped. If the user presses Escape while stopped, whether editing or not,
997 if (client_
->CurrentPageExists() && !client_
->IsLoading()) {
998 client_
->DiscardNonCommittedNavigations();
1002 if (!user_text_
.empty()) {
1003 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram
,
1004 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE
,
1005 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS
);
1008 // Unconditionally revert/select all. This ensures any popup, whether due to
1009 // normal editing or ZeroSuggest, is closed, and the full text is selected.
1010 // This in turn allows the user to use escape to quickly select all the text
1011 // for ease of replacement, and matches other browsers.
1012 bool user_input_was_in_progress
= user_input_in_progress_
;
1014 view_
->SelectAll(true);
1016 // If the user was in the midst of editing, don't cancel any underlying page
1017 // load. This doesn't match IE or Firefox, but seems more correct. Note that
1018 // we do allow the page load to be stopped in the case where ZeroSuggest was
1019 // visible; this is so that it's still possible to focus the address bar and
1020 // hit escape once to stop a load even if the address being loaded triggers
1021 // the ZeroSuggest popup.
1022 return user_input_was_in_progress
;
1025 void OmniboxEditModel::OnControlKeyChanged(bool pressed
) {
1026 if (pressed
== (control_key_state_
== UP
))
1027 control_key_state_
= pressed
? DOWN_WITHOUT_CHANGE
: UP
;
1030 void OmniboxEditModel::OnPaste() {
1031 UMA_HISTOGRAM_COUNTS("Omnibox.Paste", 1);
1032 paste_state_
= PASTING
;
1035 void OmniboxEditModel::OnUpOrDownKeyPressed(int count
) {
1036 // NOTE: This purposefully doesn't trigger any code that resets paste_state_.
1037 if (popup_model() && popup_model()->IsOpen()) {
1038 // The popup is open, so the user should be able to interact with it
1040 popup_model()->Move(count
);
1044 if (!query_in_progress()) {
1045 // The popup is neither open nor working on a query already. So, start an
1046 // autocomplete query for the current text. This also sets
1047 // user_input_in_progress_ to true, which we want: if the user has started
1048 // to interact with the popup, changing the permanent_text_ shouldn't change
1049 // the displayed text.
1050 // Note: This does not force the popup to open immediately.
1051 // TODO(pkasting): We should, in fact, force this particular query to open
1052 // the popup immediately.
1053 if (!user_input_in_progress_
)
1054 InternalSetUserText(permanent_text_
);
1055 view_
->UpdatePopup();
1059 // TODO(pkasting): The popup is working on a query but is not open. We should
1060 // force it to open immediately.
1063 void OmniboxEditModel::OnPopupDataChanged(
1064 const base::string16
& text
,
1065 GURL
* destination_for_temporary_text_change
,
1066 const base::string16
& keyword
,
1067 bool is_keyword_hint
) {
1068 // The popup changed its data, the match in the controller is no longer valid.
1069 omnibox_controller_
->InvalidateCurrentMatch();
1071 // Update keyword/hint-related local state.
1072 bool keyword_state_changed
= (keyword_
!= keyword
) ||
1073 ((is_keyword_hint_
!= is_keyword_hint
) && !keyword
.empty());
1074 if (keyword_state_changed
) {
1076 is_keyword_hint_
= is_keyword_hint
;
1078 // |is_keyword_hint_| should always be false if |keyword_| is empty.
1079 DCHECK(!keyword_
.empty() || !is_keyword_hint_
);
1082 // Handle changes to temporary text.
1083 if (destination_for_temporary_text_change
!= NULL
) {
1084 const bool save_original_selection
= !has_temporary_text_
;
1085 if (save_original_selection
) {
1086 // Save the original selection and URL so it can be reverted later.
1087 has_temporary_text_
= true;
1088 original_url_
= *destination_for_temporary_text_change
;
1089 inline_autocomplete_text_
.clear();
1090 view_
->OnInlineAutocompleteTextCleared();
1092 if (control_key_state_
== DOWN_WITHOUT_CHANGE
) {
1093 // Arrowing around the popup cancels control-enter.
1094 control_key_state_
= DOWN_WITH_CHANGE
;
1095 // Now things are a bit screwy: the desired_tld has changed, but if we
1096 // update the popup, the new order of entries won't match the old, so the
1097 // user's selection gets screwy; and if we don't update the popup, and the
1098 // user reverts, then the selected item will be as if control is still
1099 // pressed, even though maybe it isn't any more. There is no obvious
1100 // right answer here :(
1102 view_
->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text
),
1103 save_original_selection
, true);
1107 bool call_controller_onchanged
= true;
1108 inline_autocomplete_text_
= text
;
1109 if (inline_autocomplete_text_
.empty())
1110 view_
->OnInlineAutocompleteTextCleared();
1112 const base::string16
& user_text
=
1113 user_input_in_progress_
? user_text_
: permanent_text_
;
1114 if (keyword_state_changed
&& is_keyword_selected()) {
1115 // If we reach here, the user most likely entered keyword mode by inserting
1116 // a space between a keyword name and a search string (as pressing space or
1117 // tab after the keyword name alone would have been be handled in
1118 // MaybeAcceptKeywordBySpace() by calling AcceptKeyword(), which won't reach
1119 // here). In this case, we don't want to call
1120 // OnInlineAutocompleteTextMaybeChanged() as normal, because that will
1121 // correctly change the text (to the search string alone) but move the caret
1122 // to the end of the string; instead we want the caret at the start of the
1123 // search string since that's where it was in the original input. So we set
1124 // the text and caret position directly.
1126 // It may also be possible to reach here if we're reverting from having
1127 // temporary text back to a default match that's a keyword search, but in
1128 // that case the RevertTemporaryText() call below will reset the caret or
1129 // selection correctly so the caret positioning we do here won't matter.
1130 view_
->SetWindowTextAndCaretPos(DisplayTextFromUserText(user_text
), 0,
1132 } else if (view_
->OnInlineAutocompleteTextMaybeChanged(
1133 DisplayTextFromUserText(user_text
+ inline_autocomplete_text_
),
1134 DisplayTextFromUserText(user_text
).length())) {
1135 call_controller_onchanged
= false;
1138 // If |has_temporary_text_| is true, then we previously had a manual selection
1139 // but now don't (or |destination_for_temporary_text_change| would have been
1140 // non-NULL). This can happen when deleting the selected item in the popup.
1141 // In this case, we've already reverted the popup to the default match, so we
1142 // need to revert ourselves as well.
1143 if (has_temporary_text_
) {
1144 RevertTemporaryText(false);
1145 call_controller_onchanged
= false;
1148 // We need to invoke OnChanged in case the destination url changed (as could
1149 // happen when control is toggled).
1150 if (call_controller_onchanged
)
1154 bool OmniboxEditModel::OnAfterPossibleChange(const base::string16
& old_text
,
1155 const base::string16
& new_text
,
1156 size_t selection_start
,
1157 size_t selection_end
,
1158 bool selection_differs
,
1160 bool just_deleted_text
,
1161 bool allow_keyword_ui_change
) {
1162 // Update the paste state as appropriate: if we're just finishing a paste
1163 // that replaced all the text, preserve that information; otherwise, if we've
1164 // made some other edit, clear paste tracking.
1165 if (paste_state_
== PASTING
)
1166 paste_state_
= PASTED
;
1167 else if (text_differs
)
1168 paste_state_
= NONE
;
1170 if (text_differs
|| selection_differs
) {
1171 // Record current focus state for this input if we haven't already.
1172 if (focus_source_
== INVALID
) {
1173 // We should generally expect the omnibox to have focus at this point, but
1174 // it doesn't always on Linux. This is because, unlike other platforms,
1175 // right clicking in the omnibox on Linux doesn't focus it. So pasting via
1176 // right-click can change the contents without focusing the omnibox.
1177 // TODO(samarth): fix Linux focus behavior and add a DCHECK here to
1178 // check that the omnibox does have focus.
1179 focus_source_
= (focus_state_
== OMNIBOX_FOCUS_INVISIBLE
) ?
1183 // Restore caret visibility whenever the user changes text or selection in
1185 SetFocusState(OMNIBOX_FOCUS_VISIBLE
, OMNIBOX_FOCUS_CHANGE_TYPING
);
1188 // Modifying the selection counts as accepting the autocompleted text.
1189 const bool user_text_changed
=
1190 text_differs
|| (selection_differs
&& !inline_autocomplete_text_
.empty());
1192 // If something has changed while the control key is down, prevent
1193 // "ctrl-enter" until the control key is released.
1194 if ((text_differs
|| selection_differs
) &&
1195 (control_key_state_
== DOWN_WITHOUT_CHANGE
))
1196 control_key_state_
= DOWN_WITH_CHANGE
;
1198 if (!user_text_changed
)
1201 // If the user text has not changed, we do not want to change the model's
1202 // state associated with the text. Otherwise, we can get surprising behavior
1203 // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983
1204 InternalSetUserText(UserTextFromDisplayText(new_text
));
1205 has_temporary_text_
= false;
1207 // Track when the user has deleted text so we won't allow inline
1209 just_deleted_text_
= just_deleted_text
;
1211 if (user_input_in_progress_
&& user_text_
.empty()) {
1212 // Log cases where the user started editing and then subsequently cleared
1213 // all the text. Note that this explicitly doesn't catch cases like
1214 // "hit ctrl-l to select whole edit contents, then hit backspace", because
1215 // in such cases, |user_input_in_progress| won't be true here.
1216 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram
,
1217 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING
,
1218 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS
);
1221 const bool no_selection
= selection_start
== selection_end
;
1223 // Update the popup for the change, in the process changing to keyword mode
1224 // if the user hit space in mid-string after a keyword.
1225 // |allow_exact_keyword_match_| will be used by StartAutocomplete() method,
1226 // which will be called by |view_->UpdatePopup()|; so after that returns we
1227 // can safely reset this flag.
1228 allow_exact_keyword_match_
= text_differs
&& allow_keyword_ui_change
&&
1229 !just_deleted_text
&& no_selection
&&
1230 CreatedKeywordSearchByInsertingSpaceInMiddle(old_text
, user_text_
,
1232 view_
->UpdatePopup();
1233 if (allow_exact_keyword_match_
) {
1234 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram
,
1235 ENTERED_KEYWORD_MODE_VIA_SPACE_IN_MIDDLE
,
1236 ENTERED_KEYWORD_MODE_NUM_ITEMS
);
1237 allow_exact_keyword_match_
= false;
1240 // Change to keyword mode if the user is now pressing space after a keyword
1241 // name. Note that if this is the case, then even if there was no keyword
1242 // hint when we entered this function (e.g. if the user has used space to
1243 // replace some selected text that was adjoined to this keyword), there will
1244 // be one now because of the call to UpdatePopup() above; so it's safe for
1245 // MaybeAcceptKeywordBySpace() to look at |keyword_| and |is_keyword_hint_| to
1246 // determine what keyword, if any, is applicable.
1248 // If MaybeAcceptKeywordBySpace() accepts the keyword and returns true, that
1249 // will have updated our state already, so in that case we don't also return
1250 // true from this function.
1251 return !(text_differs
&& allow_keyword_ui_change
&& !just_deleted_text
&&
1252 no_selection
&& (selection_start
== user_text_
.length()) &&
1253 MaybeAcceptKeywordBySpace(user_text_
));
1256 // TODO(beaudoin): Merge OnPopupDataChanged with this method once the popup
1257 // handling has completely migrated to omnibox_controller.
1258 void OmniboxEditModel::OnCurrentMatchChanged() {
1259 has_temporary_text_
= false;
1261 const AutocompleteMatch
& match
= omnibox_controller_
->current_match();
1263 client_
->OnCurrentMatchChanged(match
);
1265 // We store |keyword| and |is_keyword_hint| in temporary variables since
1266 // OnPopupDataChanged use their previous state to detect changes.
1267 base::string16 keyword
;
1268 bool is_keyword_hint
;
1269 TemplateURLService
* service
=
1270 TemplateURLServiceFactory::GetForProfile(profile_
);
1271 match
.GetKeywordUIState(service
, &keyword
, &is_keyword_hint
);
1273 popup_model()->OnResultChanged();
1274 // OnPopupDataChanged() resets OmniboxController's |current_match_| early
1275 // on. Therefore, copy match.inline_autocompletion to a temp to preserve
1276 // its value across the entire call.
1277 const base::string16
inline_autocompletion(match
.inline_autocompletion
);
1278 OnPopupDataChanged(inline_autocompletion
, NULL
, keyword
, is_keyword_hint
);
1282 const char OmniboxEditModel::kCutOrCopyAllTextHistogram
[] =
1283 "Omnibox.CutOrCopyAllText";
1285 bool OmniboxEditModel::query_in_progress() const {
1286 return !autocomplete_controller()->done();
1289 void OmniboxEditModel::InternalSetUserText(const base::string16
& text
) {
1291 just_deleted_text_
= false;
1292 inline_autocomplete_text_
.clear();
1293 view_
->OnInlineAutocompleteTextCleared();
1296 void OmniboxEditModel::ClearPopupKeywordMode() const {
1297 omnibox_controller_
->ClearPopupKeywordMode();
1300 base::string16
OmniboxEditModel::DisplayTextFromUserText(
1301 const base::string16
& text
) const {
1302 return is_keyword_selected() ?
1303 KeywordProvider::SplitReplacementStringFromInput(text
, false) : text
;
1306 base::string16
OmniboxEditModel::UserTextFromDisplayText(
1307 const base::string16
& text
) const {
1308 return is_keyword_selected() ? (keyword_
+ base::char16(' ') + text
) : text
;
1311 void OmniboxEditModel::GetInfoForCurrentText(AutocompleteMatch
* match
,
1312 GURL
* alternate_nav_url
) const {
1313 DCHECK(match
!= NULL
);
1315 if (controller_
->GetToolbarModel()->WouldPerformSearchTermReplacement(
1317 // Any time the user hits enter on the unchanged omnibox, we should reload.
1318 // When we're not extracting search terms, AcceptInput() will take care of
1319 // this (see code referring to PAGE_TRANSITION_RELOAD there), but when we're
1320 // extracting search terms, the conditionals there won't fire, so we
1321 // explicitly set up a match that will reload here.
1323 // It's important that we fetch the current visible URL to reload instead of
1324 // just getting a "search what you typed" URL from
1325 // SearchProvider::CreateSearchSuggestion(), since the user may be in a
1326 // non-default search mode such as image search.
1327 match
->type
= AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED
;
1328 match
->provider
= autocomplete_controller()->search_provider();
1329 match
->destination_url
= client_
->GetURL();
1330 match
->transition
= ui::PAGE_TRANSITION_RELOAD
;
1331 } else if (query_in_progress() ||
1332 (popup_model() && popup_model()->IsOpen())) {
1333 if (query_in_progress()) {
1334 // It's technically possible for |result| to be empty if no provider
1335 // returns a synchronous result but the query has not completed
1336 // synchronously; pratically, however, that should never actually happen.
1337 if (result().empty())
1339 // The user cannot have manually selected a match, or the query would have
1340 // stopped. So the default match must be the desired selection.
1341 *match
= *result().default_match();
1343 // If there are no results, the popup should be closed, so we shouldn't
1344 // have gotten here.
1345 CHECK(!result().empty());
1346 CHECK(popup_model()->selected_line() < result().size());
1347 const AutocompleteMatch
& selected_match
=
1348 result().match_at(popup_model()->selected_line());
1350 (popup_model()->selected_line_state() == OmniboxPopupModel::KEYWORD
) ?
1351 *selected_match
.associated_keyword
: selected_match
;
1353 if (alternate_nav_url
&&
1354 (!popup_model() || popup_model()->manually_selected_match().empty()))
1355 *alternate_nav_url
= result().alternate_nav_url();
1357 AutocompleteClassifierFactory::GetForProfile(profile_
)->Classify(
1358 UserTextFromDisplayText(view_
->GetText()), is_keyword_selected(), true,
1359 ClassifyPage(), match
, alternate_nav_url
);
1363 void OmniboxEditModel::RevertTemporaryText(bool revert_popup
) {
1364 // The user typed something, then selected a different item. Restore the
1365 // text they typed and change back to the default item.
1366 // NOTE: This purposefully does not reset paste_state_.
1367 just_deleted_text_
= false;
1368 has_temporary_text_
= false;
1370 if (revert_popup
&& popup_model())
1371 popup_model()->ResetToDefaultMatch();
1372 view_
->OnRevertTemporaryText();
1375 bool OmniboxEditModel::MaybeAcceptKeywordBySpace(
1376 const base::string16
& new_text
) {
1377 size_t keyword_length
= new_text
.length() - 1;
1378 return (paste_state_
== NONE
) && is_keyword_hint_
&&
1379 (keyword_
.length() == keyword_length
) &&
1380 IsSpaceCharForAcceptingKeyword(new_text
[keyword_length
]) &&
1381 !new_text
.compare(0, keyword_length
, keyword_
, 0, keyword_length
) &&
1382 AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_SPACE_AT_END
);
1385 bool OmniboxEditModel::CreatedKeywordSearchByInsertingSpaceInMiddle(
1386 const base::string16
& old_text
,
1387 const base::string16
& new_text
,
1388 size_t caret_position
) const {
1389 DCHECK_GE(new_text
.length(), caret_position
);
1391 // Check simple conditions first.
1392 if ((paste_state_
!= NONE
) || (caret_position
< 2) ||
1393 (old_text
.length() < caret_position
) ||
1394 (new_text
.length() == caret_position
))
1396 size_t space_position
= caret_position
- 1;
1397 if (!IsSpaceCharForAcceptingKeyword(new_text
[space_position
]) ||
1398 base::IsUnicodeWhitespace(new_text
[space_position
- 1]) ||
1399 new_text
.compare(0, space_position
, old_text
, 0, space_position
) ||
1400 !new_text
.compare(space_position
, new_text
.length() - space_position
,
1401 old_text
, space_position
,
1402 old_text
.length() - space_position
)) {
1406 // Then check if the text before the inserted space matches a keyword.
1407 base::string16 keyword
;
1408 base::TrimWhitespace(new_text
.substr(0, space_position
), base::TRIM_LEADING
,
1410 return !keyword
.empty() && !autocomplete_controller()->keyword_provider()->
1411 GetKeywordForText(keyword
).empty();
1415 bool OmniboxEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c
) {
1417 case 0x0020: // Space
1418 case 0x3000: // Ideographic Space
1425 OmniboxEventProto::PageClassification
OmniboxEditModel::ClassifyPage() const {
1426 if (!client_
->CurrentPageExists())
1427 return OmniboxEventProto::OTHER
;
1428 if (client_
->IsInstantNTP()) {
1429 // Note that we treat OMNIBOX as the source if focus_source_ is INVALID,
1430 // i.e., if input isn't actually in progress.
1431 return (focus_source_
== FAKEBOX
) ?
1432 OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS
:
1433 OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS
;
1435 const GURL
& gurl
= client_
->GetURL();
1436 if (!gurl
.is_valid())
1437 return OmniboxEventProto::INVALID_SPEC
;
1438 const std::string
& url
= gurl
.spec();
1439 if (url
== chrome::kChromeUINewTabURL
)
1440 return OmniboxEventProto::NTP
;
1441 if (url
== url::kAboutBlankURL
)
1442 return OmniboxEventProto::BLANK
;
1443 if (url
== profile()->GetPrefs()->GetString(prefs::kHomePage
))
1444 return OmniboxEventProto::HOME_PAGE
;
1445 if (controller_
->GetToolbarModel()->WouldPerformSearchTermReplacement(true))
1446 return OmniboxEventProto::SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT
;
1447 if (client_
->IsSearchResultsPage())
1448 return OmniboxEventProto::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT
;
1449 return OmniboxEventProto::OTHER
;
1452 void OmniboxEditModel::ClassifyStringForPasteAndGo(
1453 const base::string16
& text
,
1454 AutocompleteMatch
* match
,
1455 GURL
* alternate_nav_url
) const {
1457 AutocompleteClassifierFactory::GetForProfile(profile_
)->Classify(
1458 text
, false, false, ClassifyPage(), match
, alternate_nav_url
);
1461 void OmniboxEditModel::SetFocusState(OmniboxFocusState state
,
1462 OmniboxFocusChangeReason reason
) {
1463 if (state
== focus_state_
)
1466 // Update state and notify view if the omnibox has focus and the caret
1467 // visibility changed.
1468 const bool was_caret_visible
= is_caret_visible();
1469 focus_state_
= state
;
1470 if (focus_state_
!= OMNIBOX_FOCUS_NONE
&&
1471 is_caret_visible() != was_caret_visible
)
1472 view_
->ApplyCaretVisibility();
1474 client_
->OnFocusChanged(focus_state_
, reason
);