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