Add a minor text member to ui::MenuModel.
[chromium-blink-merge.git] / chrome / browser / ui / omnibox / omnibox_edit_model.cc
blob5b1cb45a2deee036a089a981829f98015efd0a3b
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 <string>
9 #include "base/auto_reset.h"
10 #include "base/format_macros.h"
11 #include "base/metrics/histogram.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "chrome/app/chrome_command_ids.h"
17 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
18 #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
19 #include "chrome/browser/autocomplete/autocomplete_input.h"
20 #include "chrome/browser/autocomplete/autocomplete_provider.h"
21 #include "chrome/browser/autocomplete/extension_app_provider.h"
22 #include "chrome/browser/autocomplete/history_url_provider.h"
23 #include "chrome/browser/autocomplete/keyword_provider.h"
24 #include "chrome/browser/autocomplete/search_provider.h"
25 #include "chrome/browser/bookmarks/bookmark_utils.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/google/google_url_tracker.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.h"
40 #include "chrome/browser/search_engines/template_url_prepopulate_data.h"
41 #include "chrome/browser/search_engines/template_url_service.h"
42 #include "chrome/browser/search_engines/template_url_service_factory.h"
43 #include "chrome/browser/sessions/session_tab_helper.h"
44 #include "chrome/browser/ui/browser_list.h"
45 #include "chrome/browser/ui/omnibox/omnibox_current_page_delegate_impl.h"
46 #include "chrome/browser/ui/omnibox/omnibox_edit_controller.h"
47 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
48 #include "chrome/browser/ui/omnibox/omnibox_popup_view.h"
49 #include "chrome/browser/ui/omnibox/omnibox_view.h"
50 #include "chrome/browser/ui/search/instant_controller.h"
51 #include "chrome/browser/ui/search/search_tab_helper.h"
52 #include "chrome/browser/ui/toolbar/toolbar_model.h"
53 #include "chrome/common/chrome_switches.h"
54 #include "chrome/common/net/url_fixer_upper.h"
55 #include "chrome/common/pref_names.h"
56 #include "chrome/common/url_constants.h"
57 #include "content/public/browser/navigation_controller.h"
58 #include "content/public/browser/navigation_entry.h"
59 #include "content/public/browser/notification_service.h"
60 #include "content/public/browser/render_view_host.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 content::UserMetricsAction;
67 using predictors::AutocompleteActionPredictor;
68 using predictors::AutocompleteActionPredictorFactory;
70 namespace {
72 // Histogram name which counts the number of times that the user text is
73 // cleared. IME users are sometimes in the situation that IME was
74 // unintentionally turned on and failed to input latin alphabets (ASCII
75 // characters) or the opposite case. In that case, users may delete all
76 // the text and the user text gets cleared. We'd like to measure how often
77 // this scenario happens.
79 // Note that since we don't currently correlate "text cleared" events with
80 // IME usage, this also captures many other cases where users clear the text;
81 // though it explicitly doesn't log deleting all the permanent text as
82 // the first action of an editing sequence (see comments in
83 // OnAfterPossibleChange()).
84 const char kOmniboxUserTextClearedHistogram[] = "Omnibox.UserTextCleared";
86 enum UserTextClearedType {
87 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING = 0,
88 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE = 1,
89 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS,
92 // Histogram name which counts the number of times the user enters
93 // keyword hint mode and via what method. The possible values are listed
94 // in the EnteredKeywordModeMethod enum which is defined in the .h file.
95 const char kEnteredKeywordModeHistogram[] = "Omnibox.EnteredKeywordMode";
97 // Histogram name which counts the number of milliseconds a user takes
98 // between focusing and editing the omnibox.
99 const char kFocusToEditTimeHistogram[] = "Omnibox.FocusToEditTime";
101 // Histogram name which counts the number of milliseconds a user takes
102 // between focusing and opening an omnibox match.
103 const char kFocusToOpenTimeHistogram[] = "Omnibox.FocusToOpenTime";
105 void RecordPercentageMatchHistogram(const string16& old_text,
106 const string16& new_text,
107 bool search_term_replacement_active,
108 content::PageTransition transition) {
109 size_t avg_length = (old_text.length() + new_text.length()) / 2;
111 int percent = 0;
112 if (!old_text.empty() && !new_text.empty()) {
113 size_t shorter_length = std::min(old_text.length(), new_text.length());
114 string16::const_iterator end(old_text.begin() + shorter_length);
115 string16::const_iterator mismatch(
116 std::mismatch(old_text.begin(), end, new_text.begin()).first);
117 size_t matching_characters = mismatch - old_text.begin();
118 percent = static_cast<float>(matching_characters) / avg_length * 100;
121 if (search_term_replacement_active) {
122 if (transition == content::PAGE_TRANSITION_TYPED) {
123 UMA_HISTOGRAM_PERCENTAGE(
124 "InstantExtended.PercentageMatchV2_QuerytoURL", percent);
125 } else {
126 UMA_HISTOGRAM_PERCENTAGE(
127 "InstantExtended.PercentageMatchV2_QuerytoQuery", percent);
129 } else {
130 if (transition == content::PAGE_TRANSITION_TYPED) {
131 UMA_HISTOGRAM_PERCENTAGE(
132 "InstantExtended.PercentageMatchV2_URLtoURL", percent);
133 } else {
134 UMA_HISTOGRAM_PERCENTAGE(
135 "InstantExtended.PercentageMatchV2_URLtoQuery", percent);
140 } // namespace
142 ///////////////////////////////////////////////////////////////////////////////
143 // OmniboxEditModel::State
145 OmniboxEditModel::State::State(bool user_input_in_progress,
146 const string16& user_text,
147 const string16& gray_text,
148 const string16& keyword,
149 bool is_keyword_hint,
150 OmniboxFocusState focus_state,
151 FocusSource focus_source)
152 : user_input_in_progress(user_input_in_progress),
153 user_text(user_text),
154 gray_text(gray_text),
155 keyword(keyword),
156 is_keyword_hint(is_keyword_hint),
157 focus_state(focus_state),
158 focus_source(focus_source) {
161 OmniboxEditModel::State::~State() {
164 ///////////////////////////////////////////////////////////////////////////////
165 // OmniboxEditModel
167 OmniboxEditModel::OmniboxEditModel(OmniboxView* view,
168 OmniboxEditController* controller,
169 Profile* profile)
170 : view_(view),
171 controller_(controller),
172 focus_state_(OMNIBOX_FOCUS_NONE),
173 focus_source_(INVALID),
174 user_input_in_progress_(false),
175 user_input_since_focus_(true),
176 just_deleted_text_(false),
177 has_temporary_text_(false),
178 paste_state_(NONE),
179 control_key_state_(UP),
180 is_keyword_hint_(false),
181 profile_(profile),
182 in_revert_(false),
183 allow_exact_keyword_match_(false) {
184 omnibox_controller_.reset(new OmniboxController(this, profile));
185 delegate_.reset(new OmniboxCurrentPageDelegateImpl(controller, profile));
188 OmniboxEditModel::~OmniboxEditModel() {
191 const OmniboxEditModel::State OmniboxEditModel::GetStateForTabSwitch() {
192 // Like typing, switching tabs "accepts" the temporary text as the user
193 // text, because it makes little sense to have temporary text when the
194 // popup is closed.
195 if (user_input_in_progress_) {
196 // Weird edge case to match other browsers: if the edit is empty, revert to
197 // the permanent text (so the user can get it back easily) but select it (so
198 // on switching back, typing will "just work").
199 const string16 user_text(UserTextFromDisplayText(view_->GetText()));
200 if (user_text.empty()) {
201 base::AutoReset<bool> tmp(&in_revert_, true);
202 view_->RevertAll();
203 view_->SelectAll(true);
204 } else {
205 InternalSetUserText(user_text);
209 return State(user_input_in_progress_,
210 user_text_,
211 view_->GetGrayTextAutocompletion(),
212 keyword_,
213 is_keyword_hint_,
214 focus_state_,
215 focus_source_);
218 void OmniboxEditModel::RestoreState(const State* state) {
219 // We need to update the permanent text correctly and revert the view
220 // regardless of whether there is saved state.
221 permanent_text_ = controller_->GetToolbarModel()->GetText(true);
222 view_->RevertAll();
223 if (!state)
224 return;
226 SetFocusState(state->focus_state, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH);
227 focus_source_ = state->focus_source;
228 // Restore any user editing.
229 if (state->user_input_in_progress) {
230 // NOTE: Be sure and set keyword-related state BEFORE invoking
231 // DisplayTextFromUserText(), as its result depends upon this state.
232 keyword_ = state->keyword;
233 is_keyword_hint_ = state->is_keyword_hint;
234 view_->SetUserText(state->user_text,
235 DisplayTextFromUserText(state->user_text), false);
236 view_->SetGrayTextAutocompletion(state->gray_text);
240 AutocompleteMatch OmniboxEditModel::CurrentMatch(
241 GURL* alternate_nav_url) const {
242 // If we have a valid match use it. Otherwise get one for the current text.
243 AutocompleteMatch match = omnibox_controller_->current_match();
245 if (!match.destination_url.is_valid()) {
246 GetInfoForCurrentText(&match, alternate_nav_url);
247 } else if (alternate_nav_url) {
248 *alternate_nav_url = AutocompleteResult::ComputeAlternateNavUrl(
249 autocomplete_controller()->input(), match);
251 return match;
254 bool OmniboxEditModel::UpdatePermanentText() {
255 // When there's a new URL, and the user is not editing anything or the edit
256 // doesn't have focus, we want to revert the edit to show the new URL. (The
257 // common case where the edit doesn't have focus is when the user has started
258 // an edit and then abandoned it and clicked a link on the page.)
260 // If the page is auto-committing gray text, however, we generally don't want
261 // to make any change to the edit. While auto-commits modify the underlying
262 // permanent URL, they're intended to have no effect on the user's editing
263 // process -- before and after the auto-commit, the omnibox should show the
264 // same user text and the same instant suggestion, even if the auto-commit
265 // happens while the edit doesn't have focus.
266 string16 new_permanent_text = controller_->GetToolbarModel()->GetText(true);
267 string16 gray_text = view_->GetGrayTextAutocompletion();
268 const bool visibly_changed_permanent_text =
269 (permanent_text_ != new_permanent_text) &&
270 (!has_focus() ||
271 (!user_input_in_progress_ && !popup_model()->IsOpen())) &&
272 (gray_text.empty() ||
273 new_permanent_text != user_text_ + gray_text);
275 permanent_text_ = new_permanent_text;
276 return visibly_changed_permanent_text;
279 GURL OmniboxEditModel::PermanentURL() {
280 return URLFixerUpper::FixupURL(UTF16ToUTF8(permanent_text_), std::string());
283 void OmniboxEditModel::SetUserText(const string16& text) {
284 SetInputInProgress(true);
285 InternalSetUserText(text);
286 omnibox_controller_->InvalidateCurrentMatch();
287 paste_state_ = NONE;
288 has_temporary_text_ = false;
291 bool OmniboxEditModel::CommitSuggestedText() {
292 const string16 suggestion = view_->GetGrayTextAutocompletion();
293 if (suggestion.empty())
294 return false;
296 const string16 final_text = view_->GetText() + suggestion;
297 view_->OnBeforePossibleChange();
298 view_->SetWindowTextAndCaretPos(final_text, final_text.length(), false,
299 false);
300 view_->OnAfterPossibleChange();
301 return true;
304 void OmniboxEditModel::OnChanged() {
305 // Don't call CurrentMatch() when there's no editing, as in this case we'll
306 // never actually use it. This avoids running the autocomplete providers (and
307 // any systems they then spin up) during startup.
308 const AutocompleteMatch& current_match = user_input_in_progress_ ?
309 CurrentMatch(NULL) : AutocompleteMatch();
311 AutocompleteActionPredictor::Action recommended_action =
312 AutocompleteActionPredictor::ACTION_NONE;
313 AutocompleteActionPredictor* action_predictor =
314 user_input_in_progress_ ?
315 AutocompleteActionPredictorFactory::GetForProfile(profile_) : NULL;
316 if (action_predictor) {
317 action_predictor->RegisterTransitionalMatches(user_text_, result());
318 // Confer with the AutocompleteActionPredictor to determine what action, if
319 // any, we should take. Get the recommended action here even if we don't
320 // need it so we can get stats for anyone who is opted in to UMA, but only
321 // get it if the user has actually typed something to avoid constructing it
322 // before it's needed. Note: This event is triggered as part of startup when
323 // the initial tab transitions to the start page.
324 recommended_action =
325 action_predictor->RecommendAction(user_text_, current_match);
328 UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.Action",
329 recommended_action,
330 AutocompleteActionPredictor::LAST_PREDICT_ACTION);
332 // Hide any suggestions we might be showing.
333 view_->SetGrayTextAutocompletion(string16());
335 switch (recommended_action) {
336 case AutocompleteActionPredictor::ACTION_PRERENDER:
337 // It's possible that there is no current page, for instance if the tab
338 // has been closed or on return from a sleep state.
339 // (http://crbug.com/105689)
340 if (!delegate_->CurrentPageExists())
341 break;
342 // Ask for prerendering if the destination URL is different than the
343 // current URL.
344 if (current_match.destination_url != PermanentURL())
345 delegate_->DoPrerender(current_match);
346 break;
347 case AutocompleteActionPredictor::ACTION_PRECONNECT:
348 omnibox_controller_->DoPreconnect(current_match);
349 break;
350 case AutocompleteActionPredictor::ACTION_NONE:
351 break;
354 controller_->OnChanged();
357 void OmniboxEditModel::GetDataForURLExport(GURL* url,
358 string16* title,
359 gfx::Image* favicon) {
360 *url = CurrentMatch(NULL).destination_url;
361 if (*url == URLFixerUpper::FixupURL(UTF16ToUTF8(permanent_text_),
362 std::string())) {
363 *title = controller_->GetTitle();
364 *favicon = controller_->GetFavicon();
368 bool OmniboxEditModel::CurrentTextIsURL() const {
369 if (controller_->GetToolbarModel()->WouldReplaceSearchURLWithSearchTerms(
370 false))
371 return false;
373 // If current text is not composed of replaced search terms and
374 // !user_input_in_progress_, then permanent text is showing and should be a
375 // URL, so no further checking is needed. By avoiding checking in this case,
376 // we avoid calling into the autocomplete providers, and thus initializing the
377 // history system, as long as possible, which speeds startup.
378 if (!user_input_in_progress_)
379 return true;
381 return !AutocompleteMatch::IsSearchType(CurrentMatch(NULL).type);
384 AutocompleteMatch::Type OmniboxEditModel::CurrentTextType() const {
385 return CurrentMatch(NULL).type;
388 void OmniboxEditModel::AdjustTextForCopy(int sel_min,
389 bool is_all_selected,
390 string16* text,
391 GURL* url,
392 bool* write_url) {
393 *write_url = false;
395 // Do not adjust if selection did not start at the beginning of the field, or
396 // if the URL was replaced by search terms.
397 if ((sel_min != 0) ||
398 controller_->GetToolbarModel()->WouldReplaceSearchURLWithSearchTerms(
399 false))
400 return;
402 if (!user_input_in_progress_ && is_all_selected) {
403 // The user selected all the text and has not edited it. Use the url as the
404 // text so that if the scheme was stripped it's added back, and the url
405 // is unescaped (we escape parts of the url for display).
406 *url = PermanentURL();
407 *text = UTF8ToUTF16(url->spec());
408 *write_url = true;
409 return;
412 // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now
413 // the user is probably holding down control to cause the copy, which will
414 // screw up our calculation of the desired_tld.
415 AutocompleteMatch match;
416 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(*text,
417 KeywordIsSelected(), true, &match, NULL);
418 if (AutocompleteMatch::IsSearchType(match.type))
419 return;
420 *url = match.destination_url;
422 // Prefix the text with 'http://' if the text doesn't start with 'http://',
423 // the text parses as a url with a scheme of http, the user selected the
424 // entire host, and the user hasn't edited the host or manually removed the
425 // scheme.
426 GURL perm_url(PermanentURL());
427 if (perm_url.SchemeIs(chrome::kHttpScheme) &&
428 url->SchemeIs(chrome::kHttpScheme) && perm_url.host() == url->host()) {
429 *write_url = true;
430 string16 http = ASCIIToUTF16(chrome::kHttpScheme) +
431 ASCIIToUTF16(content::kStandardSchemeSeparator);
432 if (text->compare(0, http.length(), http) != 0)
433 *text = http + *text;
437 void OmniboxEditModel::SetInputInProgress(bool in_progress) {
438 if (in_progress && !user_input_since_focus_) {
439 base::TimeTicks now = base::TimeTicks::Now();
440 DCHECK(last_omnibox_focus_ <= now);
441 UMA_HISTOGRAM_TIMES(kFocusToEditTimeHistogram, now - last_omnibox_focus_);
442 user_input_since_focus_ = true;
445 if (user_input_in_progress_ == in_progress)
446 return;
448 user_input_in_progress_ = in_progress;
449 if (user_input_in_progress_) {
450 time_user_first_modified_omnibox_ = base::TimeTicks::Now();
451 content::RecordAction(content::UserMetricsAction("OmniboxInputInProgress"));
452 autocomplete_controller()->ResetSession();
454 controller_->OnInputInProgress(in_progress);
456 delegate_->NotifySearchTabHelper(user_input_in_progress_, !in_revert_);
459 void OmniboxEditModel::Revert() {
460 SetInputInProgress(false);
461 paste_state_ = NONE;
462 InternalSetUserText(string16());
463 keyword_.clear();
464 is_keyword_hint_ = false;
465 has_temporary_text_ = false;
466 view_->SetWindowTextAndCaretPos(permanent_text_,
467 has_focus() ? permanent_text_.length() : 0,
468 false, true);
469 AutocompleteActionPredictor* action_predictor =
470 AutocompleteActionPredictorFactory::GetForProfile(profile_);
471 if (action_predictor)
472 action_predictor->ClearTransitionalMatches();
475 void OmniboxEditModel::StartAutocomplete(
476 bool has_selected_text,
477 bool prevent_inline_autocomplete) const {
478 size_t cursor_position;
479 if (inline_autocomplete_text_.empty()) {
480 // Cursor position is equivalent to the current selection's end.
481 size_t start;
482 view_->GetSelectionBounds(&start, &cursor_position);
483 // Adjust cursor position taking into account possible keyword in the user
484 // text. We rely on DisplayTextFromUserText() method which is consistent
485 // with keyword extraction done in KeywordProvider/SearchProvider.
486 const size_t cursor_offset =
487 user_text_.length() - DisplayTextFromUserText(user_text_).length();
488 cursor_position += cursor_offset;
489 } else {
490 // There are some cases where StartAutocomplete() may be called
491 // with non-empty |inline_autocomplete_text_|. In such cases, we cannot
492 // use the current selection, because it could result with the cursor
493 // position past the last character from the user text. Instead,
494 // we assume that the cursor is simply at the end of input.
495 // One example is when user presses Ctrl key while having a highlighted
496 // inline autocomplete text.
497 // TODO: Rethink how we are going to handle this case to avoid
498 // inconsistent behavior when user presses Ctrl key.
499 // See http://crbug.com/165961 and http://crbug.com/165968 for more details.
500 cursor_position = user_text_.length();
503 GURL current_url =
504 (delegate_->CurrentPageExists() && view_->IsIndicatingQueryRefinement()) ?
505 delegate_->GetURL() : GURL();
506 bool keyword_is_selected = KeywordIsSelected();
507 omnibox_controller_->StartAutocomplete(
508 user_text_,
509 cursor_position,
510 current_url,
511 ClassifyPage(),
512 prevent_inline_autocomplete || just_deleted_text_ ||
513 (has_selected_text && inline_autocomplete_text_.empty()) ||
514 (paste_state_ != NONE),
515 keyword_is_selected,
516 keyword_is_selected || allow_exact_keyword_match_);
519 void OmniboxEditModel::StopAutocomplete() {
520 autocomplete_controller()->Stop(true);
523 bool OmniboxEditModel::CanPasteAndGo(const string16& text) const {
524 if (!view_->command_updater()->IsCommandEnabled(IDC_OPEN_CURRENT_URL))
525 return false;
527 AutocompleteMatch match;
528 ClassifyStringForPasteAndGo(text, &match, NULL);
529 return match.destination_url.is_valid();
532 void OmniboxEditModel::PasteAndGo(const string16& text) {
533 DCHECK(CanPasteAndGo(text));
534 view_->RevertAll();
535 AutocompleteMatch match;
536 GURL alternate_nav_url;
537 ClassifyStringForPasteAndGo(text, &match, &alternate_nav_url);
538 view_->OpenMatch(match, CURRENT_TAB, alternate_nav_url,
539 OmniboxPopupModel::kNoMatch);
542 bool OmniboxEditModel::IsPasteAndSearch(const string16& text) const {
543 AutocompleteMatch match;
544 ClassifyStringForPasteAndGo(text, &match, NULL);
545 return AutocompleteMatch::IsSearchType(match.type);
548 void OmniboxEditModel::AcceptInput(WindowOpenDisposition disposition,
549 bool for_drop) {
550 // Get the URL and transition type for the selected entry.
551 GURL alternate_nav_url;
552 AutocompleteMatch match = CurrentMatch(&alternate_nav_url);
554 // If CTRL is down it means the user wants to append ".com" to the text he
555 // typed. If we can successfully generate a URL_WHAT_YOU_TYPED match doing
556 // that, then we use this. These matches are marked as generated by the
557 // HistoryURLProvider so we only generate them if this provider is present.
558 if (control_key_state_ == DOWN_WITHOUT_CHANGE && !KeywordIsSelected() &&
559 autocomplete_controller()->history_url_provider()) {
560 // Generate a new AutocompleteInput, copying the latest one but using "com"
561 // as the desired TLD. Then use this autocomplete input to generate a
562 // URL_WHAT_YOU_TYPED AutocompleteMatch. Note that using the most recent
563 // input instead of the currently visible text means we'll ignore any
564 // visible inline autocompletion: if a user types "foo" and is autocompleted
565 // to "foodnetwork.com", ctrl-enter will navigate to "foo.com", not
566 // "foodnetwork.com". At the time of writing, this behavior matches
567 // Internet Explorer, but not Firefox.
568 const AutocompleteInput& old_input = autocomplete_controller()->input();
569 AutocompleteInput input(
570 old_input.text(), old_input.cursor_position(), ASCIIToUTF16("com"),
571 GURL(), old_input.current_page_classification(),
572 old_input.prevent_inline_autocomplete(), old_input.prefer_keyword(),
573 old_input.allow_exact_keyword_match(), old_input.matches_requested());
574 AutocompleteMatch url_match = HistoryURLProvider::SuggestExactInput(
575 autocomplete_controller()->history_url_provider(), input, true);
577 if (url_match.destination_url.is_valid()) {
578 // We have a valid URL, we use this newly generated AutocompleteMatch.
579 match = url_match;
580 alternate_nav_url = GURL();
584 if (!match.destination_url.is_valid())
585 return;
587 if ((match.transition == content::PAGE_TRANSITION_TYPED) &&
588 (match.destination_url ==
589 URLFixerUpper::FixupURL(UTF16ToUTF8(permanent_text_), std::string()))) {
590 // When the user hit enter on the existing permanent URL, treat it like a
591 // reload for scoring purposes. We could detect this by just checking
592 // user_input_in_progress_, but it seems better to treat "edits" that end
593 // up leaving the URL unchanged (e.g. deleting the last character and then
594 // retyping it) as reloads too. We exclude non-TYPED transitions because if
595 // the transition is GENERATED, the user input something that looked
596 // different from the current URL, even if it wound up at the same place
597 // (e.g. manually retyping the same search query), and it seems wrong to
598 // treat this as a reload.
599 match.transition = content::PAGE_TRANSITION_RELOAD;
600 } else if (for_drop || ((paste_state_ != NONE) &&
601 match.is_history_what_you_typed_match)) {
602 // When the user pasted in a URL and hit enter, score it like a link click
603 // rather than a normal typed URL, so it doesn't get inline autocompleted
604 // as aggressively later.
605 match.transition = content::PAGE_TRANSITION_LINK;
608 const TemplateURL* template_url = match.GetTemplateURL(profile_, false);
609 if (template_url && template_url->url_ref().HasGoogleBaseURLs())
610 GoogleURLTracker::GoogleURLSearchCommitted(profile_);
612 view_->OpenMatch(match, disposition, alternate_nav_url,
613 OmniboxPopupModel::kNoMatch);
616 void OmniboxEditModel::OpenMatch(const AutocompleteMatch& match,
617 WindowOpenDisposition disposition,
618 const GURL& alternate_nav_url,
619 size_t index) {
620 // We only care about cases where there is a selection (i.e. the popup is
621 // open).
622 if (popup_model()->IsOpen()) {
623 const base::TimeTicks& now(base::TimeTicks::Now());
624 base::TimeDelta elapsed_time_since_user_first_modified_omnibox(
625 now - time_user_first_modified_omnibox_);
626 base::TimeDelta elapsed_time_since_last_change_to_default_match(
627 now - autocomplete_controller()->last_time_default_match_changed());
628 // These elapsed times don't really make sense for ZeroSuggest matches
629 // (because the user does not modify the omnibox for ZeroSuggest), so for
630 // those we set the elapsed times to something that will be ignored by
631 // metrics_log.cc.
632 if (match.provider &&
633 match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST) {
634 elapsed_time_since_user_first_modified_omnibox =
635 base::TimeDelta::FromMilliseconds(-1);
636 elapsed_time_since_last_change_to_default_match =
637 base::TimeDelta::FromMilliseconds(-1);
639 OmniboxLog log(
640 autocomplete_controller()->input().text(),
641 just_deleted_text_,
642 autocomplete_controller()->input().type(),
643 popup_model()->selected_line(),
644 -1, // don't yet know tab ID; set later if appropriate
645 ClassifyPage(),
646 elapsed_time_since_user_first_modified_omnibox,
647 match.inline_autocompletion.length(),
648 elapsed_time_since_last_change_to_default_match,
649 result());
651 DCHECK(user_input_in_progress_ || (match.provider &&
652 match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST))
653 << "We didn't get here through the expected series of calls. "
654 << "time_user_first_modified_omnibox_ is not set correctly and other "
655 << "things may be wrong. Match provider: "
656 << (match.provider ? match.provider->GetName() : "NULL");
657 DCHECK(log.elapsed_time_since_user_first_modified_omnibox >=
658 log.elapsed_time_since_last_change_to_default_match)
659 << "We should've got the notification that the user modified the "
660 << "omnibox text at same time or before the most recent time the "
661 << "default match changed.";
663 if (index != OmniboxPopupModel::kNoMatch)
664 log.selected_index = index;
666 if ((disposition == CURRENT_TAB) && delegate_->CurrentPageExists()) {
667 // If we know the destination is being opened in the current tab,
668 // we can easily get the tab ID. (If it's being opened in a new
669 // tab, we don't know the tab ID yet.)
670 log.tab_id = delegate_->GetSessionID().id();
672 autocomplete_controller()->AddProvidersInfo(&log.providers_info);
673 content::NotificationService::current()->Notify(
674 chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
675 content::Source<Profile>(profile_),
676 content::Details<OmniboxLog>(&log));
677 HISTOGRAM_ENUMERATION("Omnibox.EventCount", 1, 2);
678 DCHECK(!last_omnibox_focus_.is_null())
679 << "An omnibox focus should have occurred before opening a match.";
680 UMA_HISTOGRAM_TIMES(kFocusToOpenTimeHistogram, now - last_omnibox_focus_);
683 TemplateURL* template_url = match.GetTemplateURL(profile_, false);
684 if (template_url) {
685 if (match.transition == content::PAGE_TRANSITION_KEYWORD) {
686 // The user is using a non-substituting keyword or is explicitly in
687 // keyword mode.
688 const AutocompleteMatch& match = (index == OmniboxPopupModel::kNoMatch) ?
689 CurrentMatch(NULL) : result().match_at(index);
691 // Don't increment usage count for extension keywords.
692 if (delegate_->ProcessExtensionKeyword(template_url, match,
693 disposition)) {
694 if (disposition != NEW_BACKGROUND_TAB)
695 view_->RevertAll();
696 return;
699 content::RecordAction(UserMetricsAction("AcceptedKeyword"));
700 TemplateURLServiceFactory::GetForProfile(profile_)->IncrementUsageCount(
701 template_url);
702 } else {
703 DCHECK_EQ(content::PAGE_TRANSITION_GENERATED, match.transition);
704 // NOTE: We purposefully don't increment the usage count of the default
705 // search engine here like we do for explicit keywords above; see comments
706 // in template_url.h.
709 // TODO(pkasting): This histogram obsoletes the next one. Remove the next
710 // one in Chrome 32 or later.
711 UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngineType",
712 TemplateURLPrepopulateData::GetEngineType(*template_url),
713 SEARCH_ENGINE_MAX);
714 // NOTE: Non-prepopulated engines will all have ID 0, which is fine as
715 // the prepopulate IDs start at 1. Distribution-specific engines will
716 // all have IDs above the maximum, and will be automatically lumped
717 // together in an "overflow" bucket in the histogram.
718 UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngine",
719 template_url->prepopulate_id(),
720 TemplateURLPrepopulateData::kMaxPrepopulatedEngineID);
723 // Get the current text before we call RevertAll() which will clear it.
724 string16 current_text = GetViewText();
726 if (disposition != NEW_BACKGROUND_TAB) {
727 base::AutoReset<bool> tmp(&in_revert_, true);
728 view_->RevertAll(); // Revert the box to its unedited state.
731 if (match.type == AutocompleteMatchType::EXTENSION_APP) {
732 ExtensionAppProvider::LaunchAppFromOmnibox(match, profile_, disposition);
733 } else {
734 base::TimeDelta query_formulation_time =
735 base::TimeTicks::Now() - time_user_first_modified_omnibox_;
736 const GURL destination_url = autocomplete_controller()->
737 GetDestinationURL(match, query_formulation_time);
739 RecordPercentageMatchHistogram(
740 permanent_text_, current_text,
741 controller_->GetToolbarModel()->WouldReplaceSearchURLWithSearchTerms(
742 false),
743 match.transition);
745 // Track whether the destination URL sends us to a search results page
746 // using the default search provider.
747 if (TemplateURLServiceFactory::GetForProfile(profile_)->
748 IsSearchResultsPageFromDefaultSearchProvider(destination_url)) {
749 content::RecordAction(
750 UserMetricsAction("OmniboxDestinationURLIsSearchOnDSP"));
753 // This calls RevertAll again.
754 base::AutoReset<bool> tmp(&in_revert_, true);
755 controller_->OnAutocompleteAccept(destination_url, disposition,
756 match.transition, alternate_nav_url);
759 if (match.starred)
760 bookmark_utils::RecordBookmarkLaunch(bookmark_utils::LAUNCH_OMNIBOX);
763 bool OmniboxEditModel::AcceptKeyword(EnteredKeywordModeMethod entered_method) {
764 DCHECK(is_keyword_hint_ && !keyword_.empty());
766 autocomplete_controller()->Stop(false);
767 is_keyword_hint_ = false;
769 if (popup_model()->IsOpen())
770 popup_model()->SetSelectedLineState(OmniboxPopupModel::KEYWORD);
771 else
772 StartAutocomplete(false, true);
774 // Ensure the current selection is saved before showing keyword mode
775 // so that moving to another line and then reverting the text will restore
776 // the current state properly.
777 bool save_original_selection = !has_temporary_text_;
778 has_temporary_text_ = true;
779 view_->OnTemporaryTextMaybeChanged(
780 DisplayTextFromUserText(CurrentMatch(NULL).fill_into_edit),
781 save_original_selection, true);
783 content::RecordAction(UserMetricsAction("AcceptedKeywordHint"));
784 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram, entered_method,
785 ENTERED_KEYWORD_MODE_NUM_ITEMS);
787 return true;
790 void OmniboxEditModel::AcceptTemporaryTextAsUserText() {
791 InternalSetUserText(UserTextFromDisplayText(view_->GetText()));
792 has_temporary_text_ = false;
793 delegate_->NotifySearchTabHelper(user_input_in_progress_, !in_revert_);
796 void OmniboxEditModel::ClearKeyword(const string16& visible_text) {
797 autocomplete_controller()->Stop(false);
798 omnibox_controller_->ClearPopupKeywordMode();
800 const string16 window_text(keyword_ + visible_text);
802 // Only reset the result if the edit text has changed since the
803 // keyword was accepted, or if the popup is closed.
804 if (just_deleted_text_ || !visible_text.empty() || !popup_model()->IsOpen()) {
805 view_->OnBeforePossibleChange();
806 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
807 false, false);
808 keyword_.clear();
809 is_keyword_hint_ = false;
810 view_->OnAfterPossibleChange();
811 just_deleted_text_ = true; // OnAfterPossibleChange() fails to clear this
812 // since the edit contents have actually grown
813 // longer.
814 } else {
815 is_keyword_hint_ = true;
816 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(),
817 false, true);
821 void OmniboxEditModel::OnSetFocus(bool control_down) {
822 last_omnibox_focus_ = base::TimeTicks::Now();
823 user_input_since_focus_ = false;
825 // If the omnibox lost focus while the caret was hidden and then regained
826 // focus, OnSetFocus() is called and should restore visibility. Note that
827 // focus can be regained without an accompanying call to
828 // OmniboxView::SetFocus(), e.g. by tabbing in.
829 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_EXPLICIT);
830 control_key_state_ = control_down ? DOWN_WITHOUT_CHANGE : UP;
832 // Try to get ZeroSuggest suggestions if a page is loaded and the user has
833 // not been typing in the omnibox. The |user_input_in_progress_| check is
834 // used to detect the case where this function is called after right-clicking
835 // in the omnibox and selecting paste in Linux (in which case we actually get
836 // the OnSetFocus() call after the process of handling the paste has kicked
837 // off).
838 // TODO(hfung): Remove this when crbug/271590 is fixed.
839 if (delegate_->CurrentPageExists() && !user_input_in_progress_) {
840 // TODO(jered): We may want to merge this into Start() and just call that
841 // here rather than having a special entry point for zero-suggest. Note
842 // that we avoid PermanentURL() here because it's not guaranteed to give us
843 // the actual underlying current URL, e.g. if we're on the NTP and the
844 // |permanent_text_| is empty.
845 autocomplete_controller()->StartZeroSuggest(delegate_->GetURL(),
846 ClassifyPage(),
847 permanent_text_);
850 delegate_->NotifySearchTabHelper(user_input_in_progress_, !in_revert_);
853 void OmniboxEditModel::SetCaretVisibility(bool visible) {
854 // Caret visibility only matters if the omnibox has focus.
855 if (focus_state_ != OMNIBOX_FOCUS_NONE) {
856 SetFocusState(visible ? OMNIBOX_FOCUS_VISIBLE : OMNIBOX_FOCUS_INVISIBLE,
857 OMNIBOX_FOCUS_CHANGE_EXPLICIT);
861 void OmniboxEditModel::OnWillKillFocus(gfx::NativeView view_gaining_focus) {
862 InstantController* instant = GetInstantController();
863 if (instant) {
864 instant->OmniboxFocusChanged(OMNIBOX_FOCUS_NONE,
865 OMNIBOX_FOCUS_CHANGE_EXPLICIT,
866 view_gaining_focus);
869 // TODO(jered): Rip this out along with StartZeroSuggest.
870 autocomplete_controller()->StopZeroSuggest();
871 delegate_->NotifySearchTabHelper(user_input_in_progress_, !in_revert_);
874 void OmniboxEditModel::OnKillFocus() {
875 // TODO(samarth): determine if it is safe to move the call to
876 // OmniboxFocusChanged() from OnWillKillFocus() to here, which would let us
877 // just call SetFocusState() to handle the state change.
878 focus_state_ = OMNIBOX_FOCUS_NONE;
879 focus_source_ = INVALID;
880 control_key_state_ = UP;
881 paste_state_ = NONE;
884 bool OmniboxEditModel::OnEscapeKeyPressed() {
885 const AutocompleteMatch& match = CurrentMatch(NULL);
886 if (has_temporary_text_) {
887 if (match.destination_url != original_url_) {
888 RevertTemporaryText(true);
889 return true;
893 // We do not clear the pending entry from the omnibox when a load is first
894 // stopped. If the user presses Escape while stopped, we clear it.
895 if (delegate_->CurrentPageExists() && !delegate_->IsLoading()) {
896 delegate_->GetNavigationController().DiscardNonCommittedEntries();
897 view_->Update();
900 // If the user wasn't editing, but merely had focus in the edit, allow <esc>
901 // to be processed as an accelerator, so it can still be used to stop a load.
902 // When the permanent text isn't all selected we still fall through to the
903 // SelectAll() call below so users can arrow around in the text and then hit
904 // <esc> to quickly replace all the text; this matches IE.
905 const bool has_zero_suggest_match = match.provider &&
906 (match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST);
907 if (!has_zero_suggest_match && !user_input_in_progress_ &&
908 view_->IsSelectAll())
909 return false;
911 if (!user_text_.empty()) {
912 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
913 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE,
914 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
916 view_->RevertAll();
917 view_->SelectAll(true);
918 return true;
921 void OmniboxEditModel::OnControlKeyChanged(bool pressed) {
922 if (pressed == (control_key_state_ == UP))
923 control_key_state_ = pressed ? DOWN_WITHOUT_CHANGE : UP;
926 void OmniboxEditModel::OnUpOrDownKeyPressed(int count) {
927 // NOTE: This purposefully doesn't trigger any code that resets paste_state_.
928 if (popup_model()->IsOpen()) {
929 // The popup is open, so the user should be able to interact with it
930 // normally.
931 popup_model()->Move(count);
932 return;
935 if (!query_in_progress()) {
936 // The popup is neither open nor working on a query already. So, start an
937 // autocomplete query for the current text. This also sets
938 // user_input_in_progress_ to true, which we want: if the user has started
939 // to interact with the popup, changing the permanent_text_ shouldn't change
940 // the displayed text.
941 // Note: This does not force the popup to open immediately.
942 // TODO(pkasting): We should, in fact, force this particular query to open
943 // the popup immediately.
944 if (!user_input_in_progress_)
945 InternalSetUserText(permanent_text_);
946 view_->UpdatePopup();
947 return;
950 // TODO(pkasting): The popup is working on a query but is not open. We should
951 // force it to open immediately.
954 void OmniboxEditModel::OnPopupDataChanged(
955 const string16& text,
956 GURL* destination_for_temporary_text_change,
957 const string16& keyword,
958 bool is_keyword_hint) {
959 // The popup changed its data, the match in the controller is no longer valid.
960 omnibox_controller_->InvalidateCurrentMatch();
962 // Update keyword/hint-related local state.
963 bool keyword_state_changed = (keyword_ != keyword) ||
964 ((is_keyword_hint_ != is_keyword_hint) && !keyword.empty());
965 if (keyword_state_changed) {
966 keyword_ = keyword;
967 is_keyword_hint_ = is_keyword_hint;
969 // |is_keyword_hint_| should always be false if |keyword_| is empty.
970 DCHECK(!keyword_.empty() || !is_keyword_hint_);
973 // Handle changes to temporary text.
974 if (destination_for_temporary_text_change != NULL) {
975 const bool save_original_selection = !has_temporary_text_;
976 if (save_original_selection) {
977 // Save the original selection and URL so it can be reverted later.
978 has_temporary_text_ = true;
979 original_url_ = *destination_for_temporary_text_change;
980 inline_autocomplete_text_.clear();
982 if (control_key_state_ == DOWN_WITHOUT_CHANGE) {
983 // Arrowing around the popup cancels control-enter.
984 control_key_state_ = DOWN_WITH_CHANGE;
985 // Now things are a bit screwy: the desired_tld has changed, but if we
986 // update the popup, the new order of entries won't match the old, so the
987 // user's selection gets screwy; and if we don't update the popup, and the
988 // user reverts, then the selected item will be as if control is still
989 // pressed, even though maybe it isn't any more. There is no obvious
990 // right answer here :(
992 view_->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text),
993 save_original_selection, true);
994 return;
997 bool call_controller_onchanged = true;
998 inline_autocomplete_text_ = text;
1000 string16 user_text = user_input_in_progress_ ? user_text_ : permanent_text_;
1001 if (keyword_state_changed && KeywordIsSelected()) {
1002 // If we reach here, the user most likely entered keyword mode by inserting
1003 // a space between a keyword name and a search string (as pressing space or
1004 // tab after the keyword name alone would have been be handled in
1005 // MaybeAcceptKeywordBySpace() by calling AcceptKeyword(), which won't reach
1006 // here). In this case, we don't want to call
1007 // OnInlineAutocompleteTextMaybeChanged() as normal, because that will
1008 // correctly change the text (to the search string alone) but move the caret
1009 // to the end of the string; instead we want the caret at the start of the
1010 // search string since that's where it was in the original input. So we set
1011 // the text and caret position directly.
1013 // It may also be possible to reach here if we're reverting from having
1014 // temporary text back to a default match that's a keyword search, but in
1015 // that case the RevertTemporaryText() call below will reset the caret or
1016 // selection correctly so the caret positioning we do here won't matter.
1017 view_->SetWindowTextAndCaretPos(DisplayTextFromUserText(user_text), 0,
1018 false, false);
1019 } else if (view_->OnInlineAutocompleteTextMaybeChanged(
1020 DisplayTextFromUserText(user_text + inline_autocomplete_text_),
1021 DisplayTextFromUserText(user_text).length())) {
1022 call_controller_onchanged = false;
1025 // If |has_temporary_text_| is true, then we previously had a manual selection
1026 // but now don't (or |destination_for_temporary_text_change| would have been
1027 // non-NULL). This can happen when deleting the selected item in the popup.
1028 // In this case, we've already reverted the popup to the default match, so we
1029 // need to revert ourselves as well.
1030 if (has_temporary_text_) {
1031 RevertTemporaryText(false);
1032 call_controller_onchanged = false;
1035 // We need to invoke OnChanged in case the destination url changed (as could
1036 // happen when control is toggled).
1037 if (call_controller_onchanged)
1038 OnChanged();
1041 bool OmniboxEditModel::OnAfterPossibleChange(const string16& old_text,
1042 const string16& new_text,
1043 size_t selection_start,
1044 size_t selection_end,
1045 bool selection_differs,
1046 bool text_differs,
1047 bool just_deleted_text,
1048 bool allow_keyword_ui_change) {
1049 // Update the paste state as appropriate: if we're just finishing a paste
1050 // that replaced all the text, preserve that information; otherwise, if we've
1051 // made some other edit, clear paste tracking.
1052 if (paste_state_ == PASTING)
1053 paste_state_ = PASTED;
1054 else if (text_differs)
1055 paste_state_ = NONE;
1057 if (text_differs || selection_differs) {
1058 // Record current focus state for this input if we haven't already.
1059 if (focus_source_ == INVALID) {
1060 // We should generally expect the omnibox to have focus at this point, but
1061 // it doesn't always on Linux. This is because, unlike other platforms,
1062 // right clicking in the omnibox on Linux doesn't focus it. So pasting via
1063 // right-click can change the contents without focusing the omnibox.
1064 // TODO(samarth): fix Linux focus behavior and add a DCHECK here to
1065 // check that the omnibox does have focus.
1066 focus_source_ = (focus_state_ == OMNIBOX_FOCUS_INVISIBLE) ?
1067 FAKEBOX : OMNIBOX;
1070 // Restore caret visibility whenever the user changes text or selection in
1071 // the omnibox.
1072 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_TYPING);
1075 // Modifying the selection counts as accepting the autocompleted text.
1076 const bool user_text_changed =
1077 text_differs || (selection_differs && !inline_autocomplete_text_.empty());
1079 // If something has changed while the control key is down, prevent
1080 // "ctrl-enter" until the control key is released.
1081 if ((text_differs || selection_differs) &&
1082 (control_key_state_ == DOWN_WITHOUT_CHANGE))
1083 control_key_state_ = DOWN_WITH_CHANGE;
1085 if (!user_text_changed)
1086 return false;
1088 // If the user text has not changed, we do not want to change the model's
1089 // state associated with the text. Otherwise, we can get surprising behavior
1090 // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983
1091 InternalSetUserText(UserTextFromDisplayText(new_text));
1092 has_temporary_text_ = false;
1094 // Track when the user has deleted text so we won't allow inline
1095 // autocomplete.
1096 just_deleted_text_ = just_deleted_text;
1098 if (user_input_in_progress_ && user_text_.empty()) {
1099 // Log cases where the user started editing and then subsequently cleared
1100 // all the text. Note that this explicitly doesn't catch cases like
1101 // "hit ctrl-l to select whole edit contents, then hit backspace", because
1102 // in such cases, |user_input_in_progress| won't be true here.
1103 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram,
1104 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING,
1105 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS);
1108 const bool no_selection = selection_start == selection_end;
1110 // Update the popup for the change, in the process changing to keyword mode
1111 // if the user hit space in mid-string after a keyword.
1112 // |allow_exact_keyword_match_| will be used by StartAutocomplete() method,
1113 // which will be called by |view_->UpdatePopup()|; so after that returns we
1114 // can safely reset this flag.
1115 allow_exact_keyword_match_ = text_differs && allow_keyword_ui_change &&
1116 !just_deleted_text && no_selection &&
1117 CreatedKeywordSearchByInsertingSpaceInMiddle(old_text, user_text_,
1118 selection_start);
1119 if (allow_exact_keyword_match_) {
1120 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram,
1121 ENTERED_KEYWORD_MODE_VIA_SPACE_IN_MIDDLE,
1122 ENTERED_KEYWORD_MODE_NUM_ITEMS);
1124 view_->UpdatePopup();
1125 allow_exact_keyword_match_ = false;
1127 // Change to keyword mode if the user is now pressing space after a keyword
1128 // name. Note that if this is the case, then even if there was no keyword
1129 // hint when we entered this function (e.g. if the user has used space to
1130 // replace some selected text that was adjoined to this keyword), there will
1131 // be one now because of the call to UpdatePopup() above; so it's safe for
1132 // MaybeAcceptKeywordBySpace() to look at |keyword_| and |is_keyword_hint_| to
1133 // determine what keyword, if any, is applicable.
1135 // If MaybeAcceptKeywordBySpace() accepts the keyword and returns true, that
1136 // will have updated our state already, so in that case we don't also return
1137 // true from this function.
1138 return !(text_differs && allow_keyword_ui_change && !just_deleted_text &&
1139 no_selection && (selection_start == user_text_.length()) &&
1140 MaybeAcceptKeywordBySpace(user_text_));
1143 // TODO(beaudoin): Merge OnPopupDataChanged with this method once the popup
1144 // handling has completely migrated to omnibox_controller.
1145 void OmniboxEditModel::OnCurrentMatchChanged() {
1146 has_temporary_text_ = false;
1148 const AutocompleteMatch& match = omnibox_controller_->current_match();
1150 // We store |keyword| and |is_keyword_hint| in temporary variables since
1151 // OnPopupDataChanged use their previous state to detect changes.
1152 string16 keyword;
1153 bool is_keyword_hint;
1154 match.GetKeywordUIState(profile_, &keyword, &is_keyword_hint);
1155 popup_model()->OnResultChanged();
1156 // OnPopupDataChanged() resets OmniboxController's |current_match_| early
1157 // on. Therefore, copy match.inline_autocompletion to a temp to preserve
1158 // its value across the entire call.
1159 const string16 inline_autocompletion(match.inline_autocompletion);
1160 OnPopupDataChanged(inline_autocompletion, NULL, keyword, is_keyword_hint);
1163 string16 OmniboxEditModel::GetViewText() const {
1164 return view_->GetText();
1167 InstantController* OmniboxEditModel::GetInstantController() const {
1168 return controller_->GetInstant();
1171 bool OmniboxEditModel::query_in_progress() const {
1172 return !autocomplete_controller()->done();
1175 void OmniboxEditModel::InternalSetUserText(const string16& text) {
1176 user_text_ = text;
1177 just_deleted_text_ = false;
1178 inline_autocomplete_text_.clear();
1181 bool OmniboxEditModel::KeywordIsSelected() const {
1182 return !is_keyword_hint_ && !keyword_.empty();
1185 void OmniboxEditModel::ClearPopupKeywordMode() const {
1186 omnibox_controller_->ClearPopupKeywordMode();
1189 string16 OmniboxEditModel::DisplayTextFromUserText(const string16& text) const {
1190 return KeywordIsSelected() ?
1191 KeywordProvider::SplitReplacementStringFromInput(text, false) : text;
1194 string16 OmniboxEditModel::UserTextFromDisplayText(const string16& text) const {
1195 return KeywordIsSelected() ? (keyword_ + char16(' ') + text) : text;
1198 void OmniboxEditModel::GetInfoForCurrentText(AutocompleteMatch* match,
1199 GURL* alternate_nav_url) const {
1200 DCHECK(match != NULL);
1202 if (controller_->GetToolbarModel()->WouldReplaceSearchURLWithSearchTerms(
1203 false)) {
1204 // Any time the user hits enter on the unchanged omnibox, we should reload.
1205 // When we're not extracting search terms, AcceptInput() will take care of
1206 // this (see code referring to PAGE_TRANSITION_RELOAD there), but when we're
1207 // extracting search terms, the conditionals there won't fire, so we
1208 // explicitly set up a match that will reload here.
1210 // It's important that we fetch the current visible URL to reload instead of
1211 // just getting a "search what you typed" URL from
1212 // SearchProvider::CreateSearchSuggestion(), since the user may be in a
1213 // non-default search mode such as image search.
1214 match->type = AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED;
1215 match->destination_url =
1216 delegate_->GetNavigationController().GetVisibleEntry()->GetURL();
1217 match->transition = content::PAGE_TRANSITION_RELOAD;
1218 } else if (popup_model()->IsOpen() || query_in_progress()) {
1219 if (query_in_progress()) {
1220 // It's technically possible for |result| to be empty if no provider
1221 // returns a synchronous result but the query has not completed
1222 // synchronously; pratically, however, that should never actually happen.
1223 if (result().empty())
1224 return;
1225 // The user cannot have manually selected a match, or the query would have
1226 // stopped. So the default match must be the desired selection.
1227 *match = *result().default_match();
1228 } else {
1229 // If there are no results, the popup should be closed, so we shouldn't
1230 // have gotten here.
1231 CHECK(!result().empty());
1232 CHECK(popup_model()->selected_line() < result().size());
1233 *match = result().match_at(popup_model()->selected_line());
1235 if (alternate_nav_url && popup_model()->manually_selected_match().empty())
1236 *alternate_nav_url = result().alternate_nav_url();
1237 } else {
1238 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
1239 UserTextFromDisplayText(view_->GetText()), KeywordIsSelected(), true,
1240 match, alternate_nav_url);
1244 void OmniboxEditModel::RevertTemporaryText(bool revert_popup) {
1245 // The user typed something, then selected a different item. Restore the
1246 // text they typed and change back to the default item.
1247 // NOTE: This purposefully does not reset paste_state_.
1248 just_deleted_text_ = false;
1249 has_temporary_text_ = false;
1251 if (revert_popup)
1252 popup_model()->ResetToDefaultMatch();
1253 view_->OnRevertTemporaryText();
1256 bool OmniboxEditModel::MaybeAcceptKeywordBySpace(const string16& new_text) {
1257 size_t keyword_length = new_text.length() - 1;
1258 return (paste_state_ == NONE) && is_keyword_hint_ && !keyword_.empty() &&
1259 inline_autocomplete_text_.empty() &&
1260 (keyword_.length() == keyword_length) &&
1261 IsSpaceCharForAcceptingKeyword(new_text[keyword_length]) &&
1262 !new_text.compare(0, keyword_length, keyword_, 0, keyword_length) &&
1263 AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_SPACE_AT_END);
1266 bool OmniboxEditModel::CreatedKeywordSearchByInsertingSpaceInMiddle(
1267 const string16& old_text,
1268 const string16& new_text,
1269 size_t caret_position) const {
1270 DCHECK_GE(new_text.length(), caret_position);
1272 // Check simple conditions first.
1273 if ((paste_state_ != NONE) || (caret_position < 2) ||
1274 (old_text.length() < caret_position) ||
1275 (new_text.length() == caret_position))
1276 return false;
1277 size_t space_position = caret_position - 1;
1278 if (!IsSpaceCharForAcceptingKeyword(new_text[space_position]) ||
1279 IsWhitespace(new_text[space_position - 1]) ||
1280 new_text.compare(0, space_position, old_text, 0, space_position) ||
1281 !new_text.compare(space_position, new_text.length() - space_position,
1282 old_text, space_position,
1283 old_text.length() - space_position)) {
1284 return false;
1287 // Then check if the text before the inserted space matches a keyword.
1288 string16 keyword;
1289 TrimWhitespace(new_text.substr(0, space_position), TRIM_LEADING, &keyword);
1290 return !keyword.empty() && !autocomplete_controller()->keyword_provider()->
1291 GetKeywordForText(keyword).empty();
1294 // static
1295 bool OmniboxEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c) {
1296 switch (c) {
1297 case 0x0020: // Space
1298 case 0x3000: // Ideographic Space
1299 return true;
1300 default:
1301 return false;
1305 AutocompleteInput::PageClassification OmniboxEditModel::ClassifyPage() const {
1306 if (!delegate_->CurrentPageExists())
1307 return AutocompleteInput::OTHER;
1308 if (delegate_->IsInstantNTP()) {
1309 // Note that we treat OMNIBOX as the source if focus_source_ is INVALID,
1310 // i.e., if input isn't actually in progress.
1311 return (focus_source_ == FAKEBOX) ?
1312 AutocompleteInput::INSTANT_NEW_TAB_PAGE_WITH_FAKEBOX_AS_STARTING_FOCUS :
1313 AutocompleteInput::INSTANT_NEW_TAB_PAGE_WITH_OMNIBOX_AS_STARTING_FOCUS;
1315 const GURL& gurl = delegate_->GetURL();
1316 if (!gurl.is_valid())
1317 return AutocompleteInput::INVALID_SPEC;
1318 const std::string& url = gurl.spec();
1319 if (url == chrome::kChromeUINewTabURL)
1320 return AutocompleteInput::NEW_TAB_PAGE;
1321 if (url == content::kAboutBlankURL)
1322 return AutocompleteInput::BLANK;
1323 if (url == profile()->GetPrefs()->GetString(prefs::kHomePage))
1324 return AutocompleteInput::HOME_PAGE;
1325 if (controller_->GetToolbarModel()->WouldReplaceSearchURLWithSearchTerms(
1326 true))
1327 return AutocompleteInput::SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT;
1328 if (delegate_->IsSearchResultsPage())
1329 return AutocompleteInput::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT;
1330 return AutocompleteInput::OTHER;
1333 void OmniboxEditModel::ClassifyStringForPasteAndGo(
1334 const string16& text,
1335 AutocompleteMatch* match,
1336 GURL* alternate_nav_url) const {
1337 DCHECK(match);
1338 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(text,
1339 false, false, match, alternate_nav_url);
1342 void OmniboxEditModel::SetFocusState(OmniboxFocusState state,
1343 OmniboxFocusChangeReason reason) {
1344 if (state == focus_state_)
1345 return;
1347 InstantController* instant = GetInstantController();
1348 if (instant)
1349 instant->OmniboxFocusChanged(state, reason, NULL);
1351 // Update state and notify view if the omnibox has focus and the caret
1352 // visibility changed.
1353 const bool was_caret_visible = is_caret_visible();
1354 focus_state_ = state;
1355 if (focus_state_ != OMNIBOX_FOCUS_NONE &&
1356 is_caret_visible() != was_caret_visible)
1357 view_->ApplyCaretVisibility();