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