]> git.donarmstrong.com Git - lilypond.git/blob - lily/pango-font.cc
Merge remote-tracking branch 'origin/stable/2.16' into translation
[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 void
95 Pango_font::derived_mark () const
96 {
97   scm_gc_mark (physical_font_tab_);
98 }
99
100 void
101 get_glyph_index_name (char *s,
102                       FT_ULong code)
103 {
104   sprintf (s, "glyphIndex%lX", code);
105 }
106
107 void
108 get_unicode_name (char *s,
109                   FT_ULong code)
110 {
111   if (code > 0xFFFF)
112     sprintf (s, "u%lX", code);
113   else
114     sprintf (s, "uni%04lX", code);
115 }
116
117 Stencil
118 Pango_font::pango_item_string_stencil (PangoGlyphItem const *glyph_item) const
119 {
120   const int GLYPH_NAME_LEN = 256;
121   char glyph_name[GLYPH_NAME_LEN];
122
123   PangoAnalysis const *pa = &(glyph_item->item->analysis);
124   PangoGlyphString *pgs = glyph_item->glyphs;
125
126   PangoRectangle logical_rect;
127   PangoRectangle ink_rect;
128   pango_glyph_string_extents (pgs, pa->font, &ink_rect, &logical_rect);
129
130   PangoFcFont *fcfont = PANGO_FC_FONT (pa->font);
131
132   FT_Face ftface = pango_fc_font_lock_face (fcfont);
133
134   Box b (Interval (PANGO_LBEARING (logical_rect),
135                    PANGO_RBEARING (logical_rect)),
136          Interval (-PANGO_DESCENT (ink_rect),
137                    PANGO_ASCENT (ink_rect)));
138
139   b.scale (scale_);
140
141   char const *ps_name_str0 = FT_Get_Postscript_Name (ftface);
142   FcPattern *fcpat = fcfont->font_pattern;
143
144   FcChar8 *file_name_as_ptr = 0;
145   FcPatternGetString (fcpat, FC_FILE, 0, &file_name_as_ptr);
146
147   // due to a bug in FreeType 2.3.7 and earlier we can't use
148   // ftface->face_index; it is always zero for some font formats,
149   // in particular TTCs which we are interested in
150   int face_index = 0;
151   FcPatternGetInteger (fcpat, FC_INDEX, 0, &face_index);
152
153   string file_name;
154   if (file_name_as_ptr)
155     // Normalize file name.
156     file_name = File_name ((char const *)file_name_as_ptr).to_string ();
157
158   SCM glyph_exprs = SCM_EOL;
159   SCM *tail = &glyph_exprs;
160
161   Index_to_charcode_map const *cmap = 0;
162   bool has_glyph_names = ftface->face_flags & FT_FACE_FLAG_GLYPH_NAMES;
163   if (!has_glyph_names)
164     cmap = all_fonts_global->get_index_to_charcode_map (file_name, face_index, ftface);
165
166   bool is_ttf = string (FT_Get_X11_Font_Format (ftface)) == "TrueType";
167   bool cid_keyed = false;
168
169   for (int i = 0; i < pgs->num_glyphs; i++)
170     {
171       PangoGlyphInfo *pgi = pgs->glyphs + i;
172
173       PangoGlyph pg = pgi->glyph;
174       PangoGlyphGeometry ggeo = pgi->geometry;
175
176       /*
177         Zero-width characters are valid Unicode characters,
178         but glyph lookups need to be skipped.
179       */
180       if (!(pg ^ PANGO_GLYPH_EMPTY))
181         continue;
182
183       if (pg & PANGO_GLYPH_UNKNOWN_FLAG)
184         {
185           warning (_f ("no glyph for character U+%0X in font `%s'",
186                        pg & ~PANGO_GLYPH_UNKNOWN_FLAG, file_name.c_str ()));
187           continue;
188         }
189
190       glyph_name[0] = '\0';
191       if (has_glyph_names)
192         {
193           FT_Error errorcode = FT_Get_Glyph_Name (ftface, pg, glyph_name,
194                                                   GLYPH_NAME_LEN);
195           if (errorcode)
196             programming_error (_f ("FT_Get_Glyph_Name () error: %s",
197                                    freetype_error_string (errorcode).c_str ()));
198         }
199
200       SCM char_id = SCM_EOL;
201       if (glyph_name[0] == '\0'
202           && cmap
203           && is_ttf
204           && cmap->find (pg) != cmap->end ())
205         {
206           FT_ULong char_code = cmap->find (pg)->second;
207           get_unicode_name (glyph_name, char_code);
208         }
209
210       if (glyph_name[0] == '\0' && has_glyph_names)
211         {
212           programming_error (_f ("Glyph has no name, but font supports glyph naming.\n"
213                                  "Skipping glyph U+%0X, file %s",
214                                  pg, file_name.c_str ()));
215           continue;
216         }
217
218       if (glyph_name == string (".notdef") && is_ttf)
219         glyph_name[0] = '\0';
220
221       if (glyph_name[0] == '\0' && is_ttf)
222         // Access by glyph index directly.
223         get_glyph_index_name (glyph_name, pg);
224
225       if (glyph_name[0] == '\0')
226         {
227           // CID entry
228           cid_keyed = true;
229           char_id = scm_from_uint32 (pg);
230         }
231       else
232         char_id = scm_from_locale_string (glyph_name);
233
234       *tail = scm_cons (scm_list_4 (scm_from_double (ggeo.width * scale_),
235                                     scm_from_double (ggeo.x_offset * scale_),
236                                     scm_from_double (- ggeo.y_offset * scale_),
237                                     char_id),
238                         SCM_EOL);
239       tail = SCM_CDRLOC (*tail);
240     }
241   pango_fc_font_unlock_face (fcfont);
242   pango_glyph_string_free (pgs);
243   pgs = 0;
244   PangoFontDescription *descr = pango_font_describe (pa->font);
245   Real size = pango_font_description_get_size (descr)
246               / (Real (PANGO_SCALE));
247
248   if (!ps_name_str0)
249     warning (_f ("no PostScript font name for font `%s'", file_name));
250
251   string ps_name;
252   if (!ps_name_str0
253       && file_name != ""
254       && (file_name.find (".otf") != NPOS
255           || file_name.find (".cff") != NPOS))
256     {
257       // UGH: kludge a PS name for OTF/CFF fonts.
258       string name = file_name;
259       ssize idx = file_name.find (".otf");
260       if (idx == NPOS)
261         idx = file_name.find (".cff");
262
263       name = name.substr (0, idx);
264
265       ssize slash_idx = name.rfind ('/');
266       if (slash_idx != NPOS)
267         {
268           slash_idx++;
269           name = name.substr (slash_idx,
270                               name.length () - slash_idx);
271         }
272
273       string initial = name.substr (0, 1);
274       initial = String_convert::to_upper (initial);
275       name = name.substr (1, name.length () - 1);
276       name = String_convert::to_lower (name);
277       ps_name = initial + name;
278     }
279   else if (ps_name_str0)
280     ps_name = ps_name_str0;
281
282   if (ps_name.length ())
283     {
284       ((Pango_font *) this)->register_font_file (file_name,
285                                                  ps_name,
286                                                  face_index);
287       pango_fc_font_unlock_face (fcfont);
288
289       SCM expr = scm_list_5 (ly_symbol2scm ("glyph-string"),
290                              ly_string2scm (ps_name),
291                              scm_from_double (size),
292                              scm_from_bool (cid_keyed),
293                              ly_quote_scm (glyph_exprs));
294
295       return Stencil (b, expr);
296     }
297
298   warning (_ ("FreeType face has no PostScript font name"));
299   return Stencil ();
300 }
301
302 SCM
303 Pango_font::physical_font_tab () const
304 {
305   return physical_font_tab_;
306 }
307
308 extern bool music_strings_to_paths;
309
310 Stencil
311 Pango_font::text_stencil (Output_def * /* state */,
312                           string str, bool music_string) const
313 {
314   /*
315     The text assigned to a PangoLayout is automatically divided
316     into sections and reordered according to the Unicode
317     Bidirectional Algorithm, if necessary.
318   */
319   PangoLayout *layout = pango_layout_new (context_);
320   pango_layout_set_text (layout, str.c_str (), -1);
321   GSList *lines = pango_layout_get_lines (layout);
322
323   Stencil dest;
324   Real last_x = 0.0;
325
326   for (GSList *l = lines; l; l = l->next)
327     {
328       PangoLayoutLine *line = (PangoLayoutLine *) l->data;
329       GSList *layout_runs = line->runs;
330
331       for (GSList *p = layout_runs; p; p = p->next)
332         {
333           PangoGlyphItem *item = (PangoGlyphItem *) p->data;
334           Stencil item_stencil = pango_item_string_stencil (item);
335
336           item_stencil.translate_axis (last_x, X_AXIS);
337           last_x = item_stencil.extent (X_AXIS)[RIGHT];
338
339 #if 0 // Check extents.
340           if (!item_stencil.extent_box ()[X_AXIS].is_empty ())
341             {
342               Stencil frame = Lookup::frame (item_stencil.extent_box (), 0.1, 0.1);
343               Box empty;
344               empty.set_empty ();
345               Stencil dimless_frame (empty, frame.expr ());
346               dest.add_stencil (frame);
347             }
348 #endif
349
350           dest.add_stencil (item_stencil);
351         }
352     }
353
354   string name = get_output_backend_name ();
355   string output_mod = "scm output-" + name;
356   SCM mod = scm_c_resolve_module (output_mod.c_str ());
357
358   bool has_utf8_string = false;
359
360   if (ly_is_module (mod))
361     {
362       SCM utf8_string = ly_module_lookup (mod, ly_symbol2scm ("utf-8-string"));
363       /*
364         has_utf8_string should only be true when utf8_string is a
365         variable that is bound to a *named* procedure, i.e. not a
366         lambda expression.
367       */
368       if (utf8_string != SCM_BOOL_F
369           && scm_procedure_name (SCM_VARIABLE_REF (utf8_string)) != SCM_BOOL_F)
370         has_utf8_string = true;
371     }
372
373   bool to_paths = music_strings_to_paths;
374
375   /*
376     Backends with the utf-8-string expression use it when
377       1) the -dmusic-strings-to-paths option is set
378          and `str' is not a music string, or
379       2) the -dmusic-strings-to-paths option is not set.
380   */
381   if (has_utf8_string && ((to_paths && !music_string) || !to_paths))
382     {
383       // For Pango based backends, we take a shortcut.
384       SCM exp = scm_list_3 (ly_symbol2scm ("utf-8-string"),
385                             ly_string2scm (description_string ()),
386                             ly_string2scm (str));
387
388       Box b (Interval (0, 0), Interval (0, 0));
389       b.unite (dest.extent_box ());
390       return Stencil (b, exp);
391     }
392
393   return dest;
394 }
395
396 string
397 Pango_font::description_string () const
398 {
399   char *descr_string = pango_font_description_to_string (pango_description_);
400   string s (descr_string);
401   g_free (descr_string);
402   return s;
403 }
404
405 SCM
406 Pango_font::font_file_name () const
407 {
408   return SCM_BOOL_F;
409 }
410
411 #endif // HAVE_PANGO_FT2