• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_H_
6 #define UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_H_
7 
8 #include <string>
9 
10 #include "base/basictypes.h"
11 #include "base/compiler_specific.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/strings/string16.h"
15 #include "base/timer/timer.h"
16 #include "third_party/skia/include/core/SkColor.h"
17 #include "ui/base/ime/text_input_client.h"
18 #include "ui/base/ime/text_input_type.h"
19 #include "ui/base/models/simple_menu_model.h"
20 #include "ui/base/touch/touch_editing_controller.h"
21 #include "ui/events/keycodes/keyboard_codes.h"
22 #include "ui/gfx/font_list.h"
23 #include "ui/gfx/range/range.h"
24 #include "ui/gfx/selection_model.h"
25 #include "ui/gfx/text_constants.h"
26 #include "ui/views/context_menu_controller.h"
27 #include "ui/views/controls/textfield/textfield_model.h"
28 #include "ui/views/drag_controller.h"
29 #include "ui/views/view.h"
30 
31 namespace views {
32 
33 class MenuRunner;
34 class Painter;
35 class TextfieldController;
36 
37 // A views/skia textfield implementation. No platform-specific code is used.
38 class VIEWS_EXPORT Textfield : public View,
39                                public TextfieldModel::Delegate,
40                                public ContextMenuController,
41                                public DragController,
42                                public ui::TouchEditable,
43                                public ui::TextInputClient {
44  public:
45   // The textfield's class name.
46   static const char kViewClassName[];
47 
48   // Returns the text cursor blink time in milliseconds, or 0 for no blinking.
49   static size_t GetCaretBlinkMs();
50 
51   Textfield();
52   virtual ~Textfield();
53 
54   // Set the controller for this textfield.
set_controller(TextfieldController * controller)55   void set_controller(TextfieldController* controller) {
56     controller_ = controller;
57   }
58 
59   // Gets/Sets whether or not the Textfield is read-only.
read_only()60   bool read_only() const { return read_only_; }
61   void SetReadOnly(bool read_only);
62 
63   // Sets the input type; displays only asterisks for TEXT_INPUT_TYPE_PASSWORD.
64   void SetTextInputType(ui::TextInputType type);
65 
66   // Gets the text currently displayed in the Textfield.
text()67   const base::string16& text() const { return model_->text(); }
68 
69   // Sets the text currently displayed in the Textfield.  This doesn't
70   // change the cursor position if the current cursor is within the
71   // new text's range, or moves the cursor to the end if the cursor is
72   // out of the new text's range.
73   void SetText(const base::string16& new_text);
74 
75   // Appends the given string to the previously-existing text in the field.
76   void AppendText(const base::string16& new_text);
77 
78   // Inserts |new_text| at the cursor position, replacing any selected text.
79   void InsertOrReplaceText(const base::string16& new_text);
80 
81   // Returns the text direction.
82   base::i18n::TextDirection GetTextDirection() const;
83 
84   // Returns the text that is currently selected.
85   base::string16 GetSelectedText() const;
86 
87   // Select the entire text range. If |reversed| is true, the range will end at
88   // the logical beginning of the text; this generally shows the leading portion
89   // of text that overflows its display area.
90   void SelectAll(bool reversed);
91 
92   // Clears the selection within the edit field and sets the caret to the end.
93   void ClearSelection();
94 
95   // Checks if there is any selected text.
96   bool HasSelection() const;
97 
98   // Gets/sets the text color to be used when painting the Textfield.
99   // Call UseDefaultTextColor() to restore the default system color.
100   SkColor GetTextColor() const;
101   void SetTextColor(SkColor color);
102   void UseDefaultTextColor();
103 
104   // Gets/sets the background color to be used when painting the Textfield.
105   // Call UseDefaultBackgroundColor() to restore the default system color.
106   SkColor GetBackgroundColor() const;
107   void SetBackgroundColor(SkColor color);
108   void UseDefaultBackgroundColor();
109 
110   // Gets/sets the selection text color to be used when painting the Textfield.
111   // Call UseDefaultSelectionTextColor() to restore the default system color.
112   SkColor GetSelectionTextColor() const;
113   void SetSelectionTextColor(SkColor color);
114   void UseDefaultSelectionTextColor();
115 
116   // Gets/sets the selection background color to be used when painting the
117   // Textfield. Call UseDefaultSelectionBackgroundColor() to restore the default
118   // system color.
119   SkColor GetSelectionBackgroundColor() const;
120   void SetSelectionBackgroundColor(SkColor color);
121   void UseDefaultSelectionBackgroundColor();
122 
123   // Gets/Sets whether or not the cursor is enabled.
124   bool GetCursorEnabled() const;
125   void SetCursorEnabled(bool enabled);
126 
127   // Gets/Sets the fonts used when rendering the text within the Textfield.
128   const gfx::FontList& GetFontList() const;
129   void SetFontList(const gfx::FontList& font_list);
130 
131   // Sets the default width of the text control. See default_width_in_chars_.
set_default_width_in_chars(int default_width)132   void set_default_width_in_chars(int default_width) {
133     default_width_in_chars_ = default_width;
134   }
135 
136   // Sets the text to display when empty.
set_placeholder_text(const base::string16 & text)137   void set_placeholder_text(const base::string16& text) {
138     placeholder_text_ = text;
139   }
140   virtual base::string16 GetPlaceholderText() const;
141 
placeholder_text_color()142   SkColor placeholder_text_color() const { return placeholder_text_color_; }
set_placeholder_text_color(SkColor color)143   void set_placeholder_text_color(SkColor color) {
144     placeholder_text_color_ = color;
145   }
146 
147   // Get or set the horizontal alignment used for the button from the underlying
148   // RenderText object.
149   gfx::HorizontalAlignment GetHorizontalAlignment() const;
150   void SetHorizontalAlignment(gfx::HorizontalAlignment alignment);
151 
152   // Displays a virtual keyboard or alternate input view if enabled.
153   void ShowImeIfNeeded();
154 
155   // Returns whether or not an IME is composing text.
156   bool IsIMEComposing() const;
157 
158   // Gets the selected logical text range.
159   const gfx::Range& GetSelectedRange() const;
160 
161   // Selects the specified logical text range.
162   void SelectRange(const gfx::Range& range);
163 
164   // Gets the text selection model.
165   const gfx::SelectionModel& GetSelectionModel() const;
166 
167   // Sets the specified text selection model.
168   void SelectSelectionModel(const gfx::SelectionModel& sel);
169 
170   // Returns the current cursor position.
171   size_t GetCursorPosition() const;
172 
173   // Set the text color over the entire text or a logical character range.
174   // Empty and invalid ranges are ignored.
175   void SetColor(SkColor value);
176   void ApplyColor(SkColor value, const gfx::Range& range);
177 
178   // Set various text styles over the entire text or a logical character range.
179   // The respective |style| is applied if |value| is true, or removed if false.
180   // Empty and invalid ranges are ignored.
181   void SetStyle(gfx::TextStyle style, bool value);
182   void ApplyStyle(gfx::TextStyle style, bool value, const gfx::Range& range);
183 
184   // Clears Edit history.
185   void ClearEditHistory();
186 
187   // Set the accessible name of the text field.
188   void SetAccessibleName(const base::string16& name);
189 
190   // Performs the action associated with the specified command id.
191   void ExecuteCommand(int command_id);
192 
193   void SetFocusPainter(scoped_ptr<Painter> focus_painter);
194 
195   // Returns whether there is a drag operation originating from the textfield.
196   bool HasTextBeingDragged();
197 
198   // View overrides:
199   virtual int GetBaseline() const OVERRIDE;
200   virtual gfx::Size GetPreferredSize() const OVERRIDE;
201   virtual const char* GetClassName() const OVERRIDE;
202   virtual gfx::NativeCursor GetCursor(const ui::MouseEvent& event) OVERRIDE;
203   virtual bool OnMousePressed(const ui::MouseEvent& event) OVERRIDE;
204   virtual bool OnMouseDragged(const ui::MouseEvent& event) OVERRIDE;
205   virtual void OnMouseReleased(const ui::MouseEvent& event) OVERRIDE;
206   virtual bool OnKeyPressed(const ui::KeyEvent& event) OVERRIDE;
207   virtual ui::TextInputClient* GetTextInputClient() OVERRIDE;
208   virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE;
209   virtual void AboutToRequestFocusFromTabTraversal(bool reverse) OVERRIDE;
210   virtual bool SkipDefaultKeyEventProcessing(
211       const ui::KeyEvent& event) OVERRIDE;
212   virtual bool GetDropFormats(
213       int* formats,
214       std::set<ui::OSExchangeData::CustomFormat>* custom_formats) OVERRIDE;
215   virtual bool CanDrop(const ui::OSExchangeData& data) OVERRIDE;
216   virtual int OnDragUpdated(const ui::DropTargetEvent& event) OVERRIDE;
217   virtual void OnDragExited() OVERRIDE;
218   virtual int OnPerformDrop(const ui::DropTargetEvent& event) OVERRIDE;
219   virtual void OnDragDone() OVERRIDE;
220   virtual void GetAccessibleState(ui::AXViewState* state) OVERRIDE;
221   virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) OVERRIDE;
222   virtual void OnEnabledChanged() OVERRIDE;
223   virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE;
224   virtual void OnFocus() OVERRIDE;
225   virtual void OnBlur() OVERRIDE;
226   virtual gfx::Point GetKeyboardContextMenuLocation() OVERRIDE;
227   virtual void OnNativeThemeChanged(const ui::NativeTheme* theme) OVERRIDE;
228 
229   // TextfieldModel::Delegate overrides:
230   virtual void OnCompositionTextConfirmedOrCleared() OVERRIDE;
231 
232   // ContextMenuController overrides:
233   virtual void ShowContextMenuForView(View* source,
234                                       const gfx::Point& point,
235                                       ui::MenuSourceType source_type) OVERRIDE;
236 
237   // DragController overrides:
238   virtual void WriteDragDataForView(View* sender,
239                                     const gfx::Point& press_pt,
240                                     ui::OSExchangeData* data) OVERRIDE;
241   virtual int GetDragOperationsForView(View* sender,
242                                        const gfx::Point& p) OVERRIDE;
243   virtual bool CanStartDragForView(View* sender,
244                                    const gfx::Point& press_pt,
245                                    const gfx::Point& p) OVERRIDE;
246 
247   // ui::TouchEditable overrides:
248   virtual void SelectRect(const gfx::Point& start,
249                           const gfx::Point& end) OVERRIDE;
250   virtual void MoveCaretTo(const gfx::Point& point) OVERRIDE;
251   virtual void GetSelectionEndPoints(gfx::Rect* p1, gfx::Rect* p2) OVERRIDE;
252   virtual gfx::Rect GetBounds() OVERRIDE;
253   virtual gfx::NativeView GetNativeView() const OVERRIDE;
254   virtual void ConvertPointToScreen(gfx::Point* point) OVERRIDE;
255   virtual void ConvertPointFromScreen(gfx::Point* point) OVERRIDE;
256   virtual bool DrawsHandles() OVERRIDE;
257   virtual void OpenContextMenu(const gfx::Point& anchor) OVERRIDE;
258   virtual void DestroyTouchSelection() OVERRIDE;
259 
260   // ui::SimpleMenuModel::Delegate overrides:
261   virtual bool IsCommandIdChecked(int command_id) const OVERRIDE;
262   virtual bool IsCommandIdEnabled(int command_id) const OVERRIDE;
263   virtual bool GetAcceleratorForCommandId(
264       int command_id,
265       ui::Accelerator* accelerator) OVERRIDE;
266   virtual void ExecuteCommand(int command_id, int event_flags) OVERRIDE;
267 
268   // ui::TextInputClient overrides:
269   virtual void SetCompositionText(
270       const ui::CompositionText& composition) OVERRIDE;
271   virtual void ConfirmCompositionText() OVERRIDE;
272   virtual void ClearCompositionText() OVERRIDE;
273   virtual void InsertText(const base::string16& text) OVERRIDE;
274   virtual void InsertChar(base::char16 ch, int flags) OVERRIDE;
275   virtual gfx::NativeWindow GetAttachedWindow() const OVERRIDE;
276   virtual ui::TextInputType GetTextInputType() const OVERRIDE;
277   virtual ui::TextInputMode GetTextInputMode() const OVERRIDE;
278   virtual bool CanComposeInline() const OVERRIDE;
279   virtual gfx::Rect GetCaretBounds() const OVERRIDE;
280   virtual bool GetCompositionCharacterBounds(uint32 index,
281                                              gfx::Rect* rect) const OVERRIDE;
282   virtual bool HasCompositionText() const OVERRIDE;
283   virtual bool GetTextRange(gfx::Range* range) const OVERRIDE;
284   virtual bool GetCompositionTextRange(gfx::Range* range) const OVERRIDE;
285   virtual bool GetSelectionRange(gfx::Range* range) const OVERRIDE;
286   virtual bool SetSelectionRange(const gfx::Range& range) OVERRIDE;
287   virtual bool DeleteRange(const gfx::Range& range) OVERRIDE;
288   virtual bool GetTextFromRange(const gfx::Range& range,
289                                 base::string16* text) const OVERRIDE;
290   virtual void OnInputMethodChanged() OVERRIDE;
291   virtual bool ChangeTextDirectionAndLayoutAlignment(
292       base::i18n::TextDirection direction) OVERRIDE;
293   virtual void ExtendSelectionAndDelete(size_t before, size_t after) OVERRIDE;
294   virtual void EnsureCaretInRect(const gfx::Rect& rect) OVERRIDE;
295   virtual void OnCandidateWindowShown() OVERRIDE;
296   virtual void OnCandidateWindowUpdated() OVERRIDE;
297   virtual void OnCandidateWindowHidden() OVERRIDE;
298   virtual bool IsEditingCommandEnabled(int command_id) OVERRIDE;
299   virtual void ExecuteEditingCommand(int command_id) OVERRIDE;
300 
301  protected:
302   // Returns the TextfieldModel's text/cursor/selection rendering model.
303   gfx::RenderText* GetRenderText() const;
304 
last_click_location()305   gfx::Point last_click_location() const { return last_click_location_; }
306 
307   // Get the text from the selection clipboard.
308   virtual base::string16 GetSelectionClipboardText() const;
309 
310  private:
311   friend class TextfieldTestApi;
312 
313   // Handles a request to change the value of this text field from software
314   // using an accessibility API (typically automation software, screen readers
315   // don't normally use this). Sets the value and clears the selection.
316   void AccessibilitySetValue(const base::string16& new_value);
317 
318   // Updates the painted background color.
319   void UpdateBackgroundColor();
320 
321   // Does necessary updates when the text and/or cursor position changes.
322   void UpdateAfterChange(bool text_changed, bool cursor_changed);
323 
324   // A callback function to periodically update the cursor state.
325   void UpdateCursor();
326 
327   // Repaint the cursor.
328   void RepaintCursor();
329 
330   void PaintTextAndCursor(gfx::Canvas* canvas);
331 
332   // Helper function to call MoveCursorTo on the TextfieldModel.
333   void MoveCursorTo(const gfx::Point& point, bool select);
334 
335   // Helper function to update the selection on a mouse drag.
336   void SelectThroughLastDragLocation();
337 
338   // Convenience method to notify the InputMethod and TouchSelectionController.
339   void OnCaretBoundsChanged();
340 
341   // Convenience method to call TextfieldController::OnBeforeUserAction();
342   void OnBeforeUserAction();
343 
344   // Convenience method to call TextfieldController::OnAfterUserAction();
345   void OnAfterUserAction();
346 
347   // Calls |model_->Cut()| and notifies TextfieldController on success.
348   bool Cut();
349 
350   // Calls |model_->Copy()| and notifies TextfieldController on success.
351   bool Copy();
352 
353   // Calls |model_->Paste()| and calls TextfieldController::ContentsChanged()
354   // explicitly if paste succeeded.
355   bool Paste();
356 
357   // Utility function to prepare the context menu.
358   void UpdateContextMenu();
359 
360   // Tracks the mouse clicks for single/double/triple clicks.
361   void TrackMouseClicks(const ui::MouseEvent& event);
362 
363   // Returns true if the current text input type allows access by the IME.
364   bool ImeEditingAllowed() const;
365 
366   // Reveals the password character at |index| for a set duration.
367   // If |index| is -1, the existing revealed character will be reset.
368   void RevealPasswordChar(int index);
369 
370   void CreateTouchSelectionControllerAndNotifyIt();
371 
372   // Updates the selection clipboard to any non-empty text selection.
373   void UpdateSelectionClipboard() const;
374 
375   // Pastes the selection clipboard for the specified mouse event.
376   void PasteSelectionClipboard(const ui::MouseEvent& event);
377 
378   // The text model.
379   scoped_ptr<TextfieldModel> model_;
380 
381   // This is the current listener for events from this Textfield.
382   TextfieldController* controller_;
383 
384   // True if this Textfield cannot accept input and is read-only.
385   bool read_only_;
386 
387   // The default number of average characters for the width of this text field.
388   // This will be reported as the "desired size". Defaults to 0.
389   int default_width_in_chars_;
390 
391   scoped_ptr<Painter> focus_painter_;
392 
393   // Flags indicating whether various system colors should be used, and if not,
394   // what overriding color values should be used instead.
395   bool use_default_text_color_;
396   bool use_default_background_color_;
397   bool use_default_selection_text_color_;
398   bool use_default_selection_background_color_;
399   SkColor text_color_;
400   SkColor background_color_;
401   SkColor selection_text_color_;
402   SkColor selection_background_color_;
403 
404   // Text to display when empty.
405   base::string16 placeholder_text_;
406 
407   // Placeholder text color.
408   SkColor placeholder_text_color_;
409 
410   // The accessible name of the text field.
411   base::string16 accessible_name_;
412 
413   // The input type of this text field.
414   ui::TextInputType text_input_type_;
415 
416   // The duration and timer to reveal the last typed password character.
417   base::TimeDelta password_reveal_duration_;
418   base::OneShotTimer<Textfield> password_reveal_timer_;
419 
420   // Tracks whether a user action is being performed; i.e. OnBeforeUserAction()
421   // has been called, but OnAfterUserAction() has not yet been called.
422   bool performing_user_action_;
423 
424   // True if InputMethod::CancelComposition() should not be called.
425   bool skip_input_method_cancel_composition_;
426 
427   // The text editing cursor repaint timer and visibility.
428   base::RepeatingTimer<Textfield> cursor_repaint_timer_;
429   bool cursor_visible_;
430 
431   // The drop cursor is a visual cue for where dragged text will be dropped.
432   bool drop_cursor_visible_;
433   gfx::SelectionModel drop_cursor_position_;
434 
435   // Is the user potentially dragging and dropping from this view?
436   bool initiating_drag_;
437 
438   // A timer and point used to modify the selection when dragging.
439   base::RepeatingTimer<Textfield> drag_selection_timer_;
440   gfx::Point last_drag_location_;
441 
442   // State variables used to track double and triple clicks.
443   size_t aggregated_clicks_;
444   base::TimeDelta last_click_time_;
445   gfx::Point last_click_location_;
446   gfx::Range double_click_word_;
447 
448   scoped_ptr<ui::TouchSelectionController> touch_selection_controller_;
449 
450   // Context menu related members.
451   scoped_ptr<ui::SimpleMenuModel> context_menu_contents_;
452   scoped_ptr<views::MenuRunner> context_menu_runner_;
453 
454   // Used to bind callback functions to this object.
455   base::WeakPtrFactory<Textfield> weak_ptr_factory_;
456 
457   DISALLOW_COPY_AND_ASSIGN(Textfield);
458 };
459 
460 }  // namespace views
461 
462 #endif  // UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_H_
463