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 "components/omnibox/browser/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/profiler/scoped_tracker.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "components/bookmarks/browser/bookmark_model.h"
20 #include "components/metrics/proto/omnibox_event.pb.h"
21 #include "components/omnibox/browser/autocomplete_classifier.h"
22 #include "components/omnibox/browser/autocomplete_match_type.h"
23 #include "components/omnibox/browser/autocomplete_provider.h"
24 #include "components/omnibox/browser/history_url_provider.h"
25 #include "components/omnibox/browser/keyword_provider.h"
26 #include "components/omnibox/browser/omnibox_client.h"
27 #include "components/omnibox/browser/omnibox_edit_controller.h"
28 #include "components/omnibox/browser/omnibox_event_global_tracker.h"
29 #include "components/omnibox/browser/omnibox_log.h"
30 #include "components/omnibox/browser/omnibox_navigation_observer.h"
31 #include "components/omnibox/browser/omnibox_popup_model.h"
32 #include "components/omnibox/browser/omnibox_popup_view.h"
33 #include "components/omnibox/browser/omnibox_view.h"
34 #include "components/omnibox/browser/search_provider.h"
35 #include "components/search_engines/template_url.h"
36 #include "components/search_engines/template_url_prepopulate_data.h"
37 #include "components/search_engines/template_url_service.h"
38 #include "components/toolbar/toolbar_model.h"
39 #include "components/url_formatter/url_fixer.h"
40 #include "ui/gfx/image/image.h"
41 #include "url/url_util.h"
43 using bookmarks::BookmarkModel
;
44 using metrics::OmniboxEventProto
;
47 // Helpers --------------------------------------------------------------------
51 // Histogram name which counts the number of times that the user text is
52 // cleared. IME users are sometimes in the situation that IME was
53 // unintentionally turned on and failed to input latin alphabets (ASCII
54 // characters) or the opposite case. In that case, users may delete all
55 // the text and the user text gets cleared. We'd like to measure how often
56 // this scenario happens.
58 // Note that since we don't currently correlate "text cleared" events with
59 // IME usage, this also captures many other cases where users clear the text;
60 // though it explicitly doesn't log deleting all the permanent text as
61 // the first action of an editing sequence (see comments in
62 // OnAfterPossibleChange()).
63 const char kOmniboxUserTextClearedHistogram
[] = "Omnibox.UserTextCleared";
65 enum UserTextClearedType
{
66 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING
= 0,
67 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE
= 1,
68 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS
,
71 // Histogram name which counts the number of times the user enters
72 // keyword hint mode and via what method. The possible values are listed
73 // in the EnteredKeywordModeMethod enum which is defined in the .h file.
74 const char kEnteredKeywordModeHistogram
[] = "Omnibox.EnteredKeywordMode";
76 // Histogram name which counts the number of milliseconds a user takes
77 // between focusing and editing the omnibox.
78 const char kFocusToEditTimeHistogram
[] = "Omnibox.FocusToEditTime";
80 // Histogram name which counts the number of milliseconds a user takes
81 // between focusing and opening an omnibox match.
82 const char kFocusToOpenTimeHistogram
[] = "Omnibox.FocusToOpenTimeAnyPopupState";
84 // Split the percentage match histograms into buckets based on the width of the
86 const int kPercentageMatchHistogramWidthBuckets
[] = { 400, 700, 1200 };
88 void RecordPercentageMatchHistogram(const base::string16
& old_text
,
89 const base::string16
& new_text
,
90 bool url_replacement_active
,
91 ui::PageTransition transition
,
93 size_t avg_length
= (old_text
.length() + new_text
.length()) / 2;
96 if (!old_text
.empty() && !new_text
.empty()) {
97 size_t shorter_length
= std::min(old_text
.length(), new_text
.length());
98 base::string16::const_iterator
end(old_text
.begin() + shorter_length
);
99 base::string16::const_iterator
mismatch(
100 std::mismatch(old_text
.begin(), end
, new_text
.begin()).first
);
101 size_t matching_characters
= mismatch
- old_text
.begin();
102 percent
= static_cast<float>(matching_characters
) / avg_length
* 100;
105 std::string histogram_name
;
106 if (url_replacement_active
) {
107 if (transition
== ui::PAGE_TRANSITION_TYPED
) {
108 histogram_name
= "InstantExtended.PercentageMatchV2_QuerytoURL";
109 UMA_HISTOGRAM_PERCENTAGE(histogram_name
, percent
);
111 histogram_name
= "InstantExtended.PercentageMatchV2_QuerytoQuery";
112 UMA_HISTOGRAM_PERCENTAGE(histogram_name
, percent
);
115 if (transition
== ui::PAGE_TRANSITION_TYPED
) {
116 histogram_name
= "InstantExtended.PercentageMatchV2_URLtoURL";
117 UMA_HISTOGRAM_PERCENTAGE(histogram_name
, percent
);
119 histogram_name
= "InstantExtended.PercentageMatchV2_URLtoQuery";
120 UMA_HISTOGRAM_PERCENTAGE(histogram_name
, percent
);
124 std::string suffix
= "large";
125 for (size_t i
= 0; i
< arraysize(kPercentageMatchHistogramWidthBuckets
);
127 if (omnibox_width
< kPercentageMatchHistogramWidthBuckets
[i
]) {
128 suffix
= base::IntToString(kPercentageMatchHistogramWidthBuckets
[i
]);
133 // Cannot rely on UMA histograms macro because the name of the histogram is
134 // generated dynamically.
135 base::HistogramBase
* counter
= base::LinearHistogram::FactoryGet(
136 histogram_name
+ "_" + suffix
, 1, 101, 102,
137 base::Histogram::kUmaTargetedHistogramFlag
);
138 counter
->Add(percent
);
144 // OmniboxEditModel::State ----------------------------------------------------
146 OmniboxEditModel::State::State(bool user_input_in_progress
,
147 const base::string16
& user_text
,
148 const base::string16
& gray_text
,
149 const base::string16
& keyword
,
150 bool is_keyword_hint
,
151 bool url_replacement_enabled
,
152 OmniboxFocusState focus_state
,
153 FocusSource focus_source
,
154 const AutocompleteInput
& autocomplete_input
)
155 : user_input_in_progress(user_input_in_progress
),
156 user_text(user_text
),
157 gray_text(gray_text
),
159 is_keyword_hint(is_keyword_hint
),
160 url_replacement_enabled(url_replacement_enabled
),
161 focus_state(focus_state
),
162 focus_source(focus_source
),
163 autocomplete_input(autocomplete_input
) {
166 OmniboxEditModel::State::~State() {
170 // OmniboxEditModel -----------------------------------------------------------
172 OmniboxEditModel::OmniboxEditModel(OmniboxView
* view
,
173 OmniboxEditController
* controller
,
174 scoped_ptr
<OmniboxClient
> client
)
175 : client_(client
.Pass()),
177 controller_(controller
),
178 focus_state_(OMNIBOX_FOCUS_NONE
),
179 focus_source_(INVALID
),
180 user_input_in_progress_(false),
181 user_input_since_focus_(true),
182 just_deleted_text_(false),
183 has_temporary_text_(false),
185 control_key_state_(UP
),
186 is_keyword_hint_(false),
188 allow_exact_keyword_match_(false) {
189 omnibox_controller_
.reset(new OmniboxController(this, client_
.get()));
192 OmniboxEditModel::~OmniboxEditModel() {
195 const OmniboxEditModel::State
OmniboxEditModel::GetStateForTabSwitch() {
196 // Like typing, switching tabs "accepts" the temporary text as the user
197 // text, because it makes little sense to have temporary text when the
199 if (user_input_in_progress_
) {
200 // Weird edge case to match other browsers: if the edit is empty, revert to
201 // the permanent text (so the user can get it back easily) but select it (so
202 // on switching back, typing will "just work").
203 const base::string16
user_text(UserTextFromDisplayText(view_
->GetText()));
204 if (user_text
.empty()) {
205 base::AutoReset
<bool> tmp(&in_revert_
, true);
207 view_
->SelectAll(true);
209 InternalSetUserText(user_text
);
213 UMA_HISTOGRAM_BOOLEAN("Omnibox.SaveStateForTabSwitch.UserInputInProgress",
214 user_input_in_progress_
);
216 user_input_in_progress_
, user_text_
, view_
->GetGrayTextAutocompletion(),
217 keyword_
, is_keyword_hint_
,
218 controller_
->GetToolbarModel()->url_replacement_enabled(),
219 focus_state_
, focus_source_
, input_
);
222 void OmniboxEditModel::RestoreState(const State
* state
) {
223 // We need to update the permanent text correctly and revert the view
224 // regardless of whether there is saved state.
225 bool url_replacement_enabled
= !state
|| state
->url_replacement_enabled
;
226 controller_
->GetToolbarModel()->set_url_replacement_enabled(
227 url_replacement_enabled
);
228 permanent_text_
= controller_
->GetToolbarModel()->GetText();
229 // Don't muck with the search term replacement state, as we've just set it
231 view_
->RevertWithoutResettingSearchTermReplacement();
232 // Restore the autocomplete controller's input, or clear it if this is a new
234 input_
= state
? state
->autocomplete_input
: AutocompleteInput();
238 SetFocusState(state
->focus_state
, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH
);
239 focus_source_
= state
->focus_source
;
240 // Restore any user editing.
241 if (state
->user_input_in_progress
) {
242 // NOTE: Be sure and set keyword-related state BEFORE invoking
243 // DisplayTextFromUserText(), as its result depends upon this state.
244 keyword_
= state
->keyword
;
245 is_keyword_hint_
= state
->is_keyword_hint
;
246 view_
->SetUserText(state
->user_text
,
247 DisplayTextFromUserText(state
->user_text
), false);
248 view_
->SetGrayTextAutocompletion(state
->gray_text
);
252 AutocompleteMatch
OmniboxEditModel::CurrentMatch(
253 GURL
* alternate_nav_url
) const {
254 // If we have a valid match use it. Otherwise get one for the current text.
255 AutocompleteMatch match
= omnibox_controller_
->current_match();
257 if (!match
.destination_url
.is_valid()) {
258 GetInfoForCurrentText(&match
, alternate_nav_url
);
259 } else if (alternate_nav_url
) {
260 *alternate_nav_url
= AutocompleteResult::ComputeAlternateNavUrl(
266 bool OmniboxEditModel::UpdatePermanentText() {
267 // When there's new permanent text, and the user isn't interacting with the
268 // omnibox, we want to revert the edit to show the new text. We could simply
269 // define "interacting" as "the omnibox has focus", but we still allow updates
270 // when the omnibox has focus as long as the user hasn't begun editing, isn't
271 // seeing zerosuggestions (because changing this text would require changing
272 // or hiding those suggestions), and hasn't toggled on "Show URL" (because
273 // this update will re-enable search term replacement, which will be annoying
274 // if the user is trying to copy the URL). When the omnibox doesn't have
275 // focus, we assume the user may have abandoned their interaction and it's
276 // always safe to change the text; this also prevents someone toggling "Show
277 // URL" (which sounds as if it might be persistent) from seeing just that URL
278 // forever afterwards.
280 // If the page is auto-committing gray text, however, we generally don't want
281 // to make any change to the edit. While auto-commits modify the underlying
282 // permanent URL, they're intended to have no effect on the user's editing
283 // process -- before and after the auto-commit, the omnibox should show the
284 // same user text and the same instant suggestion, even if the auto-commit
285 // happens while the edit doesn't have focus.
286 base::string16 new_permanent_text
= controller_
->GetToolbarModel()->GetText();
287 base::string16 gray_text
= view_
->GetGrayTextAutocompletion();
288 const bool visibly_changed_permanent_text
=
289 (permanent_text_
!= new_permanent_text
) &&
291 (!user_input_in_progress_
&&
292 !(popup_model() && popup_model()->IsOpen()) &&
293 controller_
->GetToolbarModel()->url_replacement_enabled())) &&
294 (gray_text
.empty() ||
295 new_permanent_text
!= user_text_
+ gray_text
);
297 permanent_text_
= new_permanent_text
;
298 return visibly_changed_permanent_text
;
301 GURL
OmniboxEditModel::PermanentURL() {
302 return url_formatter::FixupURL(base::UTF16ToUTF8(permanent_text_
),
306 void OmniboxEditModel::SetUserText(const base::string16
& text
) {
307 SetInputInProgress(true);
308 InternalSetUserText(text
);
309 omnibox_controller_
->InvalidateCurrentMatch();
311 has_temporary_text_
= false;
314 bool OmniboxEditModel::CommitSuggestedText() {
315 const base::string16 suggestion
= view_
->GetGrayTextAutocompletion();
316 if (suggestion
.empty())
319 const base::string16 final_text
= view_
->GetText() + suggestion
;
320 view_
->OnBeforePossibleChange();
321 view_
->SetWindowTextAndCaretPos(final_text
, final_text
.length(), false,
323 view_
->OnAfterPossibleChange();
327 void OmniboxEditModel::OnChanged() {
328 // Hide any suggestions we might be showing.
329 view_
->SetGrayTextAutocompletion(base::string16());
331 // Don't call CurrentMatch() when there's no editing, as in this case we'll
332 // never actually use it. This avoids running the autocomplete providers (and
333 // any systems they then spin up) during startup.
334 const AutocompleteMatch
& current_match
= user_input_in_progress_
?
335 CurrentMatch(NULL
) : AutocompleteMatch();
337 client_
->OnTextChanged(current_match
, user_input_in_progress_
, user_text_
,
338 result(), popup_model() && popup_model()->IsOpen(),
340 controller_
->OnChanged();
343 void OmniboxEditModel::GetDataForURLExport(GURL
* url
,
344 base::string16
* title
,
345 gfx::Image
* favicon
) {
346 *url
= CurrentMatch(NULL
).destination_url
;
347 if (*url
== client_
->GetURL()) {
348 *title
= client_
->GetTitle();
349 *favicon
= client_
->GetFavicon();
353 bool OmniboxEditModel::CurrentTextIsURL() const {
354 if (controller_
->GetToolbarModel()->WouldReplaceURL())
357 // If current text is not composed of replaced search terms and
358 // !user_input_in_progress_, then permanent text is showing and should be a
359 // URL, so no further checking is needed. By avoiding checking in this case,
360 // we avoid calling into the autocomplete providers, and thus initializing the
361 // history system, as long as possible, which speeds startup.
362 if (!user_input_in_progress_
)
365 return !AutocompleteMatch::IsSearchType(CurrentMatch(NULL
).type
);
368 AutocompleteMatch::Type
OmniboxEditModel::CurrentTextType() const {
369 return CurrentMatch(NULL
).type
;
372 void OmniboxEditModel::AdjustTextForCopy(int sel_min
,
373 bool is_all_selected
,
374 base::string16
* text
,
379 // Do not adjust if selection did not start at the beginning of the field, or
380 // if the URL was omitted.
381 if ((sel_min
!= 0) || controller_
->GetToolbarModel()->WouldReplaceURL())
384 // Check whether the user is trying to copy the current page's URL by
385 // selecting the whole thing without editing it.
387 // This is complicated by ZeroSuggest. When ZeroSuggest is active, the user
388 // may be selecting different items and thus changing the address bar text,
389 // even though !user_input_in_progress_; and the permanent URL may change
390 // without updating the visible text, just like when user input is in
391 // progress. In these cases, we don't want to copy the underlying URL, we
392 // want to copy what the user actually sees. However, if we simply never do
393 // this block when !popup_model()->IsOpen(), then just clicking into the
394 // address bar and trying to copy will always bypass this block on pages that
395 // trigger ZeroSuggest, which is too conservative. Instead, in the
396 // ZeroSuggest case, we check that (a) the user hasn't selected one of the
397 // other suggestions, and (b) the selected text is still the same as the
398 // permanent text. ((b) probably implies (a), but it doesn't hurt to be
399 // sure.) If these hold, then it's safe to copy the underlying URL.
400 if (!user_input_in_progress_
&& is_all_selected
&&
401 (!popup_model() || !popup_model()->IsOpen() ||
402 ((popup_model()->selected_line() == 0) && (*text
== permanent_text_
)))) {
403 // It's safe to copy the underlying URL. These lines ensure that if the
404 // scheme was stripped it's added back, and the URL is unescaped (we escape
405 // parts of it for display).
406 *url
= PermanentURL();
407 *text
= base::UTF8ToUTF16(url
->spec());
412 // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now
413 // the user is probably holding down control to cause the copy, which will
414 // screw up our calculation of the desired_tld.
415 AutocompleteMatch match
;
416 client_
->GetAutocompleteClassifier()->Classify(
417 *text
, is_keyword_selected(), true, ClassifyPage(), &match
, NULL
);
418 if (AutocompleteMatch::IsSearchType(match
.type
))
420 *url
= match
.destination_url
;
422 // Prefix the text with 'http://' if the text doesn't start with 'http://',
423 // the text parses as a url with a scheme of http, the user selected the
424 // entire host, and the user hasn't edited the host or manually removed the
426 GURL
perm_url(PermanentURL());
427 if (perm_url
.SchemeIs(url::kHttpScheme
) &&
428 url
->SchemeIs(url::kHttpScheme
) && perm_url
.host() == url
->host()) {
430 base::string16 http
= base::ASCIIToUTF16(url::kHttpScheme
) +
431 base::ASCIIToUTF16(url::kStandardSchemeSeparator
);
432 if (text
->compare(0, http
.length(), http
) != 0)
433 *text
= http
+ *text
;
437 void OmniboxEditModel::SetInputInProgress(bool in_progress
) {
438 if (in_progress
&& !user_input_since_focus_
) {
439 base::TimeTicks now
= base::TimeTicks::Now();
440 DCHECK(last_omnibox_focus_
<= now
);
441 UMA_HISTOGRAM_TIMES(kFocusToEditTimeHistogram
, now
- last_omnibox_focus_
);
442 user_input_since_focus_
= true;
445 if (user_input_in_progress_
== in_progress
)
448 user_input_in_progress_
= in_progress
;
449 if (user_input_in_progress_
) {
450 time_user_first_modified_omnibox_
= base::TimeTicks::Now();
451 base::RecordAction(base::UserMetricsAction("OmniboxInputInProgress"));
452 autocomplete_controller()->ResetSession();
455 controller_
->GetToolbarModel()->set_input_in_progress(in_progress
);
456 controller_
->UpdateWithoutTabRestore();
458 if (user_input_in_progress_
|| !in_revert_
)
459 client_
->OnInputStateChanged();
462 void OmniboxEditModel::Revert() {
463 SetInputInProgress(false);
466 InternalSetUserText(base::string16());
468 is_keyword_hint_
= false;
469 has_temporary_text_
= false;
470 view_
->SetWindowTextAndCaretPos(permanent_text_
,
471 has_focus() ? permanent_text_
.length() : 0,
476 void OmniboxEditModel::StartAutocomplete(
477 bool has_selected_text
,
478 bool prevent_inline_autocomplete
,
479 bool entering_keyword_mode
) {
480 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
481 tracked_objects::ScopedTracker
tracking_profile(
482 FROM_HERE_WITH_EXPLICIT_FUNCTION(
483 "440919 OmniboxEditModel::StartAutocomplete"));
484 size_t cursor_position
;
485 if (inline_autocomplete_text_
.empty()) {
486 // Cursor position is equivalent to the current selection's end.
488 view_
->GetSelectionBounds(&start
, &cursor_position
);
489 // If we're in keyword mode, we're not displaying the full |user_text_|, so
490 // the cursor position we got from the view has to be adjusted later by the
491 // length of the undisplayed text. If we're just entering keyword mode,
492 // though, we have to avoid making this adjustment, because we haven't
493 // actually hidden any text yet, but the caller has already cleared
494 // |is_keyword_hint_|, so DisplayTextFromUserText() will believe we are
495 // already in keyword mode, and will thus mis-adjust the cursor position.
496 if (!entering_keyword_mode
) {
498 user_text_
.length() - DisplayTextFromUserText(user_text_
).length();
501 // There are some cases where StartAutocomplete() may be called
502 // with non-empty |inline_autocomplete_text_|. In such cases, we cannot
503 // use the current selection, because it could result with the cursor
504 // position past the last character from the user text. Instead,
505 // we assume that the cursor is simply at the end of input.
506 // One example is when user presses Ctrl key while having a highlighted
507 // inline autocomplete text.
508 // TODO: Rethink how we are going to handle this case to avoid
509 // inconsistent behavior when user presses Ctrl key.
510 // See http://crbug.com/165961 and http://crbug.com/165968 for more details.
511 cursor_position
= user_text_
.length();
515 if (client_
->CurrentPageExists() && view_
->IsIndicatingQueryRefinement())
516 current_url
= client_
->GetURL();
517 input_
= AutocompleteInput(
518 user_text_
, cursor_position
, std::string(), current_url
, ClassifyPage(),
519 prevent_inline_autocomplete
|| just_deleted_text_
||
520 (has_selected_text
&& inline_autocomplete_text_
.empty()) ||
521 (paste_state_
!= NONE
),
522 is_keyword_selected(),
523 is_keyword_selected() || allow_exact_keyword_match_
, true, false,
524 client_
->GetSchemeClassifier());
526 omnibox_controller_
->StartAutocomplete(input_
);
529 void OmniboxEditModel::StopAutocomplete() {
530 autocomplete_controller()->Stop(true);
533 bool OmniboxEditModel::CanPasteAndGo(const base::string16
& text
) const {
534 if (!client_
->IsPasteAndGoEnabled())
537 AutocompleteMatch match
;
538 ClassifyStringForPasteAndGo(text
, &match
, NULL
);
539 return match
.destination_url
.is_valid();
542 void OmniboxEditModel::PasteAndGo(const base::string16
& text
) {
543 DCHECK(CanPasteAndGo(text
));
544 UMA_HISTOGRAM_COUNTS("Omnibox.PasteAndGo", 1);
547 AutocompleteMatch match
;
548 GURL alternate_nav_url
;
549 ClassifyStringForPasteAndGo(text
, &match
, &alternate_nav_url
);
550 view_
->OpenMatch(match
, CURRENT_TAB
, alternate_nav_url
, text
,
551 OmniboxPopupModel::kNoMatch
);
554 bool OmniboxEditModel::IsPasteAndSearch(const base::string16
& text
) const {
555 AutocompleteMatch match
;
556 ClassifyStringForPasteAndGo(text
, &match
, NULL
);
557 return AutocompleteMatch::IsSearchType(match
.type
);
560 void OmniboxEditModel::AcceptInput(WindowOpenDisposition disposition
,
562 // Get the URL and transition type for the selected entry.
563 GURL alternate_nav_url
;
564 AutocompleteMatch match
= CurrentMatch(&alternate_nav_url
);
566 // If CTRL is down it means the user wants to append ".com" to the text he
567 // typed. If we can successfully generate a URL_WHAT_YOU_TYPED match doing
568 // that, then we use this. These matches are marked as generated by the
569 // HistoryURLProvider so we only generate them if this provider is present.
570 if (control_key_state_
== DOWN_WITHOUT_CHANGE
&& !is_keyword_selected() &&
571 autocomplete_controller()->history_url_provider()) {
572 // Generate a new AutocompleteInput, copying the latest one but using "com"
573 // as the desired TLD. Then use this autocomplete input to generate a
574 // URL_WHAT_YOU_TYPED AutocompleteMatch. Note that using the most recent
575 // input instead of the currently visible text means we'll ignore any
576 // visible inline autocompletion: if a user types "foo" and is autocompleted
577 // to "foodnetwork.com", ctrl-enter will navigate to "foo.com", not
578 // "foodnetwork.com". At the time of writing, this behavior matches
579 // Internet Explorer, but not Firefox.
580 input_
= AutocompleteInput(
581 has_temporary_text_
? UserTextFromDisplayText(view_
->GetText())
583 input_
.cursor_position(), "com", GURL(),
584 input_
.current_page_classification(),
585 input_
.prevent_inline_autocomplete(), input_
.prefer_keyword(),
586 input_
.allow_exact_keyword_match(), input_
.want_asynchronous_matches(),
587 input_
.from_omnibox_focus(), client_
->GetSchemeClassifier());
588 AutocompleteMatch
url_match(
589 autocomplete_controller()->history_url_provider()->SuggestExactInput(
590 input_
, input_
.canonicalized_url(), false));
592 if (url_match
.destination_url
.is_valid()) {
593 // We have a valid URL, we use this newly generated AutocompleteMatch.
595 alternate_nav_url
= GURL();
599 if (!match
.destination_url
.is_valid())
602 if ((match
.transition
== ui::PAGE_TRANSITION_TYPED
) &&
603 (match
.destination_url
== PermanentURL())) {
604 // When the user hit enter on the existing permanent URL, treat it like a
605 // reload for scoring purposes. We could detect this by just checking
606 // user_input_in_progress_, but it seems better to treat "edits" that end
607 // up leaving the URL unchanged (e.g. deleting the last character and then
608 // retyping it) as reloads too. We exclude non-TYPED transitions because if
609 // the transition is GENERATED, the user input something that looked
610 // different from the current URL, even if it wound up at the same place
611 // (e.g. manually retyping the same search query), and it seems wrong to
612 // treat this as a reload.
613 match
.transition
= ui::PAGE_TRANSITION_RELOAD
;
614 } else if (for_drop
||
615 ((paste_state_
!= NONE
) &&
616 (match
.type
== AutocompleteMatchType::URL_WHAT_YOU_TYPED
))) {
617 // When the user pasted in a URL and hit enter, score it like a link click
618 // rather than a normal typed URL, so it doesn't get inline autocompleted
619 // as aggressively later.
620 match
.transition
= ui::PAGE_TRANSITION_LINK
;
623 client_
->OnInputAccepted(match
);
625 DCHECK(popup_model());
626 view_
->OpenMatch(match
, disposition
, alternate_nav_url
, base::string16(),
627 popup_model()->selected_line());
630 void OmniboxEditModel::OpenMatch(AutocompleteMatch match
,
631 WindowOpenDisposition disposition
,
632 const GURL
& alternate_nav_url
,
633 const base::string16
& pasted_text
,
635 const base::TimeTicks
& now(base::TimeTicks::Now());
636 base::TimeDelta
elapsed_time_since_user_first_modified_omnibox(
637 now
- time_user_first_modified_omnibox_
);
638 autocomplete_controller()->UpdateMatchDestinationURLWithQueryFormulationTime(
639 elapsed_time_since_user_first_modified_omnibox
, &match
);
641 base::string16
input_text(pasted_text
);
642 if (input_text
.empty())
643 input_text
= user_input_in_progress_
? user_text_
: permanent_text_
;
644 // Create a dummy AutocompleteInput for use in calling SuggestExactInput()
645 // to create an alternate navigational match.
646 AutocompleteInput
alternate_input(
647 input_text
, base::string16::npos
, std::string(),
648 // Somehow we can occasionally get here with no active tab. It's not
649 // clear why this happens.
650 client_
->CurrentPageExists() ? client_
->GetURL() : GURL(), ClassifyPage(),
651 false, false, true, true, false, client_
->GetSchemeClassifier());
652 scoped_ptr
<OmniboxNavigationObserver
> observer(
653 client_
->CreateOmniboxNavigationObserver(
655 autocomplete_controller()->history_url_provider()->SuggestExactInput(
656 alternate_input
, alternate_nav_url
,
657 AutocompleteInput::HasHTTPScheme(input_text
))));
659 base::TimeDelta
elapsed_time_since_last_change_to_default_match(
660 now
- autocomplete_controller()->last_time_default_match_changed());
661 DCHECK(match
.provider
);
662 // These elapsed times don't really make sense for ZeroSuggest matches
663 // (because the user does not modify the omnibox for ZeroSuggest), so for
664 // those we set the elapsed times to something that will be ignored by
665 // metrics_log.cc. They also don't necessarily make sense if the omnibox
666 // dropdown is closed or the user used a paste-and-go action. (In most
667 // cases when this happens, the user never modified the omnibox.)
668 if ((match
.provider
->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST
) ||
669 !popup_model()->IsOpen() || !pasted_text
.empty()) {
670 const base::TimeDelta default_time_delta
=
671 base::TimeDelta::FromMilliseconds(-1);
672 elapsed_time_since_user_first_modified_omnibox
= default_time_delta
;
673 elapsed_time_since_last_change_to_default_match
= default_time_delta
;
675 // If the popup is closed or this is a paste-and-go action (meaning the
676 // contents of the dropdown are ignored regardless), we record for logging
677 // purposes a selected_index of 0 and a suggestion list as having a single
678 // entry of the match used.
679 ACMatches fake_single_entry_matches
;
680 fake_single_entry_matches
.push_back(match
);
681 AutocompleteResult fake_single_entry_result
;
682 fake_single_entry_result
.AppendMatches(input_
, fake_single_entry_matches
);
687 popup_model()->IsOpen(),
688 (!popup_model()->IsOpen() || !pasted_text
.empty()) ? 0 : index
,
689 !pasted_text
.empty(),
690 -1, // don't yet know tab ID; set later if appropriate
692 elapsed_time_since_user_first_modified_omnibox
,
693 match
.allowed_to_be_default_match
? match
.inline_autocompletion
.length() :
694 base::string16::npos
,
695 elapsed_time_since_last_change_to_default_match
,
696 (!popup_model()->IsOpen() || !pasted_text
.empty()) ?
697 fake_single_entry_result
: result());
698 DCHECK(!popup_model()->IsOpen() || !pasted_text
.empty() ||
699 (log
.elapsed_time_since_user_first_modified_omnibox
>=
700 log
.elapsed_time_since_last_change_to_default_match
))
701 << "We should've got the notification that the user modified the "
702 << "omnibox text at same time or before the most recent time the "
703 << "default match changed.";
705 if ((disposition
== CURRENT_TAB
) && client_
->CurrentPageExists()) {
706 // If we know the destination is being opened in the current tab,
707 // we can easily get the tab ID. (If it's being opened in a new
708 // tab, we don't know the tab ID yet.)
709 log
.tab_id
= client_
->GetSessionID().id();
711 autocomplete_controller()->AddProvidersInfo(&log
.providers_info
);
712 client_
->OnURLOpenedFromOmnibox(&log
);
713 OmniboxEventGlobalTracker::GetInstance()->OnURLOpened(&log
);
714 LOCAL_HISTOGRAM_BOOLEAN("Omnibox.EventCount", true);
715 DCHECK(!last_omnibox_focus_
.is_null())
716 << "An omnibox focus should have occurred before opening a match.";
717 UMA_HISTOGRAM_TIMES(kFocusToOpenTimeHistogram
, now
- last_omnibox_focus_
);
719 TemplateURLService
* service
= client_
->GetTemplateURLService();
720 TemplateURL
* template_url
= match
.GetTemplateURL(service
, false);
722 if (match
.transition
== ui::PAGE_TRANSITION_KEYWORD
) {
723 // The user is using a non-substituting keyword or is explicitly in
726 // Don't increment usage count for extension keywords.
727 if (client_
->ProcessExtensionKeyword(template_url
, match
, disposition
,
729 if (disposition
!= NEW_BACKGROUND_TAB
)
734 base::RecordAction(base::UserMetricsAction("AcceptedKeyword"));
735 client_
->GetTemplateURLService()->IncrementUsageCount(template_url
);
737 DCHECK_EQ(ui::PAGE_TRANSITION_GENERATED
, match
.transition
);
738 // NOTE: We purposefully don't increment the usage count of the default
739 // search engine here like we do for explicit keywords above; see comments
740 // in template_url.h.
743 SearchEngineType search_engine_type
= match
.destination_url
.is_valid() ?
744 TemplateURLPrepopulateData::GetEngineType(match
.destination_url
) :
746 UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngineType", search_engine_type
,
750 // Get the current text before we call RevertAll() which will clear it.
751 base::string16 current_text
= view_
->GetText();
753 if (disposition
!= NEW_BACKGROUND_TAB
) {
754 base::AutoReset
<bool> tmp(&in_revert_
, true);
755 view_
->RevertAll(); // Revert the box to its unedited state.
758 RecordPercentageMatchHistogram(
759 permanent_text_
, current_text
,
760 controller_
->GetToolbarModel()->WouldReplaceURL(),
761 match
.transition
, view_
->GetWidth());
763 // Track whether the destination URL sends us to a search results page
764 // using the default search provider.
765 if (client_
->GetTemplateURLService()
766 ->IsSearchResultsPageFromDefaultSearchProvider(
767 match
.destination_url
)) {
769 base::UserMetricsAction("OmniboxDestinationURLIsSearchOnDSP"));
772 if (match
.destination_url
.is_valid()) {
773 // This calls RevertAll again.
774 base::AutoReset
<bool> tmp(&in_revert_
, true);
775 controller_
->OnAutocompleteAccept(
776 match
.destination_url
, disposition
,
777 ui::PageTransitionFromInt(
778 match
.transition
| ui::PAGE_TRANSITION_FROM_ADDRESS_BAR
));
779 if (observer
&& observer
->HasSeenPendingLoad())
780 ignore_result(observer
.release()); // The observer will delete itself.
783 BookmarkModel
* bookmark_model
= client_
->GetBookmarkModel();
784 if (bookmark_model
&& bookmark_model
->IsBookmarked(match
.destination_url
))
785 client_
->OnBookmarkLaunched();
788 bool OmniboxEditModel::AcceptKeyword(EnteredKeywordModeMethod entered_method
) {
789 DCHECK(is_keyword_hint_
&& !keyword_
.empty());
791 autocomplete_controller()->Stop(false);
792 is_keyword_hint_
= false;
794 if (popup_model() && popup_model()->IsOpen())
795 popup_model()->SetSelectedLineState(OmniboxPopupModel::KEYWORD
);
797 StartAutocomplete(false, true, true);
799 // When entering keyword mode via tab, the new text to show is whatever the
800 // newly-selected match in the dropdown is. When entering via space, however,
801 // we should make sure to use the actual |user_text_| as the basis for the new
802 // text. This ensures that if the user types "<keyword><space>" and the
803 // default match would have inline autocompleted a further string (e.g.
804 // because there's a past multi-word search beginning with this keyword), the
805 // inline autocompletion doesn't get filled in as the keyword search query
808 // We also treat tabbing into keyword mode like tabbing through the popup in
809 // that we set |has_temporary_text_|, whereas pressing space is treated like
810 // a new keystroke that changes the current match instead of overlaying it
811 // with a temporary one. This is important because rerunning autocomplete
812 // after the user pressed space, which will have happened just before reaching
813 // here, may have generated a new match, which the user won't actually see and
814 // which we don't want to switch back to when existing keyword mode; see
815 // comments in ClearKeyword().
816 if (entered_method
== ENTERED_KEYWORD_MODE_VIA_TAB
) {
817 // Ensure the current selection is saved before showing keyword mode
818 // so that moving to another line and then reverting the text will restore
819 // the current state properly.
820 bool save_original_selection
= !has_temporary_text_
;
821 has_temporary_text_
= true;
822 const AutocompleteMatch
& match
= CurrentMatch(NULL
);
823 original_url_
= match
.destination_url
;
824 view_
->OnTemporaryTextMaybeChanged(
825 DisplayTextFromUserText(match
.fill_into_edit
),
826 save_original_selection
, true);
828 view_
->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(user_text_
),
832 base::RecordAction(base::UserMetricsAction("AcceptedKeywordHint"));
833 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram
, entered_method
,
834 ENTERED_KEYWORD_MODE_NUM_ITEMS
);
839 void OmniboxEditModel::AcceptTemporaryTextAsUserText() {
840 InternalSetUserText(UserTextFromDisplayText(view_
->GetText()));
841 has_temporary_text_
= false;
843 if (user_input_in_progress_
|| !in_revert_
)
844 client_
->OnInputStateChanged();
847 void OmniboxEditModel::ClearKeyword() {
848 autocomplete_controller()->Stop(false);
850 // While we're always in keyword mode upon reaching here, sometimes we've just
851 // toggled in via space or tab, and sometimes we're on a non-toggled line
852 // (usually because the user has typed a search string). Keep track of the
853 // difference, as we'll need it below.
854 bool was_toggled_into_keyword_mode
=
855 popup_model()->selected_line_state() == OmniboxPopupModel::KEYWORD
;
857 omnibox_controller_
->ClearPopupKeywordMode();
859 // There are several possible states we could have been in before the user hit
860 // backspace or shift-tab to enter this function:
861 // (1) was_toggled_into_keyword_mode == false, has_temporary_text_ == false
862 // The user typed a further key after being in keyword mode already, e.g.
864 // (2) was_toggled_into_keyword_mode == false, has_temporary_text_ == true
865 // The user tabbed away from a dropdown entry in keyword mode, then tabbed
866 // back to it, e.g. "google.com f<tab><shift-tab>".
867 // (3) was_toggled_into_keyword_mode == true, has_temporary_text_ == false
868 // The user had just typed space to enter keyword mode, e.g.
870 // (4) was_toggled_into_keyword_mode == true, has_temporary_text_ == true
871 // The user had just typed tab to enter keyword mode, e.g.
872 // "google.com<tab>".
874 // For states 1-3, we can safely handle the exit from keyword mode by using
875 // OnBefore/AfterPossibleChange() to do a complete state update of all
876 // objects. However, with state 4, if we do this, and if the user had tabbed
877 // into keyword mode on a line in the middle of the dropdown instead of the
878 // first line, then the state update will rerun autocompletion and reset the
879 // whole dropdown, and end up with the first line selected instead, instead of
880 // just "undoing" the keyword mode entry on the non-first line. So in this
881 // case we simply reset |is_keyword_hint_| to true and update the window text.
883 // You might wonder why we don't simply do this in all cases. In states 1-2,
884 // getting out of keyword mode likely shouldn't put us in keyword hint mode;
885 // if the user typed "google.com f" and then put the cursor before 'f' and hit
886 // backspace, the resulting text would be "google.comf", which is unlikely to
887 // be a keyword. Unconditionally putting things back in keyword hint mode is
888 // going to lead to internally inconsistent state, and possible future
889 // crashes. State 3 is more subtle; here we need to do the full state update
890 // because before entering keyword mode to begin with, we will have re-run
891 // autocomplete in ways that can produce surprising results if we just switch
892 // back out of keyword mode. For example, if a user has a keyword named "x",
893 // an inline-autocompletable history site "xyz.com", and a lower-ranked
894 // inline-autocompletable search "x y", then typing "x" will inline-
895 // autocomplete to "xyz.com", hitting space will toggle into keyword mode, but
896 // then hitting backspace could wind up with the default match as the "x y"
897 // search, which feels bizarre.
898 const base::string16
window_text(keyword_
+ view_
->GetText());
899 if (was_toggled_into_keyword_mode
&& has_temporary_text_
) {
901 is_keyword_hint_
= true;
902 view_
->SetWindowTextAndCaretPos(window_text
.c_str(), keyword_
.length(),
906 view_
->OnBeforePossibleChange();
907 view_
->SetWindowTextAndCaretPos(window_text
.c_str(), keyword_
.length(),
910 is_keyword_hint_
= false;
911 view_
->OnAfterPossibleChange();
915 void OmniboxEditModel::OnSetFocus(bool control_down
) {
916 last_omnibox_focus_
= base::TimeTicks::Now();
917 user_input_since_focus_
= false;
919 // If the omnibox lost focus while the caret was hidden and then regained
920 // focus, OnSetFocus() is called and should restore visibility. Note that
921 // focus can be regained without an accompanying call to
922 // OmniboxView::SetFocus(), e.g. by tabbing in.
923 SetFocusState(OMNIBOX_FOCUS_VISIBLE
, OMNIBOX_FOCUS_CHANGE_EXPLICIT
);
924 control_key_state_
= control_down
? DOWN_WITHOUT_CHANGE
: UP
;
926 // Try to get ZeroSuggest suggestions if a page is loaded and the user has
927 // not been typing in the omnibox. The |user_input_in_progress_| check is
928 // used to detect the case where this function is called after right-clicking
929 // in the omnibox and selecting paste in Linux (in which case we actually get
930 // the OnSetFocus() call after the process of handling the paste has kicked
932 // TODO(hfung): Remove this when crbug/271590 is fixed.
933 if (client_
->CurrentPageExists() && !user_input_in_progress_
) {
934 // We avoid PermanentURL() here because it's not guaranteed to give us the
935 // actual underlying current URL, e.g. if we're on the NTP and the
936 // |permanent_text_| is empty.
938 AutocompleteInput(permanent_text_
, base::string16::npos
, std::string(),
939 client_
->GetURL(), ClassifyPage(), false, false, true,
940 true, true, client_
->GetSchemeClassifier());
941 autocomplete_controller()->Start(input_
);
944 if (user_input_in_progress_
|| !in_revert_
)
945 client_
->OnInputStateChanged();
948 void OmniboxEditModel::SetCaretVisibility(bool visible
) {
949 // Caret visibility only matters if the omnibox has focus.
950 if (focus_state_
!= OMNIBOX_FOCUS_NONE
) {
951 SetFocusState(visible
? OMNIBOX_FOCUS_VISIBLE
: OMNIBOX_FOCUS_INVISIBLE
,
952 OMNIBOX_FOCUS_CHANGE_EXPLICIT
);
956 void OmniboxEditModel::OnWillKillFocus() {
957 if (user_input_in_progress_
|| !in_revert_
)
958 client_
->OnInputStateChanged();
961 void OmniboxEditModel::OnKillFocus() {
962 SetFocusState(OMNIBOX_FOCUS_NONE
, OMNIBOX_FOCUS_CHANGE_EXPLICIT
);
963 focus_source_
= INVALID
;
964 control_key_state_
= UP
;
968 bool OmniboxEditModel::WillHandleEscapeKey() const {
969 return user_input_in_progress_
||
970 (has_temporary_text_
&&
971 (CurrentMatch(NULL
).destination_url
!= original_url_
));
974 bool OmniboxEditModel::OnEscapeKeyPressed() {
975 if (has_temporary_text_
&&
976 (CurrentMatch(NULL
).destination_url
!= original_url_
)) {
977 RevertTemporaryText(true);
981 // We do not clear the pending entry from the omnibox when a load is first
982 // stopped. If the user presses Escape while stopped, whether editing or not,
984 if (client_
->CurrentPageExists() && !client_
->IsLoading()) {
985 client_
->DiscardNonCommittedNavigations();
989 if (!user_text_
.empty()) {
990 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram
,
991 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE
,
992 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS
);
995 // Unconditionally revert/select all. This ensures any popup, whether due to
996 // normal editing or ZeroSuggest, is closed, and the full text is selected.
997 // This in turn allows the user to use escape to quickly select all the text
998 // for ease of replacement, and matches other browsers.
999 bool user_input_was_in_progress
= user_input_in_progress_
;
1001 view_
->SelectAll(true);
1003 // If the user was in the midst of editing, don't cancel any underlying page
1004 // load. This doesn't match IE or Firefox, but seems more correct. Note that
1005 // we do allow the page load to be stopped in the case where ZeroSuggest was
1006 // visible; this is so that it's still possible to focus the address bar and
1007 // hit escape once to stop a load even if the address being loaded triggers
1008 // the ZeroSuggest popup.
1009 return user_input_was_in_progress
;
1012 void OmniboxEditModel::OnControlKeyChanged(bool pressed
) {
1013 if (pressed
== (control_key_state_
== UP
))
1014 control_key_state_
= pressed
? DOWN_WITHOUT_CHANGE
: UP
;
1017 void OmniboxEditModel::OnPaste() {
1018 UMA_HISTOGRAM_COUNTS("Omnibox.Paste", 1);
1019 paste_state_
= PASTING
;
1022 void OmniboxEditModel::OnUpOrDownKeyPressed(int count
) {
1023 // NOTE: This purposefully doesn't trigger any code that resets paste_state_.
1024 if (popup_model() && popup_model()->IsOpen()) {
1025 // The popup is open, so the user should be able to interact with it
1027 popup_model()->Move(count
);
1031 if (!query_in_progress()) {
1032 // The popup is neither open nor working on a query already. So, start an
1033 // autocomplete query for the current text. This also sets
1034 // user_input_in_progress_ to true, which we want: if the user has started
1035 // to interact with the popup, changing the permanent_text_ shouldn't change
1036 // the displayed text.
1037 // Note: This does not force the popup to open immediately.
1038 // TODO(pkasting): We should, in fact, force this particular query to open
1039 // the popup immediately.
1040 if (!user_input_in_progress_
)
1041 InternalSetUserText(permanent_text_
);
1042 view_
->UpdatePopup();
1046 // TODO(pkasting): The popup is working on a query but is not open. We should
1047 // force it to open immediately.
1050 void OmniboxEditModel::OnPopupDataChanged(
1051 const base::string16
& text
,
1052 GURL
* destination_for_temporary_text_change
,
1053 const base::string16
& keyword
,
1054 bool is_keyword_hint
) {
1055 // The popup changed its data, the match in the controller is no longer valid.
1056 omnibox_controller_
->InvalidateCurrentMatch();
1058 // Update keyword/hint-related local state.
1059 bool keyword_state_changed
= (keyword_
!= keyword
) ||
1060 ((is_keyword_hint_
!= is_keyword_hint
) && !keyword
.empty());
1061 if (keyword_state_changed
) {
1063 is_keyword_hint_
= is_keyword_hint
;
1065 // |is_keyword_hint_| should always be false if |keyword_| is empty.
1066 DCHECK(!keyword_
.empty() || !is_keyword_hint_
);
1069 // Handle changes to temporary text.
1070 if (destination_for_temporary_text_change
!= NULL
) {
1071 const bool save_original_selection
= !has_temporary_text_
;
1072 if (save_original_selection
) {
1073 // Save the original selection and URL so it can be reverted later.
1074 has_temporary_text_
= true;
1075 original_url_
= *destination_for_temporary_text_change
;
1076 inline_autocomplete_text_
.clear();
1077 view_
->OnInlineAutocompleteTextCleared();
1079 if (control_key_state_
== DOWN_WITHOUT_CHANGE
) {
1080 // Arrowing around the popup cancels control-enter.
1081 control_key_state_
= DOWN_WITH_CHANGE
;
1082 // Now things are a bit screwy: the desired_tld has changed, but if we
1083 // update the popup, the new order of entries won't match the old, so the
1084 // user's selection gets screwy; and if we don't update the popup, and the
1085 // user reverts, then the selected item will be as if control is still
1086 // pressed, even though maybe it isn't any more. There is no obvious
1087 // right answer here :(
1089 view_
->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text
),
1090 save_original_selection
, true);
1094 bool call_controller_onchanged
= true;
1095 inline_autocomplete_text_
= text
;
1096 if (inline_autocomplete_text_
.empty())
1097 view_
->OnInlineAutocompleteTextCleared();
1099 const base::string16
& user_text
=
1100 user_input_in_progress_
? user_text_
: permanent_text_
;
1101 if (keyword_state_changed
&& is_keyword_selected()) {
1102 // If we reach here, the user most likely entered keyword mode by inserting
1103 // a space between a keyword name and a search string (as pressing space or
1104 // tab after the keyword name alone would have been be handled in
1105 // MaybeAcceptKeywordBySpace() by calling AcceptKeyword(), which won't reach
1106 // here). In this case, we don't want to call
1107 // OnInlineAutocompleteTextMaybeChanged() as normal, because that will
1108 // correctly change the text (to the search string alone) but move the caret
1109 // to the end of the string; instead we want the caret at the start of the
1110 // search string since that's where it was in the original input. So we set
1111 // the text and caret position directly.
1113 // It may also be possible to reach here if we're reverting from having
1114 // temporary text back to a default match that's a keyword search, but in
1115 // that case the RevertTemporaryText() call below will reset the caret or
1116 // selection correctly so the caret positioning we do here won't matter.
1117 view_
->SetWindowTextAndCaretPos(DisplayTextFromUserText(user_text
), 0,
1119 } else if (view_
->OnInlineAutocompleteTextMaybeChanged(
1120 DisplayTextFromUserText(user_text
+ inline_autocomplete_text_
),
1121 DisplayTextFromUserText(user_text
).length())) {
1122 call_controller_onchanged
= false;
1125 // If |has_temporary_text_| is true, then we previously had a manual selection
1126 // but now don't (or |destination_for_temporary_text_change| would have been
1127 // non-NULL). This can happen when deleting the selected item in the popup.
1128 // In this case, we've already reverted the popup to the default match, so we
1129 // need to revert ourselves as well.
1130 if (has_temporary_text_
) {
1131 RevertTemporaryText(false);
1132 call_controller_onchanged
= false;
1135 // We need to invoke OnChanged in case the destination url changed (as could
1136 // happen when control is toggled).
1137 if (call_controller_onchanged
)
1141 bool OmniboxEditModel::OnAfterPossibleChange(const base::string16
& old_text
,
1142 const base::string16
& new_text
,
1143 size_t selection_start
,
1144 size_t selection_end
,
1145 bool selection_differs
,
1147 bool just_deleted_text
,
1148 bool allow_keyword_ui_change
) {
1149 // Update the paste state as appropriate: if we're just finishing a paste
1150 // that replaced all the text, preserve that information; otherwise, if we've
1151 // made some other edit, clear paste tracking.
1152 if (paste_state_
== PASTING
)
1153 paste_state_
= PASTED
;
1154 else if (text_differs
)
1155 paste_state_
= NONE
;
1157 if (text_differs
|| selection_differs
) {
1158 // Record current focus state for this input if we haven't already.
1159 if (focus_source_
== INVALID
) {
1160 // We should generally expect the omnibox to have focus at this point, but
1161 // it doesn't always on Linux. This is because, unlike other platforms,
1162 // right clicking in the omnibox on Linux doesn't focus it. So pasting via
1163 // right-click can change the contents without focusing the omnibox.
1164 // TODO(samarth): fix Linux focus behavior and add a DCHECK here to
1165 // check that the omnibox does have focus.
1166 focus_source_
= (focus_state_
== OMNIBOX_FOCUS_INVISIBLE
) ?
1170 // Restore caret visibility whenever the user changes text or selection in
1172 SetFocusState(OMNIBOX_FOCUS_VISIBLE
, OMNIBOX_FOCUS_CHANGE_TYPING
);
1175 // Modifying the selection counts as accepting the autocompleted text.
1176 const bool user_text_changed
=
1177 text_differs
|| (selection_differs
&& !inline_autocomplete_text_
.empty());
1179 // If something has changed while the control key is down, prevent
1180 // "ctrl-enter" until the control key is released.
1181 if ((text_differs
|| selection_differs
) &&
1182 (control_key_state_
== DOWN_WITHOUT_CHANGE
))
1183 control_key_state_
= DOWN_WITH_CHANGE
;
1185 if (!user_text_changed
)
1188 // If the user text has not changed, we do not want to change the model's
1189 // state associated with the text. Otherwise, we can get surprising behavior
1190 // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983
1191 InternalSetUserText(UserTextFromDisplayText(new_text
));
1192 has_temporary_text_
= false;
1194 // Track when the user has deleted text so we won't allow inline
1196 just_deleted_text_
= just_deleted_text
;
1198 if (user_input_in_progress_
&& user_text_
.empty()) {
1199 // Log cases where the user started editing and then subsequently cleared
1200 // all the text. Note that this explicitly doesn't catch cases like
1201 // "hit ctrl-l to select whole edit contents, then hit backspace", because
1202 // in such cases, |user_input_in_progress| won't be true here.
1203 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram
,
1204 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING
,
1205 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS
);
1208 const bool no_selection
= selection_start
== selection_end
;
1210 // Update the popup for the change, in the process changing to keyword mode
1211 // if the user hit space in mid-string after a keyword.
1212 // |allow_exact_keyword_match_| will be used by StartAutocomplete() method,
1213 // which will be called by |view_->UpdatePopup()|; so after that returns we
1214 // can safely reset this flag.
1215 allow_exact_keyword_match_
= text_differs
&& allow_keyword_ui_change
&&
1216 !just_deleted_text
&& no_selection
&&
1217 CreatedKeywordSearchByInsertingSpaceInMiddle(old_text
, user_text_
,
1219 view_
->UpdatePopup();
1220 if (allow_exact_keyword_match_
) {
1221 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram
,
1222 ENTERED_KEYWORD_MODE_VIA_SPACE_IN_MIDDLE
,
1223 ENTERED_KEYWORD_MODE_NUM_ITEMS
);
1224 allow_exact_keyword_match_
= false;
1227 // Change to keyword mode if the user is now pressing space after a keyword
1228 // name. Note that if this is the case, then even if there was no keyword
1229 // hint when we entered this function (e.g. if the user has used space to
1230 // replace some selected text that was adjoined to this keyword), there will
1231 // be one now because of the call to UpdatePopup() above; so it's safe for
1232 // MaybeAcceptKeywordBySpace() to look at |keyword_| and |is_keyword_hint_| to
1233 // determine what keyword, if any, is applicable.
1235 // If MaybeAcceptKeywordBySpace() accepts the keyword and returns true, that
1236 // will have updated our state already, so in that case we don't also return
1237 // true from this function.
1238 return !(text_differs
&& allow_keyword_ui_change
&& !just_deleted_text
&&
1239 no_selection
&& (selection_start
== user_text_
.length()) &&
1240 MaybeAcceptKeywordBySpace(user_text_
));
1243 // TODO(beaudoin): Merge OnPopupDataChanged with this method once the popup
1244 // handling has completely migrated to omnibox_controller.
1245 void OmniboxEditModel::OnCurrentMatchChanged() {
1246 has_temporary_text_
= false;
1248 const AutocompleteMatch
& match
= omnibox_controller_
->current_match();
1250 client_
->OnCurrentMatchChanged(match
);
1252 // We store |keyword| and |is_keyword_hint| in temporary variables since
1253 // OnPopupDataChanged use their previous state to detect changes.
1254 base::string16 keyword
;
1255 bool is_keyword_hint
;
1256 TemplateURLService
* service
= client_
->GetTemplateURLService();
1257 match
.GetKeywordUIState(service
, &keyword
, &is_keyword_hint
);
1259 popup_model()->OnResultChanged();
1260 // OnPopupDataChanged() resets OmniboxController's |current_match_| early
1261 // on. Therefore, copy match.inline_autocompletion to a temp to preserve
1262 // its value across the entire call.
1263 const base::string16
inline_autocompletion(match
.inline_autocompletion
);
1264 OnPopupDataChanged(inline_autocompletion
, NULL
, keyword
, is_keyword_hint
);
1268 const char OmniboxEditModel::kCutOrCopyAllTextHistogram
[] =
1269 "Omnibox.CutOrCopyAllText";
1271 bool OmniboxEditModel::query_in_progress() const {
1272 return !autocomplete_controller()->done();
1275 void OmniboxEditModel::InternalSetUserText(const base::string16
& text
) {
1277 just_deleted_text_
= false;
1278 inline_autocomplete_text_
.clear();
1279 view_
->OnInlineAutocompleteTextCleared();
1282 void OmniboxEditModel::ClearPopupKeywordMode() const {
1283 omnibox_controller_
->ClearPopupKeywordMode();
1286 base::string16
OmniboxEditModel::DisplayTextFromUserText(
1287 const base::string16
& text
) const {
1288 return is_keyword_selected() ?
1289 KeywordProvider::SplitReplacementStringFromInput(text
, false) : text
;
1292 base::string16
OmniboxEditModel::UserTextFromDisplayText(
1293 const base::string16
& text
) const {
1294 return is_keyword_selected() ? (keyword_
+ base::char16(' ') + text
) : text
;
1297 void OmniboxEditModel::GetInfoForCurrentText(AutocompleteMatch
* match
,
1298 GURL
* alternate_nav_url
) const {
1299 DCHECK(match
!= NULL
);
1301 if (controller_
->GetToolbarModel()->WouldPerformSearchTermReplacement(
1303 // Any time the user hits enter on the unchanged omnibox, we should reload.
1304 // When we're not extracting search terms, AcceptInput() will take care of
1305 // this (see code referring to PAGE_TRANSITION_RELOAD there), but when we're
1306 // extracting search terms, the conditionals there won't fire, so we
1307 // explicitly set up a match that will reload here.
1309 // It's important that we fetch the current visible URL to reload instead of
1310 // just getting a "search what you typed" URL from
1311 // SearchProvider::CreateSearchSuggestion(), since the user may be in a
1312 // non-default search mode such as image search.
1313 match
->type
= AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED
;
1314 match
->provider
= autocomplete_controller()->search_provider();
1315 match
->destination_url
= client_
->GetURL();
1316 match
->transition
= ui::PAGE_TRANSITION_RELOAD
;
1317 } else if (query_in_progress() ||
1318 (popup_model() && popup_model()->IsOpen())) {
1319 if (query_in_progress()) {
1320 // It's technically possible for |result| to be empty if no provider
1321 // returns a synchronous result but the query has not completed
1322 // synchronously; pratically, however, that should never actually happen.
1323 if (result().empty())
1325 // The user cannot have manually selected a match, or the query would have
1326 // stopped. So the default match must be the desired selection.
1327 *match
= *result().default_match();
1329 // If there are no results, the popup should be closed, so we shouldn't
1330 // have gotten here.
1331 CHECK(!result().empty());
1332 CHECK(popup_model()->selected_line() < result().size());
1333 const AutocompleteMatch
& selected_match
=
1334 result().match_at(popup_model()->selected_line());
1336 (popup_model()->selected_line_state() == OmniboxPopupModel::KEYWORD
) ?
1337 *selected_match
.associated_keyword
: selected_match
;
1339 if (alternate_nav_url
&&
1340 (!popup_model() || popup_model()->manually_selected_match().empty()))
1341 *alternate_nav_url
= result().alternate_nav_url();
1343 client_
->GetAutocompleteClassifier()->Classify(
1344 UserTextFromDisplayText(view_
->GetText()), is_keyword_selected(), true,
1345 ClassifyPage(), match
, alternate_nav_url
);
1349 void OmniboxEditModel::RevertTemporaryText(bool revert_popup
) {
1350 // The user typed something, then selected a different item. Restore the
1351 // text they typed and change back to the default item.
1352 // NOTE: This purposefully does not reset paste_state_.
1353 just_deleted_text_
= false;
1354 has_temporary_text_
= false;
1356 if (revert_popup
&& popup_model())
1357 popup_model()->ResetToDefaultMatch();
1358 view_
->OnRevertTemporaryText();
1361 bool OmniboxEditModel::MaybeAcceptKeywordBySpace(
1362 const base::string16
& new_text
) {
1363 size_t keyword_length
= new_text
.length() - 1;
1364 return (paste_state_
== NONE
) && is_keyword_hint_
&&
1365 (keyword_
.length() == keyword_length
) &&
1366 IsSpaceCharForAcceptingKeyword(new_text
[keyword_length
]) &&
1367 !new_text
.compare(0, keyword_length
, keyword_
, 0, keyword_length
) &&
1368 AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_SPACE_AT_END
);
1371 bool OmniboxEditModel::CreatedKeywordSearchByInsertingSpaceInMiddle(
1372 const base::string16
& old_text
,
1373 const base::string16
& new_text
,
1374 size_t caret_position
) const {
1375 DCHECK_GE(new_text
.length(), caret_position
);
1377 // Check simple conditions first.
1378 if ((paste_state_
!= NONE
) || (caret_position
< 2) ||
1379 (old_text
.length() < caret_position
) ||
1380 (new_text
.length() == caret_position
))
1382 size_t space_position
= caret_position
- 1;
1383 if (!IsSpaceCharForAcceptingKeyword(new_text
[space_position
]) ||
1384 base::IsUnicodeWhitespace(new_text
[space_position
- 1]) ||
1385 new_text
.compare(0, space_position
, old_text
, 0, space_position
) ||
1386 !new_text
.compare(space_position
, new_text
.length() - space_position
,
1387 old_text
, space_position
,
1388 old_text
.length() - space_position
)) {
1392 // Then check if the text before the inserted space matches a keyword.
1393 base::string16 keyword
;
1394 base::TrimWhitespace(new_text
.substr(0, space_position
), base::TRIM_LEADING
,
1396 return !keyword
.empty() && !autocomplete_controller()->keyword_provider()->
1397 GetKeywordForText(keyword
).empty();
1401 bool OmniboxEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c
) {
1403 case 0x0020: // Space
1404 case 0x3000: // Ideographic Space
1411 OmniboxEventProto::PageClassification
OmniboxEditModel::ClassifyPage() const {
1412 if (!client_
->CurrentPageExists())
1413 return OmniboxEventProto::OTHER
;
1414 if (client_
->IsInstantNTP()) {
1415 // Note that we treat OMNIBOX as the source if focus_source_ is INVALID,
1416 // i.e., if input isn't actually in progress.
1417 return (focus_source_
== FAKEBOX
) ?
1418 OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS
:
1419 OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS
;
1421 const GURL
& gurl
= client_
->GetURL();
1422 if (!gurl
.is_valid())
1423 return OmniboxEventProto::INVALID_SPEC
;
1424 const std::string
& url
= gurl
.spec();
1425 if (client_
->IsNewTabPage(url
))
1426 return OmniboxEventProto::NTP
;
1427 if (url
== url::kAboutBlankURL
)
1428 return OmniboxEventProto::BLANK
;
1429 if (client_
->IsHomePage(url
))
1430 return OmniboxEventProto::HOME_PAGE
;
1431 if (controller_
->GetToolbarModel()->WouldPerformSearchTermReplacement(true))
1432 return OmniboxEventProto::SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT
;
1433 if (client_
->IsSearchResultsPage())
1434 return OmniboxEventProto::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT
;
1435 return OmniboxEventProto::OTHER
;
1438 void OmniboxEditModel::ClassifyStringForPasteAndGo(
1439 const base::string16
& text
,
1440 AutocompleteMatch
* match
,
1441 GURL
* alternate_nav_url
) const {
1443 client_
->GetAutocompleteClassifier()->Classify(
1444 text
, false, false, ClassifyPage(), match
, alternate_nav_url
);
1447 void OmniboxEditModel::SetFocusState(OmniboxFocusState state
,
1448 OmniboxFocusChangeReason reason
) {
1449 if (state
== focus_state_
)
1452 // Update state and notify view if the omnibox has focus and the caret
1453 // visibility changed.
1454 const bool was_caret_visible
= is_caret_visible();
1455 focus_state_
= state
;
1456 if (focus_state_
!= OMNIBOX_FOCUS_NONE
&&
1457 is_caret_visible() != was_caret_visible
)
1458 view_
->ApplyCaretVisibility();
1460 client_
->OnFocusChanged(focus_state_
, reason
);