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