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