Home | History | Annotate | Download | only in gfx
      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/pango_util.h"
      6 
      7 #include <cairo/cairo.h>
      8 #include <fontconfig/fontconfig.h>
      9 #include <pango/pango.h>
     10 #include <pango/pangocairo.h>
     11 #include <string>
     12 
     13 #include <algorithm>
     14 #include <map>
     15 #include <vector>
     16 
     17 #include "base/logging.h"
     18 #include "base/strings/utf_string_conversions.h"
     19 #include "ui/gfx/canvas.h"
     20 #include "ui/gfx/font.h"
     21 #include "ui/gfx/font_render_params_linux.h"
     22 #include "ui/gfx/platform_font_pango.h"
     23 #include "ui/gfx/rect.h"
     24 #include "ui/gfx/text_utils.h"
     25 
     26 #if defined(TOOLKIT_GTK)
     27 #include <gdk/gdk.h>
     28 #endif
     29 
     30 namespace gfx {
     31 
     32 namespace {
     33 
     34 // Marker for accelerators in the text.
     35 const gunichar kAcceleratorChar = '&';
     36 
     37 // Multiply by the text height to determine how much text should be faded
     38 // when elliding.
     39 const double kFadeWidthFactor = 1.5;
     40 
     41 // End state of the elliding fade.
     42 const double kFadeFinalAlpha = 0.15;
     43 
     44 // Return |cairo_font_options|. If needed, allocate and update it.
     45 // TODO(derat): Return font-specific options: http://crbug.com/125235
     46 cairo_font_options_t* GetCairoFontOptions() {
     47   // Font settings that we initialize once and then use when drawing text.
     48   static cairo_font_options_t* cairo_font_options = NULL;
     49   if (cairo_font_options)
     50     return cairo_font_options;
     51 
     52   cairo_font_options = cairo_font_options_create();
     53 
     54   const FontRenderParams& params = GetDefaultFontRenderParams();
     55   FontRenderParams::SubpixelRendering subpixel = params.subpixel_rendering;
     56   if (!params.antialiasing) {
     57     cairo_font_options_set_antialias(cairo_font_options, CAIRO_ANTIALIAS_NONE);
     58   } else if (subpixel == FontRenderParams::SUBPIXEL_RENDERING_NONE) {
     59     cairo_font_options_set_antialias(cairo_font_options, CAIRO_ANTIALIAS_GRAY);
     60   } else {
     61     cairo_font_options_set_antialias(cairo_font_options,
     62                                      CAIRO_ANTIALIAS_SUBPIXEL);
     63     cairo_subpixel_order_t cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_DEFAULT;
     64     if (subpixel == FontRenderParams::SUBPIXEL_RENDERING_RGB)
     65       cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_RGB;
     66     else if (subpixel == FontRenderParams::SUBPIXEL_RENDERING_BGR)
     67       cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_BGR;
     68     else if (subpixel == FontRenderParams::SUBPIXEL_RENDERING_VRGB)
     69       cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_VRGB;
     70     else if (subpixel == FontRenderParams::SUBPIXEL_RENDERING_VBGR)
     71       cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_VBGR;
     72     else
     73       NOTREACHED() << "Unhandled subpixel rendering type " << subpixel;
     74     cairo_font_options_set_subpixel_order(cairo_font_options,
     75                                           cairo_subpixel_order);
     76   }
     77 
     78   if (params.hinting == FontRenderParams::HINTING_NONE ||
     79       params.subpixel_positioning) {
     80     cairo_font_options_set_hint_style(cairo_font_options,
     81                                       CAIRO_HINT_STYLE_NONE);
     82     cairo_font_options_set_hint_metrics(cairo_font_options,
     83                                         CAIRO_HINT_METRICS_OFF);
     84   } else {
     85     cairo_hint_style_t cairo_hint_style = CAIRO_HINT_STYLE_DEFAULT;
     86     if (params.hinting == FontRenderParams::HINTING_SLIGHT)
     87       cairo_hint_style = CAIRO_HINT_STYLE_SLIGHT;
     88     else if (params.hinting == FontRenderParams::HINTING_MEDIUM)
     89       cairo_hint_style = CAIRO_HINT_STYLE_MEDIUM;
     90     else if (params.hinting == FontRenderParams::HINTING_FULL)
     91       cairo_hint_style = CAIRO_HINT_STYLE_FULL;
     92     else
     93       NOTREACHED() << "Unhandled hinting style " << params.hinting;
     94     cairo_font_options_set_hint_style(cairo_font_options, cairo_hint_style);
     95     cairo_font_options_set_hint_metrics(cairo_font_options,
     96                                         CAIRO_HINT_METRICS_ON);
     97   }
     98 
     99   return cairo_font_options;
    100 }
    101 
    102 // Returns the number of pixels in a point.
    103 // - multiply a point size by this to get pixels ("device units")
    104 // - divide a pixel size by this to get points
    105 float GetPixelsInPoint() {
    106   static float pixels_in_point = 1.0;
    107   static bool determined_value = false;
    108 
    109   if (!determined_value) {
    110     // http://goo.gl/UIh5m: "This is a scale factor between points specified in
    111     // a PangoFontDescription and Cairo units.  The default value is 96, meaning
    112     // that a 10 point font will be 13 units high. (10 * 96. / 72. = 13.3)."
    113     double pango_dpi = GetPangoResolution();
    114     if (pango_dpi <= 0)
    115       pango_dpi = 96.0;
    116     pixels_in_point = pango_dpi / 72.0;  // 72 points in an inch
    117     determined_value = true;
    118   }
    119 
    120   return pixels_in_point;
    121 }
    122 
    123 }  // namespace
    124 
    125 PangoContext* GetPangoContext() {
    126 #if defined(TOOLKIT_GTK)
    127   return gdk_pango_context_get();
    128 #else
    129   PangoFontMap* font_map = pango_cairo_font_map_get_default();
    130   return pango_font_map_create_context(font_map);
    131 #endif
    132 }
    133 
    134 double GetPangoResolution() {
    135   static double resolution;
    136   static bool determined_resolution = false;
    137   if (!determined_resolution) {
    138     determined_resolution = true;
    139     PangoContext* default_context = GetPangoContext();
    140     resolution = pango_cairo_context_get_resolution(default_context);
    141     g_object_unref(default_context);
    142   }
    143   return resolution;
    144 }
    145 
    146 void DrawTextOntoCairoSurface(cairo_t* cr,
    147                               const base::string16& text,
    148                               const gfx::Font& font,
    149                               const gfx::Rect& bounds,
    150                               const gfx::Rect& clip,
    151                               SkColor text_color,
    152                               int flags) {
    153   PangoLayout* layout = pango_cairo_create_layout(cr);
    154   base::i18n::TextDirection text_direction =
    155       base::i18n::GetFirstStrongCharacterDirection(text);
    156   DCHECK(!bounds.IsEmpty());
    157 
    158   gfx::SetupPangoLayout(
    159       layout, text, font, bounds.width(), text_direction, flags);
    160 
    161   pango_layout_set_height(layout, bounds.height() * PANGO_SCALE);
    162 
    163   cairo_save(cr);
    164   cairo_rectangle(cr, clip.x(), clip.y(), clip.width(), clip.height());
    165   cairo_clip(cr);
    166 
    167   int width = 0, height = 0;
    168   pango_layout_get_pixel_size(layout, &width, &height);
    169   Rect text_rect(bounds.x(), bounds.y(), width, height);
    170   // Vertically center |text_rect| in |bounds|.
    171   text_rect += gfx::Vector2d(0, (bounds.height() - text_rect.height()) / 2);
    172 
    173   DrawPangoLayout(cr, layout, font, bounds, text_rect,
    174                   text_color, text_direction, flags);
    175 
    176   cairo_restore(cr);
    177   g_object_unref(layout);
    178 }
    179 
    180 // Pass a width greater than 0 to force wrapping and eliding.
    181 static void SetupPangoLayoutWithoutFont(
    182     PangoLayout* layout,
    183     const base::string16& text,
    184     int width,
    185     base::i18n::TextDirection text_direction,
    186     int flags) {
    187   cairo_font_options_t* cairo_font_options = GetCairoFontOptions();
    188 
    189   // If we got an explicit request to turn off subpixel rendering, disable it on
    190   // a copy of the static font options object.
    191   bool copied_cairo_font_options = false;
    192   if ((flags & Canvas::NO_SUBPIXEL_RENDERING) &&
    193       (cairo_font_options_get_antialias(cairo_font_options) ==
    194        CAIRO_ANTIALIAS_SUBPIXEL)) {
    195     cairo_font_options = cairo_font_options_copy(cairo_font_options);
    196     copied_cairo_font_options = true;
    197     cairo_font_options_set_antialias(cairo_font_options, CAIRO_ANTIALIAS_GRAY);
    198   }
    199 
    200   // This needs to be done early on; it has no effect when called just before
    201   // pango_cairo_show_layout().
    202   pango_cairo_context_set_font_options(
    203       pango_layout_get_context(layout), cairo_font_options);
    204 
    205   if (copied_cairo_font_options) {
    206     cairo_font_options_destroy(cairo_font_options);
    207     cairo_font_options = NULL;
    208   }
    209 
    210   // Set Pango's base text direction explicitly from |text_direction|.
    211   pango_layout_set_auto_dir(layout, FALSE);
    212   pango_context_set_base_dir(pango_layout_get_context(layout),
    213       (text_direction == base::i18n::RIGHT_TO_LEFT ?
    214        PANGO_DIRECTION_RTL : PANGO_DIRECTION_LTR));
    215 
    216   if (width > 0)
    217     pango_layout_set_width(layout, width * PANGO_SCALE);
    218 
    219   if (flags & Canvas::TEXT_ALIGN_CENTER) {
    220     // We don't support center aligned w/ eliding.
    221     DCHECK(gfx::Canvas::NO_ELLIPSIS);
    222     pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);
    223   } else if (flags & Canvas::TEXT_ALIGN_RIGHT) {
    224     pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT);
    225   }
    226 
    227   if (flags & Canvas::NO_ELLIPSIS) {
    228     pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE);
    229     if (flags & Canvas::MULTI_LINE) {
    230       pango_layout_set_wrap(layout,
    231           (flags & Canvas::CHARACTER_BREAK) ?
    232               PANGO_WRAP_WORD_CHAR : PANGO_WRAP_WORD);
    233     }
    234   } else if (text_direction == base::i18n::RIGHT_TO_LEFT) {
    235     pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);
    236   } else {
    237     // Fading the text will be handled in the draw operation.
    238     // Ensure that the text is only on one line.
    239     pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE);
    240     pango_layout_set_width(layout, -1);
    241   }
    242 
    243   // Set the resolution to match that used by Gtk. If we don't set the
    244   // resolution and the resolution differs from the default, Gtk and Chrome end
    245   // up drawing at different sizes.
    246   double resolution = GetPangoResolution();
    247   if (resolution > 0) {
    248     pango_cairo_context_set_resolution(pango_layout_get_context(layout),
    249                                        resolution);
    250   }
    251 
    252   // Set text and accelerator character if needed.
    253   if (flags & Canvas::SHOW_PREFIX) {
    254     // Escape the text string to be used as markup.
    255     std::string utf8 = UTF16ToUTF8(text);
    256     gchar* escaped_text = g_markup_escape_text(utf8.c_str(), utf8.size());
    257     pango_layout_set_markup_with_accel(layout,
    258                                        escaped_text,
    259                                        strlen(escaped_text),
    260                                        kAcceleratorChar, NULL);
    261     g_free(escaped_text);
    262   } else {
    263     std::string utf8;
    264 
    265     // Remove the ampersand character.  A double ampersand is output as
    266     // a single ampersand.
    267     if (flags & Canvas::HIDE_PREFIX) {
    268       DCHECK_EQ(1, g_unichar_to_utf8(kAcceleratorChar, NULL));
    269       base::string16 accelerator_removed =
    270           RemoveAcceleratorChar(text, static_cast<char16>(kAcceleratorChar),
    271                                 NULL, NULL);
    272       utf8 = UTF16ToUTF8(accelerator_removed);
    273     } else {
    274       utf8 = UTF16ToUTF8(text);
    275     }
    276 
    277     pango_layout_set_text(layout, utf8.data(), utf8.size());
    278   }
    279 }
    280 
    281 void SetupPangoLayout(PangoLayout* layout,
    282                       const base::string16& text,
    283                       const Font& font,
    284                       int width,
    285                       base::i18n::TextDirection text_direction,
    286                       int flags) {
    287   SetupPangoLayoutWithoutFont(layout, text, width, text_direction, flags);
    288 
    289   ScopedPangoFontDescription desc(font.GetNativeFont());
    290   pango_layout_set_font_description(layout, desc.get());
    291 }
    292 
    293 void SetupPangoLayoutWithFontDescription(
    294     PangoLayout* layout,
    295     const base::string16& text,
    296     const std::string& font_description,
    297     int width,
    298     base::i18n::TextDirection text_direction,
    299     int flags) {
    300   SetupPangoLayoutWithoutFont(layout, text, width, text_direction, flags);
    301 
    302   ScopedPangoFontDescription desc(
    303       pango_font_description_from_string(font_description.c_str()));
    304   pango_layout_set_font_description(layout, desc.get());
    305 }
    306 
    307 void DrawPangoLayout(cairo_t* cr,
    308                      PangoLayout* layout,
    309                      const Font& font,
    310                      const gfx::Rect& bounds,
    311                      const gfx::Rect& text_rect,
    312                      SkColor text_color,
    313                      base::i18n::TextDirection text_direction,
    314                      int flags) {
    315   double r = SkColorGetR(text_color) / 255.0,
    316          g = SkColorGetG(text_color) / 255.0,
    317          b = SkColorGetB(text_color) / 255.0,
    318          a = SkColorGetA(text_color) / 255.0;
    319 
    320   cairo_pattern_t* pattern = NULL;
    321 
    322   cairo_save(cr);
    323 
    324   // If we're not eliding, use a fixed color.
    325   // Otherwise, create a gradient pattern to use as the source.
    326   if (text_direction == base::i18n::RIGHT_TO_LEFT ||
    327       (flags & gfx::Canvas::NO_ELLIPSIS) ||
    328       text_rect.width() <= bounds.width()) {
    329     cairo_set_source_rgba(cr, r, g, b, a);
    330   } else {
    331     // Fade to semi-transparent to elide.
    332     int fade_width = static_cast<double>(text_rect.height()) * kFadeWidthFactor;
    333     if (fade_width > bounds.width() / 2) {
    334       // Don't fade more than half the text.
    335       fade_width = bounds.width() / 2;
    336     }
    337     int fade_x = bounds.x() + bounds.width() - fade_width;
    338 
    339     pattern = cairo_pattern_create_linear(
    340         fade_x, bounds.y(), bounds.x() + bounds.width(), bounds.y());
    341     cairo_pattern_add_color_stop_rgba(pattern, 0, r, g, b, a);
    342     cairo_pattern_add_color_stop_rgba(pattern, 1, r, g, b, kFadeFinalAlpha);
    343     cairo_set_source(cr, pattern);
    344   }
    345 
    346   cairo_move_to(cr, text_rect.x(), text_rect.y());
    347   pango_cairo_show_layout(cr, layout);
    348 
    349   if (font.GetStyle() & gfx::Font::UNDERLINE) {
    350     gfx::PlatformFontPango* platform_font =
    351         static_cast<gfx::PlatformFontPango*>(font.platform_font());
    352     DrawPangoTextUnderline(cr, platform_font, 0.0, text_rect);
    353   }
    354 
    355   if (pattern)
    356     cairo_pattern_destroy(pattern);
    357 
    358   cairo_restore(cr);
    359 }
    360 
    361 void DrawPangoTextUnderline(cairo_t* cr,
    362                             gfx::PlatformFontPango* platform_font,
    363                             double extra_edge_width,
    364                             const Rect& text_rect) {
    365   const double underline_y =
    366       static_cast<double>(text_rect.y()) + text_rect.height() +
    367       platform_font->underline_position();
    368   cairo_set_line_width(
    369       cr, platform_font->underline_thickness() + 2 * extra_edge_width);
    370   cairo_move_to(cr,
    371                 text_rect.x() - extra_edge_width,
    372                 underline_y);
    373   cairo_line_to(cr,
    374                 text_rect.x() + text_rect.width() + extra_edge_width,
    375                 underline_y);
    376   cairo_stroke(cr);
    377 }
    378 
    379 size_t GetPangoFontSizeInPixels(PangoFontDescription* pango_font) {
    380   size_t size_in_pixels = pango_font_description_get_size(pango_font);
    381   if (pango_font_description_get_size_is_absolute(pango_font)) {
    382     // If the size is absolute, then it's in Pango units rather than points.
    383     // There are PANGO_SCALE Pango units in a device unit (pixel).
    384     size_in_pixels /= PANGO_SCALE;
    385   } else {
    386     // Otherwise, we need to convert from points.
    387     size_in_pixels = size_in_pixels * GetPixelsInPoint() / PANGO_SCALE;
    388   }
    389   return size_in_pixels;
    390 }
    391 
    392 PangoFontMetrics* GetPangoFontMetrics(PangoFontDescription* desc) {
    393   static std::map<int, PangoFontMetrics*>* desc_to_metrics = NULL;
    394   static PangoContext* context = NULL;
    395 
    396   if (!context) {
    397     context = GetPangoContext();
    398     pango_context_set_language(context, pango_language_get_default());
    399   }
    400 
    401   if (!desc_to_metrics)
    402     desc_to_metrics = new std::map<int, PangoFontMetrics*>();
    403 
    404   const int desc_hash = pango_font_description_hash(desc);
    405   std::map<int, PangoFontMetrics*>::iterator i =
    406       desc_to_metrics->find(desc_hash);
    407 
    408   if (i == desc_to_metrics->end()) {
    409     PangoFontMetrics* metrics = pango_context_get_metrics(context, desc, NULL);
    410     desc_to_metrics->insert(std::make_pair(desc_hash, metrics));
    411     return metrics;
    412   }
    413   return i->second;
    414 }
    415 
    416 }  // namespace gfx
    417