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::SetWordWrapBehavior(WordWrapBehavior behavior
) {
536 if (word_wrap_behavior_
== behavior
)
538 word_wrap_behavior_
= behavior
;
540 cached_bounds_and_offset_valid_
= false;
542 OnTextAttributeChanged();
546 void RenderText::SetReplaceNewlineCharsWithSymbols(bool replace
) {
547 if (replace_newline_chars_with_symbols_
== replace
)
549 replace_newline_chars_with_symbols_
= replace
;
550 cached_bounds_and_offset_valid_
= false;
551 OnTextAttributeChanged();
554 void RenderText::SetMinLineHeight(int line_height
) {
555 if (min_line_height_
== line_height
)
557 min_line_height_
= line_height
;
558 cached_bounds_and_offset_valid_
= false;
560 OnDisplayTextAttributeChanged();
563 void RenderText::SetElideBehavior(ElideBehavior elide_behavior
) {
564 // TODO(skanuj) : Add a test for triggering layout change.
565 if (elide_behavior_
!= elide_behavior
) {
566 elide_behavior_
= elide_behavior
;
567 OnDisplayTextAttributeChanged();
571 void RenderText::SetDisplayRect(const Rect
& r
) {
572 if (r
!= display_rect_
) {
574 baseline_
= kInvalidBaseline
;
575 cached_bounds_and_offset_valid_
= false;
577 if (elide_behavior_
!= NO_ELIDE
&&
578 elide_behavior_
!= FADE_TAIL
) {
579 OnDisplayTextAttributeChanged();
584 void RenderText::SetCursorPosition(size_t position
) {
585 MoveCursorTo(position
, false);
588 void RenderText::MoveCursor(BreakType break_type
,
589 VisualCursorDirection direction
,
591 SelectionModel
cursor(cursor_position(), selection_model_
.caret_affinity());
592 // Cancelling a selection moves to the edge of the selection.
593 if (break_type
!= LINE_BREAK
&& !selection().is_empty() && !select
) {
594 SelectionModel selection_start
= GetSelectionModelForSelectionStart();
595 int start_x
= GetCursorBounds(selection_start
, true).x();
596 int cursor_x
= GetCursorBounds(cursor
, true).x();
597 // Use the selection start if it is left (when |direction| is CURSOR_LEFT)
598 // or right (when |direction| is CURSOR_RIGHT) of the selection end.
599 if (direction
== CURSOR_RIGHT
? start_x
> cursor_x
: start_x
< cursor_x
)
600 cursor
= selection_start
;
601 // Use the nearest word boundary in the proper |direction| for word breaks.
602 if (break_type
== WORD_BREAK
)
603 cursor
= GetAdjacentSelectionModel(cursor
, break_type
, direction
);
604 // Use an adjacent selection model if the cursor is not at a valid position.
605 if (!IsValidCursorIndex(cursor
.caret_pos()))
606 cursor
= GetAdjacentSelectionModel(cursor
, CHARACTER_BREAK
, direction
);
608 cursor
= GetAdjacentSelectionModel(cursor
, break_type
, direction
);
611 cursor
.set_selection_start(selection().start());
612 MoveCursorTo(cursor
);
615 bool RenderText::MoveCursorTo(const SelectionModel
& model
) {
616 // Enforce valid selection model components.
617 size_t text_length
= text().length();
618 Range
range(std::min(model
.selection().start(), text_length
),
619 std::min(model
.caret_pos(), text_length
));
620 // The current model only supports caret positions at valid cursor indices.
621 if (!IsValidCursorIndex(range
.start()) || !IsValidCursorIndex(range
.end()))
623 SelectionModel
sel(range
, model
.caret_affinity());
624 bool changed
= sel
!= selection_model_
;
625 SetSelectionModel(sel
);
629 bool RenderText::SelectRange(const Range
& range
) {
630 Range
sel(std::min(range
.start(), text().length()),
631 std::min(range
.end(), text().length()));
632 // Allow selection bounds at valid indicies amid multi-character graphemes.
633 if (!IsValidLogicalIndex(sel
.start()) || !IsValidLogicalIndex(sel
.end()))
635 LogicalCursorDirection affinity
=
636 (sel
.is_reversed() || sel
.is_empty()) ? CURSOR_FORWARD
: CURSOR_BACKWARD
;
637 SetSelectionModel(SelectionModel(sel
, affinity
));
641 bool RenderText::IsPointInSelection(const Point
& point
) {
642 if (selection().is_empty())
644 SelectionModel cursor
= FindCursorPosition(point
);
645 return RangeContainsCaret(
646 selection(), cursor
.caret_pos(), cursor
.caret_affinity());
649 void RenderText::ClearSelection() {
650 SetSelectionModel(SelectionModel(cursor_position(),
651 selection_model_
.caret_affinity()));
654 void RenderText::SelectAll(bool reversed
) {
655 const size_t length
= text().length();
656 const Range all
= reversed
? Range(length
, 0) : Range(0, length
);
657 const bool success
= SelectRange(all
);
661 void RenderText::SelectWord() {
667 size_t selection_max
= selection().GetMax();
669 base::i18n::BreakIterator
iter(text(), base::i18n::BreakIterator::BREAK_WORD
);
670 bool success
= iter
.Init();
675 size_t selection_min
= selection().GetMin();
676 if (selection_min
== text().length() && selection_min
!= 0)
679 for (; selection_min
!= 0; --selection_min
) {
680 if (iter
.IsStartOfWord(selection_min
) ||
681 iter
.IsEndOfWord(selection_min
))
685 if (selection_min
== selection_max
&& selection_max
!= text().length())
688 for (; selection_max
< text().length(); ++selection_max
)
689 if (iter
.IsEndOfWord(selection_max
) || iter
.IsStartOfWord(selection_max
))
692 const bool reversed
= selection().is_reversed();
693 MoveCursorTo(reversed
? selection_max
: selection_min
, false);
694 MoveCursorTo(reversed
? selection_min
: selection_max
, true);
697 void RenderText::SetCompositionRange(const Range
& composition_range
) {
698 CHECK(!composition_range
.IsValid() ||
699 Range(0, text_
.length()).Contains(composition_range
));
700 composition_range_
.set_end(composition_range
.end());
701 composition_range_
.set_start(composition_range
.start());
702 // TODO(oshima|msw): Altering composition underlines shouldn't
703 // require layout changes. It's currently necessary because
704 // RenderTextHarfBuzz paints text decorations by run, and
705 // RenderTextMac applies all styles during layout.
706 OnLayoutTextAttributeChanged(false);
709 void RenderText::SetColor(SkColor value
) {
710 colors_
.SetValue(value
);
713 void RenderText::ApplyColor(SkColor value
, const Range
& range
) {
714 colors_
.ApplyValue(value
, range
);
717 void RenderText::SetBaselineStyle(BaselineStyle value
) {
718 baselines_
.SetValue(value
);
721 void RenderText::ApplyBaselineStyle(BaselineStyle value
, const Range
& range
) {
722 baselines_
.ApplyValue(value
, range
);
725 void RenderText::SetStyle(TextStyle style
, bool value
) {
726 styles_
[style
].SetValue(value
);
728 cached_bounds_and_offset_valid_
= false;
729 // TODO(oshima|msw): Not all style change requires layout changes.
730 // Consider optimizing based on the type of change.
731 OnLayoutTextAttributeChanged(false);
734 void RenderText::ApplyStyle(TextStyle style
, bool value
, const Range
& range
) {
735 // Do not change styles mid-grapheme to avoid breaking ligatures.
736 const size_t start
= IsValidCursorIndex(range
.start()) ? range
.start() :
737 IndexOfAdjacentGrapheme(range
.start(), CURSOR_BACKWARD
);
738 const size_t end
= IsValidCursorIndex(range
.end()) ? range
.end() :
739 IndexOfAdjacentGrapheme(range
.end(), CURSOR_FORWARD
);
740 styles_
[style
].ApplyValue(value
, Range(start
, end
));
742 cached_bounds_and_offset_valid_
= false;
743 // TODO(oshima|msw): Not all style change requires layout changes.
744 // Consider optimizing based on the type of change.
745 OnLayoutTextAttributeChanged(false);
748 bool RenderText::GetStyle(TextStyle style
) const {
749 return (styles_
[style
].breaks().size() == 1) &&
750 styles_
[style
].breaks().front().second
;
753 void RenderText::SetDirectionalityMode(DirectionalityMode mode
) {
754 if (mode
== directionality_mode_
)
757 directionality_mode_
= mode
;
758 text_direction_
= base::i18n::UNKNOWN_DIRECTION
;
759 cached_bounds_and_offset_valid_
= false;
760 OnLayoutTextAttributeChanged(false);
763 base::i18n::TextDirection
RenderText::GetDisplayTextDirection() {
764 return GetTextDirection(GetDisplayText());
767 VisualCursorDirection
RenderText::GetVisualDirectionOfLogicalEnd() {
768 return GetDisplayTextDirection() == base::i18n::LEFT_TO_RIGHT
?
769 CURSOR_RIGHT
: CURSOR_LEFT
;
772 SizeF
RenderText::GetStringSizeF() {
773 return GetStringSize();
776 float RenderText::GetContentWidthF() {
777 const float string_size
= GetStringSizeF().width();
778 // The cursor is drawn one pixel beyond the int-enclosed text bounds.
779 return cursor_enabled_
? std::ceil(string_size
) + 1 : string_size
;
782 int RenderText::GetContentWidth() {
783 return ToCeiledInt(GetContentWidthF());
786 int RenderText::GetBaseline() {
787 if (baseline_
== kInvalidBaseline
)
788 baseline_
= DetermineBaselineCenteringText(display_rect(), font_list());
789 DCHECK_NE(kInvalidBaseline
, baseline_
);
793 void RenderText::Draw(Canvas
* canvas
) {
796 if (clip_to_display_rect()) {
797 Rect
clip_rect(display_rect());
798 clip_rect
.Inset(ShadowValue::GetMargin(shadows_
));
801 canvas
->ClipRect(clip_rect
);
804 if (!text().empty() && focused())
805 DrawSelection(canvas
);
807 if (cursor_enabled() && cursor_visible() && focused())
808 DrawCursor(canvas
, selection_model_
);
811 DrawVisualText(canvas
);
813 if (clip_to_display_rect())
817 void RenderText::DrawCursor(Canvas
* canvas
, const SelectionModel
& position
) {
818 // Paint cursor. Replace cursor is drawn as rectangle for now.
819 // TODO(msw): Draw a better cursor with a better indication of association.
820 canvas
->FillRect(GetCursorBounds(position
, true), cursor_color_
);
823 bool RenderText::IsValidLogicalIndex(size_t index
) {
824 // Check that the index is at a valid code point (not mid-surrgate-pair) and
825 // that it's not truncated from the display text (its glyph may be shown).
827 // Indices within truncated text are disallowed so users can easily interact
828 // with the underlying truncated text using the ellipsis as a proxy. This lets
829 // users select all text, select the truncated text, and transition from the
830 // last rendered glyph to the end of the text without getting invisible cursor
831 // positions nor needing unbounded arrow key presses to traverse the ellipsis.
832 return index
== 0 || index
== text().length() ||
833 (index
< text().length() &&
834 (truncate_length_
== 0 || index
< truncate_length_
) &&
835 IsValidCodePointIndex(text(), index
));
838 Rect
RenderText::GetCursorBounds(const SelectionModel
& caret
,
840 // TODO(ckocagil): Support multiline. This function should return the height
841 // of the line the cursor is on. |GetStringSize()| now returns
842 // the multiline size, eliminate its use here.
845 size_t caret_pos
= caret
.caret_pos();
846 DCHECK(IsValidLogicalIndex(caret_pos
));
847 // In overtype mode, ignore the affinity and always indicate that we will
848 // overtype the next character.
849 LogicalCursorDirection caret_affinity
=
850 insert_mode
? caret
.caret_affinity() : CURSOR_FORWARD
;
851 int x
= 0, width
= 1;
852 Size size
= GetStringSize();
853 if (caret_pos
== (caret_affinity
== CURSOR_BACKWARD
? 0 : text().length())) {
854 // The caret is attached to the boundary. Always return a 1-dip width caret,
855 // since there is nothing to overtype.
856 if ((GetDisplayTextDirection() == base::i18n::RIGHT_TO_LEFT
)
857 == (caret_pos
== 0)) {
861 size_t grapheme_start
= (caret_affinity
== CURSOR_FORWARD
) ?
862 caret_pos
: IndexOfAdjacentGrapheme(caret_pos
, CURSOR_BACKWARD
);
863 Range
xspan(GetGlyphBounds(grapheme_start
));
865 x
= (caret_affinity
== CURSOR_BACKWARD
) ? xspan
.end() : xspan
.start();
866 } else { // overtype mode
868 width
= xspan
.length();
871 return Rect(ToViewPoint(Point(x
, 0)), Size(width
, size
.height()));
874 const Rect
& RenderText::GetUpdatedCursorBounds() {
875 UpdateCachedBoundsAndOffset();
876 return cursor_bounds_
;
879 size_t RenderText::IndexOfAdjacentGrapheme(size_t index
,
880 LogicalCursorDirection direction
) {
881 if (index
> text().length())
882 return text().length();
886 if (direction
== CURSOR_FORWARD
) {
887 while (index
< text().length()) {
889 if (IsValidCursorIndex(index
))
892 return text().length();
897 if (IsValidCursorIndex(index
))
903 SelectionModel
RenderText::GetSelectionModelForSelectionStart() {
904 const Range
& sel
= selection();
906 return selection_model_
;
907 return SelectionModel(sel
.start(),
908 sel
.is_reversed() ? CURSOR_BACKWARD
: CURSOR_FORWARD
);
911 const Vector2d
& RenderText::GetUpdatedDisplayOffset() {
912 UpdateCachedBoundsAndOffset();
913 return display_offset_
;
916 void RenderText::SetDisplayOffset(int horizontal_offset
) {
917 const int extra_content
= GetContentWidth() - display_rect_
.width();
918 const int cursor_width
= cursor_enabled_
? 1 : 0;
922 if (extra_content
> 0) {
923 switch (GetCurrentHorizontalAlignment()) {
925 min_offset
= -extra_content
;
928 max_offset
= extra_content
;
931 // The extra space reserved for cursor at the end of the text is ignored
932 // when centering text. So, to calculate the valid range for offset, we
933 // exclude that extra space, calculate the range, and add it back to the
934 // range (if cursor is enabled).
935 min_offset
= -(extra_content
- cursor_width
+ 1) / 2 - cursor_width
;
936 max_offset
= (extra_content
- cursor_width
) / 2;
942 if (horizontal_offset
< min_offset
)
943 horizontal_offset
= min_offset
;
944 else if (horizontal_offset
> max_offset
)
945 horizontal_offset
= max_offset
;
947 cached_bounds_and_offset_valid_
= true;
948 display_offset_
.set_x(horizontal_offset
);
949 cursor_bounds_
= GetCursorBounds(selection_model_
, insert_mode_
);
952 Vector2d
RenderText::GetLineOffset(size_t line_number
) {
953 Vector2d offset
= display_rect().OffsetFromOrigin();
954 // TODO(ckocagil): Apply the display offset for multiline scrolling.
956 offset
.Add(GetUpdatedDisplayOffset());
958 offset
.Add(Vector2d(0, lines_
[line_number
].preceding_heights
));
959 offset
.Add(GetAlignmentOffset(line_number
));
963 RenderText::RenderText()
964 : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT
: ALIGN_LEFT
),
965 directionality_mode_(DIRECTIONALITY_FROM_TEXT
),
966 text_direction_(base::i18n::UNKNOWN_DIRECTION
),
967 cursor_enabled_(true),
968 cursor_visible_(false),
970 cursor_color_(kDefaultColor
),
971 selection_color_(kDefaultColor
),
972 selection_background_focused_color_(kDefaultSelectionBackgroundColor
),
974 composition_range_(Range::InvalidRange()),
975 colors_(kDefaultColor
),
976 baselines_(NORMAL_BASELINE
),
977 styles_(NUM_TEXT_STYLES
),
978 composition_and_selection_styles_applied_(false),
980 obscured_reveal_index_(-1),
982 elide_behavior_(NO_ELIDE
),
986 word_wrap_behavior_(IGNORE_LONG_WORDS
),
987 replace_newline_chars_with_symbols_(true),
988 subpixel_rendering_suppressed_(false),
989 clip_to_display_rect_(true),
990 baseline_(kInvalidBaseline
),
991 cached_bounds_and_offset_valid_(false) {
994 SelectionModel
RenderText::GetAdjacentSelectionModel(
995 const SelectionModel
& current
,
996 BreakType break_type
,
997 VisualCursorDirection direction
) {
1000 if (break_type
== LINE_BREAK
|| text().empty())
1001 return EdgeSelectionModel(direction
);
1002 if (break_type
== CHARACTER_BREAK
)
1003 return AdjacentCharSelectionModel(current
, direction
);
1004 DCHECK(break_type
== WORD_BREAK
);
1005 return AdjacentWordSelectionModel(current
, direction
);
1008 SelectionModel
RenderText::EdgeSelectionModel(
1009 VisualCursorDirection direction
) {
1010 if (direction
== GetVisualDirectionOfLogicalEnd())
1011 return SelectionModel(text().length(), CURSOR_FORWARD
);
1012 return SelectionModel(0, CURSOR_BACKWARD
);
1015 void RenderText::SetSelectionModel(const SelectionModel
& model
) {
1016 DCHECK_LE(model
.selection().GetMax(), text().length());
1017 selection_model_
= model
;
1018 cached_bounds_and_offset_valid_
= false;
1021 void RenderText::UpdateDisplayText(float text_width
) {
1022 // TODO(oshima): Consider support eliding for multi-line text.
1023 // This requires max_line support first.
1025 elide_behavior() == NO_ELIDE
||
1026 elide_behavior() == FADE_TAIL
||
1027 text_width
< display_rect_
.width() ||
1028 layout_text_
.empty()) {
1029 text_elided_
= false;
1030 display_text_
.clear();
1034 // This doesn't trim styles so ellipsis may get rendered as a different
1035 // style than the preceding text. See crbug.com/327850.
1036 display_text_
.assign(Elide(layout_text_
,
1038 static_cast<float>(display_rect_
.width()),
1041 text_elided_
= display_text_
!= layout_text_
;
1043 display_text_
.clear();
1046 const BreakList
<size_t>& RenderText::GetLineBreaks() {
1047 if (line_breaks_
.max() != 0)
1048 return line_breaks_
;
1050 const base::string16
& layout_text
= GetDisplayText();
1051 const size_t text_length
= layout_text
.length();
1052 line_breaks_
.SetValue(0);
1053 line_breaks_
.SetMax(text_length
);
1054 base::i18n::BreakIterator
iter(layout_text
,
1055 base::i18n::BreakIterator::BREAK_LINE
);
1056 const bool success
= iter
.Init();
1060 line_breaks_
.ApplyValue(iter
.pos(), Range(iter
.pos(), text_length
));
1061 } while (iter
.Advance());
1063 return line_breaks_
;
1066 void RenderText::ApplyCompositionAndSelectionStyles() {
1067 // Save the underline and color breaks to undo the temporary styles later.
1068 DCHECK(!composition_and_selection_styles_applied_
);
1069 saved_colors_
= colors_
;
1070 saved_underlines_
= styles_
[UNDERLINE
];
1072 // Apply an underline to the composition range in |underlines|.
1073 if (composition_range_
.IsValid() && !composition_range_
.is_empty())
1074 styles_
[UNDERLINE
].ApplyValue(true, composition_range_
);
1076 // Apply the selected text color to the [un-reversed] selection range.
1077 if (!selection().is_empty() && focused()) {
1078 const Range
range(selection().GetMin(), selection().GetMax());
1079 colors_
.ApplyValue(selection_color_
, range
);
1081 composition_and_selection_styles_applied_
= true;
1084 void RenderText::UndoCompositionAndSelectionStyles() {
1085 // Restore the underline and color breaks to undo the temporary styles.
1086 DCHECK(composition_and_selection_styles_applied_
);
1087 colors_
= saved_colors_
;
1088 styles_
[UNDERLINE
] = saved_underlines_
;
1089 composition_and_selection_styles_applied_
= false;
1092 Point
RenderText::ToTextPoint(const Point
& point
) {
1093 return point
- GetLineOffset(0);
1094 // TODO(ckocagil): Convert multiline view space points to text space.
1097 Point
RenderText::ToViewPoint(const Point
& point
) {
1099 return point
+ GetLineOffset(0);
1101 // TODO(ckocagil): Traverse individual line segments for RTL support.
1102 DCHECK(!lines_
.empty());
1105 for (; line
< lines_
.size() && x
> lines_
[line
].size
.width(); ++line
)
1106 x
-= lines_
[line
].size
.width();
1107 return Point(x
, point
.y()) + GetLineOffset(line
);
1110 std::vector
<Rect
> RenderText::TextBoundsToViewBounds(const Range
& x
) {
1111 std::vector
<Rect
> rects
;
1114 rects
.push_back(Rect(ToViewPoint(Point(x
.GetMin(), 0)),
1115 Size(x
.length(), GetStringSize().height())));
1121 // Each line segment keeps its position in text coordinates. Traverse all line
1122 // segments and if the segment intersects with the given range, add the view
1123 // rect corresponding to the intersection to |rects|.
1124 for (size_t line
= 0; line
< lines_
.size(); ++line
) {
1126 const Vector2d offset
= GetLineOffset(line
);
1127 for (size_t i
= 0; i
< lines_
[line
].segments
.size(); ++i
) {
1128 const internal::LineSegment
* segment
= &lines_
[line
].segments
[i
];
1129 const Range intersection
= segment
->x_range
.Intersect(x
);
1130 if (!intersection
.is_empty()) {
1131 Rect
rect(line_x
+ intersection
.start() - segment
->x_range
.start(),
1132 0, intersection
.length(), lines_
[line
].size
.height());
1133 rects
.push_back(rect
+ offset
);
1135 line_x
+= segment
->x_range
.length();
1142 HorizontalAlignment
RenderText::GetCurrentHorizontalAlignment() {
1143 if (horizontal_alignment_
!= ALIGN_TO_HEAD
)
1144 return horizontal_alignment_
;
1145 return GetDisplayTextDirection() == base::i18n::RIGHT_TO_LEFT
?
1146 ALIGN_RIGHT
: ALIGN_LEFT
;
1149 Vector2d
RenderText::GetAlignmentOffset(size_t line_number
) {
1150 // TODO(ckocagil): Enable |lines_| usage on RenderTextMac.
1151 if (MultilineSupported() && multiline_
)
1152 DCHECK_LT(line_number
, lines_
.size());
1154 HorizontalAlignment horizontal_alignment
= GetCurrentHorizontalAlignment();
1155 if (horizontal_alignment
!= ALIGN_LEFT
) {
1156 const int width
= multiline_
?
1157 std::ceil(lines_
[line_number
].size
.width()) +
1158 (cursor_enabled_
? 1 : 0) :
1160 offset
.set_x(display_rect().width() - width
);
1161 // Put any extra margin pixel on the left to match legacy behavior.
1162 if (horizontal_alignment
== ALIGN_CENTER
)
1163 offset
.set_x((offset
.x() + 1) / 2);
1166 // Vertically center the text.
1168 const int text_height
= lines_
.back().preceding_heights
+
1169 lines_
.back().size
.height();
1170 offset
.set_y((display_rect_
.height() - text_height
) / 2);
1172 offset
.set_y(GetBaseline() - GetDisplayTextBaseline());
1178 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer
* renderer
) {
1179 const int width
= display_rect().width();
1180 if (multiline() || elide_behavior_
!= FADE_TAIL
|| GetContentWidth() <= width
)
1183 const int gradient_width
= CalculateFadeGradientWidth(font_list(), width
);
1184 if (gradient_width
== 0)
1187 HorizontalAlignment horizontal_alignment
= GetCurrentHorizontalAlignment();
1188 Rect solid_part
= display_rect();
1191 if (horizontal_alignment
!= ALIGN_LEFT
) {
1192 left_part
= solid_part
;
1193 left_part
.Inset(0, 0, solid_part
.width() - gradient_width
, 0);
1194 solid_part
.Inset(gradient_width
, 0, 0, 0);
1196 if (horizontal_alignment
!= ALIGN_RIGHT
) {
1197 right_part
= solid_part
;
1198 right_part
.Inset(solid_part
.width() - gradient_width
, 0, 0, 0);
1199 solid_part
.Inset(0, 0, gradient_width
, 0);
1202 Rect text_rect
= display_rect();
1203 text_rect
.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1205 // TODO(msw): Use the actual text colors corresponding to each faded part.
1206 skia::RefPtr
<SkShader
> shader
= CreateFadeShader(
1207 text_rect
, left_part
, right_part
, colors_
.breaks().front().second
);
1209 renderer
->SetShader(shader
.get());
1212 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer
* renderer
) {
1213 skia::RefPtr
<SkDrawLooper
> looper
= CreateShadowDrawLooper(shadows_
);
1214 renderer
->SetDrawLooper(looper
.get());
1217 base::i18n::TextDirection
RenderText::GetTextDirection(
1218 const base::string16
& text
) {
1219 if (text_direction_
== base::i18n::UNKNOWN_DIRECTION
) {
1220 switch (directionality_mode_
) {
1221 case DIRECTIONALITY_FROM_TEXT
:
1222 // Derive the direction from the display text, which differs from text()
1223 // in the case of obscured (password) textfields.
1225 base::i18n::GetFirstStrongCharacterDirection(text
);
1227 case DIRECTIONALITY_FROM_UI
:
1228 text_direction_
= base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT
:
1229 base::i18n::LEFT_TO_RIGHT
;
1231 case DIRECTIONALITY_FORCE_LTR
:
1232 text_direction_
= base::i18n::LEFT_TO_RIGHT
;
1234 case DIRECTIONALITY_FORCE_RTL
:
1235 text_direction_
= base::i18n::RIGHT_TO_LEFT
;
1242 return text_direction_
;
1245 size_t RenderText::TextIndexToGivenTextIndex(const base::string16
& given_text
,
1247 DCHECK(given_text
== layout_text() || given_text
== display_text());
1248 DCHECK_LE(index
, text().length());
1249 ptrdiff_t i
= obscured() ? UTF16IndexToOffset(text(), 0, index
) : index
;
1251 // Clamp indices to the length of the given layout or display text.
1252 return std::min
<size_t>(given_text
.length(), i
);
1255 void RenderText::UpdateStyleLengths() {
1256 const size_t text_length
= text_
.length();
1257 colors_
.SetMax(text_length
);
1258 baselines_
.SetMax(text_length
);
1259 for (size_t style
= 0; style
< NUM_TEXT_STYLES
; ++style
)
1260 styles_
[style
].SetMax(text_length
);
1264 bool RenderText::RangeContainsCaret(const Range
& range
,
1266 LogicalCursorDirection caret_affinity
) {
1267 // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1268 size_t adjacent
= (caret_affinity
== CURSOR_BACKWARD
) ?
1269 caret_pos
- 1 : caret_pos
+ 1;
1270 return range
.Contains(Range(caret_pos
, adjacent
));
1273 void RenderText::MoveCursorTo(size_t position
, bool select
) {
1274 size_t cursor
= std::min(position
, text().length());
1275 if (IsValidCursorIndex(cursor
))
1276 SetSelectionModel(SelectionModel(
1277 Range(select
? selection().start() : cursor
, cursor
),
1278 (cursor
== 0) ? CURSOR_FORWARD
: CURSOR_BACKWARD
));
1281 void RenderText::OnTextAttributeChanged() {
1282 layout_text_
.clear();
1283 display_text_
.clear();
1284 text_elided_
= false;
1285 line_breaks_
.SetMax(0);
1288 size_t obscured_text_length
=
1289 static_cast<size_t>(UTF16IndexToOffset(text_
, 0, text_
.length()));
1290 layout_text_
.assign(obscured_text_length
, kPasswordReplacementChar
);
1292 if (obscured_reveal_index_
>= 0 &&
1293 obscured_reveal_index_
< static_cast<int>(text_
.length())) {
1294 // Gets the index range in |text_| to be revealed.
1295 size_t start
= obscured_reveal_index_
;
1296 U16_SET_CP_START(text_
.data(), 0, start
);
1298 UChar32 unused_char
;
1299 U16_NEXT(text_
.data(), end
, text_
.length(), unused_char
);
1301 // Gets the index in |layout_text_| to be replaced.
1302 const size_t cp_start
=
1303 static_cast<size_t>(UTF16IndexToOffset(text_
, 0, start
));
1304 if (layout_text_
.length() > cp_start
)
1305 layout_text_
.replace(cp_start
, 1, text_
.substr(start
, end
- start
));
1308 layout_text_
= text_
;
1311 const base::string16
& text
= layout_text_
;
1312 if (truncate_length_
> 0 && truncate_length_
< text
.length()) {
1313 // Truncate the text at a valid character break and append an ellipsis.
1314 icu::StringCharacterIterator
iter(text
.c_str());
1315 // Respect ELIDE_HEAD and ELIDE_MIDDLE preferences during truncation.
1316 if (elide_behavior_
== ELIDE_HEAD
) {
1317 iter
.setIndex32(text
.length() - truncate_length_
+ 1);
1318 layout_text_
.assign(kEllipsisUTF16
+ text
.substr(iter
.getIndex()));
1319 } else if (elide_behavior_
== ELIDE_MIDDLE
) {
1320 iter
.setIndex32(truncate_length_
/ 2);
1321 const size_t ellipsis_start
= iter
.getIndex();
1322 iter
.setIndex32(text
.length() - (truncate_length_
/ 2));
1323 const size_t ellipsis_end
= iter
.getIndex();
1324 DCHECK_LE(ellipsis_start
, ellipsis_end
);
1325 layout_text_
.assign(text
.substr(0, ellipsis_start
) + kEllipsisUTF16
+
1326 text
.substr(ellipsis_end
));
1328 iter
.setIndex32(truncate_length_
- 1);
1329 layout_text_
.assign(text
.substr(0, iter
.getIndex()) + kEllipsisUTF16
);
1332 static const base::char16 kNewline
[] = { '\n', 0 };
1333 static const base::char16 kNewlineSymbol
[] = { 0x2424, 0 };
1334 if (!multiline_
&& replace_newline_chars_with_symbols_
)
1335 base::ReplaceChars(layout_text_
, kNewline
, kNewlineSymbol
, &layout_text_
);
1337 OnLayoutTextAttributeChanged(true);
1340 base::string16
RenderText::Elide(const base::string16
& text
,
1342 float available_width
,
1343 ElideBehavior behavior
) {
1344 if (available_width
<= 0 || text
.empty())
1345 return base::string16();
1346 if (behavior
== ELIDE_EMAIL
)
1347 return ElideEmail(text
, available_width
);
1348 if (text_width
> 0 && text_width
< available_width
)
1351 TRACE_EVENT0("ui", "RenderText::Elide");
1353 // Create a RenderText copy with attributes that affect the rendering width.
1354 scoped_ptr
<RenderText
> render_text
= CreateInstanceOfSameType();
1355 render_text
->SetFontList(font_list_
);
1356 render_text
->SetDirectionalityMode(directionality_mode_
);
1357 render_text
->SetCursorEnabled(cursor_enabled_
);
1358 render_text
->set_truncate_length(truncate_length_
);
1359 render_text
->styles_
= styles_
;
1360 render_text
->baselines_
= baselines_
;
1361 render_text
->colors_
= colors_
;
1362 if (text_width
== 0) {
1363 render_text
->SetText(text
);
1364 text_width
= render_text
->GetContentWidthF();
1366 if (text_width
<= available_width
)
1369 const base::string16 ellipsis
= base::string16(kEllipsisUTF16
);
1370 const bool insert_ellipsis
= (behavior
!= TRUNCATE
);
1371 const bool elide_in_middle
= (behavior
== ELIDE_MIDDLE
);
1372 const bool elide_at_beginning
= (behavior
== ELIDE_HEAD
);
1374 if (insert_ellipsis
) {
1375 render_text
->SetText(ellipsis
);
1376 const float ellipsis_width
= render_text
->GetContentWidthF();
1377 if (ellipsis_width
> available_width
)
1378 return base::string16();
1381 StringSlicer
slicer(text
, ellipsis
, elide_in_middle
, elide_at_beginning
);
1383 // Use binary search to compute the elided text.
1385 size_t hi
= text
.length() - 1;
1386 const base::i18n::TextDirection text_direction
= GetTextDirection(text
);
1387 for (size_t guess
= (lo
+ hi
) / 2; lo
<= hi
; guess
= (lo
+ hi
) / 2) {
1388 // Restore colors. They will be truncated to size by SetText.
1389 render_text
->colors_
= colors_
;
1390 base::string16 new_text
=
1391 slicer
.CutString(guess
, insert_ellipsis
&& behavior
!= ELIDE_TAIL
);
1392 render_text
->SetText(new_text
);
1394 // This has to be an additional step so that the ellipsis is rendered with
1395 // same style as trailing part of the text.
1396 if (insert_ellipsis
&& behavior
== ELIDE_TAIL
) {
1397 // When ellipsis follows text whose directionality is not the same as that
1398 // of the whole text, it will be rendered with the directionality of the
1399 // whole text. Since we want ellipsis to indicate continuation of the
1400 // preceding text, we force the directionality of ellipsis to be same as
1401 // the preceding text using LTR or RTL markers.
1402 base::i18n::TextDirection trailing_text_direction
=
1403 base::i18n::GetLastStrongCharacterDirection(new_text
);
1404 new_text
.append(ellipsis
);
1405 if (trailing_text_direction
!= text_direction
) {
1406 if (trailing_text_direction
== base::i18n::LEFT_TO_RIGHT
)
1407 new_text
+= base::i18n::kLeftToRightMark
;
1409 new_text
+= base::i18n::kRightToLeftMark
;
1411 render_text
->SetText(new_text
);
1414 // Restore styles and baselines without breaking multi-character graphemes.
1415 render_text
->styles_
= styles_
;
1416 for (size_t style
= 0; style
< NUM_TEXT_STYLES
; ++style
)
1417 RestoreBreakList(render_text
.get(), render_text
->styles_
[style
]);
1418 RestoreBreakList(render_text
.get(), render_text
->baselines_
);
1420 // We check the width of the whole desired string at once to ensure we
1421 // handle kerning/ligatures/etc. correctly.
1422 const float guess_width
= render_text
->GetContentWidthF();
1423 if (guess_width
== available_width
)
1425 if (guess_width
> available_width
) {
1427 // Move back on the loop terminating condition when the guess is too wide.
1435 return render_text
->text();
1438 base::string16
RenderText::ElideEmail(const base::string16
& email
,
1439 float available_width
) {
1440 // The returned string will have at least one character besides the ellipsis
1441 // on either side of '@'; if that's impossible, a single ellipsis is returned.
1442 // If possible, only the username is elided. Otherwise, the domain is elided
1443 // in the middle, splitting available width equally with the elided username.
1444 // If the username is short enough that it doesn't need half the available
1445 // width, the elided domain will occupy that extra width.
1447 // Split the email into its local-part (username) and domain-part. The email
1448 // spec allows for @ symbols in the username under some special requirements,
1449 // but not in the domain part, so splitting at the last @ symbol is safe.
1450 const size_t split_index
= email
.find_last_of('@');
1451 DCHECK_NE(split_index
, base::string16::npos
);
1452 base::string16 username
= email
.substr(0, split_index
);
1453 base::string16 domain
= email
.substr(split_index
+ 1);
1454 DCHECK(!username
.empty());
1455 DCHECK(!domain
.empty());
1457 // Subtract the @ symbol from the available width as it is mandatory.
1458 const base::string16 kAtSignUTF16
= base::ASCIIToUTF16("@");
1459 available_width
-= GetStringWidthF(kAtSignUTF16
, font_list());
1461 // Check whether eliding the domain is necessary: if eliding the username
1462 // is sufficient, the domain will not be elided.
1463 const float full_username_width
= GetStringWidthF(username
, font_list());
1464 const float available_domain_width
= available_width
-
1465 std::min(full_username_width
,
1466 GetStringWidthF(username
.substr(0, 1) + kEllipsisUTF16
, font_list()));
1467 if (GetStringWidthF(domain
, font_list()) > available_domain_width
) {
1468 // Elide the domain so that it only takes half of the available width.
1469 // Should the username not need all the width available in its half, the
1470 // domain will occupy the leftover width.
1471 // If |desired_domain_width| is greater than |available_domain_width|: the
1472 // minimal username elision allowed by the specifications will not fit; thus
1473 // |desired_domain_width| must be <= |available_domain_width| at all cost.
1474 const float desired_domain_width
=
1475 std::min
<float>(available_domain_width
,
1476 std::max
<float>(available_width
- full_username_width
,
1477 available_width
/ 2));
1478 domain
= Elide(domain
, 0, desired_domain_width
, ELIDE_MIDDLE
);
1479 // Failing to elide the domain such that at least one character remains
1480 // (other than the ellipsis itself) remains: return a single ellipsis.
1481 if (domain
.length() <= 1U)
1482 return base::string16(kEllipsisUTF16
);
1485 // Fit the username in the remaining width (at this point the elided username
1486 // is guaranteed to fit with at least one character remaining given all the
1487 // precautions taken earlier).
1488 available_width
-= GetStringWidthF(domain
, font_list());
1489 username
= Elide(username
, 0, available_width
, ELIDE_TAIL
);
1490 return username
+ kAtSignUTF16
+ domain
;
1493 void RenderText::UpdateCachedBoundsAndOffset() {
1494 if (cached_bounds_and_offset_valid_
)
1497 // TODO(ckocagil): Add support for scrolling multiline text.
1501 if (cursor_enabled()) {
1502 // When cursor is enabled, ensure it is visible. For this, set the valid
1503 // flag true and calculate the current cursor bounds using the stale
1504 // |display_offset_|. Then calculate the change in offset needed to move the
1505 // cursor into the visible area.
1506 cached_bounds_and_offset_valid_
= true;
1507 cursor_bounds_
= GetCursorBounds(selection_model_
, insert_mode_
);
1509 // TODO(bidi): Show RTL glyphs at the cursor position for ALIGN_LEFT, etc.
1510 if (cursor_bounds_
.right() > display_rect_
.right())
1511 delta_x
= display_rect_
.right() - cursor_bounds_
.right();
1512 else if (cursor_bounds_
.x() < display_rect_
.x())
1513 delta_x
= display_rect_
.x() - cursor_bounds_
.x();
1516 SetDisplayOffset(display_offset_
.x() + delta_x
);
1519 void RenderText::DrawSelection(Canvas
* canvas
) {
1520 for (const Rect
& s
: GetSubstringBounds(selection()))
1521 canvas
->FillRect(s
, selection_background_focused_color_
);