Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / views / omnibox / omnibox_view_views.cc
1 // Copyright (c) 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/views/omnibox/omnibox_view_views.h"
6
7 #include "base/command_line.h"
8 #include "base/logging.h"
9 #include "base/metrics/histogram.h"
10 #include "base/strings/string_util.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "chrome/app/chrome_command_ids.h"
13 #include "chrome/browser/autocomplete/autocomplete_input.h"
14 #include "chrome/browser/autocomplete/autocomplete_match.h"
15 #include "chrome/browser/command_updater.h"
16 #include "chrome/browser/search/search.h"
17 #include "chrome/browser/ui/omnibox/omnibox_edit_controller.h"
18 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
19 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
20 #include "chrome/browser/ui/view_ids.h"
21 #include "chrome/browser/ui/views/location_bar/location_bar_view.h"
22 #include "chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h"
23 #include "chrome/browser/ui/views/settings_api_bubble_helper_views.h"
24 #include "chrome/browser/ui/views/website_settings/website_settings_popup_view.h"
25 #include "components/bookmarks/core/browser/bookmark_node_data.h"
26 #include "content/public/browser/web_contents.h"
27 #include "extensions/common/constants.h"
28 #include "grit/app_locale_settings.h"
29 #include "grit/generated_resources.h"
30 #include "grit/ui_strings.h"
31 #include "net/base/escape.h"
32 #include "third_party/skia/include/core/SkColor.h"
33 #include "ui/accessibility/ax_view_state.h"
34 #include "ui/aura/client/focus_client.h"
35 #include "ui/aura/window_event_dispatcher.h"
36 #include "ui/base/clipboard/scoped_clipboard_writer.h"
37 #include "ui/base/dragdrop/drag_drop_types.h"
38 #include "ui/base/dragdrop/os_exchange_data.h"
39 #include "ui/base/ime/text_input_client.h"
40 #include "ui/base/ime/text_input_type.h"
41 #include "ui/base/l10n/l10n_util.h"
42 #include "ui/base/models/simple_menu_model.h"
43 #include "ui/base/resource/resource_bundle.h"
44 #include "ui/compositor/layer.h"
45 #include "ui/events/event.h"
46 #include "ui/gfx/animation/slide_animation.h"
47 #include "ui/gfx/canvas.h"
48 #include "ui/gfx/font_list.h"
49 #include "ui/gfx/selection_model.h"
50 #include "ui/views/border.h"
51 #include "ui/views/button_drag_utils.h"
52 #include "ui/views/controls/textfield/textfield.h"
53 #include "ui/views/ime/input_method.h"
54 #include "ui/views/layout/fill_layout.h"
55 #include "ui/views/views_delegate.h"
56 #include "ui/views/widget/widget.h"
57 #include "url/gurl.h"
58
59 #if defined(OS_WIN)
60 #include "chrome/browser/browser_process.h"
61 #endif
62
63 namespace {
64
65 // Stores omnibox state for each tab.
66 struct OmniboxState : public base::SupportsUserData::Data {
67   static const char kKey[];
68
69   OmniboxState(const OmniboxEditModel::State& model_state,
70                const gfx::Range& selection,
71                const gfx::Range& saved_selection_for_focus_change);
72   virtual ~OmniboxState();
73
74   const OmniboxEditModel::State model_state;
75
76   // We store both the actual selection and any saved selection (for when the
77   // omnibox is not focused).  This allows us to properly handle cases like
78   // selecting text, tabbing out of the omnibox, switching tabs away and back,
79   // and tabbing back into the omnibox.
80   const gfx::Range selection;
81   const gfx::Range saved_selection_for_focus_change;
82 };
83
84 // static
85 const char OmniboxState::kKey[] = "OmniboxState";
86
87 OmniboxState::OmniboxState(const OmniboxEditModel::State& model_state,
88                            const gfx::Range& selection,
89                            const gfx::Range& saved_selection_for_focus_change)
90     : model_state(model_state),
91       selection(selection),
92       saved_selection_for_focus_change(saved_selection_for_focus_change) {
93 }
94
95 OmniboxState::~OmniboxState() {}
96
97 // We'd like to set the text input type to TEXT_INPUT_TYPE_URL, because this
98 // triggers URL-specific layout in software keyboards, e.g. adding top-level "/"
99 // and ".com" keys for English.  However, this also causes IMEs to default to
100 // Latin character mode, which makes entering search queries difficult for IME
101 // users.  Therefore, we try to guess whether an IME will be used based on the
102 // application language, and set the input type accordingly.
103 ui::TextInputType DetermineTextInputType() {
104 #if defined(OS_WIN)
105   DCHECK(g_browser_process);
106   const std::string& locale = g_browser_process->GetApplicationLocale();
107   const std::string& language = locale.substr(0, 2);
108   // Assume CJK + Thai users are using an IME.
109   if (language == "ja" ||
110       language == "ko" ||
111       language == "th" ||
112       language == "zh")
113     return ui::TEXT_INPUT_TYPE_SEARCH;
114 #endif
115   return ui::TEXT_INPUT_TYPE_URL;
116 }
117
118 }  // namespace
119
120 // static
121 const char OmniboxViewViews::kViewClassName[] = "OmniboxViewViews";
122
123 OmniboxViewViews::OmniboxViewViews(OmniboxEditController* controller,
124                                    Profile* profile,
125                                    CommandUpdater* command_updater,
126                                    bool popup_window_mode,
127                                    LocationBarView* location_bar,
128                                    const gfx::FontList& font_list)
129     : OmniboxView(profile, controller, command_updater),
130       popup_window_mode_(popup_window_mode),
131       security_level_(ToolbarModel::NONE),
132       saved_selection_for_focus_change_(gfx::Range::InvalidRange()),
133       ime_composing_before_change_(false),
134       delete_at_end_pressed_(false),
135       location_bar_view_(location_bar),
136       ime_candidate_window_open_(false),
137       select_all_on_mouse_release_(false),
138       select_all_on_gesture_tap_(false) {
139   SetBorder(views::Border::NullBorder());
140   set_id(VIEW_ID_OMNIBOX);
141   SetFontList(font_list);
142 }
143
144 OmniboxViewViews::~OmniboxViewViews() {
145 #if defined(OS_CHROMEOS)
146   chromeos::input_method::InputMethodManager::Get()->
147       RemoveCandidateWindowObserver(this);
148 #endif
149
150   // Explicitly teardown members which have a reference to us.  Just to be safe
151   // we want them to be destroyed before destroying any other internal state.
152   popup_view_.reset();
153 }
154
155 ////////////////////////////////////////////////////////////////////////////////
156 // OmniboxViewViews public:
157
158 void OmniboxViewViews::Init() {
159   set_controller(this);
160   SetTextInputType(DetermineTextInputType());
161
162   if (popup_window_mode_)
163     SetReadOnly(true);
164
165   // Initialize the popup view using the same font.
166   popup_view_.reset(OmniboxPopupContentsView::Create(
167       GetFontList(), this, model(), location_bar_view_));
168
169 #if defined(OS_CHROMEOS)
170   chromeos::input_method::InputMethodManager::Get()->
171       AddCandidateWindowObserver(this);
172 #endif
173
174   fade_in_animation_.reset(new gfx::SlideAnimation(this));
175   fade_in_animation_->SetTweenType(gfx::Tween::LINEAR);
176   fade_in_animation_->SetSlideDuration(300);
177 }
178
179 void OmniboxViewViews::FadeIn() {
180   fade_in_animation_->Show();
181 }
182
183 ////////////////////////////////////////////////////////////////////////////////
184 // OmniboxViewViews, public OmniboxView implementation:
185
186 void OmniboxViewViews::SaveStateToTab(content::WebContents* tab) {
187   DCHECK(tab);
188
189   // We don't want to keep the IME status, so force quit the current
190   // session here.  It may affect the selection status, so order is
191   // also important.
192   if (IsIMEComposing()) {
193     GetTextInputClient()->ConfirmCompositionText();
194     GetInputMethod()->CancelComposition(this);
195   }
196
197   // NOTE: GetStateForTabSwitch() may affect GetSelectedRange(), so order is
198   // important.
199   OmniboxEditModel::State state = model()->GetStateForTabSwitch();
200   tab->SetUserData(OmniboxState::kKey, new OmniboxState(
201       state, GetSelectedRange(), saved_selection_for_focus_change_));
202 }
203
204 void OmniboxViewViews::OnTabChanged(const content::WebContents* web_contents) {
205   security_level_ = controller()->GetToolbarModel()->GetSecurityLevel(false);
206
207   const OmniboxState* state = static_cast<OmniboxState*>(
208       web_contents->GetUserData(&OmniboxState::kKey));
209   model()->RestoreState(state ? &state->model_state : NULL);
210   if (state) {
211     // This assumes that the omnibox has already been focused or blurred as
212     // appropriate; otherwise, a subsequent OnFocus() or OnBlur() call could
213     // goof up the selection.  See comments at the end of
214     // BrowserView::ActiveTabChanged().
215     SelectRange(state->selection);
216     saved_selection_for_focus_change_ = state->saved_selection_for_focus_change;
217   }
218
219   // TODO(msw|oshima): Consider saving/restoring edit history.
220   ClearEditHistory();
221 }
222
223 void OmniboxViewViews::Update() {
224   if (chrome::ShouldDisplayOriginChip() || chrome::ShouldDisplayOriginChipV2())
225     set_placeholder_text(GetHintText());
226
227   const ToolbarModel::SecurityLevel old_security_level = security_level_;
228   security_level_ = controller()->GetToolbarModel()->GetSecurityLevel(false);
229   if (model()->UpdatePermanentText()) {
230     // Something visibly changed.  Re-enable URL replacement.
231     controller()->GetToolbarModel()->set_url_replacement_enabled(true);
232     model()->UpdatePermanentText();
233
234     // Select all the new text if the user had all the old text selected, or if
235     // there was no previous text (for new tab page URL replacement extensions).
236     // This makes one particular case better: the user clicks in the box to
237     // change it right before the permanent URL is changed.  Since the new URL
238     // is still fully selected, the user's typing will replace the edit contents
239     // as they'd intended.
240     const bool was_select_all = IsSelectAll();
241     const bool was_reversed = GetSelectedRange().is_reversed();
242
243     RevertAll();
244
245     // Only select all when we have focus.  If we don't have focus, selecting
246     // all is unnecessary since the selection will change on regaining focus,
247     // and can in fact cause artifacts, e.g. if the user is on the NTP and
248     // clicks a link to navigate, causing |was_select_all| to be vacuously true
249     // for the empty omnibox, and we then select all here, leading to the
250     // trailing portion of a long URL being scrolled into view.  We could try
251     // and address cases like this, but it seems better to just not muck with
252     // things when the omnibox isn't focused to begin with.
253     if (was_select_all && model()->has_focus())
254       SelectAll(was_reversed);
255   } else if (old_security_level != security_level_) {
256     EmphasizeURLComponents();
257   }
258 }
259
260 base::string16 OmniboxViewViews::GetText() const {
261   // TODO(oshima): IME support
262   return text();
263 }
264
265 void OmniboxViewViews::SetUserText(const base::string16& text,
266                                    const base::string16& display_text,
267                                    bool update_popup) {
268   saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
269   OmniboxView::SetUserText(text, display_text, update_popup);
270 }
271
272 void OmniboxViewViews::SetForcedQuery() {
273   const base::string16 current_text(text());
274   const size_t start = current_text.find_first_not_of(base::kWhitespaceUTF16);
275   if (start == base::string16::npos || (current_text[start] != '?'))
276     OmniboxView::SetUserText(base::ASCIIToUTF16("?"));
277   else
278     SelectRange(gfx::Range(current_text.size(), start + 1));
279 }
280
281 void OmniboxViewViews::GetSelectionBounds(
282     base::string16::size_type* start,
283     base::string16::size_type* end) const {
284   const gfx::Range range = GetSelectedRange();
285   *start = static_cast<size_t>(range.start());
286   *end = static_cast<size_t>(range.end());
287 }
288
289 void OmniboxViewViews::SelectAll(bool reversed) {
290   views::Textfield::SelectAll(reversed);
291 }
292
293 void OmniboxViewViews::RevertAll() {
294   saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
295   OmniboxView::RevertAll();
296 }
297
298 void OmniboxViewViews::SetFocus() {
299   RequestFocus();
300   // Restore caret visibility if focus is explicitly requested. This is
301   // necessary because if we already have invisible focus, the RequestFocus()
302   // call above will short-circuit, preventing us from reaching
303   // OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the
304   // omnibox regains focus after losing focus.
305   model()->SetCaretVisibility(true);
306 }
307
308 int OmniboxViewViews::GetTextWidth() const {
309   // Returns the width necessary to display the current text, including any
310   // necessary space for the cursor or border/margin.
311   return GetRenderText()->GetContentWidth() + GetInsets().width();
312 }
313
314 bool OmniboxViewViews::IsImeComposing() const {
315   return IsIMEComposing();
316 }
317
318 void OmniboxViewViews::ExecuteCommand(int command_id, int event_flags) {
319   switch (command_id) {
320     // These commands don't invoke the popup via OnBefore/AfterPossibleChange().
321     case IDS_PASTE_AND_GO:
322       model()->PasteAndGo(GetClipboardText());
323       break;
324     case IDS_SHOW_URL:
325       controller()->ShowURL();
326       break;
327     case IDC_EDIT_SEARCH_ENGINES:
328       command_updater()->ExecuteCommand(command_id);
329       break;
330     case IDS_MOVE_DOWN:
331     case IDS_MOVE_UP:
332       model()->OnUpOrDownKeyPressed(command_id == IDS_MOVE_DOWN ? 1 : -1);
333       break;
334
335     default:
336       OnBeforePossibleChange();
337       if (command_id == IDS_APP_PASTE)
338         OnPaste();
339       else if (Textfield::IsCommandIdEnabled(command_id))
340         Textfield::ExecuteCommand(command_id, event_flags);
341       else
342         command_updater()->ExecuteCommand(command_id);
343       OnAfterPossibleChange();
344       break;
345   }
346 }
347
348 ////////////////////////////////////////////////////////////////////////////////
349 // OmniboxViewViews, private:
350
351 int OmniboxViewViews::GetOmniboxTextLength() const {
352   // TODO(oshima): Support IME.
353   return static_cast<int>(text().length());
354 }
355
356 void OmniboxViewViews::EmphasizeURLComponents() {
357   // See whether the contents are a URL with a non-empty host portion, which we
358   // should emphasize.  To check for a URL, rather than using the type returned
359   // by Parse(), ask the model, which will check the desired page transition for
360   // this input.  This can tell us whether an UNKNOWN input string is going to
361   // be treated as a search or a navigation, and is the same method the Paste
362   // And Go system uses.
363   url::Component scheme, host;
364   AutocompleteInput::ParseForEmphasizeComponents(text(), &scheme, &host);
365   bool grey_out_url = text().substr(scheme.begin, scheme.len) ==
366       base::UTF8ToUTF16(extensions::kExtensionScheme);
367   bool grey_base = model()->CurrentTextIsURL() &&
368       (host.is_nonempty() || grey_out_url);
369   SetColor(location_bar_view_->GetColor(
370       security_level_,
371       grey_base ? LocationBarView::DEEMPHASIZED_TEXT : LocationBarView::TEXT));
372   if (grey_base && !grey_out_url) {
373     ApplyColor(
374         location_bar_view_->GetColor(security_level_, LocationBarView::TEXT),
375         gfx::Range(host.begin, host.end()));
376   }
377
378   // Emphasize the scheme for security UI display purposes (if necessary).
379   // Note that we check CurrentTextIsURL() because if we're replacing search
380   // URLs with search terms, we may have a non-URL even when the user is not
381   // editing; and in some cases, e.g. for "site:foo.com" searches, the parser
382   // may have incorrectly identified a qualifier as a scheme.
383   SetStyle(gfx::DIAGONAL_STRIKE, false);
384   if (!model()->user_input_in_progress() && model()->CurrentTextIsURL() &&
385       scheme.is_nonempty() && (security_level_ != ToolbarModel::NONE)) {
386     SkColor security_color = location_bar_view_->GetColor(
387         security_level_, LocationBarView::SECURITY_TEXT);
388     const bool strike = (security_level_ == ToolbarModel::SECURITY_ERROR);
389     const gfx::Range scheme_range(scheme.begin, scheme.end());
390     ApplyColor(security_color, scheme_range);
391     ApplyStyle(gfx::DIAGONAL_STRIKE, strike, scheme_range);
392   }
393 }
394
395 void OmniboxViewViews::SetTextAndSelectedRange(const base::string16& text,
396                                                const gfx::Range& range) {
397   SetText(text);
398   SelectRange(range);
399 }
400
401 base::string16 OmniboxViewViews::GetSelectedText() const {
402   // TODO(oshima): Support IME.
403   return views::Textfield::GetSelectedText();
404 }
405
406 void OmniboxViewViews::OnPaste() {
407   const base::string16 text(GetClipboardText());
408   if (!text.empty()) {
409     // Record this paste, so we can do different behavior.
410     model()->OnPaste();
411     // Force a Paste operation to trigger the text_changed code in
412     // OnAfterPossibleChange(), even if identical contents are pasted.
413     text_before_change_.clear();
414     InsertOrReplaceText(text);
415   }
416 }
417
418 bool OmniboxViewViews::HandleEarlyTabActions(const ui::KeyEvent& event) {
419   // This must run before acclerator handling invokes a focus change on tab.
420   // Note the parallel with SkipDefaultKeyEventProcessing above.
421   if (views::FocusManager::IsTabTraversalKeyEvent(event)) {
422     if (model()->is_keyword_hint() && !event.IsShiftDown()) {
423       model()->AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_TAB);
424       return true;
425     }
426     if (model()->popup_model()->IsOpen()) {
427       if (event.IsShiftDown() &&
428           model()->popup_model()->selected_line_state() ==
429               OmniboxPopupModel::KEYWORD) {
430         model()->ClearKeyword(text());
431       } else {
432         model()->OnUpOrDownKeyPressed(event.IsShiftDown() ? -1 : 1);
433       }
434       return true;
435     }
436   }
437
438   return false;
439 }
440
441 ////////////////////////////////////////////////////////////////////////////////
442 // OmniboxViewViews, private View implementation:
443
444 void OmniboxViewViews::OnNativeThemeChanged(const ui::NativeTheme* theme) {
445   views::Textfield::OnNativeThemeChanged(theme);
446   SetBackgroundColor(location_bar_view_->GetColor(
447       ToolbarModel::NONE, LocationBarView::BACKGROUND));
448   EmphasizeURLComponents();
449 }
450
451 ////////////////////////////////////////////////////////////////////////////////
452 // OmniboxViewViews, private OmniboxView implementation:
453
454 void OmniboxViewViews::SetWindowTextAndCaretPos(const base::string16& text,
455                                                 size_t caret_pos,
456                                                 bool update_popup,
457                                                 bool notify_text_changed) {
458   const gfx::Range range(caret_pos, caret_pos);
459   SetTextAndSelectedRange(text, range);
460
461   if (update_popup)
462     UpdatePopup();
463
464   if (notify_text_changed)
465     TextChanged();
466 }
467
468 bool OmniboxViewViews::IsSelectAll() const {
469   // TODO(oshima): IME support.
470   return text() == GetSelectedText();
471 }
472
473 bool OmniboxViewViews::DeleteAtEndPressed() {
474   return delete_at_end_pressed_;
475 }
476
477 void OmniboxViewViews::UpdatePopup() {
478   model()->SetInputInProgress(true);
479   if (!model()->has_focus())
480     return;
481
482   // Prevent inline autocomplete when the caret isn't at the end of the text.
483   const gfx::Range sel = GetSelectedRange();
484   model()->StartAutocomplete(!sel.is_empty(), sel.GetMax() < text().length());
485 }
486
487 void OmniboxViewViews::ApplyCaretVisibility() {
488   SetCursorEnabled(model()->is_caret_visible());
489 }
490
491 void OmniboxViewViews::OnTemporaryTextMaybeChanged(
492     const base::string16& display_text,
493     bool save_original_selection,
494     bool notify_text_changed) {
495   if (save_original_selection)
496     saved_temporary_selection_ = GetSelectedRange();
497
498   SetWindowTextAndCaretPos(display_text, display_text.length(), false,
499                            notify_text_changed);
500 }
501
502 bool OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged(
503     const base::string16& display_text,
504     size_t user_text_length) {
505   if (display_text == text())
506     return false;
507
508   if (IsIMEComposing()) {
509     location_bar_view_->SetImeInlineAutocompletion(
510         display_text.substr(user_text_length));
511   } else {
512     gfx::Range range(display_text.size(), user_text_length);
513     SetTextAndSelectedRange(display_text, range);
514   }
515   TextChanged();
516   return true;
517 }
518
519 void OmniboxViewViews::OnInlineAutocompleteTextCleared() {
520   // Hide the inline autocompletion for IME users.
521   location_bar_view_->SetImeInlineAutocompletion(base::string16());
522 }
523
524 void OmniboxViewViews::OnRevertTemporaryText() {
525   SelectRange(saved_temporary_selection_);
526   // We got here because the user hit the Escape key. We explicitly don't call
527   // TextChanged(), since OmniboxPopupModel::ResetToDefaultMatch() has already
528   // been called by now, and it would've called TextChanged() if it was
529   // warranted.
530 }
531
532 void OmniboxViewViews::OnBeforePossibleChange() {
533   // Record our state.
534   text_before_change_ = text();
535   sel_before_change_ = GetSelectedRange();
536   ime_composing_before_change_ = IsIMEComposing();
537 }
538
539 bool OmniboxViewViews::OnAfterPossibleChange() {
540   // See if the text or selection have changed since OnBeforePossibleChange().
541   const base::string16 new_text = text();
542   const gfx::Range new_sel = GetSelectedRange();
543   const bool text_changed = (new_text != text_before_change_) ||
544       (ime_composing_before_change_ != IsIMEComposing());
545   const bool selection_differs =
546       !((sel_before_change_.is_empty() && new_sel.is_empty()) ||
547         sel_before_change_.EqualsIgnoringDirection(new_sel));
548
549   // When the user has deleted text, we don't allow inline autocomplete.  Make
550   // sure to not flag cases like selecting part of the text and then pasting
551   // (or typing) the prefix of that selection.  (We detect these by making
552   // sure the caret, which should be after any insertion, hasn't moved
553   // forward of the old selection start.)
554   const bool just_deleted_text =
555       (text_before_change_.length() > new_text.length()) &&
556       (new_sel.start() <= sel_before_change_.GetMin());
557
558   const bool something_changed = model()->OnAfterPossibleChange(
559       text_before_change_, new_text, new_sel.start(), new_sel.end(),
560       selection_differs, text_changed, just_deleted_text, !IsIMEComposing());
561
562   // If only selection was changed, we don't need to call model()'s
563   // OnChanged() method, which is called in TextChanged().
564   // But we still need to call EmphasizeURLComponents() to make sure the text
565   // attributes are updated correctly.
566   if (something_changed && text_changed)
567     TextChanged();
568   else if (selection_differs)
569     EmphasizeURLComponents();
570   else if (delete_at_end_pressed_)
571     model()->OnChanged();
572
573   return something_changed;
574 }
575
576 gfx::NativeView OmniboxViewViews::GetNativeView() const {
577   return GetWidget()->GetNativeView();
578 }
579
580 gfx::NativeView OmniboxViewViews::GetRelativeWindowForPopup() const {
581   return GetWidget()->GetTopLevelWidget()->GetNativeView();
582 }
583
584 void OmniboxViewViews::SetGrayTextAutocompletion(const base::string16& input) {
585   location_bar_view_->SetGrayTextAutocompletion(input);
586 }
587
588 base::string16 OmniboxViewViews::GetGrayTextAutocompletion() const {
589   return location_bar_view_->GetGrayTextAutocompletion();
590 }
591
592 int OmniboxViewViews::GetWidth() const {
593   return location_bar_view_->width();
594 }
595
596 bool OmniboxViewViews::IsImeShowingPopup() const {
597 #if defined(OS_CHROMEOS)
598   return ime_candidate_window_open_;
599 #else
600   const views::InputMethod* input_method = this->GetInputMethod();
601   return input_method && input_method->IsCandidatePopupOpen();
602 #endif
603 }
604
605 void OmniboxViewViews::ShowImeIfNeeded() {
606   GetInputMethod()->ShowImeIfNeeded();
607 }
608
609 void OmniboxViewViews::OnMatchOpened(const AutocompleteMatch& match,
610                                      Profile* profile,
611                                      content::WebContents* web_contents) const {
612   extensions::MaybeShowExtensionControlledSearchNotification(
613       profile, web_contents, match);
614 }
615
616 bool OmniboxViewViews::IsCommandIdEnabled(int command_id) const {
617   if (command_id == IDS_APP_PASTE)
618     return !read_only() && !GetClipboardText().empty();
619   if (command_id == IDS_PASTE_AND_GO)
620     return !read_only() && model()->CanPasteAndGo(GetClipboardText());
621   if (command_id == IDS_SHOW_URL)
622     return controller()->GetToolbarModel()->WouldReplaceURL();
623   return command_id == IDS_MOVE_DOWN || command_id == IDS_MOVE_UP ||
624          Textfield::IsCommandIdEnabled(command_id) ||
625          command_updater()->IsCommandEnabled(command_id);
626 }
627
628 bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id) const {
629   return command_id == IDS_PASTE_AND_GO;
630 }
631
632 base::string16 OmniboxViewViews::GetLabelForCommandId(int command_id) const {
633   DCHECK_EQ(IDS_PASTE_AND_GO, command_id);
634   return l10n_util::GetStringUTF16(
635       model()->IsPasteAndSearch(GetClipboardText()) ?
636           IDS_PASTE_AND_SEARCH : IDS_PASTE_AND_GO);
637 }
638
639 ////////////////////////////////////////////////////////////////////////////////
640 // OmniboxViewViews, private views::Textfield implementation:
641
642 const char* OmniboxViewViews::GetClassName() const {
643   return kViewClassName;
644 }
645
646 void OmniboxViewViews::OnPaint(gfx::Canvas* canvas) {
647   if (fade_in_animation_->is_animating()) {
648     canvas->SaveLayerAlpha(static_cast<uint8>(
649         fade_in_animation_->CurrentValueBetween(0, 255)));
650     views::Textfield::OnPaint(canvas);
651     canvas->Restore();
652   } else {
653     views::Textfield::OnPaint(canvas);
654   }
655 }
656
657 bool OmniboxViewViews::OnMousePressed(const ui::MouseEvent& event) {
658   select_all_on_mouse_release_ =
659       (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) &&
660       (!HasFocus() || (model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE));
661   if (select_all_on_mouse_release_) {
662     // Restore caret visibility whenever the user clicks in the omnibox in a way
663     // that would give it focus.  We must handle this case separately here
664     // because if the omnibox currently has invisible focus, the mouse event
665     // won't trigger either SetFocus() or OmniboxEditModel::OnSetFocus().
666     model()->SetCaretVisibility(true);
667
668     // When we're going to select all on mouse release, invalidate any saved
669     // selection lest restoring it fights with the "select all" action.  It's
670     // possible to later set select_all_on_mouse_release_ back to false, but
671     // that happens for things like dragging, which are cases where having
672     // invalidated this saved selection is still OK.
673     saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
674   }
675   return views::Textfield::OnMousePressed(event);
676 }
677
678 bool OmniboxViewViews::OnMouseDragged(const ui::MouseEvent& event) {
679   if (ExceededDragThreshold(event.location() - last_click_location()))
680     select_all_on_mouse_release_ = false;
681
682   if (HasTextBeingDragged())
683     CloseOmniboxPopup();
684
685   return views::Textfield::OnMouseDragged(event);
686 }
687
688 void OmniboxViewViews::OnMouseReleased(const ui::MouseEvent& event) {
689   views::Textfield::OnMouseReleased(event);
690   if (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) {
691     // When the user has clicked and released to give us focus, select all
692     // unless we're omitting the URL (in which case refining an existing query
693     // is common enough that we do click-to-place-cursor).
694     if (select_all_on_mouse_release_ &&
695         !controller()->GetToolbarModel()->WouldReplaceURL()) {
696       // Select all in the reverse direction so as not to scroll the caret
697       // into view and shift the contents jarringly.
698       SelectAll(true);
699     }
700
701     HandleOriginChipMouseRelease();
702   }
703   select_all_on_mouse_release_ = false;
704 }
705
706 bool OmniboxViewViews::OnKeyPressed(const ui::KeyEvent& event) {
707   // Skip processing of [Alt]+<num-pad digit> Unicode alt key codes.
708   // Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc.
709   if (event.IsUnicodeKeyCode())
710     return views::Textfield::OnKeyPressed(event);
711
712   const bool shift = event.IsShiftDown();
713   const bool control = event.IsControlDown();
714   const bool alt = event.IsAltDown() || event.IsAltGrDown();
715   switch (event.key_code()) {
716     case ui::VKEY_RETURN:
717       model()->AcceptInput(alt ? NEW_FOREGROUND_TAB : CURRENT_TAB, false);
718       return true;
719     case ui::VKEY_ESCAPE:
720       return model()->OnEscapeKeyPressed();
721     case ui::VKEY_CONTROL:
722       model()->OnControlKeyChanged(true);
723       break;
724     case ui::VKEY_DELETE:
725       if (shift && model()->popup_model()->IsOpen())
726         model()->popup_model()->TryDeletingCurrentItem();
727       break;
728     case ui::VKEY_UP:
729       if (!read_only()) {
730         model()->OnUpOrDownKeyPressed(-1);
731         return true;
732       }
733       break;
734     case ui::VKEY_DOWN:
735       if (!read_only()) {
736         model()->OnUpOrDownKeyPressed(1);
737         return true;
738       }
739       break;
740     case ui::VKEY_PRIOR:
741       if (control || alt || shift)
742         return false;
743       model()->OnUpOrDownKeyPressed(-1 * model()->result().size());
744       return true;
745     case ui::VKEY_NEXT:
746       if (control || alt || shift)
747         return false;
748       model()->OnUpOrDownKeyPressed(model()->result().size());
749       return true;
750     case ui::VKEY_V:
751       if (control && !alt && !read_only()) {
752         ExecuteCommand(IDS_APP_PASTE, 0);
753         return true;
754       }
755       break;
756     case ui::VKEY_INSERT:
757       if (shift && !control && !read_only()) {
758         ExecuteCommand(IDS_APP_PASTE, 0);
759         return true;
760       }
761       break;
762     default:
763       break;
764   }
765
766   return views::Textfield::OnKeyPressed(event) || HandleEarlyTabActions(event);
767 }
768
769 bool OmniboxViewViews::OnKeyReleased(const ui::KeyEvent& event) {
770   // The omnibox contents may change while the control key is pressed.
771   if (event.key_code() == ui::VKEY_CONTROL)
772     model()->OnControlKeyChanged(false);
773   return views::Textfield::OnKeyReleased(event);
774 }
775
776 void OmniboxViewViews::OnGestureEvent(ui::GestureEvent* event) {
777   if (!HasFocus() && event->type() == ui::ET_GESTURE_TAP_DOWN) {
778     select_all_on_gesture_tap_ = true;
779
780     // If we're trying to select all on tap, invalidate any saved selection lest
781     // restoring it fights with the "select all" action.
782     saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
783   }
784
785   if (select_all_on_gesture_tap_ && event->type() == ui::ET_GESTURE_TAP)
786     SelectAll(false);
787
788   if (event->type() == ui::ET_GESTURE_TAP ||
789       event->type() == ui::ET_GESTURE_TAP_CANCEL ||
790       event->type() == ui::ET_GESTURE_TWO_FINGER_TAP ||
791       event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||
792       event->type() == ui::ET_GESTURE_PINCH_BEGIN ||
793       event->type() == ui::ET_GESTURE_LONG_PRESS ||
794       event->type() == ui::ET_GESTURE_LONG_TAP) {
795     select_all_on_gesture_tap_ = false;
796   }
797
798   views::Textfield::OnGestureEvent(event);
799 }
800
801 void OmniboxViewViews::AboutToRequestFocusFromTabTraversal(bool reverse) {
802   views::Textfield::AboutToRequestFocusFromTabTraversal(reverse);
803   // Tabbing into the omnibox should affect the origin chip in the same way
804   // clicking it should.
805   HandleOriginChipMouseRelease();
806 }
807
808 bool OmniboxViewViews::SkipDefaultKeyEventProcessing(
809     const ui::KeyEvent& event) {
810   if (views::FocusManager::IsTabTraversalKeyEvent(event) &&
811       ((model()->is_keyword_hint() && !event.IsShiftDown()) ||
812        model()->popup_model()->IsOpen())) {
813     return true;
814   }
815   return Textfield::SkipDefaultKeyEventProcessing(event);
816 }
817
818 void OmniboxViewViews::GetAccessibleState(ui::AXViewState* state) {
819   location_bar_view_->GetAccessibleState(state);
820   state->role = ui::AX_ROLE_TEXT_FIELD;
821 }
822
823 void OmniboxViewViews::OnFocus() {
824   views::Textfield::OnFocus();
825   // TODO(oshima): Get control key state.
826   model()->OnSetFocus(false);
827   // Don't call controller()->OnSetFocus, this view has already acquired focus.
828
829   // Restore the selection we saved in OnBlur() if it's still valid.
830   if (saved_selection_for_focus_change_.IsValid()) {
831     SelectRange(saved_selection_for_focus_change_);
832     saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
833   }
834 }
835
836 void OmniboxViewViews::OnBlur() {
837   // Save the user's existing selection to restore it later.
838   saved_selection_for_focus_change_ = GetSelectedRange();
839
840   views::Textfield::OnBlur();
841   gfx::NativeView native_view = NULL;
842   views::Widget* widget = GetWidget();
843   if (widget) {
844     aura::client::FocusClient* client =
845         aura::client::GetFocusClient(widget->GetNativeView());
846     if (client)
847       native_view = client->GetFocusedWindow();
848   }
849   model()->OnWillKillFocus(native_view);
850   // Close the popup.
851   CloseOmniboxPopup();
852
853   // Tell the model to reset itself.
854   model()->OnKillFocus();
855
856   // Ignore loss of focus if we lost focus because the website settings popup
857   // is open. When the popup is destroyed, focus will return to the Omnibox.
858   if (!WebsiteSettingsPopupView::IsPopupShowing())
859     OnDidKillFocus();
860
861   // Make sure the beginning of the text is visible.
862   SelectRange(gfx::Range(0));
863 }
864
865 base::string16 OmniboxViewViews::GetSelectionClipboardText() const {
866   return SanitizeTextForPaste(Textfield::GetSelectionClipboardText());
867 }
868
869 ////////////////////////////////////////////////////////////////////////////////
870 // OmniboxViewViews, private gfx::AnimationDelegate implementation:
871
872 void OmniboxViewViews::AnimationProgressed(const gfx::Animation* animation) {
873   SchedulePaint();
874 }
875
876 void OmniboxViewViews::AnimationEnded(const gfx::Animation* animation) {
877   fade_in_animation_->Reset();
878 }
879
880 ////////////////////////////////////////////////////////////////////////////////
881 // OmniboxViewViews,
882 // chromeos::input_method::InputMethodManager::CandidateWindowObserver
883 // private implementation:
884
885 #if defined(OS_CHROMEOS)
886 void OmniboxViewViews::CandidateWindowOpened(
887       chromeos::input_method::InputMethodManager* manager) {
888   ime_candidate_window_open_ = true;
889 }
890
891 void OmniboxViewViews::CandidateWindowClosed(
892       chromeos::input_method::InputMethodManager* manager) {
893   ime_candidate_window_open_ = false;
894 }
895 #endif
896
897 ////////////////////////////////////////////////////////////////////////////////
898 // OmniboxViewViews, private views::TextfieldController implementation:
899
900 void OmniboxViewViews::ContentsChanged(views::Textfield* sender,
901                                        const base::string16& new_contents) {
902 }
903
904 bool OmniboxViewViews::HandleKeyEvent(views::Textfield* textfield,
905                                       const ui::KeyEvent& event) {
906   delete_at_end_pressed_ = false;
907
908   if (event.key_code() == ui::VKEY_BACK) {
909     // No extra handling is needed in keyword search mode, if there is a
910     // non-empty selection, or if the cursor is not leading the text.
911     if (model()->is_keyword_hint() || model()->keyword().empty() ||
912         HasSelection() || GetCursorPosition() != 0)
913       return false;
914     model()->ClearKeyword(text());
915     return true;
916   }
917
918   if (event.key_code() == ui::VKEY_DELETE && !event.IsAltDown()) {
919     delete_at_end_pressed_ =
920         (!HasSelection() && GetCursorPosition() == text().length());
921   }
922
923   // Handle the right-arrow key for LTR text and the left-arrow key for RTL text
924   // if there is gray text that needs to be committed.
925   if (GetCursorPosition() == text().length()) {
926     base::i18n::TextDirection direction = GetTextDirection();
927     if ((direction == base::i18n::LEFT_TO_RIGHT &&
928          event.key_code() == ui::VKEY_RIGHT) ||
929         (direction == base::i18n::RIGHT_TO_LEFT &&
930          event.key_code() == ui::VKEY_LEFT)) {
931       return model()->CommitSuggestedText();
932     }
933   }
934
935   return false;
936 }
937
938 void OmniboxViewViews::OnBeforeUserAction(views::Textfield* sender) {
939   OnBeforePossibleChange();
940 }
941
942 void OmniboxViewViews::OnAfterUserAction(views::Textfield* sender) {
943   OnAfterPossibleChange();
944 }
945
946 void OmniboxViewViews::OnAfterCutOrCopy(ui::ClipboardType clipboard_type) {
947   ui::Clipboard* cb = ui::Clipboard::GetForCurrentThread();
948   base::string16 selected_text;
949   cb->ReadText(clipboard_type, &selected_text);
950   GURL url;
951   bool write_url;
952   model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
953                              &selected_text, &url, &write_url);
954   if (IsSelectAll())
955     UMA_HISTOGRAM_COUNTS(OmniboxEditModel::kCutOrCopyAllTextHistogram, 1);
956
957   if (write_url) {
958     BookmarkNodeData data;
959     data.ReadFromTuple(url, selected_text);
960     data.WriteToClipboard(clipboard_type);
961   } else {
962     ui::ScopedClipboardWriter scoped_clipboard_writer(
963         ui::Clipboard::GetForCurrentThread(), clipboard_type);
964     scoped_clipboard_writer.WriteText(selected_text);
965   }
966 }
967
968 void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData* data) {
969   GURL url;
970   bool write_url;
971   bool is_all_selected = IsSelectAll();
972   base::string16 selected_text = GetSelectedText();
973   model()->AdjustTextForCopy(GetSelectedRange().GetMin(), is_all_selected,
974                              &selected_text, &url, &write_url);
975   data->SetString(selected_text);
976   if (write_url) {
977     gfx::Image favicon;
978     base::string16 title = selected_text;
979     if (is_all_selected)
980       model()->GetDataForURLExport(&url, &title, &favicon);
981     button_drag_utils::SetURLAndDragImage(url, title, favicon.AsImageSkia(),
982                                           data, GetWidget());
983     data->SetURL(url, title);
984   }
985 }
986
987 void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations) {
988   base::string16 selected_text = GetSelectedText();
989   GURL url;
990   bool write_url;
991   model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
992                              &selected_text, &url, &write_url);
993   if (write_url)
994     *drag_operations |= ui::DragDropTypes::DRAG_LINK;
995 }
996
997 void OmniboxViewViews::AppendDropFormats(
998     int* formats,
999     std::set<ui::OSExchangeData::CustomFormat>* custom_formats) {
1000   *formats = *formats | ui::OSExchangeData::URL;
1001 }
1002
1003 int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) {
1004   if (HasTextBeingDragged())
1005     return ui::DragDropTypes::DRAG_NONE;
1006
1007   if (data.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)) {
1008     GURL url;
1009     base::string16 title;
1010     if (data.GetURLAndTitle(
1011             ui::OSExchangeData::CONVERT_FILENAMES, &url, &title)) {
1012       base::string16 text(
1013           StripJavascriptSchemas(base::UTF8ToUTF16(url.spec())));
1014       if (model()->CanPasteAndGo(text)) {
1015         model()->PasteAndGo(text);
1016         return ui::DragDropTypes::DRAG_COPY;
1017       }
1018     }
1019   } else if (data.HasString()) {
1020     base::string16 text;
1021     if (data.GetString(&text)) {
1022       base::string16 collapsed_text(base::CollapseWhitespace(text, true));
1023       if (model()->CanPasteAndGo(collapsed_text))
1024         model()->PasteAndGo(collapsed_text);
1025       return ui::DragDropTypes::DRAG_COPY;
1026     }
1027   }
1028
1029   return ui::DragDropTypes::DRAG_NONE;
1030 }
1031
1032 void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel* menu_contents) {
1033   int paste_position = menu_contents->GetIndexOfCommandId(IDS_APP_PASTE);
1034   DCHECK_GE(paste_position, 0);
1035   menu_contents->InsertItemWithStringIdAt(
1036       paste_position + 1, IDS_PASTE_AND_GO, IDS_PASTE_AND_GO);
1037
1038   menu_contents->AddSeparator(ui::NORMAL_SEPARATOR);
1039
1040   if (chrome::IsQueryExtractionEnabled() || chrome::ShouldDisplayOriginChip() ||
1041       chrome::ShouldDisplayOriginChipV2()) {
1042     int select_all_position = menu_contents->GetIndexOfCommandId(
1043         IDS_APP_SELECT_ALL);
1044     DCHECK_GE(select_all_position, 0);
1045     menu_contents->InsertItemWithStringIdAt(
1046         select_all_position + 1, IDS_SHOW_URL, IDS_SHOW_URL);
1047   }
1048
1049   // Minor note: We use IDC_ for command id here while the underlying textfield
1050   // is using IDS_ for all its command ids. This is because views cannot depend
1051   // on IDC_ for now.
1052   menu_contents->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES,
1053       IDS_EDIT_SEARCH_ENGINES);
1054 }