Adding instrumentation to locate the source of jankiness
[chromium-blink-merge.git] / chrome / browser / ui / omnibox / omnibox_edit_model.cc
blob1fa637d4f338709d7a5950d92f443b4df6fd7528
1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
7 #include <algorithm>
8 #include <string>
10 #include "base/auto_reset.h"
11 #include "base/format_macros.h"
12 #include "base/metrics/histogram.h"
13 #include "base/prefs/pref_service.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "chrome/app/chrome_command_ids.h"
19 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
20 #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
21 #include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
22 #include "chrome/browser/autocomplete/history_url_provider.h"
23 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
24 #include "chrome/browser/bookmarks/bookmark_stats.h"
25 #include "chrome/browser/chrome_notification_types.h"
26 #include "chrome/browser/command_updater.h"
27 #include "chrome/browser/extensions/api/omnibox/omnibox_api.h"
28 #include "chrome/browser/favicon/favicon_tab_helper.h"
29 #include "chrome/browser/google/google_url_tracker_factory.h"
30 #include "chrome/browser/net/predictor.h"
31 #include "chrome/browser/omnibox/omnibox_log.h"
32 #include "chrome/browser/predictors/autocomplete_action_predictor.h"
33 #include "chrome/browser/predictors/autocomplete_action_predictor_factory.h"
34 #include "chrome/browser/prerender/prerender_field_trial.h"
35 #include "chrome/browser/prerender/prerender_manager.h"
36 #include "chrome/browser/prerender/prerender_manager_factory.h"
37 #include "chrome/browser/profiles/profile.h"
38 #include "chrome/browser/search/search.h"
39 #include "chrome/browser/search_engines/template_url_service_factory.h"
40 #include "chrome/browser/search_engines/ui_thread_search_terms_data.h"
41 #include "chrome/browser/sessions/session_tab_helper.h"
42 #include "chrome/browser/ui/browser_list.h"
43 #include "chrome/browser/ui/omnibox/omnibox_current_page_delegate_impl.h"
44 #include "chrome/browser/ui/omnibox/omnibox_edit_controller.h"
45 #include "chrome/browser/ui/omnibox/omnibox_navigation_observer.h"
46 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
47 #include "chrome/browser/ui/omnibox/omnibox_popup_view.h"
48 #include "chrome/browser/ui/omnibox/omnibox_view.h"
49 #include "chrome/browser/ui/search/instant_search_prerenderer.h"
50 #include "chrome/browser/ui/search/search_tab_helper.h"
51 #include "chrome/browser/ui/toolbar/toolbar_model.h"
52 #include "chrome/common/chrome_switches.h"
53 #include "chrome/common/pref_names.h"
54 #include "chrome/common/url_constants.h"
55 #include "components/bookmarks/browser/bookmark_model.h"
56 #include "components/google/core/browser/google_url_tracker.h"
57 #include "components/metrics/proto/omnibox_event.pb.h"
58 #include "components/omnibox/autocomplete_provider.h"
59 #include "components/omnibox/keyword_provider.h"
60 #include "components/omnibox/search_provider.h"
61 #include "components/search_engines/template_url.h"
62 #include "components/search_engines/template_url_prepopulate_data.h"
63 #include "components/search_engines/template_url_service.h"
64 #include "components/url_fixer/url_fixer.h"
65 #include "content/public/browser/navigation_controller.h"
66 #include "content/public/browser/navigation_entry.h"
67 #include "content/public/browser/notification_service.h"
68 #include "content/public/browser/render_view_host.h"
69 #include "content/public/browser/user_metrics.h"
70 #include "extensions/common/constants.h"
71 #include "ui/gfx/image/image.h"
72 #include "url/url_util.h"
74 using metrics::OmniboxEventProto;
75 using predictors::AutocompleteActionPredictor;
78 // Helpers --------------------------------------------------------------------
80 namespace {
82 // Histogram name which counts the number of times that the user text is
83 // cleared. IME users are sometimes in the situation that IME was
84 // unintentionally turned on and failed to input latin alphabets (ASCII
85 // characters) or the opposite case. In that case, users may delete all
86 // the text and the user text gets cleared. We'd like to measure how often
87 // this scenario happens.
89 // Note that since we don't currently correlate "text cleared" events with
90 // IME usage, this also captures many other cases where users clear the text;
91 // though it explicitly doesn't log deleting all the permanent text as
92 // the first action of an editing sequence (see comments in
93 // OnAfterPossibleChange()).
94 const char kOmniboxUserTextClearedHistogram[] = "Omnibox.UserTextCleared";
96 enum UserTextClearedType {
97 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING = 0,
98 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE = 1,
99 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS,
102 // Histogram name which counts the number of times the user enters
103 // keyword hint mode and via what method. The possible values are listed
104 // in the EnteredKeywordModeMethod enum which is defined in the .h file.
105 const char kEnteredKeywordModeHistogram[] = "Omnibox.EnteredKeywordMode";
107 // Histogram name which counts the number of milliseconds a user takes
108 // between focusing and editing the omnibox.
109 const char kFocusToEditTimeHistogram[] = "Omnibox.FocusToEditTime";
111 // Histogram name which counts the number of milliseconds a user takes
112 // between focusing and opening an omnibox match.
113 const char kFocusToOpenTimeHistogram[] = "Omnibox.FocusToOpenTimeAnyPopupState";
115 // Split the percentage match histograms into buckets based on the width of the
116 // omnibox.
117 const int kPercentageMatchHistogramWidthBuckets[] = { 400, 700, 1200 };
119 void RecordPercentageMatchHistogram(const base::string16& old_text,
120 const base::string16& new_text,
121 bool url_replacement_active,
122 ui::PageTransition transition,
123 int omnibox_width) {
124 size_t avg_length = (old_text.length() + new_text.length()) / 2;
126 int percent = 0;
127 if (!old_text.empty() && !new_text.empty()) {
128 size_t shorter_length = std::min(old_text.length(), new_text.length());
129 base::string16::const_iterator end(old_text.begin() + shorter_length);
130 base::string16::const_iterator mismatch(
131 std::mismatch(old_text.begin(), end, new_text.begin()).first);
132 size_t matching_characters = mismatch - old_text.begin();
133 percent = static_cast<float>(matching_characters) / avg_length * 100;
136 std::string histogram_name;
137 if (url_replacement_active) {
138 if (transition == ui::PAGE_TRANSITION_TYPED) {
139 histogram_name = "InstantExtended.PercentageMatchV2_QuerytoURL";
140 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
141 } else {
142 histogram_name = "InstantExtended.PercentageMatchV2_QuerytoQuery";
143 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
145 } else {
146 if (transition == ui::PAGE_TRANSITION_TYPED) {
147 histogram_name = "InstantExtended.PercentageMatchV2_URLtoURL";
148 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
149 } else {
150 histogram_name = "InstantExtended.PercentageMatchV2_URLtoQuery";
151 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
155 std::string suffix = "large";
156 for (size_t i = 0; i < arraysize(kPercentageMatchHistogramWidthBuckets);
157 ++i) {
158 if (omnibox_width < kPercentageMatchHistogramWidthBuckets[i]) {
159 suffix = base::IntToString(kPercentageMatchHistogramWidthBuckets[i]);
160 break;
164 // Cannot rely on UMA histograms macro because the name of the histogram is
165 // generated dynamically.
166 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
167 histogram_name + "_" + suffix, 1, 101, 102,
168 base::Histogram::kUmaTargetedHistogramFlag);
169 counter->Add(percent);
172 } // namespace
175 // OmniboxEditModel::State ----------------------------------------------------
177 OmniboxEditModel::State::State(bool user_input_in_progress,
178 const base::string16& user_text,
179 const base::string16& gray_text,
180 const base::string16& keyword,
181 bool is_keyword_hint,
182 bool url_replacement_enabled,
183 OmniboxFocusState focus_state,
184 FocusSource focus_source,
185 const AutocompleteInput& autocomplete_input)
186 : user_input_in_progress(user_input_in_progress),
187 user_text(user_text),
188 gray_text(gray_text),
189 keyword(keyword),
190 is_keyword_hint(is_keyword_hint),
191 url_replacement_enabled(url_replacement_enabled),
192 focus_state(focus_state),
193 focus_source(focus_source),
194 autocomplete_input(autocomplete_input) {
197 OmniboxEditModel::State::~State() {
201 // OmniboxEditModel -----------------------------------------------------------
203 OmniboxEditModel::OmniboxEditModel(OmniboxView* view,
204 OmniboxEditController* controller,
205 Profile* profile)
206 : view_(view),
207 controller_(controller),
208 focus_state_(OMNIBOX_FOCUS_NONE),
209 focus_source_(INVALID),
210 user_input_in_progress_(false),
211 user_input_since_focus_(true),
212 just_deleted_text_(false),
213 has_temporary_text_(false),
214 paste_state_(NONE),
215 control_key_state_(UP),
216 is_keyword_hint_(false),
217 profile_(profile),
218 in_revert_(false),
219 allow_exact_keyword_match_(false) {
220 omnibox_controller_.reset(new OmniboxController(this, profile));
221 delegate_.reset(new OmniboxCurrentPageDelegateImpl(controller, profile));
224 OmniboxEditModel::~OmniboxEditModel() {
227 const OmniboxEditModel::State OmniboxEditModel::GetStateForTabSwitch() {
228 // Like typing, switching tabs "accepts" the temporary text as the user
229 // text, because it makes little sense to have temporary text when the
230 // popup is closed.
231 if (user_input_in_progress_) {
232 // Weird edge case to match other browsers: if the edit is empty, revert to
233 // the permanent text (so the user can get it back easily) but select it (so
234 // on switching back, typing will "just work").
235 const base::string16 user_text(UserTextFromDisplayText(view_->GetText()));
236 if (user_text.empty()) {
237 base::AutoReset<bool> tmp(&in_revert_, true);
238 view_->RevertAll();
239 view_->SelectAll(true);
240 } else {
241 InternalSetUserText(user_text);
245 UMA_HISTOGRAM_BOOLEAN("Omnibox.SaveStateForTabSwitch.UserInputInProgress",
246 user_input_in_progress_);
247 return State(
248 user_input_in_progress_, user_text_, view_->GetGrayTextAutocompletion(),
249 keyword_, is_keyword_hint_,
250 controller_->GetToolbarModel()->url_replacement_enabled(),
251 focus_state_, focus_source_, input_);
254 void OmniboxEditModel::RestoreState(const State* state) {
255 // We need to update the permanent text correctly and revert the view
256 // regardless of whether there is saved state.
257 bool url_replacement_enabled = !state || state->url_replacement_enabled;
258 controller_->GetToolbarModel()->set_url_replacement_enabled(
259 url_replacement_enabled);
260 controller_->GetToolbarModel()->set_origin_chip_enabled(
261 url_replacement_enabled);
262 permanent_text_ = controller_->GetToolbarModel()->GetText();
263 // Don't muck with the search term replacement state, as we've just set it
264 // correctly.
265 view_->RevertWithoutResettingSearchTermReplacement();
266 // Restore the autocomplete controller's input, or clear it if this is a new
267 // tab.
268 input_ = state ? state->autocomplete_input : AutocompleteInput();
269 if (!state)
270 return;
272 SetFocusState(state->focus_state, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH);
273 focus_source_ = state->focus_source;
274 // Restore any user editing.
275 if (state->user_input_in_progress) {
276 // NOTE: Be sure and set keyword-related state BEFORE invoking
277 // DisplayTextFromUserText(), as its result depends upon this state.
278 keyword_ = state->keyword;
279 is_keyword_hint_ = state->is_keyword_hint;
280 view_->SetUserText(state->user_text,
281 DisplayTextFromUserText(state->user_text), false);
282 view_->SetGrayTextAutocompletion(state->gray_text);
286 AutocompleteMatch OmniboxEditModel::CurrentMatch(
287 GURL* alternate_nav_url) const {
288 // If we have a valid match use it. Otherwise get one for the current text.
289 AutocompleteMatch match = omnibox_controller_->current_match();
291 if (!match.destination_url.is_valid()) {
292 GetInfoForCurrentText(&match, alternate_nav_url);
293 } else if (alternate_nav_url) {
294 *alternate_nav_url = AutocompleteResult::ComputeAlternateNavUrl(
295 input_, match);
297 return match;
300 bool OmniboxEditModel::UpdatePermanentText() {
301 SearchProvider* search_provider =
302 autocomplete_controller()->search_provider();
303 if (search_provider && delegate_->CurrentPageExists())
304 search_provider->set_current_page_url(delegate_->GetURL());
306 // When there's new permanent text, and the user isn't interacting with the
307 // omnibox, we want to revert the edit to show the new text. We could simply
308 // define "interacting" as "the omnibox has focus", but we still allow updates
309 // when the omnibox has focus as long as the user hasn't begun editing, isn't
310 // seeing zerosuggestions (because changing this text would require changing
311 // or hiding those suggestions), and hasn't toggled on "Show URL" (because
312 // this update will re-enable search term replacement, which will be annoying
313 // if the user is trying to copy the URL). When the omnibox doesn't have
314 // focus, we assume the user may have abandoned their interaction and it's
315 // always safe to change the text; this also prevents someone toggling "Show
316 // URL" (which sounds as if it might be persistent) from seeing just that URL
317 // forever afterwards.
319 // If the page is auto-committing gray text, however, we generally don't want
320 // to make any change to the edit. While auto-commits modify the underlying
321 // permanent URL, they're intended to have no effect on the user's editing
322 // process -- before and after the auto-commit, the omnibox should show the
323 // same user text and the same instant suggestion, even if the auto-commit
324 // happens while the edit doesn't have focus.
325 base::string16 new_permanent_text = controller_->GetToolbarModel()->GetText();
326 base::string16 gray_text = view_->GetGrayTextAutocompletion();
327 const bool visibly_changed_permanent_text =
328 (permanent_text_ != new_permanent_text) &&
329 (!has_focus() ||
330 (!user_input_in_progress_ &&
331 !(popup_model() && popup_model()->IsOpen()) &&
332 controller_->GetToolbarModel()->url_replacement_enabled())) &&
333 (gray_text.empty() ||
334 new_permanent_text != user_text_ + gray_text);
336 permanent_text_ = new_permanent_text;
337 return visibly_changed_permanent_text;
340 GURL OmniboxEditModel::PermanentURL() {
341 return url_fixer::FixupURL(base::UTF16ToUTF8(permanent_text_), std::string());
344 void OmniboxEditModel::SetUserText(const base::string16& text) {
345 SetInputInProgress(true);
346 InternalSetUserText(text);
347 omnibox_controller_->InvalidateCurrentMatch();
348 paste_state_ = NONE;
349 has_temporary_text_ = false;
352 bool OmniboxEditModel::CommitSuggestedText() {
353 const base::string16 suggestion = view_->GetGrayTextAutocompletion();
354 if (suggestion.empty())
355 return false;
357 const base::string16 final_text = view_->GetText() + suggestion;
358 view_->OnBeforePossibleChange();
359 view_->SetWindowTextAndCaretPos(final_text, final_text.length(), false,
360 false);
361 view_->OnAfterPossibleChange();
362 return true;
365 void OmniboxEditModel::OnChanged() {
366 // Don't call CurrentMatch() when there's no editing, as in this case we'll
367 // never actually use it. This avoids running the autocomplete providers (and
368 // any systems they then spin up) during startup.
369 const AutocompleteMatch& current_match = user_input_in_progress_ ?
370 CurrentMatch(NULL) : AutocompleteMatch();
372 AutocompleteActionPredictor::Action recommended_action =
373 AutocompleteActionPredictor::ACTION_NONE;
374 if (user_input_in_progress_) {
375 InstantSearchPrerenderer* prerenderer =
376 InstantSearchPrerenderer::GetForProfile(profile_);
377 if (prerenderer &&
378 prerenderer->IsAllowed(current_match, controller_->GetWebContents()) &&
379 popup_model()->IsOpen() && has_focus()) {
380 recommended_action = AutocompleteActionPredictor::ACTION_PRERENDER;
381 } else {
382 AutocompleteActionPredictor* action_predictor =
383 predictors::AutocompleteActionPredictorFactory::GetForProfile(
384 profile_);
385 action_predictor->RegisterTransitionalMatches(user_text_, result());
386 // Confer with the AutocompleteActionPredictor to determine what action,
387 // if any, we should take. Get the recommended action here even if we
388 // don't need it so we can get stats for anyone who is opted in to UMA,
389 // but only get it if the user has actually typed something to avoid
390 // constructing it before it's needed. Note: This event is triggered as
391 // part of startup when the initial tab transitions to the start page.
392 recommended_action =
393 action_predictor->RecommendAction(user_text_, current_match);
397 UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.Action",
398 recommended_action,
399 AutocompleteActionPredictor::LAST_PREDICT_ACTION);
401 // Hide any suggestions we might be showing.
402 view_->SetGrayTextAutocompletion(base::string16());
404 switch (recommended_action) {
405 case AutocompleteActionPredictor::ACTION_PRERENDER:
406 // It's possible that there is no current page, for instance if the tab
407 // has been closed or on return from a sleep state.
408 // (http://crbug.com/105689)
409 if (!delegate_->CurrentPageExists())
410 break;
411 // Ask for prerendering if the destination URL is different than the
412 // current URL.
413 if (current_match.destination_url != delegate_->GetURL())
414 delegate_->DoPrerender(current_match);
415 break;
416 case AutocompleteActionPredictor::ACTION_PRECONNECT:
417 omnibox_controller_->DoPreconnect(current_match);
418 break;
419 case AutocompleteActionPredictor::ACTION_NONE:
420 break;
423 controller_->OnChanged();
426 void OmniboxEditModel::GetDataForURLExport(GURL* url,
427 base::string16* title,
428 gfx::Image* favicon) {
429 *url = CurrentMatch(NULL).destination_url;
430 if (*url == delegate_->GetURL()) {
431 content::WebContents* web_contents = controller_->GetWebContents();
432 *title = web_contents->GetTitle();
433 *favicon = FaviconTabHelper::FromWebContents(web_contents)->GetFavicon();
437 bool OmniboxEditModel::CurrentTextIsURL() const {
438 if (controller_->GetToolbarModel()->WouldReplaceURL())
439 return false;
441 // If current text is not composed of replaced search terms and
442 // !user_input_in_progress_, then permanent text is showing and should be a
443 // URL, so no further checking is needed. By avoiding checking in this case,
444 // we avoid calling into the autocomplete providers, and thus initializing the
445 // history system, as long as possible, which speeds startup.
446 if (!user_input_in_progress_)
447 return true;
449 return !AutocompleteMatch::IsSearchType(CurrentMatch(NULL).type);
452 AutocompleteMatch::Type OmniboxEditModel::CurrentTextType() const {
453 return CurrentMatch(NULL).type;
456 void OmniboxEditModel::AdjustTextForCopy(int sel_min,
457 bool is_all_selected,
458 base::string16* text,
459 GURL* url,
460 bool* write_url) {
461 *write_url = false;
463 // Do not adjust if selection did not start at the beginning of the field, or
464 // if the URL was omitted.
465 if ((sel_min != 0) || controller_->GetToolbarModel()->WouldReplaceURL())
466 return;
468 if (!user_input_in_progress_ && is_all_selected) {
469 // The user selected all the text and has not edited it. Use the url as the
470 // text so that if the scheme was stripped it's added back, and the url
471 // is unescaped (we escape parts of the url for display).
472 *url = PermanentURL();
473 *text = base::UTF8ToUTF16(url->spec());
474 *write_url = true;
475 return;
478 // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now
479 // the user is probably holding down control to cause the copy, which will
480 // screw up our calculation of the desired_tld.
481 AutocompleteMatch match;
482 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
483 *text, is_keyword_selected(), true, ClassifyPage(), &match, NULL);
484 if (AutocompleteMatch::IsSearchType(match.type))
485 return;
486 *url = match.destination_url;
488 // Prefix the text with 'http://' if the text doesn't start with 'http://',
489 // the text parses as a url with a scheme of http, the user selected the
490 // entire host, and the user hasn't edited the host or manually removed the
491 // scheme.
492 GURL perm_url(PermanentURL());
493 if (perm_url.SchemeIs(url::kHttpScheme) &&
494 url->SchemeIs(url::kHttpScheme) && perm_url.host() == url->host()) {
495 *write_url = true;
496 base::string16 http = base::ASCIIToUTF16(url::kHttpScheme) +
497 base::ASCIIToUTF16(url::kStandardSchemeSeparator);
498 if (text->compare(0, http.length(), http) != 0)
499 *text = http + *text;
503 void OmniboxEditModel::SetInputInProgress(bool in_progress) {
504 if (in_progress && !user_input_since_focus_) {
505 base::TimeTicks now = base::TimeTicks::Now();
506 DCHECK(last_omnibox_focus_ <= now);
507 UMA_HISTOGRAM_TIMES(kFocusToEditTimeHistogram, now - last_omnibox_focus_);
508 user_input_since_focus_ = true;
511 if (user_input_in_progress_ == in_progress)
512 return;
514 user_input_in_progress_ = in_progress;
515 if (user_input_in_progress_) {
516 time_user_first_modified_omnibox_ = base::TimeTicks::Now();
517 content::RecordAction(base::UserMetricsAction("OmniboxInputInProgress"));
518 autocomplete_controller()->ResetSession();
521 // The following code handles two cases:
522 // * For HIDE_ON_USER_INPUT and ON_SRP, it hides the chip when user input
523 // begins.
524 // * For HIDE_ON_MOUSE_RELEASE, which only hides the chip on mouse release if
525 // the omnibox is empty, it handles the "omnibox was not empty" case by
526 // acting like HIDE_ON_USER_INPUT.
527 if (chrome::ShouldDisplayOriginChip() && in_progress)
528 controller()->GetToolbarModel()->set_origin_chip_enabled(false);
530 controller_->GetToolbarModel()->set_input_in_progress(in_progress);
531 controller_->EndOriginChipAnimations(true);
532 controller_->Update(NULL);
534 if (user_input_in_progress_ || !in_revert_)
535 delegate_->OnInputStateChanged();
538 void OmniboxEditModel::Revert() {
539 SetInputInProgress(false);
540 paste_state_ = NONE;
541 InternalSetUserText(base::string16());
542 keyword_.clear();
543 is_keyword_hint_ = false;
544 has_temporary_text_ = false;
545 view_->SetWindowTextAndCaretPos(permanent_text_,
546 has_focus() ? permanent_text_.length() : 0,
547 false, true);
548 AutocompleteActionPredictor* action_predictor =
549 predictors::AutocompleteActionPredictorFactory::GetForProfile(profile_);
550 action_predictor->ClearTransitionalMatches();
551 action_predictor->CancelPrerender();
554 void OmniboxEditModel::StartAutocomplete(
555 bool has_selected_text,
556 bool prevent_inline_autocomplete) {
557 size_t cursor_position;
558 if (inline_autocomplete_text_.empty()) {
559 // Cursor position is equivalent to the current selection's end.
560 size_t start;
561 view_->GetSelectionBounds(&start, &cursor_position);
562 // Adjust cursor position taking into account possible keyword in the user
563 // text. We rely on DisplayTextFromUserText() method which is consistent
564 // with keyword extraction done in KeywordProvider/SearchProvider.
565 const size_t cursor_offset =
566 user_text_.length() - DisplayTextFromUserText(user_text_).length();
567 cursor_position += cursor_offset;
568 } else {
569 // There are some cases where StartAutocomplete() may be called
570 // with non-empty |inline_autocomplete_text_|. In such cases, we cannot
571 // use the current selection, because it could result with the cursor
572 // position past the last character from the user text. Instead,
573 // we assume that the cursor is simply at the end of input.
574 // One example is when user presses Ctrl key while having a highlighted
575 // inline autocomplete text.
576 // TODO: Rethink how we are going to handle this case to avoid
577 // inconsistent behavior when user presses Ctrl key.
578 // See http://crbug.com/165961 and http://crbug.com/165968 for more details.
579 cursor_position = user_text_.length();
582 GURL current_url =
583 (delegate_->CurrentPageExists() && view_->IsIndicatingQueryRefinement()) ?
584 delegate_->GetURL() : GURL();
585 input_ = AutocompleteInput(
586 user_text_, cursor_position, std::string(), current_url, ClassifyPage(),
587 prevent_inline_autocomplete || just_deleted_text_ ||
588 (has_selected_text && inline_autocomplete_text_.empty()) ||
589 (paste_state_ != NONE),
590 is_keyword_selected(),
591 is_keyword_selected() || allow_exact_keyword_match_,
592 true, ChromeAutocompleteSchemeClassifier(profile_));
594 omnibox_controller_->StartAutocomplete(input_);
597 void OmniboxEditModel::StopAutocomplete() {
598 autocomplete_controller()->Stop(true);
601 bool OmniboxEditModel::CanPasteAndGo(const base::string16& text) const {
602 if (!view_->command_updater()->IsCommandEnabled(IDC_OPEN_CURRENT_URL))
603 return false;
605 AutocompleteMatch match;
606 ClassifyStringForPasteAndGo(text, &match, NULL);
607 return match.destination_url.is_valid();
610 void OmniboxEditModel::PasteAndGo(const base::string16& text) {
611 DCHECK(CanPasteAndGo(text));
612 UMA_HISTOGRAM_COUNTS("Omnibox.PasteAndGo", 1);
614 view_->RevertAll();
615 AutocompleteMatch match;
616 GURL alternate_nav_url;
617 ClassifyStringForPasteAndGo(text, &match, &alternate_nav_url);
618 view_->OpenMatch(match, CURRENT_TAB, alternate_nav_url, text,
619 OmniboxPopupModel::kNoMatch);
622 bool OmniboxEditModel::IsPasteAndSearch(const base::string16& text) const {
623 AutocompleteMatch match;
624 ClassifyStringForPasteAndGo(text, &match, NULL);
625 return AutocompleteMatch::IsSearchType(match.type);
628 void OmniboxEditModel::AcceptInput(WindowOpenDisposition disposition,
629 bool for_drop) {
630 // Get the URL and transition type for the selected entry.
631 GURL alternate_nav_url;
632 AutocompleteMatch match = CurrentMatch(&alternate_nav_url);
634 // If CTRL is down it means the user wants to append ".com" to the text he
635 // typed. If we can successfully generate a URL_WHAT_YOU_TYPED match doing
636 // that, then we use this. These matches are marked as generated by the
637 // HistoryURLProvider so we only generate them if this provider is present.
638 if (control_key_state_ == DOWN_WITHOUT_CHANGE && !is_keyword_selected() &&
639 autocomplete_controller()->history_url_provider()) {
640 // Generate a new AutocompleteInput, copying the latest one but using "com"
641 // as the desired TLD. Then use this autocomplete input to generate a
642 // URL_WHAT_YOU_TYPED AutocompleteMatch. Note that using the most recent
643 // input instead of the currently visible text means we'll ignore any
644 // visible inline autocompletion: if a user types "foo" and is autocompleted
645 // to "foodnetwork.com", ctrl-enter will navigate to "foo.com", not
646 // "foodnetwork.com". At the time of writing, this behavior matches
647 // Internet Explorer, but not Firefox.
648 input_ = AutocompleteInput(
649 has_temporary_text_ ?
650 UserTextFromDisplayText(view_->GetText()) : input_.text(),
651 input_.cursor_position(), "com", GURL(),
652 input_.current_page_classification(),
653 input_.prevent_inline_autocomplete(), input_.prefer_keyword(),
654 input_.allow_exact_keyword_match(), input_.want_asynchronous_matches(),
655 ChromeAutocompleteSchemeClassifier(profile_));
656 AutocompleteMatch url_match(
657 autocomplete_controller()->history_url_provider()->SuggestExactInput(
658 input_.text(), input_.canonicalized_url(), false));
661 if (url_match.destination_url.is_valid()) {
662 // We have a valid URL, we use this newly generated AutocompleteMatch.
663 match = url_match;
664 alternate_nav_url = GURL();
668 if (!match.destination_url.is_valid())
669 return;
671 if ((match.transition == ui::PAGE_TRANSITION_TYPED) &&
672 (match.destination_url == PermanentURL())) {
673 // When the user hit enter on the existing permanent URL, treat it like a
674 // reload for scoring purposes. We could detect this by just checking
675 // user_input_in_progress_, but it seems better to treat "edits" that end
676 // up leaving the URL unchanged (e.g. deleting the last character and then
677 // retyping it) as reloads too. We exclude non-TYPED transitions because if
678 // the transition is GENERATED, the user input something that looked
679 // different from the current URL, even if it wound up at the same place
680 // (e.g. manually retyping the same search query), and it seems wrong to
681 // treat this as a reload.
682 match.transition = ui::PAGE_TRANSITION_RELOAD;
683 } else if (for_drop || ((paste_state_ != NONE) &&
684 match.is_history_what_you_typed_match)) {
685 // When the user pasted in a URL and hit enter, score it like a link click
686 // rather than a normal typed URL, so it doesn't get inline autocompleted
687 // as aggressively later.
688 match.transition = ui::PAGE_TRANSITION_LINK;
691 TemplateURLService* service =
692 TemplateURLServiceFactory::GetForProfile(profile_);
693 const TemplateURL* template_url = match.GetTemplateURL(service, false);
694 if (template_url && template_url->url_ref().HasGoogleBaseURLs(
695 UIThreadSearchTermsData(profile_))) {
696 GoogleURLTracker* tracker =
697 GoogleURLTrackerFactory::GetForProfile(profile_);
698 if (tracker)
699 tracker->SearchCommitted();
702 DCHECK(popup_model());
703 view_->OpenMatch(match, disposition, alternate_nav_url, base::string16(),
704 popup_model()->selected_line());
707 void OmniboxEditModel::OpenMatch(AutocompleteMatch match,
708 WindowOpenDisposition disposition,
709 const GURL& alternate_nav_url,
710 const base::string16& pasted_text,
711 size_t index) {
712 const base::TimeTicks& now(base::TimeTicks::Now());
713 base::TimeDelta elapsed_time_since_user_first_modified_omnibox(
714 now - time_user_first_modified_omnibox_);
715 autocomplete_controller()->UpdateMatchDestinationURLWithQueryFormulationTime(
716 elapsed_time_since_user_first_modified_omnibox, &match);
718 base::string16 input_text(pasted_text);
719 if (input_text.empty())
720 input_text = user_input_in_progress_ ? user_text_ : permanent_text_;
721 scoped_ptr<OmniboxNavigationObserver> observer(
722 new OmniboxNavigationObserver(
723 profile_, input_text, match,
724 autocomplete_controller()->history_url_provider()->SuggestExactInput(
725 input_text, alternate_nav_url,
726 AutocompleteInput::HasHTTPScheme(input_text))));
728 base::TimeDelta elapsed_time_since_last_change_to_default_match(
729 now - autocomplete_controller()->last_time_default_match_changed());
730 DCHECK(match.provider);
731 // These elapsed times don't really make sense for ZeroSuggest matches
732 // (because the user does not modify the omnibox for ZeroSuggest), so for
733 // those we set the elapsed times to something that will be ignored by
734 // metrics_log.cc. They also don't necessarily make sense if the omnibox
735 // dropdown is closed or the user used a paste-and-go action. (In most
736 // cases when this happens, the user never modified the omnibox.)
737 if ((match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST) ||
738 !popup_model()->IsOpen() || !pasted_text.empty()) {
739 const base::TimeDelta default_time_delta =
740 base::TimeDelta::FromMilliseconds(-1);
741 elapsed_time_since_user_first_modified_omnibox = default_time_delta;
742 elapsed_time_since_last_change_to_default_match = default_time_delta;
744 // If the popup is closed or this is a paste-and-go action (meaning the
745 // contents of the dropdown are ignored regardless), we record for logging
746 // purposes a selected_index of 0 and a suggestion list as having a single
747 // entry of the match used.
748 ACMatches fake_single_entry_matches;
749 fake_single_entry_matches.push_back(match);
750 AutocompleteResult fake_single_entry_result;
751 fake_single_entry_result.AppendMatches(fake_single_entry_matches);
752 OmniboxLog log(
753 input_text,
754 just_deleted_text_,
755 input_.type(),
756 popup_model()->IsOpen(),
757 (!popup_model()->IsOpen() || !pasted_text.empty()) ? 0 : index,
758 !pasted_text.empty(),
759 -1, // don't yet know tab ID; set later if appropriate
760 ClassifyPage(),
761 elapsed_time_since_user_first_modified_omnibox,
762 match.allowed_to_be_default_match ? match.inline_autocompletion.length() :
763 base::string16::npos,
764 elapsed_time_since_last_change_to_default_match,
765 (!popup_model()->IsOpen() || !pasted_text.empty()) ?
766 fake_single_entry_result : result());
767 DCHECK(!popup_model()->IsOpen() || !pasted_text.empty() ||
768 (log.elapsed_time_since_user_first_modified_omnibox >=
769 log.elapsed_time_since_last_change_to_default_match))
770 << "We should've got the notification that the user modified the "
771 << "omnibox text at same time or before the most recent time the "
772 << "default match changed.";
774 if ((disposition == CURRENT_TAB) && delegate_->CurrentPageExists()) {
775 // If we know the destination is being opened in the current tab,
776 // we can easily get the tab ID. (If it's being opened in a new
777 // tab, we don't know the tab ID yet.)
778 log.tab_id = delegate_->GetSessionID().id();
780 autocomplete_controller()->AddProvidersInfo(&log.providers_info);
781 content::NotificationService::current()->Notify(
782 chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
783 content::Source<Profile>(profile_),
784 content::Details<OmniboxLog>(&log));
785 LOCAL_HISTOGRAM_BOOLEAN("Omnibox.EventCount", true);
786 DCHECK(!last_omnibox_focus_.is_null())
787 << "An omnibox focus should have occurred before opening a match.";
788 UMA_HISTOGRAM_TIMES(kFocusToOpenTimeHistogram, now - last_omnibox_focus_);
790 TemplateURLService* service =
791 TemplateURLServiceFactory::GetForProfile(profile_);
792 TemplateURL* template_url = match.GetTemplateURL(service, false);
793 if (template_url) {
794 if (match.transition == ui::PAGE_TRANSITION_KEYWORD) {
795 // The user is using a non-substituting keyword or is explicitly in
796 // keyword mode.
798 // Don't increment usage count for extension keywords.
799 if (delegate_->ProcessExtensionKeyword(template_url, match,
800 disposition)) {
801 observer->OnSuccessfulNavigation();
802 if (disposition != NEW_BACKGROUND_TAB)
803 view_->RevertAll();
804 return;
807 content::RecordAction(base::UserMetricsAction("AcceptedKeyword"));
808 TemplateURLServiceFactory::GetForProfile(profile_)->IncrementUsageCount(
809 template_url);
810 } else {
811 DCHECK_EQ(ui::PAGE_TRANSITION_GENERATED, match.transition);
812 // NOTE: We purposefully don't increment the usage count of the default
813 // search engine here like we do for explicit keywords above; see comments
814 // in template_url.h.
817 UMA_HISTOGRAM_ENUMERATION(
818 "Omnibox.SearchEngineType",
819 TemplateURLPrepopulateData::GetEngineType(
820 *template_url, UIThreadSearchTermsData(profile_)),
821 SEARCH_ENGINE_MAX);
824 // Get the current text before we call RevertAll() which will clear it.
825 base::string16 current_text = view_->GetText();
827 if (disposition != NEW_BACKGROUND_TAB) {
828 base::AutoReset<bool> tmp(&in_revert_, true);
829 view_->RevertAll(); // Revert the box to its unedited state.
832 RecordPercentageMatchHistogram(
833 permanent_text_, current_text,
834 controller_->GetToolbarModel()->WouldReplaceURL(),
835 match.transition, view_->GetWidth());
837 // Track whether the destination URL sends us to a search results page
838 // using the default search provider.
839 if (TemplateURLServiceFactory::GetForProfile(profile_)->
840 IsSearchResultsPageFromDefaultSearchProvider(match.destination_url)) {
841 content::RecordAction(
842 base::UserMetricsAction("OmniboxDestinationURLIsSearchOnDSP"));
845 if (match.destination_url.is_valid()) {
846 // This calls RevertAll again.
847 base::AutoReset<bool> tmp(&in_revert_, true);
848 controller_->OnAutocompleteAccept(
849 match.destination_url, disposition,
850 ui::PageTransitionFromInt(
851 match.transition | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR));
852 if (observer->load_state() != OmniboxNavigationObserver::LOAD_NOT_SEEN)
853 ignore_result(observer.release()); // The observer will delete itself.
856 BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(profile_);
857 if (bookmark_model && bookmark_model->IsBookmarked(match.destination_url))
858 RecordBookmarkLaunch(NULL, BOOKMARK_LAUNCH_LOCATION_OMNIBOX);
861 bool OmniboxEditModel::AcceptKeyword(EnteredKeywordModeMethod entered_method) {
862 DCHECK(is_keyword_hint_ && !keyword_.empty());
864 autocomplete_controller()->Stop(false);
865 is_keyword_hint_ = false;
867 if (popup_model() && popup_model()->IsOpen())
868 popup_model()->SetSelectedLineState(OmniboxPopupModel::KEYWORD);
869 else
870 StartAutocomplete(false, true);
872 // Ensure the current selection is saved before showing keyword mode
873 // so that moving to another line and then reverting the text will restore
874 // the current state properly.
875 bool save_original_selection = !has_temporary_text_;
876 has_temporary_text_ = true;
877 view_->OnTemporaryTextMaybeChanged(
878 DisplayTextFromUserText(CurrentMatch(NULL).fill_into_edit),
879 save_original_selection, true);
881 view_->UpdatePlaceholderText();
883 content::RecordAction(base::UserMetricsAction("AcceptedKeywordHint"));
884 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram, entered_method,
885 ENTERED_KEYWORD_MODE_NUM_ITEMS);
887 return true;
890 void OmniboxEditModel::AcceptTemporaryTextAsUserText() {
891 InternalSetUserText(UserTextFromDisplayText(view_->GetText()));
892 has_temporary_text_ = false;
894 if (user_input_in_progress_ || !in_revert_)
895 delegate_->OnInputStateChanged();
898 void OmniboxEditModel::ClearKeyword(const base::string16& visible_text) {
899 autocomplete_controller()->Stop(false);
900 omnibox_controller_->ClearPopupKeywordMode();
902 const base::string16 window_text(keyword_ + visible_text);
904 // Only reset the result if the edit text has changed since the
905 // keyword was accepted, or if the popup is closed.
906 if (just_deleted_text_ || !visible_text.empty() ||
907 !(popup_model() && popup_model()->IsOpen())) {
908 view_->OnBeforePossibleChange();
909 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
910 false, false);
911 keyword_.clear();
912 is_keyword_hint_ = false;
913 view_->OnAfterPossibleChange();
914 just_deleted_text_ = true; // OnAfterPossibleChange() fails to clear this
915 // since the edit contents have actually grown
916 // longer.
917 } else {
918 is_keyword_hint_ = true;
919 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
920 false, true);
923 view_->UpdatePlaceholderText();
926 void OmniboxEditModel::OnSetFocus(bool control_down) {
927 last_omnibox_focus_ = base::TimeTicks::Now();
928 user_input_since_focus_ = false;
930 // If the omnibox lost focus while the caret was hidden and then regained
931 // focus, OnSetFocus() is called and should restore visibility. Note that
932 // focus can be regained without an accompanying call to
933 // OmniboxView::SetFocus(), e.g. by tabbing in.
934 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_EXPLICIT);
935 control_key_state_ = control_down ? DOWN_WITHOUT_CHANGE : UP;
937 // Try to get ZeroSuggest suggestions if a page is loaded and the user has
938 // not been typing in the omnibox. The |user_input_in_progress_| check is
939 // used to detect the case where this function is called after right-clicking
940 // in the omnibox and selecting paste in Linux (in which case we actually get
941 // the OnSetFocus() call after the process of handling the paste has kicked
942 // off).
943 // TODO(hfung): Remove this when crbug/271590 is fixed.
944 if (delegate_->CurrentPageExists() && !user_input_in_progress_) {
945 // TODO(jered): We may want to merge this into Start() and just call that
946 // here rather than having a special entry point for zero-suggest. Note
947 // that we avoid PermanentURL() here because it's not guaranteed to give us
948 // the actual underlying current URL, e.g. if we're on the NTP and the
949 // |permanent_text_| is empty.
950 autocomplete_controller()->StartZeroSuggest(AutocompleteInput(
951 permanent_text_, base::string16::npos, std::string(),
952 delegate_->GetURL(), ClassifyPage(), false, false, true, true,
953 ChromeAutocompleteSchemeClassifier(profile_)));
956 if (user_input_in_progress_ || !in_revert_)
957 delegate_->OnInputStateChanged();
960 void OmniboxEditModel::SetCaretVisibility(bool visible) {
961 // Caret visibility only matters if the omnibox has focus.
962 if (focus_state_ != OMNIBOX_FOCUS_NONE) {
963 SetFocusState(visible ? OMNIBOX_FOCUS_VISIBLE : OMNIBOX_FOCUS_INVISIBLE,
964 OMNIBOX_FOCUS_CHANGE_EXPLICIT);
968 void OmniboxEditModel::OnWillKillFocus(gfx::NativeView view_gaining_focus) {
969 if (user_input_in_progress_ || !in_revert_)
970 delegate_->OnInputStateChanged();
973 void OmniboxEditModel::OnKillFocus() {
974 SetFocusState(OMNIBOX_FOCUS_NONE, OMNIBOX_FOCUS_CHANGE_EXPLICIT);
975 focus_source_ = INVALID;
976 control_key_state_ = UP;
977 paste_state_ = NONE;
980 bool OmniboxEditModel::OnEscapeKeyPressed() {
981 const AutocompleteMatch& match = CurrentMatch(NULL);
982 if (has_temporary_text_) {
983 if (match.destination_url != original_url_) {
984 RevertTemporaryText(true);
985 return true;
989 // We do not clear the pending entry from the omnibox when a load is first
990 // stopped. If the user presses Escape while stopped, we clear it.
991 if (delegate_->CurrentPageExists() && !delegate_->IsLoading()) {
992 delegate_->GetNavigationController().DiscardNonCommittedEntries();
993 view_->Update();
996 // When using the origin chip, hitting escape to revert all should either
997 // display the URL (when search term replacement would not be performed for
998 // this page) or the search terms (when it would). To accomplish this,
999 // we'll need to disable URL replacement iff it's currently enabled and
1000 // search term replacement wouldn't normally happen.
1001 bool should_disable_url_replacement =
1002 controller_->GetToolbarModel()->url_replacement_enabled() &&
1003 !controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(true);
1005 // If the user wasn't editing, but merely had focus in the edit, allow <esc>
1006 // to be processed as an accelerator, so it can still be used to stop a load.
1007 // When the permanent text isn't all selected we still fall through to the
1008 // SelectAll() call below so users can arrow around in the text and then hit
1009 // <esc> to quickly replace all the text; this matches IE.
1010 const bool has_zero_suggest_match = match.provider &&
1011 (match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST);
1012 if (!has_zero_suggest_match && !should_disable_url_replacement &&
1013 !user_input_in_progress_ && view_->IsSelectAll())
1014 return false;
1016 if (!user_text_.empty()) {
1017 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
1018 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE,
1019 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
1022 if (should_disable_url_replacement) {
1023 controller_->GetToolbarModel()->set_url_replacement_enabled(false);
1024 UpdatePermanentText();
1026 view_->RevertWithoutResettingSearchTermReplacement();
1027 view_->SelectAll(true);
1028 return true;
1031 void OmniboxEditModel::OnControlKeyChanged(bool pressed) {
1032 if (pressed == (control_key_state_ == UP))
1033 control_key_state_ = pressed ? DOWN_WITHOUT_CHANGE : UP;
1036 void OmniboxEditModel::OnPaste() {
1037 UMA_HISTOGRAM_COUNTS("Omnibox.Paste", 1);
1038 paste_state_ = PASTING;
1041 void OmniboxEditModel::OnUpOrDownKeyPressed(int count) {
1042 // NOTE: This purposefully doesn't trigger any code that resets paste_state_.
1043 if (popup_model() && popup_model()->IsOpen()) {
1044 // The popup is open, so the user should be able to interact with it
1045 // normally.
1046 popup_model()->Move(count);
1047 return;
1050 if (!query_in_progress()) {
1051 // The popup is neither open nor working on a query already. So, start an
1052 // autocomplete query for the current text. This also sets
1053 // user_input_in_progress_ to true, which we want: if the user has started
1054 // to interact with the popup, changing the permanent_text_ shouldn't change
1055 // the displayed text.
1056 // Note: This does not force the popup to open immediately.
1057 // TODO(pkasting): We should, in fact, force this particular query to open
1058 // the popup immediately.
1059 if (!user_input_in_progress_)
1060 InternalSetUserText(permanent_text_);
1061 view_->UpdatePopup();
1062 return;
1065 // TODO(pkasting): The popup is working on a query but is not open. We should
1066 // force it to open immediately.
1069 void OmniboxEditModel::OnPopupDataChanged(
1070 const base::string16& text,
1071 GURL* destination_for_temporary_text_change,
1072 const base::string16& keyword,
1073 bool is_keyword_hint) {
1074 // The popup changed its data, the match in the controller is no longer valid.
1075 omnibox_controller_->InvalidateCurrentMatch();
1077 // Update keyword/hint-related local state.
1078 bool keyword_state_changed = (keyword_ != keyword) ||
1079 ((is_keyword_hint_ != is_keyword_hint) && !keyword.empty());
1080 if (keyword_state_changed) {
1081 keyword_ = keyword;
1082 is_keyword_hint_ = is_keyword_hint;
1084 // |is_keyword_hint_| should always be false if |keyword_| is empty.
1085 DCHECK(!keyword_.empty() || !is_keyword_hint_);
1088 // Handle changes to temporary text.
1089 if (destination_for_temporary_text_change != NULL) {
1090 const bool save_original_selection = !has_temporary_text_;
1091 if (save_original_selection) {
1092 // Save the original selection and URL so it can be reverted later.
1093 has_temporary_text_ = true;
1094 original_url_ = *destination_for_temporary_text_change;
1095 inline_autocomplete_text_.clear();
1096 view_->OnInlineAutocompleteTextCleared();
1098 if (control_key_state_ == DOWN_WITHOUT_CHANGE) {
1099 // Arrowing around the popup cancels control-enter.
1100 control_key_state_ = DOWN_WITH_CHANGE;
1101 // Now things are a bit screwy: the desired_tld has changed, but if we
1102 // update the popup, the new order of entries won't match the old, so the
1103 // user's selection gets screwy; and if we don't update the popup, and the
1104 // user reverts, then the selected item will be as if control is still
1105 // pressed, even though maybe it isn't any more. There is no obvious
1106 // right answer here :(
1108 view_->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text),
1109 save_original_selection, true);
1110 return;
1113 bool call_controller_onchanged = true;
1114 inline_autocomplete_text_ = text;
1115 if (inline_autocomplete_text_.empty())
1116 view_->OnInlineAutocompleteTextCleared();
1118 const base::string16& user_text =
1119 user_input_in_progress_ ? user_text_ : permanent_text_;
1120 if (keyword_state_changed && is_keyword_selected()) {
1121 // If we reach here, the user most likely entered keyword mode by inserting
1122 // a space between a keyword name and a search string (as pressing space or
1123 // tab after the keyword name alone would have been be handled in
1124 // MaybeAcceptKeywordBySpace() by calling AcceptKeyword(), which won't reach
1125 // here). In this case, we don't want to call
1126 // OnInlineAutocompleteTextMaybeChanged() as normal, because that will
1127 // correctly change the text (to the search string alone) but move the caret
1128 // to the end of the string; instead we want the caret at the start of the
1129 // search string since that's where it was in the original input. So we set
1130 // the text and caret position directly.
1132 // It may also be possible to reach here if we're reverting from having
1133 // temporary text back to a default match that's a keyword search, but in
1134 // that case the RevertTemporaryText() call below will reset the caret or
1135 // selection correctly so the caret positioning we do here won't matter.
1136 view_->SetWindowTextAndCaretPos(DisplayTextFromUserText(user_text), 0,
1137 false, false);
1138 } else if (view_->OnInlineAutocompleteTextMaybeChanged(
1139 DisplayTextFromUserText(user_text + inline_autocomplete_text_),
1140 DisplayTextFromUserText(user_text).length())) {
1141 call_controller_onchanged = false;
1144 // If |has_temporary_text_| is true, then we previously had a manual selection
1145 // but now don't (or |destination_for_temporary_text_change| would have been
1146 // non-NULL). This can happen when deleting the selected item in the popup.
1147 // In this case, we've already reverted the popup to the default match, so we
1148 // need to revert ourselves as well.
1149 if (has_temporary_text_) {
1150 RevertTemporaryText(false);
1151 call_controller_onchanged = false;
1154 // We need to invoke OnChanged in case the destination url changed (as could
1155 // happen when control is toggled).
1156 if (call_controller_onchanged)
1157 OnChanged();
1160 bool OmniboxEditModel::OnAfterPossibleChange(const base::string16& old_text,
1161 const base::string16& new_text,
1162 size_t selection_start,
1163 size_t selection_end,
1164 bool selection_differs,
1165 bool text_differs,
1166 bool just_deleted_text,
1167 bool allow_keyword_ui_change) {
1168 // Update the paste state as appropriate: if we're just finishing a paste
1169 // that replaced all the text, preserve that information; otherwise, if we've
1170 // made some other edit, clear paste tracking.
1171 if (paste_state_ == PASTING)
1172 paste_state_ = PASTED;
1173 else if (text_differs)
1174 paste_state_ = NONE;
1176 if (text_differs || selection_differs) {
1177 // Record current focus state for this input if we haven't already.
1178 if (focus_source_ == INVALID) {
1179 // We should generally expect the omnibox to have focus at this point, but
1180 // it doesn't always on Linux. This is because, unlike other platforms,
1181 // right clicking in the omnibox on Linux doesn't focus it. So pasting via
1182 // right-click can change the contents without focusing the omnibox.
1183 // TODO(samarth): fix Linux focus behavior and add a DCHECK here to
1184 // check that the omnibox does have focus.
1185 focus_source_ = (focus_state_ == OMNIBOX_FOCUS_INVISIBLE) ?
1186 FAKEBOX : OMNIBOX;
1189 // Restore caret visibility whenever the user changes text or selection in
1190 // the omnibox.
1191 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_TYPING);
1194 // Modifying the selection counts as accepting the autocompleted text.
1195 const bool user_text_changed =
1196 text_differs || (selection_differs && !inline_autocomplete_text_.empty());
1198 // If something has changed while the control key is down, prevent
1199 // "ctrl-enter" until the control key is released.
1200 if ((text_differs || selection_differs) &&
1201 (control_key_state_ == DOWN_WITHOUT_CHANGE))
1202 control_key_state_ = DOWN_WITH_CHANGE;
1204 if (!user_text_changed)
1205 return false;
1207 // If the user text has not changed, we do not want to change the model's
1208 // state associated with the text. Otherwise, we can get surprising behavior
1209 // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983
1210 InternalSetUserText(UserTextFromDisplayText(new_text));
1211 has_temporary_text_ = false;
1213 // Track when the user has deleted text so we won't allow inline
1214 // autocomplete.
1215 just_deleted_text_ = just_deleted_text;
1217 if (user_input_in_progress_ && user_text_.empty()) {
1218 // Log cases where the user started editing and then subsequently cleared
1219 // all the text. Note that this explicitly doesn't catch cases like
1220 // "hit ctrl-l to select whole edit contents, then hit backspace", because
1221 // in such cases, |user_input_in_progress| won't be true here.
1222 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
1223 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING,
1224 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
1227 const bool no_selection = selection_start == selection_end;
1229 // Update the popup for the change, in the process changing to keyword mode
1230 // if the user hit space in mid-string after a keyword.
1231 // |allow_exact_keyword_match_| will be used by StartAutocomplete() method,
1232 // which will be called by |view_->UpdatePopup()|; so after that returns we
1233 // can safely reset this flag.
1234 allow_exact_keyword_match_ = text_differs && allow_keyword_ui_change &&
1235 !just_deleted_text && no_selection &&
1236 CreatedKeywordSearchByInsertingSpaceInMiddle(old_text, user_text_,
1237 selection_start);
1238 view_->UpdatePopup();
1239 if (allow_exact_keyword_match_) {
1240 view_->UpdatePlaceholderText();
1241 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram,
1242 ENTERED_KEYWORD_MODE_VIA_SPACE_IN_MIDDLE,
1243 ENTERED_KEYWORD_MODE_NUM_ITEMS);
1244 allow_exact_keyword_match_ = false;
1247 // Change to keyword mode if the user is now pressing space after a keyword
1248 // name. Note that if this is the case, then even if there was no keyword
1249 // hint when we entered this function (e.g. if the user has used space to
1250 // replace some selected text that was adjoined to this keyword), there will
1251 // be one now because of the call to UpdatePopup() above; so it's safe for
1252 // MaybeAcceptKeywordBySpace() to look at |keyword_| and |is_keyword_hint_| to
1253 // determine what keyword, if any, is applicable.
1255 // If MaybeAcceptKeywordBySpace() accepts the keyword and returns true, that
1256 // will have updated our state already, so in that case we don't also return
1257 // true from this function.
1258 return !(text_differs && allow_keyword_ui_change && !just_deleted_text &&
1259 no_selection && (selection_start == user_text_.length()) &&
1260 MaybeAcceptKeywordBySpace(user_text_));
1263 // TODO(beaudoin): Merge OnPopupDataChanged with this method once the popup
1264 // handling has completely migrated to omnibox_controller.
1265 void OmniboxEditModel::OnCurrentMatchChanged() {
1266 has_temporary_text_ = false;
1268 const AutocompleteMatch& match = omnibox_controller_->current_match();
1270 // We store |keyword| and |is_keyword_hint| in temporary variables since
1271 // OnPopupDataChanged use their previous state to detect changes.
1272 base::string16 keyword;
1273 bool is_keyword_hint;
1274 TemplateURLService* service =
1275 TemplateURLServiceFactory::GetForProfile(profile_);
1276 match.GetKeywordUIState(service, &keyword, &is_keyword_hint);
1277 if (popup_model())
1278 popup_model()->OnResultChanged();
1279 // OnPopupDataChanged() resets OmniboxController's |current_match_| early
1280 // on. Therefore, copy match.inline_autocompletion to a temp to preserve
1281 // its value across the entire call.
1282 const base::string16 inline_autocompletion(match.inline_autocompletion);
1283 OnPopupDataChanged(inline_autocompletion, NULL, keyword, is_keyword_hint);
1286 void OmniboxEditModel::SetSuggestionToPrefetch(
1287 const InstantSuggestion& suggestion) {
1288 delegate_->SetSuggestionToPrefetch(suggestion);
1291 // static
1292 const char OmniboxEditModel::kCutOrCopyAllTextHistogram[] =
1293 "Omnibox.CutOrCopyAllText";
1295 bool OmniboxEditModel::query_in_progress() const {
1296 return !autocomplete_controller()->done();
1299 void OmniboxEditModel::InternalSetUserText(const base::string16& text) {
1300 user_text_ = text;
1301 just_deleted_text_ = false;
1302 inline_autocomplete_text_.clear();
1303 view_->OnInlineAutocompleteTextCleared();
1306 void OmniboxEditModel::ClearPopupKeywordMode() const {
1307 omnibox_controller_->ClearPopupKeywordMode();
1310 base::string16 OmniboxEditModel::DisplayTextFromUserText(
1311 const base::string16& text) const {
1312 return is_keyword_selected() ?
1313 KeywordProvider::SplitReplacementStringFromInput(text, false) : text;
1316 base::string16 OmniboxEditModel::UserTextFromDisplayText(
1317 const base::string16& text) const {
1318 return is_keyword_selected() ? (keyword_ + base::char16(' ') + text) : text;
1321 void OmniboxEditModel::GetInfoForCurrentText(AutocompleteMatch* match,
1322 GURL* alternate_nav_url) const {
1323 DCHECK(match != NULL);
1325 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(
1326 false)) {
1327 // Any time the user hits enter on the unchanged omnibox, we should reload.
1328 // When we're not extracting search terms, AcceptInput() will take care of
1329 // this (see code referring to PAGE_TRANSITION_RELOAD there), but when we're
1330 // extracting search terms, the conditionals there won't fire, so we
1331 // explicitly set up a match that will reload here.
1333 // It's important that we fetch the current visible URL to reload instead of
1334 // just getting a "search what you typed" URL from
1335 // SearchProvider::CreateSearchSuggestion(), since the user may be in a
1336 // non-default search mode such as image search.
1337 match->type = AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED;
1338 match->provider = autocomplete_controller()->search_provider();
1339 match->destination_url =
1340 delegate_->GetNavigationController().GetVisibleEntry()->GetURL();
1341 match->transition = ui::PAGE_TRANSITION_RELOAD;
1342 } else if (query_in_progress() ||
1343 (popup_model() && popup_model()->IsOpen())) {
1344 if (query_in_progress()) {
1345 // It's technically possible for |result| to be empty if no provider
1346 // returns a synchronous result but the query has not completed
1347 // synchronously; pratically, however, that should never actually happen.
1348 if (result().empty())
1349 return;
1350 // The user cannot have manually selected a match, or the query would have
1351 // stopped. So the default match must be the desired selection.
1352 *match = *result().default_match();
1353 } else {
1354 // If there are no results, the popup should be closed, so we shouldn't
1355 // have gotten here.
1356 CHECK(!result().empty());
1357 CHECK(popup_model()->selected_line() < result().size());
1358 *match = result().match_at(popup_model()->selected_line());
1360 if (alternate_nav_url &&
1361 (!popup_model() || popup_model()->manually_selected_match().empty()))
1362 *alternate_nav_url = result().alternate_nav_url();
1363 } else {
1364 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
1365 UserTextFromDisplayText(view_->GetText()), is_keyword_selected(), true,
1366 ClassifyPage(), match, alternate_nav_url);
1370 void OmniboxEditModel::RevertTemporaryText(bool revert_popup) {
1371 // The user typed something, then selected a different item. Restore the
1372 // text they typed and change back to the default item.
1373 // NOTE: This purposefully does not reset paste_state_.
1374 just_deleted_text_ = false;
1375 has_temporary_text_ = false;
1377 if (revert_popup && popup_model())
1378 popup_model()->ResetToDefaultMatch();
1379 view_->OnRevertTemporaryText();
1382 bool OmniboxEditModel::MaybeAcceptKeywordBySpace(
1383 const base::string16& new_text) {
1384 size_t keyword_length = new_text.length() - 1;
1385 return (paste_state_ == NONE) && is_keyword_hint_ && !keyword_.empty() &&
1386 inline_autocomplete_text_.empty() &&
1387 (keyword_.length() == keyword_length) &&
1388 IsSpaceCharForAcceptingKeyword(new_text[keyword_length]) &&
1389 !new_text.compare(0, keyword_length, keyword_, 0, keyword_length) &&
1390 AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_SPACE_AT_END);
1393 bool OmniboxEditModel::CreatedKeywordSearchByInsertingSpaceInMiddle(
1394 const base::string16& old_text,
1395 const base::string16& new_text,
1396 size_t caret_position) const {
1397 DCHECK_GE(new_text.length(), caret_position);
1399 // Check simple conditions first.
1400 if ((paste_state_ != NONE) || (caret_position < 2) ||
1401 (old_text.length() < caret_position) ||
1402 (new_text.length() == caret_position))
1403 return false;
1404 size_t space_position = caret_position - 1;
1405 if (!IsSpaceCharForAcceptingKeyword(new_text[space_position]) ||
1406 IsWhitespace(new_text[space_position - 1]) ||
1407 new_text.compare(0, space_position, old_text, 0, space_position) ||
1408 !new_text.compare(space_position, new_text.length() - space_position,
1409 old_text, space_position,
1410 old_text.length() - space_position)) {
1411 return false;
1414 // Then check if the text before the inserted space matches a keyword.
1415 base::string16 keyword;
1416 base::TrimWhitespace(new_text.substr(0, space_position), base::TRIM_LEADING,
1417 &keyword);
1418 return !keyword.empty() && !autocomplete_controller()->keyword_provider()->
1419 GetKeywordForText(keyword).empty();
1422 // static
1423 bool OmniboxEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c) {
1424 switch (c) {
1425 case 0x0020: // Space
1426 case 0x3000: // Ideographic Space
1427 return true;
1428 default:
1429 return false;
1433 OmniboxEventProto::PageClassification OmniboxEditModel::ClassifyPage() const {
1434 if (!delegate_->CurrentPageExists())
1435 return OmniboxEventProto::OTHER;
1436 if (delegate_->IsInstantNTP()) {
1437 // Note that we treat OMNIBOX as the source if focus_source_ is INVALID,
1438 // i.e., if input isn't actually in progress.
1439 return (focus_source_ == FAKEBOX) ?
1440 OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS :
1441 OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS;
1443 const GURL& gurl = delegate_->GetURL();
1444 if (!gurl.is_valid())
1445 return OmniboxEventProto::INVALID_SPEC;
1446 const std::string& url = gurl.spec();
1447 if (url == chrome::kChromeUINewTabURL)
1448 return OmniboxEventProto::NTP;
1449 if (url == url::kAboutBlankURL)
1450 return OmniboxEventProto::BLANK;
1451 if (url == profile()->GetPrefs()->GetString(prefs::kHomePage))
1452 return OmniboxEventProto::HOME_PAGE;
1453 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(true))
1454 return OmniboxEventProto::SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT;
1455 if (delegate_->IsSearchResultsPage())
1456 return OmniboxEventProto::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT;
1457 return OmniboxEventProto::OTHER;
1460 void OmniboxEditModel::ClassifyStringForPasteAndGo(
1461 const base::string16& text,
1462 AutocompleteMatch* match,
1463 GURL* alternate_nav_url) const {
1464 DCHECK(match);
1465 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
1466 text, false, false, ClassifyPage(), match, alternate_nav_url);
1469 void OmniboxEditModel::SetFocusState(OmniboxFocusState state,
1470 OmniboxFocusChangeReason reason) {
1471 if (state == focus_state_)
1472 return;
1474 // Update state and notify view if the omnibox has focus and the caret
1475 // visibility changed.
1476 const bool was_caret_visible = is_caret_visible();
1477 focus_state_ = state;
1478 if (focus_state_ != OMNIBOX_FOCUS_NONE &&
1479 is_caret_visible() != was_caret_visible)
1480 view_->ApplyCaretVisibility();
1482 delegate_->OnFocusChanged(focus_state_, reason);