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 #include "ui/gfx/render_text.h"
10 #include "base/command_line.h"
11 #include "base/i18n/break_iterator.h"
12 #include "base/logging.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/trace_event/trace_event.h"
17 #include "third_party/icu/source/common/unicode/rbbi.h"
18 #include "third_party/icu/source/common/unicode/utf16.h"
19 #include "third_party/skia/include/core/SkTypeface.h"
20 #include "third_party/skia/include/effects/SkGradientShader.h"
21 #include "ui/gfx/canvas.h"
22 #include "ui/gfx/geometry/insets.h"
23 #include "ui/gfx/geometry/safe_integer_conversions.h"
24 #include "ui/gfx/render_text_harfbuzz.h"
25 #include "ui/gfx/scoped_canvas.h"
26 #include "ui/gfx/skia_util.h"
27 #include "ui/gfx/switches.h"
28 #include "ui/gfx/text_elider.h"
29 #include "ui/gfx/text_utils.h"
30 #include "ui/gfx/utf16_indexing.h"
32 #if defined(OS_MACOSX)
33 #include "ui/gfx/render_text_mac.h"
34 #endif // defined(OS_MACOSX)
40 // All chars are replaced by this char when the password style is set.
41 // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*'
42 // that's available in the font (find_invisible_char() in gtkentry.c).
43 const base::char16 kPasswordReplacementChar
= '*';
45 // Default color used for the text and cursor.
46 const SkColor kDefaultColor
= SK_ColorBLACK
;
48 // Default color used for drawing selection background.
49 const SkColor kDefaultSelectionBackgroundColor
= SK_ColorGRAY
;
51 // Fraction of the text size to lower a strike through below the baseline.
52 const SkScalar kStrikeThroughOffset
= (-SK_Scalar1
* 6 / 21);
53 // Fraction of the text size to lower an underline below the baseline.
54 const SkScalar kUnderlineOffset
= (SK_Scalar1
/ 9);
55 // Fraction of the text size to use for a strike through or under-line.
56 const SkScalar kLineThickness
= (SK_Scalar1
/ 18);
57 // Fraction of the text size to use for a top margin of a diagonal strike.
58 const SkScalar kDiagonalStrikeMarginOffset
= (SK_Scalar1
/ 4);
60 // Invalid value of baseline. Assigning this value to |baseline_| causes
61 // re-calculation of baseline.
62 const int kInvalidBaseline
= INT_MAX
;
64 // Returns the baseline, with which the text best appears vertically centered.
65 int DetermineBaselineCenteringText(const Rect
& display_rect
,
66 const FontList
& font_list
) {
67 const int display_height
= display_rect
.height();
68 const int font_height
= font_list
.GetHeight();
69 // Lower and upper bound of baseline shift as we try to show as much area of
70 // text as possible. In particular case of |display_height| == |font_height|,
71 // we do not want to shift the baseline.
72 const int min_shift
= std::min(0, display_height
- font_height
);
73 const int max_shift
= std::abs(display_height
- font_height
);
74 const int baseline
= font_list
.GetBaseline();
75 const int cap_height
= font_list
.GetCapHeight();
76 const int internal_leading
= baseline
- cap_height
;
77 // Some platforms don't support getting the cap height, and simply return
78 // the entire font ascent from GetCapHeight(). Centering the ascent makes
79 // the font look too low, so if GetCapHeight() returns the ascent, center
80 // the entire font height instead.
82 display_height
- ((internal_leading
!= 0) ? cap_height
: font_height
);
83 const int baseline_shift
= space
/ 2 - internal_leading
;
84 return baseline
+ std::max(min_shift
, std::min(max_shift
, baseline_shift
));
87 // Converts |Font::FontStyle| flags to |SkTypeface::Style| flags.
88 SkTypeface::Style
ConvertFontStyleToSkiaTypefaceStyle(int font_style
) {
89 int skia_style
= SkTypeface::kNormal
;
90 skia_style
|= (font_style
& Font::BOLD
) ? SkTypeface::kBold
: 0;
91 skia_style
|= (font_style
& Font::ITALIC
) ? SkTypeface::kItalic
: 0;
92 return static_cast<SkTypeface::Style
>(skia_style
);
95 // Given |font| and |display_width|, returns the width of the fade gradient.
96 int CalculateFadeGradientWidth(const FontList
& font_list
, int display_width
) {
97 // Fade in/out about 2.5 characters of the beginning/end of the string.
98 // The .5 here is helpful if one of the characters is a space.
99 // Use a quarter of the display width if the display width is very short.
100 const int average_character_width
= font_list
.GetExpectedTextWidth(1);
101 const double gradient_width
= std::min(average_character_width
* 2.5,
102 display_width
/ 4.0);
103 DCHECK_GE(gradient_width
, 0.0);
104 return static_cast<int>(floor(gradient_width
+ 0.5));
107 // Appends to |positions| and |colors| values corresponding to the fade over
108 // |fade_rect| from color |c0| to color |c1|.
109 void AddFadeEffect(const Rect
& text_rect
,
110 const Rect
& fade_rect
,
113 std::vector
<SkScalar
>* positions
,
114 std::vector
<SkColor
>* colors
) {
115 const SkScalar left
= static_cast<SkScalar
>(fade_rect
.x() - text_rect
.x());
116 const SkScalar width
= static_cast<SkScalar
>(fade_rect
.width());
117 const SkScalar p0
= left
/ text_rect
.width();
118 const SkScalar p1
= (left
+ width
) / text_rect
.width();
119 // Prepend 0.0 to |positions|, as required by Skia.
120 if (positions
->empty() && p0
!= 0.0) {
121 positions
->push_back(0.0);
122 colors
->push_back(c0
);
124 positions
->push_back(p0
);
125 colors
->push_back(c0
);
126 positions
->push_back(p1
);
127 colors
->push_back(c1
);
130 // Creates a SkShader to fade the text, with |left_part| specifying the left
131 // fade effect, if any, and |right_part| specifying the right fade effect.
132 skia::RefPtr
<SkShader
> CreateFadeShader(const Rect
& text_rect
,
133 const Rect
& left_part
,
134 const Rect
& right_part
,
136 // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color.
137 const SkColor fade_color
= SkColorSetA(color
, 51);
138 std::vector
<SkScalar
> positions
;
139 std::vector
<SkColor
> colors
;
141 if (!left_part
.IsEmpty())
142 AddFadeEffect(text_rect
, left_part
, fade_color
, color
,
143 &positions
, &colors
);
144 if (!right_part
.IsEmpty())
145 AddFadeEffect(text_rect
, right_part
, color
, fade_color
,
146 &positions
, &colors
);
147 DCHECK(!positions
.empty());
149 // Terminate |positions| with 1.0, as required by Skia.
150 if (positions
.back() != 1.0) {
151 positions
.push_back(1.0);
152 colors
.push_back(colors
.back());
156 points
[0].iset(text_rect
.x(), text_rect
.y());
157 points
[1].iset(text_rect
.right(), text_rect
.y());
159 return skia::AdoptRef(
160 SkGradientShader::CreateLinear(&points
[0], &colors
[0], &positions
[0],
161 colors
.size(), SkShader::kClamp_TileMode
));
164 // Converts a FontRenderParams::Hinting value to the corresponding
165 // SkPaint::Hinting value.
166 SkPaint::Hinting
FontRenderParamsHintingToSkPaintHinting(
167 FontRenderParams::Hinting params_hinting
) {
168 switch (params_hinting
) {
169 case FontRenderParams::HINTING_NONE
: return SkPaint::kNo_Hinting
;
170 case FontRenderParams::HINTING_SLIGHT
: return SkPaint::kSlight_Hinting
;
171 case FontRenderParams::HINTING_MEDIUM
: return SkPaint::kNormal_Hinting
;
172 case FontRenderParams::HINTING_FULL
: return SkPaint::kFull_Hinting
;
174 return SkPaint::kNo_Hinting
;
177 // Make sure ranges don't break text graphemes. If a range in |break_list|
178 // does break a grapheme in |render_text|, the range will be slightly
179 // extended to encompass the grapheme.
180 template <typename T
>
181 void RestoreBreakList(RenderText
* render_text
, BreakList
<T
>& break_list
) {
182 break_list
.SetMax(render_text
->text().length());
184 while (range
.end() < break_list
.max()) {
185 const auto& current_break
= break_list
.GetBreak(range
.end());
186 range
= break_list
.GetRange(current_break
);
187 if (range
.end() < break_list
.max() &&
188 !render_text
->IsValidCursorIndex(range
.end())) {
190 render_text
->IndexOfAdjacentGrapheme(range
.end(), CURSOR_FORWARD
));
191 break_list
.ApplyValue(current_break
->second
, range
);
200 // Value of |underline_thickness_| that indicates that underline metrics have
201 // not been set explicitly.
202 const SkScalar kUnderlineMetricsNotSet
= -1.0f
;
204 SkiaTextRenderer::SkiaTextRenderer(Canvas
* canvas
)
206 canvas_skia_(canvas
->sk_canvas()),
207 underline_thickness_(kUnderlineMetricsNotSet
),
208 underline_position_(0.0f
) {
209 DCHECK(canvas_skia_
);
210 paint_
.setTextEncoding(SkPaint::kGlyphID_TextEncoding
);
211 paint_
.setStyle(SkPaint::kFill_Style
);
212 paint_
.setAntiAlias(true);
213 paint_
.setSubpixelText(true);
214 paint_
.setLCDRenderText(true);
215 paint_
.setHinting(SkPaint::kNormal_Hinting
);
218 SkiaTextRenderer::~SkiaTextRenderer() {
221 void SkiaTextRenderer::SetDrawLooper(SkDrawLooper
* draw_looper
) {
222 paint_
.setLooper(draw_looper
);
225 void SkiaTextRenderer::SetFontRenderParams(const FontRenderParams
& params
,
226 bool subpixel_rendering_suppressed
) {
227 ApplyRenderParams(params
, subpixel_rendering_suppressed
, &paint_
);
230 void SkiaTextRenderer::SetTypeface(SkTypeface
* typeface
) {
231 paint_
.setTypeface(typeface
);
234 void SkiaTextRenderer::SetTextSize(SkScalar size
) {
235 paint_
.setTextSize(size
);
238 void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string
& family
,
240 DCHECK(!family
.empty());
242 skia::RefPtr
<SkTypeface
> typeface
= CreateSkiaTypeface(family
.c_str(), style
);
244 // |paint_| adds its own ref. So don't |release()| it from the ref ptr here.
245 SetTypeface(typeface
.get());
247 // Enable fake bold text if bold style is needed but new typeface does not
249 paint_
.setFakeBoldText((style
& Font::BOLD
) && !typeface
->isBold());
253 void SkiaTextRenderer::SetForegroundColor(SkColor foreground
) {
254 paint_
.setColor(foreground
);
257 void SkiaTextRenderer::SetShader(SkShader
* shader
) {
258 paint_
.setShader(shader
);
261 void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness
,
263 underline_thickness_
= thickness
;
264 underline_position_
= position
;
267 void SkiaTextRenderer::DrawPosText(const SkPoint
* pos
,
268 const uint16
* glyphs
,
269 size_t glyph_count
) {
270 const size_t byte_length
= glyph_count
* sizeof(glyphs
[0]);
271 canvas_skia_
->drawPosText(&glyphs
[0], byte_length
, &pos
[0], paint_
);
274 void SkiaTextRenderer::DrawDecorations(int x
, int y
, int width
, bool underline
,
275 bool strike
, bool diagonal_strike
) {
277 DrawUnderline(x
, y
, width
);
279 DrawStrike(x
, y
, width
);
280 if (diagonal_strike
) {
282 diagonal_
.reset(new DiagonalStrike(canvas_
, Point(x
, y
), paint_
));
283 diagonal_
->AddPiece(width
, paint_
.getColor());
284 } else if (diagonal_
) {
289 void SkiaTextRenderer::EndDiagonalStrike() {
296 void SkiaTextRenderer::DrawUnderline(int x
, int y
, int width
) {
297 SkScalar x_scalar
= SkIntToScalar(x
);
298 SkRect r
= SkRect::MakeLTRB(
299 x_scalar
, y
+ underline_position_
, x_scalar
+ width
,
300 y
+ underline_position_
+ underline_thickness_
);
301 if (underline_thickness_
== kUnderlineMetricsNotSet
) {
302 const SkScalar text_size
= paint_
.getTextSize();
303 r
.fTop
= SkScalarMulAdd(text_size
, kUnderlineOffset
, y
);
304 r
.fBottom
= r
.fTop
+ SkScalarMul(text_size
, kLineThickness
);
306 canvas_skia_
->drawRect(r
, paint_
);
309 void SkiaTextRenderer::DrawStrike(int x
, int y
, int width
) const {
310 const SkScalar text_size
= paint_
.getTextSize();
311 const SkScalar height
= SkScalarMul(text_size
, kLineThickness
);
312 const SkScalar offset
= SkScalarMulAdd(text_size
, kStrikeThroughOffset
, y
);
313 SkScalar x_scalar
= SkIntToScalar(x
);
315 SkRect::MakeLTRB(x_scalar
, offset
, x_scalar
+ width
, offset
+ height
);
316 canvas_skia_
->drawRect(r
, paint_
);
319 SkiaTextRenderer::DiagonalStrike::DiagonalStrike(Canvas
* canvas
,
321 const SkPaint
& paint
)
328 SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() {
331 void SkiaTextRenderer::DiagonalStrike::AddPiece(int length
, SkColor color
) {
332 pieces_
.push_back(Piece(length
, color
));
333 total_length_
+= length
;
336 void SkiaTextRenderer::DiagonalStrike::Draw() {
337 const SkScalar text_size
= paint_
.getTextSize();
338 const SkScalar offset
= SkScalarMul(text_size
, kDiagonalStrikeMarginOffset
);
339 const int thickness
=
340 SkScalarCeilToInt(SkScalarMul(text_size
, kLineThickness
) * 2);
341 const int height
= SkScalarCeilToInt(text_size
- offset
);
342 const Point end
= start_
+ Vector2d(total_length_
, -height
);
343 const int clip_height
= height
+ 2 * thickness
;
345 paint_
.setAntiAlias(true);
346 paint_
.setStrokeWidth(SkIntToScalar(thickness
));
348 const bool clipped
= pieces_
.size() > 1;
349 SkCanvas
* sk_canvas
= canvas_
->sk_canvas();
352 for (size_t i
= 0; i
< pieces_
.size(); ++i
) {
353 paint_
.setColor(pieces_
[i
].second
);
357 sk_canvas
->clipRect(RectToSkRect(
358 Rect(x
, end
.y() - thickness
, pieces_
[i
].first
, clip_height
)));
361 canvas_
->DrawLine(start_
, end
, paint_
);
366 x
+= pieces_
[i
].first
;
370 StyleIterator::StyleIterator(const BreakList
<SkColor
>& colors
,
371 const BreakList
<BaselineStyle
>& baselines
,
372 const std::vector
<BreakList
<bool>>& styles
)
373 : colors_(colors
), baselines_(baselines
), styles_(styles
) {
374 color_
= colors_
.breaks().begin();
375 baseline_
= baselines_
.breaks().begin();
376 for (size_t i
= 0; i
< styles_
.size(); ++i
)
377 style_
.push_back(styles_
[i
].breaks().begin());
380 StyleIterator::~StyleIterator() {}
382 Range
StyleIterator::GetRange() const {
383 Range
range(colors_
.GetRange(color_
));
384 range
= range
.Intersect(baselines_
.GetRange(baseline_
));
385 for (size_t i
= 0; i
< NUM_TEXT_STYLES
; ++i
)
386 range
= range
.Intersect(styles_
[i
].GetRange(style_
[i
]));
390 void StyleIterator::UpdatePosition(size_t position
) {
391 color_
= colors_
.GetBreak(position
);
392 baseline_
= baselines_
.GetBreak(position
);
393 for (size_t i
= 0; i
< NUM_TEXT_STYLES
; ++i
)
394 style_
[i
] = styles_
[i
].GetBreak(position
);
397 LineSegment::LineSegment() : width(0), run(0) {}
399 LineSegment::~LineSegment() {}
401 Line::Line() : preceding_heights(0), baseline(0) {}
405 skia::RefPtr
<SkTypeface
> CreateSkiaTypeface(const std::string
& family
,
407 SkTypeface::Style skia_style
= ConvertFontStyleToSkiaTypefaceStyle(style
);
408 return skia::AdoptRef(SkTypeface::CreateFromName(family
.c_str(), skia_style
));
411 void ApplyRenderParams(const FontRenderParams
& params
,
412 bool subpixel_rendering_suppressed
,
414 paint
->setAntiAlias(params
.antialiasing
);
415 paint
->setLCDRenderText(!subpixel_rendering_suppressed
&&
416 params
.subpixel_rendering
!= FontRenderParams::SUBPIXEL_RENDERING_NONE
);
417 paint
->setSubpixelText(params
.subpixel_positioning
);
418 paint
->setAutohinted(params
.autohinter
);
419 paint
->setHinting(FontRenderParamsHintingToSkPaintHinting(params
.hinting
));
422 } // namespace internal
424 RenderText::~RenderText() {
428 RenderText
* RenderText::CreateInstance() {
429 #if defined(OS_MACOSX)
430 static const bool use_native
=
431 !base::CommandLine::ForCurrentProcess()->HasSwitch(
432 switches::kEnableHarfBuzzRenderText
);
434 return new RenderTextMac
;
435 #endif // defined(OS_MACOSX)
436 return new RenderTextHarfBuzz
;
440 RenderText
* RenderText::CreateInstanceForEditing() {
441 return new RenderTextHarfBuzz
;
444 void RenderText::SetText(const base::string16
& text
) {
445 DCHECK(!composition_range_
.IsValid());
449 UpdateStyleLengths();
451 // Clear style ranges as they might break new text graphemes and apply
452 // the first style to the whole text instead.
453 colors_
.SetValue(colors_
.breaks().begin()->second
);
454 baselines_
.SetValue(baselines_
.breaks().begin()->second
);
455 for (size_t style
= 0; style
< NUM_TEXT_STYLES
; ++style
)
456 styles_
[style
].SetValue(styles_
[style
].breaks().begin()->second
);
457 cached_bounds_and_offset_valid_
= false;
459 // Reset selection model. SetText should always followed by SetSelectionModel
460 // or SetCursorPosition in upper layer.
461 SetSelectionModel(SelectionModel());
463 // Invalidate the cached text direction if it depends on the text contents.
464 if (directionality_mode_
== DIRECTIONALITY_FROM_TEXT
)
465 text_direction_
= base::i18n::UNKNOWN_DIRECTION
;
467 obscured_reveal_index_
= -1;
468 OnTextAttributeChanged();
471 void RenderText::AppendText(const base::string16
& text
) {
473 UpdateStyleLengths();
474 cached_bounds_and_offset_valid_
= false;
475 obscured_reveal_index_
= -1;
476 OnTextAttributeChanged();
479 void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment
) {
480 if (horizontal_alignment_
!= alignment
) {
481 horizontal_alignment_
= alignment
;
482 display_offset_
= Vector2d();
483 cached_bounds_and_offset_valid_
= false;
487 void RenderText::SetFontList(const FontList
& font_list
) {
488 font_list_
= font_list
;
489 const int font_style
= font_list
.GetFontStyle();
490 SetStyle(BOLD
, (font_style
& gfx::Font::BOLD
) != 0);
491 SetStyle(ITALIC
, (font_style
& gfx::Font::ITALIC
) != 0);
492 SetStyle(UNDERLINE
, (font_style
& gfx::Font::UNDERLINE
) != 0);
493 baseline_
= kInvalidBaseline
;
494 cached_bounds_and_offset_valid_
= false;
495 OnLayoutTextAttributeChanged(false);
498 void RenderText::SetCursorEnabled(bool cursor_enabled
) {
499 cursor_enabled_
= cursor_enabled
;
500 cached_bounds_and_offset_valid_
= false;
503 void RenderText::ToggleInsertMode() {
504 insert_mode_
= !insert_mode_
;
505 cached_bounds_and_offset_valid_
= false;
508 void RenderText::SetObscured(bool obscured
) {
509 if (obscured
!= obscured_
) {
510 obscured_
= obscured
;
511 obscured_reveal_index_
= -1;
512 cached_bounds_and_offset_valid_
= false;
513 OnTextAttributeChanged();
517 void RenderText::SetObscuredRevealIndex(int index
) {
518 if (obscured_reveal_index_
== index
)
521 obscured_reveal_index_
= index
;
522 cached_bounds_and_offset_valid_
= false;
523 OnTextAttributeChanged();
526 void RenderText::SetMultiline(bool multiline
) {
527 if (multiline
!= multiline_
) {
528 multiline_
= multiline
;
529 cached_bounds_and_offset_valid_
= false;
531 OnTextAttributeChanged();
535 void RenderText::SetReplaceNewlineCharsWithSymbols(bool replace
) {
536 if (replace_newline_chars_with_symbols_
== replace
)
538 replace_newline_chars_with_symbols_
= replace
;
539 cached_bounds_and_offset_valid_
= false;
540 OnTextAttributeChanged();
543 void RenderText::SetMinLineHeight(int line_height
) {
544 if (min_line_height_
== line_height
)
546 min_line_height_
= line_height
;
547 cached_bounds_and_offset_valid_
= false;
549 OnDisplayTextAttributeChanged();
552 void RenderText::SetElideBehavior(ElideBehavior elide_behavior
) {
553 // TODO(skanuj) : Add a test for triggering layout change.
554 if (elide_behavior_
!= elide_behavior
) {
555 elide_behavior_
= elide_behavior
;
556 OnDisplayTextAttributeChanged();
560 void RenderText::SetDisplayRect(const Rect
& r
) {
561 if (r
!= display_rect_
) {
563 baseline_
= kInvalidBaseline
;
564 cached_bounds_and_offset_valid_
= false;
566 if (elide_behavior_
!= NO_ELIDE
&&
567 elide_behavior_
!= FADE_TAIL
) {
568 OnDisplayTextAttributeChanged();
573 void RenderText::SetCursorPosition(size_t position
) {
574 MoveCursorTo(position
, false);
577 void RenderText::MoveCursor(BreakType break_type
,
578 VisualCursorDirection direction
,
580 SelectionModel
cursor(cursor_position(), selection_model_
.caret_affinity());
581 // Cancelling a selection moves to the edge of the selection.
582 if (break_type
!= LINE_BREAK
&& !selection().is_empty() && !select
) {
583 SelectionModel selection_start
= GetSelectionModelForSelectionStart();
584 int start_x
= GetCursorBounds(selection_start
, true).x();
585 int cursor_x
= GetCursorBounds(cursor
, true).x();
586 // Use the selection start if it is left (when |direction| is CURSOR_LEFT)
587 // or right (when |direction| is CURSOR_RIGHT) of the selection end.
588 if (direction
== CURSOR_RIGHT
? start_x
> cursor_x
: start_x
< cursor_x
)
589 cursor
= selection_start
;
590 // Use the nearest word boundary in the proper |direction| for word breaks.
591 if (break_type
== WORD_BREAK
)
592 cursor
= GetAdjacentSelectionModel(cursor
, break_type
, direction
);
593 // Use an adjacent selection model if the cursor is not at a valid position.
594 if (!IsValidCursorIndex(cursor
.caret_pos()))
595 cursor
= GetAdjacentSelectionModel(cursor
, CHARACTER_BREAK
, direction
);
597 cursor
= GetAdjacentSelectionModel(cursor
, break_type
, direction
);
600 cursor
.set_selection_start(selection().start());
601 MoveCursorTo(cursor
);
604 bool RenderText::MoveCursorTo(const SelectionModel
& model
) {
605 // Enforce valid selection model components.
606 size_t text_length
= text().length();
607 Range
range(std::min(model
.selection().start(), text_length
),
608 std::min(model
.caret_pos(), text_length
));
609 // The current model only supports caret positions at valid cursor indices.
610 if (!IsValidCursorIndex(range
.start()) || !IsValidCursorIndex(range
.end()))
612 SelectionModel
sel(range
, model
.caret_affinity());
613 bool changed
= sel
!= selection_model_
;
614 SetSelectionModel(sel
);
618 bool RenderText::SelectRange(const Range
& range
) {
619 Range
sel(std::min(range
.start(), text().length()),
620 std::min(range
.end(), text().length()));
621 // Allow selection bounds at valid indicies amid multi-character graphemes.
622 if (!IsValidLogicalIndex(sel
.start()) || !IsValidLogicalIndex(sel
.end()))
624 LogicalCursorDirection affinity
=
625 (sel
.is_reversed() || sel
.is_empty()) ? CURSOR_FORWARD
: CURSOR_BACKWARD
;
626 SetSelectionModel(SelectionModel(sel
, affinity
));
630 bool RenderText::IsPointInSelection(const Point
& point
) {
631 if (selection().is_empty())
633 SelectionModel cursor
= FindCursorPosition(point
);
634 return RangeContainsCaret(
635 selection(), cursor
.caret_pos(), cursor
.caret_affinity());
638 void RenderText::ClearSelection() {
639 SetSelectionModel(SelectionModel(cursor_position(),
640 selection_model_
.caret_affinity()));
643 void RenderText::SelectAll(bool reversed
) {
644 const size_t length
= text().length();
645 const Range all
= reversed
? Range(length
, 0) : Range(0, length
);
646 const bool success
= SelectRange(all
);
650 void RenderText::SelectWord() {
656 size_t selection_max
= selection().GetMax();
658 base::i18n::BreakIterator
iter(text(), base::i18n::BreakIterator::BREAK_WORD
);
659 bool success
= iter
.Init();
664 size_t selection_min
= selection().GetMin();
665 if (selection_min
== text().length() && selection_min
!= 0)
668 for (; selection_min
!= 0; --selection_min
) {
669 if (iter
.IsStartOfWord(selection_min
) ||
670 iter
.IsEndOfWord(selection_min
))
674 if (selection_min
== selection_max
&& selection_max
!= text().length())
677 for (; selection_max
< text().length(); ++selection_max
)
678 if (iter
.IsEndOfWord(selection_max
) || iter
.IsStartOfWord(selection_max
))
681 const bool reversed
= selection().is_reversed();
682 MoveCursorTo(reversed
? selection_max
: selection_min
, false);
683 MoveCursorTo(reversed
? selection_min
: selection_max
, true);
686 const Range
& RenderText::GetCompositionRange() const {
687 return composition_range_
;
690 void RenderText::SetCompositionRange(const Range
& composition_range
) {
691 CHECK(!composition_range
.IsValid() ||
692 Range(0, text_
.length()).Contains(composition_range
));
693 composition_range_
.set_end(composition_range
.end());
694 composition_range_
.set_start(composition_range
.start());
695 // TODO(oshima|msw): Altering composition underlines shouldn't
696 // require layout changes. It's currently necessary because
697 // RenderTextHarfBuzz paints text decorations by run, and
698 // RenderTextMac applies all styles during layout.
699 OnLayoutTextAttributeChanged(false);
702 void RenderText::SetColor(SkColor value
) {
703 colors_
.SetValue(value
);
706 void RenderText::ApplyColor(SkColor value
, const Range
& range
) {
707 colors_
.ApplyValue(value
, range
);
710 void RenderText::SetBaselineStyle(BaselineStyle value
) {
711 baselines_
.SetValue(value
);
714 void RenderText::ApplyBaselineStyle(BaselineStyle value
, const Range
& range
) {
715 baselines_
.ApplyValue(value
, range
);
718 void RenderText::SetStyle(TextStyle style
, bool value
) {
719 styles_
[style
].SetValue(value
);
721 cached_bounds_and_offset_valid_
= false;
722 // TODO(oshima|msw): Not all style change requires layout changes.
723 // Consider optimizing based on the type of change.
724 OnLayoutTextAttributeChanged(false);
727 void RenderText::ApplyStyle(TextStyle style
, bool value
, const Range
& range
) {
728 // Do not change styles mid-grapheme to avoid breaking ligatures.
729 const size_t start
= IsValidCursorIndex(range
.start()) ? range
.start() :
730 IndexOfAdjacentGrapheme(range
.start(), CURSOR_BACKWARD
);
731 const size_t end
= IsValidCursorIndex(range
.end()) ? range
.end() :
732 IndexOfAdjacentGrapheme(range
.end(), CURSOR_FORWARD
);
733 styles_
[style
].ApplyValue(value
, Range(start
, end
));
735 cached_bounds_and_offset_valid_
= false;
736 // TODO(oshima|msw): Not all style change requires layout changes.
737 // Consider optimizing based on the type of change.
738 OnLayoutTextAttributeChanged(false);
741 bool RenderText::GetStyle(TextStyle style
) const {
742 return (styles_
[style
].breaks().size() == 1) &&
743 styles_
[style
].breaks().front().second
;
746 void RenderText::SetDirectionalityMode(DirectionalityMode mode
) {
747 if (mode
== directionality_mode_
)
750 directionality_mode_
= mode
;
751 text_direction_
= base::i18n::UNKNOWN_DIRECTION
;
752 cached_bounds_and_offset_valid_
= false;
753 OnLayoutTextAttributeChanged(false);
756 base::i18n::TextDirection
RenderText::GetDisplayTextDirection() {
757 return GetTextDirection(GetDisplayText());
760 VisualCursorDirection
RenderText::GetVisualDirectionOfLogicalEnd() {
761 return GetDisplayTextDirection() == base::i18n::LEFT_TO_RIGHT
?
762 CURSOR_RIGHT
: CURSOR_LEFT
;
765 SizeF
RenderText::GetStringSizeF() {
766 return GetStringSize();
769 float RenderText::GetContentWidthF() {
770 const float string_size
= GetStringSizeF().width();
771 // The cursor is drawn one pixel beyond the int-enclosed text bounds.
772 return cursor_enabled_
? std::ceil(string_size
) + 1 : string_size
;
775 int RenderText::GetContentWidth() {
776 return ToCeiledInt(GetContentWidthF());
779 int RenderText::GetBaseline() {
780 if (baseline_
== kInvalidBaseline
)
781 baseline_
= DetermineBaselineCenteringText(display_rect(), font_list());
782 DCHECK_NE(kInvalidBaseline
, baseline_
);
786 void RenderText::Draw(Canvas
* canvas
) {
789 if (clip_to_display_rect()) {
790 Rect
clip_rect(display_rect());
791 clip_rect
.Inset(ShadowValue::GetMargin(shadows_
));
794 canvas
->ClipRect(clip_rect
);
797 if (!text().empty() && focused())
798 DrawSelection(canvas
);
800 if (cursor_enabled() && cursor_visible() && focused())
801 DrawCursor(canvas
, selection_model_
);
804 DrawVisualText(canvas
);
806 if (clip_to_display_rect())
810 void RenderText::DrawCursor(Canvas
* canvas
, const SelectionModel
& position
) {
811 // Paint cursor. Replace cursor is drawn as rectangle for now.
812 // TODO(msw): Draw a better cursor with a better indication of association.
813 canvas
->FillRect(GetCursorBounds(position
, true), cursor_color_
);
816 bool RenderText::IsValidLogicalIndex(size_t index
) {
817 // Check that the index is at a valid code point (not mid-surrgate-pair) and
818 // that it's not truncated from the display text (its glyph may be shown).
820 // Indices within truncated text are disallowed so users can easily interact
821 // with the underlying truncated text using the ellipsis as a proxy. This lets
822 // users select all text, select the truncated text, and transition from the
823 // last rendered glyph to the end of the text without getting invisible cursor
824 // positions nor needing unbounded arrow key presses to traverse the ellipsis.
825 return index
== 0 || index
== text().length() ||
826 (index
< text().length() &&
827 (truncate_length_
== 0 || index
< truncate_length_
) &&
828 IsValidCodePointIndex(text(), index
));
831 Rect
RenderText::GetCursorBounds(const SelectionModel
& caret
,
833 // TODO(ckocagil): Support multiline. This function should return the height
834 // of the line the cursor is on. |GetStringSize()| now returns
835 // the multiline size, eliminate its use here.
838 size_t caret_pos
= caret
.caret_pos();
839 DCHECK(IsValidLogicalIndex(caret_pos
));
840 // In overtype mode, ignore the affinity and always indicate that we will
841 // overtype the next character.
842 LogicalCursorDirection caret_affinity
=
843 insert_mode
? caret
.caret_affinity() : CURSOR_FORWARD
;
844 int x
= 0, width
= 1;
845 Size size
= GetStringSize();
846 if (caret_pos
== (caret_affinity
== CURSOR_BACKWARD
? 0 : text().length())) {
847 // The caret is attached to the boundary. Always return a 1-dip width caret,
848 // since there is nothing to overtype.
849 if ((GetDisplayTextDirection() == base::i18n::RIGHT_TO_LEFT
)
850 == (caret_pos
== 0)) {
854 size_t grapheme_start
= (caret_affinity
== CURSOR_FORWARD
) ?
855 caret_pos
: IndexOfAdjacentGrapheme(caret_pos
, CURSOR_BACKWARD
);
856 Range
xspan(GetGlyphBounds(grapheme_start
));
858 x
= (caret_affinity
== CURSOR_BACKWARD
) ? xspan
.end() : xspan
.start();
859 } else { // overtype mode
861 width
= xspan
.length();
864 return Rect(ToViewPoint(Point(x
, 0)), Size(width
, size
.height()));
867 const Rect
& RenderText::GetUpdatedCursorBounds() {
868 UpdateCachedBoundsAndOffset();
869 return cursor_bounds_
;
872 size_t RenderText::IndexOfAdjacentGrapheme(size_t index
,
873 LogicalCursorDirection direction
) {
874 if (index
> text().length())
875 return text().length();
879 if (direction
== CURSOR_FORWARD
) {
880 while (index
< text().length()) {
882 if (IsValidCursorIndex(index
))
885 return text().length();
890 if (IsValidCursorIndex(index
))
896 SelectionModel
RenderText::GetSelectionModelForSelectionStart() {
897 const Range
& sel
= selection();
899 return selection_model_
;
900 return SelectionModel(sel
.start(),
901 sel
.is_reversed() ? CURSOR_BACKWARD
: CURSOR_FORWARD
);
904 const Vector2d
& RenderText::GetUpdatedDisplayOffset() {
905 UpdateCachedBoundsAndOffset();
906 return display_offset_
;
909 void RenderText::SetDisplayOffset(int horizontal_offset
) {
910 const int extra_content
= GetContentWidth() - display_rect_
.width();
911 const int cursor_width
= cursor_enabled_
? 1 : 0;
915 if (extra_content
> 0) {
916 switch (GetCurrentHorizontalAlignment()) {
918 min_offset
= -extra_content
;
921 max_offset
= extra_content
;
924 // The extra space reserved for cursor at the end of the text is ignored
925 // when centering text. So, to calculate the valid range for offset, we
926 // exclude that extra space, calculate the range, and add it back to the
927 // range (if cursor is enabled).
928 min_offset
= -(extra_content
- cursor_width
+ 1) / 2 - cursor_width
;
929 max_offset
= (extra_content
- cursor_width
) / 2;
935 if (horizontal_offset
< min_offset
)
936 horizontal_offset
= min_offset
;
937 else if (horizontal_offset
> max_offset
)
938 horizontal_offset
= max_offset
;
940 cached_bounds_and_offset_valid_
= true;
941 display_offset_
.set_x(horizontal_offset
);
942 cursor_bounds_
= GetCursorBounds(selection_model_
, insert_mode_
);
945 Vector2d
RenderText::GetLineOffset(size_t line_number
) {
946 Vector2d offset
= display_rect().OffsetFromOrigin();
947 // TODO(ckocagil): Apply the display offset for multiline scrolling.
949 offset
.Add(GetUpdatedDisplayOffset());
951 offset
.Add(Vector2d(0, lines_
[line_number
].preceding_heights
));
952 offset
.Add(GetAlignmentOffset(line_number
));
956 RenderText::RenderText()
957 : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT
: ALIGN_LEFT
),
958 directionality_mode_(DIRECTIONALITY_FROM_TEXT
),
959 text_direction_(base::i18n::UNKNOWN_DIRECTION
),
960 cursor_enabled_(true),
961 cursor_visible_(false),
963 cursor_color_(kDefaultColor
),
964 selection_color_(kDefaultColor
),
965 selection_background_focused_color_(kDefaultSelectionBackgroundColor
),
967 composition_range_(Range::InvalidRange()),
968 colors_(kDefaultColor
),
969 baselines_(NORMAL_BASELINE
),
970 styles_(NUM_TEXT_STYLES
),
971 composition_and_selection_styles_applied_(false),
973 obscured_reveal_index_(-1),
975 elide_behavior_(NO_ELIDE
),
979 replace_newline_chars_with_symbols_(true),
980 subpixel_rendering_suppressed_(false),
981 clip_to_display_rect_(true),
982 baseline_(kInvalidBaseline
),
983 cached_bounds_and_offset_valid_(false) {
986 SelectionModel
RenderText::GetAdjacentSelectionModel(
987 const SelectionModel
& current
,
988 BreakType break_type
,
989 VisualCursorDirection direction
) {
992 if (break_type
== LINE_BREAK
|| text().empty())
993 return EdgeSelectionModel(direction
);
994 if (break_type
== CHARACTER_BREAK
)
995 return AdjacentCharSelectionModel(current
, direction
);
996 DCHECK(break_type
== WORD_BREAK
);
997 return AdjacentWordSelectionModel(current
, direction
);
1000 SelectionModel
RenderText::EdgeSelectionModel(
1001 VisualCursorDirection direction
) {
1002 if (direction
== GetVisualDirectionOfLogicalEnd())
1003 return SelectionModel(text().length(), CURSOR_FORWARD
);
1004 return SelectionModel(0, CURSOR_BACKWARD
);
1007 void RenderText::SetSelectionModel(const SelectionModel
& model
) {
1008 DCHECK_LE(model
.selection().GetMax(), text().length());
1009 selection_model_
= model
;
1010 cached_bounds_and_offset_valid_
= false;
1013 void RenderText::UpdateDisplayText(float text_width
) {
1014 // TODO(oshima): Consider support eliding for multi-line text.
1015 // This requires max_line support first.
1017 elide_behavior() == NO_ELIDE
||
1018 elide_behavior() == FADE_TAIL
||
1019 text_width
< display_rect_
.width() ||
1020 layout_text_
.empty()) {
1021 text_elided_
= false;
1022 display_text_
.clear();
1026 // This doesn't trim styles so ellipsis may get rendered as a different
1027 // style than the preceding text. See crbug.com/327850.
1028 display_text_
.assign(Elide(layout_text_
,
1030 static_cast<float>(display_rect_
.width()),
1033 text_elided_
= display_text_
!= layout_text_
;
1035 display_text_
.clear();
1038 const BreakList
<size_t>& RenderText::GetLineBreaks() {
1039 if (line_breaks_
.max() != 0)
1040 return line_breaks_
;
1042 const base::string16
& layout_text
= GetDisplayText();
1043 const size_t text_length
= layout_text
.length();
1044 line_breaks_
.SetValue(0);
1045 line_breaks_
.SetMax(text_length
);
1046 base::i18n::BreakIterator
iter(layout_text
,
1047 base::i18n::BreakIterator::BREAK_LINE
);
1048 const bool success
= iter
.Init();
1052 line_breaks_
.ApplyValue(iter
.pos(), Range(iter
.pos(), text_length
));
1053 } while (iter
.Advance());
1055 return line_breaks_
;
1058 void RenderText::ApplyCompositionAndSelectionStyles() {
1059 // Save the underline and color breaks to undo the temporary styles later.
1060 DCHECK(!composition_and_selection_styles_applied_
);
1061 saved_colors_
= colors_
;
1062 saved_underlines_
= styles_
[UNDERLINE
];
1064 // Apply an underline to the composition range in |underlines|.
1065 if (composition_range_
.IsValid() && !composition_range_
.is_empty())
1066 styles_
[UNDERLINE
].ApplyValue(true, composition_range_
);
1068 // Apply the selected text color to the [un-reversed] selection range.
1069 if (!selection().is_empty() && focused()) {
1070 const Range
range(selection().GetMin(), selection().GetMax());
1071 colors_
.ApplyValue(selection_color_
, range
);
1073 composition_and_selection_styles_applied_
= true;
1076 void RenderText::UndoCompositionAndSelectionStyles() {
1077 // Restore the underline and color breaks to undo the temporary styles.
1078 DCHECK(composition_and_selection_styles_applied_
);
1079 colors_
= saved_colors_
;
1080 styles_
[UNDERLINE
] = saved_underlines_
;
1081 composition_and_selection_styles_applied_
= false;
1084 Point
RenderText::ToTextPoint(const Point
& point
) {
1085 return point
- GetLineOffset(0);
1086 // TODO(ckocagil): Convert multiline view space points to text space.
1089 Point
RenderText::ToViewPoint(const Point
& point
) {
1091 return point
+ GetLineOffset(0);
1093 // TODO(ckocagil): Traverse individual line segments for RTL support.
1094 DCHECK(!lines_
.empty());
1097 for (; line
< lines_
.size() && x
> lines_
[line
].size
.width(); ++line
)
1098 x
-= lines_
[line
].size
.width();
1099 return Point(x
, point
.y()) + GetLineOffset(line
);
1102 std::vector
<Rect
> RenderText::TextBoundsToViewBounds(const Range
& x
) {
1103 std::vector
<Rect
> rects
;
1106 rects
.push_back(Rect(ToViewPoint(Point(x
.GetMin(), 0)),
1107 Size(x
.length(), GetStringSize().height())));
1113 // Each line segment keeps its position in text coordinates. Traverse all line
1114 // segments and if the segment intersects with the given range, add the view
1115 // rect corresponding to the intersection to |rects|.
1116 for (size_t line
= 0; line
< lines_
.size(); ++line
) {
1118 const Vector2d offset
= GetLineOffset(line
);
1119 for (size_t i
= 0; i
< lines_
[line
].segments
.size(); ++i
) {
1120 const internal::LineSegment
* segment
= &lines_
[line
].segments
[i
];
1121 const Range intersection
= segment
->x_range
.Intersect(x
);
1122 if (!intersection
.is_empty()) {
1123 Rect
rect(line_x
+ intersection
.start() - segment
->x_range
.start(),
1124 0, intersection
.length(), lines_
[line
].size
.height());
1125 rects
.push_back(rect
+ offset
);
1127 line_x
+= segment
->x_range
.length();
1134 HorizontalAlignment
RenderText::GetCurrentHorizontalAlignment() {
1135 if (horizontal_alignment_
!= ALIGN_TO_HEAD
)
1136 return horizontal_alignment_
;
1137 return GetDisplayTextDirection() == base::i18n::RIGHT_TO_LEFT
?
1138 ALIGN_RIGHT
: ALIGN_LEFT
;
1141 Vector2d
RenderText::GetAlignmentOffset(size_t line_number
) {
1142 // TODO(ckocagil): Enable |lines_| usage on RenderTextMac.
1143 if (MultilineSupported() && multiline_
)
1144 DCHECK_LT(line_number
, lines_
.size());
1146 HorizontalAlignment horizontal_alignment
= GetCurrentHorizontalAlignment();
1147 if (horizontal_alignment
!= ALIGN_LEFT
) {
1148 const int width
= multiline_
?
1149 std::ceil(lines_
[line_number
].size
.width()) +
1150 (cursor_enabled_
? 1 : 0) :
1152 offset
.set_x(display_rect().width() - width
);
1153 // Put any extra margin pixel on the left to match legacy behavior.
1154 if (horizontal_alignment
== ALIGN_CENTER
)
1155 offset
.set_x((offset
.x() + 1) / 2);
1158 // Vertically center the text.
1160 const int text_height
= lines_
.back().preceding_heights
+
1161 lines_
.back().size
.height();
1162 offset
.set_y((display_rect_
.height() - text_height
) / 2);
1164 offset
.set_y(GetBaseline() - GetDisplayTextBaseline());
1170 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer
* renderer
) {
1171 const int width
= display_rect().width();
1172 if (multiline() || elide_behavior_
!= FADE_TAIL
|| GetContentWidth() <= width
)
1175 const int gradient_width
= CalculateFadeGradientWidth(font_list(), width
);
1176 if (gradient_width
== 0)
1179 HorizontalAlignment horizontal_alignment
= GetCurrentHorizontalAlignment();
1180 Rect solid_part
= display_rect();
1183 if (horizontal_alignment
!= ALIGN_LEFT
) {
1184 left_part
= solid_part
;
1185 left_part
.Inset(0, 0, solid_part
.width() - gradient_width
, 0);
1186 solid_part
.Inset(gradient_width
, 0, 0, 0);
1188 if (horizontal_alignment
!= ALIGN_RIGHT
) {
1189 right_part
= solid_part
;
1190 right_part
.Inset(solid_part
.width() - gradient_width
, 0, 0, 0);
1191 solid_part
.Inset(0, 0, gradient_width
, 0);
1194 Rect text_rect
= display_rect();
1195 text_rect
.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1197 // TODO(msw): Use the actual text colors corresponding to each faded part.
1198 skia::RefPtr
<SkShader
> shader
= CreateFadeShader(
1199 text_rect
, left_part
, right_part
, colors_
.breaks().front().second
);
1201 renderer
->SetShader(shader
.get());
1204 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer
* renderer
) {
1205 skia::RefPtr
<SkDrawLooper
> looper
= CreateShadowDrawLooper(shadows_
);
1206 renderer
->SetDrawLooper(looper
.get());
1209 base::i18n::TextDirection
RenderText::GetTextDirection(
1210 const base::string16
& text
) {
1211 if (text_direction_
== base::i18n::UNKNOWN_DIRECTION
) {
1212 switch (directionality_mode_
) {
1213 case DIRECTIONALITY_FROM_TEXT
:
1214 // Derive the direction from the display text, which differs from text()
1215 // in the case of obscured (password) textfields.
1217 base::i18n::GetFirstStrongCharacterDirection(text
);
1219 case DIRECTIONALITY_FROM_UI
:
1220 text_direction_
= base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT
:
1221 base::i18n::LEFT_TO_RIGHT
;
1223 case DIRECTIONALITY_FORCE_LTR
:
1224 text_direction_
= base::i18n::LEFT_TO_RIGHT
;
1226 case DIRECTIONALITY_FORCE_RTL
:
1227 text_direction_
= base::i18n::RIGHT_TO_LEFT
;
1234 return text_direction_
;
1237 size_t RenderText::TextIndexToGivenTextIndex(const base::string16
& given_text
,
1239 DCHECK(given_text
== layout_text() || given_text
== display_text());
1240 DCHECK_LE(index
, text().length());
1241 ptrdiff_t i
= obscured() ? UTF16IndexToOffset(text(), 0, index
) : index
;
1243 // Clamp indices to the length of the given layout or display text.
1244 return std::min
<size_t>(given_text
.length(), i
);
1247 void RenderText::UpdateStyleLengths() {
1248 const size_t text_length
= text_
.length();
1249 colors_
.SetMax(text_length
);
1250 baselines_
.SetMax(text_length
);
1251 for (size_t style
= 0; style
< NUM_TEXT_STYLES
; ++style
)
1252 styles_
[style
].SetMax(text_length
);
1256 bool RenderText::RangeContainsCaret(const Range
& range
,
1258 LogicalCursorDirection caret_affinity
) {
1259 // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1260 size_t adjacent
= (caret_affinity
== CURSOR_BACKWARD
) ?
1261 caret_pos
- 1 : caret_pos
+ 1;
1262 return range
.Contains(Range(caret_pos
, adjacent
));
1265 void RenderText::MoveCursorTo(size_t position
, bool select
) {
1266 size_t cursor
= std::min(position
, text().length());
1267 if (IsValidCursorIndex(cursor
))
1268 SetSelectionModel(SelectionModel(
1269 Range(select
? selection().start() : cursor
, cursor
),
1270 (cursor
== 0) ? CURSOR_FORWARD
: CURSOR_BACKWARD
));
1273 void RenderText::OnTextAttributeChanged() {
1274 layout_text_
.clear();
1275 display_text_
.clear();
1276 text_elided_
= false;
1277 line_breaks_
.SetMax(0);
1280 size_t obscured_text_length
=
1281 static_cast<size_t>(UTF16IndexToOffset(text_
, 0, text_
.length()));
1282 layout_text_
.assign(obscured_text_length
, kPasswordReplacementChar
);
1284 if (obscured_reveal_index_
>= 0 &&
1285 obscured_reveal_index_
< static_cast<int>(text_
.length())) {
1286 // Gets the index range in |text_| to be revealed.
1287 size_t start
= obscured_reveal_index_
;
1288 U16_SET_CP_START(text_
.data(), 0, start
);
1290 UChar32 unused_char
;
1291 U16_NEXT(text_
.data(), end
, text_
.length(), unused_char
);
1293 // Gets the index in |layout_text_| to be replaced.
1294 const size_t cp_start
=
1295 static_cast<size_t>(UTF16IndexToOffset(text_
, 0, start
));
1296 if (layout_text_
.length() > cp_start
)
1297 layout_text_
.replace(cp_start
, 1, text_
.substr(start
, end
- start
));
1300 layout_text_
= text_
;
1303 const base::string16
& text
= layout_text_
;
1304 if (truncate_length_
> 0 && truncate_length_
< text
.length()) {
1305 // Truncate the text at a valid character break and append an ellipsis.
1306 icu::StringCharacterIterator
iter(text
.c_str());
1307 // Respect ELIDE_HEAD and ELIDE_MIDDLE preferences during truncation.
1308 if (elide_behavior_
== ELIDE_HEAD
) {
1309 iter
.setIndex32(text
.length() - truncate_length_
+ 1);
1310 layout_text_
.assign(kEllipsisUTF16
+ text
.substr(iter
.getIndex()));
1311 } else if (elide_behavior_
== ELIDE_MIDDLE
) {
1312 iter
.setIndex32(truncate_length_
/ 2);
1313 const size_t ellipsis_start
= iter
.getIndex();
1314 iter
.setIndex32(text
.length() - (truncate_length_
/ 2));
1315 const size_t ellipsis_end
= iter
.getIndex();
1316 DCHECK_LE(ellipsis_start
, ellipsis_end
);
1317 layout_text_
.assign(text
.substr(0, ellipsis_start
) + kEllipsisUTF16
+
1318 text
.substr(ellipsis_end
));
1320 iter
.setIndex32(truncate_length_
- 1);
1321 layout_text_
.assign(text
.substr(0, iter
.getIndex()) + kEllipsisUTF16
);
1324 static const base::char16 kNewline
[] = { '\n', 0 };
1325 static const base::char16 kNewlineSymbol
[] = { 0x2424, 0 };
1326 if (!multiline_
&& replace_newline_chars_with_symbols_
)
1327 base::ReplaceChars(layout_text_
, kNewline
, kNewlineSymbol
, &layout_text_
);
1329 OnLayoutTextAttributeChanged(true);
1332 base::string16
RenderText::Elide(const base::string16
& text
,
1334 float available_width
,
1335 ElideBehavior behavior
) {
1336 if (available_width
<= 0 || text
.empty())
1337 return base::string16();
1338 if (behavior
== ELIDE_EMAIL
)
1339 return ElideEmail(text
, available_width
);
1340 if (text_width
> 0 && text_width
< available_width
)
1343 TRACE_EVENT0("ui", "RenderText::Elide");
1345 // Create a RenderText copy with attributes that affect the rendering width.
1346 scoped_ptr
<RenderText
> render_text
= CreateInstanceOfSameType();
1347 render_text
->SetFontList(font_list_
);
1348 render_text
->SetDirectionalityMode(directionality_mode_
);
1349 render_text
->SetCursorEnabled(cursor_enabled_
);
1350 render_text
->set_truncate_length(truncate_length_
);
1351 render_text
->styles_
= styles_
;
1352 render_text
->baselines_
= baselines_
;
1353 render_text
->colors_
= colors_
;
1354 if (text_width
== 0) {
1355 render_text
->SetText(text
);
1356 text_width
= render_text
->GetContentWidthF();
1358 if (text_width
<= available_width
)
1361 const base::string16 ellipsis
= base::string16(kEllipsisUTF16
);
1362 const bool insert_ellipsis
= (behavior
!= TRUNCATE
);
1363 const bool elide_in_middle
= (behavior
== ELIDE_MIDDLE
);
1364 const bool elide_at_beginning
= (behavior
== ELIDE_HEAD
);
1366 if (insert_ellipsis
) {
1367 render_text
->SetText(ellipsis
);
1368 const float ellipsis_width
= render_text
->GetContentWidthF();
1369 if (ellipsis_width
> available_width
)
1370 return base::string16();
1373 StringSlicer
slicer(text
, ellipsis
, elide_in_middle
, elide_at_beginning
);
1375 // Use binary search to compute the elided text.
1377 size_t hi
= text
.length() - 1;
1378 const base::i18n::TextDirection text_direction
= GetTextDirection(text
);
1379 for (size_t guess
= (lo
+ hi
) / 2; lo
<= hi
; guess
= (lo
+ hi
) / 2) {
1380 // Restore colors. They will be truncated to size by SetText.
1381 render_text
->colors_
= colors_
;
1382 base::string16 new_text
=
1383 slicer
.CutString(guess
, insert_ellipsis
&& behavior
!= ELIDE_TAIL
);
1384 render_text
->SetText(new_text
);
1386 // This has to be an additional step so that the ellipsis is rendered with
1387 // same style as trailing part of the text.
1388 if (insert_ellipsis
&& behavior
== ELIDE_TAIL
) {
1389 // When ellipsis follows text whose directionality is not the same as that
1390 // of the whole text, it will be rendered with the directionality of the
1391 // whole text. Since we want ellipsis to indicate continuation of the
1392 // preceding text, we force the directionality of ellipsis to be same as
1393 // the preceding text using LTR or RTL markers.
1394 base::i18n::TextDirection trailing_text_direction
=
1395 base::i18n::GetLastStrongCharacterDirection(new_text
);
1396 new_text
.append(ellipsis
);
1397 if (trailing_text_direction
!= text_direction
) {
1398 if (trailing_text_direction
== base::i18n::LEFT_TO_RIGHT
)
1399 new_text
+= base::i18n::kLeftToRightMark
;
1401 new_text
+= base::i18n::kRightToLeftMark
;
1403 render_text
->SetText(new_text
);
1406 // Restore styles and baselines without breaking multi-character graphemes.
1407 render_text
->styles_
= styles_
;
1408 for (size_t style
= 0; style
< NUM_TEXT_STYLES
; ++style
)
1409 RestoreBreakList(render_text
.get(), render_text
->styles_
[style
]);
1410 RestoreBreakList(render_text
.get(), render_text
->baselines_
);
1412 // We check the width of the whole desired string at once to ensure we
1413 // handle kerning/ligatures/etc. correctly.
1414 const float guess_width
= render_text
->GetContentWidthF();
1415 if (guess_width
== available_width
)
1417 if (guess_width
> available_width
) {
1419 // Move back on the loop terminating condition when the guess is too wide.
1427 return render_text
->text();
1430 base::string16
RenderText::ElideEmail(const base::string16
& email
,
1431 float available_width
) {
1432 // The returned string will have at least one character besides the ellipsis
1433 // on either side of '@'; if that's impossible, a single ellipsis is returned.
1434 // If possible, only the username is elided. Otherwise, the domain is elided
1435 // in the middle, splitting available width equally with the elided username.
1436 // If the username is short enough that it doesn't need half the available
1437 // width, the elided domain will occupy that extra width.
1439 // Split the email into its local-part (username) and domain-part. The email
1440 // spec allows for @ symbols in the username under some special requirements,
1441 // but not in the domain part, so splitting at the last @ symbol is safe.
1442 const size_t split_index
= email
.find_last_of('@');
1443 DCHECK_NE(split_index
, base::string16::npos
);
1444 base::string16 username
= email
.substr(0, split_index
);
1445 base::string16 domain
= email
.substr(split_index
+ 1);
1446 DCHECK(!username
.empty());
1447 DCHECK(!domain
.empty());
1449 // Subtract the @ symbol from the available width as it is mandatory.
1450 const base::string16 kAtSignUTF16
= base::ASCIIToUTF16("@");
1451 available_width
-= GetStringWidthF(kAtSignUTF16
, font_list());
1453 // Check whether eliding the domain is necessary: if eliding the username
1454 // is sufficient, the domain will not be elided.
1455 const float full_username_width
= GetStringWidthF(username
, font_list());
1456 const float available_domain_width
= available_width
-
1457 std::min(full_username_width
,
1458 GetStringWidthF(username
.substr(0, 1) + kEllipsisUTF16
, font_list()));
1459 if (GetStringWidthF(domain
, font_list()) > available_domain_width
) {
1460 // Elide the domain so that it only takes half of the available width.
1461 // Should the username not need all the width available in its half, the
1462 // domain will occupy the leftover width.
1463 // If |desired_domain_width| is greater than |available_domain_width|: the
1464 // minimal username elision allowed by the specifications will not fit; thus
1465 // |desired_domain_width| must be <= |available_domain_width| at all cost.
1466 const float desired_domain_width
=
1467 std::min
<float>(available_domain_width
,
1468 std::max
<float>(available_width
- full_username_width
,
1469 available_width
/ 2));
1470 domain
= Elide(domain
, 0, desired_domain_width
, ELIDE_MIDDLE
);
1471 // Failing to elide the domain such that at least one character remains
1472 // (other than the ellipsis itself) remains: return a single ellipsis.
1473 if (domain
.length() <= 1U)
1474 return base::string16(kEllipsisUTF16
);
1477 // Fit the username in the remaining width (at this point the elided username
1478 // is guaranteed to fit with at least one character remaining given all the
1479 // precautions taken earlier).
1480 available_width
-= GetStringWidthF(domain
, font_list());
1481 username
= Elide(username
, 0, available_width
, ELIDE_TAIL
);
1482 return username
+ kAtSignUTF16
+ domain
;
1485 void RenderText::UpdateCachedBoundsAndOffset() {
1486 if (cached_bounds_and_offset_valid_
)
1489 // TODO(ckocagil): Add support for scrolling multiline text.
1493 if (cursor_enabled()) {
1494 // When cursor is enabled, ensure it is visible. For this, set the valid
1495 // flag true and calculate the current cursor bounds using the stale
1496 // |display_offset_|. Then calculate the change in offset needed to move the
1497 // cursor into the visible area.
1498 cached_bounds_and_offset_valid_
= true;
1499 cursor_bounds_
= GetCursorBounds(selection_model_
, insert_mode_
);
1501 // TODO(bidi): Show RTL glyphs at the cursor position for ALIGN_LEFT, etc.
1502 if (cursor_bounds_
.right() > display_rect_
.right())
1503 delta_x
= display_rect_
.right() - cursor_bounds_
.right();
1504 else if (cursor_bounds_
.x() < display_rect_
.x())
1505 delta_x
= display_rect_
.x() - cursor_bounds_
.x();
1508 SetDisplayOffset(display_offset_
.x() + delta_x
);
1511 void RenderText::DrawSelection(Canvas
* canvas
) {
1512 for (const Rect
& s
: GetSubstringBounds(selection()))
1513 canvas
->FillRect(s
, selection_background_focused_color_
);