1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
9 #include "base/format_macros.h"
10 #include "base/metrics/histogram.h"
11 #include "base/string_util.h"
12 #include "base/stringprintf.h"
13 #include "base/utf_string_conversions.h"
14 #include "chrome/app/chrome_command_ids.h"
15 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
16 #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
17 #include "chrome/browser/autocomplete/autocomplete_input.h"
18 #include "chrome/browser/autocomplete/autocomplete_log.h"
19 #include "chrome/browser/autocomplete/extension_app_provider.h"
20 #include "chrome/browser/autocomplete/keyword_provider.h"
21 #include "chrome/browser/autocomplete/search_provider.h"
22 #include "chrome/browser/bookmarks/bookmark_utils.h"
23 #include "chrome/browser/command_updater.h"
24 #include "chrome/browser/extensions/api/omnibox/omnibox_api.h"
25 #include "chrome/browser/google/google_url_tracker.h"
26 #include "chrome/browser/instant/instant_controller.h"
27 #include "chrome/browser/net/predictor.h"
28 #include "chrome/browser/net/url_fixer_upper.h"
29 #include "chrome/browser/predictors/autocomplete_action_predictor.h"
30 #include "chrome/browser/predictors/autocomplete_action_predictor_factory.h"
31 #include "chrome/browser/prefs/pref_service.h"
32 #include "chrome/browser/prerender/prerender_field_trial.h"
33 #include "chrome/browser/prerender/prerender_manager.h"
34 #include "chrome/browser/prerender/prerender_manager_factory.h"
35 #include "chrome/browser/profiles/profile.h"
36 #include "chrome/browser/search_engines/template_url.h"
37 #include "chrome/browser/search_engines/template_url_prepopulate_data.h"
38 #include "chrome/browser/search_engines/template_url_service.h"
39 #include "chrome/browser/search_engines/template_url_service_factory.h"
40 #include "chrome/browser/sessions/restore_tab_helper.h"
41 #include "chrome/browser/ui/browser_list.h"
42 #include "chrome/browser/ui/omnibox/omnibox_edit_controller.h"
43 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
44 #include "chrome/browser/ui/omnibox/omnibox_popup_view.h"
45 #include "chrome/browser/ui/omnibox/omnibox_view.h"
46 #include "chrome/browser/ui/search/search_tab_helper.h"
47 #include "chrome/browser/ui/tab_contents/tab_contents.h"
48 #include "chrome/common/chrome_notification_types.h"
49 #include "chrome/common/chrome_switches.h"
50 #include "chrome/common/pref_names.h"
51 #include "chrome/common/url_constants.h"
52 #include "content/public/browser/notification_service.h"
53 #include "content/public/browser/render_view_host.h"
54 #include "content/public/browser/user_metrics.h"
55 #include "content/public/browser/web_contents.h"
56 #include "content/public/browser/web_contents_view.h"
57 #include "googleurl/src/url_util.h"
58 #include "third_party/skia/include/core/SkBitmap.h"
60 using content::UserMetricsAction
;
61 using predictors::AutocompleteActionPredictor
;
62 using predictors::AutocompleteActionPredictorFactory
;
64 ///////////////////////////////////////////////////////////////////////////////
65 // OmniboxEditModel::State
67 OmniboxEditModel::State::State(bool user_input_in_progress
,
68 const string16
& user_text
,
69 const string16
& keyword
,
71 : user_input_in_progress(user_input_in_progress
),
74 is_keyword_hint(is_keyword_hint
) {
77 OmniboxEditModel::State::~State() {
80 ///////////////////////////////////////////////////////////////////////////////
83 OmniboxEditModel::OmniboxEditModel(OmniboxView
* view
,
84 OmniboxEditController
* controller
,
86 : ALLOW_THIS_IN_INITIALIZER_LIST(
87 autocomplete_controller_(new AutocompleteController(profile
, this))),
90 controller_(controller
),
92 user_input_in_progress_(false),
93 just_deleted_text_(false),
94 has_temporary_text_(false),
96 control_key_state_(UP
),
97 is_keyword_hint_(false),
100 allow_exact_keyword_match_(false) {
103 OmniboxEditModel::~OmniboxEditModel() {
106 const OmniboxEditModel::State
OmniboxEditModel::GetStateForTabSwitch() {
107 // Like typing, switching tabs "accepts" the temporary text as the user
108 // text, because it makes little sense to have temporary text when the
110 if (user_input_in_progress_
) {
111 // Weird edge case to match other browsers: if the edit is empty, revert to
112 // the permanent text (so the user can get it back easily) but select it (so
113 // on switching back, typing will "just work").
114 const string16
user_text(UserTextFromDisplayText(view_
->GetText()));
115 if (user_text
.empty()) {
117 view_
->SelectAll(true);
119 InternalSetUserText(user_text
);
123 return State(user_input_in_progress_
, user_text_
, keyword_
, is_keyword_hint_
);
126 void OmniboxEditModel::RestoreState(const State
& state
) {
127 // Restore any user editing.
128 if (state
.user_input_in_progress
) {
129 // NOTE: Be sure and set keyword-related state BEFORE invoking
130 // DisplayTextFromUserText(), as its result depends upon this state.
131 keyword_
= state
.keyword
;
132 is_keyword_hint_
= state
.is_keyword_hint
;
133 view_
->SetUserText(state
.user_text
,
134 DisplayTextFromUserText(state
.user_text
), false);
138 AutocompleteMatch
OmniboxEditModel::CurrentMatch() {
139 AutocompleteMatch match
;
140 GetInfoForCurrentText(&match
, NULL
);
144 bool OmniboxEditModel::UpdatePermanentText(const string16
& new_permanent_text
) {
145 // When there's a new URL, and the user is not editing anything or the edit
146 // doesn't have focus, we want to revert the edit to show the new URL. (The
147 // common case where the edit doesn't have focus is when the user has started
148 // an edit and then abandoned it and clicked a link on the page.)
149 const bool visibly_changed_permanent_text
=
150 (permanent_text_
!= new_permanent_text
) &&
151 (!user_input_in_progress_
|| !has_focus_
);
153 permanent_text_
= new_permanent_text
;
154 return visibly_changed_permanent_text
;
157 GURL
OmniboxEditModel::PermanentURL() {
158 return URLFixerUpper::FixupURL(UTF16ToUTF8(permanent_text_
), std::string());
161 void OmniboxEditModel::SetUserText(const string16
& text
) {
162 SetInputInProgress(true);
163 InternalSetUserText(text
);
165 has_temporary_text_
= false;
168 void OmniboxEditModel::FinalizeInstantQuery(const string16
& input_text
,
169 const string16
& suggest_text
,
170 bool skip_inline_autocomplete
) {
171 if (skip_inline_autocomplete
) {
172 const string16 final_text
= input_text
+ suggest_text
;
173 view_
->OnBeforePossibleChange();
174 view_
->SetWindowTextAndCaretPos(final_text
, final_text
.length(), false,
176 view_
->OnAfterPossibleChange();
177 } else if (popup_
->IsOpen()) {
178 SearchProvider
* search_provider
=
179 autocomplete_controller_
->search_provider();
180 // There may be no providers during testing; guard against that.
182 search_provider
->FinalizeInstantQuery(input_text
, suggest_text
);
186 void OmniboxEditModel::SetSuggestedText(const string16
& text
,
187 InstantCompleteBehavior behavior
) {
188 if (behavior
== INSTANT_COMPLETE_NOW
) {
190 FinalizeInstantQuery(view_
->GetText(), text
, false);
192 view_
->SetInstantSuggestion(text
, false);
194 DCHECK((behavior
== INSTANT_COMPLETE_DELAYED
) ||
195 (behavior
== INSTANT_COMPLETE_NEVER
));
196 view_
->SetInstantSuggestion(text
, behavior
== INSTANT_COMPLETE_DELAYED
);
200 bool OmniboxEditModel::CommitSuggestedText(bool skip_inline_autocomplete
) {
201 if (!controller_
->GetInstant())
204 const string16 suggestion
= view_
->GetInstantSuggestion();
205 if (suggestion
.empty())
208 FinalizeInstantQuery(view_
->GetText(), suggestion
, skip_inline_autocomplete
);
212 bool OmniboxEditModel::AcceptCurrentInstantPreview() {
213 InstantController
* instant
= controller_
->GetInstant();
214 return instant
&& instant
->IsCurrent() &&
215 instant
->CommitCurrentPreview(INSTANT_COMMIT_PRESSED_ENTER
);
218 void OmniboxEditModel::OnChanged() {
219 // Don't call CurrentMatch() when there's no editing, as in this case we'll
220 // never actually use it. This avoids running the autocomplete providers (and
221 // any systems they then spin up) during startup.
222 const AutocompleteMatch
& current_match
= user_input_in_progress_
?
223 CurrentMatch() : AutocompleteMatch();
225 AutocompleteActionPredictor::Action recommended_action
=
226 AutocompleteActionPredictor::ACTION_NONE
;
227 AutocompleteActionPredictor
* action_predictor
=
228 user_input_in_progress_
?
229 AutocompleteActionPredictorFactory::GetForProfile(profile_
) : NULL
;
230 if (action_predictor
) {
231 action_predictor
->RegisterTransitionalMatches(user_text_
, result());
232 // Confer with the AutocompleteActionPredictor to determine what action, if
233 // any, we should take. Get the recommended action here even if we don't
234 // need it so we can get stats for anyone who is opted in to UMA, but only
235 // get it if the user has actually typed something to avoid constructing it
236 // before it's needed. Note: This event is triggered as part of startup when
237 // the initial tab transitions to the start page.
239 action_predictor
->RecommendAction(user_text_
, current_match
);
242 UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.Action",
244 AutocompleteActionPredictor::LAST_PREDICT_ACTION
);
246 string16 suggested_text
;
247 InstantCompleteBehavior complete_behavior
= INSTANT_COMPLETE_NOW
;
249 if (DoInstant(current_match
, &suggested_text
, &complete_behavior
)) {
250 SetSuggestedText(suggested_text
, complete_behavior
);
252 switch (recommended_action
) {
253 case AutocompleteActionPredictor::ACTION_PRERENDER
:
254 DoPrerender(current_match
);
256 case AutocompleteActionPredictor::ACTION_PRECONNECT
:
257 DoPreconnect(current_match
);
259 case AutocompleteActionPredictor::ACTION_NONE
:
262 NOTREACHED() << "Unexpected recommended action: " << recommended_action
;
266 // Hide any suggestions we might be showing.
267 view_
->SetInstantSuggestion(string16(), false);
269 // No need to wait any longer for instant.
270 FinalizeInstantQuery(string16(), string16(), false);
273 controller_
->OnChanged();
276 void OmniboxEditModel::GetDataForURLExport(GURL
* url
,
279 AutocompleteMatch match
;
280 GetInfoForCurrentText(&match
, NULL
);
281 *url
= match
.destination_url
;
282 if (*url
== URLFixerUpper::FixupURL(UTF16ToUTF8(permanent_text_
),
284 *title
= controller_
->GetTitle();
285 *favicon
= controller_
->GetFavicon();
289 bool OmniboxEditModel::UseVerbatimInstant() {
290 #if defined(OS_MACOSX)
291 // TODO(suzhe): Fix Mac port to display Instant suggest in a separated NSView,
292 // so that we can display instant suggest along with composition text.
293 const AutocompleteInput
& input
= autocomplete_controller_
->input();
294 if (input
.prevent_inline_autocomplete())
298 // The value of input.prevent_inline_autocomplete() is determined by
299 // following conditions:
300 // 1. If the caret is at the end of the text (checked below).
301 // 2. If it's in IME composition mode.
302 // As we use a separated widget for displaying the instant suggest, it won't
303 // interfere with IME composition, so we don't need to care about the value of
304 // input.prevent_inline_autocomplete() here.
305 if (view_
->DeleteAtEndPressed() || (popup_
->selected_line() != 0) ||
310 view_
->GetSelectionBounds(&start
, &end
);
311 return (start
!= end
) || (start
!= view_
->GetText().length());
314 string16
OmniboxEditModel::GetDesiredTLD() const {
315 // Tricky corner case: The user has typed "foo" and currently sees an inline
316 // autocomplete suggestion of "foo.net". He now presses ctrl-a (e.g. to
317 // select all, on Windows). If we treat the ctrl press as potentially for the
318 // sake of ctrl-enter, then we risk "www.foo.com" being promoted as the best
319 // match. This would make the autocompleted text disappear, leaving our user
320 // feeling very confused when the wrong text gets highlighted.
322 // Thus, we only treat the user as pressing ctrl-enter when the user presses
323 // ctrl without any fragile state built up in the omnibox:
324 // * the contents of the omnibox have not changed since the keypress,
325 // * there is no autocompleted text visible, and
326 // * the user is not typing a keyword query.
327 return (control_key_state_
== DOWN_WITHOUT_CHANGE
&&
328 inline_autocomplete_text_
.empty() && !KeywordIsSelected())?
329 ASCIIToUTF16("com") : string16();
332 bool OmniboxEditModel::CurrentTextIsURL() const {
333 // If !user_input_in_progress_, the permanent text is showing, which should
334 // always be a URL, so no further checking is needed. By avoiding checking in
335 // this case, we avoid calling into the autocomplete providers, and thus
336 // initializing the history system, as long as possible, which speeds startup.
337 if (!user_input_in_progress_
)
340 AutocompleteMatch match
;
341 GetInfoForCurrentText(&match
, NULL
);
342 return match
.transition
== content::PAGE_TRANSITION_TYPED
;
345 AutocompleteMatch::Type
OmniboxEditModel::CurrentTextType() const {
346 AutocompleteMatch match
;
347 GetInfoForCurrentText(&match
, NULL
);
351 void OmniboxEditModel::AdjustTextForCopy(int sel_min
,
352 bool is_all_selected
,
361 if (!user_input_in_progress_
&& is_all_selected
) {
362 // The user selected all the text and has not edited it. Use the url as the
363 // text so that if the scheme was stripped it's added back, and the url
364 // is unescaped (we escape parts of the url for display).
365 *url
= PermanentURL();
366 *text
= UTF8ToUTF16(url
->spec());
371 // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now
372 // the user is probably holding down control to cause the copy, which will
373 // screw up our calculation of the desired_tld.
374 AutocompleteMatch match
;
375 AutocompleteClassifierFactory::GetForProfile(profile_
)->Classify(*text
,
376 string16(), KeywordIsSelected(), true, &match
, NULL
);
377 if (match
.transition
!= content::PAGE_TRANSITION_TYPED
)
379 *url
= match
.destination_url
;
381 // Prefix the text with 'http://' if the text doesn't start with 'http://',
382 // the text parses as a url with a scheme of http, the user selected the
383 // entire host, and the user hasn't edited the host or manually removed the
385 GURL
perm_url(PermanentURL());
386 if (perm_url
.SchemeIs(chrome::kHttpScheme
) &&
387 url
->SchemeIs(chrome::kHttpScheme
) && perm_url
.host() == url
->host()) {
389 string16 http
= ASCIIToUTF16(chrome::kHttpScheme
) +
390 ASCIIToUTF16(content::kStandardSchemeSeparator
);
391 if (text
->compare(0, http
.length(), http
) != 0)
392 *text
= http
+ *text
;
396 void OmniboxEditModel::SetInputInProgress(bool in_progress
) {
397 if (user_input_in_progress_
== in_progress
)
400 user_input_in_progress_
= in_progress
;
401 if (user_input_in_progress_
)
402 time_user_first_modified_omnibox_
= base::TimeTicks::Now();
403 controller_
->OnInputInProgress(in_progress
);
405 NotifySearchTabHelper();
408 void OmniboxEditModel::Revert() {
409 SetInputInProgress(false);
411 InternalSetUserText(string16());
413 is_keyword_hint_
= false;
414 has_temporary_text_
= false;
415 view_
->SetWindowTextAndCaretPos(permanent_text_
,
416 has_focus_
? permanent_text_
.length() : 0,
418 AutocompleteActionPredictor
* action_predictor
=
419 AutocompleteActionPredictorFactory::GetForProfile(profile_
);
420 if (action_predictor
)
421 action_predictor
->ClearTransitionalMatches();
424 void OmniboxEditModel::StartAutocomplete(
425 bool has_selected_text
,
426 bool prevent_inline_autocomplete
) const {
427 ClearPopupKeywordMode();
429 bool keyword_is_selected
= KeywordIsSelected();
430 popup_
->SetHoveredLine(OmniboxPopupModel::kNoMatch
);
431 // We don't explicitly clear OmniboxPopupModel::manually_selected_match, as
432 // Start ends up invoking OmniboxPopupModel::OnResultChanged which clears it.
433 autocomplete_controller_
->Start(
434 user_text_
, GetDesiredTLD(),
435 prevent_inline_autocomplete
|| just_deleted_text_
||
436 (has_selected_text
&& inline_autocomplete_text_
.empty()) ||
437 (paste_state_
!= NONE
), keyword_is_selected
,
438 keyword_is_selected
|| allow_exact_keyword_match_
,
439 AutocompleteInput::ALL_MATCHES
);
442 void OmniboxEditModel::StopAutocomplete() {
443 if (popup_
->IsOpen() && !in_revert_
) {
444 InstantController
* instant
= controller_
->GetInstant();
445 if (instant
&& !instant
->commit_on_pointer_release())
449 autocomplete_controller_
->Stop(true);
452 bool OmniboxEditModel::CanPasteAndGo(const string16
& text
) const {
453 if (!view_
->command_updater()->IsCommandEnabled(IDC_OPEN_CURRENT_URL
))
456 AutocompleteMatch match
;
457 ClassifyStringForPasteAndGo(text
, &match
, NULL
);
458 return match
.destination_url
.is_valid();
461 void OmniboxEditModel::PasteAndGo(const string16
& text
) {
462 DCHECK(CanPasteAndGo(text
));
464 AutocompleteMatch match
;
465 GURL alternate_nav_url
;
466 ClassifyStringForPasteAndGo(text
, &match
, &alternate_nav_url
);
467 view_
->OpenMatch(match
, CURRENT_TAB
, alternate_nav_url
,
468 OmniboxPopupModel::kNoMatch
);
471 bool OmniboxEditModel::IsPasteAndSearch(const string16
& text
) const {
472 AutocompleteMatch match
;
473 ClassifyStringForPasteAndGo(text
, &match
, NULL
);
474 return (match
.transition
!= content::PAGE_TRANSITION_TYPED
);
477 void OmniboxEditModel::AcceptInput(WindowOpenDisposition disposition
,
479 // Get the URL and transition type for the selected entry.
480 AutocompleteMatch match
;
481 GURL alternate_nav_url
;
482 GetInfoForCurrentText(&match
, &alternate_nav_url
);
484 if (!match
.destination_url
.is_valid())
487 if ((match
.transition
== content::PAGE_TRANSITION_TYPED
) &&
488 (match
.destination_url
==
489 URLFixerUpper::FixupURL(UTF16ToUTF8(permanent_text_
), std::string()))) {
490 // When the user hit enter on the existing permanent URL, treat it like a
491 // reload for scoring purposes. We could detect this by just checking
492 // user_input_in_progress_, but it seems better to treat "edits" that end
493 // up leaving the URL unchanged (e.g. deleting the last character and then
494 // retyping it) as reloads too. We exclude non-TYPED transitions because if
495 // the transition is GENERATED, the user input something that looked
496 // different from the current URL, even if it wound up at the same place
497 // (e.g. manually retyping the same search query), and it seems wrong to
498 // treat this as a reload.
499 match
.transition
= content::PAGE_TRANSITION_RELOAD
;
500 } else if (for_drop
|| ((paste_state_
!= NONE
) &&
501 match
.is_history_what_you_typed_match
)) {
502 // When the user pasted in a URL and hit enter, score it like a link click
503 // rather than a normal typed URL, so it doesn't get inline autocompleted
504 // as aggressively later.
505 match
.transition
= content::PAGE_TRANSITION_LINK
;
508 const TemplateURL
* template_url
= match
.GetTemplateURL(profile_
);
509 if (template_url
&& template_url
->url_ref().HasGoogleBaseURLs())
510 GoogleURLTracker::GoogleURLSearchCommitted(profile_
);
512 view_
->OpenMatch(match
, disposition
, alternate_nav_url
,
513 OmniboxPopupModel::kNoMatch
);
516 void OmniboxEditModel::OpenMatch(const AutocompleteMatch
& match
,
517 WindowOpenDisposition disposition
,
518 const GURL
& alternate_nav_url
,
520 // We only care about cases where there is a selection (i.e. the popup is
522 if (popup_
->IsOpen()) {
524 autocomplete_controller_
->input().text(),
526 autocomplete_controller_
->input().type(),
527 popup_
->selected_line(),
528 -1, // don't yet know tab ID; set later if appropriate
529 ClassifyPage(controller_
->GetTabContents()->
530 web_contents()->GetURL()),
531 base::TimeTicks::Now() - time_user_first_modified_omnibox_
,
532 0, // inline autocomplete length; possibly set later
534 DCHECK(user_input_in_progress_
) << "We didn't get here through the "
535 "expected series of calls. time_user_first_modified_omnibox_ is "
536 "not set correctly and other things may be wrong.";
537 if (index
!= OmniboxPopupModel::kNoMatch
)
538 log
.selected_index
= index
;
539 else if (!has_temporary_text_
)
540 log
.inline_autocompleted_length
= inline_autocomplete_text_
.length();
541 if (disposition
== CURRENT_TAB
) {
542 // If we know the destination is being opened in the current tab,
543 // we can easily get the tab ID. (If it's being opened in a new
544 // tab, we don't know the tab ID yet.)
545 log
.tab_id
= controller_
->GetTabContents()->
546 restore_tab_helper()->session_id().id();
548 autocomplete_controller_
->AddProvidersInfo(&log
.providers_info
);
549 content::NotificationService::current()->Notify(
550 chrome::NOTIFICATION_OMNIBOX_OPENED_URL
,
551 content::Source
<Profile
>(profile_
),
552 content::Details
<AutocompleteLog
>(&log
));
553 HISTOGRAM_ENUMERATION("Omnibox.EventCount", 1, 2);
556 TemplateURL
* template_url
= match
.GetTemplateURL(profile_
);
558 if (match
.transition
== content::PAGE_TRANSITION_KEYWORD
) {
559 // The user is using a non-substituting keyword or is explicitly in
562 // Special case for extension keywords. Don't increment usage count for
564 if (template_url
->IsExtensionKeyword()) {
565 AutocompleteMatch current_match
;
566 GetInfoForCurrentText(¤t_match
, NULL
);
568 const AutocompleteMatch
& match
=
569 (index
== OmniboxPopupModel::kNoMatch
) ?
570 current_match
: result().match_at(index
);
572 // Strip the keyword + leading space off the input.
573 size_t prefix_length
= match
.keyword
.length() + 1;
574 extensions::ExtensionOmniboxEventRouter::OnInputEntered(
575 controller_
->GetTabContents(),
576 template_url
->GetExtensionId(),
577 UTF16ToUTF8(match
.fill_into_edit
.substr(prefix_length
)));
582 content::RecordAction(UserMetricsAction("AcceptedKeyword"));
583 TemplateURLServiceFactory::GetForProfile(profile_
)->IncrementUsageCount(
586 DCHECK_EQ(content::PAGE_TRANSITION_GENERATED
, match
.transition
);
587 // NOTE: We purposefully don't increment the usage count of the default
588 // search engine here like we do for explicit keywords above; see comments
589 // in template_url.h.
592 // NOTE: Non-prepopulated engines will all have ID 0, which is fine as
593 // the prepopulate IDs start at 1. Distribution-specific engines will
594 // all have IDs above the maximum, and will be automatically lumped
595 // together in an "overflow" bucket in the histogram.
596 UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngine",
597 template_url
->prepopulate_id(),
598 TemplateURLPrepopulateData::kMaxPrepopulatedEngineID
);
601 if (disposition
!= NEW_BACKGROUND_TAB
) {
603 view_
->RevertAll(); // Revert the box to its unedited state
606 if (match
.type
== AutocompleteMatch::EXTENSION_APP
) {
607 ExtensionAppProvider::LaunchAppFromOmnibox(match
, profile_
, disposition
);
609 GURL
destination_url(match
.destination_url
);
610 // Append the query formulation time (time from when the user first typed a
611 // character into the omnibox to when the user selected a query) to the AQS
612 // parameter if other AQS parameters were already populated.
613 if (template_url
&& match
.search_terms_args
.get() &&
614 !match
.search_terms_args
->assisted_query_stats
.empty()) {
615 base::TimeDelta query_formulation_time
=
616 base::TimeTicks::Now() - time_user_first_modified_omnibox_
;
617 TemplateURLRef::SearchTermsArgs
search_terms_args(
618 *match
.search_terms_args
);
619 search_terms_args
.assisted_query_stats
+=
620 base::StringPrintf(".%" PRId64
,
621 query_formulation_time
.InMilliseconds());
622 destination_url
= GURL(template_url
->url_ref().
623 ReplaceSearchTerms(search_terms_args
));
625 controller_
->OnAutocompleteAccept(destination_url
, disposition
,
626 match
.transition
, alternate_nav_url
);
630 bookmark_utils::RecordBookmarkLaunch(bookmark_utils::LAUNCH_OMNIBOX
);
632 InstantController
* instant
= controller_
->GetInstant();
633 if (instant
&& !popup_
->IsOpen())
638 bool OmniboxEditModel::AcceptKeyword() {
639 DCHECK(is_keyword_hint_
&& !keyword_
.empty());
641 autocomplete_controller_
->Stop(false);
642 is_keyword_hint_
= false;
644 if (popup_
->IsOpen())
645 popup_
->SetSelectedLineState(OmniboxPopupModel::KEYWORD
);
647 StartAutocomplete(false, true);
649 // Ensure the current selection is saved before showing keyword mode
650 // so that moving to another line and then reverting the text will restore
651 // the current state properly.
652 bool save_original_selection
= !has_temporary_text_
;
653 has_temporary_text_
= true;
654 view_
->OnTemporaryTextMaybeChanged(
655 DisplayTextFromUserText(CurrentMatch().fill_into_edit
),
656 save_original_selection
);
658 content::RecordAction(UserMetricsAction("AcceptedKeywordHint"));
662 void OmniboxEditModel::ClearKeyword(const string16
& visible_text
) {
663 autocomplete_controller_
->Stop(false);
664 ClearPopupKeywordMode();
666 const string16
window_text(keyword_
+ visible_text
);
668 // Only reset the result if the edit text has changed since the
669 // keyword was accepted, or if the popup is closed.
670 if (just_deleted_text_
|| !visible_text
.empty() || !popup_
->IsOpen()) {
671 view_
->OnBeforePossibleChange();
672 view_
->SetWindowTextAndCaretPos(window_text
.c_str(), keyword_
.length(),
675 is_keyword_hint_
= false;
676 view_
->OnAfterPossibleChange();
677 just_deleted_text_
= true; // OnAfterPossibleChange() fails to clear this
678 // since the edit contents have actually grown
681 is_keyword_hint_
= true;
682 view_
->SetWindowTextAndCaretPos(window_text
.c_str(), keyword_
.length(),
687 const AutocompleteResult
& OmniboxEditModel::result() const {
688 return autocomplete_controller_
->result();
691 void OmniboxEditModel::OnSetFocus(bool control_down
) {
693 control_key_state_
= control_down
? DOWN_WITHOUT_CHANGE
: UP
;
695 InstantController
* instant
= controller_
->GetInstant();
697 instant
->OnAutocompleteGotFocus();
699 NotifySearchTabHelper();
702 void OmniboxEditModel::OnWillKillFocus(gfx::NativeView view_gaining_focus
) {
703 SetSuggestedText(string16(), INSTANT_COMPLETE_NOW
);
705 if (InstantController
* instant
= controller_
->GetInstant())
706 instant
->OnAutocompleteLostFocus(view_gaining_focus
);
708 NotifySearchTabHelper();
711 void OmniboxEditModel::OnKillFocus() {
713 control_key_state_
= UP
;
717 bool OmniboxEditModel::OnEscapeKeyPressed() {
718 if (has_temporary_text_
) {
719 AutocompleteMatch match
;
720 InfoForCurrentSelection(&match
, NULL
);
721 if (match
.destination_url
!= original_url_
) {
722 RevertTemporaryText(true);
727 // We do not clear the pending entry from the omnibox when a load is first
728 // stopped. If the user presses Escape while stopped, we clear it.
729 content::WebContents
* contents
=
730 controller_
->GetTabContents()->web_contents();
731 if (!contents
->IsLoading()) {
732 contents
->GetController().DiscardNonCommittedEntries();
736 // If the user wasn't editing, but merely had focus in the edit, allow <esc>
737 // to be processed as an accelerator, so it can still be used to stop a load.
738 // When the permanent text isn't all selected we still fall through to the
739 // SelectAll() call below so users can arrow around in the text and then hit
740 // <esc> to quickly replace all the text; this matches IE.
741 if (!user_input_in_progress_
&& view_
->IsSelectAll())
745 view_
->SelectAll(true);
749 void OmniboxEditModel::OnControlKeyChanged(bool pressed
) {
750 // Don't change anything unless the key state is actually toggling.
751 if (pressed
== (control_key_state_
== UP
)) {
752 ControlKeyState old_state
= control_key_state_
;
753 control_key_state_
= pressed
? DOWN_WITHOUT_CHANGE
: UP
;
754 if ((control_key_state_
== DOWN_WITHOUT_CHANGE
) && has_temporary_text_
) {
755 // Arrowing down and then hitting control accepts the temporary text as
757 InternalSetUserText(UserTextFromDisplayText(view_
->GetText()));
758 has_temporary_text_
= false;
759 if (KeywordIsSelected())
762 if ((old_state
!= DOWN_WITH_CHANGE
) && popup_
->IsOpen()) {
763 // Autocomplete history provider results may change, so refresh the
764 // popup. This will force user_input_in_progress_ to true, but if the
765 // popup is open, that should have already been the case.
766 view_
->UpdatePopup();
771 void OmniboxEditModel::OnUpOrDownKeyPressed(int count
) {
772 // NOTE: This purposefully don't trigger any code that resets paste_state_.
774 if (!popup_
->IsOpen()) {
775 if (!query_in_progress()) {
776 // The popup is neither open nor working on a query already. So, start an
777 // autocomplete query for the current text. This also sets
778 // user_input_in_progress_ to true, which we want: if the user has started
779 // to interact with the popup, changing the permanent_text_ shouldn't
780 // change the displayed text.
781 // Note: This does not force the popup to open immediately.
782 // TODO(pkasting): We should, in fact, force this particular query to open
783 // the popup immediately.
784 if (!user_input_in_progress_
)
785 InternalSetUserText(permanent_text_
);
786 view_
->UpdatePopup();
788 // TODO(pkasting): The popup is working on a query but is not open. We
789 // should force it to open immediately.
792 // The popup is open, so the user should be able to interact with it
798 void OmniboxEditModel::OnPopupDataChanged(
799 const string16
& text
,
800 GURL
* destination_for_temporary_text_change
,
801 const string16
& keyword
,
802 bool is_keyword_hint
) {
803 // Update keyword/hint-related local state.
804 bool keyword_state_changed
= (keyword_
!= keyword
) ||
805 ((is_keyword_hint_
!= is_keyword_hint
) && !keyword
.empty());
806 if (keyword_state_changed
) {
808 is_keyword_hint_
= is_keyword_hint
;
810 // |is_keyword_hint_| should always be false if |keyword_| is empty.
811 DCHECK(!keyword_
.empty() || !is_keyword_hint_
);
814 // Handle changes to temporary text.
815 if (destination_for_temporary_text_change
!= NULL
) {
816 const bool save_original_selection
= !has_temporary_text_
;
817 if (save_original_selection
) {
818 // Save the original selection and URL so it can be reverted later.
819 has_temporary_text_
= true;
820 original_url_
= *destination_for_temporary_text_change
;
821 inline_autocomplete_text_
.clear();
823 if (control_key_state_
== DOWN_WITHOUT_CHANGE
) {
824 // Arrowing around the popup cancels control-enter.
825 control_key_state_
= DOWN_WITH_CHANGE
;
826 // Now things are a bit screwy: the desired_tld has changed, but if we
827 // update the popup, the new order of entries won't match the old, so the
828 // user's selection gets screwy; and if we don't update the popup, and the
829 // user reverts, then the selected item will be as if control is still
830 // pressed, even though maybe it isn't any more. There is no obvious
831 // right answer here :(
833 view_
->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text
),
834 save_original_selection
);
838 bool call_controller_onchanged
= true;
839 inline_autocomplete_text_
= text
;
840 if (view_
->OnInlineAutocompleteTextMaybeChanged(
841 DisplayTextFromUserText(user_text_
+ inline_autocomplete_text_
),
842 DisplayTextFromUserText(user_text_
).length()))
843 call_controller_onchanged
= false;
845 // If |has_temporary_text_| is true, then we previously had a manual selection
846 // but now don't (or |destination_for_temporary_text_change| would have been
847 // non-NULL). This can happen when deleting the selected item in the popup.
848 // In this case, we've already reverted the popup to the default match, so we
849 // need to revert ourselves as well.
850 if (has_temporary_text_
) {
851 RevertTemporaryText(false);
852 call_controller_onchanged
= false;
855 // We need to invoke OnChanged in case the destination url changed (as could
856 // happen when control is toggled).
857 if (call_controller_onchanged
)
861 bool OmniboxEditModel::OnAfterPossibleChange(const string16
& old_text
,
862 const string16
& new_text
,
863 size_t selection_start
,
864 size_t selection_end
,
865 bool selection_differs
,
867 bool just_deleted_text
,
868 bool allow_keyword_ui_change
) {
869 // Update the paste state as appropriate: if we're just finishing a paste
870 // that replaced all the text, preserve that information; otherwise, if we've
871 // made some other edit, clear paste tracking.
872 if (paste_state_
== PASTING
)
873 paste_state_
= PASTED
;
874 else if (text_differs
)
877 // Modifying the selection counts as accepting the autocompleted text.
878 const bool user_text_changed
=
879 text_differs
|| (selection_differs
&& !inline_autocomplete_text_
.empty());
881 // If something has changed while the control key is down, prevent
882 // "ctrl-enter" until the control key is released. When we do this, we need
883 // to update the popup if it's open, since the desired_tld will have changed.
884 if ((text_differs
|| selection_differs
) &&
885 (control_key_state_
== DOWN_WITHOUT_CHANGE
)) {
886 control_key_state_
= DOWN_WITH_CHANGE
;
887 if (!text_differs
&& !popup_
->IsOpen())
888 return false; // Don't open the popup for no reason.
889 } else if (!user_text_changed
) {
893 // If the user text has not changed, we do not want to change the model's
894 // state associated with the text. Otherwise, we can get surprising behavior
895 // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983
896 if (user_text_changed
) {
897 InternalSetUserText(UserTextFromDisplayText(new_text
));
898 has_temporary_text_
= false;
900 // Track when the user has deleted text so we won't allow inline
902 just_deleted_text_
= just_deleted_text
;
905 const bool no_selection
= selection_start
== selection_end
;
907 // Update the popup for the change, in the process changing to keyword mode
908 // if the user hit space in mid-string after a keyword.
909 // |allow_exact_keyword_match_| will be used by StartAutocomplete() method,
910 // which will be called by |view_->UpdatePopup()|; so after that returns we
911 // can safely reset this flag.
912 allow_exact_keyword_match_
= text_differs
&& allow_keyword_ui_change
&&
913 !just_deleted_text
&& no_selection
&&
914 CreatedKeywordSearchByInsertingSpaceInMiddle(old_text
, user_text_
,
916 view_
->UpdatePopup();
917 allow_exact_keyword_match_
= false;
919 // Change to keyword mode if the user is now pressing space after a keyword
920 // name. Note that if this is the case, then even if there was no keyword
921 // hint when we entered this function (e.g. if the user has used space to
922 // replace some selected text that was adjoined to this keyword), there will
923 // be one now because of the call to UpdatePopup() above; so it's safe for
924 // MaybeAcceptKeywordBySpace() to look at |keyword_| and |is_keyword_hint_| to
925 // determine what keyword, if any, is applicable.
927 // If MaybeAcceptKeywordBySpace() accepts the keyword and returns true, that
928 // will have updated our state already, so in that case we don't also return
929 // true from this function.
930 return !(text_differs
&& allow_keyword_ui_change
&& !just_deleted_text
&&
931 no_selection
&& (selection_start
== user_text_
.length()) &&
932 MaybeAcceptKeywordBySpace(user_text_
));
935 void OmniboxEditModel::PopupBoundsChangedTo(const gfx::Rect
& bounds
) {
936 InstantController
* instant
= controller_
->GetInstant();
938 instant
->SetOmniboxBounds(bounds
);
941 void OmniboxEditModel::OnResultChanged(bool default_match_changed
) {
942 const bool was_open
= popup_
->IsOpen();
943 if (default_match_changed
) {
944 string16 inline_autocomplete_text
;
946 bool is_keyword_hint
= false;
947 const AutocompleteResult
& result
= this->result();
948 const AutocompleteResult::const_iterator
match(result
.default_match());
949 if (match
!= result
.end()) {
950 if ((match
->inline_autocomplete_offset
!= string16::npos
) &&
951 (match
->inline_autocomplete_offset
<
952 match
->fill_into_edit
.length())) {
953 inline_autocomplete_text
=
954 match
->fill_into_edit
.substr(match
->inline_autocomplete_offset
);
957 if (!prerender::IsOmniboxEnabled(profile_
))
958 DoPreconnect(*match
);
960 // We could prefetch the alternate nav URL, if any, but because there
961 // can be many of these as a user types an initial series of characters,
962 // the OS DNS cache could suffer eviction problems for minimal gain.
964 match
->GetKeywordUIState(profile_
, &keyword
, &is_keyword_hint
);
967 popup_
->OnResultChanged();
968 OnPopupDataChanged(inline_autocomplete_text
, NULL
, keyword
,
971 popup_
->OnResultChanged();
974 if (popup_
->IsOpen()) {
975 PopupBoundsChangedTo(popup_
->view()->GetTargetBounds());
976 } else if (was_open
) {
977 // Accepts the temporary text as the user text, because it makes little
978 // sense to have temporary text when the popup is closed.
979 InternalSetUserText(UserTextFromDisplayText(view_
->GetText()));
980 has_temporary_text_
= false;
981 PopupBoundsChangedTo(gfx::Rect());
982 NotifySearchTabHelper();
986 bool OmniboxEditModel::query_in_progress() const {
987 return !autocomplete_controller_
->done();
990 void OmniboxEditModel::InternalSetUserText(const string16
& text
) {
992 just_deleted_text_
= false;
993 inline_autocomplete_text_
.clear();
996 bool OmniboxEditModel::KeywordIsSelected() const {
997 return !is_keyword_hint_
&& !keyword_
.empty();
1000 void OmniboxEditModel::ClearPopupKeywordMode() const {
1001 if (popup_
->IsOpen() &&
1002 popup_
->selected_line_state() == OmniboxPopupModel::KEYWORD
)
1003 popup_
->SetSelectedLineState(OmniboxPopupModel::NORMAL
);
1006 string16
OmniboxEditModel::DisplayTextFromUserText(const string16
& text
) const {
1007 return KeywordIsSelected() ?
1008 KeywordProvider::SplitReplacementStringFromInput(text
, false) : text
;
1011 string16
OmniboxEditModel::UserTextFromDisplayText(const string16
& text
) const {
1012 return KeywordIsSelected() ? (keyword_
+ char16(' ') + text
) : text
;
1015 void OmniboxEditModel::InfoForCurrentSelection(AutocompleteMatch
* match
,
1016 GURL
* alternate_nav_url
) const {
1017 DCHECK(match
!= NULL
);
1018 const AutocompleteResult
& result
= this->result();
1019 if (!autocomplete_controller_
->done()) {
1020 // It's technically possible for |result| to be empty if no provider returns
1021 // a synchronous result but the query has not completed synchronously;
1022 // pratically, however, that should never actually happen.
1025 // The user cannot have manually selected a match, or the query would have
1026 // stopped. So the default match must be the desired selection.
1027 *match
= *result
.default_match();
1029 CHECK(popup_
->IsOpen());
1030 // If there are no results, the popup should be closed (so we should have
1031 // failed the CHECK above), and URLsForDefaultMatch() should have been
1033 CHECK(!result
.empty());
1034 CHECK(popup_
->selected_line() < result
.size());
1035 *match
= result
.match_at(popup_
->selected_line());
1037 if (alternate_nav_url
&& popup_
->manually_selected_match().empty())
1038 *alternate_nav_url
= result
.alternate_nav_url();
1041 void OmniboxEditModel::GetInfoForCurrentText(AutocompleteMatch
* match
,
1042 GURL
* alternate_nav_url
) const {
1043 if (popup_
->IsOpen() || query_in_progress()) {
1044 InfoForCurrentSelection(match
, alternate_nav_url
);
1046 AutocompleteClassifierFactory::GetForProfile(profile_
)->Classify(
1047 UserTextFromDisplayText(view_
->GetText()), GetDesiredTLD(),
1048 KeywordIsSelected(), true, match
, alternate_nav_url
);
1052 void OmniboxEditModel::RevertTemporaryText(bool revert_popup
) {
1053 // The user typed something, then selected a different item. Restore the
1054 // text they typed and change back to the default item.
1055 // NOTE: This purposefully does not reset paste_state_.
1056 just_deleted_text_
= false;
1057 has_temporary_text_
= false;
1059 popup_
->ResetToDefaultMatch();
1060 view_
->OnRevertTemporaryText();
1063 bool OmniboxEditModel::MaybeAcceptKeywordBySpace(const string16
& new_text
) {
1064 size_t keyword_length
= new_text
.length() - 1;
1065 return (paste_state_
== NONE
) && is_keyword_hint_
&& !keyword_
.empty() &&
1066 inline_autocomplete_text_
.empty() &&
1067 (keyword_
.length() == keyword_length
) &&
1068 IsSpaceCharForAcceptingKeyword(new_text
[keyword_length
]) &&
1069 !new_text
.compare(0, keyword_length
, keyword_
, 0, keyword_length
) &&
1073 bool OmniboxEditModel::CreatedKeywordSearchByInsertingSpaceInMiddle(
1074 const string16
& old_text
,
1075 const string16
& new_text
,
1076 size_t caret_position
) const {
1077 DCHECK_GE(new_text
.length(), caret_position
);
1079 // Check simple conditions first.
1080 if ((paste_state_
!= NONE
) || (caret_position
< 2) ||
1081 (old_text
.length() < caret_position
) ||
1082 (new_text
.length() == caret_position
))
1084 size_t space_position
= caret_position
- 1;
1085 if (!IsSpaceCharForAcceptingKeyword(new_text
[space_position
]) ||
1086 IsWhitespace(new_text
[space_position
- 1]) ||
1087 new_text
.compare(0, space_position
, old_text
, 0, space_position
) ||
1088 !new_text
.compare(space_position
, new_text
.length() - space_position
,
1089 old_text
, space_position
,
1090 old_text
.length() - space_position
)) {
1094 // Then check if the text before the inserted space matches a keyword.
1096 TrimWhitespace(new_text
.substr(0, space_position
), TRIM_LEADING
, &keyword
);
1097 return !keyword
.empty() &&
1098 !autocomplete_controller_
->keyword_provider()->
1099 GetKeywordForText(keyword
).empty();
1102 void OmniboxEditModel::NotifySearchTabHelper() {
1103 if (controller_
->GetTabContents()) {
1104 controller_
->GetTabContents()->search_tab_helper()->
1105 OmniboxEditModelChanged(user_input_in_progress_
, !in_revert_
);
1109 bool OmniboxEditModel::DoInstant(
1110 const AutocompleteMatch
& match
,
1111 string16
* suggested_text
,
1112 InstantCompleteBehavior
* complete_behavior
) {
1113 DCHECK(suggested_text
);
1114 DCHECK(complete_behavior
);
1119 InstantController
* instant
= controller_
->GetInstant();
1124 if (user_input_in_progress_
&& popup_
->IsOpen()) {
1125 // The two pieces of text we want to send Instant, viz., what the user has
1126 // typed, and any inline autocomplete suggestion.
1127 string16 user_text
= user_text_
;
1128 *suggested_text
= inline_autocomplete_text_
;
1130 // If there's temporary text, that overrides the user_text. In this case, we
1131 // should ignore any inline_autocomplete_text_, because it won't be visible.
1132 if (has_temporary_text_
) {
1133 user_text
= CurrentMatch().fill_into_edit
;
1134 suggested_text
->clear();
1137 // Remove any keywords and "?" prefix.
1138 user_text
= DisplayTextFromUserText(user_text
);
1139 AutocompleteInput::RemoveForcedQueryStringIfNecessary(
1140 autocomplete_controller_
->input().type(), &user_text
);
1142 return instant
->Update(match
, user_text
, UseVerbatimInstant(),
1143 suggested_text
, complete_behavior
);
1146 // It's possible DoInstant() was called due to an OnChanged() event from the
1147 // omnibox view if the user clicked the renderer while IME composition was
1148 // active. In that case we still want to commit on mouse up, so don't call
1150 if (!instant
->commit_on_pointer_release())
1155 void OmniboxEditModel::DoPrerender(const AutocompleteMatch
& match
) {
1156 // Do not prerender if the destination URL is the same as the current URL.
1157 if (match
.destination_url
== PermanentURL())
1159 // It's possible the tab strip does not have an active tab contents, for
1160 // instance if the tab has been closed or on return from a sleep state
1161 // (http://crbug.com/105689)
1162 TabContents
* tab
= controller_
->GetTabContents();
1165 gfx::Rect container_bounds
;
1166 tab
->web_contents()->GetView()->GetContainerBounds(&container_bounds
);
1167 AutocompleteActionPredictorFactory::GetForProfile(profile_
)->
1168 StartPrerendering(match
.destination_url
,
1169 tab
->web_contents()->GetController()
1170 .GetSessionStorageNamespaceMap(),
1171 container_bounds
.size());
1174 void OmniboxEditModel::DoPreconnect(const AutocompleteMatch
& match
) {
1175 if (!match
.destination_url
.SchemeIs(chrome::kExtensionScheme
)) {
1176 // Warm up DNS Prefetch cache, or preconnect to a search service.
1177 UMA_HISTOGRAM_ENUMERATION("Autocomplete.MatchType", match
.type
,
1178 AutocompleteMatch::NUM_TYPES
);
1179 if (profile_
->GetNetworkPredictor()) {
1180 profile_
->GetNetworkPredictor()->AnticipateOmniboxUrl(
1181 match
.destination_url
,
1182 AutocompleteActionPredictor::IsPreconnectable(match
));
1184 // We could prefetch the alternate nav URL, if any, but because there
1185 // can be many of these as a user types an initial series of characters,
1186 // the OS DNS cache could suffer eviction problems for minimal gain.
1191 bool OmniboxEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c
) {
1193 case 0x0020: // Space
1194 case 0x3000: // Ideographic Space
1201 metrics::OmniboxEventProto::PageClassification
1202 OmniboxEditModel::ClassifyPage(const GURL
& gurl
) const {
1203 if (!gurl
.is_valid())
1204 return metrics::OmniboxEventProto_PageClassification_INVALID_SPEC
;
1205 const std::string
& url
= gurl
.spec();
1206 if (url
== chrome::kChromeUINewTabURL
)
1207 return metrics::OmniboxEventProto_PageClassification_NEW_TAB_PAGE
;
1208 if (url
== chrome::kAboutBlankURL
)
1209 return metrics::OmniboxEventProto_PageClassification_BLANK
;
1210 if (url
== profile()->GetPrefs()->GetString(prefs::kHomePage
))
1211 return metrics::OmniboxEventProto_PageClassification_HOMEPAGE
;
1212 return metrics::OmniboxEventProto_PageClassification_OTHER
;
1215 void OmniboxEditModel::ClassifyStringForPasteAndGo(
1216 const string16
& text
,
1217 AutocompleteMatch
* match
,
1218 GURL
* alternate_nav_url
) const {
1220 AutocompleteClassifierFactory::GetForProfile(profile_
)->Classify(text
,
1221 string16(), false, false, match
, alternate_nav_url
);