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 "third_party/icu/source/common/unicode/rbbi.h"
17 #include "third_party/icu/source/common/unicode/utf16.h"
18 #include "third_party/skia/include/core/SkTypeface.h"
19 #include "third_party/skia/include/effects/SkGradientShader.h"
20 #include "ui/gfx/canvas.h"
21 #include "ui/gfx/geometry/insets.h"
22 #include "ui/gfx/geometry/safe_integer_conversions.h"
23 #include "ui/gfx/render_text_harfbuzz.h"
24 #include "ui/gfx/scoped_canvas.h"
25 #include "ui/gfx/skia_util.h"
26 #include "ui/gfx/switches.h"
27 #include "ui/gfx/text_elider.h"
28 #include "ui/gfx/text_utils.h"
29 #include "ui/gfx/utf16_indexing.h"
35 // All chars are replaced by this char when the password style is set.
36 // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*'
37 // that's available in the font (find_invisible_char() in gtkentry.c).
38 const base::char16 kPasswordReplacementChar
= '*';
40 // Default color used for the text and cursor.
41 const SkColor kDefaultColor
= SK_ColorBLACK
;
43 // Default color used for drawing selection background.
44 const SkColor kDefaultSelectionBackgroundColor
= SK_ColorGRAY
;
46 // Fraction of the text size to lower a strike through below the baseline.
47 const SkScalar kStrikeThroughOffset
= (-SK_Scalar1
* 6 / 21);
48 // Fraction of the text size to lower an underline below the baseline.
49 const SkScalar kUnderlineOffset
= (SK_Scalar1
/ 9);
50 // Fraction of the text size to use for a strike through or under-line.
51 const SkScalar kLineThickness
= (SK_Scalar1
/ 18);
52 // Fraction of the text size to use for a top margin of a diagonal strike.
53 const SkScalar kDiagonalStrikeMarginOffset
= (SK_Scalar1
/ 4);
55 // Invalid value of baseline. Assigning this value to |baseline_| causes
56 // re-calculation of baseline.
57 const int kInvalidBaseline
= INT_MAX
;
59 // Returns the baseline, with which the text best appears vertically centered.
60 int DetermineBaselineCenteringText(const Rect
& display_rect
,
61 const FontList
& font_list
) {
62 const int display_height
= display_rect
.height();
63 const int font_height
= font_list
.GetHeight();
64 // Lower and upper bound of baseline shift as we try to show as much area of
65 // text as possible. In particular case of |display_height| == |font_height|,
66 // we do not want to shift the baseline.
67 const int min_shift
= std::min(0, display_height
- font_height
);
68 const int max_shift
= std::abs(display_height
- font_height
);
69 const int baseline
= font_list
.GetBaseline();
70 const int cap_height
= font_list
.GetCapHeight();
71 const int internal_leading
= baseline
- cap_height
;
72 // Some platforms don't support getting the cap height, and simply return
73 // the entire font ascent from GetCapHeight(). Centering the ascent makes
74 // the font look too low, so if GetCapHeight() returns the ascent, center
75 // the entire font height instead.
77 display_height
- ((internal_leading
!= 0) ? cap_height
: font_height
);
78 const int baseline_shift
= space
/ 2 - internal_leading
;
79 return baseline
+ std::max(min_shift
, std::min(max_shift
, baseline_shift
));
82 // Converts |Font::FontStyle| flags to |SkTypeface::Style| flags.
83 SkTypeface::Style
ConvertFontStyleToSkiaTypefaceStyle(int font_style
) {
84 int skia_style
= SkTypeface::kNormal
;
85 skia_style
|= (font_style
& Font::BOLD
) ? SkTypeface::kBold
: 0;
86 skia_style
|= (font_style
& Font::ITALIC
) ? SkTypeface::kItalic
: 0;
87 return static_cast<SkTypeface::Style
>(skia_style
);
90 // Given |font| and |display_width|, returns the width of the fade gradient.
91 int CalculateFadeGradientWidth(const FontList
& font_list
, int display_width
) {
92 // Fade in/out about 2.5 characters of the beginning/end of the string.
93 // The .5 here is helpful if one of the characters is a space.
94 // Use a quarter of the display width if the display width is very short.
95 const int average_character_width
= font_list
.GetExpectedTextWidth(1);
96 const double gradient_width
= std::min(average_character_width
* 2.5,
98 DCHECK_GE(gradient_width
, 0.0);
99 return static_cast<int>(floor(gradient_width
+ 0.5));
102 // Appends to |positions| and |colors| values corresponding to the fade over
103 // |fade_rect| from color |c0| to color |c1|.
104 void AddFadeEffect(const Rect
& text_rect
,
105 const Rect
& fade_rect
,
108 std::vector
<SkScalar
>* positions
,
109 std::vector
<SkColor
>* colors
) {
110 const SkScalar left
= static_cast<SkScalar
>(fade_rect
.x() - text_rect
.x());
111 const SkScalar width
= static_cast<SkScalar
>(fade_rect
.width());
112 const SkScalar p0
= left
/ text_rect
.width();
113 const SkScalar p1
= (left
+ width
) / text_rect
.width();
114 // Prepend 0.0 to |positions|, as required by Skia.
115 if (positions
->empty() && p0
!= 0.0) {
116 positions
->push_back(0.0);
117 colors
->push_back(c0
);
119 positions
->push_back(p0
);
120 colors
->push_back(c0
);
121 positions
->push_back(p1
);
122 colors
->push_back(c1
);
125 // Creates a SkShader to fade the text, with |left_part| specifying the left
126 // fade effect, if any, and |right_part| specifying the right fade effect.
127 skia::RefPtr
<SkShader
> CreateFadeShader(const Rect
& text_rect
,
128 const Rect
& left_part
,
129 const Rect
& right_part
,
131 // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color.
132 const SkColor fade_color
= SkColorSetA(color
, 51);
133 std::vector
<SkScalar
> positions
;
134 std::vector
<SkColor
> colors
;
136 if (!left_part
.IsEmpty())
137 AddFadeEffect(text_rect
, left_part
, fade_color
, color
,
138 &positions
, &colors
);
139 if (!right_part
.IsEmpty())
140 AddFadeEffect(text_rect
, right_part
, color
, fade_color
,
141 &positions
, &colors
);
142 DCHECK(!positions
.empty());
144 // Terminate |positions| with 1.0, as required by Skia.
145 if (positions
.back() != 1.0) {
146 positions
.push_back(1.0);
147 colors
.push_back(colors
.back());
151 points
[0].iset(text_rect
.x(), text_rect
.y());
152 points
[1].iset(text_rect
.right(), text_rect
.y());
154 return skia::AdoptRef(
155 SkGradientShader::CreateLinear(&points
[0], &colors
[0], &positions
[0],
156 colors
.size(), SkShader::kClamp_TileMode
));
159 // Converts a FontRenderParams::Hinting value to the corresponding
160 // SkPaint::Hinting value.
161 SkPaint::Hinting
FontRenderParamsHintingToSkPaintHinting(
162 FontRenderParams::Hinting params_hinting
) {
163 switch (params_hinting
) {
164 case FontRenderParams::HINTING_NONE
: return SkPaint::kNo_Hinting
;
165 case FontRenderParams::HINTING_SLIGHT
: return SkPaint::kSlight_Hinting
;
166 case FontRenderParams::HINTING_MEDIUM
: return SkPaint::kNormal_Hinting
;
167 case FontRenderParams::HINTING_FULL
: return SkPaint::kFull_Hinting
;
169 return SkPaint::kNo_Hinting
;
176 // Value of |underline_thickness_| that indicates that underline metrics have
177 // not been set explicitly.
178 const SkScalar kUnderlineMetricsNotSet
= -1.0f
;
180 SkiaTextRenderer::SkiaTextRenderer(Canvas
* canvas
)
182 canvas_skia_(canvas
->sk_canvas()),
183 underline_thickness_(kUnderlineMetricsNotSet
),
184 underline_position_(0.0f
) {
185 DCHECK(canvas_skia_
);
186 paint_
.setTextEncoding(SkPaint::kGlyphID_TextEncoding
);
187 paint_
.setStyle(SkPaint::kFill_Style
);
188 paint_
.setAntiAlias(true);
189 paint_
.setSubpixelText(true);
190 paint_
.setLCDRenderText(true);
191 paint_
.setHinting(SkPaint::kNormal_Hinting
);
194 SkiaTextRenderer::~SkiaTextRenderer() {
197 void SkiaTextRenderer::SetDrawLooper(SkDrawLooper
* draw_looper
) {
198 paint_
.setLooper(draw_looper
);
201 void SkiaTextRenderer::SetFontRenderParams(const FontRenderParams
& params
,
202 bool background_is_transparent
) {
203 ApplyRenderParams(params
, background_is_transparent
, &paint_
);
206 void SkiaTextRenderer::SetTypeface(SkTypeface
* typeface
) {
207 paint_
.setTypeface(typeface
);
210 void SkiaTextRenderer::SetTextSize(SkScalar size
) {
211 paint_
.setTextSize(size
);
214 void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string
& family
,
216 DCHECK(!family
.empty());
218 skia::RefPtr
<SkTypeface
> typeface
= CreateSkiaTypeface(family
.c_str(), style
);
220 // |paint_| adds its own ref. So don't |release()| it from the ref ptr here.
221 SetTypeface(typeface
.get());
223 // Enable fake bold text if bold style is needed but new typeface does not
225 paint_
.setFakeBoldText((style
& Font::BOLD
) && !typeface
->isBold());
229 void SkiaTextRenderer::SetForegroundColor(SkColor foreground
) {
230 paint_
.setColor(foreground
);
233 void SkiaTextRenderer::SetShader(SkShader
* shader
) {
234 paint_
.setShader(shader
);
237 void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness
,
239 underline_thickness_
= thickness
;
240 underline_position_
= position
;
243 void SkiaTextRenderer::DrawPosText(const SkPoint
* pos
,
244 const uint16
* glyphs
,
245 size_t glyph_count
) {
246 const size_t byte_length
= glyph_count
* sizeof(glyphs
[0]);
247 canvas_skia_
->drawPosText(&glyphs
[0], byte_length
, &pos
[0], paint_
);
250 void SkiaTextRenderer::DrawDecorations(int x
, int y
, int width
, bool underline
,
251 bool strike
, bool diagonal_strike
) {
253 DrawUnderline(x
, y
, width
);
255 DrawStrike(x
, y
, width
);
256 if (diagonal_strike
) {
258 diagonal_
.reset(new DiagonalStrike(canvas_
, Point(x
, y
), paint_
));
259 diagonal_
->AddPiece(width
, paint_
.getColor());
260 } else if (diagonal_
) {
265 void SkiaTextRenderer::EndDiagonalStrike() {
272 void SkiaTextRenderer::DrawUnderline(int x
, int y
, int width
) {
273 SkScalar x_scalar
= SkIntToScalar(x
);
274 SkRect r
= SkRect::MakeLTRB(
275 x_scalar
, y
+ underline_position_
, x_scalar
+ width
,
276 y
+ underline_position_
+ underline_thickness_
);
277 if (underline_thickness_
== kUnderlineMetricsNotSet
) {
278 const SkScalar text_size
= paint_
.getTextSize();
279 r
.fTop
= SkScalarMulAdd(text_size
, kUnderlineOffset
, y
);
280 r
.fBottom
= r
.fTop
+ SkScalarMul(text_size
, kLineThickness
);
282 canvas_skia_
->drawRect(r
, paint_
);
285 void SkiaTextRenderer::DrawStrike(int x
, int y
, int width
) const {
286 const SkScalar text_size
= paint_
.getTextSize();
287 const SkScalar height
= SkScalarMul(text_size
, kLineThickness
);
288 const SkScalar offset
= SkScalarMulAdd(text_size
, kStrikeThroughOffset
, y
);
289 SkScalar x_scalar
= SkIntToScalar(x
);
291 SkRect::MakeLTRB(x_scalar
, offset
, x_scalar
+ width
, offset
+ height
);
292 canvas_skia_
->drawRect(r
, paint_
);
295 SkiaTextRenderer::DiagonalStrike::DiagonalStrike(Canvas
* canvas
,
297 const SkPaint
& paint
)
304 SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() {
307 void SkiaTextRenderer::DiagonalStrike::AddPiece(int length
, SkColor color
) {
308 pieces_
.push_back(Piece(length
, color
));
309 total_length_
+= length
;
312 void SkiaTextRenderer::DiagonalStrike::Draw() {
313 const SkScalar text_size
= paint_
.getTextSize();
314 const SkScalar offset
= SkScalarMul(text_size
, kDiagonalStrikeMarginOffset
);
315 const int thickness
=
316 SkScalarCeilToInt(SkScalarMul(text_size
, kLineThickness
) * 2);
317 const int height
= SkScalarCeilToInt(text_size
- offset
);
318 const Point end
= start_
+ Vector2d(total_length_
, -height
);
319 const int clip_height
= height
+ 2 * thickness
;
321 paint_
.setAntiAlias(true);
322 paint_
.setStrokeWidth(SkIntToScalar(thickness
));
324 const bool clipped
= pieces_
.size() > 1;
325 SkCanvas
* sk_canvas
= canvas_
->sk_canvas();
328 for (size_t i
= 0; i
< pieces_
.size(); ++i
) {
329 paint_
.setColor(pieces_
[i
].second
);
333 sk_canvas
->clipRect(RectToSkRect(
334 Rect(x
, end
.y() - thickness
, pieces_
[i
].first
, clip_height
)));
337 canvas_
->DrawLine(start_
, end
, paint_
);
342 x
+= pieces_
[i
].first
;
346 StyleIterator::StyleIterator(const BreakList
<SkColor
>& colors
,
347 const std::vector
<BreakList
<bool> >& styles
)
350 color_
= colors_
.breaks().begin();
351 for (size_t i
= 0; i
< styles_
.size(); ++i
)
352 style_
.push_back(styles_
[i
].breaks().begin());
355 StyleIterator::~StyleIterator() {}
357 Range
StyleIterator::GetRange() const {
358 Range
range(colors_
.GetRange(color_
));
359 for (size_t i
= 0; i
< NUM_TEXT_STYLES
; ++i
)
360 range
= range
.Intersect(styles_
[i
].GetRange(style_
[i
]));
364 void StyleIterator::UpdatePosition(size_t position
) {
365 color_
= colors_
.GetBreak(position
);
366 for (size_t i
= 0; i
< NUM_TEXT_STYLES
; ++i
)
367 style_
[i
] = styles_
[i
].GetBreak(position
);
370 LineSegment::LineSegment() : run(0) {}
372 LineSegment::~LineSegment() {}
374 Line::Line() : preceding_heights(0), baseline(0) {}
378 skia::RefPtr
<SkTypeface
> CreateSkiaTypeface(const std::string
& family
,
380 SkTypeface::Style skia_style
= ConvertFontStyleToSkiaTypefaceStyle(style
);
381 return skia::AdoptRef(SkTypeface::CreateFromName(family
.c_str(), skia_style
));
384 void ApplyRenderParams(const FontRenderParams
& params
,
385 bool background_is_transparent
,
387 paint
->setAntiAlias(params
.antialiasing
);
388 paint
->setLCDRenderText(!background_is_transparent
&&
389 params
.subpixel_rendering
!= FontRenderParams::SUBPIXEL_RENDERING_NONE
);
390 paint
->setSubpixelText(params
.subpixel_positioning
);
391 paint
->setAutohinted(params
.autohinter
);
392 paint
->setHinting(FontRenderParamsHintingToSkPaintHinting(params
.hinting
));
395 } // namespace internal
397 RenderText::~RenderText() {
400 RenderText
* RenderText::CreateInstance() {
401 #if defined(OS_MACOSX)
402 static const bool use_harfbuzz
=
403 base::CommandLine::ForCurrentProcess()->HasSwitch(
404 switches::kEnableHarfBuzzRenderText
);
406 static const bool use_harfbuzz
=
407 !base::CommandLine::ForCurrentProcess()->HasSwitch(
408 switches::kDisableHarfBuzzRenderText
);
410 return use_harfbuzz
? new RenderTextHarfBuzz
: CreateNativeInstance();
413 RenderText
* RenderText::CreateInstanceForEditing() {
414 static const bool use_harfbuzz
=
415 !base::CommandLine::ForCurrentProcess()->HasSwitch(
416 switches::kDisableHarfBuzzRenderText
);
417 return use_harfbuzz
? new RenderTextHarfBuzz
: CreateNativeInstance();
420 void RenderText::SetText(const base::string16
& text
) {
421 DCHECK(!composition_range_
.IsValid());
426 // Adjust ranged styles and colors to accommodate a new text length.
427 // Clear style ranges as they might break new text graphemes and apply
428 // the first style to the whole text instead.
429 const size_t text_length
= text_
.length();
430 colors_
.SetMax(text_length
);
431 for (size_t style
= 0; style
< NUM_TEXT_STYLES
; ++style
) {
432 BreakList
<bool>& break_list
= styles_
[style
];
433 break_list
.SetValue(break_list
.breaks().begin()->second
);
434 break_list
.SetMax(text_length
);
436 cached_bounds_and_offset_valid_
= false;
438 // Reset selection model. SetText should always followed by SetSelectionModel
439 // or SetCursorPosition in upper layer.
440 SetSelectionModel(SelectionModel());
442 // Invalidate the cached text direction if it depends on the text contents.
443 if (directionality_mode_
== DIRECTIONALITY_FROM_TEXT
)
444 text_direction_
= base::i18n::UNKNOWN_DIRECTION
;
446 obscured_reveal_index_
= -1;
450 void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment
) {
451 if (horizontal_alignment_
!= alignment
) {
452 horizontal_alignment_
= alignment
;
453 display_offset_
= Vector2d();
454 cached_bounds_and_offset_valid_
= false;
458 void RenderText::SetFontList(const FontList
& font_list
) {
459 font_list_
= font_list
;
460 const int font_style
= font_list
.GetFontStyle();
461 SetStyle(BOLD
, (font_style
& gfx::Font::BOLD
) != 0);
462 SetStyle(ITALIC
, (font_style
& gfx::Font::ITALIC
) != 0);
463 SetStyle(UNDERLINE
, (font_style
& gfx::Font::UNDERLINE
) != 0);
464 baseline_
= kInvalidBaseline
;
465 cached_bounds_and_offset_valid_
= false;
469 void RenderText::SetCursorEnabled(bool cursor_enabled
) {
470 cursor_enabled_
= cursor_enabled
;
471 cached_bounds_and_offset_valid_
= false;
474 void RenderText::ToggleInsertMode() {
475 insert_mode_
= !insert_mode_
;
476 cached_bounds_and_offset_valid_
= false;
479 void RenderText::SetObscured(bool obscured
) {
480 if (obscured
!= obscured_
) {
481 obscured_
= obscured
;
482 obscured_reveal_index_
= -1;
483 cached_bounds_and_offset_valid_
= false;
488 void RenderText::SetObscuredRevealIndex(int index
) {
489 if (obscured_reveal_index_
== index
)
492 obscured_reveal_index_
= index
;
493 cached_bounds_and_offset_valid_
= false;
497 void RenderText::SetReplaceNewlineCharsWithSymbols(bool replace
) {
498 replace_newline_chars_with_symbols_
= replace
;
499 cached_bounds_and_offset_valid_
= false;
503 void RenderText::SetMultiline(bool multiline
) {
504 if (multiline
!= multiline_
) {
505 multiline_
= multiline
;
506 cached_bounds_and_offset_valid_
= false;
511 void RenderText::SetElideBehavior(ElideBehavior elide_behavior
) {
512 // TODO(skanuj) : Add a test for triggering layout change.
513 if (elide_behavior_
!= elide_behavior
) {
514 elide_behavior_
= elide_behavior
;
519 void RenderText::SetDisplayRect(const Rect
& r
) {
520 if (r
!= display_rect_
) {
522 baseline_
= kInvalidBaseline
;
523 cached_bounds_and_offset_valid_
= false;
525 if (elide_behavior_
!= NO_ELIDE
)
530 void RenderText::SetCursorPosition(size_t position
) {
531 MoveCursorTo(position
, false);
534 void RenderText::MoveCursor(BreakType break_type
,
535 VisualCursorDirection direction
,
537 SelectionModel
cursor(cursor_position(), selection_model_
.caret_affinity());
538 // Cancelling a selection moves to the edge of the selection.
539 if (break_type
!= LINE_BREAK
&& !selection().is_empty() && !select
) {
540 SelectionModel selection_start
= GetSelectionModelForSelectionStart();
541 int start_x
= GetCursorBounds(selection_start
, true).x();
542 int cursor_x
= GetCursorBounds(cursor
, true).x();
543 // Use the selection start if it is left (when |direction| is CURSOR_LEFT)
544 // or right (when |direction| is CURSOR_RIGHT) of the selection end.
545 if (direction
== CURSOR_RIGHT
? start_x
> cursor_x
: start_x
< cursor_x
)
546 cursor
= selection_start
;
547 // Use the nearest word boundary in the proper |direction| for word breaks.
548 if (break_type
== WORD_BREAK
)
549 cursor
= GetAdjacentSelectionModel(cursor
, break_type
, direction
);
550 // Use an adjacent selection model if the cursor is not at a valid position.
551 if (!IsValidCursorIndex(cursor
.caret_pos()))
552 cursor
= GetAdjacentSelectionModel(cursor
, CHARACTER_BREAK
, direction
);
554 cursor
= GetAdjacentSelectionModel(cursor
, break_type
, direction
);
557 cursor
.set_selection_start(selection().start());
558 MoveCursorTo(cursor
);
561 bool RenderText::MoveCursorTo(const SelectionModel
& model
) {
562 // Enforce valid selection model components.
563 size_t text_length
= text().length();
564 Range
range(std::min(model
.selection().start(), text_length
),
565 std::min(model
.caret_pos(), text_length
));
566 // The current model only supports caret positions at valid cursor indices.
567 if (!IsValidCursorIndex(range
.start()) || !IsValidCursorIndex(range
.end()))
569 SelectionModel
sel(range
, model
.caret_affinity());
570 bool changed
= sel
!= selection_model_
;
571 SetSelectionModel(sel
);
575 bool RenderText::SelectRange(const Range
& range
) {
576 Range
sel(std::min(range
.start(), text().length()),
577 std::min(range
.end(), text().length()));
578 // Allow selection bounds at valid indicies amid multi-character graphemes.
579 if (!IsValidLogicalIndex(sel
.start()) || !IsValidLogicalIndex(sel
.end()))
581 LogicalCursorDirection affinity
=
582 (sel
.is_reversed() || sel
.is_empty()) ? CURSOR_FORWARD
: CURSOR_BACKWARD
;
583 SetSelectionModel(SelectionModel(sel
, affinity
));
587 bool RenderText::IsPointInSelection(const Point
& point
) {
588 if (selection().is_empty())
590 SelectionModel cursor
= FindCursorPosition(point
);
591 return RangeContainsCaret(
592 selection(), cursor
.caret_pos(), cursor
.caret_affinity());
595 void RenderText::ClearSelection() {
596 SetSelectionModel(SelectionModel(cursor_position(),
597 selection_model_
.caret_affinity()));
600 void RenderText::SelectAll(bool reversed
) {
601 const size_t length
= text().length();
602 const Range all
= reversed
? Range(length
, 0) : Range(0, length
);
603 const bool success
= SelectRange(all
);
607 void RenderText::SelectWord() {
613 size_t selection_max
= selection().GetMax();
615 base::i18n::BreakIterator
iter(text(), base::i18n::BreakIterator::BREAK_WORD
);
616 bool success
= iter
.Init();
621 size_t selection_min
= selection().GetMin();
622 if (selection_min
== text().length() && selection_min
!= 0)
625 for (; selection_min
!= 0; --selection_min
) {
626 if (iter
.IsStartOfWord(selection_min
) ||
627 iter
.IsEndOfWord(selection_min
))
631 if (selection_min
== selection_max
&& selection_max
!= text().length())
634 for (; selection_max
< text().length(); ++selection_max
)
635 if (iter
.IsEndOfWord(selection_max
) || iter
.IsStartOfWord(selection_max
))
638 const bool reversed
= selection().is_reversed();
639 MoveCursorTo(reversed
? selection_max
: selection_min
, false);
640 MoveCursorTo(reversed
? selection_min
: selection_max
, true);
643 const Range
& RenderText::GetCompositionRange() const {
644 return composition_range_
;
647 void RenderText::SetCompositionRange(const Range
& composition_range
) {
648 CHECK(!composition_range
.IsValid() ||
649 Range(0, text_
.length()).Contains(composition_range
));
650 composition_range_
.set_end(composition_range
.end());
651 composition_range_
.set_start(composition_range
.start());
655 void RenderText::SetColor(SkColor value
) {
656 colors_
.SetValue(value
);
659 void RenderText::ApplyColor(SkColor value
, const Range
& range
) {
660 colors_
.ApplyValue(value
, range
);
663 void RenderText::SetStyle(TextStyle style
, bool value
) {
664 styles_
[style
].SetValue(value
);
666 cached_bounds_and_offset_valid_
= false;
670 void RenderText::ApplyStyle(TextStyle style
, bool value
, const Range
& range
) {
671 // Do not change styles mid-grapheme to avoid breaking ligatures.
672 const size_t start
= IsValidCursorIndex(range
.start()) ? range
.start() :
673 IndexOfAdjacentGrapheme(range
.start(), CURSOR_BACKWARD
);
674 const size_t end
= IsValidCursorIndex(range
.end()) ? range
.end() :
675 IndexOfAdjacentGrapheme(range
.end(), CURSOR_FORWARD
);
676 styles_
[style
].ApplyValue(value
, Range(start
, end
));
678 cached_bounds_and_offset_valid_
= false;
682 bool RenderText::GetStyle(TextStyle style
) const {
683 return (styles_
[style
].breaks().size() == 1) &&
684 styles_
[style
].breaks().front().second
;
687 void RenderText::SetDirectionalityMode(DirectionalityMode mode
) {
688 if (mode
== directionality_mode_
)
691 directionality_mode_
= mode
;
692 text_direction_
= base::i18n::UNKNOWN_DIRECTION
;
693 cached_bounds_and_offset_valid_
= false;
697 base::i18n::TextDirection
RenderText::GetTextDirection() {
698 if (text_direction_
== base::i18n::UNKNOWN_DIRECTION
) {
699 switch (directionality_mode_
) {
700 case DIRECTIONALITY_FROM_TEXT
:
701 // Derive the direction from the display text, which differs from text()
702 // in the case of obscured (password) textfields.
704 base::i18n::GetFirstStrongCharacterDirection(GetLayoutText());
706 case DIRECTIONALITY_FROM_UI
:
707 text_direction_
= base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT
:
708 base::i18n::LEFT_TO_RIGHT
;
710 case DIRECTIONALITY_FORCE_LTR
:
711 text_direction_
= base::i18n::LEFT_TO_RIGHT
;
713 case DIRECTIONALITY_FORCE_RTL
:
714 text_direction_
= base::i18n::RIGHT_TO_LEFT
;
721 return text_direction_
;
724 VisualCursorDirection
RenderText::GetVisualDirectionOfLogicalEnd() {
725 return GetTextDirection() == base::i18n::LEFT_TO_RIGHT
?
726 CURSOR_RIGHT
: CURSOR_LEFT
;
729 SizeF
RenderText::GetStringSizeF() {
730 return GetStringSize();
733 float RenderText::GetContentWidthF() {
734 const float string_size
= GetStringSizeF().width();
735 // The cursor is drawn one pixel beyond the int-enclosed text bounds.
736 return cursor_enabled_
? std::ceil(string_size
) + 1 : string_size
;
739 int RenderText::GetContentWidth() {
740 return ToCeiledInt(GetContentWidthF());
743 int RenderText::GetBaseline() {
744 if (baseline_
== kInvalidBaseline
)
745 baseline_
= DetermineBaselineCenteringText(display_rect(), font_list());
746 DCHECK_NE(kInvalidBaseline
, baseline_
);
750 void RenderText::Draw(Canvas
* canvas
) {
753 if (clip_to_display_rect()) {
754 Rect
clip_rect(display_rect());
755 clip_rect
.Inset(ShadowValue::GetMargin(shadows_
));
758 canvas
->ClipRect(clip_rect
);
761 if (!text().empty() && focused())
762 DrawSelection(canvas
);
764 if (cursor_enabled() && cursor_visible() && focused())
765 DrawCursor(canvas
, selection_model_
);
768 DrawVisualText(canvas
);
770 if (clip_to_display_rect())
774 void RenderText::DrawCursor(Canvas
* canvas
, const SelectionModel
& position
) {
775 // Paint cursor. Replace cursor is drawn as rectangle for now.
776 // TODO(msw): Draw a better cursor with a better indication of association.
777 canvas
->FillRect(GetCursorBounds(position
, true), cursor_color_
);
780 bool RenderText::IsValidLogicalIndex(size_t index
) {
781 // Check that the index is at a valid code point (not mid-surrgate-pair) and
782 // that it's not truncated from the layout text (its glyph may be shown).
784 // Indices within truncated text are disallowed so users can easily interact
785 // with the underlying truncated text using the ellipsis as a proxy. This lets
786 // users select all text, select the truncated text, and transition from the
787 // last rendered glyph to the end of the text without getting invisible cursor
788 // positions nor needing unbounded arrow key presses to traverse the ellipsis.
789 return index
== 0 || index
== text().length() ||
790 (index
< text().length() &&
791 (truncate_length_
== 0 || index
< truncate_length_
) &&
792 IsValidCodePointIndex(text(), index
));
795 Rect
RenderText::GetCursorBounds(const SelectionModel
& caret
,
797 // TODO(ckocagil): Support multiline. This function should return the height
798 // of the line the cursor is on. |GetStringSize()| now returns
799 // the multiline size, eliminate its use here.
802 size_t caret_pos
= caret
.caret_pos();
803 DCHECK(IsValidLogicalIndex(caret_pos
));
804 // In overtype mode, ignore the affinity and always indicate that we will
805 // overtype the next character.
806 LogicalCursorDirection caret_affinity
=
807 insert_mode
? caret
.caret_affinity() : CURSOR_FORWARD
;
808 int x
= 0, width
= 1;
809 Size size
= GetStringSize();
810 if (caret_pos
== (caret_affinity
== CURSOR_BACKWARD
? 0 : text().length())) {
811 // The caret is attached to the boundary. Always return a 1-dip width caret,
812 // since there is nothing to overtype.
813 if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT
) == (caret_pos
== 0))
816 size_t grapheme_start
= (caret_affinity
== CURSOR_FORWARD
) ?
817 caret_pos
: IndexOfAdjacentGrapheme(caret_pos
, CURSOR_BACKWARD
);
818 Range
xspan(GetGlyphBounds(grapheme_start
));
820 x
= (caret_affinity
== CURSOR_BACKWARD
) ? xspan
.end() : xspan
.start();
821 } else { // overtype mode
823 width
= xspan
.length();
826 return Rect(ToViewPoint(Point(x
, 0)), Size(width
, size
.height()));
829 const Rect
& RenderText::GetUpdatedCursorBounds() {
830 UpdateCachedBoundsAndOffset();
831 return cursor_bounds_
;
834 size_t RenderText::IndexOfAdjacentGrapheme(size_t index
,
835 LogicalCursorDirection direction
) {
836 if (index
> text().length())
837 return text().length();
841 if (direction
== CURSOR_FORWARD
) {
842 while (index
< text().length()) {
844 if (IsValidCursorIndex(index
))
847 return text().length();
852 if (IsValidCursorIndex(index
))
858 SelectionModel
RenderText::GetSelectionModelForSelectionStart() {
859 const Range
& sel
= selection();
861 return selection_model_
;
862 return SelectionModel(sel
.start(),
863 sel
.is_reversed() ? CURSOR_BACKWARD
: CURSOR_FORWARD
);
866 const Vector2d
& RenderText::GetUpdatedDisplayOffset() {
867 UpdateCachedBoundsAndOffset();
868 return display_offset_
;
871 void RenderText::SetDisplayOffset(int horizontal_offset
) {
872 const int extra_content
= GetContentWidth() - display_rect_
.width();
873 const int cursor_width
= cursor_enabled_
? 1 : 0;
877 if (extra_content
> 0) {
878 switch (GetCurrentHorizontalAlignment()) {
880 min_offset
= -extra_content
;
883 max_offset
= extra_content
;
886 // The extra space reserved for cursor at the end of the text is ignored
887 // when centering text. So, to calculate the valid range for offset, we
888 // exclude that extra space, calculate the range, and add it back to the
889 // range (if cursor is enabled).
890 min_offset
= -(extra_content
- cursor_width
+ 1) / 2 - cursor_width
;
891 max_offset
= (extra_content
- cursor_width
) / 2;
897 if (horizontal_offset
< min_offset
)
898 horizontal_offset
= min_offset
;
899 else if (horizontal_offset
> max_offset
)
900 horizontal_offset
= max_offset
;
902 cached_bounds_and_offset_valid_
= true;
903 display_offset_
.set_x(horizontal_offset
);
904 cursor_bounds_
= GetCursorBounds(selection_model_
, insert_mode_
);
907 RenderText::RenderText()
908 : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT
: ALIGN_LEFT
),
909 directionality_mode_(DIRECTIONALITY_FROM_TEXT
),
910 text_direction_(base::i18n::UNKNOWN_DIRECTION
),
911 cursor_enabled_(true),
912 cursor_visible_(false),
914 cursor_color_(kDefaultColor
),
915 selection_color_(kDefaultColor
),
916 selection_background_focused_color_(kDefaultSelectionBackgroundColor
),
918 composition_range_(Range::InvalidRange()),
919 colors_(kDefaultColor
),
920 styles_(NUM_TEXT_STYLES
),
921 composition_and_selection_styles_applied_(false),
923 obscured_reveal_index_(-1),
925 elide_behavior_(NO_ELIDE
),
926 replace_newline_chars_with_symbols_(true),
928 background_is_transparent_(false),
929 clip_to_display_rect_(true),
930 baseline_(kInvalidBaseline
),
931 cached_bounds_and_offset_valid_(false) {
934 SelectionModel
RenderText::GetAdjacentSelectionModel(
935 const SelectionModel
& current
,
936 BreakType break_type
,
937 VisualCursorDirection direction
) {
940 if (break_type
== LINE_BREAK
|| text().empty())
941 return EdgeSelectionModel(direction
);
942 if (break_type
== CHARACTER_BREAK
)
943 return AdjacentCharSelectionModel(current
, direction
);
944 DCHECK(break_type
== WORD_BREAK
);
945 return AdjacentWordSelectionModel(current
, direction
);
948 SelectionModel
RenderText::EdgeSelectionModel(
949 VisualCursorDirection direction
) {
950 if (direction
== GetVisualDirectionOfLogicalEnd())
951 return SelectionModel(text().length(), CURSOR_FORWARD
);
952 return SelectionModel(0, CURSOR_BACKWARD
);
955 void RenderText::SetSelectionModel(const SelectionModel
& model
) {
956 DCHECK_LE(model
.selection().GetMax(), text().length());
957 selection_model_
= model
;
958 cached_bounds_and_offset_valid_
= false;
961 const base::string16
& RenderText::GetLayoutText() const {
965 const BreakList
<size_t>& RenderText::GetLineBreaks() {
966 if (line_breaks_
.max() != 0)
969 const base::string16
& layout_text
= GetLayoutText();
970 const size_t text_length
= layout_text
.length();
971 line_breaks_
.SetValue(0);
972 line_breaks_
.SetMax(text_length
);
973 base::i18n::BreakIterator
iter(layout_text
,
974 base::i18n::BreakIterator::BREAK_LINE
);
975 const bool success
= iter
.Init();
979 line_breaks_
.ApplyValue(iter
.pos(), Range(iter
.pos(), text_length
));
980 } while (iter
.Advance());
985 void RenderText::ApplyCompositionAndSelectionStyles() {
986 // Save the underline and color breaks to undo the temporary styles later.
987 DCHECK(!composition_and_selection_styles_applied_
);
988 saved_colors_
= colors_
;
989 saved_underlines_
= styles_
[UNDERLINE
];
991 // Apply an underline to the composition range in |underlines|.
992 if (composition_range_
.IsValid() && !composition_range_
.is_empty())
993 styles_
[UNDERLINE
].ApplyValue(true, composition_range_
);
995 // Apply the selected text color to the [un-reversed] selection range.
996 if (!selection().is_empty() && focused()) {
997 const Range
range(selection().GetMin(), selection().GetMax());
998 colors_
.ApplyValue(selection_color_
, range
);
1000 composition_and_selection_styles_applied_
= true;
1003 void RenderText::UndoCompositionAndSelectionStyles() {
1004 // Restore the underline and color breaks to undo the temporary styles.
1005 DCHECK(composition_and_selection_styles_applied_
);
1006 colors_
= saved_colors_
;
1007 styles_
[UNDERLINE
] = saved_underlines_
;
1008 composition_and_selection_styles_applied_
= false;
1011 Vector2d
RenderText::GetLineOffset(size_t line_number
) {
1012 Vector2d offset
= display_rect().OffsetFromOrigin();
1013 // TODO(ckocagil): Apply the display offset for multiline scrolling.
1015 offset
.Add(GetUpdatedDisplayOffset());
1017 offset
.Add(Vector2d(0, lines_
[line_number
].preceding_heights
));
1018 offset
.Add(GetAlignmentOffset(line_number
));
1022 Point
RenderText::ToTextPoint(const Point
& point
) {
1023 return point
- GetLineOffset(0);
1024 // TODO(ckocagil): Convert multiline view space points to text space.
1027 Point
RenderText::ToViewPoint(const Point
& point
) {
1029 return point
+ GetLineOffset(0);
1031 // TODO(ckocagil): Traverse individual line segments for RTL support.
1032 DCHECK(!lines_
.empty());
1035 for (; line
< lines_
.size() && x
> lines_
[line
].size
.width(); ++line
)
1036 x
-= lines_
[line
].size
.width();
1037 return Point(x
, point
.y()) + GetLineOffset(line
);
1040 std::vector
<Rect
> RenderText::TextBoundsToViewBounds(const Range
& x
) {
1041 std::vector
<Rect
> rects
;
1044 rects
.push_back(Rect(ToViewPoint(Point(x
.GetMin(), 0)),
1045 Size(x
.length(), GetStringSize().height())));
1051 // Each line segment keeps its position in text coordinates. Traverse all line
1052 // segments and if the segment intersects with the given range, add the view
1053 // rect corresponding to the intersection to |rects|.
1054 for (size_t line
= 0; line
< lines_
.size(); ++line
) {
1056 const Vector2d offset
= GetLineOffset(line
);
1057 for (size_t i
= 0; i
< lines_
[line
].segments
.size(); ++i
) {
1058 const internal::LineSegment
* segment
= &lines_
[line
].segments
[i
];
1059 const Range intersection
= segment
->x_range
.Intersect(x
);
1060 if (!intersection
.is_empty()) {
1061 Rect
rect(line_x
+ intersection
.start() - segment
->x_range
.start(),
1062 0, intersection
.length(), lines_
[line
].size
.height());
1063 rects
.push_back(rect
+ offset
);
1065 line_x
+= segment
->x_range
.length();
1072 HorizontalAlignment
RenderText::GetCurrentHorizontalAlignment() {
1073 if (horizontal_alignment_
!= ALIGN_TO_HEAD
)
1074 return horizontal_alignment_
;
1075 return GetTextDirection() == base::i18n::RIGHT_TO_LEFT
? ALIGN_RIGHT
1079 Vector2d
RenderText::GetAlignmentOffset(size_t line_number
) {
1080 // TODO(ckocagil): Enable |lines_| usage in other platforms.
1082 DCHECK_LT(line_number
, lines_
.size());
1085 HorizontalAlignment horizontal_alignment
= GetCurrentHorizontalAlignment();
1086 if (horizontal_alignment
!= ALIGN_LEFT
) {
1088 const int width
= std::ceil(lines_
[line_number
].size
.width()) +
1089 (cursor_enabled_
? 1 : 0);
1091 const int width
= GetContentWidth();
1093 offset
.set_x(display_rect().width() - width
);
1094 // Put any extra margin pixel on the left to match legacy behavior.
1095 if (horizontal_alignment
== ALIGN_CENTER
)
1096 offset
.set_x((offset
.x() + 1) / 2);
1099 // Vertically center the text.
1101 const int text_height
= lines_
.back().preceding_heights
+
1102 lines_
.back().size
.height();
1103 offset
.set_y((display_rect_
.height() - text_height
) / 2);
1105 offset
.set_y(GetBaseline() - GetLayoutTextBaseline());
1111 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer
* renderer
) {
1112 const int width
= display_rect().width();
1113 if (multiline() || elide_behavior_
!= FADE_TAIL
|| GetContentWidth() <= width
)
1116 const int gradient_width
= CalculateFadeGradientWidth(font_list(), width
);
1117 if (gradient_width
== 0)
1120 HorizontalAlignment horizontal_alignment
= GetCurrentHorizontalAlignment();
1121 Rect solid_part
= display_rect();
1124 if (horizontal_alignment
!= ALIGN_LEFT
) {
1125 left_part
= solid_part
;
1126 left_part
.Inset(0, 0, solid_part
.width() - gradient_width
, 0);
1127 solid_part
.Inset(gradient_width
, 0, 0, 0);
1129 if (horizontal_alignment
!= ALIGN_RIGHT
) {
1130 right_part
= solid_part
;
1131 right_part
.Inset(solid_part
.width() - gradient_width
, 0, 0, 0);
1132 solid_part
.Inset(0, 0, gradient_width
, 0);
1135 Rect text_rect
= display_rect();
1136 text_rect
.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1138 // TODO(msw): Use the actual text colors corresponding to each faded part.
1139 skia::RefPtr
<SkShader
> shader
= CreateFadeShader(
1140 text_rect
, left_part
, right_part
, colors_
.breaks().front().second
);
1142 renderer
->SetShader(shader
.get());
1145 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer
* renderer
) {
1146 skia::RefPtr
<SkDrawLooper
> looper
= CreateShadowDrawLooper(shadows_
);
1147 renderer
->SetDrawLooper(looper
.get());
1151 bool RenderText::RangeContainsCaret(const Range
& range
,
1153 LogicalCursorDirection caret_affinity
) {
1154 // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1155 size_t adjacent
= (caret_affinity
== CURSOR_BACKWARD
) ?
1156 caret_pos
- 1 : caret_pos
+ 1;
1157 return range
.Contains(Range(caret_pos
, adjacent
));
1160 void RenderText::MoveCursorTo(size_t position
, bool select
) {
1161 size_t cursor
= std::min(position
, text().length());
1162 if (IsValidCursorIndex(cursor
))
1163 SetSelectionModel(SelectionModel(
1164 Range(select
? selection().start() : cursor
, cursor
),
1165 (cursor
== 0) ? CURSOR_FORWARD
: CURSOR_BACKWARD
));
1168 void RenderText::UpdateLayoutText() {
1169 layout_text_
.clear();
1170 line_breaks_
.SetMax(0);
1173 size_t obscured_text_length
=
1174 static_cast<size_t>(UTF16IndexToOffset(text_
, 0, text_
.length()));
1175 layout_text_
.assign(obscured_text_length
, kPasswordReplacementChar
);
1177 if (obscured_reveal_index_
>= 0 &&
1178 obscured_reveal_index_
< static_cast<int>(text_
.length())) {
1179 // Gets the index range in |text_| to be revealed.
1180 size_t start
= obscured_reveal_index_
;
1181 U16_SET_CP_START(text_
.data(), 0, start
);
1183 UChar32 unused_char
;
1184 U16_NEXT(text_
.data(), end
, text_
.length(), unused_char
);
1186 // Gets the index in |layout_text_| to be replaced.
1187 const size_t cp_start
=
1188 static_cast<size_t>(UTF16IndexToOffset(text_
, 0, start
));
1189 if (layout_text_
.length() > cp_start
)
1190 layout_text_
.replace(cp_start
, 1, text_
.substr(start
, end
- start
));
1193 layout_text_
= text_
;
1196 const base::string16
& text
= layout_text_
;
1197 if (truncate_length_
> 0 && truncate_length_
< text
.length()) {
1198 // Truncate the text at a valid character break and append an ellipsis.
1199 icu::StringCharacterIterator
iter(text
.c_str());
1200 // Respect ELIDE_HEAD and ELIDE_MIDDLE preferences during truncation.
1201 if (elide_behavior_
== ELIDE_HEAD
) {
1202 iter
.setIndex32(text
.length() - truncate_length_
+ 1);
1203 layout_text_
.assign(kEllipsisUTF16
+ text
.substr(iter
.getIndex()));
1204 } else if (elide_behavior_
== ELIDE_MIDDLE
) {
1205 iter
.setIndex32(truncate_length_
/ 2);
1206 const size_t ellipsis_start
= iter
.getIndex();
1207 iter
.setIndex32(text
.length() - (truncate_length_
/ 2));
1208 const size_t ellipsis_end
= iter
.getIndex();
1209 DCHECK_LE(ellipsis_start
, ellipsis_end
);
1210 layout_text_
.assign(text
.substr(0, ellipsis_start
) + kEllipsisUTF16
+
1211 text
.substr(ellipsis_end
));
1213 iter
.setIndex32(truncate_length_
- 1);
1214 layout_text_
.assign(text
.substr(0, iter
.getIndex()) + kEllipsisUTF16
);
1218 if (elide_behavior_
!= NO_ELIDE
&&
1219 elide_behavior_
!= FADE_TAIL
&&
1220 !layout_text_
.empty() &&
1221 GetContentWidth() > display_rect_
.width()) {
1222 // This doesn't trim styles so ellipsis may get rendered as a different
1223 // style than the preceding text. See crbug.com/327850.
1224 layout_text_
.assign(Elide(layout_text_
,
1225 static_cast<float>(display_rect_
.width()),
1229 // Replace the newline character with a newline symbol in single line mode.
1230 static const base::char16 kNewline
[] = { '\n', 0 };
1231 static const base::char16 kNewlineSymbol
[] = { 0x2424, 0 };
1232 if (!multiline_
&& replace_newline_chars_with_symbols_
)
1233 base::ReplaceChars(layout_text_
, kNewline
, kNewlineSymbol
, &layout_text_
);
1238 base::string16
RenderText::Elide(const base::string16
& text
,
1239 float available_width
,
1240 ElideBehavior behavior
) {
1241 if (available_width
<= 0 || text
.empty())
1242 return base::string16();
1243 if (behavior
== ELIDE_EMAIL
)
1244 return ElideEmail(text
, available_width
);
1246 // Create a RenderText copy with attributes that affect the rendering width.
1247 scoped_ptr
<RenderText
> render_text
= CreateInstanceOfSameType();
1248 render_text
->SetFontList(font_list_
);
1249 render_text
->SetDirectionalityMode(directionality_mode_
);
1250 render_text
->SetCursorEnabled(cursor_enabled_
);
1251 render_text
->set_truncate_length(truncate_length_
);
1252 render_text
->styles_
= styles_
;
1253 render_text
->colors_
= colors_
;
1254 render_text
->SetText(text
);
1255 if (render_text
->GetContentWidthF() <= available_width
)
1258 const base::string16 ellipsis
= base::string16(kEllipsisUTF16
);
1259 const bool insert_ellipsis
= (behavior
!= TRUNCATE
);
1260 const bool elide_in_middle
= (behavior
== ELIDE_MIDDLE
);
1261 const bool elide_at_beginning
= (behavior
== ELIDE_HEAD
);
1262 StringSlicer
slicer(text
, ellipsis
, elide_in_middle
, elide_at_beginning
);
1264 render_text
->SetText(ellipsis
);
1265 const float ellipsis_width
= render_text
->GetContentWidthF();
1267 if (insert_ellipsis
&& (ellipsis_width
> available_width
))
1268 return base::string16();
1270 // Use binary search to compute the elided text.
1272 size_t hi
= text
.length() - 1;
1273 const base::i18n::TextDirection text_direction
= GetTextDirection();
1274 for (size_t guess
= (lo
+ hi
) / 2; lo
<= hi
; guess
= (lo
+ hi
) / 2) {
1275 // Restore colors. They will be truncated to size by SetText.
1276 render_text
->colors_
= colors_
;
1277 base::string16 new_text
=
1278 slicer
.CutString(guess
, insert_ellipsis
&& behavior
!= ELIDE_TAIL
);
1279 render_text
->SetText(new_text
);
1281 // This has to be an additional step so that the ellipsis is rendered with
1282 // same style as trailing part of the text.
1283 if (insert_ellipsis
&& behavior
== ELIDE_TAIL
) {
1284 // When ellipsis follows text whose directionality is not the same as that
1285 // of the whole text, it will be rendered with the directionality of the
1286 // whole text. Since we want ellipsis to indicate continuation of the
1287 // preceding text, we force the directionality of ellipsis to be same as
1288 // the preceding text using LTR or RTL markers.
1289 base::i18n::TextDirection trailing_text_direction
=
1290 base::i18n::GetLastStrongCharacterDirection(new_text
);
1291 new_text
.append(ellipsis
);
1292 if (trailing_text_direction
!= text_direction
) {
1293 if (trailing_text_direction
== base::i18n::LEFT_TO_RIGHT
)
1294 new_text
+= base::i18n::kLeftToRightMark
;
1296 new_text
+= base::i18n::kRightToLeftMark
;
1298 render_text
->SetText(new_text
);
1301 // Restore styles. Make sure style ranges don't break new text graphemes.
1302 render_text
->styles_
= styles_
;
1303 for (size_t style
= 0; style
< NUM_TEXT_STYLES
; ++style
) {
1304 BreakList
<bool>& break_list
= render_text
->styles_
[style
];
1305 break_list
.SetMax(render_text
->text_
.length());
1307 while (range
.end() < break_list
.max()) {
1308 BreakList
<bool>::const_iterator current_break
=
1309 break_list
.GetBreak(range
.end());
1310 range
= break_list
.GetRange(current_break
);
1311 if (range
.end() < break_list
.max() &&
1312 !render_text
->IsValidCursorIndex(range
.end())) {
1313 range
.set_end(render_text
->IndexOfAdjacentGrapheme(range
.end(),
1315 break_list
.ApplyValue(current_break
->second
, range
);
1320 // We check the width of the whole desired string at once to ensure we
1321 // handle kerning/ligatures/etc. correctly.
1322 const float guess_width
= render_text
->GetContentWidthF();
1323 if (guess_width
== available_width
)
1325 if (guess_width
> available_width
) {
1327 // Move back on the loop terminating condition when the guess is too wide.
1335 return render_text
->text();
1338 base::string16
RenderText::ElideEmail(const base::string16
& email
,
1339 float available_width
) {
1340 // The returned string will have at least one character besides the ellipsis
1341 // on either side of '@'; if that's impossible, a single ellipsis is returned.
1342 // If possible, only the username is elided. Otherwise, the domain is elided
1343 // in the middle, splitting available width equally with the elided username.
1344 // If the username is short enough that it doesn't need half the available
1345 // width, the elided domain will occupy that extra width.
1347 // Split the email into its local-part (username) and domain-part. The email
1348 // spec allows for @ symbols in the username under some special requirements,
1349 // but not in the domain part, so splitting at the last @ symbol is safe.
1350 const size_t split_index
= email
.find_last_of('@');
1351 DCHECK_NE(split_index
, base::string16::npos
);
1352 base::string16 username
= email
.substr(0, split_index
);
1353 base::string16 domain
= email
.substr(split_index
+ 1);
1354 DCHECK(!username
.empty());
1355 DCHECK(!domain
.empty());
1357 // Subtract the @ symbol from the available width as it is mandatory.
1358 const base::string16 kAtSignUTF16
= base::ASCIIToUTF16("@");
1359 available_width
-= GetStringWidthF(kAtSignUTF16
, font_list());
1361 // Check whether eliding the domain is necessary: if eliding the username
1362 // is sufficient, the domain will not be elided.
1363 const float full_username_width
= GetStringWidthF(username
, font_list());
1364 const float available_domain_width
= available_width
-
1365 std::min(full_username_width
,
1366 GetStringWidthF(username
.substr(0, 1) + kEllipsisUTF16
, font_list()));
1367 if (GetStringWidthF(domain
, font_list()) > available_domain_width
) {
1368 // Elide the domain so that it only takes half of the available width.
1369 // Should the username not need all the width available in its half, the
1370 // domain will occupy the leftover width.
1371 // If |desired_domain_width| is greater than |available_domain_width|: the
1372 // minimal username elision allowed by the specifications will not fit; thus
1373 // |desired_domain_width| must be <= |available_domain_width| at all cost.
1374 const float desired_domain_width
=
1375 std::min
<float>(available_domain_width
,
1376 std::max
<float>(available_width
- full_username_width
,
1377 available_width
/ 2));
1378 domain
= Elide(domain
, desired_domain_width
, ELIDE_MIDDLE
);
1379 // Failing to elide the domain such that at least one character remains
1380 // (other than the ellipsis itself) remains: return a single ellipsis.
1381 if (domain
.length() <= 1U)
1382 return base::string16(kEllipsisUTF16
);
1385 // Fit the username in the remaining width (at this point the elided username
1386 // is guaranteed to fit with at least one character remaining given all the
1387 // precautions taken earlier).
1388 available_width
-= GetStringWidthF(domain
, font_list());
1389 username
= Elide(username
, available_width
, ELIDE_TAIL
);
1390 return username
+ kAtSignUTF16
+ domain
;
1393 void RenderText::UpdateCachedBoundsAndOffset() {
1394 if (cached_bounds_and_offset_valid_
)
1397 // TODO(ckocagil): Add support for scrolling multiline text.
1401 if (cursor_enabled()) {
1402 // When cursor is enabled, ensure it is visible. For this, set the valid
1403 // flag true and calculate the current cursor bounds using the stale
1404 // |display_offset_|. Then calculate the change in offset needed to move the
1405 // cursor into the visible area.
1406 cached_bounds_and_offset_valid_
= true;
1407 cursor_bounds_
= GetCursorBounds(selection_model_
, insert_mode_
);
1409 // TODO(bidi): Show RTL glyphs at the cursor position for ALIGN_LEFT, etc.
1410 if (cursor_bounds_
.right() > display_rect_
.right())
1411 delta_x
= display_rect_
.right() - cursor_bounds_
.right();
1412 else if (cursor_bounds_
.x() < display_rect_
.x())
1413 delta_x
= display_rect_
.x() - cursor_bounds_
.x();
1416 SetDisplayOffset(display_offset_
.x() + delta_x
);
1419 void RenderText::DrawSelection(Canvas
* canvas
) {
1420 const std::vector
<Rect
> sel
= GetSubstringBounds(selection());
1421 for (std::vector
<Rect
>::const_iterator i
= sel
.begin(); i
< sel
.end(); ++i
)
1422 canvas
->FillRect(*i
, selection_background_focused_color_
);