Revert "adding baseline options for super/sub scripting"
[chromium-blink-merge.git] / ui / gfx / render_text.cc
blobc4f841dfcf7898f4b590f31839f865e8afbdac74
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"
7 #include <algorithm>
8 #include <climits>
10 #include "base/command_line.h"
11 #include "base/i18n/break_iterator.h"
12 #include "base/logging.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/trace_event/trace_event.h"
17 #include "third_party/icu/source/common/unicode/rbbi.h"
18 #include "third_party/icu/source/common/unicode/utf16.h"
19 #include "third_party/skia/include/core/SkTypeface.h"
20 #include "third_party/skia/include/effects/SkGradientShader.h"
21 #include "ui/gfx/canvas.h"
22 #include "ui/gfx/geometry/insets.h"
23 #include "ui/gfx/geometry/safe_integer_conversions.h"
24 #include "ui/gfx/render_text_harfbuzz.h"
25 #include "ui/gfx/scoped_canvas.h"
26 #include "ui/gfx/skia_util.h"
27 #include "ui/gfx/switches.h"
28 #include "ui/gfx/text_elider.h"
29 #include "ui/gfx/text_utils.h"
30 #include "ui/gfx/utf16_indexing.h"
32 #if defined(OS_MACOSX)
33 #include "ui/gfx/render_text_mac.h"
34 #endif // defined(OS_MACOSX)
36 namespace gfx {
38 namespace {
40 // All chars are replaced by this char when the password style is set.
41 // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*'
42 // that's available in the font (find_invisible_char() in gtkentry.c).
43 const base::char16 kPasswordReplacementChar = '*';
45 // Default color used for the text and cursor.
46 const SkColor kDefaultColor = SK_ColorBLACK;
48 // Default color used for drawing selection background.
49 const SkColor kDefaultSelectionBackgroundColor = SK_ColorGRAY;
51 // Fraction of the text size to lower a strike through below the baseline.
52 const SkScalar kStrikeThroughOffset = (-SK_Scalar1 * 6 / 21);
53 // Fraction of the text size to lower an underline below the baseline.
54 const SkScalar kUnderlineOffset = (SK_Scalar1 / 9);
55 // Fraction of the text size to use for a strike through or under-line.
56 const SkScalar kLineThickness = (SK_Scalar1 / 18);
57 // Fraction of the text size to use for a top margin of a diagonal strike.
58 const SkScalar kDiagonalStrikeMarginOffset = (SK_Scalar1 / 4);
60 // Invalid value of baseline. Assigning this value to |baseline_| causes
61 // re-calculation of baseline.
62 const int kInvalidBaseline = INT_MAX;
64 // Returns the baseline, with which the text best appears vertically centered.
65 int DetermineBaselineCenteringText(const Rect& display_rect,
66 const FontList& font_list) {
67 const int display_height = display_rect.height();
68 const int font_height = font_list.GetHeight();
69 // Lower and upper bound of baseline shift as we try to show as much area of
70 // text as possible. In particular case of |display_height| == |font_height|,
71 // we do not want to shift the baseline.
72 const int min_shift = std::min(0, display_height - font_height);
73 const int max_shift = std::abs(display_height - font_height);
74 const int baseline = font_list.GetBaseline();
75 const int cap_height = font_list.GetCapHeight();
76 const int internal_leading = baseline - cap_height;
77 // Some platforms don't support getting the cap height, and simply return
78 // the entire font ascent from GetCapHeight(). Centering the ascent makes
79 // the font look too low, so if GetCapHeight() returns the ascent, center
80 // the entire font height instead.
81 const int space =
82 display_height - ((internal_leading != 0) ? cap_height : font_height);
83 const int baseline_shift = space / 2 - internal_leading;
84 return baseline + std::max(min_shift, std::min(max_shift, baseline_shift));
87 // Converts |Font::FontStyle| flags to |SkTypeface::Style| flags.
88 SkTypeface::Style ConvertFontStyleToSkiaTypefaceStyle(int font_style) {
89 int skia_style = SkTypeface::kNormal;
90 skia_style |= (font_style & Font::BOLD) ? SkTypeface::kBold : 0;
91 skia_style |= (font_style & Font::ITALIC) ? SkTypeface::kItalic : 0;
92 return static_cast<SkTypeface::Style>(skia_style);
95 // Given |font| and |display_width|, returns the width of the fade gradient.
96 int CalculateFadeGradientWidth(const FontList& font_list, int display_width) {
97 // Fade in/out about 2.5 characters of the beginning/end of the string.
98 // The .5 here is helpful if one of the characters is a space.
99 // Use a quarter of the display width if the display width is very short.
100 const int average_character_width = font_list.GetExpectedTextWidth(1);
101 const double gradient_width = std::min(average_character_width * 2.5,
102 display_width / 4.0);
103 DCHECK_GE(gradient_width, 0.0);
104 return static_cast<int>(floor(gradient_width + 0.5));
107 // Appends to |positions| and |colors| values corresponding to the fade over
108 // |fade_rect| from color |c0| to color |c1|.
109 void AddFadeEffect(const Rect& text_rect,
110 const Rect& fade_rect,
111 SkColor c0,
112 SkColor c1,
113 std::vector<SkScalar>* positions,
114 std::vector<SkColor>* colors) {
115 const SkScalar left = static_cast<SkScalar>(fade_rect.x() - text_rect.x());
116 const SkScalar width = static_cast<SkScalar>(fade_rect.width());
117 const SkScalar p0 = left / text_rect.width();
118 const SkScalar p1 = (left + width) / text_rect.width();
119 // Prepend 0.0 to |positions|, as required by Skia.
120 if (positions->empty() && p0 != 0.0) {
121 positions->push_back(0.0);
122 colors->push_back(c0);
124 positions->push_back(p0);
125 colors->push_back(c0);
126 positions->push_back(p1);
127 colors->push_back(c1);
130 // Creates a SkShader to fade the text, with |left_part| specifying the left
131 // fade effect, if any, and |right_part| specifying the right fade effect.
132 skia::RefPtr<SkShader> CreateFadeShader(const Rect& text_rect,
133 const Rect& left_part,
134 const Rect& right_part,
135 SkColor color) {
136 // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color.
137 const SkColor fade_color = SkColorSetA(color, 51);
138 std::vector<SkScalar> positions;
139 std::vector<SkColor> colors;
141 if (!left_part.IsEmpty())
142 AddFadeEffect(text_rect, left_part, fade_color, color,
143 &positions, &colors);
144 if (!right_part.IsEmpty())
145 AddFadeEffect(text_rect, right_part, color, fade_color,
146 &positions, &colors);
147 DCHECK(!positions.empty());
149 // Terminate |positions| with 1.0, as required by Skia.
150 if (positions.back() != 1.0) {
151 positions.push_back(1.0);
152 colors.push_back(colors.back());
155 SkPoint points[2];
156 points[0].iset(text_rect.x(), text_rect.y());
157 points[1].iset(text_rect.right(), text_rect.y());
159 return skia::AdoptRef(
160 SkGradientShader::CreateLinear(&points[0], &colors[0], &positions[0],
161 colors.size(), SkShader::kClamp_TileMode));
164 // Converts a FontRenderParams::Hinting value to the corresponding
165 // SkPaint::Hinting value.
166 SkPaint::Hinting FontRenderParamsHintingToSkPaintHinting(
167 FontRenderParams::Hinting params_hinting) {
168 switch (params_hinting) {
169 case FontRenderParams::HINTING_NONE: return SkPaint::kNo_Hinting;
170 case FontRenderParams::HINTING_SLIGHT: return SkPaint::kSlight_Hinting;
171 case FontRenderParams::HINTING_MEDIUM: return SkPaint::kNormal_Hinting;
172 case FontRenderParams::HINTING_FULL: return SkPaint::kFull_Hinting;
174 return SkPaint::kNo_Hinting;
177 } // namespace
179 namespace internal {
181 // Value of |underline_thickness_| that indicates that underline metrics have
182 // not been set explicitly.
183 const SkScalar kUnderlineMetricsNotSet = -1.0f;
185 SkiaTextRenderer::SkiaTextRenderer(Canvas* canvas)
186 : canvas_(canvas),
187 canvas_skia_(canvas->sk_canvas()),
188 underline_thickness_(kUnderlineMetricsNotSet),
189 underline_position_(0.0f) {
190 DCHECK(canvas_skia_);
191 paint_.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
192 paint_.setStyle(SkPaint::kFill_Style);
193 paint_.setAntiAlias(true);
194 paint_.setSubpixelText(true);
195 paint_.setLCDRenderText(true);
196 paint_.setHinting(SkPaint::kNormal_Hinting);
199 SkiaTextRenderer::~SkiaTextRenderer() {
202 void SkiaTextRenderer::SetDrawLooper(SkDrawLooper* draw_looper) {
203 paint_.setLooper(draw_looper);
206 void SkiaTextRenderer::SetFontRenderParams(const FontRenderParams& params,
207 bool subpixel_rendering_suppressed) {
208 ApplyRenderParams(params, subpixel_rendering_suppressed, &paint_);
211 void SkiaTextRenderer::SetTypeface(SkTypeface* typeface) {
212 paint_.setTypeface(typeface);
215 void SkiaTextRenderer::SetTextSize(SkScalar size) {
216 paint_.setTextSize(size);
219 void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string& family,
220 int style) {
221 DCHECK(!family.empty());
223 skia::RefPtr<SkTypeface> typeface = CreateSkiaTypeface(family.c_str(), style);
224 if (typeface) {
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
229 // have it.
230 paint_.setFakeBoldText((style & Font::BOLD) && !typeface->isBold());
234 void SkiaTextRenderer::SetForegroundColor(SkColor foreground) {
235 paint_.setColor(foreground);
238 void SkiaTextRenderer::SetShader(SkShader* shader) {
239 paint_.setShader(shader);
242 void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness,
243 SkScalar position) {
244 underline_thickness_ = thickness;
245 underline_position_ = position;
248 void SkiaTextRenderer::DrawPosText(const SkPoint* pos,
249 const uint16* glyphs,
250 size_t glyph_count) {
251 const size_t byte_length = glyph_count * sizeof(glyphs[0]);
252 canvas_skia_->drawPosText(&glyphs[0], byte_length, &pos[0], paint_);
255 void SkiaTextRenderer::DrawDecorations(int x, int y, int width, bool underline,
256 bool strike, bool diagonal_strike) {
257 if (underline)
258 DrawUnderline(x, y, width);
259 if (strike)
260 DrawStrike(x, y, width);
261 if (diagonal_strike) {
262 if (!diagonal_)
263 diagonal_.reset(new DiagonalStrike(canvas_, Point(x, y), paint_));
264 diagonal_->AddPiece(width, paint_.getColor());
265 } else if (diagonal_) {
266 EndDiagonalStrike();
270 void SkiaTextRenderer::EndDiagonalStrike() {
271 if (diagonal_) {
272 diagonal_->Draw();
273 diagonal_.reset();
277 void SkiaTextRenderer::DrawUnderline(int x, int y, int width) {
278 SkScalar x_scalar = SkIntToScalar(x);
279 SkRect r = SkRect::MakeLTRB(
280 x_scalar, y + underline_position_, x_scalar + width,
281 y + underline_position_ + underline_thickness_);
282 if (underline_thickness_ == kUnderlineMetricsNotSet) {
283 const SkScalar text_size = paint_.getTextSize();
284 r.fTop = SkScalarMulAdd(text_size, kUnderlineOffset, y);
285 r.fBottom = r.fTop + SkScalarMul(text_size, kLineThickness);
287 canvas_skia_->drawRect(r, paint_);
290 void SkiaTextRenderer::DrawStrike(int x, int y, int width) const {
291 const SkScalar text_size = paint_.getTextSize();
292 const SkScalar height = SkScalarMul(text_size, kLineThickness);
293 const SkScalar offset = SkScalarMulAdd(text_size, kStrikeThroughOffset, y);
294 SkScalar x_scalar = SkIntToScalar(x);
295 const SkRect r =
296 SkRect::MakeLTRB(x_scalar, offset, x_scalar + width, offset + height);
297 canvas_skia_->drawRect(r, paint_);
300 SkiaTextRenderer::DiagonalStrike::DiagonalStrike(Canvas* canvas,
301 Point start,
302 const SkPaint& paint)
303 : canvas_(canvas),
304 start_(start),
305 paint_(paint),
306 total_length_(0) {
309 SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() {
312 void SkiaTextRenderer::DiagonalStrike::AddPiece(int length, SkColor color) {
313 pieces_.push_back(Piece(length, color));
314 total_length_ += length;
317 void SkiaTextRenderer::DiagonalStrike::Draw() {
318 const SkScalar text_size = paint_.getTextSize();
319 const SkScalar offset = SkScalarMul(text_size, kDiagonalStrikeMarginOffset);
320 const int thickness =
321 SkScalarCeilToInt(SkScalarMul(text_size, kLineThickness) * 2);
322 const int height = SkScalarCeilToInt(text_size - offset);
323 const Point end = start_ + Vector2d(total_length_, -height);
324 const int clip_height = height + 2 * thickness;
326 paint_.setAntiAlias(true);
327 paint_.setStrokeWidth(SkIntToScalar(thickness));
329 const bool clipped = pieces_.size() > 1;
330 SkCanvas* sk_canvas = canvas_->sk_canvas();
331 int x = start_.x();
333 for (size_t i = 0; i < pieces_.size(); ++i) {
334 paint_.setColor(pieces_[i].second);
336 if (clipped) {
337 canvas_->Save();
338 sk_canvas->clipRect(RectToSkRect(
339 Rect(x, end.y() - thickness, pieces_[i].first, clip_height)));
342 canvas_->DrawLine(start_, end, paint_);
344 if (clipped)
345 canvas_->Restore();
347 x += pieces_[i].first;
351 StyleIterator::StyleIterator(const BreakList<SkColor>& colors,
352 const std::vector<BreakList<bool> >& styles)
353 : colors_(colors),
354 styles_(styles) {
355 color_ = colors_.breaks().begin();
356 for (size_t i = 0; i < styles_.size(); ++i)
357 style_.push_back(styles_[i].breaks().begin());
360 StyleIterator::~StyleIterator() {}
362 Range StyleIterator::GetRange() const {
363 Range range(colors_.GetRange(color_));
364 for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
365 range = range.Intersect(styles_[i].GetRange(style_[i]));
366 return range;
369 void StyleIterator::UpdatePosition(size_t position) {
370 color_ = colors_.GetBreak(position);
371 for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
372 style_[i] = styles_[i].GetBreak(position);
375 LineSegment::LineSegment() : width(0), run(0) {}
377 LineSegment::~LineSegment() {}
379 Line::Line() : preceding_heights(0), baseline(0) {}
381 Line::~Line() {}
383 skia::RefPtr<SkTypeface> CreateSkiaTypeface(const std::string& family,
384 int style) {
385 SkTypeface::Style skia_style = ConvertFontStyleToSkiaTypefaceStyle(style);
386 return skia::AdoptRef(SkTypeface::CreateFromName(family.c_str(), skia_style));
389 void ApplyRenderParams(const FontRenderParams& params,
390 bool subpixel_rendering_suppressed,
391 SkPaint* paint) {
392 paint->setAntiAlias(params.antialiasing);
393 paint->setLCDRenderText(!subpixel_rendering_suppressed &&
394 params.subpixel_rendering != FontRenderParams::SUBPIXEL_RENDERING_NONE);
395 paint->setSubpixelText(params.subpixel_positioning);
396 paint->setAutohinted(params.autohinter);
397 paint->setHinting(FontRenderParamsHintingToSkPaintHinting(params.hinting));
400 } // namespace internal
402 RenderText::~RenderText() {
405 RenderText* RenderText::CreateInstance() {
406 #if defined(OS_MACOSX)
407 static const bool use_native =
408 !base::CommandLine::ForCurrentProcess()->HasSwitch(
409 switches::kEnableHarfBuzzRenderText);
410 if (use_native)
411 return new RenderTextMac;
412 #endif // defined(OS_MACOSX)
413 return new RenderTextHarfBuzz;
416 RenderText* RenderText::CreateInstanceForEditing() {
417 return new RenderTextHarfBuzz;
420 void RenderText::SetText(const base::string16& text) {
421 DCHECK(!composition_range_.IsValid());
422 if (text_ == text)
423 return;
424 text_ = text;
426 // Adjust ranged styles and colors to accommodate a new text length.
427 // Clear style ranges as they might break new text graphemes and apply
428 // the first style to the whole text instead.
429 const size_t text_length = text_.length();
430 colors_.SetMax(text_length);
431 for (size_t style = 0; style < NUM_TEXT_STYLES; ++style) {
432 BreakList<bool>& break_list = styles_[style];
433 break_list.SetValue(break_list.breaks().begin()->second);
434 break_list.SetMax(text_length);
436 cached_bounds_and_offset_valid_ = false;
438 // Reset selection model. SetText should always followed by SetSelectionModel
439 // or SetCursorPosition in upper layer.
440 SetSelectionModel(SelectionModel());
442 // Invalidate the cached text direction if it depends on the text contents.
443 if (directionality_mode_ == DIRECTIONALITY_FROM_TEXT)
444 text_direction_ = base::i18n::UNKNOWN_DIRECTION;
446 obscured_reveal_index_ = -1;
447 OnTextAttributeChanged();
450 void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment) {
451 if (horizontal_alignment_ != alignment) {
452 horizontal_alignment_ = alignment;
453 display_offset_ = Vector2d();
454 cached_bounds_and_offset_valid_ = false;
458 void RenderText::SetFontList(const FontList& font_list) {
459 font_list_ = font_list;
460 const int font_style = font_list.GetFontStyle();
461 SetStyle(BOLD, (font_style & gfx::Font::BOLD) != 0);
462 SetStyle(ITALIC, (font_style & gfx::Font::ITALIC) != 0);
463 SetStyle(UNDERLINE, (font_style & gfx::Font::UNDERLINE) != 0);
464 baseline_ = kInvalidBaseline;
465 cached_bounds_and_offset_valid_ = false;
466 OnLayoutTextAttributeChanged(false);
469 void RenderText::SetCursorEnabled(bool cursor_enabled) {
470 cursor_enabled_ = cursor_enabled;
471 cached_bounds_and_offset_valid_ = false;
474 void RenderText::ToggleInsertMode() {
475 insert_mode_ = !insert_mode_;
476 cached_bounds_and_offset_valid_ = false;
479 void RenderText::SetObscured(bool obscured) {
480 if (obscured != obscured_) {
481 obscured_ = obscured;
482 obscured_reveal_index_ = -1;
483 cached_bounds_and_offset_valid_ = false;
484 OnTextAttributeChanged();
488 void RenderText::SetObscuredRevealIndex(int index) {
489 if (obscured_reveal_index_ == index)
490 return;
492 obscured_reveal_index_ = index;
493 cached_bounds_and_offset_valid_ = false;
494 OnTextAttributeChanged();
497 void RenderText::SetMultiline(bool multiline) {
498 if (multiline != multiline_) {
499 multiline_ = multiline;
500 cached_bounds_and_offset_valid_ = false;
501 lines_.clear();
502 OnTextAttributeChanged();
506 void RenderText::SetMinLineHeight(int line_height) {
507 if (min_line_height_ == line_height)
508 return;
509 min_line_height_ = line_height;
510 cached_bounds_and_offset_valid_ = false;
511 lines_.clear();
512 OnDisplayTextAttributeChanged();
515 void RenderText::SetElideBehavior(ElideBehavior elide_behavior) {
516 // TODO(skanuj) : Add a test for triggering layout change.
517 if (elide_behavior_ != elide_behavior) {
518 elide_behavior_ = elide_behavior;
519 OnDisplayTextAttributeChanged();
523 void RenderText::SetDisplayRect(const Rect& r) {
524 if (r != display_rect_) {
525 display_rect_ = r;
526 baseline_ = kInvalidBaseline;
527 cached_bounds_and_offset_valid_ = false;
528 lines_.clear();
529 if (elide_behavior_ != NO_ELIDE &&
530 elide_behavior_ != FADE_TAIL) {
531 OnDisplayTextAttributeChanged();
536 void RenderText::SetCursorPosition(size_t position) {
537 MoveCursorTo(position, false);
540 void RenderText::MoveCursor(BreakType break_type,
541 VisualCursorDirection direction,
542 bool select) {
543 SelectionModel cursor(cursor_position(), selection_model_.caret_affinity());
544 // Cancelling a selection moves to the edge of the selection.
545 if (break_type != LINE_BREAK && !selection().is_empty() && !select) {
546 SelectionModel selection_start = GetSelectionModelForSelectionStart();
547 int start_x = GetCursorBounds(selection_start, true).x();
548 int cursor_x = GetCursorBounds(cursor, true).x();
549 // Use the selection start if it is left (when |direction| is CURSOR_LEFT)
550 // or right (when |direction| is CURSOR_RIGHT) of the selection end.
551 if (direction == CURSOR_RIGHT ? start_x > cursor_x : start_x < cursor_x)
552 cursor = selection_start;
553 // Use the nearest word boundary in the proper |direction| for word breaks.
554 if (break_type == WORD_BREAK)
555 cursor = GetAdjacentSelectionModel(cursor, break_type, direction);
556 // Use an adjacent selection model if the cursor is not at a valid position.
557 if (!IsValidCursorIndex(cursor.caret_pos()))
558 cursor = GetAdjacentSelectionModel(cursor, CHARACTER_BREAK, direction);
559 } else {
560 cursor = GetAdjacentSelectionModel(cursor, break_type, direction);
562 if (select)
563 cursor.set_selection_start(selection().start());
564 MoveCursorTo(cursor);
567 bool RenderText::MoveCursorTo(const SelectionModel& model) {
568 // Enforce valid selection model components.
569 size_t text_length = text().length();
570 Range range(std::min(model.selection().start(), text_length),
571 std::min(model.caret_pos(), text_length));
572 // The current model only supports caret positions at valid cursor indices.
573 if (!IsValidCursorIndex(range.start()) || !IsValidCursorIndex(range.end()))
574 return false;
575 SelectionModel sel(range, model.caret_affinity());
576 bool changed = sel != selection_model_;
577 SetSelectionModel(sel);
578 return changed;
581 bool RenderText::SelectRange(const Range& range) {
582 Range sel(std::min(range.start(), text().length()),
583 std::min(range.end(), text().length()));
584 // Allow selection bounds at valid indicies amid multi-character graphemes.
585 if (!IsValidLogicalIndex(sel.start()) || !IsValidLogicalIndex(sel.end()))
586 return false;
587 LogicalCursorDirection affinity =
588 (sel.is_reversed() || sel.is_empty()) ? CURSOR_FORWARD : CURSOR_BACKWARD;
589 SetSelectionModel(SelectionModel(sel, affinity));
590 return true;
593 bool RenderText::IsPointInSelection(const Point& point) {
594 if (selection().is_empty())
595 return false;
596 SelectionModel cursor = FindCursorPosition(point);
597 return RangeContainsCaret(
598 selection(), cursor.caret_pos(), cursor.caret_affinity());
601 void RenderText::ClearSelection() {
602 SetSelectionModel(SelectionModel(cursor_position(),
603 selection_model_.caret_affinity()));
606 void RenderText::SelectAll(bool reversed) {
607 const size_t length = text().length();
608 const Range all = reversed ? Range(length, 0) : Range(0, length);
609 const bool success = SelectRange(all);
610 DCHECK(success);
613 void RenderText::SelectWord() {
614 if (obscured_) {
615 SelectAll(false);
616 return;
619 size_t selection_max = selection().GetMax();
621 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
622 bool success = iter.Init();
623 DCHECK(success);
624 if (!success)
625 return;
627 size_t selection_min = selection().GetMin();
628 if (selection_min == text().length() && selection_min != 0)
629 --selection_min;
631 for (; selection_min != 0; --selection_min) {
632 if (iter.IsStartOfWord(selection_min) ||
633 iter.IsEndOfWord(selection_min))
634 break;
637 if (selection_min == selection_max && selection_max != text().length())
638 ++selection_max;
640 for (; selection_max < text().length(); ++selection_max)
641 if (iter.IsEndOfWord(selection_max) || iter.IsStartOfWord(selection_max))
642 break;
644 const bool reversed = selection().is_reversed();
645 MoveCursorTo(reversed ? selection_max : selection_min, false);
646 MoveCursorTo(reversed ? selection_min : selection_max, true);
649 const Range& RenderText::GetCompositionRange() const {
650 return composition_range_;
653 void RenderText::SetCompositionRange(const Range& composition_range) {
654 CHECK(!composition_range.IsValid() ||
655 Range(0, text_.length()).Contains(composition_range));
656 composition_range_.set_end(composition_range.end());
657 composition_range_.set_start(composition_range.start());
658 // TODO(oshima|msw): Altering composition underlines shouldn't
659 // require layout changes. It's currently necessary because
660 // RenderTextHarfBuzz paints text decorations by run, and
661 // RenderTextMac applies all styles during layout.
662 OnLayoutTextAttributeChanged(false);
665 void RenderText::SetColor(SkColor value) {
666 colors_.SetValue(value);
669 void RenderText::ApplyColor(SkColor value, const Range& range) {
670 colors_.ApplyValue(value, range);
673 void RenderText::SetStyle(TextStyle style, bool value) {
674 styles_[style].SetValue(value);
676 cached_bounds_and_offset_valid_ = false;
677 // TODO(oshima|msw): Not all style change requires layout changes.
678 // Consider optimizing based on the type of change.
679 OnLayoutTextAttributeChanged(false);
682 void RenderText::ApplyStyle(TextStyle style, bool value, const Range& range) {
683 // Do not change styles mid-grapheme to avoid breaking ligatures.
684 const size_t start = IsValidCursorIndex(range.start()) ? range.start() :
685 IndexOfAdjacentGrapheme(range.start(), CURSOR_BACKWARD);
686 const size_t end = IsValidCursorIndex(range.end()) ? range.end() :
687 IndexOfAdjacentGrapheme(range.end(), CURSOR_FORWARD);
688 styles_[style].ApplyValue(value, Range(start, end));
690 cached_bounds_and_offset_valid_ = false;
691 // TODO(oshima|msw): Not all style change requires layout changes.
692 // Consider optimizing based on the type of change.
693 OnLayoutTextAttributeChanged(false);
696 bool RenderText::GetStyle(TextStyle style) const {
697 return (styles_[style].breaks().size() == 1) &&
698 styles_[style].breaks().front().second;
701 void RenderText::SetDirectionalityMode(DirectionalityMode mode) {
702 if (mode == directionality_mode_)
703 return;
705 directionality_mode_ = mode;
706 text_direction_ = base::i18n::UNKNOWN_DIRECTION;
707 cached_bounds_and_offset_valid_ = false;
708 OnLayoutTextAttributeChanged(false);
711 base::i18n::TextDirection RenderText::GetDisplayTextDirection() {
712 return GetTextDirection(GetDisplayText());
715 VisualCursorDirection RenderText::GetVisualDirectionOfLogicalEnd() {
716 return GetDisplayTextDirection() == base::i18n::LEFT_TO_RIGHT ?
717 CURSOR_RIGHT : CURSOR_LEFT;
720 SizeF RenderText::GetStringSizeF() {
721 return GetStringSize();
724 float RenderText::GetContentWidthF() {
725 const float string_size = GetStringSizeF().width();
726 // The cursor is drawn one pixel beyond the int-enclosed text bounds.
727 return cursor_enabled_ ? std::ceil(string_size) + 1 : string_size;
730 int RenderText::GetContentWidth() {
731 return ToCeiledInt(GetContentWidthF());
734 int RenderText::GetBaseline() {
735 if (baseline_ == kInvalidBaseline)
736 baseline_ = DetermineBaselineCenteringText(display_rect(), font_list());
737 DCHECK_NE(kInvalidBaseline, baseline_);
738 return baseline_;
741 void RenderText::Draw(Canvas* canvas) {
742 EnsureLayout();
744 if (clip_to_display_rect()) {
745 Rect clip_rect(display_rect());
746 clip_rect.Inset(ShadowValue::GetMargin(shadows_));
748 canvas->Save();
749 canvas->ClipRect(clip_rect);
752 if (!text().empty() && focused())
753 DrawSelection(canvas);
755 if (cursor_enabled() && cursor_visible() && focused())
756 DrawCursor(canvas, selection_model_);
758 if (!text().empty())
759 DrawVisualText(canvas);
761 if (clip_to_display_rect())
762 canvas->Restore();
765 void RenderText::DrawCursor(Canvas* canvas, const SelectionModel& position) {
766 // Paint cursor. Replace cursor is drawn as rectangle for now.
767 // TODO(msw): Draw a better cursor with a better indication of association.
768 canvas->FillRect(GetCursorBounds(position, true), cursor_color_);
771 bool RenderText::IsValidLogicalIndex(size_t index) {
772 // Check that the index is at a valid code point (not mid-surrgate-pair) and
773 // that it's not truncated from the display text (its glyph may be shown).
775 // Indices within truncated text are disallowed so users can easily interact
776 // with the underlying truncated text using the ellipsis as a proxy. This lets
777 // users select all text, select the truncated text, and transition from the
778 // last rendered glyph to the end of the text without getting invisible cursor
779 // positions nor needing unbounded arrow key presses to traverse the ellipsis.
780 return index == 0 || index == text().length() ||
781 (index < text().length() &&
782 (truncate_length_ == 0 || index < truncate_length_) &&
783 IsValidCodePointIndex(text(), index));
786 Rect RenderText::GetCursorBounds(const SelectionModel& caret,
787 bool insert_mode) {
788 // TODO(ckocagil): Support multiline. This function should return the height
789 // of the line the cursor is on. |GetStringSize()| now returns
790 // the multiline size, eliminate its use here.
792 EnsureLayout();
793 size_t caret_pos = caret.caret_pos();
794 DCHECK(IsValidLogicalIndex(caret_pos));
795 // In overtype mode, ignore the affinity and always indicate that we will
796 // overtype the next character.
797 LogicalCursorDirection caret_affinity =
798 insert_mode ? caret.caret_affinity() : CURSOR_FORWARD;
799 int x = 0, width = 1;
800 Size size = GetStringSize();
801 if (caret_pos == (caret_affinity == CURSOR_BACKWARD ? 0 : text().length())) {
802 // The caret is attached to the boundary. Always return a 1-dip width caret,
803 // since there is nothing to overtype.
804 if ((GetDisplayTextDirection() == base::i18n::RIGHT_TO_LEFT)
805 == (caret_pos == 0)) {
806 x = size.width();
808 } else {
809 size_t grapheme_start = (caret_affinity == CURSOR_FORWARD) ?
810 caret_pos : IndexOfAdjacentGrapheme(caret_pos, CURSOR_BACKWARD);
811 Range xspan(GetGlyphBounds(grapheme_start));
812 if (insert_mode) {
813 x = (caret_affinity == CURSOR_BACKWARD) ? xspan.end() : xspan.start();
814 } else { // overtype mode
815 x = xspan.GetMin();
816 width = xspan.length();
819 return Rect(ToViewPoint(Point(x, 0)), Size(width, size.height()));
822 const Rect& RenderText::GetUpdatedCursorBounds() {
823 UpdateCachedBoundsAndOffset();
824 return cursor_bounds_;
827 size_t RenderText::IndexOfAdjacentGrapheme(size_t index,
828 LogicalCursorDirection direction) {
829 if (index > text().length())
830 return text().length();
832 EnsureLayout();
834 if (direction == CURSOR_FORWARD) {
835 while (index < text().length()) {
836 index++;
837 if (IsValidCursorIndex(index))
838 return index;
840 return text().length();
843 while (index > 0) {
844 index--;
845 if (IsValidCursorIndex(index))
846 return index;
848 return 0;
851 SelectionModel RenderText::GetSelectionModelForSelectionStart() {
852 const Range& sel = selection();
853 if (sel.is_empty())
854 return selection_model_;
855 return SelectionModel(sel.start(),
856 sel.is_reversed() ? CURSOR_BACKWARD : CURSOR_FORWARD);
859 const Vector2d& RenderText::GetUpdatedDisplayOffset() {
860 UpdateCachedBoundsAndOffset();
861 return display_offset_;
864 void RenderText::SetDisplayOffset(int horizontal_offset) {
865 const int extra_content = GetContentWidth() - display_rect_.width();
866 const int cursor_width = cursor_enabled_ ? 1 : 0;
868 int min_offset = 0;
869 int max_offset = 0;
870 if (extra_content > 0) {
871 switch (GetCurrentHorizontalAlignment()) {
872 case ALIGN_LEFT:
873 min_offset = -extra_content;
874 break;
875 case ALIGN_RIGHT:
876 max_offset = extra_content;
877 break;
878 case ALIGN_CENTER:
879 // The extra space reserved for cursor at the end of the text is ignored
880 // when centering text. So, to calculate the valid range for offset, we
881 // exclude that extra space, calculate the range, and add it back to the
882 // range (if cursor is enabled).
883 min_offset = -(extra_content - cursor_width + 1) / 2 - cursor_width;
884 max_offset = (extra_content - cursor_width) / 2;
885 break;
886 default:
887 break;
890 if (horizontal_offset < min_offset)
891 horizontal_offset = min_offset;
892 else if (horizontal_offset > max_offset)
893 horizontal_offset = max_offset;
895 cached_bounds_and_offset_valid_ = true;
896 display_offset_.set_x(horizontal_offset);
897 cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_);
900 RenderText::RenderText()
901 : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT : ALIGN_LEFT),
902 directionality_mode_(DIRECTIONALITY_FROM_TEXT),
903 text_direction_(base::i18n::UNKNOWN_DIRECTION),
904 cursor_enabled_(true),
905 cursor_visible_(false),
906 insert_mode_(true),
907 cursor_color_(kDefaultColor),
908 selection_color_(kDefaultColor),
909 selection_background_focused_color_(kDefaultSelectionBackgroundColor),
910 focused_(false),
911 composition_range_(Range::InvalidRange()),
912 colors_(kDefaultColor),
913 styles_(NUM_TEXT_STYLES),
914 composition_and_selection_styles_applied_(false),
915 obscured_(false),
916 obscured_reveal_index_(-1),
917 truncate_length_(0),
918 elide_behavior_(NO_ELIDE),
919 text_elided_(false),
920 min_line_height_(0),
921 multiline_(false),
922 subpixel_rendering_suppressed_(false),
923 clip_to_display_rect_(true),
924 baseline_(kInvalidBaseline),
925 cached_bounds_and_offset_valid_(false) {
928 SelectionModel RenderText::GetAdjacentSelectionModel(
929 const SelectionModel& current,
930 BreakType break_type,
931 VisualCursorDirection direction) {
932 EnsureLayout();
934 if (break_type == LINE_BREAK || text().empty())
935 return EdgeSelectionModel(direction);
936 if (break_type == CHARACTER_BREAK)
937 return AdjacentCharSelectionModel(current, direction);
938 DCHECK(break_type == WORD_BREAK);
939 return AdjacentWordSelectionModel(current, direction);
942 SelectionModel RenderText::EdgeSelectionModel(
943 VisualCursorDirection direction) {
944 if (direction == GetVisualDirectionOfLogicalEnd())
945 return SelectionModel(text().length(), CURSOR_FORWARD);
946 return SelectionModel(0, CURSOR_BACKWARD);
949 void RenderText::SetSelectionModel(const SelectionModel& model) {
950 DCHECK_LE(model.selection().GetMax(), text().length());
951 selection_model_ = model;
952 cached_bounds_and_offset_valid_ = false;
955 void RenderText::UpdateDisplayText(float text_width) {
956 // TODO(oshima): Consider support eliding for multi-line text.
957 // This requires max_line support first.
958 if (multiline_ ||
959 elide_behavior() == NO_ELIDE ||
960 elide_behavior() == FADE_TAIL ||
961 text_width < display_rect_.width() ||
962 layout_text_.empty()) {
963 text_elided_ = false;
964 display_text_.clear();
965 return;
968 // This doesn't trim styles so ellipsis may get rendered as a different
969 // style than the preceding text. See crbug.com/327850.
970 display_text_.assign(Elide(layout_text_,
971 text_width,
972 static_cast<float>(display_rect_.width()),
973 elide_behavior_));
975 text_elided_ = display_text_ != layout_text_;
976 if (!text_elided_)
977 display_text_.clear();
980 const BreakList<size_t>& RenderText::GetLineBreaks() {
981 if (line_breaks_.max() != 0)
982 return line_breaks_;
984 const base::string16& layout_text = GetDisplayText();
985 const size_t text_length = layout_text.length();
986 line_breaks_.SetValue(0);
987 line_breaks_.SetMax(text_length);
988 base::i18n::BreakIterator iter(layout_text,
989 base::i18n::BreakIterator::BREAK_LINE);
990 const bool success = iter.Init();
991 DCHECK(success);
992 if (success) {
993 do {
994 line_breaks_.ApplyValue(iter.pos(), Range(iter.pos(), text_length));
995 } while (iter.Advance());
997 return line_breaks_;
1000 void RenderText::ApplyCompositionAndSelectionStyles() {
1001 // Save the underline and color breaks to undo the temporary styles later.
1002 DCHECK(!composition_and_selection_styles_applied_);
1003 saved_colors_ = colors_;
1004 saved_underlines_ = styles_[UNDERLINE];
1006 // Apply an underline to the composition range in |underlines|.
1007 if (composition_range_.IsValid() && !composition_range_.is_empty())
1008 styles_[UNDERLINE].ApplyValue(true, composition_range_);
1010 // Apply the selected text color to the [un-reversed] selection range.
1011 if (!selection().is_empty() && focused()) {
1012 const Range range(selection().GetMin(), selection().GetMax());
1013 colors_.ApplyValue(selection_color_, range);
1015 composition_and_selection_styles_applied_ = true;
1018 void RenderText::UndoCompositionAndSelectionStyles() {
1019 // Restore the underline and color breaks to undo the temporary styles.
1020 DCHECK(composition_and_selection_styles_applied_);
1021 colors_ = saved_colors_;
1022 styles_[UNDERLINE] = saved_underlines_;
1023 composition_and_selection_styles_applied_ = false;
1026 Vector2d RenderText::GetLineOffset(size_t line_number) {
1027 Vector2d offset = display_rect().OffsetFromOrigin();
1028 // TODO(ckocagil): Apply the display offset for multiline scrolling.
1029 if (!multiline())
1030 offset.Add(GetUpdatedDisplayOffset());
1031 else
1032 offset.Add(Vector2d(0, lines_[line_number].preceding_heights));
1033 offset.Add(GetAlignmentOffset(line_number));
1034 return offset;
1037 Point RenderText::ToTextPoint(const Point& point) {
1038 return point - GetLineOffset(0);
1039 // TODO(ckocagil): Convert multiline view space points to text space.
1042 Point RenderText::ToViewPoint(const Point& point) {
1043 if (!multiline())
1044 return point + GetLineOffset(0);
1046 // TODO(ckocagil): Traverse individual line segments for RTL support.
1047 DCHECK(!lines_.empty());
1048 int x = point.x();
1049 size_t line = 0;
1050 for (; line < lines_.size() && x > lines_[line].size.width(); ++line)
1051 x -= lines_[line].size.width();
1052 return Point(x, point.y()) + GetLineOffset(line);
1055 std::vector<Rect> RenderText::TextBoundsToViewBounds(const Range& x) {
1056 std::vector<Rect> rects;
1058 if (!multiline()) {
1059 rects.push_back(Rect(ToViewPoint(Point(x.GetMin(), 0)),
1060 Size(x.length(), GetStringSize().height())));
1061 return rects;
1064 EnsureLayout();
1066 // Each line segment keeps its position in text coordinates. Traverse all line
1067 // segments and if the segment intersects with the given range, add the view
1068 // rect corresponding to the intersection to |rects|.
1069 for (size_t line = 0; line < lines_.size(); ++line) {
1070 int line_x = 0;
1071 const Vector2d offset = GetLineOffset(line);
1072 for (size_t i = 0; i < lines_[line].segments.size(); ++i) {
1073 const internal::LineSegment* segment = &lines_[line].segments[i];
1074 const Range intersection = segment->x_range.Intersect(x);
1075 if (!intersection.is_empty()) {
1076 Rect rect(line_x + intersection.start() - segment->x_range.start(),
1077 0, intersection.length(), lines_[line].size.height());
1078 rects.push_back(rect + offset);
1080 line_x += segment->x_range.length();
1084 return rects;
1087 HorizontalAlignment RenderText::GetCurrentHorizontalAlignment() {
1088 if (horizontal_alignment_ != ALIGN_TO_HEAD)
1089 return horizontal_alignment_;
1090 return GetDisplayTextDirection() == base::i18n::RIGHT_TO_LEFT ?
1091 ALIGN_RIGHT : ALIGN_LEFT;
1094 Vector2d RenderText::GetAlignmentOffset(size_t line_number) {
1095 // TODO(ckocagil): Enable |lines_| usage on RenderTextMac.
1096 if (multiline_)
1097 DCHECK_LT(line_number, lines_.size());
1098 Vector2d offset;
1099 HorizontalAlignment horizontal_alignment = GetCurrentHorizontalAlignment();
1100 if (horizontal_alignment != ALIGN_LEFT) {
1101 const int width = multiline_ ?
1102 std::ceil(lines_[line_number].size.width()) +
1103 (cursor_enabled_ ? 1 : 0) :
1104 GetContentWidth();
1105 offset.set_x(display_rect().width() - width);
1106 // Put any extra margin pixel on the left to match legacy behavior.
1107 if (horizontal_alignment == ALIGN_CENTER)
1108 offset.set_x((offset.x() + 1) / 2);
1111 // Vertically center the text.
1112 if (multiline_) {
1113 const int text_height = lines_.back().preceding_heights +
1114 lines_.back().size.height();
1115 offset.set_y((display_rect_.height() - text_height) / 2);
1116 } else {
1117 offset.set_y(GetBaseline() - GetDisplayTextBaseline());
1120 return offset;
1123 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer* renderer) {
1124 const int width = display_rect().width();
1125 if (multiline() || elide_behavior_ != FADE_TAIL || GetContentWidth() <= width)
1126 return;
1128 const int gradient_width = CalculateFadeGradientWidth(font_list(), width);
1129 if (gradient_width == 0)
1130 return;
1132 HorizontalAlignment horizontal_alignment = GetCurrentHorizontalAlignment();
1133 Rect solid_part = display_rect();
1134 Rect left_part;
1135 Rect right_part;
1136 if (horizontal_alignment != ALIGN_LEFT) {
1137 left_part = solid_part;
1138 left_part.Inset(0, 0, solid_part.width() - gradient_width, 0);
1139 solid_part.Inset(gradient_width, 0, 0, 0);
1141 if (horizontal_alignment != ALIGN_RIGHT) {
1142 right_part = solid_part;
1143 right_part.Inset(solid_part.width() - gradient_width, 0, 0, 0);
1144 solid_part.Inset(0, 0, gradient_width, 0);
1147 Rect text_rect = display_rect();
1148 text_rect.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1150 // TODO(msw): Use the actual text colors corresponding to each faded part.
1151 skia::RefPtr<SkShader> shader = CreateFadeShader(
1152 text_rect, left_part, right_part, colors_.breaks().front().second);
1153 if (shader)
1154 renderer->SetShader(shader.get());
1157 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer* renderer) {
1158 skia::RefPtr<SkDrawLooper> looper = CreateShadowDrawLooper(shadows_);
1159 renderer->SetDrawLooper(looper.get());
1162 base::i18n::TextDirection RenderText::GetTextDirection(
1163 const base::string16& text) {
1164 if (text_direction_ == base::i18n::UNKNOWN_DIRECTION) {
1165 switch (directionality_mode_) {
1166 case DIRECTIONALITY_FROM_TEXT:
1167 // Derive the direction from the display text, which differs from text()
1168 // in the case of obscured (password) textfields.
1169 text_direction_ =
1170 base::i18n::GetFirstStrongCharacterDirection(text);
1171 break;
1172 case DIRECTIONALITY_FROM_UI:
1173 text_direction_ = base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT :
1174 base::i18n::LEFT_TO_RIGHT;
1175 break;
1176 case DIRECTIONALITY_FORCE_LTR:
1177 text_direction_ = base::i18n::LEFT_TO_RIGHT;
1178 break;
1179 case DIRECTIONALITY_FORCE_RTL:
1180 text_direction_ = base::i18n::RIGHT_TO_LEFT;
1181 break;
1182 default:
1183 NOTREACHED();
1187 return text_direction_;
1190 // static
1191 bool RenderText::RangeContainsCaret(const Range& range,
1192 size_t caret_pos,
1193 LogicalCursorDirection caret_affinity) {
1194 // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1195 size_t adjacent = (caret_affinity == CURSOR_BACKWARD) ?
1196 caret_pos - 1 : caret_pos + 1;
1197 return range.Contains(Range(caret_pos, adjacent));
1200 void RenderText::MoveCursorTo(size_t position, bool select) {
1201 size_t cursor = std::min(position, text().length());
1202 if (IsValidCursorIndex(cursor))
1203 SetSelectionModel(SelectionModel(
1204 Range(select ? selection().start() : cursor, cursor),
1205 (cursor == 0) ? CURSOR_FORWARD : CURSOR_BACKWARD));
1208 void RenderText::OnTextAttributeChanged() {
1209 layout_text_.clear();
1210 display_text_.clear();
1211 line_breaks_.SetMax(0);
1213 if (obscured_) {
1214 size_t obscured_text_length =
1215 static_cast<size_t>(UTF16IndexToOffset(text_, 0, text_.length()));
1216 layout_text_.assign(obscured_text_length, kPasswordReplacementChar);
1218 if (obscured_reveal_index_ >= 0 &&
1219 obscured_reveal_index_ < static_cast<int>(text_.length())) {
1220 // Gets the index range in |text_| to be revealed.
1221 size_t start = obscured_reveal_index_;
1222 U16_SET_CP_START(text_.data(), 0, start);
1223 size_t end = start;
1224 UChar32 unused_char;
1225 U16_NEXT(text_.data(), end, text_.length(), unused_char);
1227 // Gets the index in |layout_text_| to be replaced.
1228 const size_t cp_start =
1229 static_cast<size_t>(UTF16IndexToOffset(text_, 0, start));
1230 if (layout_text_.length() > cp_start)
1231 layout_text_.replace(cp_start, 1, text_.substr(start, end - start));
1233 } else {
1234 layout_text_ = text_;
1237 const base::string16& text = layout_text_;
1238 if (truncate_length_ > 0 && truncate_length_ < text.length()) {
1239 // Truncate the text at a valid character break and append an ellipsis.
1240 icu::StringCharacterIterator iter(text.c_str());
1241 // Respect ELIDE_HEAD and ELIDE_MIDDLE preferences during truncation.
1242 if (elide_behavior_ == ELIDE_HEAD) {
1243 iter.setIndex32(text.length() - truncate_length_ + 1);
1244 layout_text_.assign(kEllipsisUTF16 + text.substr(iter.getIndex()));
1245 } else if (elide_behavior_ == ELIDE_MIDDLE) {
1246 iter.setIndex32(truncate_length_ / 2);
1247 const size_t ellipsis_start = iter.getIndex();
1248 iter.setIndex32(text.length() - (truncate_length_ / 2));
1249 const size_t ellipsis_end = iter.getIndex();
1250 DCHECK_LE(ellipsis_start, ellipsis_end);
1251 layout_text_.assign(text.substr(0, ellipsis_start) + kEllipsisUTF16 +
1252 text.substr(ellipsis_end));
1253 } else {
1254 iter.setIndex32(truncate_length_ - 1);
1255 layout_text_.assign(text.substr(0, iter.getIndex()) + kEllipsisUTF16);
1258 static const base::char16 kNewline[] = { '\n', 0 };
1259 static const base::char16 kNewlineSymbol[] = { 0x2424, 0 };
1260 if (!multiline_)
1261 base::ReplaceChars(layout_text_, kNewline, kNewlineSymbol, &layout_text_);
1263 OnLayoutTextAttributeChanged(true);
1266 base::string16 RenderText::Elide(const base::string16& text,
1267 float text_width,
1268 float available_width,
1269 ElideBehavior behavior) {
1270 if (available_width <= 0 || text.empty())
1271 return base::string16();
1272 if (behavior == ELIDE_EMAIL)
1273 return ElideEmail(text, available_width);
1274 if (text_width > 0 && text_width < available_width)
1275 return text;
1277 TRACE_EVENT0("ui", "RenderText::Elide");
1279 // Create a RenderText copy with attributes that affect the rendering width.
1280 scoped_ptr<RenderText> render_text = CreateInstanceOfSameType();
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 if (text_width == 0) {
1288 render_text->SetText(text);
1289 text_width = render_text->GetContentWidthF();
1291 if (text_width <= available_width)
1292 return text;
1294 const base::string16 ellipsis = base::string16(kEllipsisUTF16);
1295 const bool insert_ellipsis = (behavior != TRUNCATE);
1296 const bool elide_in_middle = (behavior == ELIDE_MIDDLE);
1297 const bool elide_at_beginning = (behavior == ELIDE_HEAD);
1299 if (insert_ellipsis) {
1300 render_text->SetText(ellipsis);
1301 const float ellipsis_width = render_text->GetContentWidthF();
1302 if (ellipsis_width > available_width)
1303 return base::string16();
1306 StringSlicer slicer(text, ellipsis, elide_in_middle, elide_at_beginning);
1308 // Use binary search to compute the elided text.
1309 size_t lo = 0;
1310 size_t hi = text.length() - 1;
1311 const base::i18n::TextDirection text_direction = GetTextDirection(text);
1312 for (size_t guess = (lo + hi) / 2; lo <= hi; guess = (lo + hi) / 2) {
1313 // Restore colors. They will be truncated to size by SetText.
1314 render_text->colors_ = colors_;
1315 base::string16 new_text =
1316 slicer.CutString(guess, insert_ellipsis && behavior != ELIDE_TAIL);
1317 render_text->SetText(new_text);
1319 // This has to be an additional step so that the ellipsis is rendered with
1320 // same style as trailing part of the text.
1321 if (insert_ellipsis && behavior == ELIDE_TAIL) {
1322 // When ellipsis follows text whose directionality is not the same as that
1323 // of the whole text, it will be rendered with the directionality of the
1324 // whole text. Since we want ellipsis to indicate continuation of the
1325 // preceding text, we force the directionality of ellipsis to be same as
1326 // the preceding text using LTR or RTL markers.
1327 base::i18n::TextDirection trailing_text_direction =
1328 base::i18n::GetLastStrongCharacterDirection(new_text);
1329 new_text.append(ellipsis);
1330 if (trailing_text_direction != text_direction) {
1331 if (trailing_text_direction == base::i18n::LEFT_TO_RIGHT)
1332 new_text += base::i18n::kLeftToRightMark;
1333 else
1334 new_text += base::i18n::kRightToLeftMark;
1336 render_text->SetText(new_text);
1339 // Restore styles. Make sure style ranges don't break new text graphemes.
1340 render_text->styles_ = styles_;
1341 for (size_t style = 0; style < NUM_TEXT_STYLES; ++style) {
1342 BreakList<bool>& break_list = render_text->styles_[style];
1343 break_list.SetMax(render_text->text_.length());
1344 Range range;
1345 while (range.end() < break_list.max()) {
1346 BreakList<bool>::const_iterator current_break =
1347 break_list.GetBreak(range.end());
1348 range = break_list.GetRange(current_break);
1349 if (range.end() < break_list.max() &&
1350 !render_text->IsValidCursorIndex(range.end())) {
1351 range.set_end(render_text->IndexOfAdjacentGrapheme(range.end(),
1352 CURSOR_FORWARD));
1353 break_list.ApplyValue(current_break->second, range);
1358 // We check the width of the whole desired string at once to ensure we
1359 // handle kerning/ligatures/etc. correctly.
1360 const float guess_width = render_text->GetContentWidthF();
1361 if (guess_width == available_width)
1362 break;
1363 if (guess_width > available_width) {
1364 hi = guess - 1;
1365 // Move back on the loop terminating condition when the guess is too wide.
1366 if (hi < lo)
1367 lo = hi;
1368 } else {
1369 lo = guess + 1;
1373 return render_text->text();
1376 base::string16 RenderText::ElideEmail(const base::string16& email,
1377 float available_width) {
1378 // The returned string will have at least one character besides the ellipsis
1379 // on either side of '@'; if that's impossible, a single ellipsis is returned.
1380 // If possible, only the username is elided. Otherwise, the domain is elided
1381 // in the middle, splitting available width equally with the elided username.
1382 // If the username is short enough that it doesn't need half the available
1383 // width, the elided domain will occupy that extra width.
1385 // Split the email into its local-part (username) and domain-part. The email
1386 // spec allows for @ symbols in the username under some special requirements,
1387 // but not in the domain part, so splitting at the last @ symbol is safe.
1388 const size_t split_index = email.find_last_of('@');
1389 DCHECK_NE(split_index, base::string16::npos);
1390 base::string16 username = email.substr(0, split_index);
1391 base::string16 domain = email.substr(split_index + 1);
1392 DCHECK(!username.empty());
1393 DCHECK(!domain.empty());
1395 // Subtract the @ symbol from the available width as it is mandatory.
1396 const base::string16 kAtSignUTF16 = base::ASCIIToUTF16("@");
1397 available_width -= GetStringWidthF(kAtSignUTF16, font_list());
1399 // Check whether eliding the domain is necessary: if eliding the username
1400 // is sufficient, the domain will not be elided.
1401 const float full_username_width = GetStringWidthF(username, font_list());
1402 const float available_domain_width = available_width -
1403 std::min(full_username_width,
1404 GetStringWidthF(username.substr(0, 1) + kEllipsisUTF16, font_list()));
1405 if (GetStringWidthF(domain, font_list()) > available_domain_width) {
1406 // Elide the domain so that it only takes half of the available width.
1407 // Should the username not need all the width available in its half, the
1408 // domain will occupy the leftover width.
1409 // If |desired_domain_width| is greater than |available_domain_width|: the
1410 // minimal username elision allowed by the specifications will not fit; thus
1411 // |desired_domain_width| must be <= |available_domain_width| at all cost.
1412 const float desired_domain_width =
1413 std::min<float>(available_domain_width,
1414 std::max<float>(available_width - full_username_width,
1415 available_width / 2));
1416 domain = Elide(domain, 0, desired_domain_width, ELIDE_MIDDLE);
1417 // Failing to elide the domain such that at least one character remains
1418 // (other than the ellipsis itself) remains: return a single ellipsis.
1419 if (domain.length() <= 1U)
1420 return base::string16(kEllipsisUTF16);
1423 // Fit the username in the remaining width (at this point the elided username
1424 // is guaranteed to fit with at least one character remaining given all the
1425 // precautions taken earlier).
1426 available_width -= GetStringWidthF(domain, font_list());
1427 username = Elide(username, 0, available_width, ELIDE_TAIL);
1428 return username + kAtSignUTF16 + domain;
1431 void RenderText::UpdateCachedBoundsAndOffset() {
1432 if (cached_bounds_and_offset_valid_)
1433 return;
1435 // TODO(ckocagil): Add support for scrolling multiline text.
1437 int delta_x = 0;
1439 if (cursor_enabled()) {
1440 // When cursor is enabled, ensure it is visible. For this, set the valid
1441 // flag true and calculate the current cursor bounds using the stale
1442 // |display_offset_|. Then calculate the change in offset needed to move the
1443 // cursor into the visible area.
1444 cached_bounds_and_offset_valid_ = true;
1445 cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_);
1447 // TODO(bidi): Show RTL glyphs at the cursor position for ALIGN_LEFT, etc.
1448 if (cursor_bounds_.right() > display_rect_.right())
1449 delta_x = display_rect_.right() - cursor_bounds_.right();
1450 else if (cursor_bounds_.x() < display_rect_.x())
1451 delta_x = display_rect_.x() - cursor_bounds_.x();
1454 SetDisplayOffset(display_offset_.x() + delta_x);
1457 void RenderText::DrawSelection(Canvas* canvas) {
1458 for (const Rect& s : GetSubstringBounds(selection()))
1459 canvas->FillRect(s, selection_background_focused_color_);
1462 } // namespace gfx