Upstream version 9.38.198.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/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"
29
30 namespace gfx {
31
32 namespace {
33
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 = '*';
38
39 // Default color used for the text and cursor.
40 const SkColor kDefaultColor = SK_ColorBLACK;
41
42 // Default color used for drawing selection background.
43 const SkColor kDefaultSelectionBackgroundColor = SK_ColorGRAY;
44
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);
53
54 // Invalid value of baseline.  Assigning this value to |baseline_| causes
55 // re-calculation of baseline.
56 const int kInvalidBaseline = INT_MAX;
57
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));
79 }
80
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);
87 }
88
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));
99 }
100
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);
117   }
118   positions->push_back(p0);
119   colors->push_back(c0);
120   positions->push_back(p1);
121   colors->push_back(c1);
122 }
123
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;
134
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());
142
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());
147   }
148
149   SkPoint points[2];
150   points[0].iset(text_rect.x(), text_rect.y());
151   points[1].iset(text_rect.right(), text_rect.y());
152
153   return skia::AdoptRef(
154       SkGradientShader::CreateLinear(&points[0], &colors[0], &positions[0],
155                                      colors.size(), SkShader::kClamp_TileMode));
156 }
157
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;
167   }
168   return SkPaint::kNo_Hinting;
169 }
170
171 }  // namespace
172
173 namespace internal {
174
175 // Value of |underline_thickness_| that indicates that underline metrics have
176 // not been set explicitly.
177 const SkScalar kUnderlineMetricsNotSet = -1.0f;
178
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();
193 }
194
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.
199   //
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();
207   }
208 }
209
210 void SkiaTextRenderer::SetDrawLooper(SkDrawLooper* draw_looper) {
211   paint_.setLooper(draw_looper);
212 }
213
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));
222 }
223
224 void SkiaTextRenderer::SetTypeface(SkTypeface* typeface) {
225   paint_.setTypeface(typeface);
226 }
227
228 void SkiaTextRenderer::SetTextSize(SkScalar size) {
229   paint_.setTextSize(size);
230 }
231
232 void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string& family,
233                                               int style) {
234   DCHECK(!family.empty());
235
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());
240
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());
244   }
245 }
246
247 void SkiaTextRenderer::SetForegroundColor(SkColor foreground) {
248   paint_.setColor(foreground);
249 }
250
251 void SkiaTextRenderer::SetShader(SkShader* shader, const Rect& bounds) {
252   bounds_ = RectToSkRect(bounds);
253   paint_.setShader(shader);
254 }
255
256 void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness,
257                                            SkScalar position) {
258   underline_thickness_ = thickness;
259   underline_position_ = position;
260 }
261
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.
270     //
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.
273     //
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);
282     }
283   }
284
285   const size_t byte_length = glyph_count * sizeof(glyphs[0]);
286   canvas_skia_->drawPosText(&glyphs[0], byte_length, &pos[0], paint_);
287 }
288
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();
301   }
302 }
303
304 void SkiaTextRenderer::EndDiagonalStrike() {
305   if (diagonal_) {
306     diagonal_->Draw();
307     diagonal_.reset();
308   }
309 }
310
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);
318   }
319   canvas_skia_->drawRect(r, paint_);
320 }
321
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_);
328 }
329
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) {
337 }
338
339 SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() {
340 }
341
342 void SkiaTextRenderer::DiagonalStrike::AddPiece(int length, SkColor color) {
343   pieces_.push_back(Piece(length, color));
344   total_length_ += length;
345 }
346
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;
355
356   paint_.setAntiAlias(true);
357   paint_.setStrokeWidth(thickness);
358
359   const bool clipped = pieces_.size() > 1;
360   SkCanvas* sk_canvas = canvas_->sk_canvas();
361   int x = start_.x();
362
363   for (size_t i = 0; i < pieces_.size(); ++i) {
364     paint_.setColor(pieces_[i].second);
365
366     if (clipped) {
367       canvas_->Save();
368       sk_canvas->clipRect(RectToSkRect(
369           Rect(x, end.y() - thickness, pieces_[i].first, clip_height)));
370     }
371
372     canvas_->DrawLine(start_, end, paint_);
373
374     if (clipped)
375       canvas_->Restore();
376
377     x += pieces_[i].first;
378   }
379 }
380
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());
388 }
389
390 StyleIterator::~StyleIterator() {}
391
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;
397 }
398
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);
403 }
404
405 LineSegment::LineSegment() : run(0) {}
406
407 LineSegment::~LineSegment() {}
408
409 Line::Line() : preceding_heights(0), baseline(0) {}
410
411 Line::~Line() {}
412
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));
417 }
418
419 }  // namespace internal
420
421 RenderText::~RenderText() {
422 }
423
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;
432   }
433   return CreateNativeInstance();
434 #endif
435 }
436
437 void RenderText::SetText(const base::string16& text) {
438   DCHECK(!composition_range_.IsValid());
439   if (text_ == text)
440     return;
441   text_ = text;
442
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;
449
450   // Reset selection model. SetText should always followed by SetSelectionModel
451   // or SetCursorPosition in upper layer.
452   SetSelectionModel(SelectionModel());
453
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;
457
458   obscured_reveal_index_ = -1;
459   UpdateLayoutText();
460 }
461
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;
467   }
468 }
469
470 void RenderText::SetFontList(const FontList& font_list) {
471   font_list_ = font_list;
472   const int font_style = font_list.GetFontStyle();
473   SetStyle(BOLD, (font_style & gfx::Font::BOLD) != 0);
474   SetStyle(ITALIC, (font_style & gfx::Font::ITALIC) != 0);
475   SetStyle(UNDERLINE, (font_style & gfx::Font::UNDERLINE) != 0);
476   baseline_ = kInvalidBaseline;
477   cached_bounds_and_offset_valid_ = false;
478   ResetLayout();
479 }
480
481 void RenderText::SetCursorEnabled(bool cursor_enabled) {
482   cursor_enabled_ = cursor_enabled;
483   cached_bounds_and_offset_valid_ = false;
484 }
485
486 void RenderText::ToggleInsertMode() {
487   insert_mode_ = !insert_mode_;
488   cached_bounds_and_offset_valid_ = false;
489 }
490
491 void RenderText::SetObscured(bool obscured) {
492   if (obscured != obscured_) {
493     obscured_ = obscured;
494     obscured_reveal_index_ = -1;
495     cached_bounds_and_offset_valid_ = false;
496     UpdateLayoutText();
497   }
498 }
499
500 void RenderText::SetObscuredRevealIndex(int index) {
501   if (obscured_reveal_index_ == index)
502     return;
503
504   obscured_reveal_index_ = index;
505   cached_bounds_and_offset_valid_ = false;
506   UpdateLayoutText();
507 }
508
509 void RenderText::SetReplaceNewlineCharsWithSymbols(bool replace) {
510   replace_newline_chars_with_symbols_ = replace;
511   cached_bounds_and_offset_valid_ = false;
512   UpdateLayoutText();
513 }
514
515 void RenderText::SetMultiline(bool multiline) {
516   if (multiline != multiline_) {
517     multiline_ = multiline;
518     cached_bounds_and_offset_valid_ = false;
519     lines_.clear();
520   }
521 }
522
523 void RenderText::SetElideBehavior(ElideBehavior elide_behavior) {
524   // TODO(skanuj) : Add a test for triggering layout change.
525   if (elide_behavior_ != elide_behavior) {
526     elide_behavior_ = elide_behavior;
527     UpdateLayoutText();
528   }
529 }
530
531 void RenderText::SetDisplayRect(const Rect& r) {
532   if (r != display_rect_) {
533     display_rect_ = r;
534     baseline_ = kInvalidBaseline;
535     cached_bounds_and_offset_valid_ = false;
536     lines_.clear();
537     if (elide_behavior_ != NO_ELIDE)
538       UpdateLayoutText();
539   }
540 }
541
542 void RenderText::SetCursorPosition(size_t position) {
543   MoveCursorTo(position, false);
544 }
545
546 void RenderText::MoveCursor(BreakType break_type,
547                             VisualCursorDirection direction,
548                             bool select) {
549   SelectionModel cursor(cursor_position(), selection_model_.caret_affinity());
550   // Cancelling a selection moves to the edge of the selection.
551   if (break_type != LINE_BREAK && !selection().is_empty() && !select) {
552     SelectionModel selection_start = GetSelectionModelForSelectionStart();
553     int start_x = GetCursorBounds(selection_start, true).x();
554     int cursor_x = GetCursorBounds(cursor, true).x();
555     // Use the selection start if it is left (when |direction| is CURSOR_LEFT)
556     // or right (when |direction| is CURSOR_RIGHT) of the selection end.
557     if (direction == CURSOR_RIGHT ? start_x > cursor_x : start_x < cursor_x)
558       cursor = selection_start;
559     // Use the nearest word boundary in the proper |direction| for word breaks.
560     if (break_type == WORD_BREAK)
561       cursor = GetAdjacentSelectionModel(cursor, break_type, direction);
562     // Use an adjacent selection model if the cursor is not at a valid position.
563     if (!IsValidCursorIndex(cursor.caret_pos()))
564       cursor = GetAdjacentSelectionModel(cursor, CHARACTER_BREAK, direction);
565   } else {
566     cursor = GetAdjacentSelectionModel(cursor, break_type, direction);
567   }
568   if (select)
569     cursor.set_selection_start(selection().start());
570   MoveCursorTo(cursor);
571 }
572
573 bool RenderText::MoveCursorTo(const SelectionModel& model) {
574   // Enforce valid selection model components.
575   size_t text_length = text().length();
576   Range range(std::min(model.selection().start(), text_length),
577               std::min(model.caret_pos(), text_length));
578   // The current model only supports caret positions at valid cursor indices.
579   if (!IsValidCursorIndex(range.start()) || !IsValidCursorIndex(range.end()))
580     return false;
581   SelectionModel sel(range, model.caret_affinity());
582   bool changed = sel != selection_model_;
583   SetSelectionModel(sel);
584   return changed;
585 }
586
587 bool RenderText::SelectRange(const Range& range) {
588   Range sel(std::min(range.start(), text().length()),
589             std::min(range.end(), text().length()));
590   // Allow selection bounds at valid indicies amid multi-character graphemes.
591   if (!IsValidLogicalIndex(sel.start()) || !IsValidLogicalIndex(sel.end()))
592     return false;
593   LogicalCursorDirection affinity =
594       (sel.is_reversed() || sel.is_empty()) ? CURSOR_FORWARD : CURSOR_BACKWARD;
595   SetSelectionModel(SelectionModel(sel, affinity));
596   return true;
597 }
598
599 bool RenderText::IsPointInSelection(const Point& point) {
600   if (selection().is_empty())
601     return false;
602   SelectionModel cursor = FindCursorPosition(point);
603   return RangeContainsCaret(
604       selection(), cursor.caret_pos(), cursor.caret_affinity());
605 }
606
607 void RenderText::ClearSelection() {
608   SetSelectionModel(SelectionModel(cursor_position(),
609                                    selection_model_.caret_affinity()));
610 }
611
612 void RenderText::SelectAll(bool reversed) {
613   const size_t length = text().length();
614   const Range all = reversed ? Range(length, 0) : Range(0, length);
615   const bool success = SelectRange(all);
616   DCHECK(success);
617 }
618
619 void RenderText::SelectWord() {
620   if (obscured_) {
621     SelectAll(false);
622     return;
623   }
624
625   size_t selection_max = selection().GetMax();
626
627   base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
628   bool success = iter.Init();
629   DCHECK(success);
630   if (!success)
631     return;
632
633   size_t selection_min = selection().GetMin();
634   if (selection_min == text().length() && selection_min != 0)
635     --selection_min;
636
637   for (; selection_min != 0; --selection_min) {
638     if (iter.IsStartOfWord(selection_min) ||
639         iter.IsEndOfWord(selection_min))
640       break;
641   }
642
643   if (selection_min == selection_max && selection_max != text().length())
644     ++selection_max;
645
646   for (; selection_max < text().length(); ++selection_max)
647     if (iter.IsEndOfWord(selection_max) || iter.IsStartOfWord(selection_max))
648       break;
649
650   const bool reversed = selection().is_reversed();
651   MoveCursorTo(reversed ? selection_max : selection_min, false);
652   MoveCursorTo(reversed ? selection_min : selection_max, true);
653 }
654
655 const Range& RenderText::GetCompositionRange() const {
656   return composition_range_;
657 }
658
659 void RenderText::SetCompositionRange(const Range& composition_range) {
660   CHECK(!composition_range.IsValid() ||
661         Range(0, text_.length()).Contains(composition_range));
662   composition_range_.set_end(composition_range.end());
663   composition_range_.set_start(composition_range.start());
664   ResetLayout();
665 }
666
667 void RenderText::SetColor(SkColor value) {
668   colors_.SetValue(value);
669
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
675 }
676
677 void RenderText::ApplyColor(SkColor value, const Range& range) {
678   colors_.ApplyValue(value, range);
679
680 #if defined(OS_WIN)
681   // TODO(msw): Windows applies colors and decorations in the layout process.
682   cached_bounds_and_offset_valid_ = false;
683   ResetLayout();
684 #endif
685 }
686
687 void RenderText::SetStyle(TextStyle style, bool value) {
688   styles_[style].SetValue(value);
689
690   // Only invalidate the layout on font changes; not for colors or decorations.
691   bool invalidate = (style == BOLD) || (style == ITALIC);
692 #if defined(OS_WIN)
693   // TODO(msw): Windows applies colors and decorations in the layout process.
694   invalidate = true;
695 #endif
696   if (invalidate) {
697     cached_bounds_and_offset_valid_ = false;
698     ResetLayout();
699   }
700 }
701
702 void RenderText::ApplyStyle(TextStyle style, bool value, const Range& range) {
703   styles_[style].ApplyValue(value, range);
704
705   // Only invalidate the layout on font changes; not for colors or decorations.
706   bool invalidate = (style == BOLD) || (style == ITALIC);
707 #if defined(OS_WIN)
708   // TODO(msw): Windows applies colors and decorations in the layout process.
709   invalidate = true;
710 #endif
711   if (invalidate) {
712     cached_bounds_and_offset_valid_ = false;
713     ResetLayout();
714   }
715 }
716
717 bool RenderText::GetStyle(TextStyle style) const {
718   return (styles_[style].breaks().size() == 1) &&
719       styles_[style].breaks().front().second;
720 }
721
722 void RenderText::SetDirectionalityMode(DirectionalityMode mode) {
723   if (mode == directionality_mode_)
724     return;
725
726   directionality_mode_ = mode;
727   text_direction_ = base::i18n::UNKNOWN_DIRECTION;
728   cached_bounds_and_offset_valid_ = false;
729   ResetLayout();
730 }
731
732 base::i18n::TextDirection RenderText::GetTextDirection() {
733   if (text_direction_ == base::i18n::UNKNOWN_DIRECTION) {
734     switch (directionality_mode_) {
735       case DIRECTIONALITY_FROM_TEXT:
736         // Derive the direction from the display text, which differs from text()
737         // in the case of obscured (password) textfields.
738         text_direction_ =
739             base::i18n::GetFirstStrongCharacterDirection(GetLayoutText());
740         break;
741       case DIRECTIONALITY_FROM_UI:
742         text_direction_ = base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT :
743                                                 base::i18n::LEFT_TO_RIGHT;
744         break;
745       case DIRECTIONALITY_FORCE_LTR:
746         text_direction_ = base::i18n::LEFT_TO_RIGHT;
747         break;
748       case DIRECTIONALITY_FORCE_RTL:
749         text_direction_ = base::i18n::RIGHT_TO_LEFT;
750         break;
751       default:
752         NOTREACHED();
753     }
754   }
755
756   return text_direction_;
757 }
758
759 VisualCursorDirection RenderText::GetVisualDirectionOfLogicalEnd() {
760   return GetTextDirection() == base::i18n::LEFT_TO_RIGHT ?
761       CURSOR_RIGHT : CURSOR_LEFT;
762 }
763
764 SizeF RenderText::GetStringSizeF() {
765   const Size size = GetStringSize();
766   return SizeF(size.width(), size.height());
767 }
768
769 float RenderText::GetContentWidth() {
770   return GetStringSizeF().width() + (cursor_enabled_ ? 1 : 0);
771 }
772
773 int RenderText::GetBaseline() {
774   if (baseline_ == kInvalidBaseline)
775     baseline_ = DetermineBaselineCenteringText(display_rect(), font_list());
776   DCHECK_NE(kInvalidBaseline, baseline_);
777   return baseline_;
778 }
779
780 void RenderText::Draw(Canvas* canvas) {
781   EnsureLayout();
782
783   if (clip_to_display_rect()) {
784     Rect clip_rect(display_rect());
785     clip_rect.Inset(ShadowValue::GetMargin(shadows_));
786
787     canvas->Save();
788     canvas->ClipRect(clip_rect);
789   }
790
791   if (!text().empty() && focused())
792     DrawSelection(canvas);
793
794   if (cursor_enabled() && cursor_visible() && focused())
795     DrawCursor(canvas, selection_model_);
796
797   if (!text().empty())
798     DrawVisualText(canvas);
799
800   if (clip_to_display_rect())
801     canvas->Restore();
802 }
803
804 void RenderText::DrawCursor(Canvas* canvas, const SelectionModel& position) {
805   // Paint cursor. Replace cursor is drawn as rectangle for now.
806   // TODO(msw): Draw a better cursor with a better indication of association.
807   canvas->FillRect(GetCursorBounds(position, true), cursor_color_);
808 }
809
810 bool RenderText::IsValidLogicalIndex(size_t index) {
811   // Check that the index is at a valid code point (not mid-surrgate-pair) and
812   // that it's not truncated from the layout text (its glyph may be shown).
813   //
814   // Indices within truncated text are disallowed so users can easily interact
815   // with the underlying truncated text using the ellipsis as a proxy. This lets
816   // users select all text, select the truncated text, and transition from the
817   // last rendered glyph to the end of the text without getting invisible cursor
818   // positions nor needing unbounded arrow key presses to traverse the ellipsis.
819   return index == 0 || index == text().length() ||
820       (index < text().length() &&
821        (truncate_length_ == 0 || index < truncate_length_) &&
822        IsValidCodePointIndex(text(), index));
823 }
824
825 Rect RenderText::GetCursorBounds(const SelectionModel& caret,
826                                  bool insert_mode) {
827   // TODO(ckocagil): Support multiline. This function should return the height
828   //                 of the line the cursor is on. |GetStringSize()| now returns
829   //                 the multiline size, eliminate its use here.
830
831   EnsureLayout();
832   size_t caret_pos = caret.caret_pos();
833   DCHECK(IsValidLogicalIndex(caret_pos));
834   // In overtype mode, ignore the affinity and always indicate that we will
835   // overtype the next character.
836   LogicalCursorDirection caret_affinity =
837       insert_mode ? caret.caret_affinity() : CURSOR_FORWARD;
838   int x = 0, width = 1;
839   Size size = GetStringSize();
840   if (caret_pos == (caret_affinity == CURSOR_BACKWARD ? 0 : text().length())) {
841     // The caret is attached to the boundary. Always return a 1-dip width caret,
842     // since there is nothing to overtype.
843     if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT) == (caret_pos == 0))
844       x = size.width();
845   } else {
846     size_t grapheme_start = (caret_affinity == CURSOR_FORWARD) ?
847         caret_pos : IndexOfAdjacentGrapheme(caret_pos, CURSOR_BACKWARD);
848     Range xspan(GetGlyphBounds(grapheme_start));
849     if (insert_mode) {
850       x = (caret_affinity == CURSOR_BACKWARD) ? xspan.end() : xspan.start();
851     } else {  // overtype mode
852       x = xspan.GetMin();
853       width = xspan.length();
854     }
855   }
856   return Rect(ToViewPoint(Point(x, 0)), Size(width, size.height()));
857 }
858
859 const Rect& RenderText::GetUpdatedCursorBounds() {
860   UpdateCachedBoundsAndOffset();
861   return cursor_bounds_;
862 }
863
864 size_t RenderText::IndexOfAdjacentGrapheme(size_t index,
865                                            LogicalCursorDirection direction) {
866   if (index > text().length())
867     return text().length();
868
869   EnsureLayout();
870
871   if (direction == CURSOR_FORWARD) {
872     while (index < text().length()) {
873       index++;
874       if (IsValidCursorIndex(index))
875         return index;
876     }
877     return text().length();
878   }
879
880   while (index > 0) {
881     index--;
882     if (IsValidCursorIndex(index))
883       return index;
884   }
885   return 0;
886 }
887
888 SelectionModel RenderText::GetSelectionModelForSelectionStart() {
889   const Range& sel = selection();
890   if (sel.is_empty())
891     return selection_model_;
892   return SelectionModel(sel.start(),
893                         sel.is_reversed() ? CURSOR_BACKWARD : CURSOR_FORWARD);
894 }
895
896 const Vector2d& RenderText::GetUpdatedDisplayOffset() {
897   UpdateCachedBoundsAndOffset();
898   return display_offset_;
899 }
900
901 void RenderText::SetDisplayOffset(int horizontal_offset) {
902   const int extra_content = GetContentWidth() - display_rect_.width();
903   const int cursor_width = cursor_enabled_ ? 1 : 0;
904
905   int min_offset = 0;
906   int max_offset = 0;
907   if (extra_content > 0) {
908     switch (GetCurrentHorizontalAlignment()) {
909       case ALIGN_LEFT:
910         min_offset = -extra_content;
911         break;
912       case ALIGN_RIGHT:
913         max_offset = extra_content;
914         break;
915       case ALIGN_CENTER:
916         // The extra space reserved for cursor at the end of the text is ignored
917         // when centering text. So, to calculate the valid range for offset, we
918         // exclude that extra space, calculate the range, and add it back to the
919         // range (if cursor is enabled).
920         min_offset = -(extra_content - cursor_width + 1) / 2 - cursor_width;
921         max_offset = (extra_content - cursor_width) / 2;
922         break;
923       default:
924         break;
925     }
926   }
927   if (horizontal_offset < min_offset)
928     horizontal_offset = min_offset;
929   else if (horizontal_offset > max_offset)
930     horizontal_offset = max_offset;
931
932   cached_bounds_and_offset_valid_ = true;
933   display_offset_.set_x(horizontal_offset);
934   cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_);
935 }
936
937 RenderText::RenderText()
938     : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT : ALIGN_LEFT),
939       directionality_mode_(DIRECTIONALITY_FROM_TEXT),
940       text_direction_(base::i18n::UNKNOWN_DIRECTION),
941       cursor_enabled_(true),
942       cursor_visible_(false),
943       insert_mode_(true),
944       cursor_color_(kDefaultColor),
945       selection_color_(kDefaultColor),
946       selection_background_focused_color_(kDefaultSelectionBackgroundColor),
947       focused_(false),
948       composition_range_(Range::InvalidRange()),
949       colors_(kDefaultColor),
950       styles_(NUM_TEXT_STYLES),
951       composition_and_selection_styles_applied_(false),
952       obscured_(false),
953       obscured_reveal_index_(-1),
954       truncate_length_(0),
955       elide_behavior_(NO_ELIDE),
956       replace_newline_chars_with_symbols_(true),
957       multiline_(false),
958       background_is_transparent_(false),
959       clip_to_display_rect_(true),
960       baseline_(kInvalidBaseline),
961       cached_bounds_and_offset_valid_(false) {
962 }
963
964 SelectionModel RenderText::GetAdjacentSelectionModel(
965     const SelectionModel& current,
966     BreakType break_type,
967     VisualCursorDirection direction) {
968   EnsureLayout();
969
970   if (break_type == LINE_BREAK || text().empty())
971     return EdgeSelectionModel(direction);
972   if (break_type == CHARACTER_BREAK)
973     return AdjacentCharSelectionModel(current, direction);
974   DCHECK(break_type == WORD_BREAK);
975   return AdjacentWordSelectionModel(current, direction);
976 }
977
978 SelectionModel RenderText::EdgeSelectionModel(
979     VisualCursorDirection direction) {
980   if (direction == GetVisualDirectionOfLogicalEnd())
981     return SelectionModel(text().length(), CURSOR_FORWARD);
982   return SelectionModel(0, CURSOR_BACKWARD);
983 }
984
985 void RenderText::SetSelectionModel(const SelectionModel& model) {
986   DCHECK_LE(model.selection().GetMax(), text().length());
987   selection_model_ = model;
988   cached_bounds_and_offset_valid_ = false;
989 }
990
991 const base::string16& RenderText::GetLayoutText() const {
992   return layout_text_;
993 }
994
995 const BreakList<size_t>& RenderText::GetLineBreaks() {
996   if (line_breaks_.max() != 0)
997     return line_breaks_;
998
999   const base::string16& layout_text = GetLayoutText();
1000   const size_t text_length = layout_text.length();
1001   line_breaks_.SetValue(0);
1002   line_breaks_.SetMax(text_length);
1003   base::i18n::BreakIterator iter(layout_text,
1004                                  base::i18n::BreakIterator::BREAK_LINE);
1005   const bool success = iter.Init();
1006   DCHECK(success);
1007   if (success) {
1008     do {
1009       line_breaks_.ApplyValue(iter.pos(), Range(iter.pos(), text_length));
1010     } while (iter.Advance());
1011   }
1012   return line_breaks_;
1013 }
1014
1015 void RenderText::ApplyCompositionAndSelectionStyles() {
1016   // Save the underline and color breaks to undo the temporary styles later.
1017   DCHECK(!composition_and_selection_styles_applied_);
1018   saved_colors_ = colors_;
1019   saved_underlines_ = styles_[UNDERLINE];
1020
1021   // Apply an underline to the composition range in |underlines|.
1022   if (composition_range_.IsValid() && !composition_range_.is_empty())
1023     styles_[UNDERLINE].ApplyValue(true, composition_range_);
1024
1025   // Apply the selected text color to the [un-reversed] selection range.
1026   if (!selection().is_empty() && focused()) {
1027     const Range range(selection().GetMin(), selection().GetMax());
1028     colors_.ApplyValue(selection_color_, range);
1029   }
1030   composition_and_selection_styles_applied_ = true;
1031 }
1032
1033 void RenderText::UndoCompositionAndSelectionStyles() {
1034   // Restore the underline and color breaks to undo the temporary styles.
1035   DCHECK(composition_and_selection_styles_applied_);
1036   colors_ = saved_colors_;
1037   styles_[UNDERLINE] = saved_underlines_;
1038   composition_and_selection_styles_applied_ = false;
1039 }
1040
1041 Vector2d RenderText::GetLineOffset(size_t line_number) {
1042   Vector2d offset = display_rect().OffsetFromOrigin();
1043   // TODO(ckocagil): Apply the display offset for multiline scrolling.
1044   if (!multiline())
1045     offset.Add(GetUpdatedDisplayOffset());
1046   else
1047     offset.Add(Vector2d(0, lines_[line_number].preceding_heights));
1048   offset.Add(GetAlignmentOffset(line_number));
1049   return offset;
1050 }
1051
1052 Point RenderText::ToTextPoint(const Point& point) {
1053   return point - GetLineOffset(0);
1054   // TODO(ckocagil): Convert multiline view space points to text space.
1055 }
1056
1057 Point RenderText::ToViewPoint(const Point& point) {
1058   if (!multiline())
1059     return point + GetLineOffset(0);
1060
1061   // TODO(ckocagil): Traverse individual line segments for RTL support.
1062   DCHECK(!lines_.empty());
1063   int x = point.x();
1064   size_t line = 0;
1065   for (; line < lines_.size() && x > lines_[line].size.width(); ++line)
1066     x -= lines_[line].size.width();
1067   return Point(x, point.y()) + GetLineOffset(line);
1068 }
1069
1070 std::vector<Rect> RenderText::TextBoundsToViewBounds(const Range& x) {
1071   std::vector<Rect> rects;
1072
1073   if (!multiline()) {
1074     rects.push_back(Rect(ToViewPoint(Point(x.GetMin(), 0)),
1075                          Size(x.length(), GetStringSize().height())));
1076     return rects;
1077   }
1078
1079   EnsureLayout();
1080
1081   // Each line segment keeps its position in text coordinates. Traverse all line
1082   // segments and if the segment intersects with the given range, add the view
1083   // rect corresponding to the intersection to |rects|.
1084   for (size_t line = 0; line < lines_.size(); ++line) {
1085     int line_x = 0;
1086     const Vector2d offset = GetLineOffset(line);
1087     for (size_t i = 0; i < lines_[line].segments.size(); ++i) {
1088       const internal::LineSegment* segment = &lines_[line].segments[i];
1089       const Range intersection = segment->x_range.Intersect(x);
1090       if (!intersection.is_empty()) {
1091         Rect rect(line_x + intersection.start() - segment->x_range.start(),
1092                   0, intersection.length(), lines_[line].size.height());
1093         rects.push_back(rect + offset);
1094       }
1095       line_x += segment->x_range.length();
1096     }
1097   }
1098
1099   return rects;
1100 }
1101
1102 HorizontalAlignment RenderText::GetCurrentHorizontalAlignment() {
1103   if (horizontal_alignment_ != ALIGN_TO_HEAD)
1104     return horizontal_alignment_;
1105   return GetTextDirection() == base::i18n::RIGHT_TO_LEFT ? ALIGN_RIGHT
1106                                                          : ALIGN_LEFT;
1107 }
1108
1109 Vector2d RenderText::GetAlignmentOffset(size_t line_number) {
1110   // TODO(ckocagil): Enable |lines_| usage in other platforms.
1111 #if defined(OS_WIN)
1112   DCHECK_LT(line_number, lines_.size());
1113 #endif
1114   Vector2d offset;
1115   HorizontalAlignment horizontal_alignment = GetCurrentHorizontalAlignment();
1116   if (horizontal_alignment != ALIGN_LEFT) {
1117 #if defined(OS_WIN)
1118     const int width = lines_[line_number].size.width() +
1119         (cursor_enabled_ ? 1 : 0);
1120 #else
1121     const int width = GetContentWidth();
1122 #endif
1123     offset.set_x(display_rect().width() - width);
1124     // Put any extra margin pixel on the left to match legacy behavior.
1125     if (horizontal_alignment == ALIGN_CENTER)
1126       offset.set_x((offset.x() + 1) / 2);
1127   }
1128
1129   // Vertically center the text.
1130   if (multiline_) {
1131     const int text_height = lines_.back().preceding_heights +
1132         lines_.back().size.height();
1133     offset.set_y((display_rect_.height() - text_height) / 2);
1134   } else {
1135     offset.set_y(GetBaseline() - GetLayoutTextBaseline());
1136   }
1137
1138   return offset;
1139 }
1140
1141 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer* renderer) {
1142   const int width = display_rect().width();
1143   if (multiline() || elide_behavior_ != FADE_TAIL || GetContentWidth() <= width)
1144     return;
1145
1146   const int gradient_width = CalculateFadeGradientWidth(font_list(), width);
1147   if (gradient_width == 0)
1148     return;
1149
1150   HorizontalAlignment horizontal_alignment = GetCurrentHorizontalAlignment();
1151   Rect solid_part = display_rect();
1152   Rect left_part;
1153   Rect right_part;
1154   if (horizontal_alignment != ALIGN_LEFT) {
1155     left_part = solid_part;
1156     left_part.Inset(0, 0, solid_part.width() - gradient_width, 0);
1157     solid_part.Inset(gradient_width, 0, 0, 0);
1158   }
1159   if (horizontal_alignment != ALIGN_RIGHT) {
1160     right_part = solid_part;
1161     right_part.Inset(solid_part.width() - gradient_width, 0, 0, 0);
1162     solid_part.Inset(0, 0, gradient_width, 0);
1163   }
1164
1165   Rect text_rect = display_rect();
1166   text_rect.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1167
1168   // TODO(msw): Use the actual text colors corresponding to each faded part.
1169   skia::RefPtr<SkShader> shader = CreateFadeShader(
1170       text_rect, left_part, right_part, colors_.breaks().front().second);
1171   if (shader)
1172     renderer->SetShader(shader.get(), display_rect());
1173 }
1174
1175 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer* renderer) {
1176   skia::RefPtr<SkDrawLooper> looper = CreateShadowDrawLooper(shadows_);
1177   renderer->SetDrawLooper(looper.get());
1178 }
1179
1180 // static
1181 bool RenderText::RangeContainsCaret(const Range& range,
1182                                     size_t caret_pos,
1183                                     LogicalCursorDirection caret_affinity) {
1184   // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1185   size_t adjacent = (caret_affinity == CURSOR_BACKWARD) ?
1186       caret_pos - 1 : caret_pos + 1;
1187   return range.Contains(Range(caret_pos, adjacent));
1188 }
1189
1190 void RenderText::MoveCursorTo(size_t position, bool select) {
1191   size_t cursor = std::min(position, text().length());
1192   if (IsValidCursorIndex(cursor))
1193     SetSelectionModel(SelectionModel(
1194         Range(select ? selection().start() : cursor, cursor),
1195         (cursor == 0) ? CURSOR_FORWARD : CURSOR_BACKWARD));
1196 }
1197
1198 void RenderText::UpdateLayoutText() {
1199   layout_text_.clear();
1200   line_breaks_.SetMax(0);
1201
1202   if (obscured_) {
1203     size_t obscured_text_length =
1204         static_cast<size_t>(UTF16IndexToOffset(text_, 0, text_.length()));
1205     layout_text_.assign(obscured_text_length, kPasswordReplacementChar);
1206
1207     if (obscured_reveal_index_ >= 0 &&
1208         obscured_reveal_index_ < static_cast<int>(text_.length())) {
1209       // Gets the index range in |text_| to be revealed.
1210       size_t start = obscured_reveal_index_;
1211       U16_SET_CP_START(text_.data(), 0, start);
1212       size_t end = start;
1213       UChar32 unused_char;
1214       U16_NEXT(text_.data(), end, text_.length(), unused_char);
1215
1216       // Gets the index in |layout_text_| to be replaced.
1217       const size_t cp_start =
1218           static_cast<size_t>(UTF16IndexToOffset(text_, 0, start));
1219       if (layout_text_.length() > cp_start)
1220         layout_text_.replace(cp_start, 1, text_.substr(start, end - start));
1221     }
1222   } else {
1223     layout_text_ = text_;
1224   }
1225
1226   const base::string16& text = layout_text_;
1227   if (truncate_length_ > 0 && truncate_length_ < text.length()) {
1228     // Truncate the text at a valid character break and append an ellipsis.
1229     icu::StringCharacterIterator iter(text.c_str());
1230     // Respect ELIDE_HEAD and ELIDE_MIDDLE preferences during truncation.
1231     if (elide_behavior_ == ELIDE_HEAD) {
1232       iter.setIndex32(text.length() - truncate_length_ + 1);
1233       layout_text_.assign(kEllipsisUTF16 + text.substr(iter.getIndex()));
1234     } else if (elide_behavior_ == ELIDE_MIDDLE) {
1235       iter.setIndex32(truncate_length_ / 2);
1236       const size_t ellipsis_start = iter.getIndex();
1237       iter.setIndex32(text.length() - (truncate_length_ / 2));
1238       const size_t ellipsis_end = iter.getIndex();
1239       DCHECK_LE(ellipsis_start, ellipsis_end);
1240       layout_text_.assign(text.substr(0, ellipsis_start) + kEllipsisUTF16 +
1241                           text.substr(ellipsis_end));
1242     } else {
1243       iter.setIndex32(truncate_length_ - 1);
1244       layout_text_.assign(text.substr(0, iter.getIndex()) + kEllipsisUTF16);
1245     }
1246   }
1247
1248   if (elide_behavior_ != NO_ELIDE && elide_behavior_ != FADE_TAIL &&
1249       !layout_text_.empty() && GetContentWidth() > display_rect_.width()) {
1250     // This doesn't trim styles so ellipsis may get rendered as a different
1251     // style than the preceding text. See crbug.com/327850.
1252     layout_text_.assign(
1253         Elide(layout_text_, display_rect_.width(), elide_behavior_));
1254   }
1255
1256   // Replace the newline character with a newline symbol in single line mode.
1257   static const base::char16 kNewline[] = { '\n', 0 };
1258   static const base::char16 kNewlineSymbol[] = { 0x2424, 0 };
1259   if (!multiline_ && replace_newline_chars_with_symbols_)
1260     base::ReplaceChars(layout_text_, kNewline, kNewlineSymbol, &layout_text_);
1261
1262   ResetLayout();
1263 }
1264
1265 base::string16 RenderText::Elide(const base::string16& text,
1266                                  float available_width,
1267                                  ElideBehavior behavior) {
1268   if (available_width <= 0 || text.empty())
1269     return base::string16();
1270   if (behavior == ELIDE_EMAIL)
1271     return ElideEmail(text, available_width);
1272
1273   // Create a RenderText copy with attributes that affect the rendering width.
1274   scoped_ptr<RenderText> render_text(CreateInstance());
1275   render_text->SetFontList(font_list_);
1276   render_text->SetDirectionalityMode(directionality_mode_);
1277   render_text->SetCursorEnabled(cursor_enabled_);
1278   render_text->set_truncate_length(truncate_length_);
1279   render_text->styles_ = styles_;
1280   render_text->colors_ = colors_;
1281   render_text->SetText(text);
1282   if (render_text->GetContentWidth() <= available_width)
1283     return text;
1284
1285   const base::string16 ellipsis = base::string16(kEllipsisUTF16);
1286   const bool insert_ellipsis = (behavior != TRUNCATE);
1287   const bool elide_in_middle = (behavior == ELIDE_MIDDLE);
1288   const bool elide_at_beginning = (behavior == ELIDE_HEAD);
1289   StringSlicer slicer(text, ellipsis, elide_in_middle, elide_at_beginning);
1290
1291   render_text->SetText(ellipsis);
1292   const float ellipsis_width = render_text->GetContentWidth();
1293
1294   if (insert_ellipsis && (ellipsis_width > available_width))
1295     return base::string16();
1296
1297   // Use binary search to compute the elided text.
1298   size_t lo = 0;
1299   size_t hi = text.length() - 1;
1300   const base::i18n::TextDirection text_direction = GetTextDirection();
1301   for (size_t guess = (lo + hi) / 2; lo <= hi; guess = (lo + hi) / 2) {
1302     // Restore styles and colors. They will be truncated to size by SetText.
1303     render_text->styles_ = styles_;
1304     render_text->colors_ = colors_;
1305     base::string16 new_text =
1306         slicer.CutString(guess, insert_ellipsis && behavior != ELIDE_TAIL);
1307     render_text->SetText(new_text);
1308
1309     // This has to be an additional step so that the ellipsis is rendered with
1310     // same style as trailing part of the text.
1311     if (insert_ellipsis && behavior == ELIDE_TAIL) {
1312       // When ellipsis follows text whose directionality is not the same as that
1313       // of the whole text, it will be rendered with the directionality of the
1314       // whole text. Since we want ellipsis to indicate continuation of the
1315       // preceding text, we force the directionality of ellipsis to be same as
1316       // the preceding text using LTR or RTL markers.
1317       base::i18n::TextDirection trailing_text_direction =
1318           base::i18n::GetLastStrongCharacterDirection(new_text);
1319       new_text.append(ellipsis);
1320       if (trailing_text_direction != text_direction) {
1321         if (trailing_text_direction == base::i18n::LEFT_TO_RIGHT)
1322           new_text += base::i18n::kLeftToRightMark;
1323         else
1324           new_text += base::i18n::kRightToLeftMark;
1325       }
1326       render_text->SetText(new_text);
1327     }
1328
1329     // We check the width of the whole desired string at once to ensure we
1330     // handle kerning/ligatures/etc. correctly.
1331     const float guess_width = render_text->GetContentWidth();
1332     if (guess_width == available_width)
1333       break;
1334     if (guess_width > available_width) {
1335       hi = guess - 1;
1336       // Move back on the loop terminating condition when the guess is too wide.
1337       if (hi < lo)
1338         lo = hi;
1339     } else {
1340       lo = guess + 1;
1341     }
1342   }
1343
1344   return render_text->text();
1345 }
1346
1347 base::string16 RenderText::ElideEmail(const base::string16& email,
1348                                       float available_width) {
1349   // The returned string will have at least one character besides the ellipsis
1350   // on either side of '@'; if that's impossible, a single ellipsis is returned.
1351   // If possible, only the username is elided. Otherwise, the domain is elided
1352   // in the middle, splitting available width equally with the elided username.
1353   // If the username is short enough that it doesn't need half the available
1354   // width, the elided domain will occupy that extra width.
1355
1356   // Split the email into its local-part (username) and domain-part. The email
1357   // spec allows for @ symbols in the username under some special requirements,
1358   // but not in the domain part, so splitting at the last @ symbol is safe.
1359   const size_t split_index = email.find_last_of('@');
1360   DCHECK_NE(split_index, base::string16::npos);
1361   base::string16 username = email.substr(0, split_index);
1362   base::string16 domain = email.substr(split_index + 1);
1363   DCHECK(!username.empty());
1364   DCHECK(!domain.empty());
1365
1366   // Subtract the @ symbol from the available width as it is mandatory.
1367   const base::string16 kAtSignUTF16 = base::ASCIIToUTF16("@");
1368   available_width -= GetStringWidthF(kAtSignUTF16, font_list());
1369
1370   // Check whether eliding the domain is necessary: if eliding the username
1371   // is sufficient, the domain will not be elided.
1372   const float full_username_width = GetStringWidthF(username, font_list());
1373   const float available_domain_width = available_width -
1374       std::min(full_username_width,
1375           GetStringWidthF(username.substr(0, 1) + kEllipsisUTF16, font_list()));
1376   if (GetStringWidthF(domain, font_list()) > available_domain_width) {
1377     // Elide the domain so that it only takes half of the available width.
1378     // Should the username not need all the width available in its half, the
1379     // domain will occupy the leftover width.
1380     // If |desired_domain_width| is greater than |available_domain_width|: the
1381     // minimal username elision allowed by the specifications will not fit; thus
1382     // |desired_domain_width| must be <= |available_domain_width| at all cost.
1383     const float desired_domain_width =
1384         std::min<float>(available_domain_width,
1385             std::max<float>(available_width - full_username_width,
1386                             available_width / 2));
1387     domain = Elide(domain, desired_domain_width, ELIDE_MIDDLE);
1388     // Failing to elide the domain such that at least one character remains
1389     // (other than the ellipsis itself) remains: return a single ellipsis.
1390     if (domain.length() <= 1U)
1391       return base::string16(kEllipsisUTF16);
1392   }
1393
1394   // Fit the username in the remaining width (at this point the elided username
1395   // is guaranteed to fit with at least one character remaining given all the
1396   // precautions taken earlier).
1397   available_width -= GetStringWidthF(domain, font_list());
1398   username = Elide(username, available_width, ELIDE_TAIL);
1399   return username + kAtSignUTF16 + domain;
1400 }
1401
1402 void RenderText::UpdateCachedBoundsAndOffset() {
1403   if (cached_bounds_and_offset_valid_)
1404     return;
1405
1406   // TODO(ckocagil): Add support for scrolling multiline text.
1407
1408   int delta_x = 0;
1409
1410   if (cursor_enabled()) {
1411     // When cursor is enabled, ensure it is visible. For this, set the valid
1412     // flag true and calculate the current cursor bounds using the stale
1413     // |display_offset_|. Then calculate the change in offset needed to move the
1414     // cursor into the visible area.
1415     cached_bounds_and_offset_valid_ = true;
1416     cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_);
1417
1418     // TODO(bidi): Show RTL glyphs at the cursor position for ALIGN_LEFT, etc.
1419     if (cursor_bounds_.right() > display_rect_.right())
1420       delta_x = display_rect_.right() - cursor_bounds_.right();
1421     else if (cursor_bounds_.x() < display_rect_.x())
1422       delta_x = display_rect_.x() - cursor_bounds_.x();
1423   }
1424
1425   SetDisplayOffset(display_offset_.x() + delta_x);
1426 }
1427
1428 void RenderText::DrawSelection(Canvas* canvas) {
1429   const std::vector<Rect> sel = GetSubstringBounds(selection());
1430   for (std::vector<Rect>::const_iterator i = sel.begin(); i < sel.end(); ++i)
1431     canvas->FillRect(*i, selection_background_focused_color_);
1432 }
1433
1434 }  // namespace gfx