summaryrefslogtreecommitdiff
path: root/chromium/ui/gfx/pango_util.cc
blob: 3f96d4b140d6f5e76129da7d862dc02a77f6f9de (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
// 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/pango_util.h"

#include <cairo/cairo.h>
#include <fontconfig/fontconfig.h>
#include <pango/pango.h>
#include <pango/pangocairo.h>
#include <string>

#include <algorithm>
#include <map>
#include <vector>

#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/font.h"
#include "ui/gfx/font_render_params_linux.h"
#include "ui/gfx/platform_font_pango.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/text_utils.h"

#if defined(TOOLKIT_GTK)
#include <gdk/gdk.h>
#endif

namespace gfx {

namespace {

// Marker for accelerators in the text.
const gunichar kAcceleratorChar = '&';

// Multiply by the text height to determine how much text should be faded
// when elliding.
const double kFadeWidthFactor = 1.5;

// End state of the elliding fade.
const double kFadeFinalAlpha = 0.15;

// Return |cairo_font_options|. If needed, allocate and update it.
// TODO(derat): Return font-specific options: http://crbug.com/125235
cairo_font_options_t* GetCairoFontOptions() {
  // Font settings that we initialize once and then use when drawing text.
  static cairo_font_options_t* cairo_font_options = NULL;
  if (cairo_font_options)
    return cairo_font_options;

  cairo_font_options = cairo_font_options_create();

  const FontRenderParams& params = GetDefaultFontRenderParams();
  FontRenderParams::SubpixelRendering subpixel = params.subpixel_rendering;
  if (!params.antialiasing) {
    cairo_font_options_set_antialias(cairo_font_options, CAIRO_ANTIALIAS_NONE);
  } else if (subpixel == FontRenderParams::SUBPIXEL_RENDERING_NONE) {
    cairo_font_options_set_antialias(cairo_font_options, CAIRO_ANTIALIAS_GRAY);
  } else {
    cairo_font_options_set_antialias(cairo_font_options,
                                     CAIRO_ANTIALIAS_SUBPIXEL);
    cairo_subpixel_order_t cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_DEFAULT;
    if (subpixel == FontRenderParams::SUBPIXEL_RENDERING_RGB)
      cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_RGB;
    else if (subpixel == FontRenderParams::SUBPIXEL_RENDERING_BGR)
      cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_BGR;
    else if (subpixel == FontRenderParams::SUBPIXEL_RENDERING_VRGB)
      cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_VRGB;
    else if (subpixel == FontRenderParams::SUBPIXEL_RENDERING_VBGR)
      cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_VBGR;
    else
      NOTREACHED() << "Unhandled subpixel rendering type " << subpixel;
    cairo_font_options_set_subpixel_order(cairo_font_options,
                                          cairo_subpixel_order);
  }

  if (params.hinting == FontRenderParams::HINTING_NONE ||
      params.subpixel_positioning) {
    cairo_font_options_set_hint_style(cairo_font_options,
                                      CAIRO_HINT_STYLE_NONE);
    cairo_font_options_set_hint_metrics(cairo_font_options,
                                        CAIRO_HINT_METRICS_OFF);
  } else {
    cairo_hint_style_t cairo_hint_style = CAIRO_HINT_STYLE_DEFAULT;
    if (params.hinting == FontRenderParams::HINTING_SLIGHT)
      cairo_hint_style = CAIRO_HINT_STYLE_SLIGHT;
    else if (params.hinting == FontRenderParams::HINTING_MEDIUM)
      cairo_hint_style = CAIRO_HINT_STYLE_MEDIUM;
    else if (params.hinting == FontRenderParams::HINTING_FULL)
      cairo_hint_style = CAIRO_HINT_STYLE_FULL;
    else
      NOTREACHED() << "Unhandled hinting style " << params.hinting;
    cairo_font_options_set_hint_style(cairo_font_options, cairo_hint_style);
    cairo_font_options_set_hint_metrics(cairo_font_options,
                                        CAIRO_HINT_METRICS_ON);
  }

  return cairo_font_options;
}

// Returns the number of pixels in a point.
// - multiply a point size by this to get pixels ("device units")
// - divide a pixel size by this to get points
float GetPixelsInPoint() {
  static float pixels_in_point = 1.0;
  static bool determined_value = false;

  if (!determined_value) {
    // http://goo.gl/UIh5m: "This is a scale factor between points specified in
    // a PangoFontDescription and Cairo units.  The default value is 96, meaning
    // that a 10 point font will be 13 units high. (10 * 96. / 72. = 13.3)."
    double pango_dpi = GetPangoResolution();
    if (pango_dpi <= 0)
      pango_dpi = 96.0;
    pixels_in_point = pango_dpi / 72.0;  // 72 points in an inch
    determined_value = true;
  }

  return pixels_in_point;
}

}  // namespace

PangoContext* GetPangoContext() {
#if defined(TOOLKIT_GTK)
  return gdk_pango_context_get();
#else
  PangoFontMap* font_map = pango_cairo_font_map_get_default();
  return pango_font_map_create_context(font_map);
#endif
}

double GetPangoResolution() {
  static double resolution;
  static bool determined_resolution = false;
  if (!determined_resolution) {
    determined_resolution = true;
    PangoContext* default_context = GetPangoContext();
    resolution = pango_cairo_context_get_resolution(default_context);
    g_object_unref(default_context);
  }
  return resolution;
}

void DrawTextOntoCairoSurface(cairo_t* cr,
                              const base::string16& text,
                              const gfx::Font& font,
                              const gfx::Rect& bounds,
                              const gfx::Rect& clip,
                              SkColor text_color,
                              int flags) {
  PangoLayout* layout = pango_cairo_create_layout(cr);
  base::i18n::TextDirection text_direction =
      base::i18n::GetFirstStrongCharacterDirection(text);
  DCHECK(!bounds.IsEmpty());

  gfx::SetupPangoLayout(
      layout, text, font, bounds.width(), text_direction, flags);

  pango_layout_set_height(layout, bounds.height() * PANGO_SCALE);

  cairo_save(cr);
  cairo_rectangle(cr, clip.x(), clip.y(), clip.width(), clip.height());
  cairo_clip(cr);

  int width = 0, height = 0;
  pango_layout_get_pixel_size(layout, &width, &height);
  Rect text_rect(bounds.x(), bounds.y(), width, height);
  // Vertically center |text_rect| in |bounds|.
  text_rect += gfx::Vector2d(0, (bounds.height() - text_rect.height()) / 2);

  DrawPangoLayout(cr, layout, font, bounds, text_rect,
                  text_color, text_direction, flags);

  cairo_restore(cr);
  g_object_unref(layout);
}

// Pass a width greater than 0 to force wrapping and eliding.
static void SetupPangoLayoutWithoutFont(
    PangoLayout* layout,
    const base::string16& text,
    int width,
    base::i18n::TextDirection text_direction,
    int flags) {
  cairo_font_options_t* cairo_font_options = GetCairoFontOptions();

  // If we got an explicit request to turn off subpixel rendering, disable it on
  // a copy of the static font options object.
  bool copied_cairo_font_options = false;
  if ((flags & Canvas::NO_SUBPIXEL_RENDERING) &&
      (cairo_font_options_get_antialias(cairo_font_options) ==
       CAIRO_ANTIALIAS_SUBPIXEL)) {
    cairo_font_options = cairo_font_options_copy(cairo_font_options);
    copied_cairo_font_options = true;
    cairo_font_options_set_antialias(cairo_font_options, CAIRO_ANTIALIAS_GRAY);
  }

  // This needs to be done early on; it has no effect when called just before
  // pango_cairo_show_layout().
  pango_cairo_context_set_font_options(
      pango_layout_get_context(layout), cairo_font_options);

  if (copied_cairo_font_options) {
    cairo_font_options_destroy(cairo_font_options);
    cairo_font_options = NULL;
  }

  // Set Pango's base text direction explicitly from |text_direction|.
  pango_layout_set_auto_dir(layout, FALSE);
  pango_context_set_base_dir(pango_layout_get_context(layout),
      (text_direction == base::i18n::RIGHT_TO_LEFT ?
       PANGO_DIRECTION_RTL : PANGO_DIRECTION_LTR));

  if (width > 0)
    pango_layout_set_width(layout, width * PANGO_SCALE);

  if (flags & Canvas::TEXT_ALIGN_CENTER) {
    // We don't support center aligned w/ eliding.
    DCHECK(gfx::Canvas::NO_ELLIPSIS);
    pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);
  } else if (flags & Canvas::TEXT_ALIGN_RIGHT) {
    pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT);
  }

  if (flags & Canvas::NO_ELLIPSIS) {
    pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE);
    if (flags & Canvas::MULTI_LINE) {
      pango_layout_set_wrap(layout,
          (flags & Canvas::CHARACTER_BREAK) ?
              PANGO_WRAP_WORD_CHAR : PANGO_WRAP_WORD);
    }
  } else if (text_direction == base::i18n::RIGHT_TO_LEFT) {
    pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);
  } else {
    // Fading the text will be handled in the draw operation.
    // Ensure that the text is only on one line.
    pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE);
    pango_layout_set_width(layout, -1);
  }

  // Set the resolution to match that used by Gtk. If we don't set the
  // resolution and the resolution differs from the default, Gtk and Chrome end
  // up drawing at different sizes.
  double resolution = GetPangoResolution();
  if (resolution > 0) {
    pango_cairo_context_set_resolution(pango_layout_get_context(layout),
                                       resolution);
  }

  // Set text and accelerator character if needed.
  if (flags & Canvas::SHOW_PREFIX) {
    // Escape the text string to be used as markup.
    std::string utf8 = UTF16ToUTF8(text);
    gchar* escaped_text = g_markup_escape_text(utf8.c_str(), utf8.size());
    pango_layout_set_markup_with_accel(layout,
                                       escaped_text,
                                       strlen(escaped_text),
                                       kAcceleratorChar, NULL);
    g_free(escaped_text);
  } else {
    std::string utf8;

    // Remove the ampersand character.  A double ampersand is output as
    // a single ampersand.
    if (flags & Canvas::HIDE_PREFIX) {
      DCHECK_EQ(1, g_unichar_to_utf8(kAcceleratorChar, NULL));
      base::string16 accelerator_removed =
          RemoveAcceleratorChar(text, static_cast<char16>(kAcceleratorChar),
                                NULL, NULL);
      utf8 = UTF16ToUTF8(accelerator_removed);
    } else {
      utf8 = UTF16ToUTF8(text);
    }

    pango_layout_set_text(layout, utf8.data(), utf8.size());
  }
}

void SetupPangoLayout(PangoLayout* layout,
                      const base::string16& text,
                      const Font& font,
                      int width,
                      base::i18n::TextDirection text_direction,
                      int flags) {
  SetupPangoLayoutWithoutFont(layout, text, width, text_direction, flags);

  ScopedPangoFontDescription desc(font.GetNativeFont());
  pango_layout_set_font_description(layout, desc.get());
}

void SetupPangoLayoutWithFontDescription(
    PangoLayout* layout,
    const base::string16& text,
    const std::string& font_description,
    int width,
    base::i18n::TextDirection text_direction,
    int flags) {
  SetupPangoLayoutWithoutFont(layout, text, width, text_direction, flags);

  ScopedPangoFontDescription desc(
      pango_font_description_from_string(font_description.c_str()));
  pango_layout_set_font_description(layout, desc.get());
}

void DrawPangoLayout(cairo_t* cr,
                     PangoLayout* layout,
                     const Font& font,
                     const gfx::Rect& bounds,
                     const gfx::Rect& text_rect,
                     SkColor text_color,
                     base::i18n::TextDirection text_direction,
                     int flags) {
  double r = SkColorGetR(text_color) / 255.0,
         g = SkColorGetG(text_color) / 255.0,
         b = SkColorGetB(text_color) / 255.0,
         a = SkColorGetA(text_color) / 255.0;

  cairo_pattern_t* pattern = NULL;

  cairo_save(cr);

  // If we're not eliding, use a fixed color.
  // Otherwise, create a gradient pattern to use as the source.
  if (text_direction == base::i18n::RIGHT_TO_LEFT ||
      (flags & gfx::Canvas::NO_ELLIPSIS) ||
      text_rect.width() <= bounds.width()) {
    cairo_set_source_rgba(cr, r, g, b, a);
  } else {
    // Fade to semi-transparent to elide.
    int fade_width = static_cast<double>(text_rect.height()) * kFadeWidthFactor;
    if (fade_width > bounds.width() / 2) {
      // Don't fade more than half the text.
      fade_width = bounds.width() / 2;
    }
    int fade_x = bounds.x() + bounds.width() - fade_width;

    pattern = cairo_pattern_create_linear(
        fade_x, bounds.y(), bounds.x() + bounds.width(), bounds.y());
    cairo_pattern_add_color_stop_rgba(pattern, 0, r, g, b, a);
    cairo_pattern_add_color_stop_rgba(pattern, 1, r, g, b, kFadeFinalAlpha);
    cairo_set_source(cr, pattern);
  }

  cairo_move_to(cr, text_rect.x(), text_rect.y());
  pango_cairo_show_layout(cr, layout);

  if (font.GetStyle() & gfx::Font::UNDERLINE) {
    gfx::PlatformFontPango* platform_font =
        static_cast<gfx::PlatformFontPango*>(font.platform_font());
    DrawPangoTextUnderline(cr, platform_font, 0.0, text_rect);
  }

  if (pattern)
    cairo_pattern_destroy(pattern);

  cairo_restore(cr);
}

void DrawPangoTextUnderline(cairo_t* cr,
                            gfx::PlatformFontPango* platform_font,
                            double extra_edge_width,
                            const Rect& text_rect) {
  const double underline_y =
      static_cast<double>(text_rect.y()) + text_rect.height() +
      platform_font->underline_position();
  cairo_set_line_width(
      cr, platform_font->underline_thickness() + 2 * extra_edge_width);
  cairo_move_to(cr,
                text_rect.x() - extra_edge_width,
                underline_y);
  cairo_line_to(cr,
                text_rect.x() + text_rect.width() + extra_edge_width,
                underline_y);
  cairo_stroke(cr);
}

size_t GetPangoFontSizeInPixels(PangoFontDescription* pango_font) {
  size_t size_in_pixels = pango_font_description_get_size(pango_font);
  if (pango_font_description_get_size_is_absolute(pango_font)) {
    // If the size is absolute, then it's in Pango units rather than points.
    // There are PANGO_SCALE Pango units in a device unit (pixel).
    size_in_pixels /= PANGO_SCALE;
  } else {
    // Otherwise, we need to convert from points.
    size_in_pixels = size_in_pixels * GetPixelsInPoint() / PANGO_SCALE;
  }
  return size_in_pixels;
}

PangoFontMetrics* GetPangoFontMetrics(PangoFontDescription* desc) {
  static std::map<int, PangoFontMetrics*>* desc_to_metrics = NULL;
  static PangoContext* context = NULL;

  if (!context) {
    context = GetPangoContext();
    pango_context_set_language(context, pango_language_get_default());
  }

  if (!desc_to_metrics)
    desc_to_metrics = new std::map<int, PangoFontMetrics*>();

  const int desc_hash = pango_font_description_hash(desc);
  std::map<int, PangoFontMetrics*>::iterator i =
      desc_to_metrics->find(desc_hash);

  if (i == desc_to_metrics->end()) {
    PangoFontMetrics* metrics = pango_context_get_metrics(context, desc, NULL);
    desc_to_metrics->insert(std::make_pair(desc_hash, metrics));
    return metrics;
  }
  return i->second;
}

}  // namespace gfx