Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / ui / gfx / render_text.cc
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.
4
5 #include "ui/gfx/render_text.h"
6
7 #include <algorithm>
8 #include <climits>
9
10 #include "base/i18n/break_iterator.h"
11 #include "base/logging.h"
12 #include "base/stl_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "third_party/icu/source/common/unicode/rbbi.h"
15 #include "third_party/icu/source/common/unicode/utf16.h"
16 #include "third_party/skia/include/core/SkTypeface.h"
17 #include "third_party/skia/include/effects/SkGradientShader.h"
18 #include "ui/gfx/canvas.h"
19 #include "ui/gfx/insets.h"
20 #include "ui/gfx/skia_util.h"
21 #include "ui/gfx/text_constants.h"
22 #include "ui/gfx/text_elider.h"
23 #include "ui/gfx/text_utils.h"
24 #include "ui/gfx/utf16_indexing.h"
25
26 namespace gfx {
27
28 namespace {
29
30 // All chars are replaced by this char when the password style is set.
31 // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*'
32 // that's available in the font (find_invisible_char() in gtkentry.c).
33 const base::char16 kPasswordReplacementChar = '*';
34
35 // Default color used for the text and cursor.
36 const SkColor kDefaultColor = SK_ColorBLACK;
37
38 // Default color used for drawing selection background.
39 const SkColor kDefaultSelectionBackgroundColor = SK_ColorGRAY;
40
41 // Fraction of the text size to lower a strike through below the baseline.
42 const SkScalar kStrikeThroughOffset = (-SK_Scalar1 * 6 / 21);
43 // Fraction of the text size to lower an underline below the baseline.
44 const SkScalar kUnderlineOffset = (SK_Scalar1 / 9);
45 // Fraction of the text size to use for a strike through or under-line.
46 const SkScalar kLineThickness = (SK_Scalar1 / 18);
47 // Fraction of the text size to use for a top margin of a diagonal strike.
48 const SkScalar kDiagonalStrikeMarginOffset = (SK_Scalar1 / 4);
49
50 // Invalid value of baseline.  Assigning this value to |baseline_| causes
51 // re-calculation of baseline.
52 const int kInvalidBaseline = INT_MAX;
53
54 // Returns the baseline, with which the text best appears vertically centered.
55 int DetermineBaselineCenteringText(const Rect& display_rect,
56                                    const FontList& font_list) {
57   const int display_height = display_rect.height();
58   const int font_height = font_list.GetHeight();
59   // Lower and upper bound of baseline shift as we try to show as much area of
60   // text as possible.  In particular case of |display_height| == |font_height|,
61   // we do not want to shift the baseline.
62   const int min_shift = std::min(0, display_height - font_height);
63   const int max_shift = std::abs(display_height - font_height);
64   const int baseline = font_list.GetBaseline();
65   const int cap_height = font_list.GetCapHeight();
66   const int internal_leading = baseline - cap_height;
67   // Some platforms don't support getting the cap height, and simply return
68   // the entire font ascent from GetCapHeight().  Centering the ascent makes
69   // the font look too low, so if GetCapHeight() returns the ascent, center
70   // the entire font height instead.
71   const int space =
72       display_height - ((internal_leading != 0) ? cap_height : font_height);
73   const int baseline_shift = space / 2 - internal_leading;
74   return baseline + std::max(min_shift, std::min(max_shift, baseline_shift));
75 }
76
77 // Converts |gfx::Font::FontStyle| flags to |SkTypeface::Style| flags.
78 SkTypeface::Style ConvertFontStyleToSkiaTypefaceStyle(int font_style) {
79   int skia_style = SkTypeface::kNormal;
80   skia_style |= (font_style & gfx::Font::BOLD) ? SkTypeface::kBold : 0;
81   skia_style |= (font_style & gfx::Font::ITALIC) ? SkTypeface::kItalic : 0;
82   return static_cast<SkTypeface::Style>(skia_style);
83 }
84
85 // Given |font| and |display_width|, returns the width of the fade gradient.
86 int CalculateFadeGradientWidth(const FontList& font_list, int display_width) {
87   // Fade in/out about 2.5 characters of the beginning/end of the string.
88   // The .5 here is helpful if one of the characters is a space.
89   // Use a quarter of the display width if the display width is very short.
90   const int average_character_width = font_list.GetExpectedTextWidth(1);
91   const double gradient_width = std::min(average_character_width * 2.5,
92                                          display_width / 4.0);
93   DCHECK_GE(gradient_width, 0.0);
94   return static_cast<int>(floor(gradient_width + 0.5));
95 }
96
97 // Appends to |positions| and |colors| values corresponding to the fade over
98 // |fade_rect| from color |c0| to color |c1|.
99 void AddFadeEffect(const Rect& text_rect,
100                    const Rect& fade_rect,
101                    SkColor c0,
102                    SkColor c1,
103                    std::vector<SkScalar>* positions,
104                    std::vector<SkColor>* colors) {
105   const SkScalar left = static_cast<SkScalar>(fade_rect.x() - text_rect.x());
106   const SkScalar width = static_cast<SkScalar>(fade_rect.width());
107   const SkScalar p0 = left / text_rect.width();
108   const SkScalar p1 = (left + width) / text_rect.width();
109   // Prepend 0.0 to |positions|, as required by Skia.
110   if (positions->empty() && p0 != 0.0) {
111     positions->push_back(0.0);
112     colors->push_back(c0);
113   }
114   positions->push_back(p0);
115   colors->push_back(c0);
116   positions->push_back(p1);
117   colors->push_back(c1);
118 }
119
120 // Creates a SkShader to fade the text, with |left_part| specifying the left
121 // fade effect, if any, and |right_part| specifying the right fade effect.
122 skia::RefPtr<SkShader> CreateFadeShader(const Rect& text_rect,
123                                         const Rect& left_part,
124                                         const Rect& right_part,
125                                         SkColor color) {
126   // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color.
127   const SkColor fade_color = SkColorSetA(color, 51);
128   std::vector<SkScalar> positions;
129   std::vector<SkColor> colors;
130
131   if (!left_part.IsEmpty())
132     AddFadeEffect(text_rect, left_part, fade_color, color,
133                   &positions, &colors);
134   if (!right_part.IsEmpty())
135     AddFadeEffect(text_rect, right_part, color, fade_color,
136                   &positions, &colors);
137   DCHECK(!positions.empty());
138
139   // Terminate |positions| with 1.0, as required by Skia.
140   if (positions.back() != 1.0) {
141     positions.push_back(1.0);
142     colors.push_back(colors.back());
143   }
144
145   SkPoint points[2];
146   points[0].iset(text_rect.x(), text_rect.y());
147   points[1].iset(text_rect.right(), text_rect.y());
148
149   return skia::AdoptRef(
150       SkGradientShader::CreateLinear(&points[0], &colors[0], &positions[0],
151                                      colors.size(), SkShader::kClamp_TileMode));
152 }
153
154 }  // namespace
155
156 namespace internal {
157
158 // Value of |underline_thickness_| that indicates that underline metrics have
159 // not been set explicitly.
160 const SkScalar kUnderlineMetricsNotSet = -1.0f;
161
162 SkiaTextRenderer::SkiaTextRenderer(Canvas* canvas)
163     : canvas_(canvas),
164       canvas_skia_(canvas->sk_canvas()),
165       started_drawing_(false),
166       underline_thickness_(kUnderlineMetricsNotSet),
167       underline_position_(0.0f) {
168   DCHECK(canvas_skia_);
169   paint_.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
170   paint_.setStyle(SkPaint::kFill_Style);
171   paint_.setAntiAlias(true);
172   paint_.setSubpixelText(true);
173   paint_.setLCDRenderText(true);
174   paint_.setHinting(SkPaint::kNormal_Hinting);
175   bounds_.setEmpty();
176 }
177
178 SkiaTextRenderer::~SkiaTextRenderer() {
179   // Work-around for http://crbug.com/122743, where non-ClearType text is
180   // rendered with incorrect gamma when using the fade shader. Draw the text
181   // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode.
182   //
183   // TODO(asvitkine): Remove this work-around once the Skia bug is fixed.
184   //                  http://code.google.com/p/skia/issues/detail?id=590
185   if (deferred_fade_shader_.get()) {
186     paint_.setShader(deferred_fade_shader_.get());
187     paint_.setXfermodeMode(SkXfermode::kDstIn_Mode);
188     canvas_skia_->drawRect(bounds_, paint_);
189     canvas_skia_->restore();
190   }
191 }
192
193 void SkiaTextRenderer::SetDrawLooper(SkDrawLooper* draw_looper) {
194   paint_.setLooper(draw_looper);
195 }
196
197 void SkiaTextRenderer::SetFontSmoothingSettings(bool antialiasing,
198                                                 bool subpixel_rendering,
199                                                 bool subpixel_positioning) {
200   paint_.setAntiAlias(antialiasing);
201   paint_.setLCDRenderText(subpixel_rendering);
202   paint_.setSubpixelText(subpixel_positioning);
203 }
204
205 void SkiaTextRenderer::SetFontHinting(SkPaint::Hinting hinting) {
206   paint_.setHinting(hinting);
207 }
208
209 void SkiaTextRenderer::SetTypeface(SkTypeface* typeface) {
210   paint_.setTypeface(typeface);
211 }
212
213 void SkiaTextRenderer::SetTextSize(SkScalar size) {
214   paint_.setTextSize(size);
215 }
216
217 void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string& family,
218                                               int style) {
219   DCHECK(!family.empty());
220
221   SkTypeface::Style skia_style = ConvertFontStyleToSkiaTypefaceStyle(style);
222   skia::RefPtr<SkTypeface> typeface =
223       skia::AdoptRef(SkTypeface::CreateFromName(family.c_str(), skia_style));
224   if (typeface) {
225     // |paint_| adds its own ref. So don't |release()| it from the ref ptr here.
226     SetTypeface(typeface.get());
227
228     // Enable fake bold text if bold style is needed but new typeface does not
229     // have it.
230     paint_.setFakeBoldText((skia_style & SkTypeface::kBold) &&
231                            !typeface->isBold());
232   }
233 }
234
235 void SkiaTextRenderer::SetForegroundColor(SkColor foreground) {
236   paint_.setColor(foreground);
237 }
238
239 void SkiaTextRenderer::SetShader(SkShader* shader, const Rect& bounds) {
240   bounds_ = RectToSkRect(bounds);
241   paint_.setShader(shader);
242 }
243
244 void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness,
245                                            SkScalar position) {
246   underline_thickness_ = thickness;
247   underline_position_ = position;
248 }
249
250 void SkiaTextRenderer::DrawPosText(const SkPoint* pos,
251                                    const uint16* glyphs,
252                                    size_t glyph_count) {
253   if (!started_drawing_) {
254     started_drawing_ = true;
255     // Work-around for http://crbug.com/122743, where non-ClearType text is
256     // rendered with incorrect gamma when using the fade shader. Draw the text
257     // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode.
258     //
259     // Skip this when there is a looper which seems not working well with
260     // deferred paint. Currently a looper is only used for text shadows.
261     //
262     // TODO(asvitkine): Remove this work-around once the Skia bug is fixed.
263     //                  http://code.google.com/p/skia/issues/detail?id=590
264     if (!paint_.isLCDRenderText() &&
265         paint_.getShader() &&
266         !paint_.getLooper()) {
267       deferred_fade_shader_ = skia::SharePtr(paint_.getShader());
268       paint_.setShader(NULL);
269       canvas_skia_->saveLayer(&bounds_, NULL);
270     }
271   }
272
273   const size_t byte_length = glyph_count * sizeof(glyphs[0]);
274   canvas_skia_->drawPosText(&glyphs[0], byte_length, &pos[0], paint_);
275 }
276
277 void SkiaTextRenderer::DrawDecorations(int x, int y, int width, bool underline,
278                                        bool strike, bool diagonal_strike) {
279   if (underline)
280     DrawUnderline(x, y, width);
281   if (strike)
282     DrawStrike(x, y, width);
283   if (diagonal_strike) {
284     if (!diagonal_)
285       diagonal_.reset(new DiagonalStrike(canvas_, Point(x, y), paint_));
286     diagonal_->AddPiece(width, paint_.getColor());
287   } else if (diagonal_) {
288     EndDiagonalStrike();
289   }
290 }
291
292 void SkiaTextRenderer::EndDiagonalStrike() {
293   if (diagonal_) {
294     diagonal_->Draw();
295     diagonal_.reset();
296   }
297 }
298
299 void SkiaTextRenderer::DrawUnderline(int x, int y, int width) {
300   SkRect r = SkRect::MakeLTRB(x, y + underline_position_, x + width,
301                               y + underline_position_ + underline_thickness_);
302   if (underline_thickness_ == kUnderlineMetricsNotSet) {
303     const SkScalar text_size = paint_.getTextSize();
304     r.fTop = SkScalarMulAdd(text_size, kUnderlineOffset, y);
305     r.fBottom = r.fTop + SkScalarMul(text_size, kLineThickness);
306   }
307   canvas_skia_->drawRect(r, paint_);
308 }
309
310 void SkiaTextRenderer::DrawStrike(int x, int y, int width) const {
311   const SkScalar text_size = paint_.getTextSize();
312   const SkScalar height = SkScalarMul(text_size, kLineThickness);
313   const SkScalar offset = SkScalarMulAdd(text_size, kStrikeThroughOffset, y);
314   const SkRect r = SkRect::MakeLTRB(x, offset, x + width, offset + height);
315   canvas_skia_->drawRect(r, paint_);
316 }
317
318 SkiaTextRenderer::DiagonalStrike::DiagonalStrike(Canvas* canvas,
319                                                  Point start,
320                                                  const SkPaint& paint)
321     : canvas_(canvas),
322       start_(start),
323       paint_(paint),
324       total_length_(0) {
325 }
326
327 SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() {
328 }
329
330 void SkiaTextRenderer::DiagonalStrike::AddPiece(int length, SkColor color) {
331   pieces_.push_back(Piece(length, color));
332   total_length_ += length;
333 }
334
335 void SkiaTextRenderer::DiagonalStrike::Draw() {
336   const SkScalar text_size = paint_.getTextSize();
337   const SkScalar offset = SkScalarMul(text_size, kDiagonalStrikeMarginOffset);
338   const int thickness =
339       SkScalarCeilToInt(SkScalarMul(text_size, kLineThickness) * 2);
340   const int height = SkScalarCeilToInt(text_size - offset);
341   const Point end = start_ + Vector2d(total_length_, -height);
342
343   paint_.setAntiAlias(true);
344   paint_.setStrokeWidth(thickness);
345
346   const bool clipped = pieces_.size() > 1;
347   int x = start_.x();
348   for (size_t i = 0; i < pieces_.size(); ++i) {
349     paint_.setColor(pieces_[i].second);
350
351     if (clipped) {
352       canvas_->Save();
353       canvas_->ClipRect(Rect(x, 0, pieces_[i].first, start_.y() + thickness));
354     }
355
356     canvas_->DrawLine(start_, end, paint_);
357
358     if (clipped)
359       canvas_->Restore();
360
361     x += pieces_[i].first;
362   }
363 }
364
365 StyleIterator::StyleIterator(const BreakList<SkColor>& colors,
366                              const std::vector<BreakList<bool> >& styles)
367     : colors_(colors),
368       styles_(styles) {
369   color_ = colors_.breaks().begin();
370   for (size_t i = 0; i < styles_.size(); ++i)
371     style_.push_back(styles_[i].breaks().begin());
372 }
373
374 StyleIterator::~StyleIterator() {}
375
376 Range StyleIterator::GetRange() const {
377   Range range(colors_.GetRange(color_));
378   for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
379     range = range.Intersect(styles_[i].GetRange(style_[i]));
380   return range;
381 }
382
383 void StyleIterator::UpdatePosition(size_t position) {
384   color_ = colors_.GetBreak(position);
385   for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
386     style_[i] = styles_[i].GetBreak(position);
387 }
388
389 LineSegment::LineSegment() : run(0) {}
390
391 LineSegment::~LineSegment() {}
392
393 Line::Line() : preceding_heights(0), baseline(0) {}
394
395 Line::~Line() {}
396
397 }  // namespace internal
398
399 RenderText::~RenderText() {
400 }
401
402 void RenderText::SetText(const base::string16& text) {
403   DCHECK(!composition_range_.IsValid());
404   if (text_ == text)
405     return;
406   text_ = text;
407
408   // Adjust ranged styles and colors to accommodate a new text length.
409   const size_t text_length = text_.length();
410   colors_.SetMax(text_length);
411   for (size_t style = 0; style < NUM_TEXT_STYLES; ++style)
412     styles_[style].SetMax(text_length);
413   cached_bounds_and_offset_valid_ = false;
414
415   // Reset selection model. SetText should always followed by SetSelectionModel
416   // or SetCursorPosition in upper layer.
417   SetSelectionModel(SelectionModel());
418
419   // Invalidate the cached text direction if it depends on the text contents.
420   if (directionality_mode_ == DIRECTIONALITY_FROM_TEXT)
421     text_direction_ = base::i18n::UNKNOWN_DIRECTION;
422
423   obscured_reveal_index_ = -1;
424   UpdateLayoutText();
425 }
426
427 void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment) {
428   if (horizontal_alignment_ != alignment) {
429     horizontal_alignment_ = alignment;
430     display_offset_ = Vector2d();
431     cached_bounds_and_offset_valid_ = false;
432   }
433 }
434
435 void RenderText::SetFontList(const FontList& font_list) {
436   font_list_ = font_list;
437   baseline_ = kInvalidBaseline;
438   cached_bounds_and_offset_valid_ = false;
439   ResetLayout();
440 }
441
442 void RenderText::SetCursorEnabled(bool cursor_enabled) {
443   cursor_enabled_ = cursor_enabled;
444   cached_bounds_and_offset_valid_ = false;
445 }
446
447 void RenderText::ToggleInsertMode() {
448   insert_mode_ = !insert_mode_;
449   cached_bounds_and_offset_valid_ = false;
450 }
451
452 void RenderText::SetObscured(bool obscured) {
453   if (obscured != obscured_) {
454     obscured_ = obscured;
455     obscured_reveal_index_ = -1;
456     cached_bounds_and_offset_valid_ = false;
457     UpdateLayoutText();
458   }
459 }
460
461 void RenderText::SetObscuredRevealIndex(int index) {
462   if (obscured_reveal_index_ == index)
463     return;
464
465   obscured_reveal_index_ = index;
466   cached_bounds_and_offset_valid_ = false;
467   UpdateLayoutText();
468 }
469
470 void RenderText::SetMultiline(bool multiline) {
471   if (multiline != multiline_) {
472     multiline_ = multiline;
473     cached_bounds_and_offset_valid_ = false;
474     lines_.clear();
475   }
476 }
477
478 void RenderText::SetElideBehavior(ElideBehavior elide_behavior) {
479   // TODO(skanuj) : Add a test for triggering layout change.
480   if (elide_behavior_ != elide_behavior) {
481     elide_behavior_ = elide_behavior;
482     UpdateLayoutText();
483   }
484 }
485
486 void RenderText::SetDisplayRect(const Rect& r) {
487   if (r != display_rect_) {
488     display_rect_ = r;
489     baseline_ = kInvalidBaseline;
490     cached_bounds_and_offset_valid_ = false;
491     lines_.clear();
492     if (elide_behavior_ != gfx::NO_ELIDE)
493       UpdateLayoutText();
494   }
495 }
496
497 void RenderText::SetCursorPosition(size_t position) {
498   MoveCursorTo(position, false);
499 }
500
501 void RenderText::MoveCursor(BreakType break_type,
502                             VisualCursorDirection direction,
503                             bool select) {
504   SelectionModel cursor(cursor_position(), selection_model_.caret_affinity());
505   // Cancelling a selection moves to the edge of the selection.
506   if (break_type != LINE_BREAK && !selection().is_empty() && !select) {
507     SelectionModel selection_start = GetSelectionModelForSelectionStart();
508     int start_x = GetCursorBounds(selection_start, true).x();
509     int cursor_x = GetCursorBounds(cursor, true).x();
510     // Use the selection start if it is left (when |direction| is CURSOR_LEFT)
511     // or right (when |direction| is CURSOR_RIGHT) of the selection end.
512     if (direction == CURSOR_RIGHT ? start_x > cursor_x : start_x < cursor_x)
513       cursor = selection_start;
514     // Use the nearest word boundary in the proper |direction| for word breaks.
515     if (break_type == WORD_BREAK)
516       cursor = GetAdjacentSelectionModel(cursor, break_type, direction);
517     // Use an adjacent selection model if the cursor is not at a valid position.
518     if (!IsValidCursorIndex(cursor.caret_pos()))
519       cursor = GetAdjacentSelectionModel(cursor, CHARACTER_BREAK, direction);
520   } else {
521     cursor = GetAdjacentSelectionModel(cursor, break_type, direction);
522   }
523   if (select)
524     cursor.set_selection_start(selection().start());
525   MoveCursorTo(cursor);
526 }
527
528 bool RenderText::MoveCursorTo(const SelectionModel& model) {
529   // Enforce valid selection model components.
530   size_t text_length = text().length();
531   Range range(std::min(model.selection().start(), text_length),
532               std::min(model.caret_pos(), text_length));
533   // The current model only supports caret positions at valid cursor indices.
534   if (!IsValidCursorIndex(range.start()) || !IsValidCursorIndex(range.end()))
535     return false;
536   SelectionModel sel(range, model.caret_affinity());
537   bool changed = sel != selection_model_;
538   SetSelectionModel(sel);
539   return changed;
540 }
541
542 bool RenderText::SelectRange(const Range& range) {
543   Range sel(std::min(range.start(), text().length()),
544             std::min(range.end(), text().length()));
545   // Allow selection bounds at valid indicies amid multi-character graphemes.
546   if (!IsValidLogicalIndex(sel.start()) || !IsValidLogicalIndex(sel.end()))
547     return false;
548   LogicalCursorDirection affinity =
549       (sel.is_reversed() || sel.is_empty()) ? CURSOR_FORWARD : CURSOR_BACKWARD;
550   SetSelectionModel(SelectionModel(sel, affinity));
551   return true;
552 }
553
554 bool RenderText::IsPointInSelection(const Point& point) {
555   if (selection().is_empty())
556     return false;
557   SelectionModel cursor = FindCursorPosition(point);
558   return RangeContainsCaret(
559       selection(), cursor.caret_pos(), cursor.caret_affinity());
560 }
561
562 void RenderText::ClearSelection() {
563   SetSelectionModel(SelectionModel(cursor_position(),
564                                    selection_model_.caret_affinity()));
565 }
566
567 void RenderText::SelectAll(bool reversed) {
568   const size_t length = text().length();
569   const Range all = reversed ? Range(length, 0) : Range(0, length);
570   const bool success = SelectRange(all);
571   DCHECK(success);
572 }
573
574 void RenderText::SelectWord() {
575   if (obscured_) {
576     SelectAll(false);
577     return;
578   }
579
580   size_t selection_max = selection().GetMax();
581
582   base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
583   bool success = iter.Init();
584   DCHECK(success);
585   if (!success)
586     return;
587
588   size_t selection_min = selection().GetMin();
589   if (selection_min == text().length() && selection_min != 0)
590     --selection_min;
591
592   for (; selection_min != 0; --selection_min) {
593     if (iter.IsStartOfWord(selection_min) ||
594         iter.IsEndOfWord(selection_min))
595       break;
596   }
597
598   if (selection_min == selection_max && selection_max != text().length())
599     ++selection_max;
600
601   for (; selection_max < text().length(); ++selection_max)
602     if (iter.IsEndOfWord(selection_max) || iter.IsStartOfWord(selection_max))
603       break;
604
605   const bool reversed = selection().is_reversed();
606   MoveCursorTo(reversed ? selection_max : selection_min, false);
607   MoveCursorTo(reversed ? selection_min : selection_max, true);
608 }
609
610 const Range& RenderText::GetCompositionRange() const {
611   return composition_range_;
612 }
613
614 void RenderText::SetCompositionRange(const Range& composition_range) {
615   CHECK(!composition_range.IsValid() ||
616         Range(0, text_.length()).Contains(composition_range));
617   composition_range_.set_end(composition_range.end());
618   composition_range_.set_start(composition_range.start());
619   ResetLayout();
620 }
621
622 void RenderText::SetColor(SkColor value) {
623   colors_.SetValue(value);
624
625 #if defined(OS_WIN)
626   // TODO(msw): Windows applies colors and decorations in the layout process.
627   cached_bounds_and_offset_valid_ = false;
628   ResetLayout();
629 #endif
630 }
631
632 void RenderText::ApplyColor(SkColor value, const Range& range) {
633   colors_.ApplyValue(value, range);
634
635 #if defined(OS_WIN)
636   // TODO(msw): Windows applies colors and decorations in the layout process.
637   cached_bounds_and_offset_valid_ = false;
638   ResetLayout();
639 #endif
640 }
641
642 void RenderText::SetStyle(TextStyle style, bool value) {
643   styles_[style].SetValue(value);
644
645   // Only invalidate the layout on font changes; not for colors or decorations.
646   bool invalidate = (style == BOLD) || (style == ITALIC);
647 #if defined(OS_WIN)
648   // TODO(msw): Windows applies colors and decorations in the layout process.
649   invalidate = true;
650 #endif
651   if (invalidate) {
652     cached_bounds_and_offset_valid_ = false;
653     ResetLayout();
654   }
655 }
656
657 void RenderText::ApplyStyle(TextStyle style, bool value, const Range& range) {
658   styles_[style].ApplyValue(value, range);
659
660   // Only invalidate the layout on font changes; not for colors or decorations.
661   bool invalidate = (style == BOLD) || (style == ITALIC);
662 #if defined(OS_WIN)
663   // TODO(msw): Windows applies colors and decorations in the layout process.
664   invalidate = true;
665 #endif
666   if (invalidate) {
667     cached_bounds_and_offset_valid_ = false;
668     ResetLayout();
669   }
670 }
671
672 bool RenderText::GetStyle(TextStyle style) const {
673   return (styles_[style].breaks().size() == 1) &&
674       styles_[style].breaks().front().second;
675 }
676
677 void RenderText::SetDirectionalityMode(DirectionalityMode mode) {
678   if (mode == directionality_mode_)
679     return;
680
681   directionality_mode_ = mode;
682   text_direction_ = base::i18n::UNKNOWN_DIRECTION;
683   cached_bounds_and_offset_valid_ = false;
684   ResetLayout();
685 }
686
687 base::i18n::TextDirection RenderText::GetTextDirection() {
688   if (text_direction_ == base::i18n::UNKNOWN_DIRECTION) {
689     switch (directionality_mode_) {
690       case DIRECTIONALITY_FROM_TEXT:
691         // Derive the direction from the display text, which differs from text()
692         // in the case of obscured (password) textfields.
693         text_direction_ =
694             base::i18n::GetFirstStrongCharacterDirection(GetLayoutText());
695         break;
696       case DIRECTIONALITY_FROM_UI:
697         text_direction_ = base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT :
698                                                 base::i18n::LEFT_TO_RIGHT;
699         break;
700       case DIRECTIONALITY_FORCE_LTR:
701         text_direction_ = base::i18n::LEFT_TO_RIGHT;
702         break;
703       case DIRECTIONALITY_FORCE_RTL:
704         text_direction_ = base::i18n::RIGHT_TO_LEFT;
705         break;
706       default:
707         NOTREACHED();
708     }
709   }
710
711   return text_direction_;
712 }
713
714 VisualCursorDirection RenderText::GetVisualDirectionOfLogicalEnd() {
715   return GetTextDirection() == base::i18n::LEFT_TO_RIGHT ?
716       CURSOR_RIGHT : CURSOR_LEFT;
717 }
718
719 SizeF RenderText::GetStringSizeF() {
720   const Size size = GetStringSize();
721   return SizeF(size.width(), size.height());
722 }
723
724 int RenderText::GetContentWidth() {
725   return GetStringSize().width() + (cursor_enabled_ ? 1 : 0);
726 }
727
728 int RenderText::GetBaseline() {
729   if (baseline_ == kInvalidBaseline)
730     baseline_ = DetermineBaselineCenteringText(display_rect(), font_list());
731   DCHECK_NE(kInvalidBaseline, baseline_);
732   return baseline_;
733 }
734
735 void RenderText::Draw(Canvas* canvas) {
736   EnsureLayout();
737
738   if (clip_to_display_rect()) {
739     Rect clip_rect(display_rect());
740     clip_rect.Inset(ShadowValue::GetMargin(text_shadows_));
741
742     canvas->Save();
743     canvas->ClipRect(clip_rect);
744   }
745
746   if (!text().empty() && focused())
747     DrawSelection(canvas);
748
749   if (cursor_enabled() && cursor_visible() && focused())
750     DrawCursor(canvas, selection_model_);
751
752   if (!text().empty())
753     DrawVisualText(canvas);
754
755   if (clip_to_display_rect())
756     canvas->Restore();
757 }
758
759 void RenderText::DrawCursor(Canvas* canvas, const SelectionModel& position) {
760   // Paint cursor. Replace cursor is drawn as rectangle for now.
761   // TODO(msw): Draw a better cursor with a better indication of association.
762   canvas->FillRect(GetCursorBounds(position, true), cursor_color_);
763 }
764
765 bool RenderText::IsValidLogicalIndex(size_t index) {
766   // Check that the index is at a valid code point (not mid-surrgate-pair) and
767   // that it's not truncated from the layout text (its glyph may be shown).
768   //
769   // Indices within truncated text are disallowed so users can easily interact
770   // with the underlying truncated text using the ellipsis as a proxy. This lets
771   // users select all text, select the truncated text, and transition from the
772   // last rendered glyph to the end of the text without getting invisible cursor
773   // positions nor needing unbounded arrow key presses to traverse the ellipsis.
774   return index == 0 || index == text().length() ||
775       (index < text().length() &&
776        (truncate_length_ == 0 || index < truncate_length_) &&
777        IsValidCodePointIndex(text(), index));
778 }
779
780 Rect RenderText::GetCursorBounds(const SelectionModel& caret,
781                                  bool insert_mode) {
782   // TODO(ckocagil): Support multiline. This function should return the height
783   //                 of the line the cursor is on. |GetStringSize()| now returns
784   //                 the multiline size, eliminate its use here.
785
786   EnsureLayout();
787   size_t caret_pos = caret.caret_pos();
788   DCHECK(IsValidLogicalIndex(caret_pos));
789   // In overtype mode, ignore the affinity and always indicate that we will
790   // overtype the next character.
791   LogicalCursorDirection caret_affinity =
792       insert_mode ? caret.caret_affinity() : CURSOR_FORWARD;
793   int x = 0, width = 1;
794   Size size = GetStringSize();
795   if (caret_pos == (caret_affinity == CURSOR_BACKWARD ? 0 : text().length())) {
796     // The caret is attached to the boundary. Always return a 1-dip width caret,
797     // since there is nothing to overtype.
798     if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT) == (caret_pos == 0))
799       x = size.width();
800   } else {
801     size_t grapheme_start = (caret_affinity == CURSOR_FORWARD) ?
802         caret_pos : IndexOfAdjacentGrapheme(caret_pos, CURSOR_BACKWARD);
803     Range xspan(GetGlyphBounds(grapheme_start));
804     if (insert_mode) {
805       x = (caret_affinity == CURSOR_BACKWARD) ? xspan.end() : xspan.start();
806     } else {  // overtype mode
807       x = xspan.GetMin();
808       width = xspan.length();
809     }
810   }
811   return Rect(ToViewPoint(Point(x, 0)), Size(width, size.height()));
812 }
813
814 const Rect& RenderText::GetUpdatedCursorBounds() {
815   UpdateCachedBoundsAndOffset();
816   return cursor_bounds_;
817 }
818
819 size_t RenderText::IndexOfAdjacentGrapheme(size_t index,
820                                            LogicalCursorDirection direction) {
821   if (index > text().length())
822     return text().length();
823
824   EnsureLayout();
825
826   if (direction == CURSOR_FORWARD) {
827     while (index < text().length()) {
828       index++;
829       if (IsValidCursorIndex(index))
830         return index;
831     }
832     return text().length();
833   }
834
835   while (index > 0) {
836     index--;
837     if (IsValidCursorIndex(index))
838       return index;
839   }
840   return 0;
841 }
842
843 SelectionModel RenderText::GetSelectionModelForSelectionStart() {
844   const Range& sel = selection();
845   if (sel.is_empty())
846     return selection_model_;
847   return SelectionModel(sel.start(),
848                         sel.is_reversed() ? CURSOR_BACKWARD : CURSOR_FORWARD);
849 }
850
851 void RenderText::SetTextShadows(const ShadowValues& shadows) {
852   text_shadows_ = shadows;
853 }
854
855 RenderText::RenderText()
856     : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT : ALIGN_LEFT),
857       directionality_mode_(DIRECTIONALITY_FROM_TEXT),
858       text_direction_(base::i18n::UNKNOWN_DIRECTION),
859       cursor_enabled_(true),
860       cursor_visible_(false),
861       insert_mode_(true),
862       cursor_color_(kDefaultColor),
863       selection_color_(kDefaultColor),
864       selection_background_focused_color_(kDefaultSelectionBackgroundColor),
865       focused_(false),
866       composition_range_(Range::InvalidRange()),
867       colors_(kDefaultColor),
868       styles_(NUM_TEXT_STYLES),
869       composition_and_selection_styles_applied_(false),
870       obscured_(false),
871       obscured_reveal_index_(-1),
872       truncate_length_(0),
873       elide_behavior_(NO_ELIDE),
874       multiline_(false),
875       fade_head_(false),
876       fade_tail_(false),
877       background_is_transparent_(false),
878       clip_to_display_rect_(true),
879       baseline_(kInvalidBaseline),
880       cached_bounds_and_offset_valid_(false) {
881 }
882
883 const Vector2d& RenderText::GetUpdatedDisplayOffset() {
884   UpdateCachedBoundsAndOffset();
885   return display_offset_;
886 }
887
888 SelectionModel RenderText::GetAdjacentSelectionModel(
889     const SelectionModel& current,
890     BreakType break_type,
891     VisualCursorDirection direction) {
892   EnsureLayout();
893
894   if (break_type == LINE_BREAK || text().empty())
895     return EdgeSelectionModel(direction);
896   if (break_type == CHARACTER_BREAK)
897     return AdjacentCharSelectionModel(current, direction);
898   DCHECK(break_type == WORD_BREAK);
899   return AdjacentWordSelectionModel(current, direction);
900 }
901
902 SelectionModel RenderText::EdgeSelectionModel(
903     VisualCursorDirection direction) {
904   if (direction == GetVisualDirectionOfLogicalEnd())
905     return SelectionModel(text().length(), CURSOR_FORWARD);
906   return SelectionModel(0, CURSOR_BACKWARD);
907 }
908
909 void RenderText::SetSelectionModel(const SelectionModel& model) {
910   DCHECK_LE(model.selection().GetMax(), text().length());
911   selection_model_ = model;
912   cached_bounds_and_offset_valid_ = false;
913 }
914
915 const base::string16& RenderText::GetLayoutText() const {
916   return layout_text_;
917 }
918
919 const BreakList<size_t>& RenderText::GetLineBreaks() {
920   if (line_breaks_.max() != 0)
921     return line_breaks_;
922
923   const base::string16& layout_text = GetLayoutText();
924   const size_t text_length = layout_text.length();
925   line_breaks_.SetValue(0);
926   line_breaks_.SetMax(text_length);
927   base::i18n::BreakIterator iter(layout_text,
928                                  base::i18n::BreakIterator::BREAK_LINE);
929   const bool success = iter.Init();
930   DCHECK(success);
931   if (success) {
932     do {
933       line_breaks_.ApplyValue(iter.pos(), Range(iter.pos(), text_length));
934     } while (iter.Advance());
935   }
936   return line_breaks_;
937 }
938
939 void RenderText::ApplyCompositionAndSelectionStyles() {
940   // Save the underline and color breaks to undo the temporary styles later.
941   DCHECK(!composition_and_selection_styles_applied_);
942   saved_colors_ = colors_;
943   saved_underlines_ = styles_[UNDERLINE];
944
945   // Apply an underline to the composition range in |underlines|.
946   if (composition_range_.IsValid() && !composition_range_.is_empty())
947     styles_[UNDERLINE].ApplyValue(true, composition_range_);
948
949   // Apply the selected text color to the [un-reversed] selection range.
950   if (!selection().is_empty() && focused()) {
951     const Range range(selection().GetMin(), selection().GetMax());
952     colors_.ApplyValue(selection_color_, range);
953   }
954   composition_and_selection_styles_applied_ = true;
955 }
956
957 void RenderText::UndoCompositionAndSelectionStyles() {
958   // Restore the underline and color breaks to undo the temporary styles.
959   DCHECK(composition_and_selection_styles_applied_);
960   colors_ = saved_colors_;
961   styles_[UNDERLINE] = saved_underlines_;
962   composition_and_selection_styles_applied_ = false;
963 }
964
965 Vector2d RenderText::GetLineOffset(size_t line_number) {
966   Vector2d offset = display_rect().OffsetFromOrigin();
967   // TODO(ckocagil): Apply the display offset for multiline scrolling.
968   if (!multiline())
969     offset.Add(GetUpdatedDisplayOffset());
970   else
971     offset.Add(Vector2d(0, lines_[line_number].preceding_heights));
972   offset.Add(GetAlignmentOffset(line_number));
973   return offset;
974 }
975
976 Point RenderText::ToTextPoint(const Point& point) {
977   return point - GetLineOffset(0);
978   // TODO(ckocagil): Convert multiline view space points to text space.
979 }
980
981 Point RenderText::ToViewPoint(const Point& point) {
982   if (!multiline())
983     return point + GetLineOffset(0);
984
985   // TODO(ckocagil): Traverse individual line segments for RTL support.
986   DCHECK(!lines_.empty());
987   int x = point.x();
988   size_t line = 0;
989   for (; line < lines_.size() && x > lines_[line].size.width(); ++line)
990     x -= lines_[line].size.width();
991   return Point(x, point.y()) + GetLineOffset(line);
992 }
993
994 std::vector<Rect> RenderText::TextBoundsToViewBounds(const Range& x) {
995   std::vector<Rect> rects;
996
997   if (!multiline()) {
998     rects.push_back(Rect(ToViewPoint(Point(x.GetMin(), 0)),
999                          Size(x.length(), GetStringSize().height())));
1000     return rects;
1001   }
1002
1003   EnsureLayout();
1004
1005   // Each line segment keeps its position in text coordinates. Traverse all line
1006   // segments and if the segment intersects with the given range, add the view
1007   // rect corresponding to the intersection to |rects|.
1008   for (size_t line = 0; line < lines_.size(); ++line) {
1009     int line_x = 0;
1010     const Vector2d offset = GetLineOffset(line);
1011     for (size_t i = 0; i < lines_[line].segments.size(); ++i) {
1012       const internal::LineSegment* segment = &lines_[line].segments[i];
1013       const Range intersection = segment->x_range.Intersect(x);
1014       if (!intersection.is_empty()) {
1015         Rect rect(line_x + intersection.start() - segment->x_range.start(),
1016                   0, intersection.length(), lines_[line].size.height());
1017         rects.push_back(rect + offset);
1018       }
1019       line_x += segment->x_range.length();
1020     }
1021   }
1022
1023   return rects;
1024 }
1025
1026 Vector2d RenderText::GetAlignmentOffset(size_t line_number) {
1027   // TODO(ckocagil): Enable |lines_| usage in other platforms.
1028 #if defined(OS_WIN)
1029   DCHECK_LT(line_number, lines_.size());
1030 #endif
1031   Vector2d offset;
1032   if (horizontal_alignment_ != ALIGN_LEFT) {
1033 #if defined(OS_WIN)
1034     const int width = lines_[line_number].size.width() +
1035         (cursor_enabled_ ? 1 : 0);
1036 #else
1037     const int width = GetContentWidth();
1038 #endif
1039     offset.set_x(display_rect().width() - width);
1040     if (horizontal_alignment_ == ALIGN_CENTER)
1041       offset.set_x(offset.x() / 2);
1042   }
1043
1044   // Vertically center the text.
1045   if (multiline_) {
1046     const int text_height = lines_.back().preceding_heights +
1047         lines_.back().size.height();
1048     offset.set_y((display_rect_.height() - text_height) / 2);
1049   } else {
1050     offset.set_y(GetBaseline() - GetLayoutTextBaseline());
1051   }
1052
1053   return offset;
1054 }
1055
1056 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer* renderer) {
1057   if (multiline() || (!fade_head() && !fade_tail()))
1058     return;
1059
1060   const int display_width = display_rect().width();
1061
1062   // If the text fits as-is, no need to fade.
1063   if (GetStringSize().width() <= display_width)
1064     return;
1065
1066   int gradient_width = CalculateFadeGradientWidth(font_list(), display_width);
1067   if (gradient_width == 0)
1068     return;
1069
1070   bool fade_left = fade_head();
1071   bool fade_right = fade_tail();
1072   // Under RTL, |fade_right| == |fade_head|.
1073   // TODO(asvitkine): This is currently not based on GetTextDirection() because
1074   //                  RenderTextWin does not return a direction that's based on
1075   //                  the text content.
1076   if (horizontal_alignment_ == ALIGN_RIGHT)
1077     std::swap(fade_left, fade_right);
1078
1079   Rect solid_part = display_rect();
1080   Rect left_part;
1081   Rect right_part;
1082   if (fade_left) {
1083     left_part = solid_part;
1084     left_part.Inset(0, 0, solid_part.width() - gradient_width, 0);
1085     solid_part.Inset(gradient_width, 0, 0, 0);
1086   }
1087   if (fade_right) {
1088     right_part = solid_part;
1089     right_part.Inset(solid_part.width() - gradient_width, 0, 0, 0);
1090     solid_part.Inset(0, 0, gradient_width, 0);
1091   }
1092
1093   Rect text_rect = display_rect();
1094   text_rect.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1095
1096   // TODO(msw): Use the actual text colors corresponding to each faded part.
1097   skia::RefPtr<SkShader> shader = CreateFadeShader(
1098       text_rect, left_part, right_part, colors_.breaks().front().second);
1099   if (shader)
1100     renderer->SetShader(shader.get(), display_rect());
1101 }
1102
1103 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer* renderer) {
1104   skia::RefPtr<SkDrawLooper> looper = CreateShadowDrawLooper(text_shadows_);
1105   renderer->SetDrawLooper(looper.get());
1106 }
1107
1108 // static
1109 bool RenderText::RangeContainsCaret(const Range& range,
1110                                     size_t caret_pos,
1111                                     LogicalCursorDirection caret_affinity) {
1112   // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1113   size_t adjacent = (caret_affinity == CURSOR_BACKWARD) ?
1114       caret_pos - 1 : caret_pos + 1;
1115   return range.Contains(Range(caret_pos, adjacent));
1116 }
1117
1118 void RenderText::MoveCursorTo(size_t position, bool select) {
1119   size_t cursor = std::min(position, text().length());
1120   if (IsValidCursorIndex(cursor))
1121     SetSelectionModel(SelectionModel(
1122         Range(select ? selection().start() : cursor, cursor),
1123         (cursor == 0) ? CURSOR_FORWARD : CURSOR_BACKWARD));
1124 }
1125
1126 void RenderText::UpdateLayoutText() {
1127   layout_text_.clear();
1128   line_breaks_.SetMax(0);
1129
1130   if (obscured_) {
1131     size_t obscured_text_length =
1132         static_cast<size_t>(gfx::UTF16IndexToOffset(text_, 0, text_.length()));
1133     layout_text_.assign(obscured_text_length, kPasswordReplacementChar);
1134
1135     if (obscured_reveal_index_ >= 0 &&
1136         obscured_reveal_index_ < static_cast<int>(text_.length())) {
1137       // Gets the index range in |text_| to be revealed.
1138       size_t start = obscured_reveal_index_;
1139       U16_SET_CP_START(text_.data(), 0, start);
1140       size_t end = start;
1141       UChar32 unused_char;
1142       U16_NEXT(text_.data(), end, text_.length(), unused_char);
1143
1144       // Gets the index in |layout_text_| to be replaced.
1145       const size_t cp_start =
1146           static_cast<size_t>(gfx::UTF16IndexToOffset(text_, 0, start));
1147       if (layout_text_.length() > cp_start)
1148         layout_text_.replace(cp_start, 1, text_.substr(start, end - start));
1149     }
1150   } else {
1151     layout_text_ = text_;
1152   }
1153
1154   const base::string16& text = layout_text_;
1155   if (truncate_length_ > 0 && truncate_length_ < text.length()) {
1156     // Truncate the text at a valid character break and append an ellipsis.
1157     icu::StringCharacterIterator iter(text.c_str());
1158     iter.setIndex32(truncate_length_ - 1);
1159     layout_text_.assign(text.substr(0, iter.getIndex()) + gfx::kEllipsisUTF16);
1160   }
1161
1162   if (elide_behavior_ != NO_ELIDE && display_rect_.width() > 0 &&
1163       !layout_text_.empty() && GetContentWidth() > display_rect_.width()) {
1164     // This doesn't trim styles so ellipsis may get rendered as a different
1165     // style than the preceding text. See crbug.com/327850.
1166     layout_text_.assign(ElideText(layout_text_));
1167   }
1168
1169   ResetLayout();
1170 }
1171
1172 // TODO(skanuj): Fix code duplication with ElideText in ui/gfx/text_elider.cc
1173 // See crbug.com/327846
1174 base::string16 RenderText::ElideText(const base::string16& text) {
1175   const bool insert_ellipsis = (elide_behavior_ != TRUNCATE_AT_END);
1176   // Create a RenderText copy with attributes that affect the rendering width.
1177   scoped_ptr<RenderText> render_text(CreateInstance());
1178   render_text->SetFontList(font_list_);
1179   render_text->SetDirectionalityMode(directionality_mode_);
1180   render_text->SetCursorEnabled(cursor_enabled_);
1181
1182   render_text->styles_ = styles_;
1183   render_text->colors_ = colors_;
1184   render_text->SetText(text);
1185   const int current_text_pixel_width = render_text->GetContentWidth();
1186
1187   const base::string16 ellipsis = base::string16(gfx::kEllipsisUTF16);
1188   const bool elide_in_middle = false;
1189   const bool elide_at_beginning = false;
1190   StringSlicer slicer(text, ellipsis, elide_in_middle, elide_at_beginning);
1191
1192   // Pango will return 0 width for absurdly long strings. Cut the string in
1193   // half and try again.
1194   // This is caused by an int overflow in Pango (specifically, in
1195   // pango_glyph_string_extents_range). It's actually more subtle than just
1196   // returning 0, since on super absurdly long strings, the int can wrap and
1197   // return positive numbers again. Detecting that is probably not worth it
1198   // (eliding way too much from a ridiculous string is probably still
1199   // ridiculous), but we should check other widths for bogus values as well.
1200   if (current_text_pixel_width <= 0 && !text.empty())
1201     return ElideText(slicer.CutString(text.length() / 2, insert_ellipsis));
1202
1203   if (current_text_pixel_width <= display_rect_.width())
1204     return text;
1205
1206   render_text->SetText(base::string16());
1207   render_text->SetText(ellipsis);
1208   const int ellipsis_width = render_text->GetContentWidth();
1209
1210   if (insert_ellipsis && (ellipsis_width >= display_rect_.width()))
1211     return base::string16();
1212
1213   // Use binary search to compute the elided text.
1214   size_t lo = 0;
1215   size_t hi = text.length() - 1;
1216   const base::i18n::TextDirection text_direction = GetTextDirection();
1217   for (size_t guess = (lo + hi) / 2; lo <= hi; guess = (lo + hi) / 2) {
1218     // Restore styles and colors. They will be truncated to size by SetText.
1219     render_text->styles_ = styles_;
1220     render_text->colors_ = colors_;
1221     base::string16 new_text = slicer.CutString(guess, false);
1222     render_text->SetText(new_text);
1223
1224     // This has to be an additional step so that the ellipsis is rendered with
1225     // same style as trailing part of the text.
1226     if (insert_ellipsis) {
1227       // When ellipsis follows text whose directionality is not the same as that
1228       // of the whole text, it will be rendered with the directionality of the
1229       // whole text. Since we want ellipsis to indicate continuation of the
1230       // preceding text, we force the directionality of ellipsis to be same as
1231       // the preceding text using LTR or RTL markers.
1232       base::i18n::TextDirection trailing_text_direction =
1233           base::i18n::GetLastStrongCharacterDirection(new_text);
1234       new_text.append(ellipsis);
1235       if (trailing_text_direction != text_direction) {
1236         if (trailing_text_direction == base::i18n::LEFT_TO_RIGHT)
1237           new_text += base::i18n::kLeftToRightMark;
1238         else
1239           new_text += base::i18n::kRightToLeftMark;
1240       }
1241       render_text->SetText(new_text);
1242     }
1243
1244     // We check the width of the whole desired string at once to ensure we
1245     // handle kerning/ligatures/etc. correctly.
1246     const int guess_width = render_text->GetContentWidth();
1247     if (guess_width == display_rect_.width())
1248       break;
1249     if (guess_width > display_rect_.width()) {
1250       hi = guess - 1;
1251       // Move back if we are on loop terminating condition, and guess is wider
1252       // than available.
1253       if (hi < lo)
1254         lo = hi;
1255     } else {
1256       lo = guess + 1;
1257     }
1258   }
1259
1260   return render_text->text();
1261 }
1262
1263 void RenderText::UpdateCachedBoundsAndOffset() {
1264   if (cached_bounds_and_offset_valid_)
1265     return;
1266
1267   // TODO(ckocagil): Add support for scrolling multiline text.
1268
1269   // First, set the valid flag true to calculate the current cursor bounds using
1270   // the stale |display_offset_|. Applying |delta_offset| at the end of this
1271   // function will set |cursor_bounds_| and |display_offset_| to correct values.
1272   cached_bounds_and_offset_valid_ = true;
1273   if (cursor_enabled())
1274     cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_);
1275
1276   // Update |display_offset_| to ensure the current cursor is visible.
1277   const int display_width = display_rect_.width();
1278   const int content_width = GetContentWidth();
1279
1280   int delta_x = 0;
1281   if (content_width <= display_width || !cursor_enabled()) {
1282     // Don't pan if the text fits in the display width or when the cursor is
1283     // disabled.
1284     delta_x = -display_offset_.x();
1285   } else if (cursor_bounds_.right() > display_rect_.right()) {
1286     // TODO(xji): when the character overflow is a RTL character, currently, if
1287     // we pan cursor at the rightmost position, the entered RTL character is not
1288     // displayed. Should pan cursor to show the last logical characters.
1289     //
1290     // Pan to show the cursor when it overflows to the right.
1291     delta_x = display_rect_.right() - cursor_bounds_.right();
1292   } else if (cursor_bounds_.x() < display_rect_.x()) {
1293     // TODO(xji): have similar problem as above when overflow character is a
1294     // LTR character.
1295     //
1296     // Pan to show the cursor when it overflows to the left.
1297     delta_x = display_rect_.x() - cursor_bounds_.x();
1298   } else if (display_offset_.x() != 0) {
1299     // Reduce the pan offset to show additional overflow text when the display
1300     // width increases.
1301     const int negate_rtl = horizontal_alignment_ == ALIGN_RIGHT ? -1 : 1;
1302     const int offset = negate_rtl * display_offset_.x();
1303     if (display_width > (content_width + offset)) {
1304       delta_x = negate_rtl * (display_width - (content_width + offset));
1305     }
1306   }
1307
1308   Vector2d delta_offset(delta_x, 0);
1309   display_offset_ += delta_offset;
1310   cursor_bounds_ += delta_offset;
1311 }
1312
1313 void RenderText::DrawSelection(Canvas* canvas) {
1314   const std::vector<Rect> sel = GetSubstringBounds(selection());
1315   for (std::vector<Rect>::const_iterator i = sel.begin(); i < sel.end(); ++i)
1316     canvas->FillRect(*i, selection_background_focused_color_);
1317 }
1318
1319 }  // namespace gfx