[SyncFS] Build indexes from FileTracker entries on disk.
[chromium-blink-merge.git] / ui / gfx / render_text.cc
blob8497aa5bef99a204079b8b47364ee0f284f98910
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 "third_party/icu/source/common/unicode/rbbi.h"
17 #include "third_party/icu/source/common/unicode/utf16.h"
18 #include "third_party/skia/include/core/SkTypeface.h"
19 #include "third_party/skia/include/effects/SkGradientShader.h"
20 #include "ui/gfx/canvas.h"
21 #include "ui/gfx/insets.h"
22 #include "ui/gfx/render_text_harfbuzz.h"
23 #include "ui/gfx/scoped_canvas.h"
24 #include "ui/gfx/skia_util.h"
25 #include "ui/gfx/switches.h"
26 #include "ui/gfx/text_elider.h"
27 #include "ui/gfx/text_utils.h"
28 #include "ui/gfx/utf16_indexing.h"
30 namespace gfx {
32 namespace {
34 // All chars are replaced by this char when the password style is set.
35 // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*'
36 // that's available in the font (find_invisible_char() in gtkentry.c).
37 const base::char16 kPasswordReplacementChar = '*';
39 // Default color used for the text and cursor.
40 const SkColor kDefaultColor = SK_ColorBLACK;
42 // Default color used for drawing selection background.
43 const SkColor kDefaultSelectionBackgroundColor = SK_ColorGRAY;
45 // Fraction of the text size to lower a strike through below the baseline.
46 const SkScalar kStrikeThroughOffset = (-SK_Scalar1 * 6 / 21);
47 // Fraction of the text size to lower an underline below the baseline.
48 const SkScalar kUnderlineOffset = (SK_Scalar1 / 9);
49 // Fraction of the text size to use for a strike through or under-line.
50 const SkScalar kLineThickness = (SK_Scalar1 / 18);
51 // Fraction of the text size to use for a top margin of a diagonal strike.
52 const SkScalar kDiagonalStrikeMarginOffset = (SK_Scalar1 / 4);
54 // Invalid value of baseline. Assigning this value to |baseline_| causes
55 // re-calculation of baseline.
56 const int kInvalidBaseline = INT_MAX;
58 // Returns the baseline, with which the text best appears vertically centered.
59 int DetermineBaselineCenteringText(const Rect& display_rect,
60 const FontList& font_list) {
61 const int display_height = display_rect.height();
62 const int font_height = font_list.GetHeight();
63 // Lower and upper bound of baseline shift as we try to show as much area of
64 // text as possible. In particular case of |display_height| == |font_height|,
65 // we do not want to shift the baseline.
66 const int min_shift = std::min(0, display_height - font_height);
67 const int max_shift = std::abs(display_height - font_height);
68 const int baseline = font_list.GetBaseline();
69 const int cap_height = font_list.GetCapHeight();
70 const int internal_leading = baseline - cap_height;
71 // Some platforms don't support getting the cap height, and simply return
72 // the entire font ascent from GetCapHeight(). Centering the ascent makes
73 // the font look too low, so if GetCapHeight() returns the ascent, center
74 // the entire font height instead.
75 const int space =
76 display_height - ((internal_leading != 0) ? cap_height : font_height);
77 const int baseline_shift = space / 2 - internal_leading;
78 return baseline + std::max(min_shift, std::min(max_shift, baseline_shift));
81 // Converts |Font::FontStyle| flags to |SkTypeface::Style| flags.
82 SkTypeface::Style ConvertFontStyleToSkiaTypefaceStyle(int font_style) {
83 int skia_style = SkTypeface::kNormal;
84 skia_style |= (font_style & Font::BOLD) ? SkTypeface::kBold : 0;
85 skia_style |= (font_style & Font::ITALIC) ? SkTypeface::kItalic : 0;
86 return static_cast<SkTypeface::Style>(skia_style);
89 // Given |font| and |display_width|, returns the width of the fade gradient.
90 int CalculateFadeGradientWidth(const FontList& font_list, int display_width) {
91 // Fade in/out about 2.5 characters of the beginning/end of the string.
92 // The .5 here is helpful if one of the characters is a space.
93 // Use a quarter of the display width if the display width is very short.
94 const int average_character_width = font_list.GetExpectedTextWidth(1);
95 const double gradient_width = std::min(average_character_width * 2.5,
96 display_width / 4.0);
97 DCHECK_GE(gradient_width, 0.0);
98 return static_cast<int>(floor(gradient_width + 0.5));
101 // Appends to |positions| and |colors| values corresponding to the fade over
102 // |fade_rect| from color |c0| to color |c1|.
103 void AddFadeEffect(const Rect& text_rect,
104 const Rect& fade_rect,
105 SkColor c0,
106 SkColor c1,
107 std::vector<SkScalar>* positions,
108 std::vector<SkColor>* colors) {
109 const SkScalar left = static_cast<SkScalar>(fade_rect.x() - text_rect.x());
110 const SkScalar width = static_cast<SkScalar>(fade_rect.width());
111 const SkScalar p0 = left / text_rect.width();
112 const SkScalar p1 = (left + width) / text_rect.width();
113 // Prepend 0.0 to |positions|, as required by Skia.
114 if (positions->empty() && p0 != 0.0) {
115 positions->push_back(0.0);
116 colors->push_back(c0);
118 positions->push_back(p0);
119 colors->push_back(c0);
120 positions->push_back(p1);
121 colors->push_back(c1);
124 // Creates a SkShader to fade the text, with |left_part| specifying the left
125 // fade effect, if any, and |right_part| specifying the right fade effect.
126 skia::RefPtr<SkShader> CreateFadeShader(const Rect& text_rect,
127 const Rect& left_part,
128 const Rect& right_part,
129 SkColor color) {
130 // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color.
131 const SkColor fade_color = SkColorSetA(color, 51);
132 std::vector<SkScalar> positions;
133 std::vector<SkColor> colors;
135 if (!left_part.IsEmpty())
136 AddFadeEffect(text_rect, left_part, fade_color, color,
137 &positions, &colors);
138 if (!right_part.IsEmpty())
139 AddFadeEffect(text_rect, right_part, color, fade_color,
140 &positions, &colors);
141 DCHECK(!positions.empty());
143 // Terminate |positions| with 1.0, as required by Skia.
144 if (positions.back() != 1.0) {
145 positions.push_back(1.0);
146 colors.push_back(colors.back());
149 SkPoint points[2];
150 points[0].iset(text_rect.x(), text_rect.y());
151 points[1].iset(text_rect.right(), text_rect.y());
153 return skia::AdoptRef(
154 SkGradientShader::CreateLinear(&points[0], &colors[0], &positions[0],
155 colors.size(), SkShader::kClamp_TileMode));
158 // Converts a FontRenderParams::Hinting value to the corresponding
159 // SkPaint::Hinting value.
160 SkPaint::Hinting FontRenderParamsHintingToSkPaintHinting(
161 FontRenderParams::Hinting params_hinting) {
162 switch (params_hinting) {
163 case FontRenderParams::HINTING_NONE: return SkPaint::kNo_Hinting;
164 case FontRenderParams::HINTING_SLIGHT: return SkPaint::kSlight_Hinting;
165 case FontRenderParams::HINTING_MEDIUM: return SkPaint::kNormal_Hinting;
166 case FontRenderParams::HINTING_FULL: return SkPaint::kFull_Hinting;
168 return SkPaint::kNo_Hinting;
171 } // namespace
173 namespace internal {
175 // Value of |underline_thickness_| that indicates that underline metrics have
176 // not been set explicitly.
177 const SkScalar kUnderlineMetricsNotSet = -1.0f;
179 SkiaTextRenderer::SkiaTextRenderer(Canvas* canvas)
180 : canvas_(canvas),
181 canvas_skia_(canvas->sk_canvas()),
182 started_drawing_(false),
183 underline_thickness_(kUnderlineMetricsNotSet),
184 underline_position_(0.0f) {
185 DCHECK(canvas_skia_);
186 paint_.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
187 paint_.setStyle(SkPaint::kFill_Style);
188 paint_.setAntiAlias(true);
189 paint_.setSubpixelText(true);
190 paint_.setLCDRenderText(true);
191 paint_.setHinting(SkPaint::kNormal_Hinting);
192 bounds_.setEmpty();
195 SkiaTextRenderer::~SkiaTextRenderer() {
196 // Work-around for http://crbug.com/122743, where non-ClearType text is
197 // rendered with incorrect gamma when using the fade shader. Draw the text
198 // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode.
200 // TODO(asvitkine): Remove this work-around once the Skia bug is fixed.
201 // http://code.google.com/p/skia/issues/detail?id=590
202 if (deferred_fade_shader_.get()) {
203 paint_.setShader(deferred_fade_shader_.get());
204 paint_.setXfermodeMode(SkXfermode::kDstIn_Mode);
205 canvas_skia_->drawRect(bounds_, paint_);
206 canvas_skia_->restore();
210 void SkiaTextRenderer::SetDrawLooper(SkDrawLooper* draw_looper) {
211 paint_.setLooper(draw_looper);
214 void SkiaTextRenderer::SetFontRenderParams(const FontRenderParams& params,
215 bool background_is_transparent) {
216 paint_.setAntiAlias(params.antialiasing);
217 paint_.setLCDRenderText(!background_is_transparent &&
218 params.subpixel_rendering != FontRenderParams::SUBPIXEL_RENDERING_NONE);
219 paint_.setSubpixelText(params.subpixel_positioning);
220 paint_.setAutohinted(params.autohinter);
221 paint_.setHinting(FontRenderParamsHintingToSkPaintHinting(params.hinting));
224 void SkiaTextRenderer::SetTypeface(SkTypeface* typeface) {
225 paint_.setTypeface(typeface);
228 void SkiaTextRenderer::SetTextSize(SkScalar size) {
229 paint_.setTextSize(size);
232 void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string& family,
233 int style) {
234 DCHECK(!family.empty());
236 skia::RefPtr<SkTypeface> typeface = CreateSkiaTypeface(family.c_str(), style);
237 if (typeface) {
238 // |paint_| adds its own ref. So don't |release()| it from the ref ptr here.
239 SetTypeface(typeface.get());
241 // Enable fake bold text if bold style is needed but new typeface does not
242 // have it.
243 paint_.setFakeBoldText((style & Font::BOLD) && !typeface->isBold());
247 void SkiaTextRenderer::SetForegroundColor(SkColor foreground) {
248 paint_.setColor(foreground);
251 void SkiaTextRenderer::SetShader(SkShader* shader, const Rect& bounds) {
252 bounds_ = RectToSkRect(bounds);
253 paint_.setShader(shader);
256 void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness,
257 SkScalar position) {
258 underline_thickness_ = thickness;
259 underline_position_ = position;
262 void SkiaTextRenderer::DrawPosText(const SkPoint* pos,
263 const uint16* glyphs,
264 size_t glyph_count) {
265 if (!started_drawing_) {
266 started_drawing_ = true;
267 // Work-around for http://crbug.com/122743, where non-ClearType text is
268 // rendered with incorrect gamma when using the fade shader. Draw the text
269 // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode.
271 // Skip this when there is a looper which seems not working well with
272 // deferred paint. Currently a looper is only used for text shadows.
274 // TODO(asvitkine): Remove this work-around once the Skia bug is fixed.
275 // http://code.google.com/p/skia/issues/detail?id=590
276 if (!paint_.isLCDRenderText() &&
277 paint_.getShader() &&
278 !paint_.getLooper()) {
279 deferred_fade_shader_ = skia::SharePtr(paint_.getShader());
280 paint_.setShader(NULL);
281 canvas_skia_->saveLayer(&bounds_, NULL);
285 const size_t byte_length = glyph_count * sizeof(glyphs[0]);
286 canvas_skia_->drawPosText(&glyphs[0], byte_length, &pos[0], paint_);
289 void SkiaTextRenderer::DrawDecorations(int x, int y, int width, bool underline,
290 bool strike, bool diagonal_strike) {
291 if (underline)
292 DrawUnderline(x, y, width);
293 if (strike)
294 DrawStrike(x, y, width);
295 if (diagonal_strike) {
296 if (!diagonal_)
297 diagonal_.reset(new DiagonalStrike(canvas_, Point(x, y), paint_));
298 diagonal_->AddPiece(width, paint_.getColor());
299 } else if (diagonal_) {
300 EndDiagonalStrike();
304 void SkiaTextRenderer::EndDiagonalStrike() {
305 if (diagonal_) {
306 diagonal_->Draw();
307 diagonal_.reset();
311 void SkiaTextRenderer::DrawUnderline(int x, int y, int width) {
312 SkRect r = SkRect::MakeLTRB(x, y + underline_position_, x + width,
313 y + underline_position_ + underline_thickness_);
314 if (underline_thickness_ == kUnderlineMetricsNotSet) {
315 const SkScalar text_size = paint_.getTextSize();
316 r.fTop = SkScalarMulAdd(text_size, kUnderlineOffset, y);
317 r.fBottom = r.fTop + SkScalarMul(text_size, kLineThickness);
319 canvas_skia_->drawRect(r, paint_);
322 void SkiaTextRenderer::DrawStrike(int x, int y, int width) const {
323 const SkScalar text_size = paint_.getTextSize();
324 const SkScalar height = SkScalarMul(text_size, kLineThickness);
325 const SkScalar offset = SkScalarMulAdd(text_size, kStrikeThroughOffset, y);
326 const SkRect r = SkRect::MakeLTRB(x, offset, x + width, offset + height);
327 canvas_skia_->drawRect(r, paint_);
330 SkiaTextRenderer::DiagonalStrike::DiagonalStrike(Canvas* canvas,
331 Point start,
332 const SkPaint& paint)
333 : canvas_(canvas),
334 start_(start),
335 paint_(paint),
336 total_length_(0) {
339 SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() {
342 void SkiaTextRenderer::DiagonalStrike::AddPiece(int length, SkColor color) {
343 pieces_.push_back(Piece(length, color));
344 total_length_ += length;
347 void SkiaTextRenderer::DiagonalStrike::Draw() {
348 const SkScalar text_size = paint_.getTextSize();
349 const SkScalar offset = SkScalarMul(text_size, kDiagonalStrikeMarginOffset);
350 const int thickness =
351 SkScalarCeilToInt(SkScalarMul(text_size, kLineThickness) * 2);
352 const int height = SkScalarCeilToInt(text_size - offset);
353 const Point end = start_ + Vector2d(total_length_, -height);
354 const int clip_height = height + 2 * thickness;
356 paint_.setAntiAlias(true);
357 paint_.setStrokeWidth(thickness);
359 const bool clipped = pieces_.size() > 1;
360 SkCanvas* sk_canvas = canvas_->sk_canvas();
361 int x = start_.x();
363 for (size_t i = 0; i < pieces_.size(); ++i) {
364 paint_.setColor(pieces_[i].second);
366 if (clipped) {
367 canvas_->Save();
368 sk_canvas->clipRect(RectToSkRect(
369 Rect(x, end.y() - thickness, pieces_[i].first, clip_height)));
372 canvas_->DrawLine(start_, end, paint_);
374 if (clipped)
375 canvas_->Restore();
377 x += pieces_[i].first;
381 StyleIterator::StyleIterator(const BreakList<SkColor>& colors,
382 const std::vector<BreakList<bool> >& styles)
383 : colors_(colors),
384 styles_(styles) {
385 color_ = colors_.breaks().begin();
386 for (size_t i = 0; i < styles_.size(); ++i)
387 style_.push_back(styles_[i].breaks().begin());
390 StyleIterator::~StyleIterator() {}
392 Range StyleIterator::GetRange() const {
393 Range range(colors_.GetRange(color_));
394 for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
395 range = range.Intersect(styles_[i].GetRange(style_[i]));
396 return range;
399 void StyleIterator::UpdatePosition(size_t position) {
400 color_ = colors_.GetBreak(position);
401 for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
402 style_[i] = styles_[i].GetBreak(position);
405 LineSegment::LineSegment() : run(0) {}
407 LineSegment::~LineSegment() {}
409 Line::Line() : preceding_heights(0), baseline(0) {}
411 Line::~Line() {}
413 skia::RefPtr<SkTypeface> CreateSkiaTypeface(const std::string& family,
414 int style) {
415 SkTypeface::Style skia_style = ConvertFontStyleToSkiaTypefaceStyle(style);
416 return skia::AdoptRef(SkTypeface::CreateFromName(family.c_str(), skia_style));
419 } // namespace internal
421 RenderText::~RenderText() {
424 RenderText* RenderText::CreateInstance() {
425 #if defined(OS_MACOSX) && defined(TOOLKIT_VIEWS)
426 // Use the more complete HarfBuzz implementation for Views controls on Mac.
427 return new RenderTextHarfBuzz;
428 #else
429 if (CommandLine::ForCurrentProcess()->HasSwitch(
430 switches::kEnableHarfBuzzRenderText)) {
431 return new RenderTextHarfBuzz;
433 return CreateNativeInstance();
434 #endif
437 void RenderText::SetText(const base::string16& text) {
438 DCHECK(!composition_range_.IsValid());
439 if (text_ == text)
440 return;
441 text_ = text;
443 // Adjust ranged styles and colors to accommodate a new text length.
444 const size_t text_length = text_.length();
445 colors_.SetMax(text_length);
446 for (size_t style = 0; style < NUM_TEXT_STYLES; ++style)
447 styles_[style].SetMax(text_length);
448 cached_bounds_and_offset_valid_ = false;
450 // Reset selection model. SetText should always followed by SetSelectionModel
451 // or SetCursorPosition in upper layer.
452 SetSelectionModel(SelectionModel());
454 // Invalidate the cached text direction if it depends on the text contents.
455 if (directionality_mode_ == DIRECTIONALITY_FROM_TEXT)
456 text_direction_ = base::i18n::UNKNOWN_DIRECTION;
458 obscured_reveal_index_ = -1;
459 UpdateLayoutText();
462 void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment) {
463 if (horizontal_alignment_ != alignment) {
464 horizontal_alignment_ = alignment;
465 display_offset_ = Vector2d();
466 cached_bounds_and_offset_valid_ = false;
470 void RenderText::SetFontList(const FontList& font_list) {
471 font_list_ = font_list;
472 baseline_ = kInvalidBaseline;
473 cached_bounds_and_offset_valid_ = false;
474 ResetLayout();
477 void RenderText::SetCursorEnabled(bool cursor_enabled) {
478 cursor_enabled_ = cursor_enabled;
479 cached_bounds_and_offset_valid_ = false;
482 void RenderText::ToggleInsertMode() {
483 insert_mode_ = !insert_mode_;
484 cached_bounds_and_offset_valid_ = false;
487 void RenderText::SetObscured(bool obscured) {
488 if (obscured != obscured_) {
489 obscured_ = obscured;
490 obscured_reveal_index_ = -1;
491 cached_bounds_and_offset_valid_ = false;
492 UpdateLayoutText();
496 void RenderText::SetObscuredRevealIndex(int index) {
497 if (obscured_reveal_index_ == index)
498 return;
500 obscured_reveal_index_ = index;
501 cached_bounds_and_offset_valid_ = false;
502 UpdateLayoutText();
505 void RenderText::SetMultiline(bool multiline) {
506 if (multiline != multiline_) {
507 multiline_ = multiline;
508 cached_bounds_and_offset_valid_ = false;
509 lines_.clear();
513 void RenderText::SetElideBehavior(ElideBehavior elide_behavior) {
514 // TODO(skanuj) : Add a test for triggering layout change.
515 if (elide_behavior_ != elide_behavior) {
516 elide_behavior_ = elide_behavior;
517 UpdateLayoutText();
521 void RenderText::SetDisplayRect(const Rect& r) {
522 if (r != display_rect_) {
523 display_rect_ = r;
524 baseline_ = kInvalidBaseline;
525 cached_bounds_and_offset_valid_ = false;
526 lines_.clear();
527 if (elide_behavior_ != NO_ELIDE)
528 UpdateLayoutText();
532 void RenderText::SetCursorPosition(size_t position) {
533 MoveCursorTo(position, false);
536 void RenderText::MoveCursor(BreakType break_type,
537 VisualCursorDirection direction,
538 bool select) {
539 SelectionModel cursor(cursor_position(), selection_model_.caret_affinity());
540 // Cancelling a selection moves to the edge of the selection.
541 if (break_type != LINE_BREAK && !selection().is_empty() && !select) {
542 SelectionModel selection_start = GetSelectionModelForSelectionStart();
543 int start_x = GetCursorBounds(selection_start, true).x();
544 int cursor_x = GetCursorBounds(cursor, true).x();
545 // Use the selection start if it is left (when |direction| is CURSOR_LEFT)
546 // or right (when |direction| is CURSOR_RIGHT) of the selection end.
547 if (direction == CURSOR_RIGHT ? start_x > cursor_x : start_x < cursor_x)
548 cursor = selection_start;
549 // Use the nearest word boundary in the proper |direction| for word breaks.
550 if (break_type == WORD_BREAK)
551 cursor = GetAdjacentSelectionModel(cursor, break_type, direction);
552 // Use an adjacent selection model if the cursor is not at a valid position.
553 if (!IsValidCursorIndex(cursor.caret_pos()))
554 cursor = GetAdjacentSelectionModel(cursor, CHARACTER_BREAK, direction);
555 } else {
556 cursor = GetAdjacentSelectionModel(cursor, break_type, direction);
558 if (select)
559 cursor.set_selection_start(selection().start());
560 MoveCursorTo(cursor);
563 bool RenderText::MoveCursorTo(const SelectionModel& model) {
564 // Enforce valid selection model components.
565 size_t text_length = text().length();
566 Range range(std::min(model.selection().start(), text_length),
567 std::min(model.caret_pos(), text_length));
568 // The current model only supports caret positions at valid cursor indices.
569 if (!IsValidCursorIndex(range.start()) || !IsValidCursorIndex(range.end()))
570 return false;
571 SelectionModel sel(range, model.caret_affinity());
572 bool changed = sel != selection_model_;
573 SetSelectionModel(sel);
574 return changed;
577 bool RenderText::SelectRange(const Range& range) {
578 Range sel(std::min(range.start(), text().length()),
579 std::min(range.end(), text().length()));
580 // Allow selection bounds at valid indicies amid multi-character graphemes.
581 if (!IsValidLogicalIndex(sel.start()) || !IsValidLogicalIndex(sel.end()))
582 return false;
583 LogicalCursorDirection affinity =
584 (sel.is_reversed() || sel.is_empty()) ? CURSOR_FORWARD : CURSOR_BACKWARD;
585 SetSelectionModel(SelectionModel(sel, affinity));
586 return true;
589 bool RenderText::IsPointInSelection(const Point& point) {
590 if (selection().is_empty())
591 return false;
592 SelectionModel cursor = FindCursorPosition(point);
593 return RangeContainsCaret(
594 selection(), cursor.caret_pos(), cursor.caret_affinity());
597 void RenderText::ClearSelection() {
598 SetSelectionModel(SelectionModel(cursor_position(),
599 selection_model_.caret_affinity()));
602 void RenderText::SelectAll(bool reversed) {
603 const size_t length = text().length();
604 const Range all = reversed ? Range(length, 0) : Range(0, length);
605 const bool success = SelectRange(all);
606 DCHECK(success);
609 void RenderText::SelectWord() {
610 if (obscured_) {
611 SelectAll(false);
612 return;
615 size_t selection_max = selection().GetMax();
617 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
618 bool success = iter.Init();
619 DCHECK(success);
620 if (!success)
621 return;
623 size_t selection_min = selection().GetMin();
624 if (selection_min == text().length() && selection_min != 0)
625 --selection_min;
627 for (; selection_min != 0; --selection_min) {
628 if (iter.IsStartOfWord(selection_min) ||
629 iter.IsEndOfWord(selection_min))
630 break;
633 if (selection_min == selection_max && selection_max != text().length())
634 ++selection_max;
636 for (; selection_max < text().length(); ++selection_max)
637 if (iter.IsEndOfWord(selection_max) || iter.IsStartOfWord(selection_max))
638 break;
640 const bool reversed = selection().is_reversed();
641 MoveCursorTo(reversed ? selection_max : selection_min, false);
642 MoveCursorTo(reversed ? selection_min : selection_max, true);
645 const Range& RenderText::GetCompositionRange() const {
646 return composition_range_;
649 void RenderText::SetCompositionRange(const Range& composition_range) {
650 CHECK(!composition_range.IsValid() ||
651 Range(0, text_.length()).Contains(composition_range));
652 composition_range_.set_end(composition_range.end());
653 composition_range_.set_start(composition_range.start());
654 ResetLayout();
657 void RenderText::SetColor(SkColor value) {
658 colors_.SetValue(value);
660 #if defined(OS_WIN)
661 // TODO(msw): Windows applies colors and decorations in the layout process.
662 cached_bounds_and_offset_valid_ = false;
663 ResetLayout();
664 #endif
667 void RenderText::ApplyColor(SkColor value, const Range& range) {
668 colors_.ApplyValue(value, range);
670 #if defined(OS_WIN)
671 // TODO(msw): Windows applies colors and decorations in the layout process.
672 cached_bounds_and_offset_valid_ = false;
673 ResetLayout();
674 #endif
677 void RenderText::SetStyle(TextStyle style, bool value) {
678 styles_[style].SetValue(value);
680 // Only invalidate the layout on font changes; not for colors or decorations.
681 bool invalidate = (style == BOLD) || (style == ITALIC);
682 #if defined(OS_WIN)
683 // TODO(msw): Windows applies colors and decorations in the layout process.
684 invalidate = true;
685 #endif
686 if (invalidate) {
687 cached_bounds_and_offset_valid_ = false;
688 ResetLayout();
692 void RenderText::ApplyStyle(TextStyle style, bool value, const Range& range) {
693 styles_[style].ApplyValue(value, range);
695 // Only invalidate the layout on font changes; not for colors or decorations.
696 bool invalidate = (style == BOLD) || (style == ITALIC);
697 #if defined(OS_WIN)
698 // TODO(msw): Windows applies colors and decorations in the layout process.
699 invalidate = true;
700 #endif
701 if (invalidate) {
702 cached_bounds_and_offset_valid_ = false;
703 ResetLayout();
707 bool RenderText::GetStyle(TextStyle style) const {
708 return (styles_[style].breaks().size() == 1) &&
709 styles_[style].breaks().front().second;
712 void RenderText::SetDirectionalityMode(DirectionalityMode mode) {
713 if (mode == directionality_mode_)
714 return;
716 directionality_mode_ = mode;
717 text_direction_ = base::i18n::UNKNOWN_DIRECTION;
718 cached_bounds_and_offset_valid_ = false;
719 ResetLayout();
722 base::i18n::TextDirection RenderText::GetTextDirection() {
723 if (text_direction_ == base::i18n::UNKNOWN_DIRECTION) {
724 switch (directionality_mode_) {
725 case DIRECTIONALITY_FROM_TEXT:
726 // Derive the direction from the display text, which differs from text()
727 // in the case of obscured (password) textfields.
728 text_direction_ =
729 base::i18n::GetFirstStrongCharacterDirection(GetLayoutText());
730 break;
731 case DIRECTIONALITY_FROM_UI:
732 text_direction_ = base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT :
733 base::i18n::LEFT_TO_RIGHT;
734 break;
735 case DIRECTIONALITY_FORCE_LTR:
736 text_direction_ = base::i18n::LEFT_TO_RIGHT;
737 break;
738 case DIRECTIONALITY_FORCE_RTL:
739 text_direction_ = base::i18n::RIGHT_TO_LEFT;
740 break;
741 default:
742 NOTREACHED();
746 return text_direction_;
749 VisualCursorDirection RenderText::GetVisualDirectionOfLogicalEnd() {
750 return GetTextDirection() == base::i18n::LEFT_TO_RIGHT ?
751 CURSOR_RIGHT : CURSOR_LEFT;
754 SizeF RenderText::GetStringSizeF() {
755 const Size size = GetStringSize();
756 return SizeF(size.width(), size.height());
759 float RenderText::GetContentWidth() {
760 return GetStringSizeF().width() + (cursor_enabled_ ? 1 : 0);
763 int RenderText::GetBaseline() {
764 if (baseline_ == kInvalidBaseline)
765 baseline_ = DetermineBaselineCenteringText(display_rect(), font_list());
766 DCHECK_NE(kInvalidBaseline, baseline_);
767 return baseline_;
770 void RenderText::Draw(Canvas* canvas) {
771 EnsureLayout();
773 if (clip_to_display_rect()) {
774 Rect clip_rect(display_rect());
775 clip_rect.Inset(ShadowValue::GetMargin(shadows_));
777 canvas->Save();
778 canvas->ClipRect(clip_rect);
781 if (!text().empty() && focused())
782 DrawSelection(canvas);
784 if (cursor_enabled() && cursor_visible() && focused())
785 DrawCursor(canvas, selection_model_);
787 if (!text().empty())
788 DrawVisualText(canvas);
790 if (clip_to_display_rect())
791 canvas->Restore();
794 void RenderText::DrawCursor(Canvas* canvas, const SelectionModel& position) {
795 // Paint cursor. Replace cursor is drawn as rectangle for now.
796 // TODO(msw): Draw a better cursor with a better indication of association.
797 canvas->FillRect(GetCursorBounds(position, true), cursor_color_);
800 bool RenderText::IsValidLogicalIndex(size_t index) {
801 // Check that the index is at a valid code point (not mid-surrgate-pair) and
802 // that it's not truncated from the layout text (its glyph may be shown).
804 // Indices within truncated text are disallowed so users can easily interact
805 // with the underlying truncated text using the ellipsis as a proxy. This lets
806 // users select all text, select the truncated text, and transition from the
807 // last rendered glyph to the end of the text without getting invisible cursor
808 // positions nor needing unbounded arrow key presses to traverse the ellipsis.
809 return index == 0 || index == text().length() ||
810 (index < text().length() &&
811 (truncate_length_ == 0 || index < truncate_length_) &&
812 IsValidCodePointIndex(text(), index));
815 Rect RenderText::GetCursorBounds(const SelectionModel& caret,
816 bool insert_mode) {
817 // TODO(ckocagil): Support multiline. This function should return the height
818 // of the line the cursor is on. |GetStringSize()| now returns
819 // the multiline size, eliminate its use here.
821 EnsureLayout();
822 size_t caret_pos = caret.caret_pos();
823 DCHECK(IsValidLogicalIndex(caret_pos));
824 // In overtype mode, ignore the affinity and always indicate that we will
825 // overtype the next character.
826 LogicalCursorDirection caret_affinity =
827 insert_mode ? caret.caret_affinity() : CURSOR_FORWARD;
828 int x = 0, width = 1;
829 Size size = GetStringSize();
830 if (caret_pos == (caret_affinity == CURSOR_BACKWARD ? 0 : text().length())) {
831 // The caret is attached to the boundary. Always return a 1-dip width caret,
832 // since there is nothing to overtype.
833 if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT) == (caret_pos == 0))
834 x = size.width();
835 } else {
836 size_t grapheme_start = (caret_affinity == CURSOR_FORWARD) ?
837 caret_pos : IndexOfAdjacentGrapheme(caret_pos, CURSOR_BACKWARD);
838 Range xspan(GetGlyphBounds(grapheme_start));
839 if (insert_mode) {
840 x = (caret_affinity == CURSOR_BACKWARD) ? xspan.end() : xspan.start();
841 } else { // overtype mode
842 x = xspan.GetMin();
843 width = xspan.length();
846 return Rect(ToViewPoint(Point(x, 0)), Size(width, size.height()));
849 const Rect& RenderText::GetUpdatedCursorBounds() {
850 UpdateCachedBoundsAndOffset();
851 return cursor_bounds_;
854 size_t RenderText::IndexOfAdjacentGrapheme(size_t index,
855 LogicalCursorDirection direction) {
856 if (index > text().length())
857 return text().length();
859 EnsureLayout();
861 if (direction == CURSOR_FORWARD) {
862 while (index < text().length()) {
863 index++;
864 if (IsValidCursorIndex(index))
865 return index;
867 return text().length();
870 while (index > 0) {
871 index--;
872 if (IsValidCursorIndex(index))
873 return index;
875 return 0;
878 SelectionModel RenderText::GetSelectionModelForSelectionStart() {
879 const Range& sel = selection();
880 if (sel.is_empty())
881 return selection_model_;
882 return SelectionModel(sel.start(),
883 sel.is_reversed() ? CURSOR_BACKWARD : CURSOR_FORWARD);
886 const Vector2d& RenderText::GetUpdatedDisplayOffset() {
887 UpdateCachedBoundsAndOffset();
888 return display_offset_;
891 void RenderText::SetDisplayOffset(int horizontal_offset) {
892 const int extra_content = GetContentWidth() - display_rect_.width();
894 int min_offset = 0;
895 int max_offset = 0;
896 if (extra_content > 0) {
897 switch (horizontal_alignment_) {
898 case ALIGN_LEFT:
899 min_offset = -extra_content;
900 break;
901 case ALIGN_RIGHT:
902 max_offset = extra_content;
903 break;
904 case ALIGN_CENTER:
905 min_offset = -extra_content / 2;
906 max_offset = extra_content / 2;
907 break;
908 default:
909 break;
912 if (horizontal_offset < min_offset)
913 horizontal_offset = min_offset;
914 else if (horizontal_offset > max_offset)
915 horizontal_offset = max_offset;
917 cached_bounds_and_offset_valid_ = true;
918 display_offset_.set_x(horizontal_offset);
919 cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_);
922 RenderText::RenderText()
923 : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT : ALIGN_LEFT),
924 directionality_mode_(DIRECTIONALITY_FROM_TEXT),
925 text_direction_(base::i18n::UNKNOWN_DIRECTION),
926 cursor_enabled_(true),
927 cursor_visible_(false),
928 insert_mode_(true),
929 cursor_color_(kDefaultColor),
930 selection_color_(kDefaultColor),
931 selection_background_focused_color_(kDefaultSelectionBackgroundColor),
932 focused_(false),
933 composition_range_(Range::InvalidRange()),
934 colors_(kDefaultColor),
935 styles_(NUM_TEXT_STYLES),
936 composition_and_selection_styles_applied_(false),
937 obscured_(false),
938 obscured_reveal_index_(-1),
939 truncate_length_(0),
940 elide_behavior_(NO_ELIDE),
941 multiline_(false),
942 background_is_transparent_(false),
943 clip_to_display_rect_(true),
944 baseline_(kInvalidBaseline),
945 cached_bounds_and_offset_valid_(false) {
948 SelectionModel RenderText::GetAdjacentSelectionModel(
949 const SelectionModel& current,
950 BreakType break_type,
951 VisualCursorDirection direction) {
952 EnsureLayout();
954 if (break_type == LINE_BREAK || text().empty())
955 return EdgeSelectionModel(direction);
956 if (break_type == CHARACTER_BREAK)
957 return AdjacentCharSelectionModel(current, direction);
958 DCHECK(break_type == WORD_BREAK);
959 return AdjacentWordSelectionModel(current, direction);
962 SelectionModel RenderText::EdgeSelectionModel(
963 VisualCursorDirection direction) {
964 if (direction == GetVisualDirectionOfLogicalEnd())
965 return SelectionModel(text().length(), CURSOR_FORWARD);
966 return SelectionModel(0, CURSOR_BACKWARD);
969 void RenderText::SetSelectionModel(const SelectionModel& model) {
970 DCHECK_LE(model.selection().GetMax(), text().length());
971 selection_model_ = model;
972 cached_bounds_and_offset_valid_ = false;
975 const base::string16& RenderText::GetLayoutText() const {
976 return layout_text_;
979 const BreakList<size_t>& RenderText::GetLineBreaks() {
980 if (line_breaks_.max() != 0)
981 return line_breaks_;
983 const base::string16& layout_text = GetLayoutText();
984 const size_t text_length = layout_text.length();
985 line_breaks_.SetValue(0);
986 line_breaks_.SetMax(text_length);
987 base::i18n::BreakIterator iter(layout_text,
988 base::i18n::BreakIterator::BREAK_LINE);
989 const bool success = iter.Init();
990 DCHECK(success);
991 if (success) {
992 do {
993 line_breaks_.ApplyValue(iter.pos(), Range(iter.pos(), text_length));
994 } while (iter.Advance());
996 return line_breaks_;
999 void RenderText::ApplyCompositionAndSelectionStyles() {
1000 // Save the underline and color breaks to undo the temporary styles later.
1001 DCHECK(!composition_and_selection_styles_applied_);
1002 saved_colors_ = colors_;
1003 saved_underlines_ = styles_[UNDERLINE];
1005 // Apply an underline to the composition range in |underlines|.
1006 if (composition_range_.IsValid() && !composition_range_.is_empty())
1007 styles_[UNDERLINE].ApplyValue(true, composition_range_);
1009 // Apply the selected text color to the [un-reversed] selection range.
1010 if (!selection().is_empty() && focused()) {
1011 const Range range(selection().GetMin(), selection().GetMax());
1012 colors_.ApplyValue(selection_color_, range);
1014 composition_and_selection_styles_applied_ = true;
1017 void RenderText::UndoCompositionAndSelectionStyles() {
1018 // Restore the underline and color breaks to undo the temporary styles.
1019 DCHECK(composition_and_selection_styles_applied_);
1020 colors_ = saved_colors_;
1021 styles_[UNDERLINE] = saved_underlines_;
1022 composition_and_selection_styles_applied_ = false;
1025 Vector2d RenderText::GetLineOffset(size_t line_number) {
1026 Vector2d offset = display_rect().OffsetFromOrigin();
1027 // TODO(ckocagil): Apply the display offset for multiline scrolling.
1028 if (!multiline())
1029 offset.Add(GetUpdatedDisplayOffset());
1030 else
1031 offset.Add(Vector2d(0, lines_[line_number].preceding_heights));
1032 offset.Add(GetAlignmentOffset(line_number));
1033 return offset;
1036 Point RenderText::ToTextPoint(const Point& point) {
1037 return point - GetLineOffset(0);
1038 // TODO(ckocagil): Convert multiline view space points to text space.
1041 Point RenderText::ToViewPoint(const Point& point) {
1042 if (!multiline())
1043 return point + GetLineOffset(0);
1045 // TODO(ckocagil): Traverse individual line segments for RTL support.
1046 DCHECK(!lines_.empty());
1047 int x = point.x();
1048 size_t line = 0;
1049 for (; line < lines_.size() && x > lines_[line].size.width(); ++line)
1050 x -= lines_[line].size.width();
1051 return Point(x, point.y()) + GetLineOffset(line);
1054 std::vector<Rect> RenderText::TextBoundsToViewBounds(const Range& x) {
1055 std::vector<Rect> rects;
1057 if (!multiline()) {
1058 rects.push_back(Rect(ToViewPoint(Point(x.GetMin(), 0)),
1059 Size(x.length(), GetStringSize().height())));
1060 return rects;
1063 EnsureLayout();
1065 // Each line segment keeps its position in text coordinates. Traverse all line
1066 // segments and if the segment intersects with the given range, add the view
1067 // rect corresponding to the intersection to |rects|.
1068 for (size_t line = 0; line < lines_.size(); ++line) {
1069 int line_x = 0;
1070 const Vector2d offset = GetLineOffset(line);
1071 for (size_t i = 0; i < lines_[line].segments.size(); ++i) {
1072 const internal::LineSegment* segment = &lines_[line].segments[i];
1073 const Range intersection = segment->x_range.Intersect(x);
1074 if (!intersection.is_empty()) {
1075 Rect rect(line_x + intersection.start() - segment->x_range.start(),
1076 0, intersection.length(), lines_[line].size.height());
1077 rects.push_back(rect + offset);
1079 line_x += segment->x_range.length();
1083 return rects;
1086 Vector2d RenderText::GetAlignmentOffset(size_t line_number) {
1087 // TODO(ckocagil): Enable |lines_| usage in other platforms.
1088 #if defined(OS_WIN)
1089 DCHECK_LT(line_number, lines_.size());
1090 #endif
1091 Vector2d offset;
1092 if (horizontal_alignment_ != ALIGN_LEFT) {
1093 #if defined(OS_WIN)
1094 const int width = lines_[line_number].size.width() +
1095 (cursor_enabled_ ? 1 : 0);
1096 #else
1097 const int width = GetContentWidth();
1098 #endif
1099 offset.set_x(display_rect().width() - width);
1100 if (horizontal_alignment_ == ALIGN_CENTER)
1101 offset.set_x(offset.x() / 2);
1104 // Vertically center the text.
1105 if (multiline_) {
1106 const int text_height = lines_.back().preceding_heights +
1107 lines_.back().size.height();
1108 offset.set_y((display_rect_.height() - text_height) / 2);
1109 } else {
1110 offset.set_y(GetBaseline() - GetLayoutTextBaseline());
1113 return offset;
1116 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer* renderer) {
1117 const int width = display_rect().width();
1118 if (multiline() || elide_behavior_ != FADE_TAIL || GetContentWidth() <= width)
1119 return;
1121 const int gradient_width = CalculateFadeGradientWidth(font_list(), width);
1122 if (gradient_width == 0)
1123 return;
1125 Rect solid_part = display_rect();
1126 Rect left_part;
1127 Rect right_part;
1128 if (horizontal_alignment_ != ALIGN_LEFT) {
1129 left_part = solid_part;
1130 left_part.Inset(0, 0, solid_part.width() - gradient_width, 0);
1131 solid_part.Inset(gradient_width, 0, 0, 0);
1133 if (horizontal_alignment_ != ALIGN_RIGHT) {
1134 right_part = solid_part;
1135 right_part.Inset(solid_part.width() - gradient_width, 0, 0, 0);
1136 solid_part.Inset(0, 0, gradient_width, 0);
1139 Rect text_rect = display_rect();
1140 text_rect.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1142 // TODO(msw): Use the actual text colors corresponding to each faded part.
1143 skia::RefPtr<SkShader> shader = CreateFadeShader(
1144 text_rect, left_part, right_part, colors_.breaks().front().second);
1145 if (shader)
1146 renderer->SetShader(shader.get(), display_rect());
1149 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer* renderer) {
1150 skia::RefPtr<SkDrawLooper> looper = CreateShadowDrawLooper(shadows_);
1151 renderer->SetDrawLooper(looper.get());
1154 // static
1155 bool RenderText::RangeContainsCaret(const Range& range,
1156 size_t caret_pos,
1157 LogicalCursorDirection caret_affinity) {
1158 // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1159 size_t adjacent = (caret_affinity == CURSOR_BACKWARD) ?
1160 caret_pos - 1 : caret_pos + 1;
1161 return range.Contains(Range(caret_pos, adjacent));
1164 void RenderText::MoveCursorTo(size_t position, bool select) {
1165 size_t cursor = std::min(position, text().length());
1166 if (IsValidCursorIndex(cursor))
1167 SetSelectionModel(SelectionModel(
1168 Range(select ? selection().start() : cursor, cursor),
1169 (cursor == 0) ? CURSOR_FORWARD : CURSOR_BACKWARD));
1172 void RenderText::UpdateLayoutText() {
1173 layout_text_.clear();
1174 line_breaks_.SetMax(0);
1176 if (obscured_) {
1177 size_t obscured_text_length =
1178 static_cast<size_t>(UTF16IndexToOffset(text_, 0, text_.length()));
1179 layout_text_.assign(obscured_text_length, kPasswordReplacementChar);
1181 if (obscured_reveal_index_ >= 0 &&
1182 obscured_reveal_index_ < static_cast<int>(text_.length())) {
1183 // Gets the index range in |text_| to be revealed.
1184 size_t start = obscured_reveal_index_;
1185 U16_SET_CP_START(text_.data(), 0, start);
1186 size_t end = start;
1187 UChar32 unused_char;
1188 U16_NEXT(text_.data(), end, text_.length(), unused_char);
1190 // Gets the index in |layout_text_| to be replaced.
1191 const size_t cp_start =
1192 static_cast<size_t>(UTF16IndexToOffset(text_, 0, start));
1193 if (layout_text_.length() > cp_start)
1194 layout_text_.replace(cp_start, 1, text_.substr(start, end - start));
1196 } else {
1197 layout_text_ = text_;
1200 const base::string16& text = layout_text_;
1201 if (truncate_length_ > 0 && truncate_length_ < text.length()) {
1202 // Truncate the text at a valid character break and append an ellipsis.
1203 icu::StringCharacterIterator iter(text.c_str());
1204 // Respect ELIDE_HEAD and ELIDE_MIDDLE preferences during truncation.
1205 if (elide_behavior_ == ELIDE_HEAD) {
1206 iter.setIndex32(text.length() - truncate_length_ + 1);
1207 layout_text_.assign(kEllipsisUTF16 + text.substr(iter.getIndex()));
1208 } else if (elide_behavior_ == ELIDE_MIDDLE) {
1209 iter.setIndex32(truncate_length_ / 2);
1210 const size_t ellipsis_start = iter.getIndex();
1211 iter.setIndex32(text.length() - (truncate_length_ / 2));
1212 const size_t ellipsis_end = iter.getIndex();
1213 DCHECK_LE(ellipsis_start, ellipsis_end);
1214 layout_text_.assign(text.substr(0, ellipsis_start) + kEllipsisUTF16 +
1215 text.substr(ellipsis_end));
1216 } else {
1217 iter.setIndex32(truncate_length_ - 1);
1218 layout_text_.assign(text.substr(0, iter.getIndex()) + kEllipsisUTF16);
1222 if (elide_behavior_ != NO_ELIDE && elide_behavior_ != FADE_TAIL &&
1223 !layout_text_.empty() && GetContentWidth() > display_rect_.width()) {
1224 // This doesn't trim styles so ellipsis may get rendered as a different
1225 // style than the preceding text. See crbug.com/327850.
1226 layout_text_.assign(
1227 Elide(layout_text_, display_rect_.width(), elide_behavior_));
1230 // Replace the newline character with a newline symbol in single line mode.
1231 static const base::char16 kNewline[] = { '\n', 0 };
1232 static const base::char16 kNewlineSymbol[] = { 0x2424, 0 };
1233 if (!multiline_)
1234 base::ReplaceChars(layout_text_, kNewline, kNewlineSymbol, &layout_text_);
1236 ResetLayout();
1239 base::string16 RenderText::Elide(const base::string16& text,
1240 float available_width,
1241 ElideBehavior behavior) {
1242 if (available_width <= 0 || text.empty())
1243 return base::string16();
1244 if (behavior == ELIDE_EMAIL)
1245 return ElideEmail(text, available_width);
1247 // Create a RenderText copy with attributes that affect the rendering width.
1248 scoped_ptr<RenderText> render_text(CreateInstance());
1249 render_text->SetFontList(font_list_);
1250 render_text->SetDirectionalityMode(directionality_mode_);
1251 render_text->SetCursorEnabled(cursor_enabled_);
1252 render_text->set_truncate_length(truncate_length_);
1253 render_text->styles_ = styles_;
1254 render_text->colors_ = colors_;
1255 render_text->SetText(text);
1256 if (render_text->GetContentWidth() <= available_width)
1257 return text;
1259 const base::string16 ellipsis = base::string16(kEllipsisUTF16);
1260 const bool insert_ellipsis = (behavior != TRUNCATE);
1261 const bool elide_in_middle = (behavior == ELIDE_MIDDLE);
1262 const bool elide_at_beginning = (behavior == ELIDE_HEAD);
1263 StringSlicer slicer(text, ellipsis, elide_in_middle, elide_at_beginning);
1265 render_text->SetText(ellipsis);
1266 const float ellipsis_width = render_text->GetContentWidth();
1268 if (insert_ellipsis && (ellipsis_width > available_width))
1269 return base::string16();
1271 // Use binary search to compute the elided text.
1272 size_t lo = 0;
1273 size_t hi = text.length() - 1;
1274 const base::i18n::TextDirection text_direction = GetTextDirection();
1275 for (size_t guess = (lo + hi) / 2; lo <= hi; guess = (lo + hi) / 2) {
1276 // Restore styles and colors. They will be truncated to size by SetText.
1277 render_text->styles_ = styles_;
1278 render_text->colors_ = colors_;
1279 base::string16 new_text =
1280 slicer.CutString(guess, insert_ellipsis && behavior != ELIDE_TAIL);
1281 render_text->SetText(new_text);
1283 // This has to be an additional step so that the ellipsis is rendered with
1284 // same style as trailing part of the text.
1285 if (insert_ellipsis && behavior == ELIDE_TAIL) {
1286 // When ellipsis follows text whose directionality is not the same as that
1287 // of the whole text, it will be rendered with the directionality of the
1288 // whole text. Since we want ellipsis to indicate continuation of the
1289 // preceding text, we force the directionality of ellipsis to be same as
1290 // the preceding text using LTR or RTL markers.
1291 base::i18n::TextDirection trailing_text_direction =
1292 base::i18n::GetLastStrongCharacterDirection(new_text);
1293 new_text.append(ellipsis);
1294 if (trailing_text_direction != text_direction) {
1295 if (trailing_text_direction == base::i18n::LEFT_TO_RIGHT)
1296 new_text += base::i18n::kLeftToRightMark;
1297 else
1298 new_text += base::i18n::kRightToLeftMark;
1300 render_text->SetText(new_text);
1303 // We check the width of the whole desired string at once to ensure we
1304 // handle kerning/ligatures/etc. correctly.
1305 const float guess_width = render_text->GetContentWidth();
1306 if (guess_width == available_width)
1307 break;
1308 if (guess_width > available_width) {
1309 hi = guess - 1;
1310 // Move back on the loop terminating condition when the guess is too wide.
1311 if (hi < lo)
1312 lo = hi;
1313 } else {
1314 lo = guess + 1;
1318 return render_text->text();
1321 base::string16 RenderText::ElideEmail(const base::string16& email,
1322 float available_width) {
1323 // The returned string will have at least one character besides the ellipsis
1324 // on either side of '@'; if that's impossible, a single ellipsis is returned.
1325 // If possible, only the username is elided. Otherwise, the domain is elided
1326 // in the middle, splitting available width equally with the elided username.
1327 // If the username is short enough that it doesn't need half the available
1328 // width, the elided domain will occupy that extra width.
1330 // Split the email into its local-part (username) and domain-part. The email
1331 // spec allows for @ symbols in the username under some special requirements,
1332 // but not in the domain part, so splitting at the last @ symbol is safe.
1333 const size_t split_index = email.find_last_of('@');
1334 DCHECK_NE(split_index, base::string16::npos);
1335 base::string16 username = email.substr(0, split_index);
1336 base::string16 domain = email.substr(split_index + 1);
1337 DCHECK(!username.empty());
1338 DCHECK(!domain.empty());
1340 // Subtract the @ symbol from the available width as it is mandatory.
1341 const base::string16 kAtSignUTF16 = base::ASCIIToUTF16("@");
1342 available_width -= GetStringWidthF(kAtSignUTF16, font_list());
1344 // Check whether eliding the domain is necessary: if eliding the username
1345 // is sufficient, the domain will not be elided.
1346 const float full_username_width = GetStringWidthF(username, font_list());
1347 const float available_domain_width = available_width -
1348 std::min(full_username_width,
1349 GetStringWidthF(username.substr(0, 1) + kEllipsisUTF16, font_list()));
1350 if (GetStringWidthF(domain, font_list()) > available_domain_width) {
1351 // Elide the domain so that it only takes half of the available width.
1352 // Should the username not need all the width available in its half, the
1353 // domain will occupy the leftover width.
1354 // If |desired_domain_width| is greater than |available_domain_width|: the
1355 // minimal username elision allowed by the specifications will not fit; thus
1356 // |desired_domain_width| must be <= |available_domain_width| at all cost.
1357 const float desired_domain_width =
1358 std::min<float>(available_domain_width,
1359 std::max<float>(available_width - full_username_width,
1360 available_width / 2));
1361 domain = Elide(domain, desired_domain_width, ELIDE_MIDDLE);
1362 // Failing to elide the domain such that at least one character remains
1363 // (other than the ellipsis itself) remains: return a single ellipsis.
1364 if (domain.length() <= 1U)
1365 return base::string16(kEllipsisUTF16);
1368 // Fit the username in the remaining width (at this point the elided username
1369 // is guaranteed to fit with at least one character remaining given all the
1370 // precautions taken earlier).
1371 available_width -= GetStringWidthF(domain, font_list());
1372 username = Elide(username, available_width, ELIDE_TAIL);
1373 return username + kAtSignUTF16 + domain;
1376 void RenderText::UpdateCachedBoundsAndOffset() {
1377 if (cached_bounds_and_offset_valid_)
1378 return;
1380 // TODO(ckocagil): Add support for scrolling multiline text.
1382 // First, set the valid flag true to calculate the current cursor bounds using
1383 // the stale |display_offset_|. Applying |delta_offset| at the end of this
1384 // function will set |cursor_bounds_| and |display_offset_| to correct values.
1385 cached_bounds_and_offset_valid_ = true;
1386 if (cursor_enabled())
1387 cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_);
1389 // Update |display_offset_| to ensure the current cursor is visible.
1390 const int display_width = display_rect_.width();
1391 const int content_width = GetContentWidth();
1393 int delta_x = 0;
1394 if (content_width <= display_width || !cursor_enabled()) {
1395 // Don't pan if the text fits in the display width or when the cursor is
1396 // disabled.
1397 delta_x = -display_offset_.x();
1398 } else if (cursor_bounds_.right() > display_rect_.right()) {
1399 // TODO(xji): when the character overflow is a RTL character, currently, if
1400 // we pan cursor at the rightmost position, the entered RTL character is not
1401 // displayed. Should pan cursor to show the last logical characters.
1403 // Pan to show the cursor when it overflows to the right.
1404 delta_x = display_rect_.right() - cursor_bounds_.right();
1405 } else if (cursor_bounds_.x() < display_rect_.x()) {
1406 // TODO(xji): have similar problem as above when overflow character is a
1407 // LTR character.
1409 // Pan to show the cursor when it overflows to the left.
1410 delta_x = display_rect_.x() - cursor_bounds_.x();
1411 } else if (display_offset_.x() != 0) {
1412 // Reduce the pan offset to show additional overflow text when the display
1413 // width increases.
1414 const int negate_rtl = horizontal_alignment_ == ALIGN_RIGHT ? -1 : 1;
1415 const int offset = negate_rtl * display_offset_.x();
1416 if (display_width > (content_width + offset)) {
1417 delta_x = negate_rtl * (display_width - (content_width + offset));
1421 Vector2d delta_offset(delta_x, 0);
1422 display_offset_ += delta_offset;
1423 cursor_bounds_ += delta_offset;
1426 void RenderText::DrawSelection(Canvas* canvas) {
1427 const std::vector<Rect> sel = GetSubstringBounds(selection());
1428 for (std::vector<Rect>::const_iterator i = sel.begin(); i < sel.end(); ++i)
1429 canvas->FillRect(*i, selection_background_focused_color_);
1432 } // namespace gfx