Don't crash when SimpleCache index is corrupt.
[chromium-blink-merge.git] / ui / gfx / render_text.h
blobc10b8abf3d63c2177ee68269b73a0fc9888312a6
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& GetFont() 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 SkColor selection_background_unfocused_color() const {
173 return selection_background_unfocused_color_;
175 void set_selection_background_unfocused_color(SkColor color) {
176 selection_background_unfocused_color_ = color;
179 bool focused() const { return focused_; }
180 void set_focused(bool focused) { focused_ = focused; }
182 bool clip_to_display_rect() const { return clip_to_display_rect_; }
183 void set_clip_to_display_rect(bool clip) { clip_to_display_rect_ = clip; }
185 // In an obscured (password) field, all text is drawn as asterisks or bullets.
186 bool obscured() const { return obscured_; }
187 void SetObscured(bool obscured);
189 // Makes a char in obscured text at |index| to be revealed. |index| should be
190 // a UTF16 text index. If there is a previous revealed index, the previous one
191 // is cleared and only the last set index will be revealed. If |index| is -1
192 // or out of range, no char will be revealed. The revealed index is also
193 // cleared when SetText or SetObscured is called.
194 void SetObscuredRevealIndex(int index);
196 const Rect& display_rect() const { return display_rect_; }
197 void SetDisplayRect(const Rect& r);
199 void set_fade_head(bool fade_head) { fade_head_ = fade_head; }
200 bool fade_head() const { return fade_head_; }
201 void set_fade_tail(bool fade_tail) { fade_tail_ = fade_tail; }
202 bool fade_tail() const { return fade_tail_; }
204 bool background_is_transparent() const { return background_is_transparent_; }
205 void set_background_is_transparent(bool transparent) {
206 background_is_transparent_ = transparent;
209 const SelectionModel& selection_model() const { return selection_model_; }
211 const ui::Range& selection() const { return selection_model_.selection(); }
213 size_t cursor_position() const { return selection_model_.caret_pos(); }
214 void SetCursorPosition(size_t position);
216 // Moves the cursor left or right. Cursor movement is visual, meaning that
217 // left and right are relative to screen, not the directionality of the text.
218 // If |select| is false, the selection start is moved to the same position.
219 void MoveCursor(BreakType break_type,
220 VisualCursorDirection direction,
221 bool select);
223 // Set the selection_model_ to the value of |selection|.
224 // The selection range is clamped to text().length() if out of range.
225 // Returns true if the cursor position or selection range changed.
226 // If any index in |selection_model| is not a cursorable position (not on a
227 // grapheme boundary), it is a no-op and returns false.
228 bool MoveCursorTo(const SelectionModel& selection_model);
230 // Move the cursor to the position associated with the clicked point.
231 // If |select| is false, the selection start is moved to the same position.
232 // Returns true if the cursor position or selection range changed.
233 bool MoveCursorTo(const Point& point, bool select);
235 // Set the selection_model_ based on |range|.
236 // If the |range| start or end is greater than text length, it is modified
237 // to be the text length.
238 // If the |range| start or end is not a cursorable position (not on grapheme
239 // boundary), it is a NO-OP and returns false. Otherwise, returns true.
240 bool SelectRange(const ui::Range& range);
242 // Returns true if the local point is over selected text.
243 bool IsPointInSelection(const Point& point);
245 // Selects no text, keeping the current cursor position and caret affinity.
246 void ClearSelection();
248 // Select the entire text range. If |reversed| is true, the range will end at
249 // the logical beginning of the text; this generally shows the leading portion
250 // of text that overflows its display area.
251 void SelectAll(bool reversed);
253 // Selects the word at the current cursor position. If there is a non-empty
254 // selection, the selection bounds are extended to their nearest word
255 // boundaries.
256 void SelectWord();
258 const ui::Range& GetCompositionRange() const;
259 void SetCompositionRange(const ui::Range& composition_range);
261 // Set the text color over the entire text or a logical character range.
262 // The |range| should be valid, non-reversed, and within [0, text().length()].
263 void SetColor(SkColor value);
264 void ApplyColor(SkColor value, const ui::Range& range);
266 // Set various text styles over the entire text or a logical character range.
267 // The respective |style| is applied if |value| is true, or removed if false.
268 // The |range| should be valid, non-reversed, and within [0, text().length()].
269 void SetStyle(TextStyle style, bool value);
270 void ApplyStyle(TextStyle style, bool value, const ui::Range& range);
272 // Returns whether this style is enabled consistently across the entire
273 // RenderText.
274 bool GetStyle(TextStyle style) const;
276 // Set the text directionality mode and get the text direction yielded.
277 void SetDirectionalityMode(DirectionalityMode mode);
278 base::i18n::TextDirection GetTextDirection();
280 // Returns the visual movement direction corresponding to the logical end
281 // of the text, considering only the dominant direction returned by
282 // |GetTextDirection()|, not the direction of a particular run.
283 VisualCursorDirection GetVisualDirectionOfLogicalEnd();
285 // Returns the size in pixels of the entire string. For the height, this will
286 // return the maximum height among the different fonts in the text runs.
287 // Note that this returns the raw size of the string, which does not include
288 // the margin area of text shadows.
289 virtual Size GetStringSize() = 0;
291 // Returns the width of content, which reserves room for the cursor if
292 // |cursor_enabled_| is true.
293 int GetContentWidth();
295 // Returns the common baseline of the text. The returned value is the vertical
296 // offset from the top of |display_rect| to the text baseline, in pixels.
297 virtual int GetBaseline() = 0;
299 void Draw(Canvas* canvas);
301 // Draws a cursor at |position|.
302 void DrawCursor(Canvas* canvas, const SelectionModel& position);
304 // Draw the selected text without a cursor or selection highlight.
305 void DrawSelectedText(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_text_|.
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, GraphemePositions);
455 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, EdgeSelectionModels);
456 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, GetTextOffset);
457 FRIEND_TEST_ALL_PREFIXES(RenderTextTest, GetTextOffsetHorizontalDefaultInRTL);
459 // Set the cursor to |position|, with the caret trailing the previous
460 // grapheme, or if there is no previous grapheme, leading the cursor position.
461 // If |select| is false, the selection start is moved to the same position.
462 // If the |position| is not a cursorable position (not on grapheme boundary),
463 // it is a NO-OP.
464 void MoveCursorTo(size_t position, bool select);
466 // Updates |obscured_text_| if the text is obscured.
467 void UpdateObscuredText();
469 // Update the cached bounds and display offset to ensure that the current
470 // cursor is within the visible display area.
471 void UpdateCachedBoundsAndOffset();
473 // Draw the selection.
474 void DrawSelection(Canvas* canvas);
476 // Logical UTF-16 string data to be drawn.
477 base::string16 text_;
479 // Horizontal alignment of the text with respect to |display_rect_|. The
480 // default is to align left if the application UI is LTR and right if RTL.
481 HorizontalAlignment horizontal_alignment_;
483 // Vertical alignment of the text with respect to |display_rect_|. The
484 // default is to align vertically centered.
485 VerticalAlignment vertical_alignment_;
487 // The text directionality mode, defaults to DIRECTIONALITY_FROM_TEXT.
488 DirectionalityMode directionality_mode_;
490 // The cached text direction, potentially computed from the text or UI locale.
491 // Use GetTextDirection(), do not use this potentially invalid value directly!
492 base::i18n::TextDirection text_direction_;
494 // A list of fonts used to render |text_|.
495 FontList font_list_;
497 // Logical selection range and visual cursor position.
498 SelectionModel selection_model_;
500 // The cached cursor bounds; get these bounds with GetUpdatedCursorBounds.
501 Rect cursor_bounds_;
503 // Specifies whether the cursor is enabled. If disabled, no space is reserved
504 // for the cursor when positioning text.
505 bool cursor_enabled_;
507 // The cursor visibility and insert mode.
508 bool cursor_visible_;
509 bool insert_mode_;
511 // The color used for the cursor.
512 SkColor cursor_color_;
514 // The color used for drawing selected text.
515 SkColor selection_color_;
517 // The background color used for drawing the selection when focused.
518 SkColor selection_background_focused_color_;
520 // The background color used for drawing the selection when not focused.
521 SkColor selection_background_unfocused_color_;
523 // The focus state of the text.
524 bool focused_;
526 // Composition text range.
527 ui::Range composition_range_;
529 // Color and style breaks, used to color and stylize ranges of text.
530 // BreakList positions are stored with text indices, not layout indices.
531 // TODO(msw): Expand to support cursor, selection, background, etc. colors.
532 BreakList<SkColor> colors_;
533 std::vector<BreakList<bool> > styles_;
535 // Breaks saved without temporary composition and selection styling.
536 BreakList<SkColor> saved_colors_;
537 BreakList<bool> saved_underlines_;
538 bool composition_and_selection_styles_applied_;
540 // A flag and the text to display for obscured (password) fields.
541 // Asterisks are used instead of the actual text glyphs when true.
542 bool obscured_;
543 base::string16 obscured_text_;
545 // The index at which the char should be revealed in the obscured text.
546 int obscured_reveal_index_;
548 // Fade text head and/or tail, if text doesn't fit into |display_rect_|.
549 bool fade_head_;
550 bool fade_tail_;
552 // Is the background transparent (either partially or fully)?
553 bool background_is_transparent_;
555 // The local display area for rendering the text.
556 Rect display_rect_;
558 // Flag to work around a Skia bug with the PDF path (http://crbug.com/133548)
559 // that results in incorrect clipping when drawing to the document margins.
560 // This field allows disabling clipping to work around the issue.
561 // TODO(asvitkine): Remove this when the underlying Skia bug is fixed.
562 bool clip_to_display_rect_;
564 // The offset for the text to be drawn, relative to the display area.
565 // Get this point with GetUpdatedDisplayOffset (or risk using a stale value).
566 Vector2d display_offset_;
568 // The cached bounds and offset are invalidated by changes to the cursor,
569 // selection, font, and other operations that adjust the visible text bounds.
570 bool cached_bounds_and_offset_valid_;
572 // Text shadows to be drawn.
573 ShadowValues text_shadows_;
575 DISALLOW_COPY_AND_ASSIGN(RenderText);
578 } // namespace gfx
580 #endif // UI_GFX_RENDER_TEXT_H_