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_pango.h" 6 7#include <pango/pangocairo.h> 8#include <algorithm> 9#include <string> 10#include <vector> 11 12#include "base/i18n/break_iterator.h" 13#include "base/logging.h" 14#include "third_party/skia/include/core/SkTypeface.h" 15#include "ui/gfx/canvas.h" 16#include "ui/gfx/font.h" 17#include "ui/gfx/font_list.h" 18#include "ui/gfx/font_render_params.h" 19#include "ui/gfx/pango_util.h" 20#include "ui/gfx/platform_font_pango.h" 21#include "ui/gfx/utf16_indexing.h" 22 23namespace gfx { 24 25namespace { 26 27// Returns the preceding element in a GSList (O(n)). 28GSList* GSListPrevious(GSList* head, GSList* item) { 29 GSList* prev = NULL; 30 for (GSList* cur = head; cur != item; cur = cur->next) { 31 DCHECK(cur); 32 prev = cur; 33 } 34 return prev; 35} 36 37// Returns true if the given visual cursor |direction| is logically forward 38// motion in the given Pango |item|. 39bool IsForwardMotion(VisualCursorDirection direction, const PangoItem* item) { 40 bool rtl = item->analysis.level & 1; 41 return rtl == (direction == CURSOR_LEFT); 42} 43 44// Checks whether |range| contains |index|. This is not the same as calling 45// range.Contains(Range(index)), which returns true if |index| == |range.end()|. 46bool IndexInRange(const Range& range, size_t index) { 47 return index >= range.start() && index < range.end(); 48} 49 50// Sets underline metrics on |renderer| according to Pango font |desc|. 51void SetPangoUnderlineMetrics(PangoFontDescription *desc, 52 internal::SkiaTextRenderer* renderer) { 53 PangoFontMetrics* metrics = GetPangoFontMetrics(desc); 54 int thickness = pango_font_metrics_get_underline_thickness(metrics); 55 // Pango returns the position "above the baseline". Change its sign to convert 56 // it to a vertical offset from the baseline. 57 int position = -pango_font_metrics_get_underline_position(metrics); 58 59 // Note: pango_quantize_line_geometry() guarantees pixel boundaries, so 60 // PANGO_PIXELS() is safe to use. 61 pango_quantize_line_geometry(&thickness, &position); 62 int thickness_pixels = PANGO_PIXELS(thickness); 63 int position_pixels = PANGO_PIXELS(position); 64 65 // Ugly hack: make sure that underlines don't get clipped. See 66 // http://crbug.com/393117. 67 int descent_pixels = PANGO_PIXELS(pango_font_metrics_get_descent(metrics)); 68 position_pixels = std::min(position_pixels, 69 descent_pixels - thickness_pixels); 70 71 renderer->SetUnderlineMetrics(thickness_pixels, position_pixels); 72} 73 74} // namespace 75 76// TODO(xji): index saved in upper layer is utf16 index. Pango uses utf8 index. 77// Since caret_pos is used internally, we could save utf8 index for caret_pos 78// to avoid conversion. 79 80RenderTextPango::RenderTextPango() 81 : layout_(NULL), 82 current_line_(NULL), 83 log_attrs_(NULL), 84 num_log_attrs_(0), 85 layout_text_(NULL) { 86} 87 88RenderTextPango::~RenderTextPango() { 89 ResetLayout(); 90} 91 92Size RenderTextPango::GetStringSize() { 93 EnsureLayout(); 94 int width = 0, height = 0; 95 pango_layout_get_pixel_size(layout_, &width, &height); 96 97 // Pango returns 0 widths for very long strings (of 0x40000 chars or more). 98 // This is caused by an int overflow in pango_glyph_string_extents_range. 99 // Absurdly long strings may even report non-zero garbage values for width; 100 // while detecting that isn't worthwhile, this handles the 0 width cases. 101 const long kAbsurdLength = 100000; 102 if (width == 0 && g_utf8_strlen(layout_text_, -1) > kAbsurdLength) 103 width = font_list().GetExpectedTextWidth(g_utf8_strlen(layout_text_, -1)); 104 105 // Keep a consistent height between this particular string's PangoLayout and 106 // potentially larger text supported by the FontList. 107 // For example, if a text field contains a Japanese character, which is 108 // smaller than Latin ones, and then later a Latin one is inserted, this 109 // ensures that the text baseline does not shift. 110 return Size(width, std::max(height, font_list().GetHeight())); 111} 112 113SelectionModel RenderTextPango::FindCursorPosition(const Point& point) { 114 EnsureLayout(); 115 116 if (text().empty()) 117 return SelectionModel(0, CURSOR_FORWARD); 118 119 Point p(ToTextPoint(point)); 120 121 // When the point is outside of text, return HOME/END position. 122 if (p.x() < 0) 123 return EdgeSelectionModel(CURSOR_LEFT); 124 if (p.x() > GetStringSize().width()) 125 return EdgeSelectionModel(CURSOR_RIGHT); 126 127 int caret_pos = 0, trailing = 0; 128 pango_layout_xy_to_index(layout_, p.x() * PANGO_SCALE, p.y() * PANGO_SCALE, 129 &caret_pos, &trailing); 130 131 DCHECK_GE(trailing, 0); 132 if (trailing > 0) { 133 caret_pos = g_utf8_offset_to_pointer(layout_text_ + caret_pos, 134 trailing) - layout_text_; 135 DCHECK_LE(static_cast<size_t>(caret_pos), strlen(layout_text_)); 136 } 137 138 return SelectionModel(LayoutIndexToTextIndex(caret_pos), 139 (trailing > 0) ? CURSOR_BACKWARD : CURSOR_FORWARD); 140} 141 142std::vector<RenderText::FontSpan> RenderTextPango::GetFontSpansForTesting() { 143 EnsureLayout(); 144 145 std::vector<RenderText::FontSpan> spans; 146 for (GSList* it = current_line_->runs; it; it = it->next) { 147 PangoItem* item = reinterpret_cast<PangoLayoutRun*>(it->data)->item; 148 const int start = LayoutIndexToTextIndex(item->offset); 149 const int end = LayoutIndexToTextIndex(item->offset + item->length); 150 const Range range(start, end); 151 152 ScopedPangoFontDescription desc(pango_font_describe(item->analysis.font)); 153 spans.push_back(RenderText::FontSpan(Font(desc.get()), range)); 154 } 155 156 return spans; 157} 158 159int RenderTextPango::GetLayoutTextBaseline() { 160 EnsureLayout(); 161 return PANGO_PIXELS(pango_layout_get_baseline(layout_)); 162} 163 164SelectionModel RenderTextPango::AdjacentCharSelectionModel( 165 const SelectionModel& selection, 166 VisualCursorDirection direction) { 167 GSList* run = GetRunContainingCaret(selection); 168 if (!run) { 169 // The cursor is not in any run: we're at the visual and logical edge. 170 SelectionModel edge = EdgeSelectionModel(direction); 171 if (edge.caret_pos() == selection.caret_pos()) 172 return edge; 173 else 174 run = (direction == CURSOR_RIGHT) ? 175 current_line_->runs : g_slist_last(current_line_->runs); 176 } else { 177 // If the cursor is moving within the current run, just move it by one 178 // grapheme in the appropriate direction. 179 PangoItem* item = reinterpret_cast<PangoLayoutRun*>(run->data)->item; 180 size_t caret = selection.caret_pos(); 181 if (IsForwardMotion(direction, item)) { 182 if (caret < LayoutIndexToTextIndex(item->offset + item->length)) { 183 caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD); 184 return SelectionModel(caret, CURSOR_BACKWARD); 185 } 186 } else { 187 if (caret > LayoutIndexToTextIndex(item->offset)) { 188 caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD); 189 return SelectionModel(caret, CURSOR_FORWARD); 190 } 191 } 192 // The cursor is at the edge of a run; move to the visually adjacent run. 193 // TODO(xji): Keep a vector of runs to avoid using a singly-linked list. 194 run = (direction == CURSOR_RIGHT) ? 195 run->next : GSListPrevious(current_line_->runs, run); 196 if (!run) 197 return EdgeSelectionModel(direction); 198 } 199 PangoItem* item = reinterpret_cast<PangoLayoutRun*>(run->data)->item; 200 return IsForwardMotion(direction, item) ? 201 FirstSelectionModelInsideRun(item) : LastSelectionModelInsideRun(item); 202} 203 204SelectionModel RenderTextPango::AdjacentWordSelectionModel( 205 const SelectionModel& selection, 206 VisualCursorDirection direction) { 207 if (obscured()) 208 return EdgeSelectionModel(direction); 209 210 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD); 211 bool success = iter.Init(); 212 DCHECK(success); 213 if (!success) 214 return selection; 215 216 SelectionModel cur(selection); 217 for (;;) { 218 cur = AdjacentCharSelectionModel(cur, direction); 219 GSList* run = GetRunContainingCaret(cur); 220 if (!run) 221 break; 222 PangoItem* item = reinterpret_cast<PangoLayoutRun*>(run->data)->item; 223 size_t cursor = cur.caret_pos(); 224 if (IsForwardMotion(direction, item) ? 225 iter.IsEndOfWord(cursor) : iter.IsStartOfWord(cursor)) 226 break; 227 } 228 229 return cur; 230} 231 232Range RenderTextPango::GetGlyphBounds(size_t index) { 233 EnsureLayout(); 234 PangoRectangle pos; 235 pango_layout_index_to_pos(layout_, TextIndexToLayoutIndex(index), &pos); 236 // TODO(derat): Support fractional ranges for subpixel positioning? 237 return Range(PANGO_PIXELS(pos.x), PANGO_PIXELS(pos.x + pos.width)); 238} 239 240std::vector<Rect> RenderTextPango::GetSubstringBounds(const Range& range) { 241 DCHECK_LE(range.GetMax(), text().length()); 242 if (range.is_empty()) 243 return std::vector<Rect>(); 244 245 EnsureLayout(); 246 int* ranges = NULL; 247 int n_ranges = 0; 248 pango_layout_line_get_x_ranges(current_line_, 249 TextIndexToLayoutIndex(range.GetMin()), 250 TextIndexToLayoutIndex(range.GetMax()), 251 &ranges, 252 &n_ranges); 253 254 const int height = GetStringSize().height(); 255 256 std::vector<Rect> bounds; 257 for (int i = 0; i < n_ranges; ++i) { 258 // TODO(derat): Support fractional bounds for subpixel positioning? 259 int x = PANGO_PIXELS(ranges[2 * i]); 260 int width = PANGO_PIXELS(ranges[2 * i + 1]) - x; 261 Rect rect(x, 0, width, height); 262 rect.set_origin(ToViewPoint(rect.origin())); 263 bounds.push_back(rect); 264 } 265 g_free(ranges); 266 return bounds; 267} 268 269size_t RenderTextPango::TextIndexToLayoutIndex(size_t index) const { 270 DCHECK(layout_); 271 ptrdiff_t offset = UTF16IndexToOffset(text(), 0, index); 272 // Clamp layout indices to the length of the text actually used for layout. 273 offset = std::min<size_t>(offset, g_utf8_strlen(layout_text_, -1)); 274 const char* layout_pointer = g_utf8_offset_to_pointer(layout_text_, offset); 275 return (layout_pointer - layout_text_); 276} 277 278size_t RenderTextPango::LayoutIndexToTextIndex(size_t index) const { 279 DCHECK(layout_); 280 const char* layout_pointer = layout_text_ + index; 281 const long offset = g_utf8_pointer_to_offset(layout_text_, layout_pointer); 282 return UTF16OffsetToIndex(text(), 0, offset); 283} 284 285bool RenderTextPango::IsValidCursorIndex(size_t index) { 286 if (index == 0 || index == text().length()) 287 return true; 288 if (!IsValidLogicalIndex(index)) 289 return false; 290 291 EnsureLayout(); 292 ptrdiff_t offset = UTF16IndexToOffset(text(), 0, index); 293 // Check that the index is marked as a legitimate cursor position by Pango. 294 return offset < num_log_attrs_ && log_attrs_[offset].is_cursor_position; 295} 296 297void RenderTextPango::ResetLayout() { 298 // set_cached_bounds_and_offset_valid(false) is done in RenderText for every 299 // operation that triggers ResetLayout(). 300 if (layout_) { 301 // TODO(msw): Keep |layout_| across text changes, etc.; it can be re-used. 302 g_object_unref(layout_); 303 layout_ = NULL; 304 } 305 if (current_line_) { 306 pango_layout_line_unref(current_line_); 307 current_line_ = NULL; 308 } 309 if (log_attrs_) { 310 g_free(log_attrs_); 311 log_attrs_ = NULL; 312 num_log_attrs_ = 0; 313 } 314 layout_text_ = NULL; 315} 316 317void RenderTextPango::EnsureLayout() { 318 if (layout_ == NULL) { 319 cairo_surface_t* surface = 320 cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0); 321 CHECK_EQ(CAIRO_STATUS_SUCCESS, cairo_surface_status(surface)); 322 cairo_t* cr = cairo_create(surface); 323 CHECK_EQ(CAIRO_STATUS_SUCCESS, cairo_status(cr)); 324 325 layout_ = pango_cairo_create_layout(cr); 326 CHECK_NE(static_cast<PangoLayout*>(NULL), layout_); 327 cairo_destroy(cr); 328 cairo_surface_destroy(surface); 329 330 SetUpPangoLayout(layout_, GetLayoutText(), font_list(), GetTextDirection(), 331 Canvas::DefaultCanvasTextAlignment()); 332 333 // No width set so that the x-axis position is relative to the start of the 334 // text. ToViewPoint and ToTextPoint take care of the position conversion 335 // between text space and view spaces. 336 pango_layout_set_width(layout_, -1); 337 // TODO(xji): If RenderText will be used for displaying purpose, such as 338 // label, we will need to remove the single-line-mode setting. 339 pango_layout_set_single_paragraph_mode(layout_, true); 340 341 layout_text_ = pango_layout_get_text(layout_); 342 SetupPangoAttributes(layout_); 343 344 current_line_ = pango_layout_get_line_readonly(layout_, 0); 345 CHECK_NE(static_cast<PangoLayoutLine*>(NULL), current_line_); 346 pango_layout_line_ref(current_line_); 347 348 pango_layout_get_log_attrs(layout_, &log_attrs_, &num_log_attrs_); 349 } 350} 351 352void RenderTextPango::SetupPangoAttributes(PangoLayout* layout) { 353 PangoAttrList* attrs = pango_attr_list_new(); 354 355 // Splitting text runs to accommodate styling can break Arabic glyph shaping. 356 // Only split text runs as needed for bold and italic font styles changes. 357 BreakList<bool>::const_iterator bold = styles()[BOLD].breaks().begin(); 358 BreakList<bool>::const_iterator italic = styles()[ITALIC].breaks().begin(); 359 while (bold != styles()[BOLD].breaks().end() && 360 italic != styles()[ITALIC].breaks().end()) { 361 const int style = (bold->second ? Font::BOLD : 0) | 362 (italic->second ? Font::ITALIC : 0); 363 const size_t bold_end = styles()[BOLD].GetRange(bold).end(); 364 const size_t italic_end = styles()[ITALIC].GetRange(italic).end(); 365 const size_t style_end = std::min(bold_end, italic_end); 366 if (style != font_list().GetFontStyle()) { 367 // TODO(derat): Don't interpret gfx::FontList font descriptions as Pango 368 // font descriptions: http://crbug.com/393067 369 FontList derived_font_list = font_list().DeriveWithStyle(style); 370 ScopedPangoFontDescription desc( 371 derived_font_list.GetFontDescriptionString()); 372 373 PangoAttribute* pango_attr = pango_attr_font_desc_new(desc.get()); 374 pango_attr->start_index = 375 TextIndexToLayoutIndex(std::max(bold->first, italic->first)); 376 pango_attr->end_index = TextIndexToLayoutIndex(style_end); 377 pango_attr_list_insert(attrs, pango_attr); 378 } 379 bold += bold_end == style_end ? 1 : 0; 380 italic += italic_end == style_end ? 1 : 0; 381 } 382 DCHECK(bold == styles()[BOLD].breaks().end()); 383 DCHECK(italic == styles()[ITALIC].breaks().end()); 384 385 pango_layout_set_attributes(layout, attrs); 386 pango_attr_list_unref(attrs); 387} 388 389void RenderTextPango::DrawVisualText(Canvas* canvas) { 390 DCHECK(layout_); 391 392 // Skia will draw glyphs with respect to the baseline. 393 Vector2d offset(GetLineOffset(0) + Vector2d(0, GetLayoutTextBaseline())); 394 395 SkScalar x = SkIntToScalar(offset.x()); 396 SkScalar y = SkIntToScalar(offset.y()); 397 398 std::vector<SkPoint> pos; 399 std::vector<uint16> glyphs; 400 401 internal::SkiaTextRenderer renderer(canvas); 402 ApplyFadeEffects(&renderer); 403 ApplyTextShadows(&renderer); 404 renderer.SetFontRenderParams( 405 font_list().GetPrimaryFont().GetFontRenderParams(), 406 background_is_transparent()); 407 408 // Temporarily apply composition underlines and selection colors. 409 ApplyCompositionAndSelectionStyles(); 410 411 internal::StyleIterator style(colors(), styles()); 412 for (GSList* it = current_line_->runs; it; it = it->next) { 413 // Skip painting runs outside the display area. 414 if (SkScalarTruncToInt(x) >= display_rect().right()) 415 break; 416 417 PangoLayoutRun* run = reinterpret_cast<PangoLayoutRun*>(it->data); 418 int glyph_count = run->glyphs->num_glyphs; 419 if (glyph_count == 0) 420 continue; 421 422 ScopedPangoFontDescription desc( 423 pango_font_describe(run->item->analysis.font)); 424 const std::string family_name = 425 pango_font_description_get_family(desc.get()); 426 renderer.SetTextSize(GetPangoFontSizeInPixels(desc.get())); 427 428 glyphs.resize(glyph_count); 429 pos.resize(glyph_count); 430 431 // Track the current glyph and the glyph at the start of its styled range. 432 int glyph_index = 0; 433 int style_start_glyph_index = glyph_index; 434 435 // Track the x-coordinates for each styled range (|x| marks the current). 436 SkScalar style_start_x = x; 437 438 // Track the current style and its text (not layout) index range. 439 style.UpdatePosition(GetGlyphTextIndex(run, style_start_glyph_index)); 440 Range style_range = style.GetRange(); 441 442 do { 443 const PangoGlyphInfo& glyph = run->glyphs->glyphs[glyph_index]; 444 glyphs[glyph_index] = static_cast<uint16>(glyph.glyph); 445 // Use pango_units_to_double() rather than PANGO_PIXELS() here, so units 446 // are not rounded to the pixel grid if subpixel positioning is enabled. 447 pos[glyph_index].set(x + pango_units_to_double(glyph.geometry.x_offset), 448 y + pango_units_to_double(glyph.geometry.y_offset)); 449 x += pango_units_to_double(glyph.geometry.width); 450 451 ++glyph_index; 452 // If this is the last glyph of the range or the last glyph inside the 453 // display area (which would cause early termination of the loop), paint 454 // the range. 455 const size_t glyph_text_index = (glyph_index == glyph_count) ? 456 style_range.end() : GetGlyphTextIndex(run, glyph_index); 457 if (!IndexInRange(style_range, glyph_text_index) || 458 SkScalarTruncToInt(x) >= display_rect().right()) { 459 // TODO(asvitkine): For cases like "fi", where "fi" is a single glyph 460 // but can span multiple styles, Pango splits the 461 // styles evenly over the glyph. We can do this too by 462 // clipping and drawing the glyph several times. 463 renderer.SetForegroundColor(style.color()); 464 const int font_style = (style.style(BOLD) ? Font::BOLD : 0) | 465 (style.style(ITALIC) ? Font::ITALIC : 0); 466 renderer.SetFontFamilyWithStyle(family_name, font_style); 467 renderer.DrawPosText(&pos[style_start_glyph_index], 468 &glyphs[style_start_glyph_index], 469 glyph_index - style_start_glyph_index); 470 if (style.style(UNDERLINE)) 471 SetPangoUnderlineMetrics(desc.get(), &renderer); 472 renderer.DrawDecorations(style_start_x, y, x - style_start_x, 473 style.style(UNDERLINE), style.style(STRIKE), 474 style.style(DIAGONAL_STRIKE)); 475 style.UpdatePosition(glyph_text_index); 476 style_range = style.GetRange(); 477 style_start_glyph_index = glyph_index; 478 style_start_x = x; 479 } 480 // Terminates loop when the end of the range has been reached or the next 481 // glyph falls outside the display area. 482 } while (glyph_index < glyph_count && 483 SkScalarTruncToInt(x) < display_rect().right()); 484 } 485 486 renderer.EndDiagonalStrike(); 487 488 // Undo the temporarily applied composition underlines and selection colors. 489 UndoCompositionAndSelectionStyles(); 490} 491 492GSList* RenderTextPango::GetRunContainingCaret( 493 const SelectionModel& caret) const { 494 size_t position = TextIndexToLayoutIndex(caret.caret_pos()); 495 LogicalCursorDirection affinity = caret.caret_affinity(); 496 GSList* run = current_line_->runs; 497 while (run) { 498 PangoItem* item = reinterpret_cast<PangoLayoutRun*>(run->data)->item; 499 Range item_range(item->offset, item->offset + item->length); 500 if (RangeContainsCaret(item_range, position, affinity)) 501 return run; 502 run = run->next; 503 } 504 return NULL; 505} 506 507SelectionModel RenderTextPango::FirstSelectionModelInsideRun( 508 const PangoItem* item) { 509 size_t caret = IndexOfAdjacentGrapheme( 510 LayoutIndexToTextIndex(item->offset), CURSOR_FORWARD); 511 return SelectionModel(caret, CURSOR_BACKWARD); 512} 513 514SelectionModel RenderTextPango::LastSelectionModelInsideRun( 515 const PangoItem* item) { 516 size_t caret = IndexOfAdjacentGrapheme( 517 LayoutIndexToTextIndex(item->offset + item->length), CURSOR_BACKWARD); 518 return SelectionModel(caret, CURSOR_FORWARD); 519} 520 521size_t RenderTextPango::GetGlyphTextIndex(PangoLayoutRun* run, 522 int glyph_index) const { 523 return LayoutIndexToTextIndex(run->item->offset + 524 run->glyphs->log_clusters[glyph_index]); 525} 526 527RenderText* RenderText::CreateNativeInstance() { 528 return new RenderTextPango; 529} 530 531} // namespace gfx 532