1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/gfx/render_text_pango.h"
7 #include <pango/pangocairo.h>
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_render_params_linux.h"
18 #include "ui/gfx/pango_util.h"
19 #include "ui/gfx/utf16_indexing.h"
25 // Returns the preceding element in a GSList (O(n)).
26 GSList
* GSListPrevious(GSList
* head
, GSList
* item
) {
28 for (GSList
* cur
= head
; cur
!= item
; cur
= cur
->next
) {
35 // Returns true if the given visual cursor |direction| is logically forward
36 // motion in the given Pango |item|.
37 bool IsForwardMotion(VisualCursorDirection direction
, const PangoItem
* item
) {
38 bool rtl
= item
->analysis
.level
& 1;
39 return rtl
== (direction
== CURSOR_LEFT
);
42 // Checks whether |range| contains |index|. This is not the same as calling
43 // |range.Contains(gfx::Range(index))| - as that would return true when
44 // |index| == |range.end()|.
45 bool IndexInRange(const Range
& range
, size_t index
) {
46 return index
>= range
.start() && index
< range
.end();
49 // Sets underline metrics on |renderer| according to Pango font |desc|.
50 void SetPangoUnderlineMetrics(PangoFontDescription
*desc
,
51 internal::SkiaTextRenderer
* renderer
) {
52 PangoFontMetrics
* metrics
= GetPangoFontMetrics(desc
);
53 int thickness
= pango_font_metrics_get_underline_thickness(metrics
);
54 // Pango returns the position "above the baseline". Change its sign to convert
55 // it to a vertical offset from the baseline.
56 int position
= -pango_font_metrics_get_underline_position(metrics
);
57 pango_quantize_line_geometry(&thickness
, &position
);
58 // Note: pango_quantize_line_geometry() guarantees pixel boundaries, so
59 // PANGO_PIXELS() is safe to use.
60 renderer
->SetUnderlineMetrics(PANGO_PIXELS(thickness
),
61 PANGO_PIXELS(position
));
66 // TODO(xji): index saved in upper layer is utf16 index. Pango uses utf8 index.
67 // Since caret_pos is used internally, we could save utf8 index for caret_pos
68 // to avoid conversion.
70 RenderTextPango::RenderTextPango()
78 RenderTextPango::~RenderTextPango() {
82 Size
RenderTextPango::GetStringSize() {
84 int width
= 0, height
= 0;
85 pango_layout_get_pixel_size(layout_
, &width
, &height
);
86 // Keep a consistent height between this particular string's PangoLayout and
87 // potentially larger text supported by the FontList.
88 // For example, if a text field contains a Japanese character, which is
89 // smaller than Latin ones, and then later a Latin one is inserted, this
90 // ensures that the text baseline does not shift.
91 return Size(width
, std::max(height
, font_list().GetHeight()));
94 SelectionModel
RenderTextPango::FindCursorPosition(const Point
& point
) {
98 return SelectionModel(0, CURSOR_FORWARD
);
100 Point
p(ToTextPoint(point
));
102 // When the point is outside of text, return HOME/END position.
104 return EdgeSelectionModel(CURSOR_LEFT
);
105 if (p
.x() > GetStringSize().width())
106 return EdgeSelectionModel(CURSOR_RIGHT
);
108 int caret_pos
= 0, trailing
= 0;
109 pango_layout_xy_to_index(layout_
, p
.x() * PANGO_SCALE
, p
.y() * PANGO_SCALE
,
110 &caret_pos
, &trailing
);
112 DCHECK_GE(trailing
, 0);
114 caret_pos
= g_utf8_offset_to_pointer(layout_text_
+ caret_pos
,
115 trailing
) - layout_text_
;
116 DCHECK_LE(static_cast<size_t>(caret_pos
), strlen(layout_text_
));
119 return SelectionModel(LayoutIndexToTextIndex(caret_pos
),
120 (trailing
> 0) ? CURSOR_BACKWARD
: CURSOR_FORWARD
);
123 std::vector
<RenderText::FontSpan
> RenderTextPango::GetFontSpansForTesting() {
126 std::vector
<RenderText::FontSpan
> spans
;
127 for (GSList
* it
= current_line_
->runs
; it
; it
= it
->next
) {
128 PangoItem
* item
= reinterpret_cast<PangoLayoutRun
*>(it
->data
)->item
;
129 const int start
= LayoutIndexToTextIndex(item
->offset
);
130 const int end
= LayoutIndexToTextIndex(item
->offset
+ item
->length
);
131 const Range
range(start
, end
);
133 ScopedPangoFontDescription
desc(pango_font_describe(item
->analysis
.font
));
134 spans
.push_back(RenderText::FontSpan(Font(desc
.get()), range
));
140 int RenderTextPango::GetLayoutTextBaseline() {
142 return PANGO_PIXELS(pango_layout_get_baseline(layout_
));
145 SelectionModel
RenderTextPango::AdjacentCharSelectionModel(
146 const SelectionModel
& selection
,
147 VisualCursorDirection direction
) {
148 GSList
* run
= GetRunContainingCaret(selection
);
150 // The cursor is not in any run: we're at the visual and logical edge.
151 SelectionModel edge
= EdgeSelectionModel(direction
);
152 if (edge
.caret_pos() == selection
.caret_pos())
155 run
= (direction
== CURSOR_RIGHT
) ?
156 current_line_
->runs
: g_slist_last(current_line_
->runs
);
158 // If the cursor is moving within the current run, just move it by one
159 // grapheme in the appropriate direction.
160 PangoItem
* item
= reinterpret_cast<PangoLayoutRun
*>(run
->data
)->item
;
161 size_t caret
= selection
.caret_pos();
162 if (IsForwardMotion(direction
, item
)) {
163 if (caret
< LayoutIndexToTextIndex(item
->offset
+ item
->length
)) {
164 caret
= IndexOfAdjacentGrapheme(caret
, CURSOR_FORWARD
);
165 return SelectionModel(caret
, CURSOR_BACKWARD
);
168 if (caret
> LayoutIndexToTextIndex(item
->offset
)) {
169 caret
= IndexOfAdjacentGrapheme(caret
, CURSOR_BACKWARD
);
170 return SelectionModel(caret
, CURSOR_FORWARD
);
173 // The cursor is at the edge of a run; move to the visually adjacent run.
174 // TODO(xji): Keep a vector of runs to avoid using a singly-linked list.
175 run
= (direction
== CURSOR_RIGHT
) ?
176 run
->next
: GSListPrevious(current_line_
->runs
, run
);
178 return EdgeSelectionModel(direction
);
180 PangoItem
* item
= reinterpret_cast<PangoLayoutRun
*>(run
->data
)->item
;
181 return IsForwardMotion(direction
, item
) ?
182 FirstSelectionModelInsideRun(item
) : LastSelectionModelInsideRun(item
);
185 SelectionModel
RenderTextPango::AdjacentWordSelectionModel(
186 const SelectionModel
& selection
,
187 VisualCursorDirection direction
) {
189 return EdgeSelectionModel(direction
);
191 base::i18n::BreakIterator
iter(text(), base::i18n::BreakIterator::BREAK_WORD
);
192 bool success
= iter
.Init();
197 SelectionModel
cur(selection
);
199 cur
= AdjacentCharSelectionModel(cur
, direction
);
200 GSList
* run
= GetRunContainingCaret(cur
);
203 PangoItem
* item
= reinterpret_cast<PangoLayoutRun
*>(run
->data
)->item
;
204 size_t cursor
= cur
.caret_pos();
205 if (IsForwardMotion(direction
, item
) ?
206 iter
.IsEndOfWord(cursor
) : iter
.IsStartOfWord(cursor
))
213 Range
RenderTextPango::GetGlyphBounds(size_t index
) {
215 pango_layout_index_to_pos(layout_
, TextIndexToLayoutIndex(index
), &pos
);
216 // TODO(derat): Support fractional ranges for subpixel positioning?
217 return Range(PANGO_PIXELS(pos
.x
), PANGO_PIXELS(pos
.x
+ pos
.width
));
220 std::vector
<Rect
> RenderTextPango::GetSubstringBounds(const Range
& range
) {
221 DCHECK_LE(range
.GetMax(), text().length());
222 if (range
.is_empty())
223 return std::vector
<Rect
>();
228 pango_layout_line_get_x_ranges(current_line_
,
229 TextIndexToLayoutIndex(range
.GetMin()),
230 TextIndexToLayoutIndex(range
.GetMax()),
234 const int height
= GetStringSize().height();
236 std::vector
<Rect
> bounds
;
237 for (int i
= 0; i
< n_ranges
; ++i
) {
238 // TODO(derat): Support fractional bounds for subpixel positioning?
239 int x
= PANGO_PIXELS(ranges
[2 * i
]);
240 int width
= PANGO_PIXELS(ranges
[2 * i
+ 1]) - x
;
241 Rect
rect(x
, 0, width
, height
);
242 rect
.set_origin(ToViewPoint(rect
.origin()));
243 bounds
.push_back(rect
);
249 size_t RenderTextPango::TextIndexToLayoutIndex(size_t index
) const {
251 ptrdiff_t offset
= gfx::UTF16IndexToOffset(text(), 0, index
);
252 // Clamp layout indices to the length of the text actually used for layout.
253 offset
= std::min
<size_t>(offset
, g_utf8_strlen(layout_text_
, -1));
254 const char* layout_pointer
= g_utf8_offset_to_pointer(layout_text_
, offset
);
255 return (layout_pointer
- layout_text_
);
258 size_t RenderTextPango::LayoutIndexToTextIndex(size_t index
) const {
260 const char* layout_pointer
= layout_text_
+ index
;
261 const long offset
= g_utf8_pointer_to_offset(layout_text_
, layout_pointer
);
262 return gfx::UTF16OffsetToIndex(text(), 0, offset
);
265 bool RenderTextPango::IsCursorablePosition(size_t position
) {
266 if (position
== 0 && text().empty())
268 if (position
>= text().length())
269 return position
== text().length();
270 if (!gfx::IsValidCodePointIndex(text(), position
))
274 ptrdiff_t offset
= gfx::UTF16IndexToOffset(text(), 0, position
);
275 // Check that the index corresponds with a valid text code point, that it is
276 // marked as a legitimate cursor position by Pango, and that it is not
277 // truncated from layout text (its glyph is shown on screen).
278 return (offset
< num_log_attrs_
&& log_attrs_
[offset
].is_cursor_position
&&
279 offset
< g_utf8_strlen(layout_text_
, -1));
282 void RenderTextPango::ResetLayout() {
283 // set_cached_bounds_and_offset_valid(false) is done in RenderText for every
284 // operation that triggers ResetLayout().
286 // TODO(msw): Keep |layout_| across text changes, etc.; it can be re-used.
287 g_object_unref(layout_
);
291 pango_layout_line_unref(current_line_
);
292 current_line_
= NULL
;
302 void RenderTextPango::EnsureLayout() {
303 if (layout_
== NULL
) {
304 cairo_surface_t
* surface
=
305 cairo_image_surface_create(CAIRO_FORMAT_ARGB32
, 0, 0);
306 CHECK_EQ(CAIRO_STATUS_SUCCESS
, cairo_surface_status(surface
));
307 cairo_t
* cr
= cairo_create(surface
);
308 CHECK_EQ(CAIRO_STATUS_SUCCESS
, cairo_status(cr
));
310 layout_
= pango_cairo_create_layout(cr
);
311 CHECK_NE(static_cast<PangoLayout
*>(NULL
), layout_
);
313 cairo_surface_destroy(surface
);
315 SetupPangoLayoutWithFontDescription(layout_
,
317 font_list().GetFontDescriptionString(),
320 Canvas::DefaultCanvasTextAlignment());
322 // No width set so that the x-axis position is relative to the start of the
323 // text. ToViewPoint and ToTextPoint take care of the position conversion
324 // between text space and view spaces.
325 pango_layout_set_width(layout_
, -1);
326 // TODO(xji): If RenderText will be used for displaying purpose, such as
327 // label, we will need to remove the single-line-mode setting.
328 pango_layout_set_single_paragraph_mode(layout_
, true);
330 layout_text_
= pango_layout_get_text(layout_
);
331 SetupPangoAttributes(layout_
);
333 current_line_
= pango_layout_get_line_readonly(layout_
, 0);
334 CHECK_NE(static_cast<PangoLayoutLine
*>(NULL
), current_line_
);
335 pango_layout_line_ref(current_line_
);
337 pango_layout_get_log_attrs(layout_
, &log_attrs_
, &num_log_attrs_
);
341 void RenderTextPango::SetupPangoAttributes(PangoLayout
* layout
) {
342 PangoAttrList
* attrs
= pango_attr_list_new();
344 // Splitting text runs to accommodate styling can break Arabic glyph shaping.
345 // Only split text runs as needed for bold and italic font styles changes.
346 BreakList
<bool>::const_iterator bold
= styles()[BOLD
].breaks().begin();
347 BreakList
<bool>::const_iterator italic
= styles()[ITALIC
].breaks().begin();
348 while (bold
!= styles()[BOLD
].breaks().end() &&
349 italic
!= styles()[ITALIC
].breaks().end()) {
350 const int style
= (bold
->second
? Font::BOLD
: 0) |
351 (italic
->second
? Font::ITALIC
: 0);
352 const size_t bold_end
= styles()[BOLD
].GetRange(bold
).end();
353 const size_t italic_end
= styles()[ITALIC
].GetRange(italic
).end();
354 const size_t style_end
= std::min(bold_end
, italic_end
);
355 if (style
!= font_list().GetFontStyle()) {
356 FontList derived_font_list
= font_list().DeriveWithStyle(style
);
357 ScopedPangoFontDescription
desc(pango_font_description_from_string(
358 derived_font_list
.GetFontDescriptionString().c_str()));
360 PangoAttribute
* pango_attr
= pango_attr_font_desc_new(desc
.get());
361 pango_attr
->start_index
=
362 TextIndexToLayoutIndex(std::max(bold
->first
, italic
->first
));
363 pango_attr
->end_index
= TextIndexToLayoutIndex(style_end
);
364 pango_attr_list_insert(attrs
, pango_attr
);
366 bold
+= bold_end
== style_end
? 1 : 0;
367 italic
+= italic_end
== style_end
? 1 : 0;
369 DCHECK(bold
== styles()[BOLD
].breaks().end());
370 DCHECK(italic
== styles()[ITALIC
].breaks().end());
372 pango_layout_set_attributes(layout
, attrs
);
373 pango_attr_list_unref(attrs
);
376 void RenderTextPango::DrawVisualText(Canvas
* canvas
) {
379 // Skia will draw glyphs with respect to the baseline.
380 Vector2d
offset(GetLineOffset(0) + Vector2d(0, GetLayoutTextBaseline()));
382 SkScalar x
= SkIntToScalar(offset
.x());
383 SkScalar y
= SkIntToScalar(offset
.y());
385 std::vector
<SkPoint
> pos
;
386 std::vector
<uint16
> glyphs
;
388 internal::SkiaTextRenderer
renderer(canvas
);
389 ApplyFadeEffects(&renderer
);
390 ApplyTextShadows(&renderer
);
392 // TODO(derat): Use font-specific params: http://crbug.com/125235
393 const gfx::FontRenderParams
& render_params
=
394 gfx::GetDefaultFontRenderParams();
395 const bool use_subpixel_rendering
=
396 render_params
.subpixel_rendering
!=
397 gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE
;
398 renderer
.SetFontSmoothingSettings(
399 render_params
.antialiasing
,
400 use_subpixel_rendering
&& !background_is_transparent());
402 SkPaint::Hinting skia_hinting
= SkPaint::kNormal_Hinting
;
403 switch (render_params
.hinting
) {
404 case gfx::FontRenderParams::HINTING_NONE
:
405 skia_hinting
= SkPaint::kNo_Hinting
;
407 case gfx::FontRenderParams::HINTING_SLIGHT
:
408 skia_hinting
= SkPaint::kSlight_Hinting
;
410 case gfx::FontRenderParams::HINTING_MEDIUM
:
411 skia_hinting
= SkPaint::kNormal_Hinting
;
413 case gfx::FontRenderParams::HINTING_FULL
:
414 skia_hinting
= SkPaint::kFull_Hinting
;
417 renderer
.SetFontHinting(skia_hinting
);
419 // Temporarily apply composition underlines and selection colors.
420 ApplyCompositionAndSelectionStyles();
422 internal::StyleIterator
style(colors(), styles());
423 for (GSList
* it
= current_line_
->runs
; it
; it
= it
->next
) {
424 PangoLayoutRun
* run
= reinterpret_cast<PangoLayoutRun
*>(it
->data
);
425 int glyph_count
= run
->glyphs
->num_glyphs
;
426 // TODO(msw): Skip painting runs outside the display rect area, like Win.
427 if (glyph_count
== 0)
430 ScopedPangoFontDescription
desc(
431 pango_font_describe(run
->item
->analysis
.font
));
433 const std::string family_name
=
434 pango_font_description_get_family(desc
.get());
435 renderer
.SetTextSize(GetPangoFontSizeInPixels(desc
.get()));
437 glyphs
.resize(glyph_count
);
438 pos
.resize(glyph_count
);
440 // Track the current glyph and the glyph at the start of its styled range.
442 int style_start_glyph_index
= glyph_index
;
444 // Track the x-coordinates for each styled range (|x| marks the current).
445 SkScalar style_start_x
= x
;
447 // Track the current style and its text (not layout) index range.
448 style
.UpdatePosition(GetGlyphTextIndex(run
, style_start_glyph_index
));
449 Range style_range
= style
.GetRange();
452 const PangoGlyphInfo
& glyph
= run
->glyphs
->glyphs
[glyph_index
];
453 glyphs
[glyph_index
] = static_cast<uint16
>(glyph
.glyph
);
454 // Use pango_units_to_double() rather than PANGO_PIXELS() here, so units
455 // are not rounded to the pixel grid if subpixel positioning is enabled.
456 pos
[glyph_index
].set(x
+ pango_units_to_double(glyph
.geometry
.x_offset
),
457 y
+ pango_units_to_double(glyph
.geometry
.y_offset
));
458 x
+= pango_units_to_double(glyph
.geometry
.width
);
461 const size_t glyph_text_index
= (glyph_index
== glyph_count
) ?
462 style_range
.end() : GetGlyphTextIndex(run
, glyph_index
);
463 if (!IndexInRange(style_range
, glyph_text_index
)) {
464 // TODO(asvitkine): For cases like "fi", where "fi" is a single glyph
465 // but can span multiple styles, Pango splits the
466 // styles evenly over the glyph. We can do this too by
467 // clipping and drawing the glyph several times.
468 renderer
.SetForegroundColor(style
.color());
469 const int font_style
= (style
.style(BOLD
) ? Font::BOLD
: 0) |
470 (style
.style(ITALIC
) ? Font::ITALIC
: 0);
471 renderer
.SetFontFamilyWithStyle(family_name
, font_style
);
472 renderer
.DrawPosText(&pos
[style_start_glyph_index
],
473 &glyphs
[style_start_glyph_index
],
474 glyph_index
- style_start_glyph_index
);
475 if (style
.style(UNDERLINE
))
476 SetPangoUnderlineMetrics(desc
.get(), &renderer
);
477 renderer
.DrawDecorations(style_start_x
, y
, x
- style_start_x
,
478 style
.style(UNDERLINE
), style
.style(STRIKE
),
479 style
.style(DIAGONAL_STRIKE
));
480 style
.UpdatePosition(glyph_text_index
);
481 style_range
= style
.GetRange();
482 style_start_glyph_index
= glyph_index
;
485 } while (glyph_index
< glyph_count
);
488 // Undo the temporarily applied composition underlines and selection colors.
489 UndoCompositionAndSelectionStyles();
492 GSList
* 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
;
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
))
507 SelectionModel
RenderTextPango::FirstSelectionModelInsideRun(
508 const PangoItem
* item
) {
509 size_t caret
= IndexOfAdjacentGrapheme(
510 LayoutIndexToTextIndex(item
->offset
), CURSOR_FORWARD
);
511 return SelectionModel(caret
, CURSOR_BACKWARD
);
514 SelectionModel
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
);
521 size_t RenderTextPango::GetGlyphTextIndex(PangoLayoutRun
* run
,
522 int glyph_index
) const {
523 return LayoutIndexToTextIndex(run
->item
->offset
+
524 run
->glyphs
->log_clusters
[glyph_index
]);
527 RenderText
* RenderText::CreateInstance() {
528 return new RenderTextPango
;