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 paint_
.setAntiAlias(params
.antialiasing
);
217 paint_
.setLCDRenderText(!background_is_transparent
&&
218 params
.subpixel_rendering
!= FontRenderParams::SUBPIXEL_RENDERING_NONE
);
219 paint_
.setSubpixelText(params
.subpixel_positioning
);
220 paint_
.setAutohinted(params
.autohinter
);
221 paint_
.setHinting(FontRenderParamsHintingToSkPaintHinting(params
.hinting
));
224 void SkiaTextRenderer::SetTypeface(SkTypeface
* typeface
) {
225 paint_
.setTypeface(typeface
);
228 void SkiaTextRenderer::SetTextSize(SkScalar size
) {
229 paint_
.setTextSize(size
);
232 void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string
& family
,
234 DCHECK(!family
.empty());
236 skia::RefPtr
<SkTypeface
> typeface
= CreateSkiaTypeface(family
.c_str(), style
);
238 // |paint_| adds its own ref. So don't |release()| it from the ref ptr here.
239 SetTypeface(typeface
.get());
241 // Enable fake bold text if bold style is needed but new typeface does not
243 paint_
.setFakeBoldText((style
& Font::BOLD
) && !typeface
->isBold());
247 void SkiaTextRenderer::SetForegroundColor(SkColor foreground
) {
248 paint_
.setColor(foreground
);
251 void SkiaTextRenderer::SetShader(SkShader
* shader
, const Rect
& bounds
) {
252 bounds_
= RectToSkRect(bounds
);
253 paint_
.setShader(shader
);
256 void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness
,
258 underline_thickness_
= thickness
;
259 underline_position_
= position
;
262 void SkiaTextRenderer::DrawPosText(const SkPoint
* pos
,
263 const uint16
* glyphs
,
264 size_t glyph_count
) {
265 if (!started_drawing_
) {
266 started_drawing_
= true;
267 // Work-around for http://crbug.com/122743, where non-ClearType text is
268 // rendered with incorrect gamma when using the fade shader. Draw the text
269 // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode.
271 // Skip this when there is a looper which seems not working well with
272 // deferred paint. Currently a looper is only used for text shadows.
274 // TODO(asvitkine): Remove this work-around once the Skia bug is fixed.
275 // http://code.google.com/p/skia/issues/detail?id=590
276 if (!paint_
.isLCDRenderText() &&
277 paint_
.getShader() &&
278 !paint_
.getLooper()) {
279 deferred_fade_shader_
= skia::SharePtr(paint_
.getShader());
280 paint_
.setShader(NULL
);
281 canvas_skia_
->saveLayer(&bounds_
, NULL
);
285 const size_t byte_length
= glyph_count
* sizeof(glyphs
[0]);
286 canvas_skia_
->drawPosText(&glyphs
[0], byte_length
, &pos
[0], paint_
);
289 void SkiaTextRenderer::DrawDecorations(int x
, int y
, int width
, bool underline
,
290 bool strike
, bool diagonal_strike
) {
292 DrawUnderline(x
, y
, width
);
294 DrawStrike(x
, y
, width
);
295 if (diagonal_strike
) {
297 diagonal_
.reset(new DiagonalStrike(canvas_
, Point(x
, y
), paint_
));
298 diagonal_
->AddPiece(width
, paint_
.getColor());
299 } else if (diagonal_
) {
304 void SkiaTextRenderer::EndDiagonalStrike() {
311 void SkiaTextRenderer::DrawUnderline(int x
, int y
, int width
) {
312 SkRect r
= SkRect::MakeLTRB(x
, y
+ underline_position_
, x
+ width
,
313 y
+ underline_position_
+ underline_thickness_
);
314 if (underline_thickness_
== kUnderlineMetricsNotSet
) {
315 const SkScalar text_size
= paint_
.getTextSize();
316 r
.fTop
= SkScalarMulAdd(text_size
, kUnderlineOffset
, y
);
317 r
.fBottom
= r
.fTop
+ SkScalarMul(text_size
, kLineThickness
);
319 canvas_skia_
->drawRect(r
, paint_
);
322 void SkiaTextRenderer::DrawStrike(int x
, int y
, int width
) const {
323 const SkScalar text_size
= paint_
.getTextSize();
324 const SkScalar height
= SkScalarMul(text_size
, kLineThickness
);
325 const SkScalar offset
= SkScalarMulAdd(text_size
, kStrikeThroughOffset
, y
);
326 const SkRect r
= SkRect::MakeLTRB(x
, offset
, x
+ width
, offset
+ height
);
327 canvas_skia_
->drawRect(r
, paint_
);
330 SkiaTextRenderer::DiagonalStrike::DiagonalStrike(Canvas
* canvas
,
332 const SkPaint
& paint
)
339 SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() {
342 void SkiaTextRenderer::DiagonalStrike::AddPiece(int length
, SkColor color
) {
343 pieces_
.push_back(Piece(length
, color
));
344 total_length_
+= length
;
347 void SkiaTextRenderer::DiagonalStrike::Draw() {
348 const SkScalar text_size
= paint_
.getTextSize();
349 const SkScalar offset
= SkScalarMul(text_size
, kDiagonalStrikeMarginOffset
);
350 const int thickness
=
351 SkScalarCeilToInt(SkScalarMul(text_size
, kLineThickness
) * 2);
352 const int height
= SkScalarCeilToInt(text_size
- offset
);
353 const Point end
= start_
+ Vector2d(total_length_
, -height
);
354 const int clip_height
= height
+ 2 * thickness
;
356 paint_
.setAntiAlias(true);
357 paint_
.setStrokeWidth(thickness
);
359 const bool clipped
= pieces_
.size() > 1;
360 SkCanvas
* sk_canvas
= canvas_
->sk_canvas();
363 for (size_t i
= 0; i
< pieces_
.size(); ++i
) {
364 paint_
.setColor(pieces_
[i
].second
);
368 sk_canvas
->clipRect(RectToSkRect(
369 Rect(x
, end
.y() - thickness
, pieces_
[i
].first
, clip_height
)));
372 canvas_
->DrawLine(start_
, end
, paint_
);
377 x
+= pieces_
[i
].first
;
381 StyleIterator::StyleIterator(const BreakList
<SkColor
>& colors
,
382 const std::vector
<BreakList
<bool> >& styles
)
385 color_
= colors_
.breaks().begin();
386 for (size_t i
= 0; i
< styles_
.size(); ++i
)
387 style_
.push_back(styles_
[i
].breaks().begin());
390 StyleIterator::~StyleIterator() {}
392 Range
StyleIterator::GetRange() const {
393 Range
range(colors_
.GetRange(color_
));
394 for (size_t i
= 0; i
< NUM_TEXT_STYLES
; ++i
)
395 range
= range
.Intersect(styles_
[i
].GetRange(style_
[i
]));
399 void StyleIterator::UpdatePosition(size_t position
) {
400 color_
= colors_
.GetBreak(position
);
401 for (size_t i
= 0; i
< NUM_TEXT_STYLES
; ++i
)
402 style_
[i
] = styles_
[i
].GetBreak(position
);
405 LineSegment::LineSegment() : run(0) {}
407 LineSegment::~LineSegment() {}
409 Line::Line() : preceding_heights(0), baseline(0) {}
413 skia::RefPtr
<SkTypeface
> CreateSkiaTypeface(const std::string
& family
,
415 SkTypeface::Style skia_style
= ConvertFontStyleToSkiaTypefaceStyle(style
);
416 return skia::AdoptRef(SkTypeface::CreateFromName(family
.c_str(), skia_style
));
419 } // namespace internal
421 RenderText::~RenderText() {
424 RenderText
* RenderText::CreateInstance() {
425 #if defined(OS_MACOSX) && defined(TOOLKIT_VIEWS)
426 // Use the more complete HarfBuzz implementation for Views controls on Mac.
427 return new RenderTextHarfBuzz
;
429 if (CommandLine::ForCurrentProcess()->HasSwitch(
430 switches::kEnableHarfBuzzRenderText
)) {
431 return new RenderTextHarfBuzz
;
433 return CreateNativeInstance();
437 void RenderText::SetText(const base::string16
& text
) {
438 DCHECK(!composition_range_
.IsValid());
443 // Adjust ranged styles and colors to accommodate a new text length.
444 const size_t text_length
= text_
.length();
445 colors_
.SetMax(text_length
);
446 for (size_t style
= 0; style
< NUM_TEXT_STYLES
; ++style
)
447 styles_
[style
].SetMax(text_length
);
448 cached_bounds_and_offset_valid_
= false;
450 // Reset selection model. SetText should always followed by SetSelectionModel
451 // or SetCursorPosition in upper layer.
452 SetSelectionModel(SelectionModel());
454 // Invalidate the cached text direction if it depends on the text contents.
455 if (directionality_mode_
== DIRECTIONALITY_FROM_TEXT
)
456 text_direction_
= base::i18n::UNKNOWN_DIRECTION
;
458 obscured_reveal_index_
= -1;
462 void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment
) {
463 if (horizontal_alignment_
!= alignment
) {
464 horizontal_alignment_
= alignment
;
465 display_offset_
= Vector2d();
466 cached_bounds_and_offset_valid_
= false;
470 void RenderText::SetFontList(const FontList
& font_list
) {
471 font_list_
= font_list
;
472 baseline_
= kInvalidBaseline
;
473 cached_bounds_and_offset_valid_
= false;
477 void RenderText::SetCursorEnabled(bool cursor_enabled
) {
478 cursor_enabled_
= cursor_enabled
;
479 cached_bounds_and_offset_valid_
= false;
482 void RenderText::ToggleInsertMode() {
483 insert_mode_
= !insert_mode_
;
484 cached_bounds_and_offset_valid_
= false;
487 void RenderText::SetObscured(bool obscured
) {
488 if (obscured
!= obscured_
) {
489 obscured_
= obscured
;
490 obscured_reveal_index_
= -1;
491 cached_bounds_and_offset_valid_
= false;
496 void RenderText::SetObscuredRevealIndex(int index
) {
497 if (obscured_reveal_index_
== index
)
500 obscured_reveal_index_
= index
;
501 cached_bounds_and_offset_valid_
= false;
505 void RenderText::SetMultiline(bool multiline
) {
506 if (multiline
!= multiline_
) {
507 multiline_
= multiline
;
508 cached_bounds_and_offset_valid_
= false;
513 void RenderText::SetElideBehavior(ElideBehavior elide_behavior
) {
514 // TODO(skanuj) : Add a test for triggering layout change.
515 if (elide_behavior_
!= elide_behavior
) {
516 elide_behavior_
= elide_behavior
;
521 void RenderText::SetDisplayRect(const Rect
& r
) {
522 if (r
!= display_rect_
) {
524 baseline_
= kInvalidBaseline
;
525 cached_bounds_and_offset_valid_
= false;
527 if (elide_behavior_
!= NO_ELIDE
)
532 void RenderText::SetCursorPosition(size_t position
) {
533 MoveCursorTo(position
, false);
536 void RenderText::MoveCursor(BreakType break_type
,
537 VisualCursorDirection direction
,
539 SelectionModel
cursor(cursor_position(), selection_model_
.caret_affinity());
540 // Cancelling a selection moves to the edge of the selection.
541 if (break_type
!= LINE_BREAK
&& !selection().is_empty() && !select
) {
542 SelectionModel selection_start
= GetSelectionModelForSelectionStart();
543 int start_x
= GetCursorBounds(selection_start
, true).x();
544 int cursor_x
= GetCursorBounds(cursor
, true).x();
545 // Use the selection start if it is left (when |direction| is CURSOR_LEFT)
546 // or right (when |direction| is CURSOR_RIGHT) of the selection end.
547 if (direction
== CURSOR_RIGHT
? start_x
> cursor_x
: start_x
< cursor_x
)
548 cursor
= selection_start
;
549 // Use the nearest word boundary in the proper |direction| for word breaks.
550 if (break_type
== WORD_BREAK
)
551 cursor
= GetAdjacentSelectionModel(cursor
, break_type
, direction
);
552 // Use an adjacent selection model if the cursor is not at a valid position.
553 if (!IsValidCursorIndex(cursor
.caret_pos()))
554 cursor
= GetAdjacentSelectionModel(cursor
, CHARACTER_BREAK
, direction
);
556 cursor
= GetAdjacentSelectionModel(cursor
, break_type
, direction
);
559 cursor
.set_selection_start(selection().start());
560 MoveCursorTo(cursor
);
563 bool RenderText::MoveCursorTo(const SelectionModel
& model
) {
564 // Enforce valid selection model components.
565 size_t text_length
= text().length();
566 Range
range(std::min(model
.selection().start(), text_length
),
567 std::min(model
.caret_pos(), text_length
));
568 // The current model only supports caret positions at valid cursor indices.
569 if (!IsValidCursorIndex(range
.start()) || !IsValidCursorIndex(range
.end()))
571 SelectionModel
sel(range
, model
.caret_affinity());
572 bool changed
= sel
!= selection_model_
;
573 SetSelectionModel(sel
);
577 bool RenderText::SelectRange(const Range
& range
) {
578 Range
sel(std::min(range
.start(), text().length()),
579 std::min(range
.end(), text().length()));
580 // Allow selection bounds at valid indicies amid multi-character graphemes.
581 if (!IsValidLogicalIndex(sel
.start()) || !IsValidLogicalIndex(sel
.end()))
583 LogicalCursorDirection affinity
=
584 (sel
.is_reversed() || sel
.is_empty()) ? CURSOR_FORWARD
: CURSOR_BACKWARD
;
585 SetSelectionModel(SelectionModel(sel
, affinity
));
589 bool RenderText::IsPointInSelection(const Point
& point
) {
590 if (selection().is_empty())
592 SelectionModel cursor
= FindCursorPosition(point
);
593 return RangeContainsCaret(
594 selection(), cursor
.caret_pos(), cursor
.caret_affinity());
597 void RenderText::ClearSelection() {
598 SetSelectionModel(SelectionModel(cursor_position(),
599 selection_model_
.caret_affinity()));
602 void RenderText::SelectAll(bool reversed
) {
603 const size_t length
= text().length();
604 const Range all
= reversed
? Range(length
, 0) : Range(0, length
);
605 const bool success
= SelectRange(all
);
609 void RenderText::SelectWord() {
615 size_t selection_max
= selection().GetMax();
617 base::i18n::BreakIterator
iter(text(), base::i18n::BreakIterator::BREAK_WORD
);
618 bool success
= iter
.Init();
623 size_t selection_min
= selection().GetMin();
624 if (selection_min
== text().length() && selection_min
!= 0)
627 for (; selection_min
!= 0; --selection_min
) {
628 if (iter
.IsStartOfWord(selection_min
) ||
629 iter
.IsEndOfWord(selection_min
))
633 if (selection_min
== selection_max
&& selection_max
!= text().length())
636 for (; selection_max
< text().length(); ++selection_max
)
637 if (iter
.IsEndOfWord(selection_max
) || iter
.IsStartOfWord(selection_max
))
640 const bool reversed
= selection().is_reversed();
641 MoveCursorTo(reversed
? selection_max
: selection_min
, false);
642 MoveCursorTo(reversed
? selection_min
: selection_max
, true);
645 const Range
& RenderText::GetCompositionRange() const {
646 return composition_range_
;
649 void RenderText::SetCompositionRange(const Range
& composition_range
) {
650 CHECK(!composition_range
.IsValid() ||
651 Range(0, text_
.length()).Contains(composition_range
));
652 composition_range_
.set_end(composition_range
.end());
653 composition_range_
.set_start(composition_range
.start());
657 void RenderText::SetColor(SkColor value
) {
658 colors_
.SetValue(value
);
661 // TODO(msw): Windows applies colors and decorations in the layout process.
662 cached_bounds_and_offset_valid_
= false;
667 void RenderText::ApplyColor(SkColor value
, const Range
& range
) {
668 colors_
.ApplyValue(value
, range
);
671 // TODO(msw): Windows applies colors and decorations in the layout process.
672 cached_bounds_and_offset_valid_
= false;
677 void RenderText::SetStyle(TextStyle style
, bool value
) {
678 styles_
[style
].SetValue(value
);
680 // Only invalidate the layout on font changes; not for colors or decorations.
681 bool invalidate
= (style
== BOLD
) || (style
== ITALIC
);
683 // TODO(msw): Windows applies colors and decorations in the layout process.
687 cached_bounds_and_offset_valid_
= false;
692 void RenderText::ApplyStyle(TextStyle style
, bool value
, const Range
& range
) {
693 styles_
[style
].ApplyValue(value
, range
);
695 // Only invalidate the layout on font changes; not for colors or decorations.
696 bool invalidate
= (style
== BOLD
) || (style
== ITALIC
);
698 // TODO(msw): Windows applies colors and decorations in the layout process.
702 cached_bounds_and_offset_valid_
= false;
707 bool RenderText::GetStyle(TextStyle style
) const {
708 return (styles_
[style
].breaks().size() == 1) &&
709 styles_
[style
].breaks().front().second
;
712 void RenderText::SetDirectionalityMode(DirectionalityMode mode
) {
713 if (mode
== directionality_mode_
)
716 directionality_mode_
= mode
;
717 text_direction_
= base::i18n::UNKNOWN_DIRECTION
;
718 cached_bounds_and_offset_valid_
= false;
722 base::i18n::TextDirection
RenderText::GetTextDirection() {
723 if (text_direction_
== base::i18n::UNKNOWN_DIRECTION
) {
724 switch (directionality_mode_
) {
725 case DIRECTIONALITY_FROM_TEXT
:
726 // Derive the direction from the display text, which differs from text()
727 // in the case of obscured (password) textfields.
729 base::i18n::GetFirstStrongCharacterDirection(GetLayoutText());
731 case DIRECTIONALITY_FROM_UI
:
732 text_direction_
= base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT
:
733 base::i18n::LEFT_TO_RIGHT
;
735 case DIRECTIONALITY_FORCE_LTR
:
736 text_direction_
= base::i18n::LEFT_TO_RIGHT
;
738 case DIRECTIONALITY_FORCE_RTL
:
739 text_direction_
= base::i18n::RIGHT_TO_LEFT
;
746 return text_direction_
;
749 VisualCursorDirection
RenderText::GetVisualDirectionOfLogicalEnd() {
750 return GetTextDirection() == base::i18n::LEFT_TO_RIGHT
?
751 CURSOR_RIGHT
: CURSOR_LEFT
;
754 SizeF
RenderText::GetStringSizeF() {
755 const Size size
= GetStringSize();
756 return SizeF(size
.width(), size
.height());
759 float RenderText::GetContentWidth() {
760 return GetStringSizeF().width() + (cursor_enabled_
? 1 : 0);
763 int RenderText::GetBaseline() {
764 if (baseline_
== kInvalidBaseline
)
765 baseline_
= DetermineBaselineCenteringText(display_rect(), font_list());
766 DCHECK_NE(kInvalidBaseline
, baseline_
);
770 void RenderText::Draw(Canvas
* canvas
) {
773 if (clip_to_display_rect()) {
774 Rect
clip_rect(display_rect());
775 clip_rect
.Inset(ShadowValue::GetMargin(shadows_
));
778 canvas
->ClipRect(clip_rect
);
781 if (!text().empty() && focused())
782 DrawSelection(canvas
);
784 if (cursor_enabled() && cursor_visible() && focused())
785 DrawCursor(canvas
, selection_model_
);
788 DrawVisualText(canvas
);
790 if (clip_to_display_rect())
794 void RenderText::DrawCursor(Canvas
* canvas
, const SelectionModel
& position
) {
795 // Paint cursor. Replace cursor is drawn as rectangle for now.
796 // TODO(msw): Draw a better cursor with a better indication of association.
797 canvas
->FillRect(GetCursorBounds(position
, true), cursor_color_
);
800 bool RenderText::IsValidLogicalIndex(size_t index
) {
801 // Check that the index is at a valid code point (not mid-surrgate-pair) and
802 // that it's not truncated from the layout text (its glyph may be shown).
804 // Indices within truncated text are disallowed so users can easily interact
805 // with the underlying truncated text using the ellipsis as a proxy. This lets
806 // users select all text, select the truncated text, and transition from the
807 // last rendered glyph to the end of the text without getting invisible cursor
808 // positions nor needing unbounded arrow key presses to traverse the ellipsis.
809 return index
== 0 || index
== text().length() ||
810 (index
< text().length() &&
811 (truncate_length_
== 0 || index
< truncate_length_
) &&
812 IsValidCodePointIndex(text(), index
));
815 Rect
RenderText::GetCursorBounds(const SelectionModel
& caret
,
817 // TODO(ckocagil): Support multiline. This function should return the height
818 // of the line the cursor is on. |GetStringSize()| now returns
819 // the multiline size, eliminate its use here.
822 size_t caret_pos
= caret
.caret_pos();
823 DCHECK(IsValidLogicalIndex(caret_pos
));
824 // In overtype mode, ignore the affinity and always indicate that we will
825 // overtype the next character.
826 LogicalCursorDirection caret_affinity
=
827 insert_mode
? caret
.caret_affinity() : CURSOR_FORWARD
;
828 int x
= 0, width
= 1;
829 Size size
= GetStringSize();
830 if (caret_pos
== (caret_affinity
== CURSOR_BACKWARD
? 0 : text().length())) {
831 // The caret is attached to the boundary. Always return a 1-dip width caret,
832 // since there is nothing to overtype.
833 if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT
) == (caret_pos
== 0))
836 size_t grapheme_start
= (caret_affinity
== CURSOR_FORWARD
) ?
837 caret_pos
: IndexOfAdjacentGrapheme(caret_pos
, CURSOR_BACKWARD
);
838 Range
xspan(GetGlyphBounds(grapheme_start
));
840 x
= (caret_affinity
== CURSOR_BACKWARD
) ? xspan
.end() : xspan
.start();
841 } else { // overtype mode
843 width
= xspan
.length();
846 return Rect(ToViewPoint(Point(x
, 0)), Size(width
, size
.height()));
849 const Rect
& RenderText::GetUpdatedCursorBounds() {
850 UpdateCachedBoundsAndOffset();
851 return cursor_bounds_
;
854 size_t RenderText::IndexOfAdjacentGrapheme(size_t index
,
855 LogicalCursorDirection direction
) {
856 if (index
> text().length())
857 return text().length();
861 if (direction
== CURSOR_FORWARD
) {
862 while (index
< text().length()) {
864 if (IsValidCursorIndex(index
))
867 return text().length();
872 if (IsValidCursorIndex(index
))
878 SelectionModel
RenderText::GetSelectionModelForSelectionStart() {
879 const Range
& sel
= selection();
881 return selection_model_
;
882 return SelectionModel(sel
.start(),
883 sel
.is_reversed() ? CURSOR_BACKWARD
: CURSOR_FORWARD
);
886 const Vector2d
& RenderText::GetUpdatedDisplayOffset() {
887 UpdateCachedBoundsAndOffset();
888 return display_offset_
;
891 void RenderText::SetDisplayOffset(int horizontal_offset
) {
892 const int extra_content
= GetContentWidth() - display_rect_
.width();
896 if (extra_content
> 0) {
897 switch (horizontal_alignment_
) {
899 min_offset
= -extra_content
;
902 max_offset
= extra_content
;
905 min_offset
= -extra_content
/ 2;
906 max_offset
= extra_content
/ 2;
912 if (horizontal_offset
< min_offset
)
913 horizontal_offset
= min_offset
;
914 else if (horizontal_offset
> max_offset
)
915 horizontal_offset
= max_offset
;
917 cached_bounds_and_offset_valid_
= true;
918 display_offset_
.set_x(horizontal_offset
);
919 cursor_bounds_
= GetCursorBounds(selection_model_
, insert_mode_
);
922 RenderText::RenderText()
923 : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT
: ALIGN_LEFT
),
924 directionality_mode_(DIRECTIONALITY_FROM_TEXT
),
925 text_direction_(base::i18n::UNKNOWN_DIRECTION
),
926 cursor_enabled_(true),
927 cursor_visible_(false),
929 cursor_color_(kDefaultColor
),
930 selection_color_(kDefaultColor
),
931 selection_background_focused_color_(kDefaultSelectionBackgroundColor
),
933 composition_range_(Range::InvalidRange()),
934 colors_(kDefaultColor
),
935 styles_(NUM_TEXT_STYLES
),
936 composition_and_selection_styles_applied_(false),
938 obscured_reveal_index_(-1),
940 elide_behavior_(NO_ELIDE
),
942 background_is_transparent_(false),
943 clip_to_display_rect_(true),
944 baseline_(kInvalidBaseline
),
945 cached_bounds_and_offset_valid_(false) {
948 SelectionModel
RenderText::GetAdjacentSelectionModel(
949 const SelectionModel
& current
,
950 BreakType break_type
,
951 VisualCursorDirection direction
) {
954 if (break_type
== LINE_BREAK
|| text().empty())
955 return EdgeSelectionModel(direction
);
956 if (break_type
== CHARACTER_BREAK
)
957 return AdjacentCharSelectionModel(current
, direction
);
958 DCHECK(break_type
== WORD_BREAK
);
959 return AdjacentWordSelectionModel(current
, direction
);
962 SelectionModel
RenderText::EdgeSelectionModel(
963 VisualCursorDirection direction
) {
964 if (direction
== GetVisualDirectionOfLogicalEnd())
965 return SelectionModel(text().length(), CURSOR_FORWARD
);
966 return SelectionModel(0, CURSOR_BACKWARD
);
969 void RenderText::SetSelectionModel(const SelectionModel
& model
) {
970 DCHECK_LE(model
.selection().GetMax(), text().length());
971 selection_model_
= model
;
972 cached_bounds_and_offset_valid_
= false;
975 const base::string16
& RenderText::GetLayoutText() const {
979 const BreakList
<size_t>& RenderText::GetLineBreaks() {
980 if (line_breaks_
.max() != 0)
983 const base::string16
& layout_text
= GetLayoutText();
984 const size_t text_length
= layout_text
.length();
985 line_breaks_
.SetValue(0);
986 line_breaks_
.SetMax(text_length
);
987 base::i18n::BreakIterator
iter(layout_text
,
988 base::i18n::BreakIterator::BREAK_LINE
);
989 const bool success
= iter
.Init();
993 line_breaks_
.ApplyValue(iter
.pos(), Range(iter
.pos(), text_length
));
994 } while (iter
.Advance());
999 void RenderText::ApplyCompositionAndSelectionStyles() {
1000 // Save the underline and color breaks to undo the temporary styles later.
1001 DCHECK(!composition_and_selection_styles_applied_
);
1002 saved_colors_
= colors_
;
1003 saved_underlines_
= styles_
[UNDERLINE
];
1005 // Apply an underline to the composition range in |underlines|.
1006 if (composition_range_
.IsValid() && !composition_range_
.is_empty())
1007 styles_
[UNDERLINE
].ApplyValue(true, composition_range_
);
1009 // Apply the selected text color to the [un-reversed] selection range.
1010 if (!selection().is_empty() && focused()) {
1011 const Range
range(selection().GetMin(), selection().GetMax());
1012 colors_
.ApplyValue(selection_color_
, range
);
1014 composition_and_selection_styles_applied_
= true;
1017 void RenderText::UndoCompositionAndSelectionStyles() {
1018 // Restore the underline and color breaks to undo the temporary styles.
1019 DCHECK(composition_and_selection_styles_applied_
);
1020 colors_
= saved_colors_
;
1021 styles_
[UNDERLINE
] = saved_underlines_
;
1022 composition_and_selection_styles_applied_
= false;
1025 Vector2d
RenderText::GetLineOffset(size_t line_number
) {
1026 Vector2d offset
= display_rect().OffsetFromOrigin();
1027 // TODO(ckocagil): Apply the display offset for multiline scrolling.
1029 offset
.Add(GetUpdatedDisplayOffset());
1031 offset
.Add(Vector2d(0, lines_
[line_number
].preceding_heights
));
1032 offset
.Add(GetAlignmentOffset(line_number
));
1036 Point
RenderText::ToTextPoint(const Point
& point
) {
1037 return point
- GetLineOffset(0);
1038 // TODO(ckocagil): Convert multiline view space points to text space.
1041 Point
RenderText::ToViewPoint(const Point
& point
) {
1043 return point
+ GetLineOffset(0);
1045 // TODO(ckocagil): Traverse individual line segments for RTL support.
1046 DCHECK(!lines_
.empty());
1049 for (; line
< lines_
.size() && x
> lines_
[line
].size
.width(); ++line
)
1050 x
-= lines_
[line
].size
.width();
1051 return Point(x
, point
.y()) + GetLineOffset(line
);
1054 std::vector
<Rect
> RenderText::TextBoundsToViewBounds(const Range
& x
) {
1055 std::vector
<Rect
> rects
;
1058 rects
.push_back(Rect(ToViewPoint(Point(x
.GetMin(), 0)),
1059 Size(x
.length(), GetStringSize().height())));
1065 // Each line segment keeps its position in text coordinates. Traverse all line
1066 // segments and if the segment intersects with the given range, add the view
1067 // rect corresponding to the intersection to |rects|.
1068 for (size_t line
= 0; line
< lines_
.size(); ++line
) {
1070 const Vector2d offset
= GetLineOffset(line
);
1071 for (size_t i
= 0; i
< lines_
[line
].segments
.size(); ++i
) {
1072 const internal::LineSegment
* segment
= &lines_
[line
].segments
[i
];
1073 const Range intersection
= segment
->x_range
.Intersect(x
);
1074 if (!intersection
.is_empty()) {
1075 Rect
rect(line_x
+ intersection
.start() - segment
->x_range
.start(),
1076 0, intersection
.length(), lines_
[line
].size
.height());
1077 rects
.push_back(rect
+ offset
);
1079 line_x
+= segment
->x_range
.length();
1086 Vector2d
RenderText::GetAlignmentOffset(size_t line_number
) {
1087 // TODO(ckocagil): Enable |lines_| usage in other platforms.
1089 DCHECK_LT(line_number
, lines_
.size());
1092 if (horizontal_alignment_
!= ALIGN_LEFT
) {
1094 const int width
= lines_
[line_number
].size
.width() +
1095 (cursor_enabled_
? 1 : 0);
1097 const int width
= GetContentWidth();
1099 offset
.set_x(display_rect().width() - width
);
1100 if (horizontal_alignment_
== ALIGN_CENTER
)
1101 offset
.set_x(offset
.x() / 2);
1104 // Vertically center the text.
1106 const int text_height
= lines_
.back().preceding_heights
+
1107 lines_
.back().size
.height();
1108 offset
.set_y((display_rect_
.height() - text_height
) / 2);
1110 offset
.set_y(GetBaseline() - GetLayoutTextBaseline());
1116 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer
* renderer
) {
1117 const int width
= display_rect().width();
1118 if (multiline() || elide_behavior_
!= FADE_TAIL
|| GetContentWidth() <= width
)
1121 const int gradient_width
= CalculateFadeGradientWidth(font_list(), width
);
1122 if (gradient_width
== 0)
1125 Rect solid_part
= display_rect();
1128 if (horizontal_alignment_
!= ALIGN_LEFT
) {
1129 left_part
= solid_part
;
1130 left_part
.Inset(0, 0, solid_part
.width() - gradient_width
, 0);
1131 solid_part
.Inset(gradient_width
, 0, 0, 0);
1133 if (horizontal_alignment_
!= ALIGN_RIGHT
) {
1134 right_part
= solid_part
;
1135 right_part
.Inset(solid_part
.width() - gradient_width
, 0, 0, 0);
1136 solid_part
.Inset(0, 0, gradient_width
, 0);
1139 Rect text_rect
= display_rect();
1140 text_rect
.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1142 // TODO(msw): Use the actual text colors corresponding to each faded part.
1143 skia::RefPtr
<SkShader
> shader
= CreateFadeShader(
1144 text_rect
, left_part
, right_part
, colors_
.breaks().front().second
);
1146 renderer
->SetShader(shader
.get(), display_rect());
1149 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer
* renderer
) {
1150 skia::RefPtr
<SkDrawLooper
> looper
= CreateShadowDrawLooper(shadows_
);
1151 renderer
->SetDrawLooper(looper
.get());
1155 bool RenderText::RangeContainsCaret(const Range
& range
,
1157 LogicalCursorDirection caret_affinity
) {
1158 // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1159 size_t adjacent
= (caret_affinity
== CURSOR_BACKWARD
) ?
1160 caret_pos
- 1 : caret_pos
+ 1;
1161 return range
.Contains(Range(caret_pos
, adjacent
));
1164 void RenderText::MoveCursorTo(size_t position
, bool select
) {
1165 size_t cursor
= std::min(position
, text().length());
1166 if (IsValidCursorIndex(cursor
))
1167 SetSelectionModel(SelectionModel(
1168 Range(select
? selection().start() : cursor
, cursor
),
1169 (cursor
== 0) ? CURSOR_FORWARD
: CURSOR_BACKWARD
));
1172 void RenderText::UpdateLayoutText() {
1173 layout_text_
.clear();
1174 line_breaks_
.SetMax(0);
1177 size_t obscured_text_length
=
1178 static_cast<size_t>(UTF16IndexToOffset(text_
, 0, text_
.length()));
1179 layout_text_
.assign(obscured_text_length
, kPasswordReplacementChar
);
1181 if (obscured_reveal_index_
>= 0 &&
1182 obscured_reveal_index_
< static_cast<int>(text_
.length())) {
1183 // Gets the index range in |text_| to be revealed.
1184 size_t start
= obscured_reveal_index_
;
1185 U16_SET_CP_START(text_
.data(), 0, start
);
1187 UChar32 unused_char
;
1188 U16_NEXT(text_
.data(), end
, text_
.length(), unused_char
);
1190 // Gets the index in |layout_text_| to be replaced.
1191 const size_t cp_start
=
1192 static_cast<size_t>(UTF16IndexToOffset(text_
, 0, start
));
1193 if (layout_text_
.length() > cp_start
)
1194 layout_text_
.replace(cp_start
, 1, text_
.substr(start
, end
- start
));
1197 layout_text_
= text_
;
1200 const base::string16
& text
= layout_text_
;
1201 if (truncate_length_
> 0 && truncate_length_
< text
.length()) {
1202 // Truncate the text at a valid character break and append an ellipsis.
1203 icu::StringCharacterIterator
iter(text
.c_str());
1204 // Respect ELIDE_HEAD and ELIDE_MIDDLE preferences during truncation.
1205 if (elide_behavior_
== ELIDE_HEAD
) {
1206 iter
.setIndex32(text
.length() - truncate_length_
+ 1);
1207 layout_text_
.assign(kEllipsisUTF16
+ text
.substr(iter
.getIndex()));
1208 } else if (elide_behavior_
== ELIDE_MIDDLE
) {
1209 iter
.setIndex32(truncate_length_
/ 2);
1210 const size_t ellipsis_start
= iter
.getIndex();
1211 iter
.setIndex32(text
.length() - (truncate_length_
/ 2));
1212 const size_t ellipsis_end
= iter
.getIndex();
1213 DCHECK_LE(ellipsis_start
, ellipsis_end
);
1214 layout_text_
.assign(text
.substr(0, ellipsis_start
) + kEllipsisUTF16
+
1215 text
.substr(ellipsis_end
));
1217 iter
.setIndex32(truncate_length_
- 1);
1218 layout_text_
.assign(text
.substr(0, iter
.getIndex()) + kEllipsisUTF16
);
1222 if (elide_behavior_
!= NO_ELIDE
&& elide_behavior_
!= FADE_TAIL
&&
1223 !layout_text_
.empty() && GetContentWidth() > display_rect_
.width()) {
1224 // This doesn't trim styles so ellipsis may get rendered as a different
1225 // style than the preceding text. See crbug.com/327850.
1226 layout_text_
.assign(
1227 Elide(layout_text_
, display_rect_
.width(), elide_behavior_
));
1230 // Replace the newline character with a newline symbol in single line mode.
1231 static const base::char16 kNewline
[] = { '\n', 0 };
1232 static const base::char16 kNewlineSymbol
[] = { 0x2424, 0 };
1234 base::ReplaceChars(layout_text_
, kNewline
, kNewlineSymbol
, &layout_text_
);
1239 base::string16
RenderText::Elide(const base::string16
& text
,
1240 float available_width
,
1241 ElideBehavior behavior
) {
1242 if (available_width
<= 0 || text
.empty())
1243 return base::string16();
1244 if (behavior
== ELIDE_EMAIL
)
1245 return ElideEmail(text
, available_width
);
1247 // Create a RenderText copy with attributes that affect the rendering width.
1248 scoped_ptr
<RenderText
> render_text(CreateInstance());
1249 render_text
->SetFontList(font_list_
);
1250 render_text
->SetDirectionalityMode(directionality_mode_
);
1251 render_text
->SetCursorEnabled(cursor_enabled_
);
1252 render_text
->set_truncate_length(truncate_length_
);
1253 render_text
->styles_
= styles_
;
1254 render_text
->colors_
= colors_
;
1255 render_text
->SetText(text
);
1256 if (render_text
->GetContentWidth() <= available_width
)
1259 const base::string16 ellipsis
= base::string16(kEllipsisUTF16
);
1260 const bool insert_ellipsis
= (behavior
!= TRUNCATE
);
1261 const bool elide_in_middle
= (behavior
== ELIDE_MIDDLE
);
1262 const bool elide_at_beginning
= (behavior
== ELIDE_HEAD
);
1263 StringSlicer
slicer(text
, ellipsis
, elide_in_middle
, elide_at_beginning
);
1265 render_text
->SetText(ellipsis
);
1266 const float ellipsis_width
= render_text
->GetContentWidth();
1268 if (insert_ellipsis
&& (ellipsis_width
> available_width
))
1269 return base::string16();
1271 // Use binary search to compute the elided text.
1273 size_t hi
= text
.length() - 1;
1274 const base::i18n::TextDirection text_direction
= GetTextDirection();
1275 for (size_t guess
= (lo
+ hi
) / 2; lo
<= hi
; guess
= (lo
+ hi
) / 2) {
1276 // Restore styles and colors. They will be truncated to size by SetText.
1277 render_text
->styles_
= styles_
;
1278 render_text
->colors_
= colors_
;
1279 base::string16 new_text
=
1280 slicer
.CutString(guess
, insert_ellipsis
&& behavior
!= ELIDE_TAIL
);
1281 render_text
->SetText(new_text
);
1283 // This has to be an additional step so that the ellipsis is rendered with
1284 // same style as trailing part of the text.
1285 if (insert_ellipsis
&& behavior
== ELIDE_TAIL
) {
1286 // When ellipsis follows text whose directionality is not the same as that
1287 // of the whole text, it will be rendered with the directionality of the
1288 // whole text. Since we want ellipsis to indicate continuation of the
1289 // preceding text, we force the directionality of ellipsis to be same as
1290 // the preceding text using LTR or RTL markers.
1291 base::i18n::TextDirection trailing_text_direction
=
1292 base::i18n::GetLastStrongCharacterDirection(new_text
);
1293 new_text
.append(ellipsis
);
1294 if (trailing_text_direction
!= text_direction
) {
1295 if (trailing_text_direction
== base::i18n::LEFT_TO_RIGHT
)
1296 new_text
+= base::i18n::kLeftToRightMark
;
1298 new_text
+= base::i18n::kRightToLeftMark
;
1300 render_text
->SetText(new_text
);
1303 // We check the width of the whole desired string at once to ensure we
1304 // handle kerning/ligatures/etc. correctly.
1305 const float guess_width
= render_text
->GetContentWidth();
1306 if (guess_width
== available_width
)
1308 if (guess_width
> available_width
) {
1310 // Move back on the loop terminating condition when the guess is too wide.
1318 return render_text
->text();
1321 base::string16
RenderText::ElideEmail(const base::string16
& email
,
1322 float available_width
) {
1323 // The returned string will have at least one character besides the ellipsis
1324 // on either side of '@'; if that's impossible, a single ellipsis is returned.
1325 // If possible, only the username is elided. Otherwise, the domain is elided
1326 // in the middle, splitting available width equally with the elided username.
1327 // If the username is short enough that it doesn't need half the available
1328 // width, the elided domain will occupy that extra width.
1330 // Split the email into its local-part (username) and domain-part. The email
1331 // spec allows for @ symbols in the username under some special requirements,
1332 // but not in the domain part, so splitting at the last @ symbol is safe.
1333 const size_t split_index
= email
.find_last_of('@');
1334 DCHECK_NE(split_index
, base::string16::npos
);
1335 base::string16 username
= email
.substr(0, split_index
);
1336 base::string16 domain
= email
.substr(split_index
+ 1);
1337 DCHECK(!username
.empty());
1338 DCHECK(!domain
.empty());
1340 // Subtract the @ symbol from the available width as it is mandatory.
1341 const base::string16 kAtSignUTF16
= base::ASCIIToUTF16("@");
1342 available_width
-= GetStringWidthF(kAtSignUTF16
, font_list());
1344 // Check whether eliding the domain is necessary: if eliding the username
1345 // is sufficient, the domain will not be elided.
1346 const float full_username_width
= GetStringWidthF(username
, font_list());
1347 const float available_domain_width
= available_width
-
1348 std::min(full_username_width
,
1349 GetStringWidthF(username
.substr(0, 1) + kEllipsisUTF16
, font_list()));
1350 if (GetStringWidthF(domain
, font_list()) > available_domain_width
) {
1351 // Elide the domain so that it only takes half of the available width.
1352 // Should the username not need all the width available in its half, the
1353 // domain will occupy the leftover width.
1354 // If |desired_domain_width| is greater than |available_domain_width|: the
1355 // minimal username elision allowed by the specifications will not fit; thus
1356 // |desired_domain_width| must be <= |available_domain_width| at all cost.
1357 const float desired_domain_width
=
1358 std::min
<float>(available_domain_width
,
1359 std::max
<float>(available_width
- full_username_width
,
1360 available_width
/ 2));
1361 domain
= Elide(domain
, desired_domain_width
, ELIDE_MIDDLE
);
1362 // Failing to elide the domain such that at least one character remains
1363 // (other than the ellipsis itself) remains: return a single ellipsis.
1364 if (domain
.length() <= 1U)
1365 return base::string16(kEllipsisUTF16
);
1368 // Fit the username in the remaining width (at this point the elided username
1369 // is guaranteed to fit with at least one character remaining given all the
1370 // precautions taken earlier).
1371 available_width
-= GetStringWidthF(domain
, font_list());
1372 username
= Elide(username
, available_width
, ELIDE_TAIL
);
1373 return username
+ kAtSignUTF16
+ domain
;
1376 void RenderText::UpdateCachedBoundsAndOffset() {
1377 if (cached_bounds_and_offset_valid_
)
1380 // TODO(ckocagil): Add support for scrolling multiline text.
1382 // First, set the valid flag true to calculate the current cursor bounds using
1383 // the stale |display_offset_|. Applying |delta_offset| at the end of this
1384 // function will set |cursor_bounds_| and |display_offset_| to correct values.
1385 cached_bounds_and_offset_valid_
= true;
1386 if (cursor_enabled())
1387 cursor_bounds_
= GetCursorBounds(selection_model_
, insert_mode_
);
1389 // Update |display_offset_| to ensure the current cursor is visible.
1390 const int display_width
= display_rect_
.width();
1391 const int content_width
= GetContentWidth();
1394 if (content_width
<= display_width
|| !cursor_enabled()) {
1395 // Don't pan if the text fits in the display width or when the cursor is
1397 delta_x
= -display_offset_
.x();
1398 } else if (cursor_bounds_
.right() > display_rect_
.right()) {
1399 // TODO(xji): when the character overflow is a RTL character, currently, if
1400 // we pan cursor at the rightmost position, the entered RTL character is not
1401 // displayed. Should pan cursor to show the last logical characters.
1403 // Pan to show the cursor when it overflows to the right.
1404 delta_x
= display_rect_
.right() - cursor_bounds_
.right();
1405 } else if (cursor_bounds_
.x() < display_rect_
.x()) {
1406 // TODO(xji): have similar problem as above when overflow character is a
1409 // Pan to show the cursor when it overflows to the left.
1410 delta_x
= display_rect_
.x() - cursor_bounds_
.x();
1411 } else if (display_offset_
.x() != 0) {
1412 // Reduce the pan offset to show additional overflow text when the display
1414 const int negate_rtl
= horizontal_alignment_
== ALIGN_RIGHT
? -1 : 1;
1415 const int offset
= negate_rtl
* display_offset_
.x();
1416 if (display_width
> (content_width
+ offset
)) {
1417 delta_x
= negate_rtl
* (display_width
- (content_width
+ offset
));
1421 Vector2d
delta_offset(delta_x
, 0);
1422 display_offset_
+= delta_offset
;
1423 cursor_bounds_
+= delta_offset
;
1426 void RenderText::DrawSelection(Canvas
* canvas
) {
1427 const std::vector
<Rect
> sel
= GetSubstringBounds(selection());
1428 for (std::vector
<Rect
>::const_iterator i
= sel
.begin(); i
< sel
.end(); ++i
)
1429 canvas
->FillRect(*i
, selection_background_focused_color_
);