Remove unneeded includes in //chrome/browser/ui/omnibox
[chromium-blink-merge.git] / chrome / browser / ui / omnibox / omnibox_edit_model.cc
blob35564201c6cbd1867a67b4c21f678661d92be428
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_factory.h"
21 #include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
22 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
23 #include "chrome/browser/bookmarks/bookmark_stats.h"
24 #include "chrome/browser/command_updater.h"
25 #include "chrome/browser/extensions/api/omnibox/omnibox_api.h"
26 #include "chrome/browser/net/predictor.h"
27 #include "chrome/browser/predictors/autocomplete_action_predictor.h"
28 #include "chrome/browser/predictors/autocomplete_action_predictor_factory.h"
29 #include "chrome/browser/prerender/prerender_field_trial.h"
30 #include "chrome/browser/prerender/prerender_manager.h"
31 #include "chrome/browser/prerender/prerender_manager_factory.h"
32 #include "chrome/browser/profiles/profile.h"
33 #include "chrome/browser/search_engines/template_url_service_factory.h"
34 #include "chrome/browser/search_engines/ui_thread_search_terms_data.h"
35 #include "chrome/browser/ui/omnibox/chrome_omnibox_client.h"
36 #include "chrome/browser/ui/omnibox/omnibox_edit_controller.h"
37 #include "chrome/browser/ui/omnibox/omnibox_navigation_observer.h"
38 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
39 #include "chrome/browser/ui/omnibox/omnibox_view.h"
40 #include "chrome/browser/ui/search/instant_search_prerenderer.h"
41 #include "chrome/browser/ui/toolbar/toolbar_model.h"
42 #include "chrome/common/pref_names.h"
43 #include "chrome/common/url_constants.h"
44 #include "components/bookmarks/browser/bookmark_model.h"
45 #include "components/favicon/content/content_favicon_driver.h"
46 #include "components/metrics/proto/omnibox_event.pb.h"
47 #include "components/omnibox/browser/autocomplete_classifier.h"
48 #include "components/omnibox/browser/autocomplete_match_type.h"
49 #include "components/omnibox/browser/autocomplete_provider.h"
50 #include "components/omnibox/browser/history_url_provider.h"
51 #include "components/omnibox/browser/keyword_provider.h"
52 #include "components/omnibox/browser/omnibox_log.h"
53 #include "components/omnibox/browser/omnibox_popup_view.h"
54 #include "components/omnibox/browser/search_provider.h"
55 #include "components/search_engines/template_url.h"
56 #include "components/search_engines/template_url_prepopulate_data.h"
57 #include "components/search_engines/template_url_service.h"
58 #include "components/url_fixer/url_fixer.h"
59 #include "content/public/browser/navigation_controller.h"
60 #include "content/public/browser/navigation_entry.h"
61 #include "content/public/browser/user_metrics.h"
62 #include "extensions/common/constants.h"
63 #include "ui/gfx/image/image.h"
64 #include "url/url_util.h"
66 using bookmarks::BookmarkModel;
67 using metrics::OmniboxEventProto;
68 using predictors::AutocompleteActionPredictor;
71 // Helpers --------------------------------------------------------------------
73 namespace {
75 // Histogram name which counts the number of times that the user text is
76 // cleared. IME users are sometimes in the situation that IME was
77 // unintentionally turned on and failed to input latin alphabets (ASCII
78 // characters) or the opposite case. In that case, users may delete all
79 // the text and the user text gets cleared. We'd like to measure how often
80 // this scenario happens.
82 // Note that since we don't currently correlate "text cleared" events with
83 // IME usage, this also captures many other cases where users clear the text;
84 // though it explicitly doesn't log deleting all the permanent text as
85 // the first action of an editing sequence (see comments in
86 // OnAfterPossibleChange()).
87 const char kOmniboxUserTextClearedHistogram[] = "Omnibox.UserTextCleared";
89 enum UserTextClearedType {
90 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING = 0,
91 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE = 1,
92 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS,
95 // Histogram name which counts the number of times the user enters
96 // keyword hint mode and via what method. The possible values are listed
97 // in the EnteredKeywordModeMethod enum which is defined in the .h file.
98 const char kEnteredKeywordModeHistogram[] = "Omnibox.EnteredKeywordMode";
100 // Histogram name which counts the number of milliseconds a user takes
101 // between focusing and editing the omnibox.
102 const char kFocusToEditTimeHistogram[] = "Omnibox.FocusToEditTime";
104 // Histogram name which counts the number of milliseconds a user takes
105 // between focusing and opening an omnibox match.
106 const char kFocusToOpenTimeHistogram[] = "Omnibox.FocusToOpenTimeAnyPopupState";
108 // Split the percentage match histograms into buckets based on the width of the
109 // omnibox.
110 const int kPercentageMatchHistogramWidthBuckets[] = { 400, 700, 1200 };
112 void RecordPercentageMatchHistogram(const base::string16& old_text,
113 const base::string16& new_text,
114 bool url_replacement_active,
115 ui::PageTransition transition,
116 int omnibox_width) {
117 size_t avg_length = (old_text.length() + new_text.length()) / 2;
119 int percent = 0;
120 if (!old_text.empty() && !new_text.empty()) {
121 size_t shorter_length = std::min(old_text.length(), new_text.length());
122 base::string16::const_iterator end(old_text.begin() + shorter_length);
123 base::string16::const_iterator mismatch(
124 std::mismatch(old_text.begin(), end, new_text.begin()).first);
125 size_t matching_characters = mismatch - old_text.begin();
126 percent = static_cast<float>(matching_characters) / avg_length * 100;
129 std::string histogram_name;
130 if (url_replacement_active) {
131 if (transition == ui::PAGE_TRANSITION_TYPED) {
132 histogram_name = "InstantExtended.PercentageMatchV2_QuerytoURL";
133 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
134 } else {
135 histogram_name = "InstantExtended.PercentageMatchV2_QuerytoQuery";
136 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
138 } else {
139 if (transition == ui::PAGE_TRANSITION_TYPED) {
140 histogram_name = "InstantExtended.PercentageMatchV2_URLtoURL";
141 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
142 } else {
143 histogram_name = "InstantExtended.PercentageMatchV2_URLtoQuery";
144 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent);
148 std::string suffix = "large";
149 for (size_t i = 0; i < arraysize(kPercentageMatchHistogramWidthBuckets);
150 ++i) {
151 if (omnibox_width < kPercentageMatchHistogramWidthBuckets[i]) {
152 suffix = base::IntToString(kPercentageMatchHistogramWidthBuckets[i]);
153 break;
157 // Cannot rely on UMA histograms macro because the name of the histogram is
158 // generated dynamically.
159 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
160 histogram_name + "_" + suffix, 1, 101, 102,
161 base::Histogram::kUmaTargetedHistogramFlag);
162 counter->Add(percent);
165 } // namespace
168 // OmniboxEditModel::State ----------------------------------------------------
170 OmniboxEditModel::State::State(bool user_input_in_progress,
171 const base::string16& user_text,
172 const base::string16& gray_text,
173 const base::string16& keyword,
174 bool is_keyword_hint,
175 bool url_replacement_enabled,
176 OmniboxFocusState focus_state,
177 FocusSource focus_source,
178 const AutocompleteInput& autocomplete_input)
179 : user_input_in_progress(user_input_in_progress),
180 user_text(user_text),
181 gray_text(gray_text),
182 keyword(keyword),
183 is_keyword_hint(is_keyword_hint),
184 url_replacement_enabled(url_replacement_enabled),
185 focus_state(focus_state),
186 focus_source(focus_source),
187 autocomplete_input(autocomplete_input) {
190 OmniboxEditModel::State::~State() {
194 // OmniboxEditModel -----------------------------------------------------------
196 OmniboxEditModel::OmniboxEditModel(OmniboxView* view,
197 OmniboxEditController* controller,
198 Profile* profile)
199 : view_(view),
200 controller_(controller),
201 focus_state_(OMNIBOX_FOCUS_NONE),
202 focus_source_(INVALID),
203 user_input_in_progress_(false),
204 user_input_since_focus_(true),
205 just_deleted_text_(false),
206 has_temporary_text_(false),
207 paste_state_(NONE),
208 control_key_state_(UP),
209 is_keyword_hint_(false),
210 profile_(profile),
211 in_revert_(false),
212 allow_exact_keyword_match_(false) {
213 omnibox_controller_.reset(new OmniboxController(this, profile));
214 client_.reset(new ChromeOmniboxClient(controller, profile));
217 OmniboxEditModel::~OmniboxEditModel() {
220 const OmniboxEditModel::State OmniboxEditModel::GetStateForTabSwitch() {
221 // Like typing, switching tabs "accepts" the temporary text as the user
222 // text, because it makes little sense to have temporary text when the
223 // popup is closed.
224 if (user_input_in_progress_) {
225 // Weird edge case to match other browsers: if the edit is empty, revert to
226 // the permanent text (so the user can get it back easily) but select it (so
227 // on switching back, typing will "just work").
228 const base::string16 user_text(UserTextFromDisplayText(view_->GetText()));
229 if (user_text.empty()) {
230 base::AutoReset<bool> tmp(&in_revert_, true);
231 view_->RevertAll();
232 view_->SelectAll(true);
233 } else {
234 InternalSetUserText(user_text);
238 UMA_HISTOGRAM_BOOLEAN("Omnibox.SaveStateForTabSwitch.UserInputInProgress",
239 user_input_in_progress_);
240 return State(
241 user_input_in_progress_, user_text_, view_->GetGrayTextAutocompletion(),
242 keyword_, is_keyword_hint_,
243 controller_->GetToolbarModel()->url_replacement_enabled(),
244 focus_state_, focus_source_, input_);
247 void OmniboxEditModel::RestoreState(const State* state) {
248 // We need to update the permanent text correctly and revert the view
249 // regardless of whether there is saved state.
250 bool url_replacement_enabled = !state || state->url_replacement_enabled;
251 controller_->GetToolbarModel()->set_url_replacement_enabled(
252 url_replacement_enabled);
253 permanent_text_ = controller_->GetToolbarModel()->GetText();
254 // Don't muck with the search term replacement state, as we've just set it
255 // correctly.
256 view_->RevertWithoutResettingSearchTermReplacement();
257 // Restore the autocomplete controller's input, or clear it if this is a new
258 // tab.
259 input_ = state ? state->autocomplete_input : AutocompleteInput();
260 if (!state)
261 return;
263 SetFocusState(state->focus_state, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH);
264 focus_source_ = state->focus_source;
265 // Restore any user editing.
266 if (state->user_input_in_progress) {
267 // NOTE: Be sure and set keyword-related state BEFORE invoking
268 // DisplayTextFromUserText(), as its result depends upon this state.
269 keyword_ = state->keyword;
270 is_keyword_hint_ = state->is_keyword_hint;
271 view_->SetUserText(state->user_text,
272 DisplayTextFromUserText(state->user_text), false);
273 view_->SetGrayTextAutocompletion(state->gray_text);
277 AutocompleteMatch OmniboxEditModel::CurrentMatch(
278 GURL* alternate_nav_url) const {
279 // If we have a valid match use it. Otherwise get one for the current text.
280 AutocompleteMatch match = omnibox_controller_->current_match();
282 if (!match.destination_url.is_valid()) {
283 GetInfoForCurrentText(&match, alternate_nav_url);
284 } else if (alternate_nav_url) {
285 *alternate_nav_url = AutocompleteResult::ComputeAlternateNavUrl(
286 input_, match);
288 return match;
291 bool OmniboxEditModel::UpdatePermanentText() {
292 // When there's new permanent text, and the user isn't interacting with the
293 // omnibox, we want to revert the edit to show the new text. We could simply
294 // define "interacting" as "the omnibox has focus", but we still allow updates
295 // when the omnibox has focus as long as the user hasn't begun editing, isn't
296 // seeing zerosuggestions (because changing this text would require changing
297 // or hiding those suggestions), and hasn't toggled on "Show URL" (because
298 // this update will re-enable search term replacement, which will be annoying
299 // if the user is trying to copy the URL). When the omnibox doesn't have
300 // focus, we assume the user may have abandoned their interaction and it's
301 // always safe to change the text; this also prevents someone toggling "Show
302 // URL" (which sounds as if it might be persistent) from seeing just that URL
303 // forever afterwards.
305 // If the page is auto-committing gray text, however, we generally don't want
306 // to make any change to the edit. While auto-commits modify the underlying
307 // permanent URL, they're intended to have no effect on the user's editing
308 // process -- before and after the auto-commit, the omnibox should show the
309 // same user text and the same instant suggestion, even if the auto-commit
310 // happens while the edit doesn't have focus.
311 base::string16 new_permanent_text = controller_->GetToolbarModel()->GetText();
312 base::string16 gray_text = view_->GetGrayTextAutocompletion();
313 const bool visibly_changed_permanent_text =
314 (permanent_text_ != new_permanent_text) &&
315 (!has_focus() ||
316 (!user_input_in_progress_ &&
317 !(popup_model() && popup_model()->IsOpen()) &&
318 controller_->GetToolbarModel()->url_replacement_enabled())) &&
319 (gray_text.empty() ||
320 new_permanent_text != user_text_ + gray_text);
322 permanent_text_ = new_permanent_text;
323 return visibly_changed_permanent_text;
326 GURL OmniboxEditModel::PermanentURL() {
327 return url_fixer::FixupURL(base::UTF16ToUTF8(permanent_text_), std::string());
330 void OmniboxEditModel::SetUserText(const base::string16& text) {
331 SetInputInProgress(true);
332 InternalSetUserText(text);
333 omnibox_controller_->InvalidateCurrentMatch();
334 paste_state_ = NONE;
335 has_temporary_text_ = false;
338 bool OmniboxEditModel::CommitSuggestedText() {
339 const base::string16 suggestion = view_->GetGrayTextAutocompletion();
340 if (suggestion.empty())
341 return false;
343 const base::string16 final_text = view_->GetText() + suggestion;
344 view_->OnBeforePossibleChange();
345 view_->SetWindowTextAndCaretPos(final_text, final_text.length(), false,
346 false);
347 view_->OnAfterPossibleChange();
348 return true;
351 void OmniboxEditModel::OnChanged() {
352 // Don't call CurrentMatch() when there's no editing, as in this case we'll
353 // never actually use it. This avoids running the autocomplete providers (and
354 // any systems they then spin up) during startup.
355 const AutocompleteMatch& current_match = user_input_in_progress_ ?
356 CurrentMatch(NULL) : AutocompleteMatch();
358 AutocompleteActionPredictor::Action recommended_action =
359 AutocompleteActionPredictor::ACTION_NONE;
360 if (user_input_in_progress_) {
361 InstantSearchPrerenderer* prerenderer =
362 InstantSearchPrerenderer::GetForProfile(profile_);
363 if (prerenderer &&
364 prerenderer->IsAllowed(current_match, controller_->GetWebContents()) &&
365 popup_model()->IsOpen() && has_focus()) {
366 recommended_action = AutocompleteActionPredictor::ACTION_PRERENDER;
367 } else {
368 AutocompleteActionPredictor* action_predictor =
369 predictors::AutocompleteActionPredictorFactory::GetForProfile(
370 profile_);
371 action_predictor->RegisterTransitionalMatches(user_text_, result());
372 // Confer with the AutocompleteActionPredictor to determine what action,
373 // if any, we should take. Get the recommended action here even if we
374 // don't need it so we can get stats for anyone who is opted in to UMA,
375 // but only get it if the user has actually typed something to avoid
376 // constructing it before it's needed. Note: This event is triggered as
377 // part of startup when the initial tab transitions to the start page.
378 recommended_action =
379 action_predictor->RecommendAction(user_text_, current_match);
383 UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.Action",
384 recommended_action,
385 AutocompleteActionPredictor::LAST_PREDICT_ACTION);
387 // Hide any suggestions we might be showing.
388 view_->SetGrayTextAutocompletion(base::string16());
390 switch (recommended_action) {
391 case AutocompleteActionPredictor::ACTION_PRERENDER:
392 // It's possible that there is no current page, for instance if the tab
393 // has been closed or on return from a sleep state.
394 // (http://crbug.com/105689)
395 if (!client_->CurrentPageExists())
396 break;
397 // Ask for prerendering if the destination URL is different than the
398 // current URL.
399 if (current_match.destination_url != client_->GetURL())
400 client_->DoPrerender(current_match);
401 break;
402 case AutocompleteActionPredictor::ACTION_PRECONNECT:
403 omnibox_controller_->DoPreconnect(current_match);
404 break;
405 case AutocompleteActionPredictor::ACTION_NONE:
406 break;
409 controller_->OnChanged();
412 void OmniboxEditModel::GetDataForURLExport(GURL* url,
413 base::string16* title,
414 gfx::Image* favicon) {
415 *url = CurrentMatch(NULL).destination_url;
416 if (*url == client_->GetURL()) {
417 content::WebContents* web_contents = controller_->GetWebContents();
418 *title = web_contents->GetTitle();
419 *favicon = favicon::ContentFaviconDriver::FromWebContents(web_contents)
420 ->GetFavicon();
424 bool OmniboxEditModel::CurrentTextIsURL() const {
425 if (controller_->GetToolbarModel()->WouldReplaceURL())
426 return false;
428 // If current text is not composed of replaced search terms and
429 // !user_input_in_progress_, then permanent text is showing and should be a
430 // URL, so no further checking is needed. By avoiding checking in this case,
431 // we avoid calling into the autocomplete providers, and thus initializing the
432 // history system, as long as possible, which speeds startup.
433 if (!user_input_in_progress_)
434 return true;
436 return !AutocompleteMatch::IsSearchType(CurrentMatch(NULL).type);
439 AutocompleteMatch::Type OmniboxEditModel::CurrentTextType() const {
440 return CurrentMatch(NULL).type;
443 void OmniboxEditModel::AdjustTextForCopy(int sel_min,
444 bool is_all_selected,
445 base::string16* text,
446 GURL* url,
447 bool* write_url) {
448 *write_url = false;
450 // Do not adjust if selection did not start at the beginning of the field, or
451 // if the URL was omitted.
452 if ((sel_min != 0) || controller_->GetToolbarModel()->WouldReplaceURL())
453 return;
455 // Check whether the user is trying to copy the current page's URL by
456 // selecting the whole thing without editing it.
458 // This is complicated by ZeroSuggest. When ZeroSuggest is active, the user
459 // may be selecting different items and thus changing the address bar text,
460 // even though !user_input_in_progress_; and the permanent URL may change
461 // without updating the visible text, just like when user input is in
462 // progress. In these cases, we don't want to copy the underlying URL, we
463 // want to copy what the user actually sees. However, if we simply never do
464 // this block when !popup_model()->IsOpen(), then just clicking into the
465 // address bar and trying to copy will always bypass this block on pages that
466 // trigger ZeroSuggest, which is too conservative. Instead, in the
467 // ZeroSuggest case, we check that (a) the user hasn't selected one of the
468 // other suggestions, and (b) the selected text is still the same as the
469 // permanent text. ((b) probably implies (a), but it doesn't hurt to be
470 // sure.) If these hold, then it's safe to copy the underlying URL.
471 if (!user_input_in_progress_ && is_all_selected &&
472 (!popup_model() || !popup_model()->IsOpen() ||
473 ((popup_model()->selected_line() == 0) && (*text == permanent_text_)))) {
474 // It's safe to copy the underlying URL. These lines ensure that if the
475 // scheme was stripped it's added back, and the URL is unescaped (we escape
476 // parts of it for display).
477 *url = PermanentURL();
478 *text = base::UTF8ToUTF16(url->spec());
479 *write_url = true;
480 return;
483 // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now
484 // the user is probably holding down control to cause the copy, which will
485 // screw up our calculation of the desired_tld.
486 AutocompleteMatch match;
487 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
488 *text, is_keyword_selected(), true, ClassifyPage(), &match, NULL);
489 if (AutocompleteMatch::IsSearchType(match.type))
490 return;
491 *url = match.destination_url;
493 // Prefix the text with 'http://' if the text doesn't start with 'http://',
494 // the text parses as a url with a scheme of http, the user selected the
495 // entire host, and the user hasn't edited the host or manually removed the
496 // scheme.
497 GURL perm_url(PermanentURL());
498 if (perm_url.SchemeIs(url::kHttpScheme) &&
499 url->SchemeIs(url::kHttpScheme) && perm_url.host() == url->host()) {
500 *write_url = true;
501 base::string16 http = base::ASCIIToUTF16(url::kHttpScheme) +
502 base::ASCIIToUTF16(url::kStandardSchemeSeparator);
503 if (text->compare(0, http.length(), http) != 0)
504 *text = http + *text;
508 void OmniboxEditModel::SetInputInProgress(bool in_progress) {
509 if (in_progress && !user_input_since_focus_) {
510 base::TimeTicks now = base::TimeTicks::Now();
511 DCHECK(last_omnibox_focus_ <= now);
512 UMA_HISTOGRAM_TIMES(kFocusToEditTimeHistogram, now - last_omnibox_focus_);
513 user_input_since_focus_ = true;
516 if (user_input_in_progress_ == in_progress)
517 return;
519 user_input_in_progress_ = in_progress;
520 if (user_input_in_progress_) {
521 time_user_first_modified_omnibox_ = base::TimeTicks::Now();
522 content::RecordAction(base::UserMetricsAction("OmniboxInputInProgress"));
523 autocomplete_controller()->ResetSession();
526 controller_->GetToolbarModel()->set_input_in_progress(in_progress);
527 controller_->Update(NULL);
529 if (user_input_in_progress_ || !in_revert_)
530 client_->OnInputStateChanged();
533 void OmniboxEditModel::Revert() {
534 SetInputInProgress(false);
535 input_.Clear();
536 paste_state_ = NONE;
537 InternalSetUserText(base::string16());
538 keyword_.clear();
539 is_keyword_hint_ = false;
540 has_temporary_text_ = false;
541 view_->SetWindowTextAndCaretPos(permanent_text_,
542 has_focus() ? permanent_text_.length() : 0,
543 false, true);
544 AutocompleteActionPredictor* action_predictor =
545 predictors::AutocompleteActionPredictorFactory::GetForProfile(profile_);
546 action_predictor->ClearTransitionalMatches();
547 action_predictor->CancelPrerender();
550 void OmniboxEditModel::StartAutocomplete(
551 bool has_selected_text,
552 bool prevent_inline_autocomplete,
553 bool entering_keyword_mode) {
554 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
555 tracked_objects::ScopedTracker tracking_profile(
556 FROM_HERE_WITH_EXPLICIT_FUNCTION(
557 "440919 OmniboxEditModel::StartAutocomplete"));
558 size_t cursor_position;
559 if (inline_autocomplete_text_.empty()) {
560 // Cursor position is equivalent to the current selection's end.
561 size_t start;
562 view_->GetSelectionBounds(&start, &cursor_position);
563 // If we're in keyword mode, we're not displaying the full |user_text_|, so
564 // the cursor position we got from the view has to be adjusted later by the
565 // length of the undisplayed text. If we're just entering keyword mode,
566 // though, we have to avoid making this adjustment, because we haven't
567 // actually hidden any text yet, but the caller has already cleared
568 // |is_keyword_hint_|, so DisplayTextFromUserText() will believe we are
569 // already in keyword mode, and will thus mis-adjust the cursor position.
570 if (!entering_keyword_mode) {
571 cursor_position +=
572 user_text_.length() - DisplayTextFromUserText(user_text_).length();
574 } else {
575 // There are some cases where StartAutocomplete() may be called
576 // with non-empty |inline_autocomplete_text_|. In such cases, we cannot
577 // use the current selection, because it could result with the cursor
578 // position past the last character from the user text. Instead,
579 // we assume that the cursor is simply at the end of input.
580 // One example is when user presses Ctrl key while having a highlighted
581 // inline autocomplete text.
582 // TODO: Rethink how we are going to handle this case to avoid
583 // inconsistent behavior when user presses Ctrl key.
584 // See http://crbug.com/165961 and http://crbug.com/165968 for more details.
585 cursor_position = user_text_.length();
588 GURL current_url =
589 (client_->CurrentPageExists() && view_->IsIndicatingQueryRefinement()) ?
590 client_->GetURL() : GURL();
591 input_ = AutocompleteInput(
592 user_text_, cursor_position, std::string(), current_url, ClassifyPage(),
593 prevent_inline_autocomplete || just_deleted_text_ ||
594 (has_selected_text && inline_autocomplete_text_.empty()) ||
595 (paste_state_ != NONE),
596 is_keyword_selected(),
597 is_keyword_selected() || allow_exact_keyword_match_, true, false,
598 ChromeAutocompleteSchemeClassifier(profile_));
600 omnibox_controller_->StartAutocomplete(input_);
603 void OmniboxEditModel::StopAutocomplete() {
604 autocomplete_controller()->Stop(true);
607 bool OmniboxEditModel::CanPasteAndGo(const base::string16& text) const {
608 if (!view_->command_updater()->IsCommandEnabled(IDC_OPEN_CURRENT_URL))
609 return false;
611 AutocompleteMatch match;
612 ClassifyStringForPasteAndGo(text, &match, NULL);
613 return match.destination_url.is_valid();
616 void OmniboxEditModel::PasteAndGo(const base::string16& text) {
617 DCHECK(CanPasteAndGo(text));
618 UMA_HISTOGRAM_COUNTS("Omnibox.PasteAndGo", 1);
620 view_->RevertAll();
621 AutocompleteMatch match;
622 GURL alternate_nav_url;
623 ClassifyStringForPasteAndGo(text, &match, &alternate_nav_url);
624 view_->OpenMatch(match, CURRENT_TAB, alternate_nav_url, text,
625 OmniboxPopupModel::kNoMatch);
628 bool OmniboxEditModel::IsPasteAndSearch(const base::string16& text) const {
629 AutocompleteMatch match;
630 ClassifyStringForPasteAndGo(text, &match, NULL);
631 return AutocompleteMatch::IsSearchType(match.type);
634 void OmniboxEditModel::AcceptInput(WindowOpenDisposition disposition,
635 bool for_drop) {
636 // Get the URL and transition type for the selected entry.
637 GURL alternate_nav_url;
638 AutocompleteMatch match = CurrentMatch(&alternate_nav_url);
640 // If CTRL is down it means the user wants to append ".com" to the text he
641 // typed. If we can successfully generate a URL_WHAT_YOU_TYPED match doing
642 // that, then we use this. These matches are marked as generated by the
643 // HistoryURLProvider so we only generate them if this provider is present.
644 if (control_key_state_ == DOWN_WITHOUT_CHANGE && !is_keyword_selected() &&
645 autocomplete_controller()->history_url_provider()) {
646 // Generate a new AutocompleteInput, copying the latest one but using "com"
647 // as the desired TLD. Then use this autocomplete input to generate a
648 // URL_WHAT_YOU_TYPED AutocompleteMatch. Note that using the most recent
649 // input instead of the currently visible text means we'll ignore any
650 // visible inline autocompletion: if a user types "foo" and is autocompleted
651 // to "foodnetwork.com", ctrl-enter will navigate to "foo.com", not
652 // "foodnetwork.com". At the time of writing, this behavior matches
653 // Internet Explorer, but not Firefox.
654 input_ = AutocompleteInput(
655 has_temporary_text_ ? UserTextFromDisplayText(view_->GetText())
656 : input_.text(),
657 input_.cursor_position(), "com", GURL(),
658 input_.current_page_classification(),
659 input_.prevent_inline_autocomplete(), input_.prefer_keyword(),
660 input_.allow_exact_keyword_match(), input_.want_asynchronous_matches(),
661 input_.from_omnibox_focus(),
662 ChromeAutocompleteSchemeClassifier(profile_));
663 AutocompleteMatch url_match(
664 autocomplete_controller()->history_url_provider()->SuggestExactInput(
665 input_, input_.canonicalized_url(), false));
667 if (url_match.destination_url.is_valid()) {
668 // We have a valid URL, we use this newly generated AutocompleteMatch.
669 match = url_match;
670 alternate_nav_url = GURL();
674 if (!match.destination_url.is_valid())
675 return;
677 if ((match.transition == ui::PAGE_TRANSITION_TYPED) &&
678 (match.destination_url == PermanentURL())) {
679 // When the user hit enter on the existing permanent URL, treat it like a
680 // reload for scoring purposes. We could detect this by just checking
681 // user_input_in_progress_, but it seems better to treat "edits" that end
682 // up leaving the URL unchanged (e.g. deleting the last character and then
683 // retyping it) as reloads too. We exclude non-TYPED transitions because if
684 // the transition is GENERATED, the user input something that looked
685 // different from the current URL, even if it wound up at the same place
686 // (e.g. manually retyping the same search query), and it seems wrong to
687 // treat this as a reload.
688 match.transition = ui::PAGE_TRANSITION_RELOAD;
689 } else if (for_drop ||
690 ((paste_state_ != NONE) &&
691 (match.type == AutocompleteMatchType::URL_WHAT_YOU_TYPED))) {
692 // When the user pasted in a URL and hit enter, score it like a link click
693 // rather than a normal typed URL, so it doesn't get inline autocompleted
694 // as aggressively later.
695 match.transition = ui::PAGE_TRANSITION_LINK;
698 // While the user is typing, the instant search base page may be prerendered
699 // in the background. Even though certain inputs may not be eligible for
700 // prerendering, the prerender isn't automatically cancelled as the user
701 // continues typing, in hopes the final input will end up making use of the
702 // prerenderer. Intermediate inputs that are legal for prerendering will be
703 // sent to the prerendered page to keep it up to date; then once the user
704 // commits a navigation, it will trigger code in chrome::Navigate() to swap in
705 // the prerenderer.
707 // Unfortunately, that swap code only has the navigated URL, so it doesn't
708 // actually know whether the prerenderer has been sent the relevant input
709 // already, or whether instead the user manually navigated to something that
710 // looks like a search URL (which won't have been sent to the prerenderer).
711 // In this case, we need to ensure the prerenderer is cancelled here so that
712 // code can't attempt to wrongly swap-in, or it could swap in an empty page in
713 // place of the correct navigation.
715 // This would be clearer if we could swap in the prerenderer here instead of
716 // over in chrome::Navigate(), but we have to wait until then because the
717 // final decision about whether to use the prerendered page depends on other
718 // parts of the chrome::NavigateParams struct not available until then.
719 InstantSearchPrerenderer* prerenderer =
720 InstantSearchPrerenderer::GetForProfile(profile_);
721 if (prerenderer &&
722 !prerenderer->IsAllowed(match, controller_->GetWebContents()))
723 prerenderer->Cancel();
725 DCHECK(popup_model());
726 view_->OpenMatch(match, disposition, alternate_nav_url, base::string16(),
727 popup_model()->selected_line());
730 void OmniboxEditModel::OpenMatch(AutocompleteMatch match,
731 WindowOpenDisposition disposition,
732 const GURL& alternate_nav_url,
733 const base::string16& pasted_text,
734 size_t index) {
735 const base::TimeTicks& now(base::TimeTicks::Now());
736 base::TimeDelta elapsed_time_since_user_first_modified_omnibox(
737 now - time_user_first_modified_omnibox_);
738 autocomplete_controller()->UpdateMatchDestinationURLWithQueryFormulationTime(
739 elapsed_time_since_user_first_modified_omnibox, &match);
741 base::string16 input_text(pasted_text);
742 if (input_text.empty())
743 input_text = user_input_in_progress_ ? user_text_ : permanent_text_;
744 // Create a dummy AutocompleteInput for use in calling SuggestExactInput()
745 // to create an alternate navigational match.
746 AutocompleteInput alternate_input(
747 input_text, base::string16::npos, std::string(),
748 // Somehow we can occasionally get here with no active tab. It's not
749 // clear why this happens.
750 client_->CurrentPageExists() ? client_->GetURL() : GURL(),
751 ClassifyPage(), false, false, true, true, false,
752 ChromeAutocompleteSchemeClassifier(profile_));
753 scoped_ptr<OmniboxNavigationObserver> observer(
754 new OmniboxNavigationObserver(
755 profile_, input_text, match,
756 autocomplete_controller()->history_url_provider()->SuggestExactInput(
757 alternate_input, alternate_nav_url,
758 AutocompleteInput::HasHTTPScheme(input_text))));
760 base::TimeDelta elapsed_time_since_last_change_to_default_match(
761 now - autocomplete_controller()->last_time_default_match_changed());
762 DCHECK(match.provider);
763 // These elapsed times don't really make sense for ZeroSuggest matches
764 // (because the user does not modify the omnibox for ZeroSuggest), so for
765 // those we set the elapsed times to something that will be ignored by
766 // metrics_log.cc. They also don't necessarily make sense if the omnibox
767 // dropdown is closed or the user used a paste-and-go action. (In most
768 // cases when this happens, the user never modified the omnibox.)
769 if ((match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST) ||
770 !popup_model()->IsOpen() || !pasted_text.empty()) {
771 const base::TimeDelta default_time_delta =
772 base::TimeDelta::FromMilliseconds(-1);
773 elapsed_time_since_user_first_modified_omnibox = default_time_delta;
774 elapsed_time_since_last_change_to_default_match = default_time_delta;
776 // If the popup is closed or this is a paste-and-go action (meaning the
777 // contents of the dropdown are ignored regardless), we record for logging
778 // purposes a selected_index of 0 and a suggestion list as having a single
779 // entry of the match used.
780 ACMatches fake_single_entry_matches;
781 fake_single_entry_matches.push_back(match);
782 AutocompleteResult fake_single_entry_result;
783 fake_single_entry_result.AppendMatches(input_, fake_single_entry_matches);
784 OmniboxLog log(
785 input_text,
786 just_deleted_text_,
787 input_.type(),
788 popup_model()->IsOpen(),
789 (!popup_model()->IsOpen() || !pasted_text.empty()) ? 0 : index,
790 !pasted_text.empty(),
791 -1, // don't yet know tab ID; set later if appropriate
792 ClassifyPage(),
793 elapsed_time_since_user_first_modified_omnibox,
794 match.allowed_to_be_default_match ? match.inline_autocompletion.length() :
795 base::string16::npos,
796 elapsed_time_since_last_change_to_default_match,
797 (!popup_model()->IsOpen() || !pasted_text.empty()) ?
798 fake_single_entry_result : result());
799 DCHECK(!popup_model()->IsOpen() || !pasted_text.empty() ||
800 (log.elapsed_time_since_user_first_modified_omnibox >=
801 log.elapsed_time_since_last_change_to_default_match))
802 << "We should've got the notification that the user modified the "
803 << "omnibox text at same time or before the most recent time the "
804 << "default match changed.";
806 if ((disposition == CURRENT_TAB) && client_->CurrentPageExists()) {
807 // If we know the destination is being opened in the current tab,
808 // we can easily get the tab ID. (If it's being opened in a new
809 // tab, we don't know the tab ID yet.)
810 log.tab_id = client_->GetSessionID().id();
812 autocomplete_controller()->AddProvidersInfo(&log.providers_info);
813 client_->OnURLOpenedFromOmnibox(&log);
814 LOCAL_HISTOGRAM_BOOLEAN("Omnibox.EventCount", true);
815 DCHECK(!last_omnibox_focus_.is_null())
816 << "An omnibox focus should have occurred before opening a match.";
817 UMA_HISTOGRAM_TIMES(kFocusToOpenTimeHistogram, now - last_omnibox_focus_);
819 TemplateURLService* service =
820 TemplateURLServiceFactory::GetForProfile(profile_);
821 TemplateURL* template_url = match.GetTemplateURL(service, false);
822 if (template_url) {
823 if (match.transition == ui::PAGE_TRANSITION_KEYWORD) {
824 // The user is using a non-substituting keyword or is explicitly in
825 // keyword mode.
827 // Don't increment usage count for extension keywords.
828 if (client_->ProcessExtensionKeyword(template_url, match,
829 disposition)) {
830 observer->OnSuccessfulNavigation();
831 if (disposition != NEW_BACKGROUND_TAB)
832 view_->RevertAll();
833 return;
836 content::RecordAction(base::UserMetricsAction("AcceptedKeyword"));
837 TemplateURLServiceFactory::GetForProfile(profile_)->IncrementUsageCount(
838 template_url);
839 } else {
840 DCHECK_EQ(ui::PAGE_TRANSITION_GENERATED, match.transition);
841 // NOTE: We purposefully don't increment the usage count of the default
842 // search engine here like we do for explicit keywords above; see comments
843 // in template_url.h.
846 UMA_HISTOGRAM_ENUMERATION(
847 "Omnibox.SearchEngineType",
848 TemplateURLPrepopulateData::GetEngineType(
849 *template_url, UIThreadSearchTermsData(profile_)),
850 SEARCH_ENGINE_MAX);
853 // Get the current text before we call RevertAll() which will clear it.
854 base::string16 current_text = view_->GetText();
856 if (disposition != NEW_BACKGROUND_TAB) {
857 base::AutoReset<bool> tmp(&in_revert_, true);
858 view_->RevertAll(); // Revert the box to its unedited state.
861 RecordPercentageMatchHistogram(
862 permanent_text_, current_text,
863 controller_->GetToolbarModel()->WouldReplaceURL(),
864 match.transition, view_->GetWidth());
866 // Track whether the destination URL sends us to a search results page
867 // using the default search provider.
868 if (TemplateURLServiceFactory::GetForProfile(profile_)->
869 IsSearchResultsPageFromDefaultSearchProvider(match.destination_url)) {
870 content::RecordAction(
871 base::UserMetricsAction("OmniboxDestinationURLIsSearchOnDSP"));
874 if (match.destination_url.is_valid()) {
875 // This calls RevertAll again.
876 base::AutoReset<bool> tmp(&in_revert_, true);
877 controller_->OnAutocompleteAccept(
878 match.destination_url, disposition,
879 ui::PageTransitionFromInt(
880 match.transition | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR));
881 if (observer->load_state() != OmniboxNavigationObserver::LOAD_NOT_SEEN)
882 ignore_result(observer.release()); // The observer will delete itself.
885 BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(profile_);
886 if (bookmark_model && bookmark_model->IsBookmarked(match.destination_url))
887 RecordBookmarkLaunch(NULL, BOOKMARK_LAUNCH_LOCATION_OMNIBOX);
890 bool OmniboxEditModel::AcceptKeyword(EnteredKeywordModeMethod entered_method) {
891 DCHECK(is_keyword_hint_ && !keyword_.empty());
893 autocomplete_controller()->Stop(false);
894 is_keyword_hint_ = false;
896 if (popup_model() && popup_model()->IsOpen())
897 popup_model()->SetSelectedLineState(OmniboxPopupModel::KEYWORD);
898 else
899 StartAutocomplete(false, true, true);
901 // When entering keyword mode via tab, the new text to show is whatever the
902 // newly-selected match in the dropdown is. When entering via space, however,
903 // we should make sure to use the actual |user_text_| as the basis for the new
904 // text. This ensures that if the user types "<keyword><space>" and the
905 // default match would have inline autocompleted a further string (e.g.
906 // because there's a past multi-word search beginning with this keyword), the
907 // inline autocompletion doesn't get filled in as the keyword search query
908 // text.
910 // We also treat tabbing into keyword mode like tabbing through the popup in
911 // that we set |has_temporary_text_|, whereas pressing space is treated like
912 // a new keystroke that changes the current match instead of overlaying it
913 // with a temporary one. This is important because rerunning autocomplete
914 // after the user pressed space, which will have happened just before reaching
915 // here, may have generated a new match, which the user won't actually see and
916 // which we don't want to switch back to when existing keyword mode; see
917 // comments in ClearKeyword().
918 if (entered_method == ENTERED_KEYWORD_MODE_VIA_TAB) {
919 // Ensure the current selection is saved before showing keyword mode
920 // so that moving to another line and then reverting the text will restore
921 // the current state properly.
922 bool save_original_selection = !has_temporary_text_;
923 has_temporary_text_ = true;
924 const AutocompleteMatch& match = CurrentMatch(NULL);
925 original_url_ = match.destination_url;
926 view_->OnTemporaryTextMaybeChanged(
927 DisplayTextFromUserText(match.fill_into_edit),
928 save_original_selection, true);
929 } else {
930 view_->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(user_text_),
931 false, true);
934 content::RecordAction(base::UserMetricsAction("AcceptedKeywordHint"));
935 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram, entered_method,
936 ENTERED_KEYWORD_MODE_NUM_ITEMS);
938 return true;
941 void OmniboxEditModel::AcceptTemporaryTextAsUserText() {
942 InternalSetUserText(UserTextFromDisplayText(view_->GetText()));
943 has_temporary_text_ = false;
945 if (user_input_in_progress_ || !in_revert_)
946 client_->OnInputStateChanged();
949 void OmniboxEditModel::ClearKeyword() {
950 autocomplete_controller()->Stop(false);
952 // While we're always in keyword mode upon reaching here, sometimes we've just
953 // toggled in via space or tab, and sometimes we're on a non-toggled line
954 // (usually because the user has typed a search string). Keep track of the
955 // difference, as we'll need it below.
956 bool was_toggled_into_keyword_mode =
957 popup_model()->selected_line_state() == OmniboxPopupModel::KEYWORD;
959 omnibox_controller_->ClearPopupKeywordMode();
961 // There are several possible states we could have been in before the user hit
962 // backspace or shift-tab to enter this function:
963 // (1) was_toggled_into_keyword_mode == false, has_temporary_text_ == false
964 // The user typed a further key after being in keyword mode already, e.g.
965 // "google.com f".
966 // (2) was_toggled_into_keyword_mode == false, has_temporary_text_ == true
967 // The user tabbed away from a dropdown entry in keyword mode, then tabbed
968 // back to it, e.g. "google.com f<tab><shift-tab>".
969 // (3) was_toggled_into_keyword_mode == true, has_temporary_text_ == false
970 // The user had just typed space to enter keyword mode, e.g.
971 // "google.com ".
972 // (4) was_toggled_into_keyword_mode == true, has_temporary_text_ == true
973 // The user had just typed tab to enter keyword mode, e.g.
974 // "google.com<tab>".
976 // For states 1-3, we can safely handle the exit from keyword mode by using
977 // OnBefore/AfterPossibleChange() to do a complete state update of all
978 // objects. However, with state 4, if we do this, and if the user had tabbed
979 // into keyword mode on a line in the middle of the dropdown instead of the
980 // first line, then the state update will rerun autocompletion and reset the
981 // whole dropdown, and end up with the first line selected instead, instead of
982 // just "undoing" the keyword mode entry on the non-first line. So in this
983 // case we simply reset |is_keyword_hint_| to true and update the window text.
985 // You might wonder why we don't simply do this in all cases. In states 1-2,
986 // getting out of keyword mode likely shouldn't put us in keyword hint mode;
987 // if the user typed "google.com f" and then put the cursor before 'f' and hit
988 // backspace, the resulting text would be "google.comf", which is unlikely to
989 // be a keyword. Unconditionally putting things back in keyword hint mode is
990 // going to lead to internally inconsistent state, and possible future
991 // crashes. State 3 is more subtle; here we need to do the full state update
992 // because before entering keyword mode to begin with, we will have re-run
993 // autocomplete in ways that can produce surprising results if we just switch
994 // back out of keyword mode. For example, if a user has a keyword named "x",
995 // an inline-autocompletable history site "xyz.com", and a lower-ranked
996 // inline-autocompletable search "x y", then typing "x" will inline-
997 // autocomplete to "xyz.com", hitting space will toggle into keyword mode, but
998 // then hitting backspace could wind up with the default match as the "x y"
999 // search, which feels bizarre.
1000 const base::string16 window_text(keyword_ + view_->GetText());
1001 if (was_toggled_into_keyword_mode && has_temporary_text_) {
1002 // State 4 above.
1003 is_keyword_hint_ = true;
1004 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
1005 false, true);
1006 } else {
1007 // States 1-3 above.
1008 view_->OnBeforePossibleChange();
1009 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
1010 false, false);
1011 keyword_.clear();
1012 is_keyword_hint_ = false;
1013 view_->OnAfterPossibleChange();
1017 void OmniboxEditModel::OnSetFocus(bool control_down) {
1018 last_omnibox_focus_ = base::TimeTicks::Now();
1019 user_input_since_focus_ = false;
1021 // If the omnibox lost focus while the caret was hidden and then regained
1022 // focus, OnSetFocus() is called and should restore visibility. Note that
1023 // focus can be regained without an accompanying call to
1024 // OmniboxView::SetFocus(), e.g. by tabbing in.
1025 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_EXPLICIT);
1026 control_key_state_ = control_down ? DOWN_WITHOUT_CHANGE : UP;
1028 // Try to get ZeroSuggest suggestions if a page is loaded and the user has
1029 // not been typing in the omnibox. The |user_input_in_progress_| check is
1030 // used to detect the case where this function is called after right-clicking
1031 // in the omnibox and selecting paste in Linux (in which case we actually get
1032 // the OnSetFocus() call after the process of handling the paste has kicked
1033 // off).
1034 // TODO(hfung): Remove this when crbug/271590 is fixed.
1035 if (client_->CurrentPageExists() && !user_input_in_progress_) {
1036 // We avoid PermanentURL() here because it's not guaranteed to give us the
1037 // actual underlying current URL, e.g. if we're on the NTP and the
1038 // |permanent_text_| is empty.
1039 input_ = AutocompleteInput(permanent_text_, base::string16::npos,
1040 std::string(), client_->GetURL(),
1041 ClassifyPage(), false, false, true, true, true,
1042 ChromeAutocompleteSchemeClassifier(profile_));
1043 autocomplete_controller()->Start(input_);
1046 if (user_input_in_progress_ || !in_revert_)
1047 client_->OnInputStateChanged();
1050 void OmniboxEditModel::SetCaretVisibility(bool visible) {
1051 // Caret visibility only matters if the omnibox has focus.
1052 if (focus_state_ != OMNIBOX_FOCUS_NONE) {
1053 SetFocusState(visible ? OMNIBOX_FOCUS_VISIBLE : OMNIBOX_FOCUS_INVISIBLE,
1054 OMNIBOX_FOCUS_CHANGE_EXPLICIT);
1058 void OmniboxEditModel::OnWillKillFocus() {
1059 if (user_input_in_progress_ || !in_revert_)
1060 client_->OnInputStateChanged();
1063 void OmniboxEditModel::OnKillFocus() {
1064 SetFocusState(OMNIBOX_FOCUS_NONE, OMNIBOX_FOCUS_CHANGE_EXPLICIT);
1065 focus_source_ = INVALID;
1066 control_key_state_ = UP;
1067 paste_state_ = NONE;
1070 bool OmniboxEditModel::WillHandleEscapeKey() const {
1071 return user_input_in_progress_ ||
1072 (has_temporary_text_ &&
1073 (CurrentMatch(NULL).destination_url != original_url_));
1076 bool OmniboxEditModel::OnEscapeKeyPressed() {
1077 if (has_temporary_text_ &&
1078 (CurrentMatch(NULL).destination_url != original_url_)) {
1079 RevertTemporaryText(true);
1080 return true;
1083 // We do not clear the pending entry from the omnibox when a load is first
1084 // stopped. If the user presses Escape while stopped, whether editing or not,
1085 // we clear it.
1086 if (client_->CurrentPageExists() && !client_->IsLoading()) {
1087 client_->GetNavigationController().DiscardNonCommittedEntries();
1088 view_->Update();
1091 if (!user_text_.empty()) {
1092 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
1093 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE,
1094 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
1097 // Unconditionally revert/select all. This ensures any popup, whether due to
1098 // normal editing or ZeroSuggest, is closed, and the full text is selected.
1099 // This in turn allows the user to use escape to quickly select all the text
1100 // for ease of replacement, and matches other browsers.
1101 bool user_input_was_in_progress = user_input_in_progress_;
1102 view_->RevertAll();
1103 view_->SelectAll(true);
1105 // If the user was in the midst of editing, don't cancel any underlying page
1106 // load. This doesn't match IE or Firefox, but seems more correct. Note that
1107 // we do allow the page load to be stopped in the case where ZeroSuggest was
1108 // visible; this is so that it's still possible to focus the address bar and
1109 // hit escape once to stop a load even if the address being loaded triggers
1110 // the ZeroSuggest popup.
1111 return user_input_was_in_progress;
1114 void OmniboxEditModel::OnControlKeyChanged(bool pressed) {
1115 if (pressed == (control_key_state_ == UP))
1116 control_key_state_ = pressed ? DOWN_WITHOUT_CHANGE : UP;
1119 void OmniboxEditModel::OnPaste() {
1120 UMA_HISTOGRAM_COUNTS("Omnibox.Paste", 1);
1121 paste_state_ = PASTING;
1124 void OmniboxEditModel::OnUpOrDownKeyPressed(int count) {
1125 // NOTE: This purposefully doesn't trigger any code that resets paste_state_.
1126 if (popup_model() && popup_model()->IsOpen()) {
1127 // The popup is open, so the user should be able to interact with it
1128 // normally.
1129 popup_model()->Move(count);
1130 return;
1133 if (!query_in_progress()) {
1134 // The popup is neither open nor working on a query already. So, start an
1135 // autocomplete query for the current text. This also sets
1136 // user_input_in_progress_ to true, which we want: if the user has started
1137 // to interact with the popup, changing the permanent_text_ shouldn't change
1138 // the displayed text.
1139 // Note: This does not force the popup to open immediately.
1140 // TODO(pkasting): We should, in fact, force this particular query to open
1141 // the popup immediately.
1142 if (!user_input_in_progress_)
1143 InternalSetUserText(permanent_text_);
1144 view_->UpdatePopup();
1145 return;
1148 // TODO(pkasting): The popup is working on a query but is not open. We should
1149 // force it to open immediately.
1152 void OmniboxEditModel::OnPopupDataChanged(
1153 const base::string16& text,
1154 GURL* destination_for_temporary_text_change,
1155 const base::string16& keyword,
1156 bool is_keyword_hint) {
1157 // The popup changed its data, the match in the controller is no longer valid.
1158 omnibox_controller_->InvalidateCurrentMatch();
1160 // Update keyword/hint-related local state.
1161 bool keyword_state_changed = (keyword_ != keyword) ||
1162 ((is_keyword_hint_ != is_keyword_hint) && !keyword.empty());
1163 if (keyword_state_changed) {
1164 keyword_ = keyword;
1165 is_keyword_hint_ = is_keyword_hint;
1167 // |is_keyword_hint_| should always be false if |keyword_| is empty.
1168 DCHECK(!keyword_.empty() || !is_keyword_hint_);
1171 // Handle changes to temporary text.
1172 if (destination_for_temporary_text_change != NULL) {
1173 const bool save_original_selection = !has_temporary_text_;
1174 if (save_original_selection) {
1175 // Save the original selection and URL so it can be reverted later.
1176 has_temporary_text_ = true;
1177 original_url_ = *destination_for_temporary_text_change;
1178 inline_autocomplete_text_.clear();
1179 view_->OnInlineAutocompleteTextCleared();
1181 if (control_key_state_ == DOWN_WITHOUT_CHANGE) {
1182 // Arrowing around the popup cancels control-enter.
1183 control_key_state_ = DOWN_WITH_CHANGE;
1184 // Now things are a bit screwy: the desired_tld has changed, but if we
1185 // update the popup, the new order of entries won't match the old, so the
1186 // user's selection gets screwy; and if we don't update the popup, and the
1187 // user reverts, then the selected item will be as if control is still
1188 // pressed, even though maybe it isn't any more. There is no obvious
1189 // right answer here :(
1191 view_->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text),
1192 save_original_selection, true);
1193 return;
1196 bool call_controller_onchanged = true;
1197 inline_autocomplete_text_ = text;
1198 if (inline_autocomplete_text_.empty())
1199 view_->OnInlineAutocompleteTextCleared();
1201 const base::string16& user_text =
1202 user_input_in_progress_ ? user_text_ : permanent_text_;
1203 if (keyword_state_changed && is_keyword_selected()) {
1204 // If we reach here, the user most likely entered keyword mode by inserting
1205 // a space between a keyword name and a search string (as pressing space or
1206 // tab after the keyword name alone would have been be handled in
1207 // MaybeAcceptKeywordBySpace() by calling AcceptKeyword(), which won't reach
1208 // here). In this case, we don't want to call
1209 // OnInlineAutocompleteTextMaybeChanged() as normal, because that will
1210 // correctly change the text (to the search string alone) but move the caret
1211 // to the end of the string; instead we want the caret at the start of the
1212 // search string since that's where it was in the original input. So we set
1213 // the text and caret position directly.
1215 // It may also be possible to reach here if we're reverting from having
1216 // temporary text back to a default match that's a keyword search, but in
1217 // that case the RevertTemporaryText() call below will reset the caret or
1218 // selection correctly so the caret positioning we do here won't matter.
1219 view_->SetWindowTextAndCaretPos(DisplayTextFromUserText(user_text), 0,
1220 false, false);
1221 } else if (view_->OnInlineAutocompleteTextMaybeChanged(
1222 DisplayTextFromUserText(user_text + inline_autocomplete_text_),
1223 DisplayTextFromUserText(user_text).length())) {
1224 call_controller_onchanged = false;
1227 // If |has_temporary_text_| is true, then we previously had a manual selection
1228 // but now don't (or |destination_for_temporary_text_change| would have been
1229 // non-NULL). This can happen when deleting the selected item in the popup.
1230 // In this case, we've already reverted the popup to the default match, so we
1231 // need to revert ourselves as well.
1232 if (has_temporary_text_) {
1233 RevertTemporaryText(false);
1234 call_controller_onchanged = false;
1237 // We need to invoke OnChanged in case the destination url changed (as could
1238 // happen when control is toggled).
1239 if (call_controller_onchanged)
1240 OnChanged();
1243 bool OmniboxEditModel::OnAfterPossibleChange(const base::string16& old_text,
1244 const base::string16& new_text,
1245 size_t selection_start,
1246 size_t selection_end,
1247 bool selection_differs,
1248 bool text_differs,
1249 bool just_deleted_text,
1250 bool allow_keyword_ui_change) {
1251 // Update the paste state as appropriate: if we're just finishing a paste
1252 // that replaced all the text, preserve that information; otherwise, if we've
1253 // made some other edit, clear paste tracking.
1254 if (paste_state_ == PASTING)
1255 paste_state_ = PASTED;
1256 else if (text_differs)
1257 paste_state_ = NONE;
1259 if (text_differs || selection_differs) {
1260 // Record current focus state for this input if we haven't already.
1261 if (focus_source_ == INVALID) {
1262 // We should generally expect the omnibox to have focus at this point, but
1263 // it doesn't always on Linux. This is because, unlike other platforms,
1264 // right clicking in the omnibox on Linux doesn't focus it. So pasting via
1265 // right-click can change the contents without focusing the omnibox.
1266 // TODO(samarth): fix Linux focus behavior and add a DCHECK here to
1267 // check that the omnibox does have focus.
1268 focus_source_ = (focus_state_ == OMNIBOX_FOCUS_INVISIBLE) ?
1269 FAKEBOX : OMNIBOX;
1272 // Restore caret visibility whenever the user changes text or selection in
1273 // the omnibox.
1274 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_TYPING);
1277 // Modifying the selection counts as accepting the autocompleted text.
1278 const bool user_text_changed =
1279 text_differs || (selection_differs && !inline_autocomplete_text_.empty());
1281 // If something has changed while the control key is down, prevent
1282 // "ctrl-enter" until the control key is released.
1283 if ((text_differs || selection_differs) &&
1284 (control_key_state_ == DOWN_WITHOUT_CHANGE))
1285 control_key_state_ = DOWN_WITH_CHANGE;
1287 if (!user_text_changed)
1288 return false;
1290 // If the user text has not changed, we do not want to change the model's
1291 // state associated with the text. Otherwise, we can get surprising behavior
1292 // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983
1293 InternalSetUserText(UserTextFromDisplayText(new_text));
1294 has_temporary_text_ = false;
1296 // Track when the user has deleted text so we won't allow inline
1297 // autocomplete.
1298 just_deleted_text_ = just_deleted_text;
1300 if (user_input_in_progress_ && user_text_.empty()) {
1301 // Log cases where the user started editing and then subsequently cleared
1302 // all the text. Note that this explicitly doesn't catch cases like
1303 // "hit ctrl-l to select whole edit contents, then hit backspace", because
1304 // in such cases, |user_input_in_progress| won't be true here.
1305 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
1306 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING,
1307 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
1310 const bool no_selection = selection_start == selection_end;
1312 // Update the popup for the change, in the process changing to keyword mode
1313 // if the user hit space in mid-string after a keyword.
1314 // |allow_exact_keyword_match_| will be used by StartAutocomplete() method,
1315 // which will be called by |view_->UpdatePopup()|; so after that returns we
1316 // can safely reset this flag.
1317 allow_exact_keyword_match_ = text_differs && allow_keyword_ui_change &&
1318 !just_deleted_text && no_selection &&
1319 CreatedKeywordSearchByInsertingSpaceInMiddle(old_text, user_text_,
1320 selection_start);
1321 view_->UpdatePopup();
1322 if (allow_exact_keyword_match_) {
1323 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram,
1324 ENTERED_KEYWORD_MODE_VIA_SPACE_IN_MIDDLE,
1325 ENTERED_KEYWORD_MODE_NUM_ITEMS);
1326 allow_exact_keyword_match_ = false;
1329 // Change to keyword mode if the user is now pressing space after a keyword
1330 // name. Note that if this is the case, then even if there was no keyword
1331 // hint when we entered this function (e.g. if the user has used space to
1332 // replace some selected text that was adjoined to this keyword), there will
1333 // be one now because of the call to UpdatePopup() above; so it's safe for
1334 // MaybeAcceptKeywordBySpace() to look at |keyword_| and |is_keyword_hint_| to
1335 // determine what keyword, if any, is applicable.
1337 // If MaybeAcceptKeywordBySpace() accepts the keyword and returns true, that
1338 // will have updated our state already, so in that case we don't also return
1339 // true from this function.
1340 return !(text_differs && allow_keyword_ui_change && !just_deleted_text &&
1341 no_selection && (selection_start == user_text_.length()) &&
1342 MaybeAcceptKeywordBySpace(user_text_));
1345 // TODO(beaudoin): Merge OnPopupDataChanged with this method once the popup
1346 // handling has completely migrated to omnibox_controller.
1347 void OmniboxEditModel::OnCurrentMatchChanged() {
1348 has_temporary_text_ = false;
1350 const AutocompleteMatch& match = omnibox_controller_->current_match();
1352 // We store |keyword| and |is_keyword_hint| in temporary variables since
1353 // OnPopupDataChanged use their previous state to detect changes.
1354 base::string16 keyword;
1355 bool is_keyword_hint;
1356 TemplateURLService* service =
1357 TemplateURLServiceFactory::GetForProfile(profile_);
1358 match.GetKeywordUIState(service, &keyword, &is_keyword_hint);
1359 if (popup_model())
1360 popup_model()->OnResultChanged();
1361 // OnPopupDataChanged() resets OmniboxController's |current_match_| early
1362 // on. Therefore, copy match.inline_autocompletion to a temp to preserve
1363 // its value across the entire call.
1364 const base::string16 inline_autocompletion(match.inline_autocompletion);
1365 OnPopupDataChanged(inline_autocompletion, NULL, keyword, is_keyword_hint);
1368 void OmniboxEditModel::SetSuggestionToPrefetch(
1369 const InstantSuggestion& suggestion) {
1370 client_->SetSuggestionToPrefetch(suggestion);
1373 // static
1374 const char OmniboxEditModel::kCutOrCopyAllTextHistogram[] =
1375 "Omnibox.CutOrCopyAllText";
1377 bool OmniboxEditModel::query_in_progress() const {
1378 return !autocomplete_controller()->done();
1381 void OmniboxEditModel::InternalSetUserText(const base::string16& text) {
1382 user_text_ = text;
1383 just_deleted_text_ = false;
1384 inline_autocomplete_text_.clear();
1385 view_->OnInlineAutocompleteTextCleared();
1388 void OmniboxEditModel::ClearPopupKeywordMode() const {
1389 omnibox_controller_->ClearPopupKeywordMode();
1392 base::string16 OmniboxEditModel::DisplayTextFromUserText(
1393 const base::string16& text) const {
1394 return is_keyword_selected() ?
1395 KeywordProvider::SplitReplacementStringFromInput(text, false) : text;
1398 base::string16 OmniboxEditModel::UserTextFromDisplayText(
1399 const base::string16& text) const {
1400 return is_keyword_selected() ? (keyword_ + base::char16(' ') + text) : text;
1403 void OmniboxEditModel::GetInfoForCurrentText(AutocompleteMatch* match,
1404 GURL* alternate_nav_url) const {
1405 DCHECK(match != NULL);
1407 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(
1408 false)) {
1409 // Any time the user hits enter on the unchanged omnibox, we should reload.
1410 // When we're not extracting search terms, AcceptInput() will take care of
1411 // this (see code referring to PAGE_TRANSITION_RELOAD there), but when we're
1412 // extracting search terms, the conditionals there won't fire, so we
1413 // explicitly set up a match that will reload here.
1415 // It's important that we fetch the current visible URL to reload instead of
1416 // just getting a "search what you typed" URL from
1417 // SearchProvider::CreateSearchSuggestion(), since the user may be in a
1418 // non-default search mode such as image search.
1419 match->type = AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED;
1420 match->provider = autocomplete_controller()->search_provider();
1421 match->destination_url =
1422 client_->GetNavigationController().GetVisibleEntry()->GetURL();
1423 match->transition = ui::PAGE_TRANSITION_RELOAD;
1424 } else if (query_in_progress() ||
1425 (popup_model() && popup_model()->IsOpen())) {
1426 if (query_in_progress()) {
1427 // It's technically possible for |result| to be empty if no provider
1428 // returns a synchronous result but the query has not completed
1429 // synchronously; pratically, however, that should never actually happen.
1430 if (result().empty())
1431 return;
1432 // The user cannot have manually selected a match, or the query would have
1433 // stopped. So the default match must be the desired selection.
1434 *match = *result().default_match();
1435 } else {
1436 // If there are no results, the popup should be closed, so we shouldn't
1437 // have gotten here.
1438 CHECK(!result().empty());
1439 CHECK(popup_model()->selected_line() < result().size());
1440 const AutocompleteMatch& selected_match =
1441 result().match_at(popup_model()->selected_line());
1442 *match =
1443 (popup_model()->selected_line_state() == OmniboxPopupModel::KEYWORD) ?
1444 *selected_match.associated_keyword : selected_match;
1446 if (alternate_nav_url &&
1447 (!popup_model() || popup_model()->manually_selected_match().empty()))
1448 *alternate_nav_url = result().alternate_nav_url();
1449 } else {
1450 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
1451 UserTextFromDisplayText(view_->GetText()), is_keyword_selected(), true,
1452 ClassifyPage(), match, alternate_nav_url);
1456 void OmniboxEditModel::RevertTemporaryText(bool revert_popup) {
1457 // The user typed something, then selected a different item. Restore the
1458 // text they typed and change back to the default item.
1459 // NOTE: This purposefully does not reset paste_state_.
1460 just_deleted_text_ = false;
1461 has_temporary_text_ = false;
1463 if (revert_popup && popup_model())
1464 popup_model()->ResetToDefaultMatch();
1465 view_->OnRevertTemporaryText();
1468 bool OmniboxEditModel::MaybeAcceptKeywordBySpace(
1469 const base::string16& new_text) {
1470 size_t keyword_length = new_text.length() - 1;
1471 return (paste_state_ == NONE) && is_keyword_hint_ &&
1472 (keyword_.length() == keyword_length) &&
1473 IsSpaceCharForAcceptingKeyword(new_text[keyword_length]) &&
1474 !new_text.compare(0, keyword_length, keyword_, 0, keyword_length) &&
1475 AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_SPACE_AT_END);
1478 bool OmniboxEditModel::CreatedKeywordSearchByInsertingSpaceInMiddle(
1479 const base::string16& old_text,
1480 const base::string16& new_text,
1481 size_t caret_position) const {
1482 DCHECK_GE(new_text.length(), caret_position);
1484 // Check simple conditions first.
1485 if ((paste_state_ != NONE) || (caret_position < 2) ||
1486 (old_text.length() < caret_position) ||
1487 (new_text.length() == caret_position))
1488 return false;
1489 size_t space_position = caret_position - 1;
1490 if (!IsSpaceCharForAcceptingKeyword(new_text[space_position]) ||
1491 base::IsUnicodeWhitespace(new_text[space_position - 1]) ||
1492 new_text.compare(0, space_position, old_text, 0, space_position) ||
1493 !new_text.compare(space_position, new_text.length() - space_position,
1494 old_text, space_position,
1495 old_text.length() - space_position)) {
1496 return false;
1499 // Then check if the text before the inserted space matches a keyword.
1500 base::string16 keyword;
1501 base::TrimWhitespace(new_text.substr(0, space_position), base::TRIM_LEADING,
1502 &keyword);
1503 return !keyword.empty() && !autocomplete_controller()->keyword_provider()->
1504 GetKeywordForText(keyword).empty();
1507 // static
1508 bool OmniboxEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c) {
1509 switch (c) {
1510 case 0x0020: // Space
1511 case 0x3000: // Ideographic Space
1512 return true;
1513 default:
1514 return false;
1518 OmniboxEventProto::PageClassification OmniboxEditModel::ClassifyPage() const {
1519 if (!client_->CurrentPageExists())
1520 return OmniboxEventProto::OTHER;
1521 if (client_->IsInstantNTP()) {
1522 // Note that we treat OMNIBOX as the source if focus_source_ is INVALID,
1523 // i.e., if input isn't actually in progress.
1524 return (focus_source_ == FAKEBOX) ?
1525 OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS :
1526 OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS;
1528 const GURL& gurl = client_->GetURL();
1529 if (!gurl.is_valid())
1530 return OmniboxEventProto::INVALID_SPEC;
1531 const std::string& url = gurl.spec();
1532 if (url == chrome::kChromeUINewTabURL)
1533 return OmniboxEventProto::NTP;
1534 if (url == url::kAboutBlankURL)
1535 return OmniboxEventProto::BLANK;
1536 if (url == profile()->GetPrefs()->GetString(prefs::kHomePage))
1537 return OmniboxEventProto::HOME_PAGE;
1538 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(true))
1539 return OmniboxEventProto::SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT;
1540 if (client_->IsSearchResultsPage())
1541 return OmniboxEventProto::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT;
1542 return OmniboxEventProto::OTHER;
1545 void OmniboxEditModel::ClassifyStringForPasteAndGo(
1546 const base::string16& text,
1547 AutocompleteMatch* match,
1548 GURL* alternate_nav_url) const {
1549 DCHECK(match);
1550 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
1551 text, false, false, ClassifyPage(), match, alternate_nav_url);
1554 void OmniboxEditModel::SetFocusState(OmniboxFocusState state,
1555 OmniboxFocusChangeReason reason) {
1556 if (state == focus_state_)
1557 return;
1559 // Update state and notify view if the omnibox has focus and the caret
1560 // visibility changed.
1561 const bool was_caret_visible = is_caret_visible();
1562 focus_state_ = state;
1563 if (focus_state_ != OMNIBOX_FOCUS_NONE &&
1564 is_caret_visible() != was_caret_visible)
1565 view_->ApplyCaretVisibility();
1567 client_->OnFocusChanged(focus_state_, reason);