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.
5 #ifndef UI_GFX_RENDER_TEXT_H_
6 #define UI_GFX_RENDER_TEXT_H_
14 #include "base/gtest_prod_util.h"
15 #include "base/i18n/rtl.h"
16 #include "base/string16.h"
17 #include "third_party/skia/include/core/SkColor.h"
18 #include "third_party/skia/include/core/SkPaint.h"
19 #include "third_party/skia/include/core/SkRect.h"
20 #include "ui/base/range/range.h"
21 #include "ui/gfx/break_list.h"
22 #include "ui/gfx/font_list.h"
23 #include "ui/gfx/point.h"
24 #include "ui/gfx/rect.h"
25 #include "ui/gfx/selection_model.h"
26 #include "ui/gfx/shadow_value.h"
27 #include "ui/gfx/text_constants.h"
28 #include "ui/gfx/vector2d.h"
44 // Internal helper class used by derived classes to draw text through Skia.
45 class SkiaTextRenderer
{
47 explicit SkiaTextRenderer(Canvas
* canvas
);
50 void SetDrawLooper(SkDrawLooper
* draw_looper
);
51 void SetFontSmoothingSettings(bool enable_smoothing
, bool enable_lcd_text
);
52 void SetTypeface(SkTypeface
* typeface
);
53 void SetTextSize(SkScalar size
);
54 void SetFontFamilyWithStyle(const std::string
& family
, int font_style
);
55 void SetForegroundColor(SkColor foreground
);
56 void SetShader(SkShader
* shader
, const Rect
& bounds
);
57 // Sets underline metrics to use if the text will be drawn with an underline.
58 // If not set, default values based on the size of the text will be used. The
59 // two metrics must be set together.
60 void SetUnderlineMetrics(SkScalar thickness
, SkScalar position
);
61 void DrawSelection(const std::vector
<Rect
>& selection
, SkColor color
);
62 void DrawPosText(const SkPoint
* pos
,
65 // Draw underline and strike-through text decorations.
66 // Based on |SkCanvas::DrawTextDecorations()| and constants from:
67 // third_party/skia/src/core/SkTextFormatParams.h
68 void DrawDecorations(int x
, int y
, int width
, bool underline
, bool strike
,
69 bool diagonal_strike
);
70 void DrawUnderline(int x
, int y
, int width
);
71 void DrawStrike(int x
, int y
, int width
) const;
72 void DrawDiagonalStrike(int x
, int y
, int width
) const;
75 SkCanvas
* canvas_skia_
;
76 bool started_drawing_
;
79 SkRefPtr
<SkShader
> deferred_fade_shader_
;
80 SkScalar underline_thickness_
;
81 SkScalar underline_position_
;
83 DISALLOW_COPY_AND_ASSIGN(SkiaTextRenderer
);
86 // Internal helper class used by derived classes to iterate colors and styles.
89 StyleIterator(const BreakList
<SkColor
>& colors
,
90 const std::vector
<BreakList
<bool> >& styles
);
93 // Get the colors and styles at the current iterator position.
94 SkColor
color() const { return color_
->second
; }
95 bool style(TextStyle s
) const { return style_
[s
]->second
; }
97 // Get the intersecting range of the current iterator set.
98 ui::Range
GetRange() const;
100 // Update the iterator to point to colors and styles applicable at |position|.
101 void UpdatePosition(size_t position
);
104 BreakList
<SkColor
> colors_
;
105 std::vector
<BreakList
<bool> > styles_
;
107 BreakList
<SkColor
>::const_iterator color_
;
108 std::vector
<BreakList
<bool>::const_iterator
> style_
;
110 DISALLOW_COPY_AND_ASSIGN(StyleIterator
);
113 } // namespace internal
115 // RenderText represents an abstract model of styled text and its corresponding
116 // visual layout. Support is built in for a cursor, a selection, simple styling,
117 // complex scripts, and bi-directional text. Implementations provide mechanisms
118 // for rendering and translation between logical and visual data.
119 class UI_EXPORT RenderText
{
121 virtual ~RenderText();
123 // Creates a platform-specific RenderText instance.
124 static RenderText
* CreateInstance();
126 const string16
& text() const { return text_
; }
127 void SetText(const string16
& text
);
129 HorizontalAlignment
horizontal_alignment() const {
130 return horizontal_alignment_
;
132 void SetHorizontalAlignment(HorizontalAlignment alignment
);
134 const FontList
& font_list() const { return font_list_
; }
135 void SetFontList(const FontList
& font_list
);
136 void SetFont(const Font
& font
);
138 // Set the font size to |size| in pixels.
139 void SetFontSize(int size
);
141 // Get the first font in |font_list_|.
142 const Font
& GetFont() const;
144 bool cursor_enabled() const { return cursor_enabled_
; }
145 void SetCursorEnabled(bool cursor_enabled
);
147 bool cursor_visible() const { return cursor_visible_
; }
148 void set_cursor_visible(bool visible
) { cursor_visible_
= visible
; }
150 bool insert_mode() const { return insert_mode_
; }
151 void ToggleInsertMode();
153 SkColor
cursor_color() const { return cursor_color_
; }
154 void set_cursor_color(SkColor color
) { cursor_color_
= color
; }
156 SkColor
selection_color() const { return selection_color_
; }
157 void set_selection_color(SkColor color
) { selection_color_
= color
; }
159 SkColor
selection_background_focused_color() const {
160 return selection_background_focused_color_
;
162 void set_selection_background_focused_color(SkColor color
) {
163 selection_background_focused_color_
= color
;
166 SkColor
selection_background_unfocused_color() const {
167 return selection_background_unfocused_color_
;
169 void set_selection_background_unfocused_color(SkColor color
) {
170 selection_background_unfocused_color_
= color
;
173 bool focused() const { return focused_
; }
174 void set_focused(bool focused
) { focused_
= focused
; }
176 bool clip_to_display_rect() const { return clip_to_display_rect_
; }
177 void set_clip_to_display_rect(bool clip
) { clip_to_display_rect_
= clip
; }
179 // In an obscured (password) field, all text is drawn as asterisks or bullets.
180 bool obscured() const { return obscured_
; }
181 void SetObscured(bool obscured
);
183 const Rect
& display_rect() const { return display_rect_
; }
184 void SetDisplayRect(const Rect
& r
);
186 void set_fade_head(bool fade_head
) { fade_head_
= fade_head
; }
187 bool fade_head() const { return fade_head_
; }
188 void set_fade_tail(bool fade_tail
) { fade_tail_
= fade_tail
; }
189 bool fade_tail() const { return fade_tail_
; }
191 bool background_is_transparent() const { return background_is_transparent_
; }
192 void set_background_is_transparent(bool transparent
) {
193 background_is_transparent_
= transparent
;
196 const SelectionModel
& selection_model() const { return selection_model_
; }
198 const ui::Range
& selection() const { return selection_model_
.selection(); }
200 size_t cursor_position() const { return selection_model_
.caret_pos(); }
201 void SetCursorPosition(size_t position
);
203 // Moves the cursor left or right. Cursor movement is visual, meaning that
204 // left and right are relative to screen, not the directionality of the text.
205 // If |select| is false, the selection start is moved to the same position.
206 void MoveCursor(BreakType break_type
,
207 VisualCursorDirection direction
,
210 // Set the selection_model_ to the value of |selection|.
211 // The selection range is clamped to text().length() if out of range.
212 // Returns true if the cursor position or selection range changed.
213 // If any index in |selection_model| is not a cursorable position (not on a
214 // grapheme boundary), it is a no-op and returns false.
215 bool MoveCursorTo(const SelectionModel
& selection_model
);
217 // Move the cursor to the position associated with the clicked point.
218 // If |select| is false, the selection start is moved to the same position.
219 // Returns true if the cursor position or selection range changed.
220 bool MoveCursorTo(const Point
& point
, bool select
);
222 // Set the selection_model_ based on |range|.
223 // If the |range| start or end is greater than text length, it is modified
224 // to be the text length.
225 // If the |range| start or end is not a cursorable position (not on grapheme
226 // boundary), it is a NO-OP and returns false. Otherwise, returns true.
227 bool SelectRange(const ui::Range
& range
);
229 // Returns true if the local point is over selected text.
230 bool IsPointInSelection(const Point
& point
);
232 // Selects no text, keeping the current cursor position and caret affinity.
233 void ClearSelection();
235 // Select the entire text range. If |reversed| is true, the range will end at
236 // the logical beginning of the text; this generally shows the leading portion
237 // of text that overflows its display area.
238 void SelectAll(bool reversed
);
240 // Selects the word at the current cursor position.
243 const ui::Range
& GetCompositionRange() const;
244 void SetCompositionRange(const ui::Range
& composition_range
);
246 // Set the text color over the entire text or a logical character range.
247 // The |range| should be valid, non-reversed, and within [0, text().length()].
248 void SetColor(SkColor value
);
249 void ApplyColor(SkColor value
, const ui::Range
& range
);
251 // Set various text styles over the entire text or a logical character range.
252 // The respective |style| is applied if |value| is true, or removed if false.
253 // The |range| should be valid, non-reversed, and within [0, text().length()].
254 void SetStyle(TextStyle style
, bool value
);
255 void ApplyStyle(TextStyle style
, bool value
, const ui::Range
& range
);
257 // Set the text directionality mode and get the text direction yielded.
258 void SetDirectionalityMode(DirectionalityMode mode
);
259 base::i18n::TextDirection
GetTextDirection();
261 // Returns the visual movement direction corresponding to the logical end
262 // of the text, considering only the dominant direction returned by
263 // |GetTextDirection()|, not the direction of a particular run.
264 VisualCursorDirection
GetVisualDirectionOfLogicalEnd();
266 // Returns the size in pixels of the entire string. For the height, this will
267 // return the maximum height among the different fonts in the text runs.
268 // Note that this returns the raw size of the string, which does not include
269 // the margin area of text shadows.
270 virtual Size
GetStringSize() = 0;
272 // Returns the common baseline of the text. The returned value is the vertical
273 // offset from the top of |display_rect| to the text baseline, in pixels.
274 virtual int GetBaseline() = 0;
276 void Draw(Canvas
* canvas
);
278 // Draw the selected text without a cursor or selection highlight.
279 void DrawSelectedText(Canvas
* canvas
);
281 // Gets the SelectionModel from a visual point in local coordinates.
282 virtual SelectionModel
FindCursorPosition(const Point
& point
) = 0;
284 // Get the visual bounds of a cursor at |selection|. These bounds typically
285 // represent a vertical line, but if |insert_mode| is true they contain the
286 // bounds of the associated glyph. These bounds are in local coordinates, but
287 // may be outside the visible region if the text is longer than the textfield.
288 // Subsequent text, cursor, or bounds changes may invalidate returned values.
289 Rect
GetCursorBounds(const SelectionModel
& selection
, bool insert_mode
);
291 // Compute the current cursor bounds, panning the text to show the cursor in
292 // the display rect if necessary. These bounds are in local coordinates.
293 // Subsequent text, cursor, or bounds changes may invalidate returned values.
294 const Rect
& GetUpdatedCursorBounds();
296 // Given an |index| in text(), return the next or previous grapheme boundary
297 // in logical order (that is, the nearest index for which
298 // |IsCursorablePosition(index)| returns true). The return value is in the
299 // range 0 to text().length() inclusive (the input is clamped if it is out of
300 // that range). Always moves by at least one character index unless the
301 // supplied index is already at the boundary of the string.
302 size_t IndexOfAdjacentGrapheme(size_t index
,
303 LogicalCursorDirection direction
);
305 // Return a SelectionModel with the cursor at the current selection's start.
306 // The returned value represents a cursor/caret position without a selection.
307 SelectionModel
GetSelectionModelForSelectionStart();
309 // Sets shadows to drawn with text.
310 void SetTextShadows(const ShadowValues
& shadows
);
312 typedef std::pair
<Font
, ui::Range
> FontSpan
;
313 // For testing purposes, returns which fonts were chosen for which parts of
314 // the text by returning a vector of Font and Range pairs, where each range
315 // specifies the character range for which the corresponding font has been
317 virtual std::vector
<FontSpan
> GetFontSpansForTesting() = 0;
322 const BreakList
<SkColor
>& colors() const { return colors_
; }
323 const std::vector
<BreakList
<bool> >& styles() const { return styles_
; }
325 const Vector2d
& GetUpdatedDisplayOffset();
327 void set_cached_bounds_and_offset_valid(bool valid
) {
328 cached_bounds_and_offset_valid_
= valid
;
331 // Get the selection model that visually neighbors |position| by |break_type|.
332 // The returned value represents a cursor/caret position without a selection.
333 SelectionModel
GetAdjacentSelectionModel(const SelectionModel
& current
,
334 BreakType break_type
,
335 VisualCursorDirection direction
);
337 // Get the selection model visually left/right of |selection| by one grapheme.
338 // The returned value represents a cursor/caret position without a selection.
339 virtual SelectionModel
AdjacentCharSelectionModel(
340 const SelectionModel
& selection
,
341 VisualCursorDirection direction
) = 0;
343 // Get the selection model visually left/right of |selection| by one word.
344 // The returned value represents a cursor/caret position without a selection.
345 virtual SelectionModel
AdjacentWordSelectionModel(
346 const SelectionModel
& selection
,
347 VisualCursorDirection direction
) = 0;
349 // Get the SelectionModels corresponding to visual text ends.
350 // The returned value represents a cursor/caret position without a selection.
351 SelectionModel
EdgeSelectionModel(VisualCursorDirection direction
);
353 // Sets the selection model, the argument is assumed to be valid.
354 virtual void SetSelectionModel(const SelectionModel
& model
);
356 // Get the height and horizontal bounds (relative to the left of the text, not
357 // the view) of the glyph starting at |index|. If the glyph is RTL then
358 // xspan->is_reversed(). This does not return a Rect because a Rect can't have
360 virtual void GetGlyphBounds(size_t index
, ui::Range
* xspan
, int* height
) = 0;
362 // Get the visual bounds containing the logical substring within the |range|.
363 // If |range| is empty, the result is empty. These bounds could be visually
364 // discontinuous if the substring is split by a LTR/RTL level change.
365 // These bounds are in local coordinates, but may be outside the visible
366 // region if the text is longer than the textfield. Subsequent text, cursor,
367 // or bounds changes may invalidate returned values.
368 virtual std::vector
<Rect
> GetSubstringBounds(const ui::Range
& range
) = 0;
370 // Convert between indices into |text_| and indices into |obscured_text_|,
371 // which differ when the text is obscured. Regardless of whether or not the
372 // text is obscured, the character (code point) offsets always match.
373 virtual size_t TextIndexToLayoutIndex(size_t index
) const = 0;
374 virtual size_t LayoutIndexToTextIndex(size_t index
) const = 0;
376 // Return true if cursor can appear in front of the character at |position|,
377 // which means it is a grapheme boundary or the first character in the text.
378 virtual bool IsCursorablePosition(size_t position
) = 0;
380 // Reset the layout to be invalid.
381 virtual void ResetLayout() = 0;
383 // Ensure the text is laid out.
384 virtual void EnsureLayout() = 0;
387 virtual void DrawVisualText(Canvas
* canvas
) = 0;
389 // Returns the text used for layout, which may be |obscured_text_|.
390 const string16
& GetLayoutText() const;
392 // Apply (and undo) temporary composition underlines and selection colors.
393 void ApplyCompositionAndSelectionStyles();
394 void UndoCompositionAndSelectionStyles();
396 // Returns the text offset from the origin after applying text alignment and
398 Vector2d
GetTextOffset();
400 // Convert points from the text space to the view space and back.
401 // Handles the display area, display offset, and the application LTR/RTL mode.
402 Point
ToTextPoint(const Point
& point
);
403 Point
ToViewPoint(const Point
& point
);
405 // Returns the width of content, which reserves room for the cursor if
406 // |cursor_enabled_| is true.
407 int GetContentWidth();
409 // Returns display offset based on current text alignment.
410 Vector2d
GetAlignmentOffset();
412 // Returns the offset for drawing text. Does not account for font
413 // baseline, as needed by Skia.
414 Vector2d
GetOffsetForDrawing();
416 // Applies fade effects to |renderer|.
417 void ApplyFadeEffects(internal::SkiaTextRenderer
* renderer
);
419 // Applies text shadows to |renderer|.
420 void ApplyTextShadows(internal::SkiaTextRenderer
* renderer
);
422 // A convenience function to check whether the glyph attached to the caret
423 // is within the given range.
424 static bool RangeContainsCaret(const ui::Range
& range
,
426 LogicalCursorDirection caret_affinity
);
429 friend class RenderTextTest
;
430 FRIEND_TEST_ALL_PREFIXES(RenderTextTest
, DefaultStyle
);
431 FRIEND_TEST_ALL_PREFIXES(RenderTextTest
, SetColorAndStyle
);
432 FRIEND_TEST_ALL_PREFIXES(RenderTextTest
, ApplyColorAndStyle
);
433 FRIEND_TEST_ALL_PREFIXES(RenderTextTest
, ObscuredText
);
434 FRIEND_TEST_ALL_PREFIXES(RenderTextTest
, GraphemePositions
);
435 FRIEND_TEST_ALL_PREFIXES(RenderTextTest
, EdgeSelectionModels
);
436 FRIEND_TEST_ALL_PREFIXES(RenderTextTest
, OriginForDrawing
);
438 // Set the cursor to |position|, with the caret trailing the previous
439 // grapheme, or if there is no previous grapheme, leading the cursor position.
440 // If |select| is false, the selection start is moved to the same position.
441 // If the |position| is not a cursorable position (not on grapheme boundary),
443 void MoveCursorTo(size_t position
, bool select
);
445 // Updates |obscured_text_| if the text is obscured.
446 void UpdateObscuredText();
448 // Update the cached bounds and display offset to ensure that the current
449 // cursor is within the visible display area.
450 void UpdateCachedBoundsAndOffset();
452 // Draw the selection and cursor.
453 void DrawSelection(Canvas
* canvas
);
454 void DrawCursor(Canvas
* canvas
);
456 // Logical UTF-16 string data to be drawn.
459 // Horizontal alignment of the text with respect to |display_rect_|.
460 HorizontalAlignment horizontal_alignment_
;
462 // The text directionality mode, defaults to DIRECTIONALITY_FROM_TEXT.
463 DirectionalityMode directionality_mode_
;
465 // The cached text direction, potentially computed from the text or UI locale.
466 // Use GetTextDirection(), do not use this potentially invalid value directly!
467 base::i18n::TextDirection text_direction_
;
469 // A list of fonts used to render |text_|.
472 // Logical selection range and visual cursor position.
473 SelectionModel selection_model_
;
475 // The cached cursor bounds; get these bounds with GetUpdatedCursorBounds.
478 // Specifies whether the cursor is enabled. If disabled, no space is reserved
479 // for the cursor when positioning text.
480 bool cursor_enabled_
;
482 // The cursor visibility and insert mode.
483 bool cursor_visible_
;
486 // The color used for the cursor.
487 SkColor cursor_color_
;
489 // The color used for drawing selected text.
490 SkColor selection_color_
;
492 // The background color used for drawing the selection when focused.
493 SkColor selection_background_focused_color_
;
495 // The background color used for drawing the selection when not focused.
496 SkColor selection_background_unfocused_color_
;
498 // The focus state of the text.
501 // Composition text range.
502 ui::Range composition_range_
;
504 // Color and style breaks, used to color and stylize ranges of text.
505 // BreakList positions are stored with text indices, not layout indices.
506 // TODO(msw): Expand to support cursor, selection, background, etc. colors.
507 BreakList
<SkColor
> colors_
;
508 std::vector
<BreakList
<bool> > styles_
;
510 // Breaks saved without temporary composition and selection styling.
511 BreakList
<SkColor
> saved_colors_
;
512 BreakList
<bool> saved_underlines_
;
513 bool composition_and_selection_styles_applied_
;
515 // A flag and the text to display for obscured (password) fields.
516 // Asterisks are used instead of the actual text glyphs when true.
518 string16 obscured_text_
;
520 // Fade text head and/or tail, if text doesn't fit into |display_rect_|.
524 // Is the background transparent (either partially or fully)?
525 bool background_is_transparent_
;
527 // The local display area for rendering the text.
530 // Flag to work around a Skia bug with the PDF path (http://crbug.com/133548)
531 // that results in incorrect clipping when drawing to the document margins.
532 // This field allows disabling clipping to work around the issue.
533 // TODO(asvitkine): Remove this when the underlying Skia bug is fixed.
534 bool clip_to_display_rect_
;
536 // The offset for the text to be drawn, relative to the display area.
537 // Get this point with GetUpdatedDisplayOffset (or risk using a stale value).
538 Vector2d display_offset_
;
540 // The cached bounds and offset are invalidated by changes to the cursor,
541 // selection, font, and other operations that adjust the visible text bounds.
542 bool cached_bounds_and_offset_valid_
;
544 // Text shadows to be drawn.
545 ShadowValues text_shadows_
;
547 DISALLOW_COPY_AND_ASSIGN(RenderText
);
552 #endif // UI_GFX_RENDER_TEXT_H_