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/i18n/break_iterator.h"
11 #include "base/logging.h"
12 #include "base/stl_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "third_party/icu/source/common/unicode/rbbi.h"
15 #include "third_party/icu/source/common/unicode/utf16.h"
16 #include "third_party/skia/include/core/SkTypeface.h"
17 #include "third_party/skia/include/effects/SkGradientShader.h"
18 #include "ui/gfx/canvas.h"
19 #include "ui/gfx/insets.h"
20 #include "ui/gfx/skia_util.h"
21 #include "ui/gfx/text_constants.h"
22 #include "ui/gfx/text_elider.h"
23 #include "ui/gfx/text_utils.h"
24 #include "ui/gfx/utf16_indexing.h"
30 // All chars are replaced by this char when the password style is set.
31 // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*'
32 // that's available in the font (find_invisible_char() in gtkentry.c).
33 const base::char16 kPasswordReplacementChar = '*';
35 // Default color used for the text and cursor.
36 const SkColor kDefaultColor = SK_ColorBLACK;
38 // Default color used for drawing selection background.
39 const SkColor kDefaultSelectionBackgroundColor = SK_ColorGRAY;
41 // Fraction of the text size to lower a strike through below the baseline.
42 const SkScalar kStrikeThroughOffset = (-SK_Scalar1 * 6 / 21);
43 // Fraction of the text size to lower an underline below the baseline.
44 const SkScalar kUnderlineOffset = (SK_Scalar1 / 9);
45 // Fraction of the text size to use for a strike through or under-line.
46 const SkScalar kLineThickness = (SK_Scalar1 / 18);
47 // Fraction of the text size to use for a top margin of a diagonal strike.
48 const SkScalar kDiagonalStrikeMarginOffset = (SK_Scalar1 / 4);
50 // Invalid value of baseline. Assigning this value to |baseline_| causes
51 // re-calculation of baseline.
52 const int kInvalidBaseline = INT_MAX;
54 // Returns the baseline, with which the text best appears vertically centered.
55 int DetermineBaselineCenteringText(const Rect& display_rect,
56 const FontList& font_list) {
57 const int display_height = display_rect.height();
58 const int font_height = font_list.GetHeight();
59 // Lower and upper bound of baseline shift as we try to show as much area of
60 // text as possible. In particular case of |display_height| == |font_height|,
61 // we do not want to shift the baseline.
62 const int min_shift = std::min(0, display_height - font_height);
63 const int max_shift = std::abs(display_height - font_height);
64 const int baseline = font_list.GetBaseline();
65 const int cap_height = font_list.GetCapHeight();
66 const int internal_leading = baseline - cap_height;
67 // Some platforms don't support getting the cap height, and simply return
68 // the entire font ascent from GetCapHeight(). Centering the ascent makes
69 // the font look too low, so if GetCapHeight() returns the ascent, center
70 // the entire font height instead.
72 display_height - ((internal_leading != 0) ? cap_height : font_height);
73 const int baseline_shift = space / 2 - internal_leading;
74 return baseline + std::max(min_shift, std::min(max_shift, baseline_shift));
77 // Converts |gfx::Font::FontStyle| flags to |SkTypeface::Style| flags.
78 SkTypeface::Style ConvertFontStyleToSkiaTypefaceStyle(int font_style) {
79 int skia_style = SkTypeface::kNormal;
80 skia_style |= (font_style & gfx::Font::BOLD) ? SkTypeface::kBold : 0;
81 skia_style |= (font_style & gfx::Font::ITALIC) ? SkTypeface::kItalic : 0;
82 return static_cast<SkTypeface::Style>(skia_style);
85 // Given |font| and |display_width|, returns the width of the fade gradient.
86 int CalculateFadeGradientWidth(const FontList& font_list, int display_width) {
87 // Fade in/out about 2.5 characters of the beginning/end of the string.
88 // The .5 here is helpful if one of the characters is a space.
89 // Use a quarter of the display width if the display width is very short.
90 const int average_character_width = font_list.GetExpectedTextWidth(1);
91 const double gradient_width = std::min(average_character_width * 2.5,
93 DCHECK_GE(gradient_width, 0.0);
94 return static_cast<int>(floor(gradient_width + 0.5));
97 // Appends to |positions| and |colors| values corresponding to the fade over
98 // |fade_rect| from color |c0| to color |c1|.
99 void AddFadeEffect(const Rect& text_rect,
100 const Rect& fade_rect,
103 std::vector<SkScalar>* positions,
104 std::vector<SkColor>* colors) {
105 const SkScalar left = static_cast<SkScalar>(fade_rect.x() - text_rect.x());
106 const SkScalar width = static_cast<SkScalar>(fade_rect.width());
107 const SkScalar p0 = left / text_rect.width();
108 const SkScalar p1 = (left + width) / text_rect.width();
109 // Prepend 0.0 to |positions|, as required by Skia.
110 if (positions->empty() && p0 != 0.0) {
111 positions->push_back(0.0);
112 colors->push_back(c0);
114 positions->push_back(p0);
115 colors->push_back(c0);
116 positions->push_back(p1);
117 colors->push_back(c1);
120 // Creates a SkShader to fade the text, with |left_part| specifying the left
121 // fade effect, if any, and |right_part| specifying the right fade effect.
122 skia::RefPtr<SkShader> CreateFadeShader(const Rect& text_rect,
123 const Rect& left_part,
124 const Rect& right_part,
126 // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color.
127 const SkColor fade_color = SkColorSetA(color, 51);
128 std::vector<SkScalar> positions;
129 std::vector<SkColor> colors;
131 if (!left_part.IsEmpty())
132 AddFadeEffect(text_rect, left_part, fade_color, color,
133 &positions, &colors);
134 if (!right_part.IsEmpty())
135 AddFadeEffect(text_rect, right_part, color, fade_color,
136 &positions, &colors);
137 DCHECK(!positions.empty());
139 // Terminate |positions| with 1.0, as required by Skia.
140 if (positions.back() != 1.0) {
141 positions.push_back(1.0);
142 colors.push_back(colors.back());
146 points[0].iset(text_rect.x(), text_rect.y());
147 points[1].iset(text_rect.right(), text_rect.y());
149 return skia::AdoptRef(
150 SkGradientShader::CreateLinear(&points[0], &colors[0], &positions[0],
151 colors.size(), SkShader::kClamp_TileMode));
158 // Value of |underline_thickness_| that indicates that underline metrics have
159 // not been set explicitly.
160 const SkScalar kUnderlineMetricsNotSet = -1.0f;
162 SkiaTextRenderer::SkiaTextRenderer(Canvas* canvas)
164 canvas_skia_(canvas->sk_canvas()),
165 started_drawing_(false),
166 underline_thickness_(kUnderlineMetricsNotSet),
167 underline_position_(0.0f) {
168 DCHECK(canvas_skia_);
169 paint_.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
170 paint_.setStyle(SkPaint::kFill_Style);
171 paint_.setAntiAlias(true);
172 paint_.setSubpixelText(true);
173 paint_.setLCDRenderText(true);
174 paint_.setHinting(SkPaint::kNormal_Hinting);
178 SkiaTextRenderer::~SkiaTextRenderer() {
179 // Work-around for http://crbug.com/122743, where non-ClearType text is
180 // rendered with incorrect gamma when using the fade shader. Draw the text
181 // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode.
183 // TODO(asvitkine): Remove this work-around once the Skia bug is fixed.
184 // http://code.google.com/p/skia/issues/detail?id=590
185 if (deferred_fade_shader_.get()) {
186 paint_.setShader(deferred_fade_shader_.get());
187 paint_.setXfermodeMode(SkXfermode::kDstIn_Mode);
188 canvas_skia_->drawRect(bounds_, paint_);
189 canvas_skia_->restore();
193 void SkiaTextRenderer::SetDrawLooper(SkDrawLooper* draw_looper) {
194 paint_.setLooper(draw_looper);
197 void SkiaTextRenderer::SetFontSmoothingSettings(bool antialiasing,
198 bool subpixel_rendering,
199 bool subpixel_positioning) {
200 paint_.setAntiAlias(antialiasing);
201 paint_.setLCDRenderText(subpixel_rendering);
202 paint_.setSubpixelText(subpixel_positioning);
205 void SkiaTextRenderer::SetFontHinting(SkPaint::Hinting hinting) {
206 paint_.setHinting(hinting);
209 void SkiaTextRenderer::SetTypeface(SkTypeface* typeface) {
210 paint_.setTypeface(typeface);
213 void SkiaTextRenderer::SetTextSize(SkScalar size) {
214 paint_.setTextSize(size);
217 void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string& family,
219 DCHECK(!family.empty());
221 SkTypeface::Style skia_style = ConvertFontStyleToSkiaTypefaceStyle(style);
222 skia::RefPtr<SkTypeface> typeface =
223 skia::AdoptRef(SkTypeface::CreateFromName(family.c_str(), skia_style));
225 // |paint_| adds its own ref. So don't |release()| it from the ref ptr here.
226 SetTypeface(typeface.get());
228 // Enable fake bold text if bold style is needed but new typeface does not
230 paint_.setFakeBoldText((skia_style & SkTypeface::kBold) &&
231 !typeface->isBold());
235 void SkiaTextRenderer::SetForegroundColor(SkColor foreground) {
236 paint_.setColor(foreground);
239 void SkiaTextRenderer::SetShader(SkShader* shader, const Rect& bounds) {
240 bounds_ = RectToSkRect(bounds);
241 paint_.setShader(shader);
244 void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness,
246 underline_thickness_ = thickness;
247 underline_position_ = position;
250 void SkiaTextRenderer::DrawPosText(const SkPoint* pos,
251 const uint16* glyphs,
252 size_t glyph_count) {
253 if (!started_drawing_) {
254 started_drawing_ = true;
255 // Work-around for http://crbug.com/122743, where non-ClearType text is
256 // rendered with incorrect gamma when using the fade shader. Draw the text
257 // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode.
259 // Skip this when there is a looper which seems not working well with
260 // deferred paint. Currently a looper is only used for text shadows.
262 // TODO(asvitkine): Remove this work-around once the Skia bug is fixed.
263 // http://code.google.com/p/skia/issues/detail?id=590
264 if (!paint_.isLCDRenderText() &&
265 paint_.getShader() &&
266 !paint_.getLooper()) {
267 deferred_fade_shader_ = skia::SharePtr(paint_.getShader());
268 paint_.setShader(NULL);
269 canvas_skia_->saveLayer(&bounds_, NULL);
273 const size_t byte_length = glyph_count * sizeof(glyphs[0]);
274 canvas_skia_->drawPosText(&glyphs[0], byte_length, &pos[0], paint_);
277 void SkiaTextRenderer::DrawDecorations(int x, int y, int width, bool underline,
278 bool strike, bool diagonal_strike) {
280 DrawUnderline(x, y, width);
282 DrawStrike(x, y, width);
283 if (diagonal_strike) {
285 diagonal_.reset(new DiagonalStrike(canvas_, Point(x, y), paint_));
286 diagonal_->AddPiece(width, paint_.getColor());
287 } else if (diagonal_) {
292 void SkiaTextRenderer::EndDiagonalStrike() {
299 void SkiaTextRenderer::DrawUnderline(int x, int y, int width) {
300 SkRect r = SkRect::MakeLTRB(x, y + underline_position_, x + width,
301 y + underline_position_ + underline_thickness_);
302 if (underline_thickness_ == kUnderlineMetricsNotSet) {
303 const SkScalar text_size = paint_.getTextSize();
304 r.fTop = SkScalarMulAdd(text_size, kUnderlineOffset, y);
305 r.fBottom = r.fTop + SkScalarMul(text_size, kLineThickness);
307 canvas_skia_->drawRect(r, paint_);
310 void SkiaTextRenderer::DrawStrike(int x, int y, int width) const {
311 const SkScalar text_size = paint_.getTextSize();
312 const SkScalar height = SkScalarMul(text_size, kLineThickness);
313 const SkScalar offset = SkScalarMulAdd(text_size, kStrikeThroughOffset, y);
314 const SkRect r = SkRect::MakeLTRB(x, offset, x + width, offset + height);
315 canvas_skia_->drawRect(r, paint_);
318 SkiaTextRenderer::DiagonalStrike::DiagonalStrike(Canvas* canvas,
320 const SkPaint& paint)
327 SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() {
330 void SkiaTextRenderer::DiagonalStrike::AddPiece(int length, SkColor color) {
331 pieces_.push_back(Piece(length, color));
332 total_length_ += length;
335 void SkiaTextRenderer::DiagonalStrike::Draw() {
336 const SkScalar text_size = paint_.getTextSize();
337 const SkScalar offset = SkScalarMul(text_size, kDiagonalStrikeMarginOffset);
338 const int thickness =
339 SkScalarCeilToInt(SkScalarMul(text_size, kLineThickness) * 2);
340 const int height = SkScalarCeilToInt(text_size - offset);
341 const Point end = start_ + Vector2d(total_length_, -height);
343 paint_.setAntiAlias(true);
344 paint_.setStrokeWidth(thickness);
346 const bool clipped = pieces_.size() > 1;
348 for (size_t i = 0; i < pieces_.size(); ++i) {
349 paint_.setColor(pieces_[i].second);
353 canvas_->ClipRect(Rect(x, 0, pieces_[i].first, start_.y() + thickness));
356 canvas_->DrawLine(start_, end, paint_);
361 x += pieces_[i].first;
365 StyleIterator::StyleIterator(const BreakList<SkColor>& colors,
366 const std::vector<BreakList<bool> >& styles)
369 color_ = colors_.breaks().begin();
370 for (size_t i = 0; i < styles_.size(); ++i)
371 style_.push_back(styles_[i].breaks().begin());
374 StyleIterator::~StyleIterator() {}
376 Range StyleIterator::GetRange() const {
377 Range range(colors_.GetRange(color_));
378 for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
379 range = range.Intersect(styles_[i].GetRange(style_[i]));
383 void StyleIterator::UpdatePosition(size_t position) {
384 color_ = colors_.GetBreak(position);
385 for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
386 style_[i] = styles_[i].GetBreak(position);
389 LineSegment::LineSegment() : run(0) {}
391 LineSegment::~LineSegment() {}
393 Line::Line() : preceding_heights(0), baseline(0) {}
397 } // namespace internal
399 RenderText::~RenderText() {
402 void RenderText::SetText(const base::string16& text) {
403 DCHECK(!composition_range_.IsValid());
408 // Adjust ranged styles and colors to accommodate a new text length.
409 const size_t text_length = text_.length();
410 colors_.SetMax(text_length);
411 for (size_t style = 0; style < NUM_TEXT_STYLES; ++style)
412 styles_[style].SetMax(text_length);
413 cached_bounds_and_offset_valid_ = false;
415 // Reset selection model. SetText should always followed by SetSelectionModel
416 // or SetCursorPosition in upper layer.
417 SetSelectionModel(SelectionModel());
419 // Invalidate the cached text direction if it depends on the text contents.
420 if (directionality_mode_ == DIRECTIONALITY_FROM_TEXT)
421 text_direction_ = base::i18n::UNKNOWN_DIRECTION;
423 obscured_reveal_index_ = -1;
427 void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment) {
428 if (horizontal_alignment_ != alignment) {
429 horizontal_alignment_ = alignment;
430 display_offset_ = Vector2d();
431 cached_bounds_and_offset_valid_ = false;
435 void RenderText::SetFontList(const FontList& font_list) {
436 font_list_ = font_list;
437 baseline_ = kInvalidBaseline;
438 cached_bounds_and_offset_valid_ = false;
442 void RenderText::SetCursorEnabled(bool cursor_enabled) {
443 cursor_enabled_ = cursor_enabled;
444 cached_bounds_and_offset_valid_ = false;
447 void RenderText::ToggleInsertMode() {
448 insert_mode_ = !insert_mode_;
449 cached_bounds_and_offset_valid_ = false;
452 void RenderText::SetObscured(bool obscured) {
453 if (obscured != obscured_) {
454 obscured_ = obscured;
455 obscured_reveal_index_ = -1;
456 cached_bounds_and_offset_valid_ = false;
461 void RenderText::SetObscuredRevealIndex(int index) {
462 if (obscured_reveal_index_ == index)
465 obscured_reveal_index_ = index;
466 cached_bounds_and_offset_valid_ = false;
470 void RenderText::SetMultiline(bool multiline) {
471 if (multiline != multiline_) {
472 multiline_ = multiline;
473 cached_bounds_and_offset_valid_ = false;
478 void RenderText::SetElideBehavior(ElideBehavior elide_behavior) {
479 // TODO(skanuj) : Add a test for triggering layout change.
480 if (elide_behavior_ != elide_behavior) {
481 elide_behavior_ = elide_behavior;
486 void RenderText::SetDisplayRect(const Rect& r) {
487 if (r != display_rect_) {
489 baseline_ = kInvalidBaseline;
490 cached_bounds_and_offset_valid_ = false;
492 if (elide_behavior_ != gfx::NO_ELIDE)
497 void RenderText::SetCursorPosition(size_t position) {
498 MoveCursorTo(position, false);
501 void RenderText::MoveCursor(BreakType break_type,
502 VisualCursorDirection direction,
504 SelectionModel cursor(cursor_position(), selection_model_.caret_affinity());
505 // Cancelling a selection moves to the edge of the selection.
506 if (break_type != LINE_BREAK && !selection().is_empty() && !select) {
507 SelectionModel selection_start = GetSelectionModelForSelectionStart();
508 int start_x = GetCursorBounds(selection_start, true).x();
509 int cursor_x = GetCursorBounds(cursor, true).x();
510 // Use the selection start if it is left (when |direction| is CURSOR_LEFT)
511 // or right (when |direction| is CURSOR_RIGHT) of the selection end.
512 if (direction == CURSOR_RIGHT ? start_x > cursor_x : start_x < cursor_x)
513 cursor = selection_start;
514 // Use the nearest word boundary in the proper |direction| for word breaks.
515 if (break_type == WORD_BREAK)
516 cursor = GetAdjacentSelectionModel(cursor, break_type, direction);
517 // Use an adjacent selection model if the cursor is not at a valid position.
518 if (!IsValidCursorIndex(cursor.caret_pos()))
519 cursor = GetAdjacentSelectionModel(cursor, CHARACTER_BREAK, direction);
521 cursor = GetAdjacentSelectionModel(cursor, break_type, direction);
524 cursor.set_selection_start(selection().start());
525 MoveCursorTo(cursor);
528 bool RenderText::MoveCursorTo(const SelectionModel& model) {
529 // Enforce valid selection model components.
530 size_t text_length = text().length();
531 Range range(std::min(model.selection().start(), text_length),
532 std::min(model.caret_pos(), text_length));
533 // The current model only supports caret positions at valid cursor indices.
534 if (!IsValidCursorIndex(range.start()) || !IsValidCursorIndex(range.end()))
536 SelectionModel sel(range, model.caret_affinity());
537 bool changed = sel != selection_model_;
538 SetSelectionModel(sel);
542 bool RenderText::SelectRange(const Range& range) {
543 Range sel(std::min(range.start(), text().length()),
544 std::min(range.end(), text().length()));
545 // Allow selection bounds at valid indicies amid multi-character graphemes.
546 if (!IsValidLogicalIndex(sel.start()) || !IsValidLogicalIndex(sel.end()))
548 LogicalCursorDirection affinity =
549 (sel.is_reversed() || sel.is_empty()) ? CURSOR_FORWARD : CURSOR_BACKWARD;
550 SetSelectionModel(SelectionModel(sel, affinity));
554 bool RenderText::IsPointInSelection(const Point& point) {
555 if (selection().is_empty())
557 SelectionModel cursor = FindCursorPosition(point);
558 return RangeContainsCaret(
559 selection(), cursor.caret_pos(), cursor.caret_affinity());
562 void RenderText::ClearSelection() {
563 SetSelectionModel(SelectionModel(cursor_position(),
564 selection_model_.caret_affinity()));
567 void RenderText::SelectAll(bool reversed) {
568 const size_t length = text().length();
569 const Range all = reversed ? Range(length, 0) : Range(0, length);
570 const bool success = SelectRange(all);
574 void RenderText::SelectWord() {
580 size_t selection_max = selection().GetMax();
582 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
583 bool success = iter.Init();
588 size_t selection_min = selection().GetMin();
589 if (selection_min == text().length() && selection_min != 0)
592 for (; selection_min != 0; --selection_min) {
593 if (iter.IsStartOfWord(selection_min) ||
594 iter.IsEndOfWord(selection_min))
598 if (selection_min == selection_max && selection_max != text().length())
601 for (; selection_max < text().length(); ++selection_max)
602 if (iter.IsEndOfWord(selection_max) || iter.IsStartOfWord(selection_max))
605 const bool reversed = selection().is_reversed();
606 MoveCursorTo(reversed ? selection_max : selection_min, false);
607 MoveCursorTo(reversed ? selection_min : selection_max, true);
610 const Range& RenderText::GetCompositionRange() const {
611 return composition_range_;
614 void RenderText::SetCompositionRange(const Range& composition_range) {
615 CHECK(!composition_range.IsValid() ||
616 Range(0, text_.length()).Contains(composition_range));
617 composition_range_.set_end(composition_range.end());
618 composition_range_.set_start(composition_range.start());
622 void RenderText::SetColor(SkColor value) {
623 colors_.SetValue(value);
626 // TODO(msw): Windows applies colors and decorations in the layout process.
627 cached_bounds_and_offset_valid_ = false;
632 void RenderText::ApplyColor(SkColor value, const Range& range) {
633 colors_.ApplyValue(value, range);
636 // TODO(msw): Windows applies colors and decorations in the layout process.
637 cached_bounds_and_offset_valid_ = false;
642 void RenderText::SetStyle(TextStyle style, bool value) {
643 styles_[style].SetValue(value);
645 // Only invalidate the layout on font changes; not for colors or decorations.
646 bool invalidate = (style == BOLD) || (style == ITALIC);
648 // TODO(msw): Windows applies colors and decorations in the layout process.
652 cached_bounds_and_offset_valid_ = false;
657 void RenderText::ApplyStyle(TextStyle style, bool value, const Range& range) {
658 styles_[style].ApplyValue(value, range);
660 // Only invalidate the layout on font changes; not for colors or decorations.
661 bool invalidate = (style == BOLD) || (style == ITALIC);
663 // TODO(msw): Windows applies colors and decorations in the layout process.
667 cached_bounds_and_offset_valid_ = false;
672 bool RenderText::GetStyle(TextStyle style) const {
673 return (styles_[style].breaks().size() == 1) &&
674 styles_[style].breaks().front().second;
677 void RenderText::SetDirectionalityMode(DirectionalityMode mode) {
678 if (mode == directionality_mode_)
681 directionality_mode_ = mode;
682 text_direction_ = base::i18n::UNKNOWN_DIRECTION;
683 cached_bounds_and_offset_valid_ = false;
687 base::i18n::TextDirection RenderText::GetTextDirection() {
688 if (text_direction_ == base::i18n::UNKNOWN_DIRECTION) {
689 switch (directionality_mode_) {
690 case DIRECTIONALITY_FROM_TEXT:
691 // Derive the direction from the display text, which differs from text()
692 // in the case of obscured (password) textfields.
694 base::i18n::GetFirstStrongCharacterDirection(GetLayoutText());
696 case DIRECTIONALITY_FROM_UI:
697 text_direction_ = base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT :
698 base::i18n::LEFT_TO_RIGHT;
700 case DIRECTIONALITY_FORCE_LTR:
701 text_direction_ = base::i18n::LEFT_TO_RIGHT;
703 case DIRECTIONALITY_FORCE_RTL:
704 text_direction_ = base::i18n::RIGHT_TO_LEFT;
711 return text_direction_;
714 VisualCursorDirection RenderText::GetVisualDirectionOfLogicalEnd() {
715 return GetTextDirection() == base::i18n::LEFT_TO_RIGHT ?
716 CURSOR_RIGHT : CURSOR_LEFT;
719 SizeF RenderText::GetStringSizeF() {
720 const Size size = GetStringSize();
721 return SizeF(size.width(), size.height());
724 int RenderText::GetContentWidth() {
725 return GetStringSize().width() + (cursor_enabled_ ? 1 : 0);
728 int RenderText::GetBaseline() {
729 if (baseline_ == kInvalidBaseline)
730 baseline_ = DetermineBaselineCenteringText(display_rect(), font_list());
731 DCHECK_NE(kInvalidBaseline, baseline_);
735 void RenderText::Draw(Canvas* canvas) {
738 if (clip_to_display_rect()) {
739 Rect clip_rect(display_rect());
740 clip_rect.Inset(ShadowValue::GetMargin(text_shadows_));
743 canvas->ClipRect(clip_rect);
746 if (!text().empty() && focused())
747 DrawSelection(canvas);
749 if (cursor_enabled() && cursor_visible() && focused())
750 DrawCursor(canvas, selection_model_);
753 DrawVisualText(canvas);
755 if (clip_to_display_rect())
759 void RenderText::DrawCursor(Canvas* canvas, const SelectionModel& position) {
760 // Paint cursor. Replace cursor is drawn as rectangle for now.
761 // TODO(msw): Draw a better cursor with a better indication of association.
762 canvas->FillRect(GetCursorBounds(position, true), cursor_color_);
765 bool RenderText::IsValidLogicalIndex(size_t index) {
766 // Check that the index is at a valid code point (not mid-surrgate-pair) and
767 // that it's not truncated from the layout text (its glyph may be shown).
769 // Indices within truncated text are disallowed so users can easily interact
770 // with the underlying truncated text using the ellipsis as a proxy. This lets
771 // users select all text, select the truncated text, and transition from the
772 // last rendered glyph to the end of the text without getting invisible cursor
773 // positions nor needing unbounded arrow key presses to traverse the ellipsis.
774 return index == 0 || index == text().length() ||
775 (index < text().length() &&
776 (truncate_length_ == 0 || index < truncate_length_) &&
777 IsValidCodePointIndex(text(), index));
780 Rect RenderText::GetCursorBounds(const SelectionModel& caret,
782 // TODO(ckocagil): Support multiline. This function should return the height
783 // of the line the cursor is on. |GetStringSize()| now returns
784 // the multiline size, eliminate its use here.
787 size_t caret_pos = caret.caret_pos();
788 DCHECK(IsValidLogicalIndex(caret_pos));
789 // In overtype mode, ignore the affinity and always indicate that we will
790 // overtype the next character.
791 LogicalCursorDirection caret_affinity =
792 insert_mode ? caret.caret_affinity() : CURSOR_FORWARD;
793 int x = 0, width = 1;
794 Size size = GetStringSize();
795 if (caret_pos == (caret_affinity == CURSOR_BACKWARD ? 0 : text().length())) {
796 // The caret is attached to the boundary. Always return a 1-dip width caret,
797 // since there is nothing to overtype.
798 if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT) == (caret_pos == 0))
801 size_t grapheme_start = (caret_affinity == CURSOR_FORWARD) ?
802 caret_pos : IndexOfAdjacentGrapheme(caret_pos, CURSOR_BACKWARD);
803 Range xspan(GetGlyphBounds(grapheme_start));
805 x = (caret_affinity == CURSOR_BACKWARD) ? xspan.end() : xspan.start();
806 } else { // overtype mode
808 width = xspan.length();
811 return Rect(ToViewPoint(Point(x, 0)), Size(width, size.height()));
814 const Rect& RenderText::GetUpdatedCursorBounds() {
815 UpdateCachedBoundsAndOffset();
816 return cursor_bounds_;
819 size_t RenderText::IndexOfAdjacentGrapheme(size_t index,
820 LogicalCursorDirection direction) {
821 if (index > text().length())
822 return text().length();
826 if (direction == CURSOR_FORWARD) {
827 while (index < text().length()) {
829 if (IsValidCursorIndex(index))
832 return text().length();
837 if (IsValidCursorIndex(index))
843 SelectionModel RenderText::GetSelectionModelForSelectionStart() {
844 const Range& sel = selection();
846 return selection_model_;
847 return SelectionModel(sel.start(),
848 sel.is_reversed() ? CURSOR_BACKWARD : CURSOR_FORWARD);
851 void RenderText::SetTextShadows(const ShadowValues& shadows) {
852 text_shadows_ = shadows;
855 RenderText::RenderText()
856 : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT : ALIGN_LEFT),
857 directionality_mode_(DIRECTIONALITY_FROM_TEXT),
858 text_direction_(base::i18n::UNKNOWN_DIRECTION),
859 cursor_enabled_(true),
860 cursor_visible_(false),
862 cursor_color_(kDefaultColor),
863 selection_color_(kDefaultColor),
864 selection_background_focused_color_(kDefaultSelectionBackgroundColor),
866 composition_range_(Range::InvalidRange()),
867 colors_(kDefaultColor),
868 styles_(NUM_TEXT_STYLES),
869 composition_and_selection_styles_applied_(false),
871 obscured_reveal_index_(-1),
873 elide_behavior_(NO_ELIDE),
877 background_is_transparent_(false),
878 clip_to_display_rect_(true),
879 baseline_(kInvalidBaseline),
880 cached_bounds_and_offset_valid_(false) {
883 const Vector2d& RenderText::GetUpdatedDisplayOffset() {
884 UpdateCachedBoundsAndOffset();
885 return display_offset_;
888 SelectionModel RenderText::GetAdjacentSelectionModel(
889 const SelectionModel& current,
890 BreakType break_type,
891 VisualCursorDirection direction) {
894 if (break_type == LINE_BREAK || text().empty())
895 return EdgeSelectionModel(direction);
896 if (break_type == CHARACTER_BREAK)
897 return AdjacentCharSelectionModel(current, direction);
898 DCHECK(break_type == WORD_BREAK);
899 return AdjacentWordSelectionModel(current, direction);
902 SelectionModel RenderText::EdgeSelectionModel(
903 VisualCursorDirection direction) {
904 if (direction == GetVisualDirectionOfLogicalEnd())
905 return SelectionModel(text().length(), CURSOR_FORWARD);
906 return SelectionModel(0, CURSOR_BACKWARD);
909 void RenderText::SetSelectionModel(const SelectionModel& model) {
910 DCHECK_LE(model.selection().GetMax(), text().length());
911 selection_model_ = model;
912 cached_bounds_and_offset_valid_ = false;
915 const base::string16& RenderText::GetLayoutText() const {
919 const BreakList<size_t>& RenderText::GetLineBreaks() {
920 if (line_breaks_.max() != 0)
923 const base::string16& layout_text = GetLayoutText();
924 const size_t text_length = layout_text.length();
925 line_breaks_.SetValue(0);
926 line_breaks_.SetMax(text_length);
927 base::i18n::BreakIterator iter(layout_text,
928 base::i18n::BreakIterator::BREAK_LINE);
929 const bool success = iter.Init();
933 line_breaks_.ApplyValue(iter.pos(), Range(iter.pos(), text_length));
934 } while (iter.Advance());
939 void RenderText::ApplyCompositionAndSelectionStyles() {
940 // Save the underline and color breaks to undo the temporary styles later.
941 DCHECK(!composition_and_selection_styles_applied_);
942 saved_colors_ = colors_;
943 saved_underlines_ = styles_[UNDERLINE];
945 // Apply an underline to the composition range in |underlines|.
946 if (composition_range_.IsValid() && !composition_range_.is_empty())
947 styles_[UNDERLINE].ApplyValue(true, composition_range_);
949 // Apply the selected text color to the [un-reversed] selection range.
950 if (!selection().is_empty() && focused()) {
951 const Range range(selection().GetMin(), selection().GetMax());
952 colors_.ApplyValue(selection_color_, range);
954 composition_and_selection_styles_applied_ = true;
957 void RenderText::UndoCompositionAndSelectionStyles() {
958 // Restore the underline and color breaks to undo the temporary styles.
959 DCHECK(composition_and_selection_styles_applied_);
960 colors_ = saved_colors_;
961 styles_[UNDERLINE] = saved_underlines_;
962 composition_and_selection_styles_applied_ = false;
965 Vector2d RenderText::GetLineOffset(size_t line_number) {
966 Vector2d offset = display_rect().OffsetFromOrigin();
967 // TODO(ckocagil): Apply the display offset for multiline scrolling.
969 offset.Add(GetUpdatedDisplayOffset());
971 offset.Add(Vector2d(0, lines_[line_number].preceding_heights));
972 offset.Add(GetAlignmentOffset(line_number));
976 Point RenderText::ToTextPoint(const Point& point) {
977 return point - GetLineOffset(0);
978 // TODO(ckocagil): Convert multiline view space points to text space.
981 Point RenderText::ToViewPoint(const Point& point) {
983 return point + GetLineOffset(0);
985 // TODO(ckocagil): Traverse individual line segments for RTL support.
986 DCHECK(!lines_.empty());
989 for (; line < lines_.size() && x > lines_[line].size.width(); ++line)
990 x -= lines_[line].size.width();
991 return Point(x, point.y()) + GetLineOffset(line);
994 std::vector<Rect> RenderText::TextBoundsToViewBounds(const Range& x) {
995 std::vector<Rect> rects;
998 rects.push_back(Rect(ToViewPoint(Point(x.GetMin(), 0)),
999 Size(x.length(), GetStringSize().height())));
1005 // Each line segment keeps its position in text coordinates. Traverse all line
1006 // segments and if the segment intersects with the given range, add the view
1007 // rect corresponding to the intersection to |rects|.
1008 for (size_t line = 0; line < lines_.size(); ++line) {
1010 const Vector2d offset = GetLineOffset(line);
1011 for (size_t i = 0; i < lines_[line].segments.size(); ++i) {
1012 const internal::LineSegment* segment = &lines_[line].segments[i];
1013 const Range intersection = segment->x_range.Intersect(x);
1014 if (!intersection.is_empty()) {
1015 Rect rect(line_x + intersection.start() - segment->x_range.start(),
1016 0, intersection.length(), lines_[line].size.height());
1017 rects.push_back(rect + offset);
1019 line_x += segment->x_range.length();
1026 Vector2d RenderText::GetAlignmentOffset(size_t line_number) {
1027 // TODO(ckocagil): Enable |lines_| usage in other platforms.
1029 DCHECK_LT(line_number, lines_.size());
1032 if (horizontal_alignment_ != ALIGN_LEFT) {
1034 const int width = lines_[line_number].size.width() +
1035 (cursor_enabled_ ? 1 : 0);
1037 const int width = GetContentWidth();
1039 offset.set_x(display_rect().width() - width);
1040 if (horizontal_alignment_ == ALIGN_CENTER)
1041 offset.set_x(offset.x() / 2);
1044 // Vertically center the text.
1046 const int text_height = lines_.back().preceding_heights +
1047 lines_.back().size.height();
1048 offset.set_y((display_rect_.height() - text_height) / 2);
1050 offset.set_y(GetBaseline() - GetLayoutTextBaseline());
1056 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer* renderer) {
1057 if (multiline() || (!fade_head() && !fade_tail()))
1060 const int display_width = display_rect().width();
1062 // If the text fits as-is, no need to fade.
1063 if (GetStringSize().width() <= display_width)
1066 int gradient_width = CalculateFadeGradientWidth(font_list(), display_width);
1067 if (gradient_width == 0)
1070 bool fade_left = fade_head();
1071 bool fade_right = fade_tail();
1072 // Under RTL, |fade_right| == |fade_head|.
1073 // TODO(asvitkine): This is currently not based on GetTextDirection() because
1074 // RenderTextWin does not return a direction that's based on
1075 // the text content.
1076 if (horizontal_alignment_ == ALIGN_RIGHT)
1077 std::swap(fade_left, fade_right);
1079 Rect solid_part = display_rect();
1083 left_part = solid_part;
1084 left_part.Inset(0, 0, solid_part.width() - gradient_width, 0);
1085 solid_part.Inset(gradient_width, 0, 0, 0);
1088 right_part = solid_part;
1089 right_part.Inset(solid_part.width() - gradient_width, 0, 0, 0);
1090 solid_part.Inset(0, 0, gradient_width, 0);
1093 Rect text_rect = display_rect();
1094 text_rect.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1096 // TODO(msw): Use the actual text colors corresponding to each faded part.
1097 skia::RefPtr<SkShader> shader = CreateFadeShader(
1098 text_rect, left_part, right_part, colors_.breaks().front().second);
1100 renderer->SetShader(shader.get(), display_rect());
1103 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer* renderer) {
1104 skia::RefPtr<SkDrawLooper> looper = CreateShadowDrawLooper(text_shadows_);
1105 renderer->SetDrawLooper(looper.get());
1109 bool RenderText::RangeContainsCaret(const Range& range,
1111 LogicalCursorDirection caret_affinity) {
1112 // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1113 size_t adjacent = (caret_affinity == CURSOR_BACKWARD) ?
1114 caret_pos - 1 : caret_pos + 1;
1115 return range.Contains(Range(caret_pos, adjacent));
1118 void RenderText::MoveCursorTo(size_t position, bool select) {
1119 size_t cursor = std::min(position, text().length());
1120 if (IsValidCursorIndex(cursor))
1121 SetSelectionModel(SelectionModel(
1122 Range(select ? selection().start() : cursor, cursor),
1123 (cursor == 0) ? CURSOR_FORWARD : CURSOR_BACKWARD));
1126 void RenderText::UpdateLayoutText() {
1127 layout_text_.clear();
1128 line_breaks_.SetMax(0);
1131 size_t obscured_text_length =
1132 static_cast<size_t>(gfx::UTF16IndexToOffset(text_, 0, text_.length()));
1133 layout_text_.assign(obscured_text_length, kPasswordReplacementChar);
1135 if (obscured_reveal_index_ >= 0 &&
1136 obscured_reveal_index_ < static_cast<int>(text_.length())) {
1137 // Gets the index range in |text_| to be revealed.
1138 size_t start = obscured_reveal_index_;
1139 U16_SET_CP_START(text_.data(), 0, start);
1141 UChar32 unused_char;
1142 U16_NEXT(text_.data(), end, text_.length(), unused_char);
1144 // Gets the index in |layout_text_| to be replaced.
1145 const size_t cp_start =
1146 static_cast<size_t>(gfx::UTF16IndexToOffset(text_, 0, start));
1147 if (layout_text_.length() > cp_start)
1148 layout_text_.replace(cp_start, 1, text_.substr(start, end - start));
1151 layout_text_ = text_;
1154 const base::string16& text = layout_text_;
1155 if (truncate_length_ > 0 && truncate_length_ < text.length()) {
1156 // Truncate the text at a valid character break and append an ellipsis.
1157 icu::StringCharacterIterator iter(text.c_str());
1158 iter.setIndex32(truncate_length_ - 1);
1159 layout_text_.assign(text.substr(0, iter.getIndex()) + gfx::kEllipsisUTF16);
1162 if (elide_behavior_ != NO_ELIDE && display_rect_.width() > 0 &&
1163 !layout_text_.empty() && GetContentWidth() > display_rect_.width()) {
1164 // This doesn't trim styles so ellipsis may get rendered as a different
1165 // style than the preceding text. See crbug.com/327850.
1166 layout_text_.assign(ElideText(layout_text_));
1172 // TODO(skanuj): Fix code duplication with ElideText in ui/gfx/text_elider.cc
1173 // See crbug.com/327846
1174 base::string16 RenderText::ElideText(const base::string16& text) {
1175 const bool insert_ellipsis = (elide_behavior_ != TRUNCATE_AT_END);
1176 // Create a RenderText copy with attributes that affect the rendering width.
1177 scoped_ptr<RenderText> render_text(CreateInstance());
1178 render_text->SetFontList(font_list_);
1179 render_text->SetDirectionalityMode(directionality_mode_);
1180 render_text->SetCursorEnabled(cursor_enabled_);
1182 render_text->styles_ = styles_;
1183 render_text->colors_ = colors_;
1184 render_text->SetText(text);
1185 const int current_text_pixel_width = render_text->GetContentWidth();
1187 const base::string16 ellipsis = base::string16(gfx::kEllipsisUTF16);
1188 const bool elide_in_middle = false;
1189 const bool elide_at_beginning = false;
1190 StringSlicer slicer(text, ellipsis, elide_in_middle, elide_at_beginning);
1192 // Pango will return 0 width for absurdly long strings. Cut the string in
1193 // half and try again.
1194 // This is caused by an int overflow in Pango (specifically, in
1195 // pango_glyph_string_extents_range). It's actually more subtle than just
1196 // returning 0, since on super absurdly long strings, the int can wrap and
1197 // return positive numbers again. Detecting that is probably not worth it
1198 // (eliding way too much from a ridiculous string is probably still
1199 // ridiculous), but we should check other widths for bogus values as well.
1200 if (current_text_pixel_width <= 0 && !text.empty())
1201 return ElideText(slicer.CutString(text.length() / 2, insert_ellipsis));
1203 if (current_text_pixel_width <= display_rect_.width())
1206 render_text->SetText(base::string16());
1207 render_text->SetText(ellipsis);
1208 const int ellipsis_width = render_text->GetContentWidth();
1210 if (insert_ellipsis && (ellipsis_width >= display_rect_.width()))
1211 return base::string16();
1213 // Use binary search to compute the elided text.
1215 size_t hi = text.length() - 1;
1216 const base::i18n::TextDirection text_direction = GetTextDirection();
1217 for (size_t guess = (lo + hi) / 2; lo <= hi; guess = (lo + hi) / 2) {
1218 // Restore styles and colors. They will be truncated to size by SetText.
1219 render_text->styles_ = styles_;
1220 render_text->colors_ = colors_;
1221 base::string16 new_text = slicer.CutString(guess, false);
1222 render_text->SetText(new_text);
1224 // This has to be an additional step so that the ellipsis is rendered with
1225 // same style as trailing part of the text.
1226 if (insert_ellipsis) {
1227 // When ellipsis follows text whose directionality is not the same as that
1228 // of the whole text, it will be rendered with the directionality of the
1229 // whole text. Since we want ellipsis to indicate continuation of the
1230 // preceding text, we force the directionality of ellipsis to be same as
1231 // the preceding text using LTR or RTL markers.
1232 base::i18n::TextDirection trailing_text_direction =
1233 base::i18n::GetLastStrongCharacterDirection(new_text);
1234 new_text.append(ellipsis);
1235 if (trailing_text_direction != text_direction) {
1236 if (trailing_text_direction == base::i18n::LEFT_TO_RIGHT)
1237 new_text += base::i18n::kLeftToRightMark;
1239 new_text += base::i18n::kRightToLeftMark;
1241 render_text->SetText(new_text);
1244 // We check the width of the whole desired string at once to ensure we
1245 // handle kerning/ligatures/etc. correctly.
1246 const int guess_width = render_text->GetContentWidth();
1247 if (guess_width == display_rect_.width())
1249 if (guess_width > display_rect_.width()) {
1251 // Move back if we are on loop terminating condition, and guess is wider
1260 return render_text->text();
1263 void RenderText::UpdateCachedBoundsAndOffset() {
1264 if (cached_bounds_and_offset_valid_)
1267 // TODO(ckocagil): Add support for scrolling multiline text.
1269 // First, set the valid flag true to calculate the current cursor bounds using
1270 // the stale |display_offset_|. Applying |delta_offset| at the end of this
1271 // function will set |cursor_bounds_| and |display_offset_| to correct values.
1272 cached_bounds_and_offset_valid_ = true;
1273 if (cursor_enabled())
1274 cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_);
1276 // Update |display_offset_| to ensure the current cursor is visible.
1277 const int display_width = display_rect_.width();
1278 const int content_width = GetContentWidth();
1281 if (content_width <= display_width || !cursor_enabled()) {
1282 // Don't pan if the text fits in the display width or when the cursor is
1284 delta_x = -display_offset_.x();
1285 } else if (cursor_bounds_.right() > display_rect_.right()) {
1286 // TODO(xji): when the character overflow is a RTL character, currently, if
1287 // we pan cursor at the rightmost position, the entered RTL character is not
1288 // displayed. Should pan cursor to show the last logical characters.
1290 // Pan to show the cursor when it overflows to the right.
1291 delta_x = display_rect_.right() - cursor_bounds_.right();
1292 } else if (cursor_bounds_.x() < display_rect_.x()) {
1293 // TODO(xji): have similar problem as above when overflow character is a
1296 // Pan to show the cursor when it overflows to the left.
1297 delta_x = display_rect_.x() - cursor_bounds_.x();
1298 } else if (display_offset_.x() != 0) {
1299 // Reduce the pan offset to show additional overflow text when the display
1301 const int negate_rtl = horizontal_alignment_ == ALIGN_RIGHT ? -1 : 1;
1302 const int offset = negate_rtl * display_offset_.x();
1303 if (display_width > (content_width + offset)) {
1304 delta_x = negate_rtl * (display_width - (content_width + offset));
1308 Vector2d delta_offset(delta_x, 0);
1309 display_offset_ += delta_offset;
1310 cursor_bounds_ += delta_offset;
1313 void RenderText::DrawSelection(Canvas* canvas) {
1314 const std::vector<Rect> sel = GetSubstringBounds(selection());
1315 for (std::vector<Rect>::const_iterator i = sel.begin(); i < sel.end(); ++i)
1316 canvas->FillRect(*i, selection_background_focused_color_);