summaryrefslogtreecommitdiffstats
path: root/ui/gfx/render_text_linux.cc
blob: 4b148193f0c8ab2a2326db778c119d64ee74e5eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/render_text_linux.h"

#include <pango/pangocairo.h>
#include <algorithm>
#include <string>
#include <vector>

#include "base/i18n/break_iterator.h"
#include "base/logging.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "ui/base/text/utf16_indexing.h"
#include "ui/gfx/canvas_skia.h"
#include "ui/gfx/font.h"
#include "ui/gfx/pango_util.h"

namespace gfx {

namespace {

// Returns the preceding element in a GSList (O(n)).
GSList* GSListPrevious(GSList* head, GSList* item) {
  GSList* prev = NULL;
  for (GSList* cur = head; cur != item; cur = cur->next) {
    DCHECK(cur);
    prev = cur;
  }
  return prev;
}

// Returns true if the given visual cursor |direction| is logically forward
// motion in the given Pango |item|.
bool IsForwardMotion(VisualCursorDirection direction, const PangoItem* item) {
  bool rtl = item->analysis.level & 1;
  return rtl == (direction == CURSOR_LEFT);
}

// Checks whether |range| contains |index|. This is not the same as calling
// |range.Contains(ui::Range(index))| - as that would return true when
// |index| == |range.end()|.
bool IndexInRange(const ui::Range& range, size_t index) {
  return index >= range.start() && index < range.end();
}

}  // namespace

// TODO(xji): index saved in upper layer is utf16 index. Pango uses utf8 index.
// Since caret_pos is used internally, we could save utf8 index for caret_pos
// to avoid conversion.

RenderTextLinux::RenderTextLinux()
    : layout_(NULL),
      current_line_(NULL),
      log_attrs_(NULL),
      num_log_attrs_(0),
      layout_text_(NULL),
      layout_text_len_(0) {
}

RenderTextLinux::~RenderTextLinux() {
  ResetLayout();
}

RenderText* RenderText::CreateRenderText() {
  return new RenderTextLinux;
}

base::i18n::TextDirection RenderTextLinux::GetTextDirection() {
  EnsureLayout();

  PangoDirection base_dir = pango_find_base_dir(layout_text_, -1);
  if (base_dir == PANGO_DIRECTION_RTL || base_dir == PANGO_DIRECTION_WEAK_RTL)
    return base::i18n::RIGHT_TO_LEFT;
  return base::i18n::LEFT_TO_RIGHT;
}

Size RenderTextLinux::GetStringSize() {
  EnsureLayout();
  int width = 0, height = 0;
  pango_layout_get_pixel_size(layout_, &width, &height);
  return Size(width, height);
}

SelectionModel RenderTextLinux::FindCursorPosition(const Point& point) {
  EnsureLayout();

  if (text().empty())
    return SelectionModel(0, CURSOR_FORWARD);

  Point p(ToTextPoint(point));

  // When the point is outside of text, return HOME/END position.
  if (p.x() < 0)
    return EdgeSelectionModel(CURSOR_LEFT);
  else if (p.x() > GetStringSize().width())
    return EdgeSelectionModel(CURSOR_RIGHT);

  int caret_pos = 0, trailing = 0;
  pango_layout_xy_to_index(layout_, p.x() * PANGO_SCALE, p.y() * PANGO_SCALE,
                           &caret_pos, &trailing);

  DCHECK_GE(trailing, 0);
  if (trailing > 0) {
    caret_pos = g_utf8_offset_to_pointer(layout_text_ + caret_pos,
                                         trailing) - layout_text_;
    DCHECK_LE(static_cast<size_t>(caret_pos), layout_text_len_);
  }

  return SelectionModel(LayoutIndexToTextIndex(caret_pos),
                        (trailing > 0) ? CURSOR_BACKWARD : CURSOR_FORWARD);
}

SelectionModel RenderTextLinux::AdjacentCharSelectionModel(
    const SelectionModel& selection,
    VisualCursorDirection direction) {
  GSList* run = GetRunContainingCaret(selection);
  if (!run) {
    // The cursor is not in any run: we're at the visual and logical edge.
    SelectionModel edge = EdgeSelectionModel(direction);
    if (edge.caret_pos() == selection.caret_pos())
      return edge;
    else
      run = (direction == CURSOR_RIGHT) ?
          current_line_->runs : g_slist_last(current_line_->runs);
  } else {
    // If the cursor is moving within the current run, just move it by one
    // grapheme in the appropriate direction.
    PangoItem* item = reinterpret_cast<PangoLayoutRun*>(run->data)->item;
    size_t caret = selection.caret_pos();
    if (IsForwardMotion(direction, item)) {
      if (caret < LayoutIndexToTextIndex(item->offset + item->length)) {
        caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD);
        return SelectionModel(caret, CURSOR_BACKWARD);
      }
    } else {
      if (caret > LayoutIndexToTextIndex(item->offset)) {
        caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD);
        return SelectionModel(caret, CURSOR_FORWARD);
      }
    }
    // The cursor is at the edge of a run; move to the visually adjacent run.
    // TODO(xji): Keep a vector of runs to avoid using a singly-linked list.
    run = (direction == CURSOR_RIGHT) ?
        run->next : GSListPrevious(current_line_->runs, run);
    if (!run)
      return EdgeSelectionModel(direction);
  }
  PangoItem* item = reinterpret_cast<PangoLayoutRun*>(run->data)->item;
  return IsForwardMotion(direction, item) ?
      FirstSelectionModelInsideRun(item) : LastSelectionModelInsideRun(item);
}

SelectionModel RenderTextLinux::AdjacentWordSelectionModel(
    const SelectionModel& selection,
    VisualCursorDirection direction) {
  if (is_obscured())
    return EdgeSelectionModel(direction);

  base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
  bool success = iter.Init();
  DCHECK(success);
  if (!success)
    return selection;

  SelectionModel cur(selection);
  for (;;) {
    cur = AdjacentCharSelectionModel(cur, direction);
    GSList* run = GetRunContainingCaret(cur);
    if (!run)
      break;
    PangoItem* item = reinterpret_cast<PangoLayoutRun*>(run->data)->item;
    size_t cursor = cur.caret_pos();
    if (IsForwardMotion(direction, item) ?
        iter.IsEndOfWord(cursor) : iter.IsStartOfWord(cursor))
      break;
  }

  return cur;
}

void RenderTextLinux::SetSelectionModel(const SelectionModel& model) {
  if (selection() != model.selection())
    selection_visual_bounds_.clear();

  RenderText::SetSelectionModel(model);
}

void RenderTextLinux::GetGlyphBounds(size_t index,
                                     ui::Range* xspan,
                                     int* height) {
  PangoRectangle pos;
  pango_layout_index_to_pos(layout_, TextIndexToLayoutIndex(index), &pos);
  *xspan = ui::Range(PANGO_PIXELS(pos.x), PANGO_PIXELS(pos.x + pos.width));
  *height = PANGO_PIXELS(pos.height);
}

std::vector<Rect> RenderTextLinux::GetSubstringBounds(ui::Range range) {
  DCHECK_LE(range.GetMax(), text().length());

  if (range.is_empty())
    return std::vector<Rect>();

  EnsureLayout();
  if (range == selection())
    return GetSelectionBounds();
  return CalculateSubstringBounds(range);
}

bool RenderTextLinux::IsCursorablePosition(size_t position) {
  if (position == 0 && text().empty())
    return true;

  EnsureLayout();
  ptrdiff_t offset = ui::UTF16IndexToOffset(text(), 0, position);
  return (offset < num_log_attrs_ && log_attrs_[offset].is_cursor_position);
}

void RenderTextLinux::ResetLayout() {
  // set_cached_bounds_and_offset_valid(false) is done in RenderText for every
  // operation that triggers ResetLayout().
  if (layout_) {
    g_object_unref(layout_);
    layout_ = NULL;
  }
  if (current_line_) {
    pango_layout_line_unref(current_line_);
    current_line_ = NULL;
  }
  if (log_attrs_) {
    g_free(log_attrs_);
    log_attrs_ = NULL;
    num_log_attrs_ = 0;
  }
  if (!selection_visual_bounds_.empty())
    selection_visual_bounds_.clear();
  layout_text_ = NULL;
  layout_text_len_ = 0;
}

void RenderTextLinux::EnsureLayout() {
  if (layout_ == NULL) {
    CanvasSkia canvas(display_rect().size(), false);
    skia::ScopedPlatformPaint scoped_platform_paint(canvas.sk_canvas());
    cairo_t* cr = scoped_platform_paint.GetPlatformSurface();

    layout_ = pango_cairo_create_layout(cr);
    SetupPangoLayoutWithFontDescription(
        layout_,
        GetDisplayText(),
        font_list().GetFontDescriptionString(),
        display_rect().width(),
        base::i18n::GetFirstStrongCharacterDirection(text()),
        CanvasSkia::DefaultCanvasTextAlignment());

    // No width set so that the x-axis position is relative to the start of the
    // text. ToViewPoint and ToTextPoint take care of the position conversion
    // between text space and view spaces.
    pango_layout_set_width(layout_, -1);
    // TODO(xji): If RenderText will be used for displaying purpose, such as
    // label, we will need to remove the single-line-mode setting.
    pango_layout_set_single_paragraph_mode(layout_, true);

    // These are used by SetupPangoAttributes.
    layout_text_ = pango_layout_get_text(layout_);
    layout_text_len_ = strlen(layout_text_);

    SetupPangoAttributes(layout_);

    current_line_ = pango_layout_get_line_readonly(layout_, 0);
    pango_layout_line_ref(current_line_);

    pango_layout_get_log_attrs(layout_, &log_attrs_, &num_log_attrs_);
  }
}

void RenderTextLinux::SetupPangoAttributes(PangoLayout* layout) {
  PangoAttrList* attrs = pango_attr_list_new();

  int default_font_style = font_list().GetFontStyle();
  for (StyleRanges::const_iterator i = style_ranges().begin();
       i < style_ranges().end(); ++i) {
    // In Pango, different fonts means different runs, and it breaks Arabic
    // shaping across run boundaries. So, set font only when it is different
    // from the default font.
    // TODO(xji): We'll eventually need to split up StyleRange into components
    // (ColorRange, FontRange, etc.) so that we can combine adjacent ranges
    // with the same Fonts (to avoid unnecessarily splitting up runs).
    if (i->font_style != default_font_style) {
      FontList derived_font_list = font_list().DeriveFontList(i->font_style);
      PangoFontDescription* desc = pango_font_description_from_string(
          derived_font_list.GetFontDescriptionString().c_str());

      PangoAttribute* pango_attr = pango_attr_font_desc_new(desc);
      pango_attr->start_index = TextIndexToLayoutIndex(i->range.start());
      pango_attr->end_index = TextIndexToLayoutIndex(i->range.end());
      pango_attr_list_insert(attrs, pango_attr);
      pango_font_description_free(desc);
    }
  }

  pango_layout_set_attributes(layout, attrs);
  pango_attr_list_unref(attrs);
}

void RenderTextLinux::DrawVisualText(Canvas* canvas) {
  DCHECK(layout_);

  Point offset(GetOriginForSkiaDrawing());
  SkScalar x = SkIntToScalar(offset.x());
  SkScalar y = SkIntToScalar(offset.y());

  std::vector<SkPoint> pos;
  std::vector<uint16> glyphs;

  StyleRanges styles(style_ranges());
  ApplyCompositionAndSelectionStyles(&styles);

  // Pre-calculate UTF8 indices from UTF16 indices.
  // TODO(asvitkine): Can we cache these?
  std::vector<ui::Range> style_ranges_utf8;
  style_ranges_utf8.reserve(styles.size());
  size_t start_index = 0;
  for (size_t i = 0; i < styles.size(); ++i) {
    size_t end_index = TextIndexToLayoutIndex(styles[i].range.end());
    style_ranges_utf8.push_back(ui::Range(start_index, end_index));
    start_index = end_index;
  }

  internal::SkiaTextRenderer renderer(canvas);
  ApplyFadeEffects(&renderer);
  renderer.SetFontSmoothingSettings(true, !background_is_transparent());

  for (GSList* it = current_line_->runs; it; it = it->next) {
    PangoLayoutRun* run = reinterpret_cast<PangoLayoutRun*>(it->data);
    int glyph_count = run->glyphs->num_glyphs;
    if (glyph_count == 0)
      continue;

    size_t run_start = run->item->offset;
    size_t first_glyph_byte_index = run_start + run->glyphs->log_clusters[0];
    size_t style_increment = IsForwardMotion(CURSOR_RIGHT, run->item) ? 1 : -1;

    // Find the initial style for this run.
    // TODO(asvitkine): Can we avoid looping here, e.g. by caching this per run?
    int style = -1;
    for (size_t i = 0; i < style_ranges_utf8.size(); ++i) {
      if (IndexInRange(style_ranges_utf8[i], first_glyph_byte_index)) {
        style = i;
        break;
      }
    }
    DCHECK_GE(style, 0);

    PangoFontDescription* native_font =
        pango_font_describe(run->item->analysis.font);

    const char* family_name = pango_font_description_get_family(native_font);
    SkAutoTUnref<SkTypeface> typeface(
        SkTypeface::CreateFromName(family_name, SkTypeface::kNormal));
    renderer.SetTypeface(typeface.get());
    renderer.SetTextSize(GetPangoFontSizeInPixels(native_font));

    pango_font_description_free(native_font);

    SkScalar glyph_x = x;
    SkScalar start_x = x;
    int start = 0;

    glyphs.resize(glyph_count);
    pos.resize(glyph_count);

    for (int i = 0; i < glyph_count; ++i) {
      const PangoGlyphInfo& glyph = run->glyphs->glyphs[i];
      glyphs[i] = static_cast<uint16>(glyph.glyph);
      pos[i].set(glyph_x + PANGO_PIXELS(glyph.geometry.x_offset),
                 y + PANGO_PIXELS(glyph.geometry.y_offset));
      glyph_x += PANGO_PIXELS(glyph.geometry.width);

      // If this glyph is beyond the current style, draw the glyphs so far and
      // advance to the next style.
      size_t glyph_byte_index = run_start + run->glyphs->log_clusters[i];
      DCHECK_GE(style, 0);
      DCHECK_LT(style, static_cast<int>(styles.size()));
      if (!IndexInRange(style_ranges_utf8[style], glyph_byte_index)) {
        // TODO(asvitkine): For cases like "fi", where "fi" is a single glyph
        //                  but can span multiple styles, Pango splits the
        //                  styles evenly over the glyph. We can do this too by
        //                  clipping and drawing the glyph several times.
        renderer.SetForegroundColor(styles[style].foreground);
        renderer.SetFontStyle(styles[style].font_style);
        renderer.DrawPosText(&pos[start], &glyphs[start], i - start);
        renderer.DrawDecorations(start_x, y, glyph_x - start_x, styles[style]);

        start = i;
        start_x = glyph_x;
        // Loop to find the next style, in case the glyph spans multiple styles.
        do {
          style += style_increment;
        } while (style >= 0 && style < static_cast<int>(styles.size()) &&
                 !IndexInRange(style_ranges_utf8[style], glyph_byte_index));
      }
    }

    // Draw the remaining glyphs.
    renderer.SetForegroundColor(styles[style].foreground);
    renderer.SetFontStyle(styles[style].font_style);
    renderer.DrawPosText(&pos[start], &glyphs[start], glyph_count - start);
    renderer.DrawDecorations(start_x, y, glyph_x - start_x, styles[style]);
    x = glyph_x;
  }
}

size_t RenderTextLinux::IndexOfAdjacentGrapheme(
    size_t index,
    LogicalCursorDirection direction) {
  if (index > text().length())
    return text().length();
  EnsureLayout();
  ptrdiff_t char_offset = ui::UTF16IndexToOffset(text(), 0, index);
  if (direction == CURSOR_BACKWARD) {
    if (char_offset > 0) {
      do {
        --char_offset;
      } while (char_offset > 0 && !log_attrs_[char_offset].is_cursor_position);
    }
  } else {  // direction == CURSOR_FORWARD
    if (char_offset < num_log_attrs_ - 1) {
      do {
        ++char_offset;
      } while (char_offset < num_log_attrs_ - 1 &&
               !log_attrs_[char_offset].is_cursor_position);
    }
  }
  return ui::UTF16OffsetToIndex(text(), 0, char_offset);
}

GSList* RenderTextLinux::GetRunContainingCaret(
    const SelectionModel& caret) const {
  size_t position = TextIndexToLayoutIndex(caret.caret_pos());
  LogicalCursorDirection affinity = caret.caret_affinity();
  GSList* run = current_line_->runs;
  while (run) {
    PangoItem* item = reinterpret_cast<PangoLayoutRun*>(run->data)->item;
    ui::Range item_range(item->offset, item->offset + item->length);
    if (RangeContainsCaret(item_range, position, affinity))
      return run;
    run = run->next;
  }
  return NULL;
}

SelectionModel RenderTextLinux::FirstSelectionModelInsideRun(
    const PangoItem* item) {
  size_t caret = IndexOfAdjacentGrapheme(
      LayoutIndexToTextIndex(item->offset), CURSOR_FORWARD);
  return SelectionModel(caret, CURSOR_BACKWARD);
}

SelectionModel RenderTextLinux::LastSelectionModelInsideRun(
    const PangoItem* item) {
  size_t caret = IndexOfAdjacentGrapheme(
      LayoutIndexToTextIndex(item->offset + item->length), CURSOR_BACKWARD);
  return SelectionModel(caret, CURSOR_FORWARD);
}

size_t RenderTextLinux::TextIndexToLayoutIndex(size_t text_index) const {
  // If the text is obscured then |layout_text_| is not the same as |text()|,
  // but whether or not the text is obscured, the character (code point) offset
  // in |layout_text_| is the same as that in |text()|.
  DCHECK(layout_);
  ptrdiff_t offset = ui::UTF16IndexToOffset(text(), 0, text_index);
  const char* layout_pointer = g_utf8_offset_to_pointer(layout_text_, offset);
  return (layout_pointer - layout_text_);
}

size_t RenderTextLinux::LayoutIndexToTextIndex(size_t layout_index) const {
  // See |TextIndexToLayoutIndex()|.
  DCHECK(layout_);
  const char* layout_pointer = layout_text_ + layout_index;
  long offset = g_utf8_pointer_to_offset(layout_text_, layout_pointer);
  return ui::UTF16OffsetToIndex(text(), 0, offset);
}

std::vector<Rect> RenderTextLinux::CalculateSubstringBounds(ui::Range range) {
  int* ranges;
  int n_ranges;
  pango_layout_line_get_x_ranges(
      current_line_,
      TextIndexToLayoutIndex(range.GetMin()),
      TextIndexToLayoutIndex(range.GetMax()),
      &ranges,
      &n_ranges);

  int height;
  pango_layout_get_pixel_size(layout_, NULL, &height);

  int y = (display_rect().height() - height) / 2;

  std::vector<Rect> bounds;
  for (int i = 0; i < n_ranges; ++i) {
    int x = PANGO_PIXELS(ranges[2 * i]);
    int width = PANGO_PIXELS(ranges[2 * i + 1]) - x;
    Rect rect(x, y, width, height);
    rect.set_origin(ToViewPoint(rect.origin()));
    bounds.push_back(rect);
  }
  g_free(ranges);
  return bounds;
}

std::vector<Rect> RenderTextLinux::GetSelectionBounds() {
  if (selection_visual_bounds_.empty())
    selection_visual_bounds_ = CalculateSubstringBounds(selection());
  return selection_visual_bounds_;
}

}  // namespace gfx