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/insets.h"
22 #include "ui/gfx/render_text_harfbuzz.h"
23 #include "ui/gfx/scoped_canvas.h"
24 #include "ui/gfx/skia_util.h"
25 #include "ui/gfx/switches.h"
26 #include "ui/gfx/text_elider.h"
27 #include "ui/gfx/text_utils.h"
28 #include "ui/gfx/utf16_indexing.h"
34 // All chars are replaced by this char when the password style is set.
35 // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*'
36 // that's available in the font (find_invisible_char() in gtkentry.c).
37 const base::char16 kPasswordReplacementChar
= '*';
39 // Default color used for the text and cursor.
40 const SkColor kDefaultColor
= SK_ColorBLACK
;
42 // Default color used for drawing selection background.
43 const SkColor kDefaultSelectionBackgroundColor
= SK_ColorGRAY
;
45 // Fraction of the text size to lower a strike through below the baseline.
46 const SkScalar kStrikeThroughOffset
= (-SK_Scalar1
* 6 / 21);
47 // Fraction of the text size to lower an underline below the baseline.
48 const SkScalar kUnderlineOffset
= (SK_Scalar1
/ 9);
49 // Fraction of the text size to use for a strike through or under-line.
50 const SkScalar kLineThickness
= (SK_Scalar1
/ 18);
51 // Fraction of the text size to use for a top margin of a diagonal strike.
52 const SkScalar kDiagonalStrikeMarginOffset
= (SK_Scalar1
/ 4);
54 // Invalid value of baseline. Assigning this value to |baseline_| causes
55 // re-calculation of baseline.
56 const int kInvalidBaseline
= INT_MAX
;
58 // Returns the baseline, with which the text best appears vertically centered.
59 int DetermineBaselineCenteringText(const Rect
& display_rect
,
60 const FontList
& font_list
) {
61 const int display_height
= display_rect
.height();
62 const int font_height
= font_list
.GetHeight();
63 // Lower and upper bound of baseline shift as we try to show as much area of
64 // text as possible. In particular case of |display_height| == |font_height|,
65 // we do not want to shift the baseline.
66 const int min_shift
= std::min(0, display_height
- font_height
);
67 const int max_shift
= std::abs(display_height
- font_height
);
68 const int baseline
= font_list
.GetBaseline();
69 const int cap_height
= font_list
.GetCapHeight();
70 const int internal_leading
= baseline
- cap_height
;
71 // Some platforms don't support getting the cap height, and simply return
72 // the entire font ascent from GetCapHeight(). Centering the ascent makes
73 // the font look too low, so if GetCapHeight() returns the ascent, center
74 // the entire font height instead.
76 display_height
- ((internal_leading
!= 0) ? cap_height
: font_height
);
77 const int baseline_shift
= space
/ 2 - internal_leading
;
78 return baseline
+ std::max(min_shift
, std::min(max_shift
, baseline_shift
));
81 // Converts |Font::FontStyle| flags to |SkTypeface::Style| flags.
82 SkTypeface::Style
ConvertFontStyleToSkiaTypefaceStyle(int font_style
) {
83 int skia_style
= SkTypeface::kNormal
;
84 skia_style
|= (font_style
& Font::BOLD
) ? SkTypeface::kBold
: 0;
85 skia_style
|= (font_style
& Font::ITALIC
) ? SkTypeface::kItalic
: 0;
86 return static_cast<SkTypeface::Style
>(skia_style
);
89 // Given |font| and |display_width|, returns the width of the fade gradient.
90 int CalculateFadeGradientWidth(const FontList
& font_list
, int display_width
) {
91 // Fade in/out about 2.5 characters of the beginning/end of the string.
92 // The .5 here is helpful if one of the characters is a space.
93 // Use a quarter of the display width if the display width is very short.
94 const int average_character_width
= font_list
.GetExpectedTextWidth(1);
95 const double gradient_width
= std::min(average_character_width
* 2.5,
97 DCHECK_GE(gradient_width
, 0.0);
98 return static_cast<int>(floor(gradient_width
+ 0.5));
101 // Appends to |positions| and |colors| values corresponding to the fade over
102 // |fade_rect| from color |c0| to color |c1|.
103 void AddFadeEffect(const Rect
& text_rect
,
104 const Rect
& fade_rect
,
107 std::vector
<SkScalar
>* positions
,
108 std::vector
<SkColor
>* colors
) {
109 const SkScalar left
= static_cast<SkScalar
>(fade_rect
.x() - text_rect
.x());
110 const SkScalar width
= static_cast<SkScalar
>(fade_rect
.width());
111 const SkScalar p0
= left
/ text_rect
.width();
112 const SkScalar p1
= (left
+ width
) / text_rect
.width();
113 // Prepend 0.0 to |positions|, as required by Skia.
114 if (positions
->empty() && p0
!= 0.0) {
115 positions
->push_back(0.0);
116 colors
->push_back(c0
);
118 positions
->push_back(p0
);
119 colors
->push_back(c0
);
120 positions
->push_back(p1
);
121 colors
->push_back(c1
);
124 // Creates a SkShader to fade the text, with |left_part| specifying the left
125 // fade effect, if any, and |right_part| specifying the right fade effect.
126 skia::RefPtr
<SkShader
> CreateFadeShader(const Rect
& text_rect
,
127 const Rect
& left_part
,
128 const Rect
& right_part
,
130 // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color.
131 const SkColor fade_color
= SkColorSetA(color
, 51);
132 std::vector
<SkScalar
> positions
;
133 std::vector
<SkColor
> colors
;
135 if (!left_part
.IsEmpty())
136 AddFadeEffect(text_rect
, left_part
, fade_color
, color
,
137 &positions
, &colors
);
138 if (!right_part
.IsEmpty())
139 AddFadeEffect(text_rect
, right_part
, color
, fade_color
,
140 &positions
, &colors
);
141 DCHECK(!positions
.empty());
143 // Terminate |positions| with 1.0, as required by Skia.
144 if (positions
.back() != 1.0) {
145 positions
.push_back(1.0);
146 colors
.push_back(colors
.back());
150 points
[0].iset(text_rect
.x(), text_rect
.y());
151 points
[1].iset(text_rect
.right(), text_rect
.y());
153 return skia::AdoptRef(
154 SkGradientShader::CreateLinear(&points
[0], &colors
[0], &positions
[0],
155 colors
.size(), SkShader::kClamp_TileMode
));
158 // Converts a FontRenderParams::Hinting value to the corresponding
159 // SkPaint::Hinting value.
160 SkPaint::Hinting
FontRenderParamsHintingToSkPaintHinting(
161 FontRenderParams::Hinting params_hinting
) {
162 switch (params_hinting
) {
163 case FontRenderParams::HINTING_NONE
: return SkPaint::kNo_Hinting
;
164 case FontRenderParams::HINTING_SLIGHT
: return SkPaint::kSlight_Hinting
;
165 case FontRenderParams::HINTING_MEDIUM
: return SkPaint::kNormal_Hinting
;
166 case FontRenderParams::HINTING_FULL
: return SkPaint::kFull_Hinting
;
168 return SkPaint::kNo_Hinting
;
175 // Value of |underline_thickness_| that indicates that underline metrics have
176 // not been set explicitly.
177 const SkScalar kUnderlineMetricsNotSet
= -1.0f
;
179 SkiaTextRenderer::SkiaTextRenderer(Canvas
* canvas
)
181 canvas_skia_(canvas
->sk_canvas()),
182 started_drawing_(false),
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
);
195 SkiaTextRenderer::~SkiaTextRenderer() {
196 // Work-around for http://crbug.com/122743, where non-ClearType text is
197 // rendered with incorrect gamma when using the fade shader. Draw the text
198 // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode.
200 // TODO(asvitkine): Remove this work-around once the Skia bug is fixed.
201 // http://code.google.com/p/skia/issues/detail?id=590
202 if (deferred_fade_shader_
.get()) {
203 paint_
.setShader(deferred_fade_shader_
.get());
204 paint_
.setXfermodeMode(SkXfermode::kDstIn_Mode
);
205 canvas_skia_
->drawRect(bounds_
, paint_
);
206 canvas_skia_
->restore();
210 void SkiaTextRenderer::SetDrawLooper(SkDrawLooper
* draw_looper
) {
211 paint_
.setLooper(draw_looper
);
214 void SkiaTextRenderer::SetFontRenderParams(const FontRenderParams
& params
,
215 bool background_is_transparent
) {
216 ApplyRenderParams(params
, background_is_transparent
, &paint_
);
219 void SkiaTextRenderer::SetTypeface(SkTypeface
* typeface
) {
220 paint_
.setTypeface(typeface
);
223 void SkiaTextRenderer::SetTextSize(SkScalar size
) {
224 paint_
.setTextSize(size
);
227 void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string
& family
,
229 DCHECK(!family
.empty());
231 skia::RefPtr
<SkTypeface
> typeface
= CreateSkiaTypeface(family
.c_str(), style
);
233 // |paint_| adds its own ref. So don't |release()| it from the ref ptr here.
234 SetTypeface(typeface
.get());
236 // Enable fake bold text if bold style is needed but new typeface does not
238 paint_
.setFakeBoldText((style
& Font::BOLD
) && !typeface
->isBold());
242 void SkiaTextRenderer::SetForegroundColor(SkColor foreground
) {
243 paint_
.setColor(foreground
);
246 void SkiaTextRenderer::SetShader(SkShader
* shader
, const Rect
& bounds
) {
247 bounds_
= RectToSkRect(bounds
);
248 paint_
.setShader(shader
);
251 void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness
,
253 underline_thickness_
= thickness
;
254 underline_position_
= position
;
257 void SkiaTextRenderer::DrawPosText(const SkPoint
* pos
,
258 const uint16
* glyphs
,
259 size_t glyph_count
) {
260 if (!started_drawing_
) {
261 started_drawing_
= true;
262 // Work-around for http://crbug.com/122743, where non-ClearType text is
263 // rendered with incorrect gamma when using the fade shader. Draw the text
264 // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode.
266 // Skip this when there is a looper which seems not working well with
267 // deferred paint. Currently a looper is only used for text shadows.
269 // TODO(asvitkine): Remove this work-around once the Skia bug is fixed.
270 // http://code.google.com/p/skia/issues/detail?id=590
271 if (!paint_
.isLCDRenderText() &&
272 paint_
.getShader() &&
273 !paint_
.getLooper()) {
274 deferred_fade_shader_
= skia::SharePtr(paint_
.getShader());
275 paint_
.setShader(NULL
);
276 canvas_skia_
->saveLayer(&bounds_
, NULL
);
280 const size_t byte_length
= glyph_count
* sizeof(glyphs
[0]);
281 canvas_skia_
->drawPosText(&glyphs
[0], byte_length
, &pos
[0], paint_
);
284 void SkiaTextRenderer::DrawDecorations(int x
, int y
, int width
, bool underline
,
285 bool strike
, bool diagonal_strike
) {
287 DrawUnderline(x
, y
, width
);
289 DrawStrike(x
, y
, width
);
290 if (diagonal_strike
) {
292 diagonal_
.reset(new DiagonalStrike(canvas_
, Point(x
, y
), paint_
));
293 diagonal_
->AddPiece(width
, paint_
.getColor());
294 } else if (diagonal_
) {
299 void SkiaTextRenderer::EndDiagonalStrike() {
306 void SkiaTextRenderer::DrawUnderline(int x
, int y
, int width
) {
307 SkRect r
= SkRect::MakeLTRB(x
, y
+ underline_position_
, x
+ width
,
308 y
+ underline_position_
+ underline_thickness_
);
309 if (underline_thickness_
== kUnderlineMetricsNotSet
) {
310 const SkScalar text_size
= paint_
.getTextSize();
311 r
.fTop
= SkScalarMulAdd(text_size
, kUnderlineOffset
, y
);
312 r
.fBottom
= r
.fTop
+ SkScalarMul(text_size
, kLineThickness
);
314 canvas_skia_
->drawRect(r
, paint_
);
317 void SkiaTextRenderer::DrawStrike(int x
, int y
, int width
) const {
318 const SkScalar text_size
= paint_
.getTextSize();
319 const SkScalar height
= SkScalarMul(text_size
, kLineThickness
);
320 const SkScalar offset
= SkScalarMulAdd(text_size
, kStrikeThroughOffset
, y
);
321 const SkRect r
= SkRect::MakeLTRB(x
, offset
, x
+ width
, offset
+ height
);
322 canvas_skia_
->drawRect(r
, paint_
);
325 SkiaTextRenderer::DiagonalStrike::DiagonalStrike(Canvas
* canvas
,
327 const SkPaint
& paint
)
334 SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() {
337 void SkiaTextRenderer::DiagonalStrike::AddPiece(int length
, SkColor color
) {
338 pieces_
.push_back(Piece(length
, color
));
339 total_length_
+= length
;
342 void SkiaTextRenderer::DiagonalStrike::Draw() {
343 const SkScalar text_size
= paint_
.getTextSize();
344 const SkScalar offset
= SkScalarMul(text_size
, kDiagonalStrikeMarginOffset
);
345 const int thickness
=
346 SkScalarCeilToInt(SkScalarMul(text_size
, kLineThickness
) * 2);
347 const int height
= SkScalarCeilToInt(text_size
- offset
);
348 const Point end
= start_
+ Vector2d(total_length_
, -height
);
349 const int clip_height
= height
+ 2 * thickness
;
351 paint_
.setAntiAlias(true);
352 paint_
.setStrokeWidth(thickness
);
354 const bool clipped
= pieces_
.size() > 1;
355 SkCanvas
* sk_canvas
= canvas_
->sk_canvas();
358 for (size_t i
= 0; i
< pieces_
.size(); ++i
) {
359 paint_
.setColor(pieces_
[i
].second
);
363 sk_canvas
->clipRect(RectToSkRect(
364 Rect(x
, end
.y() - thickness
, pieces_
[i
].first
, clip_height
)));
367 canvas_
->DrawLine(start_
, end
, paint_
);
372 x
+= pieces_
[i
].first
;
376 StyleIterator::StyleIterator(const BreakList
<SkColor
>& colors
,
377 const std::vector
<BreakList
<bool> >& styles
)
380 color_
= colors_
.breaks().begin();
381 for (size_t i
= 0; i
< styles_
.size(); ++i
)
382 style_
.push_back(styles_
[i
].breaks().begin());
385 StyleIterator::~StyleIterator() {}
387 Range
StyleIterator::GetRange() const {
388 Range
range(colors_
.GetRange(color_
));
389 for (size_t i
= 0; i
< NUM_TEXT_STYLES
; ++i
)
390 range
= range
.Intersect(styles_
[i
].GetRange(style_
[i
]));
394 void StyleIterator::UpdatePosition(size_t position
) {
395 color_
= colors_
.GetBreak(position
);
396 for (size_t i
= 0; i
< NUM_TEXT_STYLES
; ++i
)
397 style_
[i
] = styles_
[i
].GetBreak(position
);
400 LineSegment::LineSegment() : run(0) {}
402 LineSegment::~LineSegment() {}
404 Line::Line() : preceding_heights(0), baseline(0) {}
408 skia::RefPtr
<SkTypeface
> CreateSkiaTypeface(const std::string
& family
,
410 SkTypeface::Style skia_style
= ConvertFontStyleToSkiaTypefaceStyle(style
);
411 return skia::AdoptRef(SkTypeface::CreateFromName(family
.c_str(), skia_style
));
414 void ApplyRenderParams(const FontRenderParams
& params
,
415 bool background_is_transparent
,
417 paint
->setAntiAlias(params
.antialiasing
);
418 paint
->setLCDRenderText(!background_is_transparent
&&
419 params
.subpixel_rendering
!= FontRenderParams::SUBPIXEL_RENDERING_NONE
);
420 paint
->setSubpixelText(params
.subpixel_positioning
);
421 paint
->setAutohinted(params
.autohinter
);
422 paint
->setHinting(FontRenderParamsHintingToSkPaintHinting(params
.hinting
));
425 } // namespace internal
427 RenderText::~RenderText() {
430 RenderText
* RenderText::CreateInstance() {
431 #if defined(OS_MACOSX) && defined(TOOLKIT_VIEWS)
432 // Use the more complete HarfBuzz implementation for Views controls on Mac.
433 return new RenderTextHarfBuzz
;
435 if (CommandLine::ForCurrentProcess()->HasSwitch(
436 switches::kEnableHarfBuzzRenderText
)) {
437 return new RenderTextHarfBuzz
;
439 return CreateNativeInstance();
443 void RenderText::SetText(const base::string16
& text
) {
444 DCHECK(!composition_range_
.IsValid());
449 // Adjust ranged styles and colors to accommodate a new text length.
450 const size_t text_length
= text_
.length();
451 colors_
.SetMax(text_length
);
452 for (size_t style
= 0; style
< NUM_TEXT_STYLES
; ++style
)
453 styles_
[style
].SetMax(text_length
);
454 cached_bounds_and_offset_valid_
= false;
456 // Reset selection model. SetText should always followed by SetSelectionModel
457 // or SetCursorPosition in upper layer.
458 SetSelectionModel(SelectionModel());
460 // Invalidate the cached text direction if it depends on the text contents.
461 if (directionality_mode_
== DIRECTIONALITY_FROM_TEXT
)
462 text_direction_
= base::i18n::UNKNOWN_DIRECTION
;
464 obscured_reveal_index_
= -1;
468 void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment
) {
469 if (horizontal_alignment_
!= alignment
) {
470 horizontal_alignment_
= alignment
;
471 display_offset_
= Vector2d();
472 cached_bounds_and_offset_valid_
= false;
476 void RenderText::SetFontList(const FontList
& font_list
) {
477 font_list_
= font_list
;
478 const int font_style
= font_list
.GetFontStyle();
479 SetStyle(BOLD
, (font_style
& gfx::Font::BOLD
) != 0);
480 SetStyle(ITALIC
, (font_style
& gfx::Font::ITALIC
) != 0);
481 SetStyle(UNDERLINE
, (font_style
& gfx::Font::UNDERLINE
) != 0);
482 baseline_
= kInvalidBaseline
;
483 cached_bounds_and_offset_valid_
= false;
487 void RenderText::SetCursorEnabled(bool cursor_enabled
) {
488 cursor_enabled_
= cursor_enabled
;
489 cached_bounds_and_offset_valid_
= false;
492 void RenderText::ToggleInsertMode() {
493 insert_mode_
= !insert_mode_
;
494 cached_bounds_and_offset_valid_
= false;
497 void RenderText::SetObscured(bool obscured
) {
498 if (obscured
!= obscured_
) {
499 obscured_
= obscured
;
500 obscured_reveal_index_
= -1;
501 cached_bounds_and_offset_valid_
= false;
506 void RenderText::SetObscuredRevealIndex(int index
) {
507 if (obscured_reveal_index_
== index
)
510 obscured_reveal_index_
= index
;
511 cached_bounds_and_offset_valid_
= false;
515 void RenderText::SetReplaceNewlineCharsWithSymbols(bool replace
) {
516 replace_newline_chars_with_symbols_
= replace
;
517 cached_bounds_and_offset_valid_
= false;
521 void RenderText::SetMultiline(bool multiline
) {
522 if (multiline
!= multiline_
) {
523 multiline_
= multiline
;
524 cached_bounds_and_offset_valid_
= false;
529 void RenderText::SetElideBehavior(ElideBehavior elide_behavior
) {
530 // TODO(skanuj) : Add a test for triggering layout change.
531 if (elide_behavior_
!= elide_behavior
) {
532 elide_behavior_
= elide_behavior
;
537 void RenderText::SetDisplayRect(const Rect
& r
) {
538 if (r
!= display_rect_
) {
540 baseline_
= kInvalidBaseline
;
541 cached_bounds_and_offset_valid_
= false;
543 if (elide_behavior_
!= NO_ELIDE
)
548 void RenderText::SetCursorPosition(size_t position
) {
549 MoveCursorTo(position
, false);
552 void RenderText::MoveCursor(BreakType break_type
,
553 VisualCursorDirection direction
,
555 SelectionModel
cursor(cursor_position(), selection_model_
.caret_affinity());
556 // Cancelling a selection moves to the edge of the selection.
557 if (break_type
!= LINE_BREAK
&& !selection().is_empty() && !select
) {
558 SelectionModel selection_start
= GetSelectionModelForSelectionStart();
559 int start_x
= GetCursorBounds(selection_start
, true).x();
560 int cursor_x
= GetCursorBounds(cursor
, true).x();
561 // Use the selection start if it is left (when |direction| is CURSOR_LEFT)
562 // or right (when |direction| is CURSOR_RIGHT) of the selection end.
563 if (direction
== CURSOR_RIGHT
? start_x
> cursor_x
: start_x
< cursor_x
)
564 cursor
= selection_start
;
565 // Use the nearest word boundary in the proper |direction| for word breaks.
566 if (break_type
== WORD_BREAK
)
567 cursor
= GetAdjacentSelectionModel(cursor
, break_type
, direction
);
568 // Use an adjacent selection model if the cursor is not at a valid position.
569 if (!IsValidCursorIndex(cursor
.caret_pos()))
570 cursor
= GetAdjacentSelectionModel(cursor
, CHARACTER_BREAK
, direction
);
572 cursor
= GetAdjacentSelectionModel(cursor
, break_type
, direction
);
575 cursor
.set_selection_start(selection().start());
576 MoveCursorTo(cursor
);
579 bool RenderText::MoveCursorTo(const SelectionModel
& model
) {
580 // Enforce valid selection model components.
581 size_t text_length
= text().length();
582 Range
range(std::min(model
.selection().start(), text_length
),
583 std::min(model
.caret_pos(), text_length
));
584 // The current model only supports caret positions at valid cursor indices.
585 if (!IsValidCursorIndex(range
.start()) || !IsValidCursorIndex(range
.end()))
587 SelectionModel
sel(range
, model
.caret_affinity());
588 bool changed
= sel
!= selection_model_
;
589 SetSelectionModel(sel
);
593 bool RenderText::SelectRange(const Range
& range
) {
594 Range
sel(std::min(range
.start(), text().length()),
595 std::min(range
.end(), text().length()));
596 // Allow selection bounds at valid indicies amid multi-character graphemes.
597 if (!IsValidLogicalIndex(sel
.start()) || !IsValidLogicalIndex(sel
.end()))
599 LogicalCursorDirection affinity
=
600 (sel
.is_reversed() || sel
.is_empty()) ? CURSOR_FORWARD
: CURSOR_BACKWARD
;
601 SetSelectionModel(SelectionModel(sel
, affinity
));
605 bool RenderText::IsPointInSelection(const Point
& point
) {
606 if (selection().is_empty())
608 SelectionModel cursor
= FindCursorPosition(point
);
609 return RangeContainsCaret(
610 selection(), cursor
.caret_pos(), cursor
.caret_affinity());
613 void RenderText::ClearSelection() {
614 SetSelectionModel(SelectionModel(cursor_position(),
615 selection_model_
.caret_affinity()));
618 void RenderText::SelectAll(bool reversed
) {
619 const size_t length
= text().length();
620 const Range all
= reversed
? Range(length
, 0) : Range(0, length
);
621 const bool success
= SelectRange(all
);
625 void RenderText::SelectWord() {
631 size_t selection_max
= selection().GetMax();
633 base::i18n::BreakIterator
iter(text(), base::i18n::BreakIterator::BREAK_WORD
);
634 bool success
= iter
.Init();
639 size_t selection_min
= selection().GetMin();
640 if (selection_min
== text().length() && selection_min
!= 0)
643 for (; selection_min
!= 0; --selection_min
) {
644 if (iter
.IsStartOfWord(selection_min
) ||
645 iter
.IsEndOfWord(selection_min
))
649 if (selection_min
== selection_max
&& selection_max
!= text().length())
652 for (; selection_max
< text().length(); ++selection_max
)
653 if (iter
.IsEndOfWord(selection_max
) || iter
.IsStartOfWord(selection_max
))
656 const bool reversed
= selection().is_reversed();
657 MoveCursorTo(reversed
? selection_max
: selection_min
, false);
658 MoveCursorTo(reversed
? selection_min
: selection_max
, true);
661 const Range
& RenderText::GetCompositionRange() const {
662 return composition_range_
;
665 void RenderText::SetCompositionRange(const Range
& composition_range
) {
666 CHECK(!composition_range
.IsValid() ||
667 Range(0, text_
.length()).Contains(composition_range
));
668 composition_range_
.set_end(composition_range
.end());
669 composition_range_
.set_start(composition_range
.start());
673 void RenderText::SetColor(SkColor value
) {
674 colors_
.SetValue(value
);
677 // TODO(msw): Windows applies colors and decorations in the layout process.
678 cached_bounds_and_offset_valid_
= false;
683 void RenderText::ApplyColor(SkColor value
, const Range
& range
) {
684 colors_
.ApplyValue(value
, range
);
687 // TODO(msw): Windows applies colors and decorations in the layout process.
688 cached_bounds_and_offset_valid_
= false;
693 void RenderText::SetStyle(TextStyle style
, bool value
) {
694 styles_
[style
].SetValue(value
);
696 // Only invalidate the layout on font changes; not for colors or decorations.
697 bool invalidate
= (style
== BOLD
) || (style
== ITALIC
);
699 // TODO(msw): Windows applies colors and decorations in the layout process.
703 cached_bounds_and_offset_valid_
= false;
708 void RenderText::ApplyStyle(TextStyle style
, bool value
, const Range
& range
) {
709 styles_
[style
].ApplyValue(value
, range
);
711 // Only invalidate the layout on font changes; not for colors or decorations.
712 bool invalidate
= (style
== BOLD
) || (style
== ITALIC
);
714 // TODO(msw): Windows applies colors and decorations in the layout process.
718 cached_bounds_and_offset_valid_
= false;
723 bool RenderText::GetStyle(TextStyle style
) const {
724 return (styles_
[style
].breaks().size() == 1) &&
725 styles_
[style
].breaks().front().second
;
728 void RenderText::SetDirectionalityMode(DirectionalityMode mode
) {
729 if (mode
== directionality_mode_
)
732 directionality_mode_
= mode
;
733 text_direction_
= base::i18n::UNKNOWN_DIRECTION
;
734 cached_bounds_and_offset_valid_
= false;
738 base::i18n::TextDirection
RenderText::GetTextDirection() {
739 if (text_direction_
== base::i18n::UNKNOWN_DIRECTION
) {
740 switch (directionality_mode_
) {
741 case DIRECTIONALITY_FROM_TEXT
:
742 // Derive the direction from the display text, which differs from text()
743 // in the case of obscured (password) textfields.
745 base::i18n::GetFirstStrongCharacterDirection(GetLayoutText());
747 case DIRECTIONALITY_FROM_UI
:
748 text_direction_
= base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT
:
749 base::i18n::LEFT_TO_RIGHT
;
751 case DIRECTIONALITY_FORCE_LTR
:
752 text_direction_
= base::i18n::LEFT_TO_RIGHT
;
754 case DIRECTIONALITY_FORCE_RTL
:
755 text_direction_
= base::i18n::RIGHT_TO_LEFT
;
762 return text_direction_
;
765 VisualCursorDirection
RenderText::GetVisualDirectionOfLogicalEnd() {
766 return GetTextDirection() == base::i18n::LEFT_TO_RIGHT
?
767 CURSOR_RIGHT
: CURSOR_LEFT
;
770 SizeF
RenderText::GetStringSizeF() {
771 const Size size
= GetStringSize();
772 return SizeF(size
.width(), size
.height());
775 float RenderText::GetContentWidth() {
776 return GetStringSizeF().width() + (cursor_enabled_
? 1 : 0);
779 int RenderText::GetBaseline() {
780 if (baseline_
== kInvalidBaseline
)
781 baseline_
= DetermineBaselineCenteringText(display_rect(), font_list());
782 DCHECK_NE(kInvalidBaseline
, baseline_
);
786 void RenderText::Draw(Canvas
* canvas
) {
789 if (clip_to_display_rect()) {
790 Rect
clip_rect(display_rect());
791 clip_rect
.Inset(ShadowValue::GetMargin(shadows_
));
794 canvas
->ClipRect(clip_rect
);
797 if (!text().empty() && focused())
798 DrawSelection(canvas
);
800 if (cursor_enabled() && cursor_visible() && focused())
801 DrawCursor(canvas
, selection_model_
);
804 DrawVisualText(canvas
);
806 if (clip_to_display_rect())
810 void RenderText::DrawCursor(Canvas
* canvas
, const SelectionModel
& position
) {
811 // Paint cursor. Replace cursor is drawn as rectangle for now.
812 // TODO(msw): Draw a better cursor with a better indication of association.
813 canvas
->FillRect(GetCursorBounds(position
, true), cursor_color_
);
816 bool RenderText::IsValidLogicalIndex(size_t index
) {
817 // Check that the index is at a valid code point (not mid-surrgate-pair) and
818 // that it's not truncated from the layout text (its glyph may be shown).
820 // Indices within truncated text are disallowed so users can easily interact
821 // with the underlying truncated text using the ellipsis as a proxy. This lets
822 // users select all text, select the truncated text, and transition from the
823 // last rendered glyph to the end of the text without getting invisible cursor
824 // positions nor needing unbounded arrow key presses to traverse the ellipsis.
825 return index
== 0 || index
== text().length() ||
826 (index
< text().length() &&
827 (truncate_length_
== 0 || index
< truncate_length_
) &&
828 IsValidCodePointIndex(text(), index
));
831 Rect
RenderText::GetCursorBounds(const SelectionModel
& caret
,
833 // TODO(ckocagil): Support multiline. This function should return the height
834 // of the line the cursor is on. |GetStringSize()| now returns
835 // the multiline size, eliminate its use here.
838 size_t caret_pos
= caret
.caret_pos();
839 DCHECK(IsValidLogicalIndex(caret_pos
));
840 // In overtype mode, ignore the affinity and always indicate that we will
841 // overtype the next character.
842 LogicalCursorDirection caret_affinity
=
843 insert_mode
? caret
.caret_affinity() : CURSOR_FORWARD
;
844 int x
= 0, width
= 1;
845 Size size
= GetStringSize();
846 if (caret_pos
== (caret_affinity
== CURSOR_BACKWARD
? 0 : text().length())) {
847 // The caret is attached to the boundary. Always return a 1-dip width caret,
848 // since there is nothing to overtype.
849 if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT
) == (caret_pos
== 0))
852 size_t grapheme_start
= (caret_affinity
== CURSOR_FORWARD
) ?
853 caret_pos
: IndexOfAdjacentGrapheme(caret_pos
, CURSOR_BACKWARD
);
854 Range
xspan(GetGlyphBounds(grapheme_start
));
856 x
= (caret_affinity
== CURSOR_BACKWARD
) ? xspan
.end() : xspan
.start();
857 } else { // overtype mode
859 width
= xspan
.length();
862 return Rect(ToViewPoint(Point(x
, 0)), Size(width
, size
.height()));
865 const Rect
& RenderText::GetUpdatedCursorBounds() {
866 UpdateCachedBoundsAndOffset();
867 return cursor_bounds_
;
870 size_t RenderText::IndexOfAdjacentGrapheme(size_t index
,
871 LogicalCursorDirection direction
) {
872 if (index
> text().length())
873 return text().length();
877 if (direction
== CURSOR_FORWARD
) {
878 while (index
< text().length()) {
880 if (IsValidCursorIndex(index
))
883 return text().length();
888 if (IsValidCursorIndex(index
))
894 SelectionModel
RenderText::GetSelectionModelForSelectionStart() {
895 const Range
& sel
= selection();
897 return selection_model_
;
898 return SelectionModel(sel
.start(),
899 sel
.is_reversed() ? CURSOR_BACKWARD
: CURSOR_FORWARD
);
902 const Vector2d
& RenderText::GetUpdatedDisplayOffset() {
903 UpdateCachedBoundsAndOffset();
904 return display_offset_
;
907 void RenderText::SetDisplayOffset(int horizontal_offset
) {
908 const int extra_content
= GetContentWidth() - display_rect_
.width();
909 const int cursor_width
= cursor_enabled_
? 1 : 0;
913 if (extra_content
> 0) {
914 switch (GetCurrentHorizontalAlignment()) {
916 min_offset
= -extra_content
;
919 max_offset
= extra_content
;
922 // The extra space reserved for cursor at the end of the text is ignored
923 // when centering text. So, to calculate the valid range for offset, we
924 // exclude that extra space, calculate the range, and add it back to the
925 // range (if cursor is enabled).
926 min_offset
= -(extra_content
- cursor_width
+ 1) / 2 - cursor_width
;
927 max_offset
= (extra_content
- cursor_width
) / 2;
933 if (horizontal_offset
< min_offset
)
934 horizontal_offset
= min_offset
;
935 else if (horizontal_offset
> max_offset
)
936 horizontal_offset
= max_offset
;
938 cached_bounds_and_offset_valid_
= true;
939 display_offset_
.set_x(horizontal_offset
);
940 cursor_bounds_
= GetCursorBounds(selection_model_
, insert_mode_
);
943 RenderText::RenderText()
944 : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT
: ALIGN_LEFT
),
945 directionality_mode_(DIRECTIONALITY_FROM_TEXT
),
946 text_direction_(base::i18n::UNKNOWN_DIRECTION
),
947 cursor_enabled_(true),
948 cursor_visible_(false),
950 cursor_color_(kDefaultColor
),
951 selection_color_(kDefaultColor
),
952 selection_background_focused_color_(kDefaultSelectionBackgroundColor
),
954 composition_range_(Range::InvalidRange()),
955 colors_(kDefaultColor
),
956 styles_(NUM_TEXT_STYLES
),
957 composition_and_selection_styles_applied_(false),
959 obscured_reveal_index_(-1),
961 elide_behavior_(NO_ELIDE
),
962 replace_newline_chars_with_symbols_(true),
964 background_is_transparent_(false),
965 clip_to_display_rect_(true),
966 baseline_(kInvalidBaseline
),
967 cached_bounds_and_offset_valid_(false) {
970 SelectionModel
RenderText::GetAdjacentSelectionModel(
971 const SelectionModel
& current
,
972 BreakType break_type
,
973 VisualCursorDirection direction
) {
976 if (break_type
== LINE_BREAK
|| text().empty())
977 return EdgeSelectionModel(direction
);
978 if (break_type
== CHARACTER_BREAK
)
979 return AdjacentCharSelectionModel(current
, direction
);
980 DCHECK(break_type
== WORD_BREAK
);
981 return AdjacentWordSelectionModel(current
, direction
);
984 SelectionModel
RenderText::EdgeSelectionModel(
985 VisualCursorDirection direction
) {
986 if (direction
== GetVisualDirectionOfLogicalEnd())
987 return SelectionModel(text().length(), CURSOR_FORWARD
);
988 return SelectionModel(0, CURSOR_BACKWARD
);
991 void RenderText::SetSelectionModel(const SelectionModel
& model
) {
992 DCHECK_LE(model
.selection().GetMax(), text().length());
993 selection_model_
= model
;
994 cached_bounds_and_offset_valid_
= false;
997 const base::string16
& RenderText::GetLayoutText() const {
1001 const BreakList
<size_t>& RenderText::GetLineBreaks() {
1002 if (line_breaks_
.max() != 0)
1003 return line_breaks_
;
1005 const base::string16
& layout_text
= GetLayoutText();
1006 const size_t text_length
= layout_text
.length();
1007 line_breaks_
.SetValue(0);
1008 line_breaks_
.SetMax(text_length
);
1009 base::i18n::BreakIterator
iter(layout_text
,
1010 base::i18n::BreakIterator::BREAK_LINE
);
1011 const bool success
= iter
.Init();
1015 line_breaks_
.ApplyValue(iter
.pos(), Range(iter
.pos(), text_length
));
1016 } while (iter
.Advance());
1018 return line_breaks_
;
1021 void RenderText::ApplyCompositionAndSelectionStyles() {
1022 // Save the underline and color breaks to undo the temporary styles later.
1023 DCHECK(!composition_and_selection_styles_applied_
);
1024 saved_colors_
= colors_
;
1025 saved_underlines_
= styles_
[UNDERLINE
];
1027 // Apply an underline to the composition range in |underlines|.
1028 if (composition_range_
.IsValid() && !composition_range_
.is_empty())
1029 styles_
[UNDERLINE
].ApplyValue(true, composition_range_
);
1031 // Apply the selected text color to the [un-reversed] selection range.
1032 if (!selection().is_empty() && focused()) {
1033 const Range
range(selection().GetMin(), selection().GetMax());
1034 colors_
.ApplyValue(selection_color_
, range
);
1036 composition_and_selection_styles_applied_
= true;
1039 void RenderText::UndoCompositionAndSelectionStyles() {
1040 // Restore the underline and color breaks to undo the temporary styles.
1041 DCHECK(composition_and_selection_styles_applied_
);
1042 colors_
= saved_colors_
;
1043 styles_
[UNDERLINE
] = saved_underlines_
;
1044 composition_and_selection_styles_applied_
= false;
1047 Vector2d
RenderText::GetLineOffset(size_t line_number
) {
1048 Vector2d offset
= display_rect().OffsetFromOrigin();
1049 // TODO(ckocagil): Apply the display offset for multiline scrolling.
1051 offset
.Add(GetUpdatedDisplayOffset());
1053 offset
.Add(Vector2d(0, lines_
[line_number
].preceding_heights
));
1054 offset
.Add(GetAlignmentOffset(line_number
));
1058 Point
RenderText::ToTextPoint(const Point
& point
) {
1059 return point
- GetLineOffset(0);
1060 // TODO(ckocagil): Convert multiline view space points to text space.
1063 Point
RenderText::ToViewPoint(const Point
& point
) {
1065 return point
+ GetLineOffset(0);
1067 // TODO(ckocagil): Traverse individual line segments for RTL support.
1068 DCHECK(!lines_
.empty());
1071 for (; line
< lines_
.size() && x
> lines_
[line
].size
.width(); ++line
)
1072 x
-= lines_
[line
].size
.width();
1073 return Point(x
, point
.y()) + GetLineOffset(line
);
1076 std::vector
<Rect
> RenderText::TextBoundsToViewBounds(const Range
& x
) {
1077 std::vector
<Rect
> rects
;
1080 rects
.push_back(Rect(ToViewPoint(Point(x
.GetMin(), 0)),
1081 Size(x
.length(), GetStringSize().height())));
1087 // Each line segment keeps its position in text coordinates. Traverse all line
1088 // segments and if the segment intersects with the given range, add the view
1089 // rect corresponding to the intersection to |rects|.
1090 for (size_t line
= 0; line
< lines_
.size(); ++line
) {
1092 const Vector2d offset
= GetLineOffset(line
);
1093 for (size_t i
= 0; i
< lines_
[line
].segments
.size(); ++i
) {
1094 const internal::LineSegment
* segment
= &lines_
[line
].segments
[i
];
1095 const Range intersection
= segment
->x_range
.Intersect(x
);
1096 if (!intersection
.is_empty()) {
1097 Rect
rect(line_x
+ intersection
.start() - segment
->x_range
.start(),
1098 0, intersection
.length(), lines_
[line
].size
.height());
1099 rects
.push_back(rect
+ offset
);
1101 line_x
+= segment
->x_range
.length();
1108 HorizontalAlignment
RenderText::GetCurrentHorizontalAlignment() {
1109 if (horizontal_alignment_
!= ALIGN_TO_HEAD
)
1110 return horizontal_alignment_
;
1111 return GetTextDirection() == base::i18n::RIGHT_TO_LEFT
? ALIGN_RIGHT
1115 Vector2d
RenderText::GetAlignmentOffset(size_t line_number
) {
1116 // TODO(ckocagil): Enable |lines_| usage in other platforms.
1118 DCHECK_LT(line_number
, lines_
.size());
1121 HorizontalAlignment horizontal_alignment
= GetCurrentHorizontalAlignment();
1122 if (horizontal_alignment
!= ALIGN_LEFT
) {
1124 const int width
= lines_
[line_number
].size
.width() +
1125 (cursor_enabled_
? 1 : 0);
1127 const int width
= GetContentWidth();
1129 offset
.set_x(display_rect().width() - width
);
1130 // Put any extra margin pixel on the left to match legacy behavior.
1131 if (horizontal_alignment
== ALIGN_CENTER
)
1132 offset
.set_x((offset
.x() + 1) / 2);
1135 // Vertically center the text.
1137 const int text_height
= lines_
.back().preceding_heights
+
1138 lines_
.back().size
.height();
1139 offset
.set_y((display_rect_
.height() - text_height
) / 2);
1141 offset
.set_y(GetBaseline() - GetLayoutTextBaseline());
1147 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer
* renderer
) {
1148 const int width
= display_rect().width();
1149 if (multiline() || elide_behavior_
!= FADE_TAIL
|| GetContentWidth() <= width
)
1152 const int gradient_width
= CalculateFadeGradientWidth(font_list(), width
);
1153 if (gradient_width
== 0)
1156 HorizontalAlignment horizontal_alignment
= GetCurrentHorizontalAlignment();
1157 Rect solid_part
= display_rect();
1160 if (horizontal_alignment
!= ALIGN_LEFT
) {
1161 left_part
= solid_part
;
1162 left_part
.Inset(0, 0, solid_part
.width() - gradient_width
, 0);
1163 solid_part
.Inset(gradient_width
, 0, 0, 0);
1165 if (horizontal_alignment
!= ALIGN_RIGHT
) {
1166 right_part
= solid_part
;
1167 right_part
.Inset(solid_part
.width() - gradient_width
, 0, 0, 0);
1168 solid_part
.Inset(0, 0, gradient_width
, 0);
1171 Rect text_rect
= display_rect();
1172 text_rect
.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1174 // TODO(msw): Use the actual text colors corresponding to each faded part.
1175 skia::RefPtr
<SkShader
> shader
= CreateFadeShader(
1176 text_rect
, left_part
, right_part
, colors_
.breaks().front().second
);
1178 renderer
->SetShader(shader
.get(), display_rect());
1181 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer
* renderer
) {
1182 skia::RefPtr
<SkDrawLooper
> looper
= CreateShadowDrawLooper(shadows_
);
1183 renderer
->SetDrawLooper(looper
.get());
1187 bool RenderText::RangeContainsCaret(const Range
& range
,
1189 LogicalCursorDirection caret_affinity
) {
1190 // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1191 size_t adjacent
= (caret_affinity
== CURSOR_BACKWARD
) ?
1192 caret_pos
- 1 : caret_pos
+ 1;
1193 return range
.Contains(Range(caret_pos
, adjacent
));
1196 void RenderText::MoveCursorTo(size_t position
, bool select
) {
1197 size_t cursor
= std::min(position
, text().length());
1198 if (IsValidCursorIndex(cursor
))
1199 SetSelectionModel(SelectionModel(
1200 Range(select
? selection().start() : cursor
, cursor
),
1201 (cursor
== 0) ? CURSOR_FORWARD
: CURSOR_BACKWARD
));
1204 void RenderText::UpdateLayoutText() {
1205 layout_text_
.clear();
1206 line_breaks_
.SetMax(0);
1209 size_t obscured_text_length
=
1210 static_cast<size_t>(UTF16IndexToOffset(text_
, 0, text_
.length()));
1211 layout_text_
.assign(obscured_text_length
, kPasswordReplacementChar
);
1213 if (obscured_reveal_index_
>= 0 &&
1214 obscured_reveal_index_
< static_cast<int>(text_
.length())) {
1215 // Gets the index range in |text_| to be revealed.
1216 size_t start
= obscured_reveal_index_
;
1217 U16_SET_CP_START(text_
.data(), 0, start
);
1219 UChar32 unused_char
;
1220 U16_NEXT(text_
.data(), end
, text_
.length(), unused_char
);
1222 // Gets the index in |layout_text_| to be replaced.
1223 const size_t cp_start
=
1224 static_cast<size_t>(UTF16IndexToOffset(text_
, 0, start
));
1225 if (layout_text_
.length() > cp_start
)
1226 layout_text_
.replace(cp_start
, 1, text_
.substr(start
, end
- start
));
1229 layout_text_
= text_
;
1232 const base::string16
& text
= layout_text_
;
1233 if (truncate_length_
> 0 && truncate_length_
< text
.length()) {
1234 // Truncate the text at a valid character break and append an ellipsis.
1235 icu::StringCharacterIterator
iter(text
.c_str());
1236 // Respect ELIDE_HEAD and ELIDE_MIDDLE preferences during truncation.
1237 if (elide_behavior_
== ELIDE_HEAD
) {
1238 iter
.setIndex32(text
.length() - truncate_length_
+ 1);
1239 layout_text_
.assign(kEllipsisUTF16
+ text
.substr(iter
.getIndex()));
1240 } else if (elide_behavior_
== ELIDE_MIDDLE
) {
1241 iter
.setIndex32(truncate_length_
/ 2);
1242 const size_t ellipsis_start
= iter
.getIndex();
1243 iter
.setIndex32(text
.length() - (truncate_length_
/ 2));
1244 const size_t ellipsis_end
= iter
.getIndex();
1245 DCHECK_LE(ellipsis_start
, ellipsis_end
);
1246 layout_text_
.assign(text
.substr(0, ellipsis_start
) + kEllipsisUTF16
+
1247 text
.substr(ellipsis_end
));
1249 iter
.setIndex32(truncate_length_
- 1);
1250 layout_text_
.assign(text
.substr(0, iter
.getIndex()) + kEllipsisUTF16
);
1254 if (elide_behavior_
!= NO_ELIDE
&& elide_behavior_
!= FADE_TAIL
&&
1255 !layout_text_
.empty() && GetContentWidth() > display_rect_
.width()) {
1256 // This doesn't trim styles so ellipsis may get rendered as a different
1257 // style than the preceding text. See crbug.com/327850.
1258 layout_text_
.assign(
1259 Elide(layout_text_
, display_rect_
.width(), elide_behavior_
));
1262 // Replace the newline character with a newline symbol in single line mode.
1263 static const base::char16 kNewline
[] = { '\n', 0 };
1264 static const base::char16 kNewlineSymbol
[] = { 0x2424, 0 };
1265 if (!multiline_
&& replace_newline_chars_with_symbols_
)
1266 base::ReplaceChars(layout_text_
, kNewline
, kNewlineSymbol
, &layout_text_
);
1271 base::string16
RenderText::Elide(const base::string16
& text
,
1272 float available_width
,
1273 ElideBehavior behavior
) {
1274 if (available_width
<= 0 || text
.empty())
1275 return base::string16();
1276 if (behavior
== ELIDE_EMAIL
)
1277 return ElideEmail(text
, available_width
);
1279 // Create a RenderText copy with attributes that affect the rendering width.
1280 scoped_ptr
<RenderText
> render_text(CreateInstance());
1281 render_text
->SetFontList(font_list_
);
1282 render_text
->SetDirectionalityMode(directionality_mode_
);
1283 render_text
->SetCursorEnabled(cursor_enabled_
);
1284 render_text
->set_truncate_length(truncate_length_
);
1285 render_text
->styles_
= styles_
;
1286 render_text
->colors_
= colors_
;
1287 render_text
->SetText(text
);
1288 if (render_text
->GetContentWidth() <= available_width
)
1291 const base::string16 ellipsis
= base::string16(kEllipsisUTF16
);
1292 const bool insert_ellipsis
= (behavior
!= TRUNCATE
);
1293 const bool elide_in_middle
= (behavior
== ELIDE_MIDDLE
);
1294 const bool elide_at_beginning
= (behavior
== ELIDE_HEAD
);
1295 StringSlicer
slicer(text
, ellipsis
, elide_in_middle
, elide_at_beginning
);
1297 render_text
->SetText(ellipsis
);
1298 const float ellipsis_width
= render_text
->GetContentWidth();
1300 if (insert_ellipsis
&& (ellipsis_width
> available_width
))
1301 return base::string16();
1303 // Use binary search to compute the elided text.
1305 size_t hi
= text
.length() - 1;
1306 const base::i18n::TextDirection text_direction
= GetTextDirection();
1307 for (size_t guess
= (lo
+ hi
) / 2; lo
<= hi
; guess
= (lo
+ hi
) / 2) {
1308 // Restore styles and colors. They will be truncated to size by SetText.
1309 render_text
->styles_
= styles_
;
1310 render_text
->colors_
= colors_
;
1311 base::string16 new_text
=
1312 slicer
.CutString(guess
, insert_ellipsis
&& behavior
!= ELIDE_TAIL
);
1313 render_text
->SetText(new_text
);
1315 // This has to be an additional step so that the ellipsis is rendered with
1316 // same style as trailing part of the text.
1317 if (insert_ellipsis
&& behavior
== ELIDE_TAIL
) {
1318 // When ellipsis follows text whose directionality is not the same as that
1319 // of the whole text, it will be rendered with the directionality of the
1320 // whole text. Since we want ellipsis to indicate continuation of the
1321 // preceding text, we force the directionality of ellipsis to be same as
1322 // the preceding text using LTR or RTL markers.
1323 base::i18n::TextDirection trailing_text_direction
=
1324 base::i18n::GetLastStrongCharacterDirection(new_text
);
1325 new_text
.append(ellipsis
);
1326 if (trailing_text_direction
!= text_direction
) {
1327 if (trailing_text_direction
== base::i18n::LEFT_TO_RIGHT
)
1328 new_text
+= base::i18n::kLeftToRightMark
;
1330 new_text
+= base::i18n::kRightToLeftMark
;
1332 render_text
->SetText(new_text
);
1335 // We check the width of the whole desired string at once to ensure we
1336 // handle kerning/ligatures/etc. correctly.
1337 const float guess_width
= render_text
->GetContentWidth();
1338 if (guess_width
== available_width
)
1340 if (guess_width
> available_width
) {
1342 // Move back on the loop terminating condition when the guess is too wide.
1350 return render_text
->text();
1353 base::string16
RenderText::ElideEmail(const base::string16
& email
,
1354 float available_width
) {
1355 // The returned string will have at least one character besides the ellipsis
1356 // on either side of '@'; if that's impossible, a single ellipsis is returned.
1357 // If possible, only the username is elided. Otherwise, the domain is elided
1358 // in the middle, splitting available width equally with the elided username.
1359 // If the username is short enough that it doesn't need half the available
1360 // width, the elided domain will occupy that extra width.
1362 // Split the email into its local-part (username) and domain-part. The email
1363 // spec allows for @ symbols in the username under some special requirements,
1364 // but not in the domain part, so splitting at the last @ symbol is safe.
1365 const size_t split_index
= email
.find_last_of('@');
1366 DCHECK_NE(split_index
, base::string16::npos
);
1367 base::string16 username
= email
.substr(0, split_index
);
1368 base::string16 domain
= email
.substr(split_index
+ 1);
1369 DCHECK(!username
.empty());
1370 DCHECK(!domain
.empty());
1372 // Subtract the @ symbol from the available width as it is mandatory.
1373 const base::string16 kAtSignUTF16
= base::ASCIIToUTF16("@");
1374 available_width
-= GetStringWidthF(kAtSignUTF16
, font_list());
1376 // Check whether eliding the domain is necessary: if eliding the username
1377 // is sufficient, the domain will not be elided.
1378 const float full_username_width
= GetStringWidthF(username
, font_list());
1379 const float available_domain_width
= available_width
-
1380 std::min(full_username_width
,
1381 GetStringWidthF(username
.substr(0, 1) + kEllipsisUTF16
, font_list()));
1382 if (GetStringWidthF(domain
, font_list()) > available_domain_width
) {
1383 // Elide the domain so that it only takes half of the available width.
1384 // Should the username not need all the width available in its half, the
1385 // domain will occupy the leftover width.
1386 // If |desired_domain_width| is greater than |available_domain_width|: the
1387 // minimal username elision allowed by the specifications will not fit; thus
1388 // |desired_domain_width| must be <= |available_domain_width| at all cost.
1389 const float desired_domain_width
=
1390 std::min
<float>(available_domain_width
,
1391 std::max
<float>(available_width
- full_username_width
,
1392 available_width
/ 2));
1393 domain
= Elide(domain
, desired_domain_width
, ELIDE_MIDDLE
);
1394 // Failing to elide the domain such that at least one character remains
1395 // (other than the ellipsis itself) remains: return a single ellipsis.
1396 if (domain
.length() <= 1U)
1397 return base::string16(kEllipsisUTF16
);
1400 // Fit the username in the remaining width (at this point the elided username
1401 // is guaranteed to fit with at least one character remaining given all the
1402 // precautions taken earlier).
1403 available_width
-= GetStringWidthF(domain
, font_list());
1404 username
= Elide(username
, available_width
, ELIDE_TAIL
);
1405 return username
+ kAtSignUTF16
+ domain
;
1408 void RenderText::UpdateCachedBoundsAndOffset() {
1409 if (cached_bounds_and_offset_valid_
)
1412 // TODO(ckocagil): Add support for scrolling multiline text.
1416 if (cursor_enabled()) {
1417 // When cursor is enabled, ensure it is visible. For this, set the valid
1418 // flag true and calculate the current cursor bounds using the stale
1419 // |display_offset_|. Then calculate the change in offset needed to move the
1420 // cursor into the visible area.
1421 cached_bounds_and_offset_valid_
= true;
1422 cursor_bounds_
= GetCursorBounds(selection_model_
, insert_mode_
);
1424 // TODO(bidi): Show RTL glyphs at the cursor position for ALIGN_LEFT, etc.
1425 if (cursor_bounds_
.right() > display_rect_
.right())
1426 delta_x
= display_rect_
.right() - cursor_bounds_
.right();
1427 else if (cursor_bounds_
.x() < display_rect_
.x())
1428 delta_x
= display_rect_
.x() - cursor_bounds_
.x();
1431 SetDisplayOffset(display_offset_
.x() + delta_x
);
1434 void RenderText::DrawSelection(Canvas
* canvas
) {
1435 const std::vector
<Rect
> sel
= GetSubstringBounds(selection());
1436 for (std::vector
<Rect
>::const_iterator i
= sel
.begin(); i
< sel
.end(); ++i
)
1437 canvas
->FillRect(*i
, selection_background_focused_color_
);