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