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/SkDrawLooper.h"
20 #include "third_party/skia/include/core/SkTypeface.h"
21 #include "third_party/skia/include/effects/SkGradientShader.h"
22 #include "ui/gfx/canvas.h"
23 #include "ui/gfx/geometry/insets.h"
24 #include "ui/gfx/geometry/safe_integer_conversions.h"
25 #include "ui/gfx/render_text_harfbuzz.h"
26 #include "ui/gfx/scoped_canvas.h"
27 #include "ui/gfx/skia_util.h"
28 #include "ui/gfx/switches.h"
29 #include "ui/gfx/text_elider.h"
30 #include "ui/gfx/text_utils.h"
31 #include "ui/gfx/utf16_indexing.h"
33 #if defined(OS_MACOSX)
34 #include "ui/gfx/render_text_mac.h"
35 #endif // defined(OS_MACOSX)
41 // All chars are replaced by this char when the password style is set.
42 // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*'
43 // that's available in the font (find_invisible_char() in gtkentry.c).
44 const base::char16 kPasswordReplacementChar
= '*';
46 // Default color used for the text and cursor.
47 const SkColor kDefaultColor
= SK_ColorBLACK
;
49 // Default color used for drawing selection background.
50 const SkColor kDefaultSelectionBackgroundColor
= SK_ColorGRAY
;
52 // Fraction of the text size to lower a strike through below the baseline.
53 const SkScalar kStrikeThroughOffset
= (-SK_Scalar1
* 6 / 21);
54 // Fraction of the text size to lower an underline below the baseline.
55 const SkScalar kUnderlineOffset
= (SK_Scalar1
/ 9);
56 // Fraction of the text size to use for a strike through or under-line.
57 const SkScalar kLineThickness
= (SK_Scalar1
/ 18);
58 // Fraction of the text size to use for a top margin of a diagonal strike.
59 const SkScalar kDiagonalStrikeMarginOffset
= (SK_Scalar1
/ 4);
61 // Invalid value of baseline. Assigning this value to |baseline_| causes
62 // re-calculation of baseline.
63 const int kInvalidBaseline
= INT_MAX
;
65 // Returns the baseline, with which the text best appears vertically centered.
66 int DetermineBaselineCenteringText(const Rect
& display_rect
,
67 const FontList
& font_list
) {
68 const int display_height
= display_rect
.height();
69 const int font_height
= font_list
.GetHeight();
70 // Lower and upper bound of baseline shift as we try to show as much area of
71 // text as possible. In particular case of |display_height| == |font_height|,
72 // we do not want to shift the baseline.
73 const int min_shift
= std::min(0, display_height
- font_height
);
74 const int max_shift
= std::abs(display_height
- font_height
);
75 const int baseline
= font_list
.GetBaseline();
76 const int cap_height
= font_list
.GetCapHeight();
77 const int internal_leading
= baseline
- cap_height
;
78 // Some platforms don't support getting the cap height, and simply return
79 // the entire font ascent from GetCapHeight(). Centering the ascent makes
80 // the font look too low, so if GetCapHeight() returns the ascent, center
81 // the entire font height instead.
83 display_height
- ((internal_leading
!= 0) ? cap_height
: font_height
);
84 const int baseline_shift
= space
/ 2 - internal_leading
;
85 return baseline
+ std::max(min_shift
, std::min(max_shift
, baseline_shift
));
88 // Converts |Font::FontStyle| flags to |SkTypeface::Style| flags.
89 SkTypeface::Style
ConvertFontStyleToSkiaTypefaceStyle(int font_style
) {
90 int skia_style
= SkTypeface::kNormal
;
91 skia_style
|= (font_style
& Font::BOLD
) ? SkTypeface::kBold
: 0;
92 skia_style
|= (font_style
& Font::ITALIC
) ? SkTypeface::kItalic
: 0;
93 return static_cast<SkTypeface::Style
>(skia_style
);
96 // Given |font| and |display_width|, returns the width of the fade gradient.
97 int CalculateFadeGradientWidth(const FontList
& font_list
, int display_width
) {
98 // Fade in/out about 2.5 characters of the beginning/end of the string.
99 // The .5 here is helpful if one of the characters is a space.
100 // Use a quarter of the display width if the display width is very short.
101 const int average_character_width
= font_list
.GetExpectedTextWidth(1);
102 const double gradient_width
= std::min(average_character_width
* 2.5,
103 display_width
/ 4.0);
104 DCHECK_GE(gradient_width
, 0.0);
105 return static_cast<int>(floor(gradient_width
+ 0.5));
108 // Appends to |positions| and |colors| values corresponding to the fade over
109 // |fade_rect| from color |c0| to color |c1|.
110 void AddFadeEffect(const Rect
& text_rect
,
111 const Rect
& fade_rect
,
114 std::vector
<SkScalar
>* positions
,
115 std::vector
<SkColor
>* colors
) {
116 const SkScalar left
= static_cast<SkScalar
>(fade_rect
.x() - text_rect
.x());
117 const SkScalar width
= static_cast<SkScalar
>(fade_rect
.width());
118 const SkScalar p0
= left
/ text_rect
.width();
119 const SkScalar p1
= (left
+ width
) / text_rect
.width();
120 // Prepend 0.0 to |positions|, as required by Skia.
121 if (positions
->empty() && p0
!= 0.0) {
122 positions
->push_back(0.0);
123 colors
->push_back(c0
);
125 positions
->push_back(p0
);
126 colors
->push_back(c0
);
127 positions
->push_back(p1
);
128 colors
->push_back(c1
);
131 // Creates a SkShader to fade the text, with |left_part| specifying the left
132 // fade effect, if any, and |right_part| specifying the right fade effect.
133 skia::RefPtr
<SkShader
> CreateFadeShader(const Rect
& text_rect
,
134 const Rect
& left_part
,
135 const Rect
& right_part
,
137 // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color.
138 const SkColor fade_color
= SkColorSetA(color
, 51);
139 std::vector
<SkScalar
> positions
;
140 std::vector
<SkColor
> colors
;
142 if (!left_part
.IsEmpty())
143 AddFadeEffect(text_rect
, left_part
, fade_color
, color
,
144 &positions
, &colors
);
145 if (!right_part
.IsEmpty())
146 AddFadeEffect(text_rect
, right_part
, color
, fade_color
,
147 &positions
, &colors
);
148 DCHECK(!positions
.empty());
150 // Terminate |positions| with 1.0, as required by Skia.
151 if (positions
.back() != 1.0) {
152 positions
.push_back(1.0);
153 colors
.push_back(colors
.back());
157 points
[0].iset(text_rect
.x(), text_rect
.y());
158 points
[1].iset(text_rect
.right(), text_rect
.y());
160 return skia::AdoptRef(
161 SkGradientShader::CreateLinear(&points
[0], &colors
[0], &positions
[0],
162 colors
.size(), SkShader::kClamp_TileMode
));
165 // Converts a FontRenderParams::Hinting value to the corresponding
166 // SkPaint::Hinting value.
167 SkPaint::Hinting
FontRenderParamsHintingToSkPaintHinting(
168 FontRenderParams::Hinting params_hinting
) {
169 switch (params_hinting
) {
170 case FontRenderParams::HINTING_NONE
: return SkPaint::kNo_Hinting
;
171 case FontRenderParams::HINTING_SLIGHT
: return SkPaint::kSlight_Hinting
;
172 case FontRenderParams::HINTING_MEDIUM
: return SkPaint::kNormal_Hinting
;
173 case FontRenderParams::HINTING_FULL
: return SkPaint::kFull_Hinting
;
175 return SkPaint::kNo_Hinting
;
178 // Make sure ranges don't break text graphemes. If a range in |break_list|
179 // does break a grapheme in |render_text|, the range will be slightly
180 // extended to encompass the grapheme.
181 template <typename T
>
182 void RestoreBreakList(RenderText
* render_text
, BreakList
<T
>* break_list
) {
183 break_list
->SetMax(render_text
->text().length());
185 while (range
.end() < break_list
->max()) {
186 const auto& current_break
= break_list
->GetBreak(range
.end());
187 range
= break_list
->GetRange(current_break
);
188 if (range
.end() < break_list
->max() &&
189 !render_text
->IsValidCursorIndex(range
.end())) {
191 render_text
->IndexOfAdjacentGrapheme(range
.end(), CURSOR_FORWARD
));
192 break_list
->ApplyValue(current_break
->second
, range
);
201 // Value of |underline_thickness_| that indicates that underline metrics have
202 // not been set explicitly.
203 const SkScalar kUnderlineMetricsNotSet
= -1.0f
;
205 SkiaTextRenderer::SkiaTextRenderer(Canvas
* canvas
)
207 canvas_skia_(canvas
->sk_canvas()),
208 underline_thickness_(kUnderlineMetricsNotSet
),
209 underline_position_(0.0f
) {
210 DCHECK(canvas_skia_
);
211 paint_
.setTextEncoding(SkPaint::kGlyphID_TextEncoding
);
212 paint_
.setStyle(SkPaint::kFill_Style
);
213 paint_
.setAntiAlias(true);
214 paint_
.setSubpixelText(true);
215 paint_
.setLCDRenderText(true);
216 paint_
.setHinting(SkPaint::kNormal_Hinting
);
219 SkiaTextRenderer::~SkiaTextRenderer() {
222 void SkiaTextRenderer::SetDrawLooper(SkDrawLooper
* draw_looper
) {
223 paint_
.setLooper(draw_looper
);
226 void SkiaTextRenderer::SetFontRenderParams(const FontRenderParams
& params
,
227 bool subpixel_rendering_suppressed
) {
228 ApplyRenderParams(params
, subpixel_rendering_suppressed
, &paint_
);
231 void SkiaTextRenderer::SetTypeface(SkTypeface
* typeface
) {
232 paint_
.setTypeface(typeface
);
235 void SkiaTextRenderer::SetTextSize(SkScalar size
) {
236 paint_
.setTextSize(size
);
239 void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string
& family
,
241 DCHECK(!family
.empty());
243 skia::RefPtr
<SkTypeface
> typeface
= CreateSkiaTypeface(family
.c_str(), style
);
245 // |paint_| adds its own ref. So don't |release()| it from the ref ptr here.
246 SetTypeface(typeface
.get());
248 // Enable fake bold text if bold style is needed but new typeface does not
250 paint_
.setFakeBoldText((style
& Font::BOLD
) && !typeface
->isBold());
254 void SkiaTextRenderer::SetForegroundColor(SkColor foreground
) {
255 paint_
.setColor(foreground
);
258 void SkiaTextRenderer::SetShader(SkShader
* shader
) {
259 paint_
.setShader(shader
);
262 void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness
,
264 underline_thickness_
= thickness
;
265 underline_position_
= position
;
268 void SkiaTextRenderer::DrawPosText(const SkPoint
* pos
,
269 const uint16
* glyphs
,
270 size_t glyph_count
) {
271 const size_t byte_length
= glyph_count
* sizeof(glyphs
[0]);
272 canvas_skia_
->drawPosText(&glyphs
[0], byte_length
, &pos
[0], paint_
);
275 void SkiaTextRenderer::DrawDecorations(int x
, int y
, int width
, bool underline
,
276 bool strike
, bool diagonal_strike
) {
278 DrawUnderline(x
, y
, width
);
280 DrawStrike(x
, y
, width
);
281 if (diagonal_strike
) {
283 diagonal_
.reset(new DiagonalStrike(canvas_
, Point(x
, y
), paint_
));
284 diagonal_
->AddPiece(width
, paint_
.getColor());
285 } else if (diagonal_
) {
290 void SkiaTextRenderer::EndDiagonalStrike() {
297 void SkiaTextRenderer::DrawUnderline(int x
, int y
, int width
) {
298 SkScalar x_scalar
= SkIntToScalar(x
);
299 SkRect r
= SkRect::MakeLTRB(
300 x_scalar
, y
+ underline_position_
, x_scalar
+ width
,
301 y
+ underline_position_
+ underline_thickness_
);
302 if (underline_thickness_
== kUnderlineMetricsNotSet
) {
303 const SkScalar text_size
= paint_
.getTextSize();
304 r
.fTop
= SkScalarMulAdd(text_size
, kUnderlineOffset
, y
);
305 r
.fBottom
= r
.fTop
+ SkScalarMul(text_size
, kLineThickness
);
307 canvas_skia_
->drawRect(r
, paint_
);
310 void SkiaTextRenderer::DrawStrike(int x
, int y
, int width
) const {
311 const SkScalar text_size
= paint_
.getTextSize();
312 const SkScalar height
= SkScalarMul(text_size
, kLineThickness
);
313 const SkScalar offset
= SkScalarMulAdd(text_size
, kStrikeThroughOffset
, y
);
314 SkScalar x_scalar
= SkIntToScalar(x
);
316 SkRect::MakeLTRB(x_scalar
, offset
, x_scalar
+ width
, offset
+ height
);
317 canvas_skia_
->drawRect(r
, paint_
);
320 SkiaTextRenderer::DiagonalStrike::DiagonalStrike(Canvas
* canvas
,
322 const SkPaint
& paint
)
329 SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() {
332 void SkiaTextRenderer::DiagonalStrike::AddPiece(int length
, SkColor color
) {
333 pieces_
.push_back(Piece(length
, color
));
334 total_length_
+= length
;
337 void SkiaTextRenderer::DiagonalStrike::Draw() {
338 const SkScalar text_size
= paint_
.getTextSize();
339 const SkScalar offset
= SkScalarMul(text_size
, kDiagonalStrikeMarginOffset
);
340 const int thickness
=
341 SkScalarCeilToInt(SkScalarMul(text_size
, kLineThickness
) * 2);
342 const int height
= SkScalarCeilToInt(text_size
- offset
);
343 const Point end
= start_
+ Vector2d(total_length_
, -height
);
344 const int clip_height
= height
+ 2 * thickness
;
346 paint_
.setAntiAlias(true);
347 paint_
.setStrokeWidth(SkIntToScalar(thickness
));
349 const bool clipped
= pieces_
.size() > 1;
350 SkCanvas
* sk_canvas
= canvas_
->sk_canvas();
353 for (size_t i
= 0; i
< pieces_
.size(); ++i
) {
354 paint_
.setColor(pieces_
[i
].second
);
358 sk_canvas
->clipRect(RectToSkRect(
359 Rect(x
, end
.y() - thickness
, pieces_
[i
].first
, clip_height
)));
362 canvas_
->DrawLine(start_
, end
, paint_
);
367 x
+= pieces_
[i
].first
;
371 StyleIterator::StyleIterator(const BreakList
<SkColor
>& colors
,
372 const BreakList
<BaselineStyle
>& baselines
,
373 const std::vector
<BreakList
<bool>>& styles
)
374 : colors_(colors
), baselines_(baselines
), styles_(styles
) {
375 color_
= colors_
.breaks().begin();
376 baseline_
= baselines_
.breaks().begin();
377 for (size_t i
= 0; i
< styles_
.size(); ++i
)
378 style_
.push_back(styles_
[i
].breaks().begin());
381 StyleIterator::~StyleIterator() {}
383 Range
StyleIterator::GetRange() const {
384 Range
range(colors_
.GetRange(color_
));
385 range
= range
.Intersect(baselines_
.GetRange(baseline_
));
386 for (size_t i
= 0; i
< NUM_TEXT_STYLES
; ++i
)
387 range
= range
.Intersect(styles_
[i
].GetRange(style_
[i
]));
391 void StyleIterator::UpdatePosition(size_t position
) {
392 color_
= colors_
.GetBreak(position
);
393 baseline_
= baselines_
.GetBreak(position
);
394 for (size_t i
= 0; i
< NUM_TEXT_STYLES
; ++i
)
395 style_
[i
] = styles_
[i
].GetBreak(position
);
398 LineSegment::LineSegment() : run(0) {}
400 LineSegment::~LineSegment() {}
402 Line::Line() : preceding_heights(0), baseline(0) {}
406 skia::RefPtr
<SkTypeface
> CreateSkiaTypeface(const std::string
& family
,
408 SkTypeface::Style skia_style
= ConvertFontStyleToSkiaTypefaceStyle(style
);
409 return skia::AdoptRef(SkTypeface::CreateFromName(family
.c_str(), skia_style
));
412 void ApplyRenderParams(const FontRenderParams
& params
,
413 bool subpixel_rendering_suppressed
,
415 paint
->setAntiAlias(params
.antialiasing
);
416 paint
->setLCDRenderText(!subpixel_rendering_suppressed
&&
417 params
.subpixel_rendering
!= FontRenderParams::SUBPIXEL_RENDERING_NONE
);
418 paint
->setSubpixelText(params
.subpixel_positioning
);
419 paint
->setAutohinted(params
.autohinter
);
420 paint
->setHinting(FontRenderParamsHintingToSkPaintHinting(params
.hinting
));
423 } // namespace internal
425 RenderText::~RenderText() {
429 RenderText
* RenderText::CreateInstance() {
430 #if defined(OS_MACOSX)
431 static const bool use_native
=
432 !base::CommandLine::ForCurrentProcess()->HasSwitch(
433 switches::kEnableHarfBuzzRenderText
);
435 return new RenderTextMac
;
436 #endif // defined(OS_MACOSX)
437 return new RenderTextHarfBuzz
;
441 RenderText
* RenderText::CreateInstanceForEditing() {
442 return new RenderTextHarfBuzz
;
445 void RenderText::SetText(const base::string16
& text
) {
446 DCHECK(!composition_range_
.IsValid());
450 UpdateStyleLengths();
452 // Clear style ranges as they might break new text graphemes and apply
453 // the first style to the whole text instead.
454 colors_
.SetValue(colors_
.breaks().begin()->second
);
455 baselines_
.SetValue(baselines_
.breaks().begin()->second
);
456 for (size_t style
= 0; style
< NUM_TEXT_STYLES
; ++style
)
457 styles_
[style
].SetValue(styles_
[style
].breaks().begin()->second
);
458 cached_bounds_and_offset_valid_
= false;
460 // Reset selection model. SetText should always followed by SetSelectionModel
461 // or SetCursorPosition in upper layer.
462 SetSelectionModel(SelectionModel());
464 // Invalidate the cached text direction if it depends on the text contents.
465 if (directionality_mode_
== DIRECTIONALITY_FROM_TEXT
)
466 text_direction_
= base::i18n::UNKNOWN_DIRECTION
;
468 obscured_reveal_index_
= -1;
469 OnTextAttributeChanged();
472 void RenderText::AppendText(const base::string16
& text
) {
474 UpdateStyleLengths();
475 cached_bounds_and_offset_valid_
= false;
476 obscured_reveal_index_
= -1;
477 OnTextAttributeChanged();
480 void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment
) {
481 if (horizontal_alignment_
!= alignment
) {
482 horizontal_alignment_
= alignment
;
483 display_offset_
= Vector2d();
484 cached_bounds_and_offset_valid_
= false;
488 void RenderText::SetFontList(const FontList
& font_list
) {
489 font_list_
= font_list
;
490 const int font_style
= font_list
.GetFontStyle();
491 SetStyle(BOLD
, (font_style
& gfx::Font::BOLD
) != 0);
492 SetStyle(ITALIC
, (font_style
& gfx::Font::ITALIC
) != 0);
493 SetStyle(UNDERLINE
, (font_style
& gfx::Font::UNDERLINE
) != 0);
494 baseline_
= kInvalidBaseline
;
495 cached_bounds_and_offset_valid_
= false;
496 OnLayoutTextAttributeChanged(false);
499 void RenderText::SetCursorEnabled(bool cursor_enabled
) {
500 cursor_enabled_
= cursor_enabled
;
501 cached_bounds_and_offset_valid_
= false;
504 void RenderText::ToggleInsertMode() {
505 insert_mode_
= !insert_mode_
;
506 cached_bounds_and_offset_valid_
= false;
509 void RenderText::SetObscured(bool obscured
) {
510 if (obscured
!= obscured_
) {
511 obscured_
= obscured
;
512 obscured_reveal_index_
= -1;
513 cached_bounds_and_offset_valid_
= false;
514 OnTextAttributeChanged();
518 void RenderText::SetObscuredRevealIndex(int index
) {
519 if (obscured_reveal_index_
== index
)
522 obscured_reveal_index_
= index
;
523 cached_bounds_and_offset_valid_
= false;
524 OnTextAttributeChanged();
527 void RenderText::SetMultiline(bool multiline
) {
528 if (multiline
!= multiline_
) {
529 multiline_
= multiline
;
530 cached_bounds_and_offset_valid_
= false;
532 OnTextAttributeChanged();
536 void RenderText::SetWordWrapBehavior(WordWrapBehavior behavior
) {
537 if (word_wrap_behavior_
== behavior
)
539 word_wrap_behavior_
= behavior
;
541 cached_bounds_and_offset_valid_
= false;
543 OnTextAttributeChanged();
547 void RenderText::SetReplaceNewlineCharsWithSymbols(bool replace
) {
548 if (replace_newline_chars_with_symbols_
== replace
)
550 replace_newline_chars_with_symbols_
= replace
;
551 cached_bounds_and_offset_valid_
= false;
552 OnTextAttributeChanged();
555 void RenderText::SetMinLineHeight(int line_height
) {
556 if (min_line_height_
== line_height
)
558 min_line_height_
= line_height
;
559 cached_bounds_and_offset_valid_
= false;
561 OnDisplayTextAttributeChanged();
564 void RenderText::SetElideBehavior(ElideBehavior elide_behavior
) {
565 // TODO(skanuj) : Add a test for triggering layout change.
566 if (elide_behavior_
!= elide_behavior
) {
567 elide_behavior_
= elide_behavior
;
568 OnDisplayTextAttributeChanged();
572 void RenderText::SetDisplayRect(const Rect
& r
) {
573 if (r
!= display_rect_
) {
575 baseline_
= kInvalidBaseline
;
576 cached_bounds_and_offset_valid_
= false;
578 if (elide_behavior_
!= NO_ELIDE
&&
579 elide_behavior_
!= FADE_TAIL
) {
580 OnDisplayTextAttributeChanged();
585 void RenderText::SetCursorPosition(size_t position
) {
586 MoveCursorTo(position
, false);
589 void RenderText::MoveCursor(BreakType break_type
,
590 VisualCursorDirection direction
,
592 SelectionModel
cursor(cursor_position(), selection_model_
.caret_affinity());
593 // Cancelling a selection moves to the edge of the selection.
594 if (break_type
!= LINE_BREAK
&& !selection().is_empty() && !select
) {
595 SelectionModel selection_start
= GetSelectionModelForSelectionStart();
596 int start_x
= GetCursorBounds(selection_start
, true).x();
597 int cursor_x
= GetCursorBounds(cursor
, true).x();
598 // Use the selection start if it is left (when |direction| is CURSOR_LEFT)
599 // or right (when |direction| is CURSOR_RIGHT) of the selection end.
600 if (direction
== CURSOR_RIGHT
? start_x
> cursor_x
: start_x
< cursor_x
)
601 cursor
= selection_start
;
602 // Use the nearest word boundary in the proper |direction| for word breaks.
603 if (break_type
== WORD_BREAK
)
604 cursor
= GetAdjacentSelectionModel(cursor
, break_type
, direction
);
605 // Use an adjacent selection model if the cursor is not at a valid position.
606 if (!IsValidCursorIndex(cursor
.caret_pos()))
607 cursor
= GetAdjacentSelectionModel(cursor
, CHARACTER_BREAK
, direction
);
609 cursor
= GetAdjacentSelectionModel(cursor
, break_type
, direction
);
612 cursor
.set_selection_start(selection().start());
613 MoveCursorTo(cursor
);
616 bool RenderText::MoveCursorTo(const SelectionModel
& model
) {
617 // Enforce valid selection model components.
618 size_t text_length
= text().length();
619 Range
range(std::min(model
.selection().start(), text_length
),
620 std::min(model
.caret_pos(), text_length
));
621 // The current model only supports caret positions at valid cursor indices.
622 if (!IsValidCursorIndex(range
.start()) || !IsValidCursorIndex(range
.end()))
624 SelectionModel
sel(range
, model
.caret_affinity());
625 bool changed
= sel
!= selection_model_
;
626 SetSelectionModel(sel
);
630 bool RenderText::SelectRange(const Range
& range
) {
631 Range
sel(std::min(range
.start(), text().length()),
632 std::min(range
.end(), text().length()));
633 // Allow selection bounds at valid indicies amid multi-character graphemes.
634 if (!IsValidLogicalIndex(sel
.start()) || !IsValidLogicalIndex(sel
.end()))
636 LogicalCursorDirection affinity
=
637 (sel
.is_reversed() || sel
.is_empty()) ? CURSOR_FORWARD
: CURSOR_BACKWARD
;
638 SetSelectionModel(SelectionModel(sel
, affinity
));
642 bool RenderText::IsPointInSelection(const Point
& point
) {
643 if (selection().is_empty())
645 SelectionModel cursor
= FindCursorPosition(point
);
646 return RangeContainsCaret(
647 selection(), cursor
.caret_pos(), cursor
.caret_affinity());
650 void RenderText::ClearSelection() {
651 SetSelectionModel(SelectionModel(cursor_position(),
652 selection_model_
.caret_affinity()));
655 void RenderText::SelectAll(bool reversed
) {
656 const size_t length
= text().length();
657 const Range all
= reversed
? Range(length
, 0) : Range(0, length
);
658 const bool success
= SelectRange(all
);
662 void RenderText::SelectWord() {
668 size_t selection_max
= selection().GetMax();
670 base::i18n::BreakIterator
iter(text(), base::i18n::BreakIterator::BREAK_WORD
);
671 bool success
= iter
.Init();
676 size_t selection_min
= selection().GetMin();
677 if (selection_min
== text().length() && selection_min
!= 0)
680 for (; selection_min
!= 0; --selection_min
) {
681 if (iter
.IsStartOfWord(selection_min
) ||
682 iter
.IsEndOfWord(selection_min
))
686 if (selection_min
== selection_max
&& selection_max
!= text().length())
689 for (; selection_max
< text().length(); ++selection_max
)
690 if (iter
.IsEndOfWord(selection_max
) || iter
.IsStartOfWord(selection_max
))
693 const bool reversed
= selection().is_reversed();
694 MoveCursorTo(reversed
? selection_max
: selection_min
, false);
695 MoveCursorTo(reversed
? selection_min
: selection_max
, true);
698 void RenderText::SetCompositionRange(const Range
& composition_range
) {
699 CHECK(!composition_range
.IsValid() ||
700 Range(0, text_
.length()).Contains(composition_range
));
701 composition_range_
.set_end(composition_range
.end());
702 composition_range_
.set_start(composition_range
.start());
703 // TODO(oshima|msw): Altering composition underlines shouldn't
704 // require layout changes. It's currently necessary because
705 // RenderTextHarfBuzz paints text decorations by run, and
706 // RenderTextMac applies all styles during layout.
707 OnLayoutTextAttributeChanged(false);
710 void RenderText::SetColor(SkColor value
) {
711 colors_
.SetValue(value
);
714 void RenderText::ApplyColor(SkColor value
, const Range
& range
) {
715 colors_
.ApplyValue(value
, range
);
718 void RenderText::SetBaselineStyle(BaselineStyle value
) {
719 baselines_
.SetValue(value
);
722 void RenderText::ApplyBaselineStyle(BaselineStyle value
, const Range
& range
) {
723 baselines_
.ApplyValue(value
, range
);
726 void RenderText::SetStyle(TextStyle style
, bool value
) {
727 styles_
[style
].SetValue(value
);
729 cached_bounds_and_offset_valid_
= false;
730 // TODO(oshima|msw): Not all style change requires layout changes.
731 // Consider optimizing based on the type of change.
732 OnLayoutTextAttributeChanged(false);
735 void RenderText::ApplyStyle(TextStyle style
, bool value
, const Range
& range
) {
736 // Do not change styles mid-grapheme to avoid breaking ligatures.
737 const size_t start
= IsValidCursorIndex(range
.start()) ? range
.start() :
738 IndexOfAdjacentGrapheme(range
.start(), CURSOR_BACKWARD
);
739 const size_t end
= IsValidCursorIndex(range
.end()) ? range
.end() :
740 IndexOfAdjacentGrapheme(range
.end(), CURSOR_FORWARD
);
741 styles_
[style
].ApplyValue(value
, Range(start
, end
));
743 cached_bounds_and_offset_valid_
= false;
744 // TODO(oshima|msw): Not all style change requires layout changes.
745 // Consider optimizing based on the type of change.
746 OnLayoutTextAttributeChanged(false);
749 bool RenderText::GetStyle(TextStyle style
) const {
750 return (styles_
[style
].breaks().size() == 1) &&
751 styles_
[style
].breaks().front().second
;
754 void RenderText::SetDirectionalityMode(DirectionalityMode mode
) {
755 if (mode
== directionality_mode_
)
758 directionality_mode_
= mode
;
759 text_direction_
= base::i18n::UNKNOWN_DIRECTION
;
760 cached_bounds_and_offset_valid_
= false;
761 OnLayoutTextAttributeChanged(false);
764 base::i18n::TextDirection
RenderText::GetDisplayTextDirection() {
765 return GetTextDirection(GetDisplayText());
768 VisualCursorDirection
RenderText::GetVisualDirectionOfLogicalEnd() {
769 return GetDisplayTextDirection() == base::i18n::LEFT_TO_RIGHT
?
770 CURSOR_RIGHT
: CURSOR_LEFT
;
773 SizeF
RenderText::GetStringSizeF() {
774 return GetStringSize();
777 float RenderText::GetContentWidthF() {
778 const float string_size
= GetStringSizeF().width();
779 // The cursor is drawn one pixel beyond the int-enclosed text bounds.
780 return cursor_enabled_
? std::ceil(string_size
) + 1 : string_size
;
783 int RenderText::GetContentWidth() {
784 return ToCeiledInt(GetContentWidthF());
787 int RenderText::GetBaseline() {
788 if (baseline_
== kInvalidBaseline
)
789 baseline_
= DetermineBaselineCenteringText(display_rect(), font_list());
790 DCHECK_NE(kInvalidBaseline
, baseline_
);
794 void RenderText::Draw(Canvas
* canvas
) {
797 if (clip_to_display_rect()) {
798 Rect
clip_rect(display_rect());
799 clip_rect
.Inset(ShadowValue::GetMargin(shadows_
));
802 canvas
->ClipRect(clip_rect
);
805 if (!text().empty() && focused())
806 DrawSelection(canvas
);
808 if (cursor_enabled() && cursor_visible() && focused())
809 DrawCursor(canvas
, selection_model_
);
812 DrawVisualText(canvas
);
814 if (clip_to_display_rect())
818 void RenderText::DrawCursor(Canvas
* canvas
, const SelectionModel
& position
) {
819 // Paint cursor. Replace cursor is drawn as rectangle for now.
820 // TODO(msw): Draw a better cursor with a better indication of association.
821 canvas
->FillRect(GetCursorBounds(position
, true), cursor_color_
);
824 bool RenderText::IsValidLogicalIndex(size_t index
) const {
825 // Check that the index is at a valid code point (not mid-surrgate-pair) and
826 // that it's not truncated from the display text (its glyph may be shown).
828 // Indices within truncated text are disallowed so users can easily interact
829 // with the underlying truncated text using the ellipsis as a proxy. This lets
830 // users select all text, select the truncated text, and transition from the
831 // last rendered glyph to the end of the text without getting invisible cursor
832 // positions nor needing unbounded arrow key presses to traverse the ellipsis.
833 return index
== 0 || index
== text().length() ||
834 (index
< text().length() &&
835 (truncate_length_
== 0 || index
< truncate_length_
) &&
836 IsValidCodePointIndex(text(), index
));
839 Rect
RenderText::GetCursorBounds(const SelectionModel
& caret
,
841 // TODO(ckocagil): Support multiline. This function should return the height
842 // of the line the cursor is on. |GetStringSize()| now returns
843 // the multiline size, eliminate its use here.
846 size_t caret_pos
= caret
.caret_pos();
847 DCHECK(IsValidLogicalIndex(caret_pos
));
848 // In overtype mode, ignore the affinity and always indicate that we will
849 // overtype the next character.
850 LogicalCursorDirection caret_affinity
=
851 insert_mode
? caret
.caret_affinity() : CURSOR_FORWARD
;
852 int x
= 0, width
= 1;
853 Size size
= GetStringSize();
854 if (caret_pos
== (caret_affinity
== CURSOR_BACKWARD
? 0 : text().length())) {
855 // The caret is attached to the boundary. Always return a 1-dip width caret,
856 // since there is nothing to overtype.
857 if ((GetDisplayTextDirection() == base::i18n::RIGHT_TO_LEFT
)
858 == (caret_pos
== 0)) {
862 size_t grapheme_start
= (caret_affinity
== CURSOR_FORWARD
) ?
863 caret_pos
: IndexOfAdjacentGrapheme(caret_pos
, CURSOR_BACKWARD
);
864 Range
xspan(GetGlyphBounds(grapheme_start
));
866 x
= (caret_affinity
== CURSOR_BACKWARD
) ? xspan
.end() : xspan
.start();
867 } else { // overtype mode
869 width
= xspan
.length();
872 return Rect(ToViewPoint(Point(x
, 0)), Size(width
, size
.height()));
875 const Rect
& RenderText::GetUpdatedCursorBounds() {
876 UpdateCachedBoundsAndOffset();
877 return cursor_bounds_
;
880 size_t RenderText::IndexOfAdjacentGrapheme(size_t index
,
881 LogicalCursorDirection direction
) {
882 if (index
> text().length())
883 return text().length();
887 if (direction
== CURSOR_FORWARD
) {
888 while (index
< text().length()) {
890 if (IsValidCursorIndex(index
))
893 return text().length();
898 if (IsValidCursorIndex(index
))
904 SelectionModel
RenderText::GetSelectionModelForSelectionStart() const {
905 const Range
& sel
= selection();
907 return selection_model_
;
908 return SelectionModel(sel
.start(),
909 sel
.is_reversed() ? CURSOR_BACKWARD
: CURSOR_FORWARD
);
912 const Vector2d
& RenderText::GetUpdatedDisplayOffset() {
913 UpdateCachedBoundsAndOffset();
914 return display_offset_
;
917 void RenderText::SetDisplayOffset(int horizontal_offset
) {
918 const int extra_content
= GetContentWidth() - display_rect_
.width();
919 const int cursor_width
= cursor_enabled_
? 1 : 0;
923 if (extra_content
> 0) {
924 switch (GetCurrentHorizontalAlignment()) {
926 min_offset
= -extra_content
;
929 max_offset
= extra_content
;
932 // The extra space reserved for cursor at the end of the text is ignored
933 // when centering text. So, to calculate the valid range for offset, we
934 // exclude that extra space, calculate the range, and add it back to the
935 // range (if cursor is enabled).
936 min_offset
= -(extra_content
- cursor_width
+ 1) / 2 - cursor_width
;
937 max_offset
= (extra_content
- cursor_width
) / 2;
943 if (horizontal_offset
< min_offset
)
944 horizontal_offset
= min_offset
;
945 else if (horizontal_offset
> max_offset
)
946 horizontal_offset
= max_offset
;
948 cached_bounds_and_offset_valid_
= true;
949 display_offset_
.set_x(horizontal_offset
);
950 cursor_bounds_
= GetCursorBounds(selection_model_
, insert_mode_
);
953 Vector2d
RenderText::GetLineOffset(size_t line_number
) {
954 Vector2d offset
= display_rect().OffsetFromOrigin();
955 // TODO(ckocagil): Apply the display offset for multiline scrolling.
957 offset
.Add(GetUpdatedDisplayOffset());
959 offset
.Add(Vector2d(0, lines_
[line_number
].preceding_heights
));
960 offset
.Add(GetAlignmentOffset(line_number
));
964 RenderText::RenderText()
965 : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT
: ALIGN_LEFT
),
966 directionality_mode_(DIRECTIONALITY_FROM_TEXT
),
967 text_direction_(base::i18n::UNKNOWN_DIRECTION
),
968 cursor_enabled_(true),
969 cursor_visible_(false),
971 cursor_color_(kDefaultColor
),
972 selection_color_(kDefaultColor
),
973 selection_background_focused_color_(kDefaultSelectionBackgroundColor
),
975 composition_range_(Range::InvalidRange()),
976 colors_(kDefaultColor
),
977 baselines_(NORMAL_BASELINE
),
978 styles_(NUM_TEXT_STYLES
),
979 composition_and_selection_styles_applied_(false),
981 obscured_reveal_index_(-1),
983 elide_behavior_(NO_ELIDE
),
987 word_wrap_behavior_(IGNORE_LONG_WORDS
),
988 replace_newline_chars_with_symbols_(true),
989 subpixel_rendering_suppressed_(false),
990 clip_to_display_rect_(true),
991 baseline_(kInvalidBaseline
),
992 cached_bounds_and_offset_valid_(false) {
995 SelectionModel
RenderText::GetAdjacentSelectionModel(
996 const SelectionModel
& current
,
997 BreakType break_type
,
998 VisualCursorDirection direction
) {
1001 if (break_type
== LINE_BREAK
|| text().empty())
1002 return EdgeSelectionModel(direction
);
1003 if (break_type
== CHARACTER_BREAK
)
1004 return AdjacentCharSelectionModel(current
, direction
);
1005 DCHECK(break_type
== WORD_BREAK
);
1006 return AdjacentWordSelectionModel(current
, direction
);
1009 SelectionModel
RenderText::EdgeSelectionModel(
1010 VisualCursorDirection direction
) {
1011 if (direction
== GetVisualDirectionOfLogicalEnd())
1012 return SelectionModel(text().length(), CURSOR_FORWARD
);
1013 return SelectionModel(0, CURSOR_BACKWARD
);
1016 void RenderText::SetSelectionModel(const SelectionModel
& model
) {
1017 DCHECK_LE(model
.selection().GetMax(), text().length());
1018 selection_model_
= model
;
1019 cached_bounds_and_offset_valid_
= false;
1022 void RenderText::UpdateDisplayText(float text_width
) {
1023 // TODO(oshima): Consider support eliding for multi-line text.
1024 // This requires max_line support first.
1026 elide_behavior() == NO_ELIDE
||
1027 elide_behavior() == FADE_TAIL
||
1028 text_width
< display_rect_
.width() ||
1029 layout_text_
.empty()) {
1030 text_elided_
= false;
1031 display_text_
.clear();
1035 // This doesn't trim styles so ellipsis may get rendered as a different
1036 // style than the preceding text. See crbug.com/327850.
1037 display_text_
.assign(Elide(layout_text_
,
1039 static_cast<float>(display_rect_
.width()),
1042 text_elided_
= display_text_
!= layout_text_
;
1044 display_text_
.clear();
1047 const BreakList
<size_t>& RenderText::GetLineBreaks() {
1048 if (line_breaks_
.max() != 0)
1049 return line_breaks_
;
1051 const base::string16
& layout_text
= GetDisplayText();
1052 const size_t text_length
= layout_text
.length();
1053 line_breaks_
.SetValue(0);
1054 line_breaks_
.SetMax(text_length
);
1055 base::i18n::BreakIterator
iter(layout_text
,
1056 base::i18n::BreakIterator::BREAK_LINE
);
1057 const bool success
= iter
.Init();
1061 line_breaks_
.ApplyValue(iter
.pos(), Range(iter
.pos(), text_length
));
1062 } while (iter
.Advance());
1064 return line_breaks_
;
1067 void RenderText::ApplyCompositionAndSelectionStyles() {
1068 // Save the underline and color breaks to undo the temporary styles later.
1069 DCHECK(!composition_and_selection_styles_applied_
);
1070 saved_colors_
= colors_
;
1071 saved_underlines_
= styles_
[UNDERLINE
];
1073 // Apply an underline to the composition range in |underlines|.
1074 if (composition_range_
.IsValid() && !composition_range_
.is_empty())
1075 styles_
[UNDERLINE
].ApplyValue(true, composition_range_
);
1077 // Apply the selected text color to the [un-reversed] selection range.
1078 if (!selection().is_empty() && focused()) {
1079 const Range
range(selection().GetMin(), selection().GetMax());
1080 colors_
.ApplyValue(selection_color_
, range
);
1082 composition_and_selection_styles_applied_
= true;
1085 void RenderText::UndoCompositionAndSelectionStyles() {
1086 // Restore the underline and color breaks to undo the temporary styles.
1087 DCHECK(composition_and_selection_styles_applied_
);
1088 colors_
= saved_colors_
;
1089 styles_
[UNDERLINE
] = saved_underlines_
;
1090 composition_and_selection_styles_applied_
= false;
1093 Point
RenderText::ToTextPoint(const Point
& point
) {
1094 return point
- GetLineOffset(0);
1095 // TODO(ckocagil): Convert multiline view space points to text space.
1098 Point
RenderText::ToViewPoint(const Point
& point
) {
1100 return point
+ GetLineOffset(0);
1102 // TODO(ckocagil): Traverse individual line segments for RTL support.
1103 DCHECK(!lines_
.empty());
1106 for (; line
< lines_
.size() && x
> lines_
[line
].size
.width(); ++line
)
1107 x
-= lines_
[line
].size
.width();
1108 return Point(x
, point
.y()) + GetLineOffset(line
);
1111 std::vector
<Rect
> RenderText::TextBoundsToViewBounds(const Range
& x
) {
1112 std::vector
<Rect
> rects
;
1115 rects
.push_back(Rect(ToViewPoint(Point(x
.GetMin(), 0)),
1116 Size(x
.length(), GetStringSize().height())));
1122 // Each line segment keeps its position in text coordinates. Traverse all line
1123 // segments and if the segment intersects with the given range, add the view
1124 // rect corresponding to the intersection to |rects|.
1125 for (size_t line
= 0; line
< lines_
.size(); ++line
) {
1127 const Vector2d offset
= GetLineOffset(line
);
1128 for (size_t i
= 0; i
< lines_
[line
].segments
.size(); ++i
) {
1129 const internal::LineSegment
* segment
= &lines_
[line
].segments
[i
];
1130 const Range intersection
= segment
->x_range
.Intersect(x
).Ceil();
1131 if (!intersection
.is_empty()) {
1132 Rect
rect(line_x
+ intersection
.start() - segment
->x_range
.start(),
1133 0, intersection
.length(), lines_
[line
].size
.height());
1134 rects
.push_back(rect
+ offset
);
1136 line_x
+= segment
->x_range
.length();
1143 HorizontalAlignment
RenderText::GetCurrentHorizontalAlignment() {
1144 if (horizontal_alignment_
!= ALIGN_TO_HEAD
)
1145 return horizontal_alignment_
;
1146 return GetDisplayTextDirection() == base::i18n::RIGHT_TO_LEFT
?
1147 ALIGN_RIGHT
: ALIGN_LEFT
;
1150 Vector2d
RenderText::GetAlignmentOffset(size_t line_number
) {
1151 // TODO(ckocagil): Enable |lines_| usage on RenderTextMac.
1152 if (MultilineSupported() && multiline_
)
1153 DCHECK_LT(line_number
, lines_
.size());
1155 HorizontalAlignment horizontal_alignment
= GetCurrentHorizontalAlignment();
1156 if (horizontal_alignment
!= ALIGN_LEFT
) {
1157 const int width
= multiline_
?
1158 std::ceil(lines_
[line_number
].size
.width()) +
1159 (cursor_enabled_
? 1 : 0) :
1161 offset
.set_x(display_rect().width() - width
);
1162 // Put any extra margin pixel on the left to match legacy behavior.
1163 if (horizontal_alignment
== ALIGN_CENTER
)
1164 offset
.set_x((offset
.x() + 1) / 2);
1167 // Vertically center the text.
1169 const int text_height
= lines_
.back().preceding_heights
+
1170 lines_
.back().size
.height();
1171 offset
.set_y((display_rect_
.height() - text_height
) / 2);
1173 offset
.set_y(GetBaseline() - GetDisplayTextBaseline());
1179 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer
* renderer
) {
1180 const int width
= display_rect().width();
1181 if (multiline() || elide_behavior_
!= FADE_TAIL
|| GetContentWidth() <= width
)
1184 const int gradient_width
= CalculateFadeGradientWidth(font_list(), width
);
1185 if (gradient_width
== 0)
1188 HorizontalAlignment horizontal_alignment
= GetCurrentHorizontalAlignment();
1189 Rect solid_part
= display_rect();
1192 if (horizontal_alignment
!= ALIGN_LEFT
) {
1193 left_part
= solid_part
;
1194 left_part
.Inset(0, 0, solid_part
.width() - gradient_width
, 0);
1195 solid_part
.Inset(gradient_width
, 0, 0, 0);
1197 if (horizontal_alignment
!= ALIGN_RIGHT
) {
1198 right_part
= solid_part
;
1199 right_part
.Inset(solid_part
.width() - gradient_width
, 0, 0, 0);
1200 solid_part
.Inset(0, 0, gradient_width
, 0);
1203 Rect text_rect
= display_rect();
1204 text_rect
.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1206 // TODO(msw): Use the actual text colors corresponding to each faded part.
1207 skia::RefPtr
<SkShader
> shader
= CreateFadeShader(
1208 text_rect
, left_part
, right_part
, colors_
.breaks().front().second
);
1210 renderer
->SetShader(shader
.get());
1213 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer
* renderer
) {
1214 skia::RefPtr
<SkDrawLooper
> looper
= CreateShadowDrawLooper(shadows_
);
1215 renderer
->SetDrawLooper(looper
.get());
1218 base::i18n::TextDirection
RenderText::GetTextDirection(
1219 const base::string16
& text
) {
1220 if (text_direction_
== base::i18n::UNKNOWN_DIRECTION
) {
1221 switch (directionality_mode_
) {
1222 case DIRECTIONALITY_FROM_TEXT
:
1223 // Derive the direction from the display text, which differs from text()
1224 // in the case of obscured (password) textfields.
1226 base::i18n::GetFirstStrongCharacterDirection(text
);
1228 case DIRECTIONALITY_FROM_UI
:
1229 text_direction_
= base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT
:
1230 base::i18n::LEFT_TO_RIGHT
;
1232 case DIRECTIONALITY_FORCE_LTR
:
1233 text_direction_
= base::i18n::LEFT_TO_RIGHT
;
1235 case DIRECTIONALITY_FORCE_RTL
:
1236 text_direction_
= base::i18n::RIGHT_TO_LEFT
;
1243 return text_direction_
;
1246 size_t RenderText::TextIndexToGivenTextIndex(const base::string16
& given_text
,
1247 size_t index
) const {
1248 DCHECK(given_text
== layout_text() || given_text
== display_text());
1249 DCHECK_LE(index
, text().length());
1250 ptrdiff_t i
= obscured() ? UTF16IndexToOffset(text(), 0, index
) : index
;
1252 // Clamp indices to the length of the given layout or display text.
1253 return std::min
<size_t>(given_text
.length(), i
);
1256 void RenderText::UpdateStyleLengths() {
1257 const size_t text_length
= text_
.length();
1258 colors_
.SetMax(text_length
);
1259 baselines_
.SetMax(text_length
);
1260 for (size_t style
= 0; style
< NUM_TEXT_STYLES
; ++style
)
1261 styles_
[style
].SetMax(text_length
);
1265 bool RenderText::RangeContainsCaret(const Range
& range
,
1267 LogicalCursorDirection caret_affinity
) {
1268 // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1269 size_t adjacent
= (caret_affinity
== CURSOR_BACKWARD
) ?
1270 caret_pos
- 1 : caret_pos
+ 1;
1271 return range
.Contains(Range(caret_pos
, adjacent
));
1274 void RenderText::MoveCursorTo(size_t position
, bool select
) {
1275 size_t cursor
= std::min(position
, text().length());
1276 if (IsValidCursorIndex(cursor
))
1277 SetSelectionModel(SelectionModel(
1278 Range(select
? selection().start() : cursor
, cursor
),
1279 (cursor
== 0) ? CURSOR_FORWARD
: CURSOR_BACKWARD
));
1282 void RenderText::OnTextAttributeChanged() {
1283 layout_text_
.clear();
1284 display_text_
.clear();
1285 text_elided_
= false;
1286 line_breaks_
.SetMax(0);
1289 size_t obscured_text_length
=
1290 static_cast<size_t>(UTF16IndexToOffset(text_
, 0, text_
.length()));
1291 layout_text_
.assign(obscured_text_length
, kPasswordReplacementChar
);
1293 if (obscured_reveal_index_
>= 0 &&
1294 obscured_reveal_index_
< static_cast<int>(text_
.length())) {
1295 // Gets the index range in |text_| to be revealed.
1296 size_t start
= obscured_reveal_index_
;
1297 U16_SET_CP_START(text_
.data(), 0, start
);
1299 UChar32 unused_char
;
1300 U16_NEXT(text_
.data(), end
, text_
.length(), unused_char
);
1302 // Gets the index in |layout_text_| to be replaced.
1303 const size_t cp_start
=
1304 static_cast<size_t>(UTF16IndexToOffset(text_
, 0, start
));
1305 if (layout_text_
.length() > cp_start
)
1306 layout_text_
.replace(cp_start
, 1, text_
.substr(start
, end
- start
));
1309 layout_text_
= text_
;
1312 const base::string16
& text
= layout_text_
;
1313 if (truncate_length_
> 0 && truncate_length_
< text
.length()) {
1314 // Truncate the text at a valid character break and append an ellipsis.
1315 icu::StringCharacterIterator
iter(text
.c_str());
1316 // Respect ELIDE_HEAD and ELIDE_MIDDLE preferences during truncation.
1317 if (elide_behavior_
== ELIDE_HEAD
) {
1318 iter
.setIndex32(text
.length() - truncate_length_
+ 1);
1319 layout_text_
.assign(kEllipsisUTF16
+ text
.substr(iter
.getIndex()));
1320 } else if (elide_behavior_
== ELIDE_MIDDLE
) {
1321 iter
.setIndex32(truncate_length_
/ 2);
1322 const size_t ellipsis_start
= iter
.getIndex();
1323 iter
.setIndex32(text
.length() - (truncate_length_
/ 2));
1324 const size_t ellipsis_end
= iter
.getIndex();
1325 DCHECK_LE(ellipsis_start
, ellipsis_end
);
1326 layout_text_
.assign(text
.substr(0, ellipsis_start
) + kEllipsisUTF16
+
1327 text
.substr(ellipsis_end
));
1329 iter
.setIndex32(truncate_length_
- 1);
1330 layout_text_
.assign(text
.substr(0, iter
.getIndex()) + kEllipsisUTF16
);
1333 static const base::char16 kNewline
[] = { '\n', 0 };
1334 static const base::char16 kNewlineSymbol
[] = { 0x2424, 0 };
1335 if (!multiline_
&& replace_newline_chars_with_symbols_
)
1336 base::ReplaceChars(layout_text_
, kNewline
, kNewlineSymbol
, &layout_text_
);
1338 OnLayoutTextAttributeChanged(true);
1341 base::string16
RenderText::Elide(const base::string16
& text
,
1343 float available_width
,
1344 ElideBehavior behavior
) {
1345 if (available_width
<= 0 || text
.empty())
1346 return base::string16();
1347 if (behavior
== ELIDE_EMAIL
)
1348 return ElideEmail(text
, available_width
);
1349 if (text_width
> 0 && text_width
< available_width
)
1352 TRACE_EVENT0("ui", "RenderText::Elide");
1354 // Create a RenderText copy with attributes that affect the rendering width.
1355 scoped_ptr
<RenderText
> render_text
= CreateInstanceOfSameType();
1356 render_text
->SetFontList(font_list_
);
1357 render_text
->SetDirectionalityMode(directionality_mode_
);
1358 render_text
->SetCursorEnabled(cursor_enabled_
);
1359 render_text
->set_truncate_length(truncate_length_
);
1360 render_text
->styles_
= styles_
;
1361 render_text
->baselines_
= baselines_
;
1362 render_text
->colors_
= colors_
;
1363 if (text_width
== 0) {
1364 render_text
->SetText(text
);
1365 text_width
= render_text
->GetContentWidthF();
1367 if (text_width
<= available_width
)
1370 const base::string16 ellipsis
= base::string16(kEllipsisUTF16
);
1371 const bool insert_ellipsis
= (behavior
!= TRUNCATE
);
1372 const bool elide_in_middle
= (behavior
== ELIDE_MIDDLE
);
1373 const bool elide_at_beginning
= (behavior
== ELIDE_HEAD
);
1375 if (insert_ellipsis
) {
1376 render_text
->SetText(ellipsis
);
1377 const float ellipsis_width
= render_text
->GetContentWidthF();
1378 if (ellipsis_width
> available_width
)
1379 return base::string16();
1382 StringSlicer
slicer(text
, ellipsis
, elide_in_middle
, elide_at_beginning
);
1384 // Use binary search to compute the elided text.
1386 size_t hi
= text
.length() - 1;
1387 const base::i18n::TextDirection text_direction
= GetTextDirection(text
);
1388 for (size_t guess
= (lo
+ hi
) / 2; lo
<= hi
; guess
= (lo
+ hi
) / 2) {
1389 // Restore colors. They will be truncated to size by SetText.
1390 render_text
->colors_
= colors_
;
1391 base::string16 new_text
=
1392 slicer
.CutString(guess
, insert_ellipsis
&& behavior
!= ELIDE_TAIL
);
1393 render_text
->SetText(new_text
);
1395 // This has to be an additional step so that the ellipsis is rendered with
1396 // same style as trailing part of the text.
1397 if (insert_ellipsis
&& behavior
== ELIDE_TAIL
) {
1398 // When ellipsis follows text whose directionality is not the same as that
1399 // of the whole text, it will be rendered with the directionality of the
1400 // whole text. Since we want ellipsis to indicate continuation of the
1401 // preceding text, we force the directionality of ellipsis to be same as
1402 // the preceding text using LTR or RTL markers.
1403 base::i18n::TextDirection trailing_text_direction
=
1404 base::i18n::GetLastStrongCharacterDirection(new_text
);
1405 new_text
.append(ellipsis
);
1406 if (trailing_text_direction
!= text_direction
) {
1407 if (trailing_text_direction
== base::i18n::LEFT_TO_RIGHT
)
1408 new_text
+= base::i18n::kLeftToRightMark
;
1410 new_text
+= base::i18n::kRightToLeftMark
;
1412 render_text
->SetText(new_text
);
1415 // Restore styles and baselines without breaking multi-character graphemes.
1416 render_text
->styles_
= styles_
;
1417 for (size_t style
= 0; style
< NUM_TEXT_STYLES
; ++style
)
1418 RestoreBreakList(render_text
.get(), &render_text
->styles_
[style
]);
1419 RestoreBreakList(render_text
.get(), &render_text
->baselines_
);
1421 // We check the width of the whole desired string at once to ensure we
1422 // handle kerning/ligatures/etc. correctly.
1423 const float guess_width
= render_text
->GetContentWidthF();
1424 if (guess_width
== available_width
)
1426 if (guess_width
> available_width
) {
1428 // Move back on the loop terminating condition when the guess is too wide.
1436 return render_text
->text();
1439 base::string16
RenderText::ElideEmail(const base::string16
& email
,
1440 float available_width
) {
1441 // The returned string will have at least one character besides the ellipsis
1442 // on either side of '@'; if that's impossible, a single ellipsis is returned.
1443 // If possible, only the username is elided. Otherwise, the domain is elided
1444 // in the middle, splitting available width equally with the elided username.
1445 // If the username is short enough that it doesn't need half the available
1446 // width, the elided domain will occupy that extra width.
1448 // Split the email into its local-part (username) and domain-part. The email
1449 // spec allows for @ symbols in the username under some special requirements,
1450 // but not in the domain part, so splitting at the last @ symbol is safe.
1451 const size_t split_index
= email
.find_last_of('@');
1452 DCHECK_NE(split_index
, base::string16::npos
);
1453 base::string16 username
= email
.substr(0, split_index
);
1454 base::string16 domain
= email
.substr(split_index
+ 1);
1455 DCHECK(!username
.empty());
1456 DCHECK(!domain
.empty());
1458 // Subtract the @ symbol from the available width as it is mandatory.
1459 const base::string16 kAtSignUTF16
= base::ASCIIToUTF16("@");
1460 available_width
-= GetStringWidthF(kAtSignUTF16
, font_list());
1462 // Check whether eliding the domain is necessary: if eliding the username
1463 // is sufficient, the domain will not be elided.
1464 const float full_username_width
= GetStringWidthF(username
, font_list());
1465 const float available_domain_width
= available_width
-
1466 std::min(full_username_width
,
1467 GetStringWidthF(username
.substr(0, 1) + kEllipsisUTF16
, font_list()));
1468 if (GetStringWidthF(domain
, font_list()) > available_domain_width
) {
1469 // Elide the domain so that it only takes half of the available width.
1470 // Should the username not need all the width available in its half, the
1471 // domain will occupy the leftover width.
1472 // If |desired_domain_width| is greater than |available_domain_width|: the
1473 // minimal username elision allowed by the specifications will not fit; thus
1474 // |desired_domain_width| must be <= |available_domain_width| at all cost.
1475 const float desired_domain_width
=
1476 std::min
<float>(available_domain_width
,
1477 std::max
<float>(available_width
- full_username_width
,
1478 available_width
/ 2));
1479 domain
= Elide(domain
, 0, desired_domain_width
, ELIDE_MIDDLE
);
1480 // Failing to elide the domain such that at least one character remains
1481 // (other than the ellipsis itself) remains: return a single ellipsis.
1482 if (domain
.length() <= 1U)
1483 return base::string16(kEllipsisUTF16
);
1486 // Fit the username in the remaining width (at this point the elided username
1487 // is guaranteed to fit with at least one character remaining given all the
1488 // precautions taken earlier).
1489 available_width
-= GetStringWidthF(domain
, font_list());
1490 username
= Elide(username
, 0, available_width
, ELIDE_TAIL
);
1491 return username
+ kAtSignUTF16
+ domain
;
1494 void RenderText::UpdateCachedBoundsAndOffset() {
1495 if (cached_bounds_and_offset_valid_
)
1498 // TODO(ckocagil): Add support for scrolling multiline text.
1502 if (cursor_enabled()) {
1503 // When cursor is enabled, ensure it is visible. For this, set the valid
1504 // flag true and calculate the current cursor bounds using the stale
1505 // |display_offset_|. Then calculate the change in offset needed to move the
1506 // cursor into the visible area.
1507 cached_bounds_and_offset_valid_
= true;
1508 cursor_bounds_
= GetCursorBounds(selection_model_
, insert_mode_
);
1510 // TODO(bidi): Show RTL glyphs at the cursor position for ALIGN_LEFT, etc.
1511 if (cursor_bounds_
.right() > display_rect_
.right())
1512 delta_x
= display_rect_
.right() - cursor_bounds_
.right();
1513 else if (cursor_bounds_
.x() < display_rect_
.x())
1514 delta_x
= display_rect_
.x() - cursor_bounds_
.x();
1517 SetDisplayOffset(display_offset_
.x() + delta_x
);
1520 void RenderText::DrawSelection(Canvas
* canvas
) {
1521 for (const Rect
& s
: GetSubstringBounds(selection()))
1522 canvas
->FillRect(s
, selection_background_focused_color_
);