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