Revert of Add button to add new FSP services to Files app. (patchset #8 id:140001...
[chromium-blink-merge.git] / chrome / browser / ui / omnibox / omnibox_edit_model.cc
blobb5bb65d2ac1709ca96816ba0484b95acb017ab02
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/profiler/scoped_tracker.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "chrome/app/chrome_command_ids.h"
20 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
21 #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
22 #include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
23 #include "chrome/browser/autocomplete/history_url_provider.h"
24 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
25 #include "chrome/browser/bookmarks/bookmark_stats.h"
26 #include "chrome/browser/chrome_notification_types.h"
27 #include "chrome/browser/command_updater.h"
28 #include "chrome/browser/extensions/api/omnibox/omnibox_api.h"
29 #include "chrome/browser/favicon/favicon_tab_helper.h"
30 #include "chrome/browser/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/metrics/proto/omnibox_event.pb.h"
57 #include "components/omnibox/autocomplete_provider.h"
58 #include "components/omnibox/keyword_provider.h"
59 #include "components/omnibox/search_provider.h"
60 #include "components/search_engines/template_url.h"
61 #include "components/search_engines/template_url_prepopulate_data.h"
62 #include "components/search_engines/template_url_service.h"
63 #include "components/url_fixer/url_fixer.h"
64 #include "content/public/browser/navigation_controller.h"
65 #include "content/public/browser/navigation_entry.h"
66 #include "content/public/browser/notification_service.h"
67 #include "content/public/browser/render_view_host.h"
68 #include "content/public/browser/user_metrics.h"
69 #include "extensions/common/constants.h"
70 #include "ui/gfx/image/image.h"
71 #include "url/url_util.h"
73 using bookmarks::BookmarkModel;
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 permanent_text_ = controller_->GetToolbarModel()->GetText();
261 // Don't muck with the search term replacement state, as we've just set it
262 // correctly.
263 view_->RevertWithoutResettingSearchTermReplacement();
264 // Restore the autocomplete controller's input, or clear it if this is a new
265 // tab.
266 input_ = state ? state->autocomplete_input : AutocompleteInput();
267 if (!state)
268 return;
270 SetFocusState(state->focus_state, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH);
271 focus_source_ = state->focus_source;
272 // Restore any user editing.
273 if (state->user_input_in_progress) {
274 // NOTE: Be sure and set keyword-related state BEFORE invoking
275 // DisplayTextFromUserText(), as its result depends upon this state.
276 keyword_ = state->keyword;
277 is_keyword_hint_ = state->is_keyword_hint;
278 view_->SetUserText(state->user_text,
279 DisplayTextFromUserText(state->user_text), false);
280 view_->SetGrayTextAutocompletion(state->gray_text);
284 AutocompleteMatch OmniboxEditModel::CurrentMatch(
285 GURL* alternate_nav_url) const {
286 // If we have a valid match use it. Otherwise get one for the current text.
287 AutocompleteMatch match = omnibox_controller_->current_match();
289 if (!match.destination_url.is_valid()) {
290 GetInfoForCurrentText(&match, alternate_nav_url);
291 } else if (alternate_nav_url) {
292 *alternate_nav_url = AutocompleteResult::ComputeAlternateNavUrl(
293 input_, match);
295 return match;
298 bool OmniboxEditModel::UpdatePermanentText() {
299 SearchProvider* search_provider =
300 autocomplete_controller()->search_provider();
301 if (search_provider && delegate_->CurrentPageExists())
302 search_provider->set_current_page_url(delegate_->GetURL());
304 // When there's new permanent text, and the user isn't interacting with the
305 // omnibox, we want to revert the edit to show the new text. We could simply
306 // define "interacting" as "the omnibox has focus", but we still allow updates
307 // when the omnibox has focus as long as the user hasn't begun editing, isn't
308 // seeing zerosuggestions (because changing this text would require changing
309 // or hiding those suggestions), and hasn't toggled on "Show URL" (because
310 // this update will re-enable search term replacement, which will be annoying
311 // if the user is trying to copy the URL). When the omnibox doesn't have
312 // focus, we assume the user may have abandoned their interaction and it's
313 // always safe to change the text; this also prevents someone toggling "Show
314 // URL" (which sounds as if it might be persistent) from seeing just that URL
315 // forever afterwards.
317 // If the page is auto-committing gray text, however, we generally don't want
318 // to make any change to the edit. While auto-commits modify the underlying
319 // permanent URL, they're intended to have no effect on the user's editing
320 // process -- before and after the auto-commit, the omnibox should show the
321 // same user text and the same instant suggestion, even if the auto-commit
322 // happens while the edit doesn't have focus.
323 base::string16 new_permanent_text = controller_->GetToolbarModel()->GetText();
324 base::string16 gray_text = view_->GetGrayTextAutocompletion();
325 const bool visibly_changed_permanent_text =
326 (permanent_text_ != new_permanent_text) &&
327 (!has_focus() ||
328 (!user_input_in_progress_ &&
329 !(popup_model() && popup_model()->IsOpen()) &&
330 controller_->GetToolbarModel()->url_replacement_enabled())) &&
331 (gray_text.empty() ||
332 new_permanent_text != user_text_ + gray_text);
334 permanent_text_ = new_permanent_text;
335 return visibly_changed_permanent_text;
338 GURL OmniboxEditModel::PermanentURL() {
339 return url_fixer::FixupURL(base::UTF16ToUTF8(permanent_text_), std::string());
342 void OmniboxEditModel::SetUserText(const base::string16& text) {
343 SetInputInProgress(true);
344 InternalSetUserText(text);
345 omnibox_controller_->InvalidateCurrentMatch();
346 paste_state_ = NONE;
347 has_temporary_text_ = false;
350 bool OmniboxEditModel::CommitSuggestedText() {
351 const base::string16 suggestion = view_->GetGrayTextAutocompletion();
352 if (suggestion.empty())
353 return false;
355 const base::string16 final_text = view_->GetText() + suggestion;
356 view_->OnBeforePossibleChange();
357 view_->SetWindowTextAndCaretPos(final_text, final_text.length(), false,
358 false);
359 view_->OnAfterPossibleChange();
360 return true;
363 void OmniboxEditModel::OnChanged() {
364 // Don't call CurrentMatch() when there's no editing, as in this case we'll
365 // never actually use it. This avoids running the autocomplete providers (and
366 // any systems they then spin up) during startup.
367 const AutocompleteMatch& current_match = user_input_in_progress_ ?
368 CurrentMatch(NULL) : AutocompleteMatch();
370 AutocompleteActionPredictor::Action recommended_action =
371 AutocompleteActionPredictor::ACTION_NONE;
372 if (user_input_in_progress_) {
373 InstantSearchPrerenderer* prerenderer =
374 InstantSearchPrerenderer::GetForProfile(profile_);
375 if (prerenderer &&
376 prerenderer->IsAllowed(current_match, controller_->GetWebContents()) &&
377 popup_model()->IsOpen() && has_focus()) {
378 recommended_action = AutocompleteActionPredictor::ACTION_PRERENDER;
379 } else {
380 AutocompleteActionPredictor* action_predictor =
381 predictors::AutocompleteActionPredictorFactory::GetForProfile(
382 profile_);
383 action_predictor->RegisterTransitionalMatches(user_text_, result());
384 // Confer with the AutocompleteActionPredictor to determine what action,
385 // if any, we should take. Get the recommended action here even if we
386 // don't need it so we can get stats for anyone who is opted in to UMA,
387 // but only get it if the user has actually typed something to avoid
388 // constructing it before it's needed. Note: This event is triggered as
389 // part of startup when the initial tab transitions to the start page.
390 recommended_action =
391 action_predictor->RecommendAction(user_text_, current_match);
395 UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.Action",
396 recommended_action,
397 AutocompleteActionPredictor::LAST_PREDICT_ACTION);
399 // Hide any suggestions we might be showing.
400 view_->SetGrayTextAutocompletion(base::string16());
402 switch (recommended_action) {
403 case AutocompleteActionPredictor::ACTION_PRERENDER:
404 // It's possible that there is no current page, for instance if the tab
405 // has been closed or on return from a sleep state.
406 // (http://crbug.com/105689)
407 if (!delegate_->CurrentPageExists())
408 break;
409 // Ask for prerendering if the destination URL is different than the
410 // current URL.
411 if (current_match.destination_url != delegate_->GetURL())
412 delegate_->DoPrerender(current_match);
413 break;
414 case AutocompleteActionPredictor::ACTION_PRECONNECT:
415 omnibox_controller_->DoPreconnect(current_match);
416 break;
417 case AutocompleteActionPredictor::ACTION_NONE:
418 break;
421 controller_->OnChanged();
424 void OmniboxEditModel::GetDataForURLExport(GURL* url,
425 base::string16* title,
426 gfx::Image* favicon) {
427 *url = CurrentMatch(NULL).destination_url;
428 if (*url == delegate_->GetURL()) {
429 content::WebContents* web_contents = controller_->GetWebContents();
430 *title = web_contents->GetTitle();
431 *favicon = FaviconTabHelper::FromWebContents(web_contents)->GetFavicon();
435 bool OmniboxEditModel::CurrentTextIsURL() const {
436 if (controller_->GetToolbarModel()->WouldReplaceURL())
437 return false;
439 // If current text is not composed of replaced search terms and
440 // !user_input_in_progress_, then permanent text is showing and should be a
441 // URL, so no further checking is needed. By avoiding checking in this case,
442 // we avoid calling into the autocomplete providers, and thus initializing the
443 // history system, as long as possible, which speeds startup.
444 if (!user_input_in_progress_)
445 return true;
447 return !AutocompleteMatch::IsSearchType(CurrentMatch(NULL).type);
450 AutocompleteMatch::Type OmniboxEditModel::CurrentTextType() const {
451 return CurrentMatch(NULL).type;
454 void OmniboxEditModel::AdjustTextForCopy(int sel_min,
455 bool is_all_selected,
456 base::string16* text,
457 GURL* url,
458 bool* write_url) {
459 *write_url = false;
461 // Do not adjust if selection did not start at the beginning of the field, or
462 // if the URL was omitted.
463 if ((sel_min != 0) || controller_->GetToolbarModel()->WouldReplaceURL())
464 return;
466 if (!user_input_in_progress_ && is_all_selected) {
467 // The user selected all the text and has not edited it. Use the url as the
468 // text so that if the scheme was stripped it's added back, and the url
469 // is unescaped (we escape parts of the url for display).
470 *url = PermanentURL();
471 *text = base::UTF8ToUTF16(url->spec());
472 *write_url = true;
473 return;
476 // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now
477 // the user is probably holding down control to cause the copy, which will
478 // screw up our calculation of the desired_tld.
479 AutocompleteMatch match;
480 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
481 *text, is_keyword_selected(), true, ClassifyPage(), &match, NULL);
482 if (AutocompleteMatch::IsSearchType(match.type))
483 return;
484 *url = match.destination_url;
486 // Prefix the text with 'http://' if the text doesn't start with 'http://',
487 // the text parses as a url with a scheme of http, the user selected the
488 // entire host, and the user hasn't edited the host or manually removed the
489 // scheme.
490 GURL perm_url(PermanentURL());
491 if (perm_url.SchemeIs(url::kHttpScheme) &&
492 url->SchemeIs(url::kHttpScheme) && perm_url.host() == url->host()) {
493 *write_url = true;
494 base::string16 http = base::ASCIIToUTF16(url::kHttpScheme) +
495 base::ASCIIToUTF16(url::kStandardSchemeSeparator);
496 if (text->compare(0, http.length(), http) != 0)
497 *text = http + *text;
501 void OmniboxEditModel::SetInputInProgress(bool in_progress) {
502 if (in_progress && !user_input_since_focus_) {
503 base::TimeTicks now = base::TimeTicks::Now();
504 DCHECK(last_omnibox_focus_ <= now);
505 UMA_HISTOGRAM_TIMES(kFocusToEditTimeHistogram, now - last_omnibox_focus_);
506 user_input_since_focus_ = true;
509 if (user_input_in_progress_ == in_progress)
510 return;
512 user_input_in_progress_ = in_progress;
513 if (user_input_in_progress_) {
514 time_user_first_modified_omnibox_ = base::TimeTicks::Now();
515 content::RecordAction(base::UserMetricsAction("OmniboxInputInProgress"));
516 autocomplete_controller()->ResetSession();
519 controller_->GetToolbarModel()->set_input_in_progress(in_progress);
520 controller_->Update(NULL);
522 if (user_input_in_progress_ || !in_revert_)
523 delegate_->OnInputStateChanged();
526 void OmniboxEditModel::Revert() {
527 SetInputInProgress(false);
528 paste_state_ = NONE;
529 InternalSetUserText(base::string16());
530 keyword_.clear();
531 is_keyword_hint_ = false;
532 has_temporary_text_ = false;
533 view_->SetWindowTextAndCaretPos(permanent_text_,
534 has_focus() ? permanent_text_.length() : 0,
535 false, true);
536 AutocompleteActionPredictor* action_predictor =
537 predictors::AutocompleteActionPredictorFactory::GetForProfile(profile_);
538 action_predictor->ClearTransitionalMatches();
539 action_predictor->CancelPrerender();
542 void OmniboxEditModel::StartAutocomplete(
543 bool has_selected_text,
544 bool prevent_inline_autocomplete) {
545 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
546 tracked_objects::ScopedTracker tracking_profile(
547 FROM_HERE_WITH_EXPLICIT_FUNCTION(
548 "440919 OmniboxEditModel::StartAutocomplete"));
549 size_t cursor_position;
550 if (inline_autocomplete_text_.empty()) {
551 // Cursor position is equivalent to the current selection's end.
552 size_t start;
553 view_->GetSelectionBounds(&start, &cursor_position);
554 // Adjust cursor position taking into account possible keyword in the user
555 // text. We rely on DisplayTextFromUserText() method which is consistent
556 // with keyword extraction done in KeywordProvider/SearchProvider.
557 const size_t cursor_offset =
558 user_text_.length() - DisplayTextFromUserText(user_text_).length();
559 cursor_position += cursor_offset;
560 } else {
561 // There are some cases where StartAutocomplete() may be called
562 // with non-empty |inline_autocomplete_text_|. In such cases, we cannot
563 // use the current selection, because it could result with the cursor
564 // position past the last character from the user text. Instead,
565 // we assume that the cursor is simply at the end of input.
566 // One example is when user presses Ctrl key while having a highlighted
567 // inline autocomplete text.
568 // TODO: Rethink how we are going to handle this case to avoid
569 // inconsistent behavior when user presses Ctrl key.
570 // See http://crbug.com/165961 and http://crbug.com/165968 for more details.
571 cursor_position = user_text_.length();
574 GURL current_url =
575 (delegate_->CurrentPageExists() && view_->IsIndicatingQueryRefinement()) ?
576 delegate_->GetURL() : GURL();
577 input_ = AutocompleteInput(
578 user_text_, cursor_position, std::string(), current_url, ClassifyPage(),
579 prevent_inline_autocomplete || just_deleted_text_ ||
580 (has_selected_text && inline_autocomplete_text_.empty()) ||
581 (paste_state_ != NONE),
582 is_keyword_selected(),
583 is_keyword_selected() || allow_exact_keyword_match_,
584 true, ChromeAutocompleteSchemeClassifier(profile_));
586 omnibox_controller_->StartAutocomplete(input_);
589 void OmniboxEditModel::StopAutocomplete() {
590 autocomplete_controller()->Stop(true);
593 bool OmniboxEditModel::CanPasteAndGo(const base::string16& text) const {
594 if (!view_->command_updater()->IsCommandEnabled(IDC_OPEN_CURRENT_URL))
595 return false;
597 AutocompleteMatch match;
598 ClassifyStringForPasteAndGo(text, &match, NULL);
599 return match.destination_url.is_valid();
602 void OmniboxEditModel::PasteAndGo(const base::string16& text) {
603 DCHECK(CanPasteAndGo(text));
604 UMA_HISTOGRAM_COUNTS("Omnibox.PasteAndGo", 1);
606 view_->RevertAll();
607 AutocompleteMatch match;
608 GURL alternate_nav_url;
609 ClassifyStringForPasteAndGo(text, &match, &alternate_nav_url);
610 view_->OpenMatch(match, CURRENT_TAB, alternate_nav_url, text,
611 OmniboxPopupModel::kNoMatch);
614 bool OmniboxEditModel::IsPasteAndSearch(const base::string16& text) const {
615 AutocompleteMatch match;
616 ClassifyStringForPasteAndGo(text, &match, NULL);
617 return AutocompleteMatch::IsSearchType(match.type);
620 void OmniboxEditModel::AcceptInput(WindowOpenDisposition disposition,
621 bool for_drop) {
622 // Get the URL and transition type for the selected entry.
623 GURL alternate_nav_url;
624 AutocompleteMatch match = CurrentMatch(&alternate_nav_url);
626 // If CTRL is down it means the user wants to append ".com" to the text he
627 // typed. If we can successfully generate a URL_WHAT_YOU_TYPED match doing
628 // that, then we use this. These matches are marked as generated by the
629 // HistoryURLProvider so we only generate them if this provider is present.
630 if (control_key_state_ == DOWN_WITHOUT_CHANGE && !is_keyword_selected() &&
631 autocomplete_controller()->history_url_provider()) {
632 // Generate a new AutocompleteInput, copying the latest one but using "com"
633 // as the desired TLD. Then use this autocomplete input to generate a
634 // URL_WHAT_YOU_TYPED AutocompleteMatch. Note that using the most recent
635 // input instead of the currently visible text means we'll ignore any
636 // visible inline autocompletion: if a user types "foo" and is autocompleted
637 // to "foodnetwork.com", ctrl-enter will navigate to "foo.com", not
638 // "foodnetwork.com". At the time of writing, this behavior matches
639 // Internet Explorer, but not Firefox.
640 input_ = AutocompleteInput(
641 has_temporary_text_ ?
642 UserTextFromDisplayText(view_->GetText()) : input_.text(),
643 input_.cursor_position(), "com", GURL(),
644 input_.current_page_classification(),
645 input_.prevent_inline_autocomplete(), input_.prefer_keyword(),
646 input_.allow_exact_keyword_match(), input_.want_asynchronous_matches(),
647 ChromeAutocompleteSchemeClassifier(profile_));
648 AutocompleteMatch url_match(
649 autocomplete_controller()->history_url_provider()->SuggestExactInput(
650 input_.text(), input_.canonicalized_url(), false));
653 if (url_match.destination_url.is_valid()) {
654 // We have a valid URL, we use this newly generated AutocompleteMatch.
655 match = url_match;
656 alternate_nav_url = GURL();
660 if (!match.destination_url.is_valid())
661 return;
663 if ((match.transition == ui::PAGE_TRANSITION_TYPED) &&
664 (match.destination_url == PermanentURL())) {
665 // When the user hit enter on the existing permanent URL, treat it like a
666 // reload for scoring purposes. We could detect this by just checking
667 // user_input_in_progress_, but it seems better to treat "edits" that end
668 // up leaving the URL unchanged (e.g. deleting the last character and then
669 // retyping it) as reloads too. We exclude non-TYPED transitions because if
670 // the transition is GENERATED, the user input something that looked
671 // different from the current URL, even if it wound up at the same place
672 // (e.g. manually retyping the same search query), and it seems wrong to
673 // treat this as a reload.
674 match.transition = ui::PAGE_TRANSITION_RELOAD;
675 } else if (for_drop || ((paste_state_ != NONE) &&
676 match.is_history_what_you_typed_match)) {
677 // When the user pasted in a URL and hit enter, score it like a link click
678 // rather than a normal typed URL, so it doesn't get inline autocompleted
679 // as aggressively later.
680 match.transition = ui::PAGE_TRANSITION_LINK;
683 // While the user is typing, the instant search base page may be prerendered
684 // in the background. Even though certain inputs may not be eligible for
685 // prerendering, the prerender isn't automatically cancelled as the user
686 // continues typing, in hopes the final input will end up making use of the
687 // prerenderer. Intermediate inputs that are legal for prerendering will be
688 // sent to the prerendered page to keep it up to date; then once the user
689 // commits a navigation, it will trigger code in chrome::Navigate() to swap in
690 // the prerenderer.
692 // Unfortunately, that swap code only has the navigated URL, so it doesn't
693 // actually know whether the prerenderer has been sent the relevant input
694 // already, or whether instead the user manually navigated to something that
695 // looks like a search URL (which won't have been sent to the prerenderer).
696 // In this case, we need to ensure the prerenderer is cancelled here so that
697 // code can't attempt to wrongly swap-in, or it could swap in an empty page in
698 // place of the correct navigation.
700 // This would be clearer if we could swap in the prerenderer here instead of
701 // over in chrome::Navigate(), but we have to wait until then because the
702 // final decision about whether to use the prerendered page depends on other
703 // parts of the chrome::NavigateParams struct not available until then.
704 InstantSearchPrerenderer* prerenderer =
705 InstantSearchPrerenderer::GetForProfile(profile_);
706 if (prerenderer &&
707 !prerenderer->IsAllowed(match, controller_->GetWebContents()))
708 prerenderer->Cancel();
710 DCHECK(popup_model());
711 view_->OpenMatch(match, disposition, alternate_nav_url, base::string16(),
712 popup_model()->selected_line());
715 void OmniboxEditModel::OpenMatch(AutocompleteMatch match,
716 WindowOpenDisposition disposition,
717 const GURL& alternate_nav_url,
718 const base::string16& pasted_text,
719 size_t index) {
720 const base::TimeTicks& now(base::TimeTicks::Now());
721 base::TimeDelta elapsed_time_since_user_first_modified_omnibox(
722 now - time_user_first_modified_omnibox_);
723 autocomplete_controller()->UpdateMatchDestinationURLWithQueryFormulationTime(
724 elapsed_time_since_user_first_modified_omnibox, &match);
726 base::string16 input_text(pasted_text);
727 if (input_text.empty())
728 input_text = user_input_in_progress_ ? user_text_ : permanent_text_;
729 scoped_ptr<OmniboxNavigationObserver> observer(
730 new OmniboxNavigationObserver(
731 profile_, input_text, match,
732 autocomplete_controller()->history_url_provider()->SuggestExactInput(
733 input_text, alternate_nav_url,
734 AutocompleteInput::HasHTTPScheme(input_text))));
736 base::TimeDelta elapsed_time_since_last_change_to_default_match(
737 now - autocomplete_controller()->last_time_default_match_changed());
738 DCHECK(match.provider);
739 // These elapsed times don't really make sense for ZeroSuggest matches
740 // (because the user does not modify the omnibox for ZeroSuggest), so for
741 // those we set the elapsed times to something that will be ignored by
742 // metrics_log.cc. They also don't necessarily make sense if the omnibox
743 // dropdown is closed or the user used a paste-and-go action. (In most
744 // cases when this happens, the user never modified the omnibox.)
745 if ((match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST) ||
746 !popup_model()->IsOpen() || !pasted_text.empty()) {
747 const base::TimeDelta default_time_delta =
748 base::TimeDelta::FromMilliseconds(-1);
749 elapsed_time_since_user_first_modified_omnibox = default_time_delta;
750 elapsed_time_since_last_change_to_default_match = default_time_delta;
752 // If the popup is closed or this is a paste-and-go action (meaning the
753 // contents of the dropdown are ignored regardless), we record for logging
754 // purposes a selected_index of 0 and a suggestion list as having a single
755 // entry of the match used.
756 ACMatches fake_single_entry_matches;
757 fake_single_entry_matches.push_back(match);
758 AutocompleteResult fake_single_entry_result;
759 fake_single_entry_result.AppendMatches(fake_single_entry_matches);
760 OmniboxLog log(
761 input_text,
762 just_deleted_text_,
763 input_.type(),
764 popup_model()->IsOpen(),
765 (!popup_model()->IsOpen() || !pasted_text.empty()) ? 0 : index,
766 !pasted_text.empty(),
767 -1, // don't yet know tab ID; set later if appropriate
768 ClassifyPage(),
769 elapsed_time_since_user_first_modified_omnibox,
770 match.allowed_to_be_default_match ? match.inline_autocompletion.length() :
771 base::string16::npos,
772 elapsed_time_since_last_change_to_default_match,
773 (!popup_model()->IsOpen() || !pasted_text.empty()) ?
774 fake_single_entry_result : result());
775 DCHECK(!popup_model()->IsOpen() || !pasted_text.empty() ||
776 (log.elapsed_time_since_user_first_modified_omnibox >=
777 log.elapsed_time_since_last_change_to_default_match))
778 << "We should've got the notification that the user modified the "
779 << "omnibox text at same time or before the most recent time the "
780 << "default match changed.";
782 if ((disposition == CURRENT_TAB) && delegate_->CurrentPageExists()) {
783 // If we know the destination is being opened in the current tab,
784 // we can easily get the tab ID. (If it's being opened in a new
785 // tab, we don't know the tab ID yet.)
786 log.tab_id = delegate_->GetSessionID().id();
788 autocomplete_controller()->AddProvidersInfo(&log.providers_info);
789 content::NotificationService::current()->Notify(
790 chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
791 content::Source<Profile>(profile_),
792 content::Details<OmniboxLog>(&log));
793 LOCAL_HISTOGRAM_BOOLEAN("Omnibox.EventCount", true);
794 DCHECK(!last_omnibox_focus_.is_null())
795 << "An omnibox focus should have occurred before opening a match.";
796 UMA_HISTOGRAM_TIMES(kFocusToOpenTimeHistogram, now - last_omnibox_focus_);
798 TemplateURLService* service =
799 TemplateURLServiceFactory::GetForProfile(profile_);
800 TemplateURL* template_url = match.GetTemplateURL(service, false);
801 if (template_url) {
802 if (match.transition == ui::PAGE_TRANSITION_KEYWORD) {
803 // The user is using a non-substituting keyword or is explicitly in
804 // keyword mode.
806 // Don't increment usage count for extension keywords.
807 if (delegate_->ProcessExtensionKeyword(template_url, match,
808 disposition)) {
809 observer->OnSuccessfulNavigation();
810 if (disposition != NEW_BACKGROUND_TAB)
811 view_->RevertAll();
812 return;
815 content::RecordAction(base::UserMetricsAction("AcceptedKeyword"));
816 TemplateURLServiceFactory::GetForProfile(profile_)->IncrementUsageCount(
817 template_url);
818 } else {
819 DCHECK_EQ(ui::PAGE_TRANSITION_GENERATED, match.transition);
820 // NOTE: We purposefully don't increment the usage count of the default
821 // search engine here like we do for explicit keywords above; see comments
822 // in template_url.h.
825 UMA_HISTOGRAM_ENUMERATION(
826 "Omnibox.SearchEngineType",
827 TemplateURLPrepopulateData::GetEngineType(
828 *template_url, UIThreadSearchTermsData(profile_)),
829 SEARCH_ENGINE_MAX);
832 // Get the current text before we call RevertAll() which will clear it.
833 base::string16 current_text = view_->GetText();
835 if (disposition != NEW_BACKGROUND_TAB) {
836 base::AutoReset<bool> tmp(&in_revert_, true);
837 view_->RevertAll(); // Revert the box to its unedited state.
840 RecordPercentageMatchHistogram(
841 permanent_text_, current_text,
842 controller_->GetToolbarModel()->WouldReplaceURL(),
843 match.transition, view_->GetWidth());
845 // Track whether the destination URL sends us to a search results page
846 // using the default search provider.
847 if (TemplateURLServiceFactory::GetForProfile(profile_)->
848 IsSearchResultsPageFromDefaultSearchProvider(match.destination_url)) {
849 content::RecordAction(
850 base::UserMetricsAction("OmniboxDestinationURLIsSearchOnDSP"));
853 if (match.destination_url.is_valid()) {
854 // This calls RevertAll again.
855 base::AutoReset<bool> tmp(&in_revert_, true);
856 controller_->OnAutocompleteAccept(
857 match.destination_url, disposition,
858 ui::PageTransitionFromInt(
859 match.transition | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR));
860 if (observer->load_state() != OmniboxNavigationObserver::LOAD_NOT_SEEN)
861 ignore_result(observer.release()); // The observer will delete itself.
864 BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(profile_);
865 if (bookmark_model && bookmark_model->IsBookmarked(match.destination_url))
866 RecordBookmarkLaunch(NULL, BOOKMARK_LAUNCH_LOCATION_OMNIBOX);
869 bool OmniboxEditModel::AcceptKeyword(EnteredKeywordModeMethod entered_method) {
870 DCHECK(is_keyword_hint_ && !keyword_.empty());
872 autocomplete_controller()->Stop(false);
873 is_keyword_hint_ = false;
875 if (popup_model() && popup_model()->IsOpen())
876 popup_model()->SetSelectedLineState(OmniboxPopupModel::KEYWORD);
877 else
878 StartAutocomplete(false, true);
880 // Ensure the current selection is saved before showing keyword mode
881 // so that moving to another line and then reverting the text will restore
882 // the current state properly.
883 bool save_original_selection = !has_temporary_text_;
884 has_temporary_text_ = true;
885 view_->OnTemporaryTextMaybeChanged(
886 DisplayTextFromUserText(CurrentMatch(NULL).fill_into_edit),
887 save_original_selection, true);
889 view_->UpdatePlaceholderText();
891 content::RecordAction(base::UserMetricsAction("AcceptedKeywordHint"));
892 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram, entered_method,
893 ENTERED_KEYWORD_MODE_NUM_ITEMS);
895 return true;
898 void OmniboxEditModel::AcceptTemporaryTextAsUserText() {
899 InternalSetUserText(UserTextFromDisplayText(view_->GetText()));
900 has_temporary_text_ = false;
902 if (user_input_in_progress_ || !in_revert_)
903 delegate_->OnInputStateChanged();
906 void OmniboxEditModel::ClearKeyword(const base::string16& visible_text) {
907 autocomplete_controller()->Stop(false);
908 omnibox_controller_->ClearPopupKeywordMode();
910 const base::string16 window_text(keyword_ + visible_text);
912 // Only reset the result if the edit text has changed since the
913 // keyword was accepted, or if the popup is closed.
914 if (just_deleted_text_ || !visible_text.empty() ||
915 !(popup_model() && popup_model()->IsOpen())) {
916 view_->OnBeforePossibleChange();
917 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
918 false, false);
919 keyword_.clear();
920 is_keyword_hint_ = false;
921 view_->OnAfterPossibleChange();
922 just_deleted_text_ = true; // OnAfterPossibleChange() fails to clear this
923 // since the edit contents have actually grown
924 // longer.
925 } else {
926 is_keyword_hint_ = true;
927 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
928 false, true);
931 view_->UpdatePlaceholderText();
934 void OmniboxEditModel::OnSetFocus(bool control_down) {
935 last_omnibox_focus_ = base::TimeTicks::Now();
936 user_input_since_focus_ = false;
938 // If the omnibox lost focus while the caret was hidden and then regained
939 // focus, OnSetFocus() is called and should restore visibility. Note that
940 // focus can be regained without an accompanying call to
941 // OmniboxView::SetFocus(), e.g. by tabbing in.
942 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_EXPLICIT);
943 control_key_state_ = control_down ? DOWN_WITHOUT_CHANGE : UP;
945 // Try to get ZeroSuggest suggestions if a page is loaded and the user has
946 // not been typing in the omnibox. The |user_input_in_progress_| check is
947 // used to detect the case where this function is called after right-clicking
948 // in the omnibox and selecting paste in Linux (in which case we actually get
949 // the OnSetFocus() call after the process of handling the paste has kicked
950 // off).
951 // TODO(hfung): Remove this when crbug/271590 is fixed.
952 if (delegate_->CurrentPageExists() && !user_input_in_progress_) {
953 // TODO(jered): We may want to merge this into Start() and just call that
954 // here rather than having a special entry point for zero-suggest. Note
955 // that we avoid PermanentURL() here because it's not guaranteed to give us
956 // the actual underlying current URL, e.g. if we're on the NTP and the
957 // |permanent_text_| is empty.
958 autocomplete_controller()->OnOmniboxFocused(AutocompleteInput(
959 permanent_text_, base::string16::npos, std::string(),
960 delegate_->GetURL(), ClassifyPage(), false, false, true, true,
961 ChromeAutocompleteSchemeClassifier(profile_)));
964 if (user_input_in_progress_ || !in_revert_)
965 delegate_->OnInputStateChanged();
968 void OmniboxEditModel::SetCaretVisibility(bool visible) {
969 // Caret visibility only matters if the omnibox has focus.
970 if (focus_state_ != OMNIBOX_FOCUS_NONE) {
971 SetFocusState(visible ? OMNIBOX_FOCUS_VISIBLE : OMNIBOX_FOCUS_INVISIBLE,
972 OMNIBOX_FOCUS_CHANGE_EXPLICIT);
976 void OmniboxEditModel::OnWillKillFocus() {
977 if (user_input_in_progress_ || !in_revert_)
978 delegate_->OnInputStateChanged();
981 void OmniboxEditModel::OnKillFocus() {
982 SetFocusState(OMNIBOX_FOCUS_NONE, OMNIBOX_FOCUS_CHANGE_EXPLICIT);
983 focus_source_ = INVALID;
984 control_key_state_ = UP;
985 paste_state_ = NONE;
988 bool OmniboxEditModel::OnEscapeKeyPressed() {
989 const AutocompleteMatch& match = CurrentMatch(NULL);
990 if (has_temporary_text_) {
991 if (match.destination_url != original_url_) {
992 RevertTemporaryText(true);
993 return true;
997 // We do not clear the pending entry from the omnibox when a load is first
998 // stopped. If the user presses Escape while stopped, we clear it.
999 if (delegate_->CurrentPageExists() && !delegate_->IsLoading()) {
1000 delegate_->GetNavigationController().DiscardNonCommittedEntries();
1001 view_->Update();
1004 // If the user wasn't editing, but merely had focus in the edit, allow <esc>
1005 // to be processed as an accelerator, so it can still be used to stop a load.
1006 // When the permanent text isn't all selected we still fall through to the
1007 // SelectAll() call below so users can arrow around in the text and then hit
1008 // <esc> to quickly replace all the text; this matches IE.
1009 const bool has_zero_suggest_match = match.provider &&
1010 (match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST);
1011 if (!has_zero_suggest_match && !user_input_in_progress_ &&
1012 view_->IsSelectAll())
1013 return false;
1015 if (!user_text_.empty()) {
1016 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
1017 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE,
1018 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
1021 view_->RevertAll();
1022 view_->SelectAll(true);
1023 return true;
1026 void OmniboxEditModel::OnControlKeyChanged(bool pressed) {
1027 if (pressed == (control_key_state_ == UP))
1028 control_key_state_ = pressed ? DOWN_WITHOUT_CHANGE : UP;
1031 void OmniboxEditModel::OnPaste() {
1032 UMA_HISTOGRAM_COUNTS("Omnibox.Paste", 1);
1033 paste_state_ = PASTING;
1036 void OmniboxEditModel::OnUpOrDownKeyPressed(int count) {
1037 // NOTE: This purposefully doesn't trigger any code that resets paste_state_.
1038 if (popup_model() && popup_model()->IsOpen()) {
1039 // The popup is open, so the user should be able to interact with it
1040 // normally.
1041 popup_model()->Move(count);
1042 return;
1045 if (!query_in_progress()) {
1046 // The popup is neither open nor working on a query already. So, start an
1047 // autocomplete query for the current text. This also sets
1048 // user_input_in_progress_ to true, which we want: if the user has started
1049 // to interact with the popup, changing the permanent_text_ shouldn't change
1050 // the displayed text.
1051 // Note: This does not force the popup to open immediately.
1052 // TODO(pkasting): We should, in fact, force this particular query to open
1053 // the popup immediately.
1054 if (!user_input_in_progress_)
1055 InternalSetUserText(permanent_text_);
1056 view_->UpdatePopup();
1057 return;
1060 // TODO(pkasting): The popup is working on a query but is not open. We should
1061 // force it to open immediately.
1064 void OmniboxEditModel::OnPopupDataChanged(
1065 const base::string16& text,
1066 GURL* destination_for_temporary_text_change,
1067 const base::string16& keyword,
1068 bool is_keyword_hint) {
1069 // The popup changed its data, the match in the controller is no longer valid.
1070 omnibox_controller_->InvalidateCurrentMatch();
1072 // Update keyword/hint-related local state.
1073 bool keyword_state_changed = (keyword_ != keyword) ||
1074 ((is_keyword_hint_ != is_keyword_hint) && !keyword.empty());
1075 if (keyword_state_changed) {
1076 keyword_ = keyword;
1077 is_keyword_hint_ = is_keyword_hint;
1079 // |is_keyword_hint_| should always be false if |keyword_| is empty.
1080 DCHECK(!keyword_.empty() || !is_keyword_hint_);
1083 // Handle changes to temporary text.
1084 if (destination_for_temporary_text_change != NULL) {
1085 const bool save_original_selection = !has_temporary_text_;
1086 if (save_original_selection) {
1087 // Save the original selection and URL so it can be reverted later.
1088 has_temporary_text_ = true;
1089 original_url_ = *destination_for_temporary_text_change;
1090 inline_autocomplete_text_.clear();
1091 view_->OnInlineAutocompleteTextCleared();
1093 if (control_key_state_ == DOWN_WITHOUT_CHANGE) {
1094 // Arrowing around the popup cancels control-enter.
1095 control_key_state_ = DOWN_WITH_CHANGE;
1096 // Now things are a bit screwy: the desired_tld has changed, but if we
1097 // update the popup, the new order of entries won't match the old, so the
1098 // user's selection gets screwy; and if we don't update the popup, and the
1099 // user reverts, then the selected item will be as if control is still
1100 // pressed, even though maybe it isn't any more. There is no obvious
1101 // right answer here :(
1103 view_->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text),
1104 save_original_selection, true);
1105 return;
1108 bool call_controller_onchanged = true;
1109 inline_autocomplete_text_ = text;
1110 if (inline_autocomplete_text_.empty())
1111 view_->OnInlineAutocompleteTextCleared();
1113 const base::string16& user_text =
1114 user_input_in_progress_ ? user_text_ : permanent_text_;
1115 if (keyword_state_changed && is_keyword_selected()) {
1116 // If we reach here, the user most likely entered keyword mode by inserting
1117 // a space between a keyword name and a search string (as pressing space or
1118 // tab after the keyword name alone would have been be handled in
1119 // MaybeAcceptKeywordBySpace() by calling AcceptKeyword(), which won't reach
1120 // here). In this case, we don't want to call
1121 // OnInlineAutocompleteTextMaybeChanged() as normal, because that will
1122 // correctly change the text (to the search string alone) but move the caret
1123 // to the end of the string; instead we want the caret at the start of the
1124 // search string since that's where it was in the original input. So we set
1125 // the text and caret position directly.
1127 // It may also be possible to reach here if we're reverting from having
1128 // temporary text back to a default match that's a keyword search, but in
1129 // that case the RevertTemporaryText() call below will reset the caret or
1130 // selection correctly so the caret positioning we do here won't matter.
1131 view_->SetWindowTextAndCaretPos(DisplayTextFromUserText(user_text), 0,
1132 false, false);
1133 } else if (view_->OnInlineAutocompleteTextMaybeChanged(
1134 DisplayTextFromUserText(user_text + inline_autocomplete_text_),
1135 DisplayTextFromUserText(user_text).length())) {
1136 call_controller_onchanged = false;
1139 // If |has_temporary_text_| is true, then we previously had a manual selection
1140 // but now don't (or |destination_for_temporary_text_change| would have been
1141 // non-NULL). This can happen when deleting the selected item in the popup.
1142 // In this case, we've already reverted the popup to the default match, so we
1143 // need to revert ourselves as well.
1144 if (has_temporary_text_) {
1145 RevertTemporaryText(false);
1146 call_controller_onchanged = false;
1149 // We need to invoke OnChanged in case the destination url changed (as could
1150 // happen when control is toggled).
1151 if (call_controller_onchanged)
1152 OnChanged();
1155 bool OmniboxEditModel::OnAfterPossibleChange(const base::string16& old_text,
1156 const base::string16& new_text,
1157 size_t selection_start,
1158 size_t selection_end,
1159 bool selection_differs,
1160 bool text_differs,
1161 bool just_deleted_text,
1162 bool allow_keyword_ui_change) {
1163 // Update the paste state as appropriate: if we're just finishing a paste
1164 // that replaced all the text, preserve that information; otherwise, if we've
1165 // made some other edit, clear paste tracking.
1166 if (paste_state_ == PASTING)
1167 paste_state_ = PASTED;
1168 else if (text_differs)
1169 paste_state_ = NONE;
1171 if (text_differs || selection_differs) {
1172 // Record current focus state for this input if we haven't already.
1173 if (focus_source_ == INVALID) {
1174 // We should generally expect the omnibox to have focus at this point, but
1175 // it doesn't always on Linux. This is because, unlike other platforms,
1176 // right clicking in the omnibox on Linux doesn't focus it. So pasting via
1177 // right-click can change the contents without focusing the omnibox.
1178 // TODO(samarth): fix Linux focus behavior and add a DCHECK here to
1179 // check that the omnibox does have focus.
1180 focus_source_ = (focus_state_ == OMNIBOX_FOCUS_INVISIBLE) ?
1181 FAKEBOX : OMNIBOX;
1184 // Restore caret visibility whenever the user changes text or selection in
1185 // the omnibox.
1186 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_TYPING);
1189 // Modifying the selection counts as accepting the autocompleted text.
1190 const bool user_text_changed =
1191 text_differs || (selection_differs && !inline_autocomplete_text_.empty());
1193 // If something has changed while the control key is down, prevent
1194 // "ctrl-enter" until the control key is released.
1195 if ((text_differs || selection_differs) &&
1196 (control_key_state_ == DOWN_WITHOUT_CHANGE))
1197 control_key_state_ = DOWN_WITH_CHANGE;
1199 if (!user_text_changed)
1200 return false;
1202 // If the user text has not changed, we do not want to change the model's
1203 // state associated with the text. Otherwise, we can get surprising behavior
1204 // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983
1205 InternalSetUserText(UserTextFromDisplayText(new_text));
1206 has_temporary_text_ = false;
1208 // Track when the user has deleted text so we won't allow inline
1209 // autocomplete.
1210 just_deleted_text_ = just_deleted_text;
1212 if (user_input_in_progress_ && user_text_.empty()) {
1213 // Log cases where the user started editing and then subsequently cleared
1214 // all the text. Note that this explicitly doesn't catch cases like
1215 // "hit ctrl-l to select whole edit contents, then hit backspace", because
1216 // in such cases, |user_input_in_progress| won't be true here.
1217 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
1218 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING,
1219 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
1222 const bool no_selection = selection_start == selection_end;
1224 // Update the popup for the change, in the process changing to keyword mode
1225 // if the user hit space in mid-string after a keyword.
1226 // |allow_exact_keyword_match_| will be used by StartAutocomplete() method,
1227 // which will be called by |view_->UpdatePopup()|; so after that returns we
1228 // can safely reset this flag.
1229 allow_exact_keyword_match_ = text_differs && allow_keyword_ui_change &&
1230 !just_deleted_text && no_selection &&
1231 CreatedKeywordSearchByInsertingSpaceInMiddle(old_text, user_text_,
1232 selection_start);
1233 view_->UpdatePopup();
1234 if (allow_exact_keyword_match_) {
1235 view_->UpdatePlaceholderText();
1236 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram,
1237 ENTERED_KEYWORD_MODE_VIA_SPACE_IN_MIDDLE,
1238 ENTERED_KEYWORD_MODE_NUM_ITEMS);
1239 allow_exact_keyword_match_ = false;
1242 // Change to keyword mode if the user is now pressing space after a keyword
1243 // name. Note that if this is the case, then even if there was no keyword
1244 // hint when we entered this function (e.g. if the user has used space to
1245 // replace some selected text that was adjoined to this keyword), there will
1246 // be one now because of the call to UpdatePopup() above; so it's safe for
1247 // MaybeAcceptKeywordBySpace() to look at |keyword_| and |is_keyword_hint_| to
1248 // determine what keyword, if any, is applicable.
1250 // If MaybeAcceptKeywordBySpace() accepts the keyword and returns true, that
1251 // will have updated our state already, so in that case we don't also return
1252 // true from this function.
1253 return !(text_differs && allow_keyword_ui_change && !just_deleted_text &&
1254 no_selection && (selection_start == user_text_.length()) &&
1255 MaybeAcceptKeywordBySpace(user_text_));
1258 // TODO(beaudoin): Merge OnPopupDataChanged with this method once the popup
1259 // handling has completely migrated to omnibox_controller.
1260 void OmniboxEditModel::OnCurrentMatchChanged() {
1261 has_temporary_text_ = false;
1263 const AutocompleteMatch& match = omnibox_controller_->current_match();
1265 // We store |keyword| and |is_keyword_hint| in temporary variables since
1266 // OnPopupDataChanged use their previous state to detect changes.
1267 base::string16 keyword;
1268 bool is_keyword_hint;
1269 TemplateURLService* service =
1270 TemplateURLServiceFactory::GetForProfile(profile_);
1271 match.GetKeywordUIState(service, &keyword, &is_keyword_hint);
1272 if (popup_model())
1273 popup_model()->OnResultChanged();
1274 // OnPopupDataChanged() resets OmniboxController's |current_match_| early
1275 // on. Therefore, copy match.inline_autocompletion to a temp to preserve
1276 // its value across the entire call.
1277 const base::string16 inline_autocompletion(match.inline_autocompletion);
1278 OnPopupDataChanged(inline_autocompletion, NULL, keyword, is_keyword_hint);
1281 void OmniboxEditModel::SetSuggestionToPrefetch(
1282 const InstantSuggestion& suggestion) {
1283 delegate_->SetSuggestionToPrefetch(suggestion);
1286 // static
1287 const char OmniboxEditModel::kCutOrCopyAllTextHistogram[] =
1288 "Omnibox.CutOrCopyAllText";
1290 bool OmniboxEditModel::query_in_progress() const {
1291 return !autocomplete_controller()->done();
1294 void OmniboxEditModel::InternalSetUserText(const base::string16& text) {
1295 user_text_ = text;
1296 just_deleted_text_ = false;
1297 inline_autocomplete_text_.clear();
1298 view_->OnInlineAutocompleteTextCleared();
1301 void OmniboxEditModel::ClearPopupKeywordMode() const {
1302 omnibox_controller_->ClearPopupKeywordMode();
1305 base::string16 OmniboxEditModel::DisplayTextFromUserText(
1306 const base::string16& text) const {
1307 return is_keyword_selected() ?
1308 KeywordProvider::SplitReplacementStringFromInput(text, false) : text;
1311 base::string16 OmniboxEditModel::UserTextFromDisplayText(
1312 const base::string16& text) const {
1313 return is_keyword_selected() ? (keyword_ + base::char16(' ') + text) : text;
1316 void OmniboxEditModel::GetInfoForCurrentText(AutocompleteMatch* match,
1317 GURL* alternate_nav_url) const {
1318 DCHECK(match != NULL);
1320 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(
1321 false)) {
1322 // Any time the user hits enter on the unchanged omnibox, we should reload.
1323 // When we're not extracting search terms, AcceptInput() will take care of
1324 // this (see code referring to PAGE_TRANSITION_RELOAD there), but when we're
1325 // extracting search terms, the conditionals there won't fire, so we
1326 // explicitly set up a match that will reload here.
1328 // It's important that we fetch the current visible URL to reload instead of
1329 // just getting a "search what you typed" URL from
1330 // SearchProvider::CreateSearchSuggestion(), since the user may be in a
1331 // non-default search mode such as image search.
1332 match->type = AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED;
1333 match->provider = autocomplete_controller()->search_provider();
1334 match->destination_url =
1335 delegate_->GetNavigationController().GetVisibleEntry()->GetURL();
1336 match->transition = ui::PAGE_TRANSITION_RELOAD;
1337 } else if (query_in_progress() ||
1338 (popup_model() && popup_model()->IsOpen())) {
1339 if (query_in_progress()) {
1340 // It's technically possible for |result| to be empty if no provider
1341 // returns a synchronous result but the query has not completed
1342 // synchronously; pratically, however, that should never actually happen.
1343 if (result().empty())
1344 return;
1345 // The user cannot have manually selected a match, or the query would have
1346 // stopped. So the default match must be the desired selection.
1347 *match = *result().default_match();
1348 } else {
1349 // If there are no results, the popup should be closed, so we shouldn't
1350 // have gotten here.
1351 CHECK(!result().empty());
1352 CHECK(popup_model()->selected_line() < result().size());
1353 *match = result().match_at(popup_model()->selected_line());
1355 if (alternate_nav_url &&
1356 (!popup_model() || popup_model()->manually_selected_match().empty()))
1357 *alternate_nav_url = result().alternate_nav_url();
1358 } else {
1359 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
1360 UserTextFromDisplayText(view_->GetText()), is_keyword_selected(), true,
1361 ClassifyPage(), match, alternate_nav_url);
1365 void OmniboxEditModel::RevertTemporaryText(bool revert_popup) {
1366 // The user typed something, then selected a different item. Restore the
1367 // text they typed and change back to the default item.
1368 // NOTE: This purposefully does not reset paste_state_.
1369 just_deleted_text_ = false;
1370 has_temporary_text_ = false;
1372 if (revert_popup && popup_model())
1373 popup_model()->ResetToDefaultMatch();
1374 view_->OnRevertTemporaryText();
1377 bool OmniboxEditModel::MaybeAcceptKeywordBySpace(
1378 const base::string16& new_text) {
1379 size_t keyword_length = new_text.length() - 1;
1380 return (paste_state_ == NONE) && is_keyword_hint_ && !keyword_.empty() &&
1381 inline_autocomplete_text_.empty() &&
1382 (keyword_.length() == keyword_length) &&
1383 IsSpaceCharForAcceptingKeyword(new_text[keyword_length]) &&
1384 !new_text.compare(0, keyword_length, keyword_, 0, keyword_length) &&
1385 AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_SPACE_AT_END);
1388 bool OmniboxEditModel::CreatedKeywordSearchByInsertingSpaceInMiddle(
1389 const base::string16& old_text,
1390 const base::string16& new_text,
1391 size_t caret_position) const {
1392 DCHECK_GE(new_text.length(), caret_position);
1394 // Check simple conditions first.
1395 if ((paste_state_ != NONE) || (caret_position < 2) ||
1396 (old_text.length() < caret_position) ||
1397 (new_text.length() == caret_position))
1398 return false;
1399 size_t space_position = caret_position - 1;
1400 if (!IsSpaceCharForAcceptingKeyword(new_text[space_position]) ||
1401 IsWhitespace(new_text[space_position - 1]) ||
1402 new_text.compare(0, space_position, old_text, 0, space_position) ||
1403 !new_text.compare(space_position, new_text.length() - space_position,
1404 old_text, space_position,
1405 old_text.length() - space_position)) {
1406 return false;
1409 // Then check if the text before the inserted space matches a keyword.
1410 base::string16 keyword;
1411 base::TrimWhitespace(new_text.substr(0, space_position), base::TRIM_LEADING,
1412 &keyword);
1413 return !keyword.empty() && !autocomplete_controller()->keyword_provider()->
1414 GetKeywordForText(keyword).empty();
1417 // static
1418 bool OmniboxEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c) {
1419 switch (c) {
1420 case 0x0020: // Space
1421 case 0x3000: // Ideographic Space
1422 return true;
1423 default:
1424 return false;
1428 OmniboxEventProto::PageClassification OmniboxEditModel::ClassifyPage() const {
1429 if (!delegate_->CurrentPageExists())
1430 return OmniboxEventProto::OTHER;
1431 if (delegate_->IsInstantNTP()) {
1432 // Note that we treat OMNIBOX as the source if focus_source_ is INVALID,
1433 // i.e., if input isn't actually in progress.
1434 return (focus_source_ == FAKEBOX) ?
1435 OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS :
1436 OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS;
1438 const GURL& gurl = delegate_->GetURL();
1439 if (!gurl.is_valid())
1440 return OmniboxEventProto::INVALID_SPEC;
1441 const std::string& url = gurl.spec();
1442 if (url == chrome::kChromeUINewTabURL)
1443 return OmniboxEventProto::NTP;
1444 if (url == url::kAboutBlankURL)
1445 return OmniboxEventProto::BLANK;
1446 if (url == profile()->GetPrefs()->GetString(prefs::kHomePage))
1447 return OmniboxEventProto::HOME_PAGE;
1448 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(true))
1449 return OmniboxEventProto::SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT;
1450 if (delegate_->IsSearchResultsPage())
1451 return OmniboxEventProto::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT;
1452 return OmniboxEventProto::OTHER;
1455 void OmniboxEditModel::ClassifyStringForPasteAndGo(
1456 const base::string16& text,
1457 AutocompleteMatch* match,
1458 GURL* alternate_nav_url) const {
1459 DCHECK(match);
1460 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
1461 text, false, false, ClassifyPage(), match, alternate_nav_url);
1464 void OmniboxEditModel::SetFocusState(OmniboxFocusState state,
1465 OmniboxFocusChangeReason reason) {
1466 if (state == focus_state_)
1467 return;
1469 // Update state and notify view if the omnibox has focus and the caret
1470 // visibility changed.
1471 const bool was_caret_visible = is_caret_visible();
1472 focus_state_ = state;
1473 if (focus_state_ != OMNIBOX_FOCUS_NONE &&
1474 is_caret_visible() != was_caret_visible)
1475 view_->ApplyCaretVisibility();
1477 delegate_->OnFocusChanged(focus_state_, reason);