Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / ui / gfx / render_text_pango.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "ui/gfx/render_text_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_render_params_linux.h"
18 #include "ui/gfx/pango_util.h"
19 #include "ui/gfx/utf16_indexing.h"
20
21 namespace gfx {
22
23 namespace {
24
25 // Returns the preceding element in a GSList (O(n)).
26 GSList* GSListPrevious(GSList* head, GSList* item) {
27   GSList* prev = NULL;
28   for (GSList* cur = head; cur != item; cur = cur->next) {
29     DCHECK(cur);
30     prev = cur;
31   }
32   return prev;
33 }
34
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);
40 }
41
42 // Checks whether |range| contains |index|. This is not the same as calling
43 // range.Contains(Range(index)), which returns true if |index| == |range.end()|.
44 bool IndexInRange(const Range& range, size_t index) {
45   return index >= range.start() && index < range.end();
46 }
47
48 // Sets underline metrics on |renderer| according to Pango font |desc|.
49 void SetPangoUnderlineMetrics(PangoFontDescription *desc,
50                               internal::SkiaTextRenderer* renderer) {
51   PangoFontMetrics* metrics = GetPangoFontMetrics(desc);
52   int thickness = pango_font_metrics_get_underline_thickness(metrics);
53   // Pango returns the position "above the baseline". Change its sign to convert
54   // it to a vertical offset from the baseline.
55   int position = -pango_font_metrics_get_underline_position(metrics);
56   pango_quantize_line_geometry(&thickness, &position);
57   // Note: pango_quantize_line_geometry() guarantees pixel boundaries, so
58   //       PANGO_PIXELS() is safe to use.
59   renderer->SetUnderlineMetrics(PANGO_PIXELS(thickness),
60                                 PANGO_PIXELS(position));
61 }
62
63 }  // namespace
64
65 // TODO(xji): index saved in upper layer is utf16 index. Pango uses utf8 index.
66 // Since caret_pos is used internally, we could save utf8 index for caret_pos
67 // to avoid conversion.
68
69 RenderTextPango::RenderTextPango()
70     : layout_(NULL),
71       current_line_(NULL),
72       log_attrs_(NULL),
73       num_log_attrs_(0),
74       layout_text_(NULL) {
75 }
76
77 RenderTextPango::~RenderTextPango() {
78   ResetLayout();
79 }
80
81 Size RenderTextPango::GetStringSize() {
82   EnsureLayout();
83   int width = 0, height = 0;
84   pango_layout_get_pixel_size(layout_, &width, &height);
85   // Keep a consistent height between this particular string's PangoLayout and
86   // potentially larger text supported by the FontList.
87   // For example, if a text field contains a Japanese character, which is
88   // smaller than Latin ones, and then later a Latin one is inserted, this
89   // ensures that the text baseline does not shift.
90   return Size(width, std::max(height, font_list().GetHeight()));
91 }
92
93 SelectionModel RenderTextPango::FindCursorPosition(const Point& point) {
94   EnsureLayout();
95
96   if (text().empty())
97     return SelectionModel(0, CURSOR_FORWARD);
98
99   Point p(ToTextPoint(point));
100
101   // When the point is outside of text, return HOME/END position.
102   if (p.x() < 0)
103     return EdgeSelectionModel(CURSOR_LEFT);
104   if (p.x() > GetStringSize().width())
105     return EdgeSelectionModel(CURSOR_RIGHT);
106
107   int caret_pos = 0, trailing = 0;
108   pango_layout_xy_to_index(layout_, p.x() * PANGO_SCALE, p.y() * PANGO_SCALE,
109                            &caret_pos, &trailing);
110
111   DCHECK_GE(trailing, 0);
112   if (trailing > 0) {
113     caret_pos = g_utf8_offset_to_pointer(layout_text_ + caret_pos,
114                                          trailing) - layout_text_;
115     DCHECK_LE(static_cast<size_t>(caret_pos), strlen(layout_text_));
116   }
117
118   return SelectionModel(LayoutIndexToTextIndex(caret_pos),
119                         (trailing > 0) ? CURSOR_BACKWARD : CURSOR_FORWARD);
120 }
121
122 std::vector<RenderText::FontSpan> RenderTextPango::GetFontSpansForTesting() {
123   EnsureLayout();
124
125   std::vector<RenderText::FontSpan> spans;
126   for (GSList* it = current_line_->runs; it; it = it->next) {
127     PangoItem* item = reinterpret_cast<PangoLayoutRun*>(it->data)->item;
128     const int start = LayoutIndexToTextIndex(item->offset);
129     const int end = LayoutIndexToTextIndex(item->offset + item->length);
130     const Range range(start, end);
131
132     ScopedPangoFontDescription desc(pango_font_describe(item->analysis.font));
133     spans.push_back(RenderText::FontSpan(Font(desc.get()), range));
134   }
135
136   return spans;
137 }
138
139 int RenderTextPango::GetLayoutTextBaseline() {
140   EnsureLayout();
141   return PANGO_PIXELS(pango_layout_get_baseline(layout_));
142 }
143
144 SelectionModel RenderTextPango::AdjacentCharSelectionModel(
145     const SelectionModel& selection,
146     VisualCursorDirection direction) {
147   GSList* run = GetRunContainingCaret(selection);
148   if (!run) {
149     // The cursor is not in any run: we're at the visual and logical edge.
150     SelectionModel edge = EdgeSelectionModel(direction);
151     if (edge.caret_pos() == selection.caret_pos())
152       return edge;
153     else
154       run = (direction == CURSOR_RIGHT) ?
155           current_line_->runs : g_slist_last(current_line_->runs);
156   } else {
157     // If the cursor is moving within the current run, just move it by one
158     // grapheme in the appropriate direction.
159     PangoItem* item = reinterpret_cast<PangoLayoutRun*>(run->data)->item;
160     size_t caret = selection.caret_pos();
161     if (IsForwardMotion(direction, item)) {
162       if (caret < LayoutIndexToTextIndex(item->offset + item->length)) {
163         caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD);
164         return SelectionModel(caret, CURSOR_BACKWARD);
165       }
166     } else {
167       if (caret > LayoutIndexToTextIndex(item->offset)) {
168         caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD);
169         return SelectionModel(caret, CURSOR_FORWARD);
170       }
171     }
172     // The cursor is at the edge of a run; move to the visually adjacent run.
173     // TODO(xji): Keep a vector of runs to avoid using a singly-linked list.
174     run = (direction == CURSOR_RIGHT) ?
175         run->next : GSListPrevious(current_line_->runs, run);
176     if (!run)
177       return EdgeSelectionModel(direction);
178   }
179   PangoItem* item = reinterpret_cast<PangoLayoutRun*>(run->data)->item;
180   return IsForwardMotion(direction, item) ?
181       FirstSelectionModelInsideRun(item) : LastSelectionModelInsideRun(item);
182 }
183
184 SelectionModel RenderTextPango::AdjacentWordSelectionModel(
185     const SelectionModel& selection,
186     VisualCursorDirection direction) {
187   if (obscured())
188     return EdgeSelectionModel(direction);
189
190   base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
191   bool success = iter.Init();
192   DCHECK(success);
193   if (!success)
194     return selection;
195
196   SelectionModel cur(selection);
197   for (;;) {
198     cur = AdjacentCharSelectionModel(cur, direction);
199     GSList* run = GetRunContainingCaret(cur);
200     if (!run)
201       break;
202     PangoItem* item = reinterpret_cast<PangoLayoutRun*>(run->data)->item;
203     size_t cursor = cur.caret_pos();
204     if (IsForwardMotion(direction, item) ?
205         iter.IsEndOfWord(cursor) : iter.IsStartOfWord(cursor))
206       break;
207   }
208
209   return cur;
210 }
211
212 Range RenderTextPango::GetGlyphBounds(size_t index) {
213   EnsureLayout();
214   PangoRectangle pos;
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));
218 }
219
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>();
224
225   EnsureLayout();
226   int* ranges = NULL;
227   int n_ranges = 0;
228   pango_layout_line_get_x_ranges(current_line_,
229                                  TextIndexToLayoutIndex(range.GetMin()),
230                                  TextIndexToLayoutIndex(range.GetMax()),
231                                  &ranges,
232                                  &n_ranges);
233
234   const int height = GetStringSize().height();
235
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);
244   }
245   g_free(ranges);
246   return bounds;
247 }
248
249 size_t RenderTextPango::TextIndexToLayoutIndex(size_t index) const {
250   DCHECK(layout_);
251   ptrdiff_t offset = 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_);
256 }
257
258 size_t RenderTextPango::LayoutIndexToTextIndex(size_t index) const {
259   DCHECK(layout_);
260   const char* layout_pointer = layout_text_ + index;
261   const long offset = g_utf8_pointer_to_offset(layout_text_, layout_pointer);
262   return UTF16OffsetToIndex(text(), 0, offset);
263 }
264
265 bool RenderTextPango::IsValidCursorIndex(size_t index) {
266   if (index == 0 || index == text().length())
267     return true;
268   if (!IsValidLogicalIndex(index))
269     return false;
270
271   EnsureLayout();
272   ptrdiff_t offset = UTF16IndexToOffset(text(), 0, index);
273   // Check that the index is marked as a legitimate cursor position by Pango.
274   return offset < num_log_attrs_ && log_attrs_[offset].is_cursor_position;
275 }
276
277 void RenderTextPango::ResetLayout() {
278   // set_cached_bounds_and_offset_valid(false) is done in RenderText for every
279   // operation that triggers ResetLayout().
280   if (layout_) {
281     // TODO(msw): Keep |layout_| across text changes, etc.; it can be re-used.
282     g_object_unref(layout_);
283     layout_ = NULL;
284   }
285   if (current_line_) {
286     pango_layout_line_unref(current_line_);
287     current_line_ = NULL;
288   }
289   if (log_attrs_) {
290     g_free(log_attrs_);
291     log_attrs_ = NULL;
292     num_log_attrs_ = 0;
293   }
294   layout_text_ = NULL;
295 }
296
297 void RenderTextPango::EnsureLayout() {
298   if (layout_ == NULL) {
299     cairo_surface_t* surface =
300         cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0);
301     CHECK_EQ(CAIRO_STATUS_SUCCESS, cairo_surface_status(surface));
302     cairo_t* cr = cairo_create(surface);
303     CHECK_EQ(CAIRO_STATUS_SUCCESS, cairo_status(cr));
304
305     layout_ = pango_cairo_create_layout(cr);
306     CHECK_NE(static_cast<PangoLayout*>(NULL), layout_);
307     cairo_destroy(cr);
308     cairo_surface_destroy(surface);
309
310     SetupPangoLayoutWithFontDescription(layout_,
311                                         GetLayoutText(),
312                                         font_list().GetFontDescriptionString(),
313                                         0,
314                                         GetTextDirection(),
315                                         Canvas::DefaultCanvasTextAlignment());
316
317     // No width set so that the x-axis position is relative to the start of the
318     // text. ToViewPoint and ToTextPoint take care of the position conversion
319     // between text space and view spaces.
320     pango_layout_set_width(layout_, -1);
321     // TODO(xji): If RenderText will be used for displaying purpose, such as
322     // label, we will need to remove the single-line-mode setting.
323     pango_layout_set_single_paragraph_mode(layout_, true);
324
325     layout_text_ = pango_layout_get_text(layout_);
326     SetupPangoAttributes(layout_);
327
328     current_line_ = pango_layout_get_line_readonly(layout_, 0);
329     CHECK_NE(static_cast<PangoLayoutLine*>(NULL), current_line_);
330     pango_layout_line_ref(current_line_);
331
332     pango_layout_get_log_attrs(layout_, &log_attrs_, &num_log_attrs_);
333   }
334 }
335
336 void RenderTextPango::SetupPangoAttributes(PangoLayout* layout) {
337   PangoAttrList* attrs = pango_attr_list_new();
338
339   // Splitting text runs to accommodate styling can break Arabic glyph shaping.
340   // Only split text runs as needed for bold and italic font styles changes.
341   BreakList<bool>::const_iterator bold = styles()[BOLD].breaks().begin();
342   BreakList<bool>::const_iterator italic = styles()[ITALIC].breaks().begin();
343   while (bold != styles()[BOLD].breaks().end() &&
344          italic != styles()[ITALIC].breaks().end()) {
345     const int style = (bold->second ? Font::BOLD : 0) |
346                       (italic->second ? Font::ITALIC : 0);
347     const size_t bold_end = styles()[BOLD].GetRange(bold).end();
348     const size_t italic_end = styles()[ITALIC].GetRange(italic).end();
349     const size_t style_end = std::min(bold_end, italic_end);
350     if (style != font_list().GetFontStyle()) {
351       FontList derived_font_list = font_list().DeriveWithStyle(style);
352       ScopedPangoFontDescription desc(pango_font_description_from_string(
353           derived_font_list.GetFontDescriptionString().c_str()));
354
355       PangoAttribute* pango_attr = pango_attr_font_desc_new(desc.get());
356       pango_attr->start_index =
357           TextIndexToLayoutIndex(std::max(bold->first, italic->first));
358       pango_attr->end_index = TextIndexToLayoutIndex(style_end);
359       pango_attr_list_insert(attrs, pango_attr);
360     }
361     bold += bold_end == style_end ? 1 : 0;
362     italic += italic_end == style_end ? 1 : 0;
363   }
364   DCHECK(bold == styles()[BOLD].breaks().end());
365   DCHECK(italic == styles()[ITALIC].breaks().end());
366
367   pango_layout_set_attributes(layout, attrs);
368   pango_attr_list_unref(attrs);
369 }
370
371 void RenderTextPango::DrawVisualText(Canvas* canvas) {
372   DCHECK(layout_);
373
374   // Skia will draw glyphs with respect to the baseline.
375   Vector2d offset(GetLineOffset(0) + Vector2d(0, GetLayoutTextBaseline()));
376
377   SkScalar x = SkIntToScalar(offset.x());
378   SkScalar y = SkIntToScalar(offset.y());
379
380   std::vector<SkPoint> pos;
381   std::vector<uint16> glyphs;
382
383   internal::SkiaTextRenderer renderer(canvas);
384   ApplyFadeEffects(&renderer);
385   ApplyTextShadows(&renderer);
386
387   // TODO(derat): Use font-specific params: http://crbug.com/125235
388   const FontRenderParams& render_params = GetDefaultFontRenderParams();
389   const bool use_subpixel_rendering =
390       render_params.subpixel_rendering !=
391           FontRenderParams::SUBPIXEL_RENDERING_NONE;
392   renderer.SetFontSmoothingSettings(
393       render_params.antialiasing,
394       use_subpixel_rendering && !background_is_transparent(),
395       render_params.subpixel_positioning);
396
397   SkPaint::Hinting skia_hinting = SkPaint::kNormal_Hinting;
398   switch (render_params.hinting) {
399     case FontRenderParams::HINTING_NONE:
400       skia_hinting = SkPaint::kNo_Hinting;
401       break;
402     case FontRenderParams::HINTING_SLIGHT:
403       skia_hinting = SkPaint::kSlight_Hinting;
404       break;
405     case FontRenderParams::HINTING_MEDIUM:
406       skia_hinting = SkPaint::kNormal_Hinting;
407       break;
408     case FontRenderParams::HINTING_FULL:
409       skia_hinting = SkPaint::kFull_Hinting;
410       break;
411   }
412   renderer.SetFontHinting(skia_hinting);
413
414   // Temporarily apply composition underlines and selection colors.
415   ApplyCompositionAndSelectionStyles();
416
417   internal::StyleIterator style(colors(), styles());
418   for (GSList* it = current_line_->runs; it; it = it->next) {
419     PangoLayoutRun* run = reinterpret_cast<PangoLayoutRun*>(it->data);
420     int glyph_count = run->glyphs->num_glyphs;
421     // TODO(msw): Skip painting runs outside the display rect area, like Win.
422     if (glyph_count == 0)
423       continue;
424
425     ScopedPangoFontDescription desc(
426         pango_font_describe(run->item->analysis.font));
427
428     const std::string family_name =
429         pango_font_description_get_family(desc.get());
430     renderer.SetTextSize(GetPangoFontSizeInPixels(desc.get()));
431
432     glyphs.resize(glyph_count);
433     pos.resize(glyph_count);
434
435     // Track the current glyph and the glyph at the start of its styled range.
436     int glyph_index = 0;
437     int style_start_glyph_index = glyph_index;
438
439     // Track the x-coordinates for each styled range (|x| marks the current).
440     SkScalar style_start_x = x;
441
442     // Track the current style and its text (not layout) index range.
443     style.UpdatePosition(GetGlyphTextIndex(run, style_start_glyph_index));
444     Range style_range = style.GetRange();
445
446     do {
447       const PangoGlyphInfo& glyph = run->glyphs->glyphs[glyph_index];
448       glyphs[glyph_index] = static_cast<uint16>(glyph.glyph);
449       // Use pango_units_to_double() rather than PANGO_PIXELS() here, so units
450       // are not rounded to the pixel grid if subpixel positioning is enabled.
451       pos[glyph_index].set(x + pango_units_to_double(glyph.geometry.x_offset),
452                            y + pango_units_to_double(glyph.geometry.y_offset));
453       x += pango_units_to_double(glyph.geometry.width);
454
455       ++glyph_index;
456       const size_t glyph_text_index = (glyph_index == glyph_count) ?
457           style_range.end() : GetGlyphTextIndex(run, glyph_index);
458       if (!IndexInRange(style_range, glyph_text_index)) {
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     } while (glyph_index < glyph_count);
481   }
482
483   renderer.EndDiagonalStrike();
484
485   // Undo the temporarily applied composition underlines and selection colors.
486   UndoCompositionAndSelectionStyles();
487 }
488
489 GSList* RenderTextPango::GetRunContainingCaret(
490     const SelectionModel& caret) const {
491   size_t position = TextIndexToLayoutIndex(caret.caret_pos());
492   LogicalCursorDirection affinity = caret.caret_affinity();
493   GSList* run = current_line_->runs;
494   while (run) {
495     PangoItem* item = reinterpret_cast<PangoLayoutRun*>(run->data)->item;
496     Range item_range(item->offset, item->offset + item->length);
497     if (RangeContainsCaret(item_range, position, affinity))
498       return run;
499     run = run->next;
500   }
501   return NULL;
502 }
503
504 SelectionModel RenderTextPango::FirstSelectionModelInsideRun(
505     const PangoItem* item) {
506   size_t caret = IndexOfAdjacentGrapheme(
507       LayoutIndexToTextIndex(item->offset), CURSOR_FORWARD);
508   return SelectionModel(caret, CURSOR_BACKWARD);
509 }
510
511 SelectionModel RenderTextPango::LastSelectionModelInsideRun(
512     const PangoItem* item) {
513   size_t caret = IndexOfAdjacentGrapheme(
514       LayoutIndexToTextIndex(item->offset + item->length), CURSOR_BACKWARD);
515   return SelectionModel(caret, CURSOR_FORWARD);
516 }
517
518 size_t RenderTextPango::GetGlyphTextIndex(PangoLayoutRun* run,
519                                           int glyph_index) const {
520   return LayoutIndexToTextIndex(run->item->offset +
521                                 run->glyphs->log_clusters[glyph_index]);
522 }
523
524 RenderText* RenderText::CreateInstance() {
525   return new RenderTextPango;
526 }
527
528 }  // namespace gfx