gpu: Tweak Android WebGL test expectations
[chromium-blink-merge.git] / ui / gfx / render_text.h
blob34277400b7369e28c41e120950e357555c8c9415
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_
8 #include <algorithm>
9 #include <cstring>
10 #include <string>
11 #include <utility>
12 #include <vector>
14 #include "base/gtest_prod_util.h"
15 #include "base/i18n/rtl.h"
16 #include "base/strings/string16.h"
17 #include "skia/ext/refptr.h"
18 #include "third_party/skia/include/core/SkColor.h"
19 #include "third_party/skia/include/core/SkPaint.h"
20 #include "third_party/skia/include/core/SkRect.h"
21 #include "ui/base/range/range.h"
22 #include "ui/gfx/break_list.h"
23 #include "ui/gfx/font_list.h"
24 #include "ui/gfx/point.h"
25 #include "ui/gfx/rect.h"
26 #include "ui/gfx/selection_model.h"
27 #include "ui/gfx/shadow_value.h"
28 #include "ui/gfx/text_constants.h"
29 #include "ui/gfx/vector2d.h"
31 class SkCanvas;
32 class SkDrawLooper;
33 struct SkPoint;
34 class SkShader;
35 class SkTypeface;
37 namespace gfx {
39 class Canvas;
40 class Font;
41 class RenderTextTest;
43 namespace internal {
45 // Internal helper class used by derived classes to draw text through Skia.
46 class SkiaTextRenderer {
47 public:
48 explicit SkiaTextRenderer(Canvas* canvas);
49 ~SkiaTextRenderer();
51 void SetDrawLooper(SkDrawLooper* draw_looper);
52 void SetFontSmoothingSettings(bool enable_smoothing, bool enable_lcd_text);
53 void SetTypeface(SkTypeface* typeface);
54 void SetTextSize(SkScalar size);
55 void SetFontFamilyWithStyle(const std::string& family, int font_style);
56 void SetForegroundColor(SkColor foreground);
57 void SetShader(SkShader* shader, const Rect& bounds);
58 // Sets underline metrics to use if the text will be drawn with an underline.
59 // If not set, default values based on the size of the text will be used. The
60 // two metrics must be set together.
61 void SetUnderlineMetrics(SkScalar thickness, SkScalar position);
62 void DrawSelection(const std::vector<Rect>& selection, SkColor color);
63 void DrawPosText(const SkPoint* pos,
64 const uint16* glyphs,
65 size_t glyph_count);
66 // Draw underline and strike-through text decorations.
67 // Based on |SkCanvas::DrawTextDecorations()| and constants from:
68 // third_party/skia/src/core/SkTextFormatParams.h
69 void DrawDecorations(int x, int y, int width, bool underline, bool strike,
70 bool diagonal_strike);
71 void DrawUnderline(int x, int y, int width);
72 void DrawStrike(int x, int y, int width) const;
73 void DrawDiagonalStrike(int x, int y, int width) const;
75 private:
76 SkCanvas* canvas_skia_;
77 bool started_drawing_;
78 SkPaint paint_;
79 SkRect bounds_;
80 skia::RefPtr<SkShader> deferred_fade_shader_;
81 SkScalar underline_thickness_;
82 SkScalar underline_position_;
84 DISALLOW_COPY_AND_ASSIGN(SkiaTextRenderer);
87 // Internal helper class used by derived classes to iterate colors and styles.
88 class StyleIterator {
89 public:
90 StyleIterator(const BreakList<SkColor>& colors,
91 const std::vector<BreakList<bool> >& styles);
92 ~StyleIterator();
94 // Get the colors and styles at the current iterator position.
95 SkColor color() const { return color_->second; }
96 bool style(TextStyle s) const { return style_[s]->second; }
98 // Get the intersecting range of the current iterator set.
99 ui::Range GetRange() const;
101 // Update the iterator to point to colors and styles applicable at |position|.
102 void UpdatePosition(size_t position);
104 private:
105 BreakList<SkColor> colors_;
106 std::vector<BreakList<bool> > styles_;
108 BreakList<SkColor>::const_iterator color_;
109 std::vector<BreakList<bool>::const_iterator> style_;
111 DISALLOW_COPY_AND_ASSIGN(StyleIterator);
114 } // namespace internal
116 // RenderText represents an abstract model of styled text and its corresponding
117 // visual layout. Support is built in for a cursor, a selection, simple styling,
118 // complex scripts, and bi-directional text. Implementations provide mechanisms
119 // for rendering and translation between logical and visual data.
120 class UI_EXPORT RenderText {
121 public:
122 virtual ~RenderText();
124 // Creates a platform-specific RenderText instance.
125 static RenderText* CreateInstance();
127 const base::string16& text() const { return text_; }
128 void SetText(const base::string16& text);
130 HorizontalAlignment horizontal_alignment() const {
131 return horizontal_alignment_;
133 void SetHorizontalAlignment(HorizontalAlignment alignment);
135 VerticalAlignment vertical_alignment() const {
136 return vertical_alignment_;
138 void SetVerticalAlignment(VerticalAlignment alignment);
140 const FontList& font_list() const { return font_list_; }
141 void SetFontList(const FontList& font_list);
142 void SetFont(const Font& font);
144 // Set the font size to |size| in pixels.
145 void SetFontSize(int size);
147 // Get the first font in |font_list_|.
148 const Font& GetPrimaryFont() const;
150 bool cursor_enabled() const { return cursor_enabled_; }
151 void SetCursorEnabled(bool cursor_enabled);
153 bool cursor_visible() const { return cursor_visible_; }
154 void set_cursor_visible(bool visible) { cursor_visible_ = visible; }
156 bool insert_mode() const { return insert_mode_; }
157 void ToggleInsertMode();
159 SkColor cursor_color() const { return cursor_color_; }
160 void set_cursor_color(SkColor color) { cursor_color_ = color; }
162 SkColor selection_color() const { return selection_color_; }
163 void set_selection_color(SkColor color) { selection_color_ = color; }
165 SkColor selection_background_focused_color() const {
166 return selection_background_focused_color_;
168 void set_selection_background_focused_color(SkColor color) {
169 selection_background_focused_color_ = color;
172 bool focused() const { return focused_; }
173 void set_focused(bool focused) { focused_ = focused; }
175 bool clip_to_display_rect() const { return clip_to_display_rect_; }
176 void set_clip_to_display_rect(bool clip) { clip_to_display_rect_ = clip; }
178 // In an obscured (password) field, all text is drawn as asterisks or bullets.
179 bool obscured() const { return obscured_; }
180 void SetObscured(bool obscured);
182 // Makes a char in obscured text at |index| to be revealed. |index| should be
183 // a UTF16 text index. If there is a previous revealed index, the previous one
184 // is cleared and only the last set index will be revealed. If |index| is -1
185 // or out of range, no char will be revealed. The revealed index is also
186 // cleared when SetText or SetObscured is called.
187 void SetObscuredRevealIndex(int index);
189 // Set the maximum length of the displayed layout text, not the actual text.
190 // A |length| of 0 forgoes a hard limit, but does not guarantee proper
191 // functionality of very long strings. Applies to subsequent SetText calls.
192 // WARNING: Only use this for system limits, it lacks complex text support.
193 void set_truncate_length(size_t length) { truncate_length_ = length; }
195 const Rect& display_rect() const { return display_rect_; }
196 void SetDisplayRect(const Rect& r);
198 void set_fade_head(bool fade_head) { fade_head_ = fade_head; }
199 bool fade_head() const { return fade_head_; }
200 void set_fade_tail(bool fade_tail) { fade_tail_ = fade_tail; }
201 bool fade_tail() const { return fade_tail_; }
203 bool background_is_transparent() const { return background_is_transparent_; }
204 void set_background_is_transparent(bool transparent) {
205 background_is_transparent_ = transparent;
208 const SelectionModel& selection_model() const { return selection_model_; }
210 const ui::Range& selection() const { return selection_model_.selection(); }
212 size_t cursor_position() const { return selection_model_.caret_pos(); }
213 void SetCursorPosition(size_t position);
215 // Moves the cursor left or right. Cursor movement is visual, meaning that
216 // left and right are relative to screen, not the directionality of the text.
217 // If |select| is false, the selection start is moved to the same position.
218 void MoveCursor(BreakType break_type,
219 VisualCursorDirection direction,
220 bool select);
222 // Set the selection_model_ to the value of |selection|.
223 // The selection range is clamped to text().length() if out of range.
224 // Returns true if the cursor position or selection range changed.
225 // If any index in |selection_model| is not a cursorable position (not on a
226 // grapheme boundary), it is a no-op and returns false.
227 bool MoveCursorTo(const SelectionModel& selection_model);
229 // Move the cursor to the position associated with the clicked point.
230 // If |select| is false, the selection start is moved to the same position.
231 // Returns true if the cursor position or selection range changed.
232 bool MoveCursorTo(const Point& point, bool select);
234 // Set the selection_model_ based on |range|.
235 // If the |range| start or end is greater than text length, it is modified
236 // to be the text length.
237 // If the |range| start or end is not a cursorable position (not on grapheme
238 // boundary), it is a NO-OP and returns false. Otherwise, returns true.
239 bool SelectRange(const ui::Range& range);
241 // Returns true if the local point is over selected text.
242 bool IsPointInSelection(const Point& point);
244 // Selects no text, keeping the current cursor position and caret affinity.
245 void ClearSelection();
247 // Select the entire text range. If |reversed| is true, the range will end at
248 // the logical beginning of the text; this generally shows the leading portion
249 // of text that overflows its display area.
250 void SelectAll(bool reversed);
252 // Selects the word at the current cursor position. If there is a non-empty
253 // selection, the selection bounds are extended to their nearest word
254 // boundaries.
255 void SelectWord();
257 const ui::Range& GetCompositionRange() const;
258 void SetCompositionRange(const ui::Range& composition_range);
260 // Set the text color over the entire text or a logical character range.
261 // The |range| should be valid, non-reversed, and within [0, text().length()].
262 void SetColor(SkColor value);
263 void ApplyColor(SkColor value, const ui::Range& range);
265 // Set various text styles over the entire text or a logical character range.
266 // The respective |style| is applied if |value| is true, or removed if false.
267 // The |range| should be valid, non-reversed, and within [0, text().length()].
268 void SetStyle(TextStyle style, bool value);
269 void ApplyStyle(TextStyle style, bool value, const ui::Range& range);
271 // Returns whether this style is enabled consistently across the entire
272 // RenderText.
273 bool GetStyle(TextStyle style) const;
275 // Set the text directionality mode and get the text direction yielded.
276 void SetDirectionalityMode(DirectionalityMode mode);
277 base::i18n::TextDirection GetTextDirection();
279 // Returns the visual movement direction corresponding to the logical end
280 // of the text, considering only the dominant direction returned by
281 // |GetTextDirection()|, not the direction of a particular run.
282 VisualCursorDirection GetVisualDirectionOfLogicalEnd();
284 // Returns the size in pixels of the entire string. For the height, this will
285 // return the maximum height among the different fonts in the text runs.
286 // Note that this returns the raw size of the string, which does not include
287 // the margin area of text shadows.
288 virtual Size GetStringSize() = 0;
290 // Returns the width of content, which reserves room for the cursor if
291 // |cursor_enabled_| is true.
292 int GetContentWidth();
294 // Returns the common baseline of the text. The returned value is the vertical
295 // offset from the top of |display_rect| to the text baseline, in pixels.
296 virtual int GetBaseline() = 0;
298 void Draw(Canvas* canvas);
300 // Draws a cursor at |position|.
301 void DrawCursor(Canvas* canvas, const SelectionModel& position);
303 // Draw the selected text without a cursor or selection highlight. Subpixel
304 // antialiasing is disabled and foreground color is forced to black.
305 void DrawSelectedTextForDrag(Canvas* canvas);
307 // Gets the SelectionModel from a visual point in local coordinates.
308 virtual SelectionModel FindCursorPosition(const Point& point) = 0;
310 // Get the visual bounds of a cursor at |selection|. These bounds typically
311 // represent a vertical line, but if |insert_mode| is true they contain the
312 // bounds of the associated glyph. These bounds are in local coordinates, but
313 // may be outside the visible region if the text is longer than the textfield.
314 // Subsequent text, cursor, or bounds changes may invalidate returned values.
315 Rect GetCursorBounds(const SelectionModel& selection, bool insert_mode);
317 // Compute the current cursor bounds, panning the text to show the cursor in
318 // the display rect if necessary. These bounds are in local coordinates.
319 // Subsequent text, cursor, or bounds changes may invalidate returned values.
320 const Rect& GetUpdatedCursorBounds();
322 // Given an |index| in text(), return the next or previous grapheme boundary
323 // in logical order (that is, the nearest index for which
324 // |IsCursorablePosition(index)| returns true). The return value is in the
325 // range 0 to text().length() inclusive (the input is clamped if it is out of
326 // that range). Always moves by at least one character index unless the
327 // supplied index is already at the boundary of the string.
328 size_t IndexOfAdjacentGrapheme(size_t index,
329 LogicalCursorDirection direction);
331 // Return a SelectionModel with the cursor at the current selection's start.
332 // The returned value represents a cursor/caret position without a selection.
333 SelectionModel GetSelectionModelForSelectionStart();
335 // Sets shadows to drawn with text.
336 void SetTextShadows(const ShadowValues& shadows);
338 typedef std::pair<Font, ui::Range> FontSpan;
339 // For testing purposes, returns which fonts were chosen for which parts of
340 // the text by returning a vector of Font and Range pairs, where each range
341 // specifies the character range for which the corresponding font has been
342 // chosen.
343 virtual std::vector<FontSpan> GetFontSpansForTesting() = 0;
345 protected:
346 RenderText();
348 const BreakList<SkColor>& colors() const { return colors_; }
349 const std::vector<BreakList<bool> >& styles() const { return styles_; }
351 const Vector2d& GetUpdatedDisplayOffset();
353 void set_cached_bounds_and_offset_valid(bool valid) {
354 cached_bounds_and_offset_valid_ = valid;
357 // Get the selection model that visually neighbors |position| by |break_type|.
358 // The returned value represents a cursor/caret position without a selection.
359 SelectionModel GetAdjacentSelectionModel(const SelectionModel& current,
360 BreakType break_type,
361 VisualCursorDirection direction);
363 // Get the selection model visually left/right of |selection| by one grapheme.
364 // The returned value represents a cursor/caret position without a selection.
365 virtual SelectionModel AdjacentCharSelectionModel(
366 const SelectionModel& selection,
367 VisualCursorDirection direction) = 0;
369 // Get the selection model visually left/right of |selection| by one word.
370 // The returned value represents a cursor/caret position without a selection.
371 virtual SelectionModel AdjacentWordSelectionModel(
372 const SelectionModel& selection,
373 VisualCursorDirection direction) = 0;
375 // Get the SelectionModels corresponding to visual text ends.
376 // The returned value represents a cursor/caret position without a selection.
377 SelectionModel EdgeSelectionModel(VisualCursorDirection direction);
379 // Sets the selection model, the argument is assumed to be valid.
380 virtual void SetSelectionModel(const SelectionModel& model);
382 // Get the horizontal bounds (relative to the left of the text, not the view)
383 // of the glyph starting at |index|. If the glyph is RTL then the returned
384 // Range will have is_reversed() true. (This does not return a Rect because a
385 // Rect can't have a negative width.)
386 virtual ui::Range GetGlyphBounds(size_t index) = 0;
388 // Get the visual bounds containing the logical substring within the |range|.
389 // If |range| is empty, the result is empty. These bounds could be visually
390 // discontinuous if the substring is split by a LTR/RTL level change.
391 // These bounds are in local coordinates, but may be outside the visible
392 // region if the text is longer than the textfield. Subsequent text, cursor,
393 // or bounds changes may invalidate returned values.
394 virtual std::vector<Rect> GetSubstringBounds(const ui::Range& range) = 0;
396 // Convert between indices into |text_| and indices into |obscured_text_|,
397 // which differ when the text is obscured. Regardless of whether or not the
398 // text is obscured, the character (code point) offsets always match.
399 virtual size_t TextIndexToLayoutIndex(size_t index) const = 0;
400 virtual size_t LayoutIndexToTextIndex(size_t index) const = 0;
402 // Return true if cursor can appear in front of the character at |position|,
403 // which means it is a grapheme boundary or the first character in the text.
404 virtual bool IsCursorablePosition(size_t position) = 0;
406 // Reset the layout to be invalid.
407 virtual void ResetLayout() = 0;
409 // Ensure the text is laid out.
410 virtual void EnsureLayout() = 0;
412 // Draw the text.
413 virtual void DrawVisualText(Canvas* canvas) = 0;
415 // Returns the text used for layout, which may be obscured or truncated.
416 const base::string16& GetLayoutText() const;
418 // Apply (and undo) temporary composition underlines and selection colors.
419 void ApplyCompositionAndSelectionStyles();
420 void UndoCompositionAndSelectionStyles();
422 // Returns the text offset from the origin after applying text alignment and
423 // display offset.
424 Vector2d GetTextOffset();
426 // Convert points from the text space to the view space and back.
427 // Handles the display area, display offset, and the application LTR/RTL mode.
428 Point ToTextPoint(const Point& point);
429 Point ToViewPoint(const Point& point);
431 // Returns the text offset from the origin, taking into account text alignment
432 // only.
433 Vector2d GetAlignmentOffset();
435 // Applies fade effects to |renderer|.
436 void ApplyFadeEffects(internal::SkiaTextRenderer* renderer);
438 // Applies text shadows to |renderer|.
439 void ApplyTextShadows(internal::SkiaTextRenderer* renderer);
441 // A convenience function to check whether the glyph attached to the caret
442 // is within the given range.
443 static bool RangeContainsCaret(const ui::Range& range,
444 size_t caret_pos,
445 LogicalCursorDirection caret_affinity);
447 private:
448 friend class RenderTextTest;
449 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, DefaultStyle);
450 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, SetColorAndStyle);
451 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, ApplyColorAndStyle);
452 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, ObscuredText);
453 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, RevealObscuredText);
454 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, TruncatedText);
455 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, TruncatedObscuredText);
456 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, GraphemePositions);
457 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, EdgeSelectionModels);
458 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, GetTextOffset);
459 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, GetTextOffsetHorizontalDefaultInRTL);
461 // Set the cursor to |position|, with the caret trailing the previous
462 // grapheme, or if there is no previous grapheme, leading the cursor position.
463 // If |select| is false, the selection start is moved to the same position.
464 // If the |position| is not a cursorable position (not on grapheme boundary),
465 // it is a NO-OP.
466 void MoveCursorTo(size_t position, bool select);
468 // Updates |layout_text_| if the text is obscured or truncated.
469 void UpdateLayoutText();
471 // Update the cached bounds and display offset to ensure that the current
472 // cursor is within the visible display area.
473 void UpdateCachedBoundsAndOffset();
475 // Draw the selection.
476 void DrawSelection(Canvas* canvas);
478 // Logical UTF-16 string data to be drawn.
479 base::string16 text_;
481 // Horizontal alignment of the text with respect to |display_rect_|. The
482 // default is to align left if the application UI is LTR and right if RTL.
483 HorizontalAlignment horizontal_alignment_;
485 // Vertical alignment of the text with respect to |display_rect_|. The
486 // default is to align vertically centered.
487 VerticalAlignment vertical_alignment_;
489 // The text directionality mode, defaults to DIRECTIONALITY_FROM_TEXT.
490 DirectionalityMode directionality_mode_;
492 // The cached text direction, potentially computed from the text or UI locale.
493 // Use GetTextDirection(), do not use this potentially invalid value directly!
494 base::i18n::TextDirection text_direction_;
496 // A list of fonts used to render |text_|.
497 FontList font_list_;
499 // Logical selection range and visual cursor position.
500 SelectionModel selection_model_;
502 // The cached cursor bounds; get these bounds with GetUpdatedCursorBounds.
503 Rect cursor_bounds_;
505 // Specifies whether the cursor is enabled. If disabled, no space is reserved
506 // for the cursor when positioning text.
507 bool cursor_enabled_;
509 // The cursor visibility and insert mode.
510 bool cursor_visible_;
511 bool insert_mode_;
513 // The color used for the cursor.
514 SkColor cursor_color_;
516 // The color used for drawing selected text.
517 SkColor selection_color_;
519 // The background color used for drawing the selection when focused.
520 SkColor selection_background_focused_color_;
522 // The focus state of the text.
523 bool focused_;
525 // Composition text range.
526 ui::Range composition_range_;
528 // Color and style breaks, used to color and stylize ranges of text.
529 // BreakList positions are stored with text indices, not layout indices.
530 // TODO(msw): Expand to support cursor, selection, background, etc. colors.
531 BreakList<SkColor> colors_;
532 std::vector<BreakList<bool> > styles_;
534 // Breaks saved without temporary composition and selection styling.
535 BreakList<SkColor> saved_colors_;
536 BreakList<bool> saved_underlines_;
537 bool composition_and_selection_styles_applied_;
539 // A flag to obscure actual text with asterisks for password fields.
540 bool obscured_;
541 // The index at which the char should be revealed in the obscured text.
542 int obscured_reveal_index_;
544 // The maximum length of text to display, 0 forgoes a hard limit.
545 size_t truncate_length_;
547 // The obscured and/or truncated text that will be displayed.
548 base::string16 layout_text_;
550 // Fade text head and/or tail, if text doesn't fit into |display_rect_|.
551 bool fade_head_;
552 bool fade_tail_;
554 // Is the background transparent (either partially or fully)?
555 bool background_is_transparent_;
557 // The local display area for rendering the text.
558 Rect display_rect_;
560 // Flag to work around a Skia bug with the PDF path (http://crbug.com/133548)
561 // that results in incorrect clipping when drawing to the document margins.
562 // This field allows disabling clipping to work around the issue.
563 // TODO(asvitkine): Remove this when the underlying Skia bug is fixed.
564 bool clip_to_display_rect_;
566 // The offset for the text to be drawn, relative to the display area.
567 // Get this point with GetUpdatedDisplayOffset (or risk using a stale value).
568 Vector2d display_offset_;
570 // The cached bounds and offset are invalidated by changes to the cursor,
571 // selection, font, and other operations that adjust the visible text bounds.
572 bool cached_bounds_and_offset_valid_;
574 // Text shadows to be drawn.
575 ShadowValues text_shadows_;
577 DISALLOW_COPY_AND_ASSIGN(RenderText);
580 } // namespace gfx
582 #endif // UI_GFX_RENDER_TEXT_H_