]> git.donarmstrong.com Git - lilypond.git/blob - lily/pango-font.cc
Merge remote-tracking branch 'origin/translation'
[lilypond.git] / lily / pango-font.cc
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 2004--2014 Han-Wen Nienhuys <hanwen@xs4all.nl>
5
6   LilyPond is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   LilyPond is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 // Necessary for supporting pango_context_new() and
21 // pango_context_set_font_map() in Pango < 1.22
22 #define PANGO_ENABLE_BACKEND
23
24 #include <pango/pangoft2.h>
25 #include "freetype.hh"
26 #include FT_XFREE86_H
27
28 #include <map>
29 #include <cstdio>
30
31 // Ugh.
32
33 #include "pango-font.hh"
34 #include "dimensions.hh"
35 #include "file-name.hh"
36 #include "international.hh"
37 #include "lookup.hh"            // debugging
38 #include "main.hh"
39 #include "string-convert.hh"
40 #include "warn.hh"
41 #include "all-font-metrics.hh"
42 #include "program-option.hh"
43
44 #if HAVE_PANGO_FT2
45 #include "stencil.hh"
46
47 Pango_font::Pango_font (PangoFT2FontMap *fontmap,
48                         PangoFontDescription const *description,
49                         Real output_scale)
50 {
51   // This line looks stupid, but if we don't initialize physical_font_tab_ before
52   // we allocate memory in scm_c_make_hash_table, then that could trigger a garbage
53   // collection.
54   physical_font_tab_ = SCM_EOL;
55   physical_font_tab_ = scm_c_make_hash_table (11);
56   PangoDirection pango_dir = PANGO_DIRECTION_LTR;
57   context_ = pango_context_new ();
58   pango_context_set_font_map (context_, PANGO_FONT_MAP (fontmap));
59
60   pango_description_ = pango_font_description_copy (description);
61   attribute_list_ = pango_attr_list_new ();
62
63   // urgh. I don't understand this. Why isn't this 1/(scale *
64   // resolution * output_scale)
65   //
66   //  --hwn
67   output_scale_ = output_scale;
68   scale_ = INCH_TO_BP
69            / (Real (PANGO_SCALE) * Real (PANGO_RESOLUTION) * output_scale);
70
71   // ugh. Should make this configurable.
72   pango_context_set_language (context_, pango_language_from_string ("en_US"));
73   pango_context_set_base_dir (context_, pango_dir);
74   pango_context_set_font_description (context_, description);
75 }
76
77 Pango_font::~Pango_font ()
78 {
79   pango_font_description_free (pango_description_);
80   g_object_unref (context_);
81   pango_attr_list_unref (attribute_list_);
82 }
83
84 void
85 Pango_font::register_font_file (const string &filename,
86                                 const string &ps_name,
87                                 int face_index)
88 {
89   scm_hash_set_x (physical_font_tab_,
90                   ly_string2scm (ps_name),
91                   scm_list_2 (ly_string2scm (filename),
92                               scm_from_int (face_index)));
93 }
94
95 size_t
96 Pango_font::name_to_index (string nm) const
97 {
98   PangoFcFont *fcfont = PANGO_FC_FONT (pango_context_load_font (context_, pango_description_));
99   FT_Face face = pango_fc_font_lock_face (fcfont);
100   char *nm_str = (char *) nm.c_str ();
101   if (FT_UInt idx = FT_Get_Name_Index (face, nm_str))
102     {
103       pango_fc_font_unlock_face (fcfont);
104       return (size_t) idx;
105     }
106
107   pango_fc_font_unlock_face (fcfont);
108   return (size_t) - 1;
109 }
110
111 void
112 Pango_font::derived_mark () const
113 {
114   scm_gc_mark (physical_font_tab_);
115 }
116
117 void
118 get_glyph_index_name (char *s,
119                       FT_ULong code)
120 {
121   sprintf (s, "glyphIndex%lX", code);
122 }
123
124 void
125 get_unicode_name (char *s,
126                   FT_ULong code)
127 {
128   if (code > 0xFFFF)
129     sprintf (s, "u%lX", code);
130   else
131     sprintf (s, "uni%04lX", code);
132 }
133
134 Box
135 Pango_font::get_unscaled_indexed_char_dimensions (size_t signed_idx) const
136 {
137   PangoFcFont *fcfont = PANGO_FC_FONT (pango_context_load_font (context_, pango_description_));
138   FT_Face face = pango_fc_font_lock_face (fcfont);
139   Box b = ly_FT_get_unscaled_indexed_char_dimensions (face, signed_idx);
140   pango_fc_font_unlock_face (fcfont);
141   return b;
142 }
143
144 Box
145 Pango_font::get_scaled_indexed_char_dimensions (size_t signed_idx) const
146 {
147   PangoFont *font = pango_context_load_font (context_, pango_description_);
148   PangoRectangle logical_rect;
149   PangoRectangle ink_rect;
150   pango_font_get_glyph_extents (font, signed_idx, &ink_rect, &logical_rect);
151   Box out (Interval (PANGO_LBEARING (ink_rect),
152                      PANGO_RBEARING (ink_rect)),
153            Interval (-PANGO_DESCENT (ink_rect),
154                      PANGO_ASCENT (ink_rect)));
155   out.scale (scale_);
156   return out;
157 }
158
159 Box
160 Pango_font::get_glyph_outline_bbox (size_t signed_idx) const
161 {
162   PangoFcFont *fcfont = PANGO_FC_FONT (pango_context_load_font (context_, pango_description_));
163   FT_Face face = pango_fc_font_lock_face (fcfont);
164   Box b = ly_FT_get_glyph_outline_bbox (face, signed_idx);
165   pango_fc_font_unlock_face (fcfont);
166   return b;
167 }
168
169 SCM
170 Pango_font::get_glyph_outline (size_t signed_idx) const
171 {
172   PangoFcFont *fcfont = PANGO_FC_FONT (pango_context_load_font (context_, pango_description_));
173   FT_Face face = pango_fc_font_lock_face (fcfont);
174   SCM s = ly_FT_get_glyph_outline (face, signed_idx);
175   pango_fc_font_unlock_face (fcfont);
176   return s;
177 }
178
179 Stencil
180 Pango_font::pango_item_string_stencil (PangoGlyphItem const *glyph_item) const
181 {
182   const int GLYPH_NAME_LEN = 256;
183   char glyph_name[GLYPH_NAME_LEN];
184
185   PangoAnalysis const *pa = &(glyph_item->item->analysis);
186   PangoGlyphString *pgs = glyph_item->glyphs;
187
188   PangoRectangle logical_rect;
189   PangoRectangle ink_rect;
190   pango_glyph_string_extents (pgs, pa->font, &ink_rect, &logical_rect);
191
192   PangoFcFont *fcfont = PANGO_FC_FONT (pa->font);
193   FT_Face ftface = pango_fc_font_lock_face (fcfont);
194
195   Box b (Interval (PANGO_LBEARING (logical_rect),
196                    PANGO_RBEARING (logical_rect)),
197          Interval (-PANGO_DESCENT (ink_rect),
198                    PANGO_ASCENT (ink_rect)));
199
200   b.scale (scale_);
201
202   char const *ps_name_str0 = FT_Get_Postscript_Name (ftface);
203   FcPattern *fcpat = fcfont->font_pattern;
204
205   FcChar8 *file_name_as_ptr = 0;
206   FcPatternGetString (fcpat, FC_FILE, 0, &file_name_as_ptr);
207
208   // due to a bug in FreeType 2.3.7 and earlier we can't use
209   // ftface->face_index; it is always zero for some font formats,
210   // in particular TTCs which we are interested in
211   int face_index = 0;
212   FcPatternGetInteger (fcpat, FC_INDEX, 0, &face_index);
213
214   string file_name;
215   if (file_name_as_ptr)
216     // Normalize file name.
217     file_name = File_name ((char const *)file_name_as_ptr).to_string ();
218
219   SCM glyph_exprs = SCM_EOL;
220   SCM *tail = &glyph_exprs;
221
222   Index_to_charcode_map const *cmap = 0;
223   bool has_glyph_names = ftface->face_flags & FT_FACE_FLAG_GLYPH_NAMES;
224   if (!has_glyph_names)
225     cmap = all_fonts_global->get_index_to_charcode_map (file_name, face_index, ftface);
226
227   bool is_ttf = string (FT_Get_X11_Font_Format (ftface)) == "TrueType";
228   bool cid_keyed = false;
229
230   for (int i = 0; i < pgs->num_glyphs; i++)
231     {
232       PangoGlyphInfo *pgi = pgs->glyphs + i;
233
234       PangoGlyph pg = pgi->glyph;
235       PangoGlyphGeometry ggeo = pgi->geometry;
236
237       /*
238         Zero-width characters are valid Unicode characters,
239         but glyph lookups need to be skipped.
240       */
241       if (!(pg ^ PANGO_GLYPH_EMPTY))
242         continue;
243
244       if (pg & PANGO_GLYPH_UNKNOWN_FLAG)
245         {
246           warning (_f ("no glyph for character U+%0X in font `%s'",
247                        pg & ~PANGO_GLYPH_UNKNOWN_FLAG, file_name.c_str ()));
248           continue;
249         }
250
251       glyph_name[0] = '\0';
252       if (has_glyph_names)
253         {
254           FT_Error errorcode = FT_Get_Glyph_Name (ftface, pg, glyph_name,
255                                                   GLYPH_NAME_LEN);
256           if (errorcode)
257             programming_error (_f ("FT_Get_Glyph_Name () error: %s",
258                                    freetype_error_string (errorcode).c_str ()));
259         }
260
261       SCM char_id = SCM_EOL;
262       if (glyph_name[0] == '\0'
263           && cmap
264           && is_ttf
265           && cmap->find (pg) != cmap->end ())
266         {
267           FT_ULong char_code = cmap->find (pg)->second;
268           get_unicode_name (glyph_name, char_code);
269         }
270
271       if (glyph_name[0] == '\0' && has_glyph_names)
272         {
273           programming_error (_f ("Glyph has no name, but font supports glyph naming.\n"
274                                  "Skipping glyph U+%0X, file %s",
275                                  pg, file_name.c_str ()));
276           continue;
277         }
278
279       if (glyph_name == string (".notdef") && is_ttf)
280         glyph_name[0] = '\0';
281
282       if (glyph_name[0] == '\0' && is_ttf)
283         // Access by glyph index directly.
284         get_glyph_index_name (glyph_name, pg);
285
286       if (glyph_name[0] == '\0')
287         {
288           // CID entry
289           cid_keyed = true;
290           char_id = scm_from_uint32 (pg);
291         }
292       else
293         char_id = scm_from_locale_string (glyph_name);
294
295       PangoRectangle logical_sub_rect;
296       PangoRectangle ink_sub_rect;
297
298       pango_glyph_string_extents_range (pgs, i, i + 1, pa->font, &ink_sub_rect, &logical_sub_rect);
299       Box b_sub (Interval (PANGO_LBEARING (logical_sub_rect),
300                            PANGO_RBEARING (logical_sub_rect)),
301                  Interval (-PANGO_DESCENT (ink_sub_rect),
302                            PANGO_ASCENT (ink_sub_rect)));
303
304       b_sub.scale (scale_);
305
306       *tail = scm_cons (scm_list_5 (scm_from_double (b_sub[X_AXIS][RIGHT] - b_sub[X_AXIS][LEFT]),
307                                     scm_cons (scm_from_double (b_sub[Y_AXIS][DOWN]),
308                                               scm_from_double (b_sub[Y_AXIS][UP])),
309                                     scm_from_double (ggeo.x_offset * scale_),
310                                     scm_from_double (- ggeo.y_offset * scale_),
311                                     char_id),
312                         SCM_EOL);
313       tail = SCM_CDRLOC (*tail);
314     }
315   pango_fc_font_unlock_face (fcfont);
316   pango_glyph_string_free (pgs);
317   pgs = 0;
318   PangoFontDescription *descr = pango_font_describe (pa->font);
319   Real size = pango_font_description_get_size (descr)
320               / (Real (PANGO_SCALE));
321
322   if (!ps_name_str0)
323     warning (_f ("no PostScript font name for font `%s'", file_name));
324
325   string ps_name;
326   if (!ps_name_str0
327       && file_name != ""
328       && (file_name.find (".otf") != NPOS
329           || file_name.find (".cff") != NPOS))
330     {
331       // UGH: kludge a PS name for OTF/CFF fonts.
332       string name = file_name;
333       ssize idx = file_name.find (".otf");
334       if (idx == NPOS)
335         idx = file_name.find (".cff");
336
337       name = name.substr (0, idx);
338
339       ssize slash_idx = name.rfind ('/');
340       if (slash_idx != NPOS)
341         {
342           slash_idx++;
343           name = name.substr (slash_idx,
344                               name.length () - slash_idx);
345         }
346
347       string initial = name.substr (0, 1);
348       initial = String_convert::to_upper (initial);
349       name = name.substr (1, name.length () - 1);
350       name = String_convert::to_lower (name);
351       ps_name = initial + name;
352     }
353   else if (ps_name_str0)
354     ps_name = ps_name_str0;
355
356   if (ps_name.length ())
357     {
358       ((Pango_font *) this)->register_font_file (file_name,
359                                                  ps_name,
360                                                  face_index);
361
362       SCM expr = scm_list_n (ly_symbol2scm ("glyph-string"),
363                              self_scm (),
364                              ly_string2scm (ps_name),
365                              scm_from_double (size),
366                              scm_from_bool (cid_keyed),
367                              ly_quote_scm (glyph_exprs),
368                              SCM_UNDEFINED);
369
370       return Stencil (b, expr);
371     }
372
373   warning (_ ("FreeType face has no PostScript font name"));
374   return Stencil ();
375 }
376
377 SCM
378 Pango_font::physical_font_tab () const
379 {
380   return physical_font_tab_;
381 }
382
383 extern bool music_strings_to_paths;
384
385 Stencil
386 Pango_font::text_stencil (Output_def * /* state */,
387                           const string &str, bool music_string) const
388 {
389   /*
390     The text assigned to a PangoLayout is automatically divided
391     into sections and reordered according to the Unicode
392     Bidirectional Algorithm, if necessary.
393   */
394   PangoLayout *layout = pango_layout_new (context_);
395   pango_layout_set_text (layout, str.c_str (), -1);
396   GSList *lines = pango_layout_get_lines (layout);
397
398   Stencil dest;
399   Real last_x = 0.0;
400
401   for (GSList *l = lines; l; l = l->next)
402     {
403       PangoLayoutLine *line = (PangoLayoutLine *) l->data;
404       GSList *layout_runs = line->runs;
405
406       for (GSList *p = layout_runs; p; p = p->next)
407         {
408           PangoGlyphItem *item = (PangoGlyphItem *) p->data;
409           Stencil item_stencil = pango_item_string_stencil (item);
410
411           item_stencil.translate_axis (last_x, X_AXIS);
412           last_x = item_stencil.extent (X_AXIS)[RIGHT];
413
414 #if 0 // Check extents.
415           if (!item_stencil.extent_box ()[X_AXIS].is_empty ())
416             {
417               Stencil frame = Lookup::frame (item_stencil.extent_box (), 0.1, 0.1);
418               Box empty;
419               empty.set_empty ();
420               Stencil dimless_frame (empty, frame.expr ());
421               dest.add_stencil (frame);
422             }
423 #endif
424
425           dest.add_stencil (item_stencil);
426         }
427     }
428
429   string name = get_output_backend_name ();
430   string output_mod = "scm output-" + name;
431   SCM mod = scm_c_resolve_module (output_mod.c_str ());
432
433   bool has_utf8_string = false;
434
435   if (ly_is_module (mod))
436     {
437       SCM utf8_string = ly_module_lookup (mod, ly_symbol2scm ("utf-8-string"));
438       /*
439         has_utf8_string should only be true when utf8_string is a
440         variable that is bound to a *named* procedure, i.e. not a
441         lambda expression.
442       */
443       if (utf8_string != SCM_BOOL_F
444           && scm_procedure_name (SCM_VARIABLE_REF (utf8_string)) != SCM_BOOL_F)
445         has_utf8_string = true;
446     }
447
448   bool to_paths = music_strings_to_paths;
449
450   /*
451     Backends with the utf-8-string expression use it when
452       1) the -dmusic-strings-to-paths option is set
453          and `str' is not a music string, or
454       2) the -dmusic-strings-to-paths option is not set.
455   */
456   if (has_utf8_string && ((to_paths && !music_string) || !to_paths))
457     {
458       // For Pango based backends, we take a shortcut.
459       SCM exp = scm_list_3 (ly_symbol2scm ("utf-8-string"),
460                             ly_string2scm (description_string ()),
461                             ly_string2scm (str));
462
463       Box b (Interval (0, 0), Interval (0, 0));
464       b.unite (dest.extent_box ());
465       return Stencil (b, exp);
466     }
467
468   return dest;
469 }
470
471 string
472 Pango_font::description_string () const
473 {
474   char *descr_string = pango_font_description_to_string (pango_description_);
475   string s (descr_string);
476   g_free (descr_string);
477   return s;
478 }
479
480 SCM
481 Pango_font::font_file_name () const
482 {
483   return SCM_BOOL_F;
484 }
485
486 #endif // HAVE_PANGO_FT2