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