]> git.donarmstrong.com Git - lilypond.git/blob - lily/pango-font.cc
plug 2 pango memory leaks.
[lilypond.git] / lily / pango-font.cc
1 /*
2   pango-font.cc -- implement Pango_font
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 2004--2007 Han-Wen Nienhuys <hanwen@xs4all.nl>
7 */
8
9 #define PANGO_ENABLE_BACKEND // ugh, why necessary?
10 #include <pango/pangoft2.h>
11 #include <freetype/ftxf86.h>
12
13 #include <map>
14
15 /* Ugh.  */
16
17 #include "pango-font.hh"
18 #include "dimensions.hh"
19 #include "file-name.hh"
20 #include "international.hh"
21 #include "lookup.hh"            // debugging
22 #include "main.hh"
23 #include "string-convert.hh"
24 #include "warn.hh"
25 #include "all-font-metrics.hh"
26
27 #if HAVE_PANGO_FT2
28 #include "stencil.hh"
29
30 Pango_font::Pango_font (PangoFT2FontMap *fontmap,
31                         PangoFontDescription *description,
32                         Real output_scale)
33 {
34   (void) fontmap;
35   physical_font_tab_ = scm_c_make_hash_table (11);
36   PangoDirection pango_dir = PANGO_DIRECTION_LTR;
37   context_
38     = pango_ft2_get_context (PANGO_RESOLUTION, PANGO_RESOLUTION);
39   //  context_ = pango_ft2_font_map_create_context (fontmap);
40
41   pango_description_ = pango_font_description_copy (description);
42   attribute_list_ = pango_attr_list_new ();
43
44   /*
45     urgh. I don't understand this. Why isn't this 1/(scale *
46     resolution * output_scale)
47
48     --hwn
49   */
50   output_scale_ = output_scale;
51   scale_ = INCH_TO_BP / (Real (PANGO_SCALE) * Real (PANGO_RESOLUTION) * output_scale);
52
53   /*
54     ugh. Should make this configurable.
55   */
56   pango_context_set_language (context_, pango_language_from_string ("en_US"));
57   pango_context_set_base_dir (context_, pango_dir);
58   pango_context_set_font_description (context_, description);
59 }
60
61 Pango_font::~Pango_font ()
62 {
63   pango_font_description_free (pango_description_);
64   g_object_unref (context_);
65   pango_attr_list_unref (attribute_list_);
66 }
67
68 void
69 Pango_font::register_font_file (string filename, string ps_name)
70 {
71   scm_hash_set_x (physical_font_tab_,
72                   ly_string2scm (ps_name),
73                   ly_string2scm (filename));
74 }
75
76 void
77 Pango_font::derived_mark () const
78 {
79   scm_gc_mark (physical_font_tab_);
80 }
81
82
83 void
84 get_glyph_index_name (char *s, FT_ULong code)
85 {
86   sprintf (s, "glyphIndex%lX", code);
87 }
88
89 void
90 get_unicode_name (char*s, FT_ULong code)
91 {
92   if (code > 0xFFFF)
93     sprintf (s,  "u%lX", code);
94   else
95     sprintf (s,  "uni%04lX", code);
96 }
97
98
99 Stencil
100 Pango_font::pango_item_string_stencil (PangoItem const *item, string str,
101                                        bool tight_bbox) const
102 {
103   const int GLYPH_NAME_LEN = 256;
104   char glyph_name[GLYPH_NAME_LEN];
105   PangoAnalysis const *pa = &(item->analysis);
106   PangoGlyphString *pgs = pango_glyph_string_new ();
107   
108   pango_shape (str.c_str () + item->offset,
109                item->length, (PangoAnalysis*) pa, pgs);
110
111   PangoRectangle logical_rect;
112   PangoRectangle ink_rect;
113   pango_glyph_string_extents (pgs, pa->font, &ink_rect, &logical_rect);
114
115   PangoFcFont *fcfont = G_TYPE_CHECK_INSTANCE_CAST (pa->font,
116                                                     PANGO_TYPE_FC_FONT,
117                                                     PangoFcFont);
118
119   FT_Face ftface = pango_fc_font_lock_face (fcfont);
120
121   PangoRectangle const *which_rect
122     = (tight_bbox)
123     ? &ink_rect
124     : &logical_rect;
125     
126   Box b (Interval (PANGO_LBEARING (logical_rect),
127                    PANGO_RBEARING (logical_rect)),
128          Interval (-PANGO_DESCENT (*which_rect),
129                    PANGO_ASCENT (*which_rect)));
130
131   b.scale (scale_);
132   char const *ps_name_str0 = FT_Get_Postscript_Name (ftface);
133   FcPattern *fcpat = fcfont->font_pattern;
134   FcChar8 *file_name_as_ptr = 0;
135   FcPatternGetString (fcpat, FC_FILE, 0, &file_name_as_ptr);
136
137   string file_name;
138   if (file_name_as_ptr)
139     {
140       /* Normalize file name.  */
141       file_name = File_name ((char const *)file_name_as_ptr).to_string ();
142     }
143   
144   SCM glyph_exprs = SCM_EOL;
145   SCM *tail = &glyph_exprs;
146       
147   Index_to_charcode_map const *cmap = 0;
148   bool has_glyph_names = ftface->face_flags & FT_FACE_FLAG_GLYPH_NAMES;
149   if  (! has_glyph_names)
150     cmap = all_fonts_global->get_index_to_charcode_map (file_name, ftface);
151
152   bool is_ttf = string (FT_Get_X11_Font_Format (ftface)) == "TrueType";
153   bool cid_keyed = false;
154   for (int i = 0; i < pgs->num_glyphs; i++)
155     {
156       PangoGlyphInfo *pgi = pgs->glyphs + i;
157
158       PangoGlyph pg = pgi->glyph;
159       PangoGlyphGeometry ggeo = pgi->geometry;
160
161       glyph_name[0] = '\0';
162       if (has_glyph_names)
163         {
164           int errorcode = FT_Get_Glyph_Name (ftface, pg, glyph_name, GLYPH_NAME_LEN);
165           if (errorcode)
166             programming_error ("FT_Get_Glyph_Name returns error");
167         }
168
169       SCM char_id = SCM_EOL;
170       if (glyph_name[0] == '\0'
171           && cmap
172           && is_ttf
173           && cmap->find (pg) != cmap->end ())
174         {
175           FT_ULong char_code = cmap->find (pg)->second;
176           get_unicode_name (glyph_name, char_code);
177         }
178
179       if (glyph_name[0] ==  '\0' && has_glyph_names)
180         {
181           programming_error (_f ("Glyph has no name, but font supports glyph naming.\n"
182                                  "Skipping glyph U+%0X, file %s",
183                                  pg,
184                                  file_name.c_str ()));
185           continue;
186         }
187
188       
189       if (glyph_name == string (".notdef") && is_ttf)
190         glyph_name[0] = '\0';
191           
192       if (glyph_name[0] == '\0' && is_ttf)
193         {
194           // access by glyph index directly.
195           get_glyph_index_name (glyph_name, pg);
196         }
197       
198       if (glyph_name[0] == '\0')
199         {
200           /*
201             CID entry
202           */
203           cid_keyed = true;
204           char_id = scm_from_uint32 (pg);
205         }
206       else
207         char_id = scm_from_locale_string (glyph_name);
208       
209       *tail = scm_cons (scm_list_4 (scm_from_double (ggeo.width * scale_),
210                                     scm_from_double (ggeo.x_offset * scale_),
211                                     scm_from_double (ggeo.y_offset * scale_),
212                                     
213                                     char_id),
214                         SCM_EOL);
215       tail = SCM_CDRLOC (*tail);
216     }
217
218   pango_glyph_string_free (pgs);  
219   pgs = 0;
220   PangoFontDescription *descr = pango_font_describe (pa->font);
221   Real size = pango_font_description_get_size (descr)
222     / (Real (PANGO_SCALE));
223
224
225   if (!ps_name_str0)
226     warning (_f ("no PostScript font name for font `%s'", file_name));
227
228   string ps_name;
229   if (!ps_name_str0
230       && file_name != ""
231       && (file_name.find (".otf") != NPOS
232           || file_name.find (".cff") != NPOS))
233     {
234
235       /* UGH: kludge a PS name for OTF/CFF fonts.  */
236       string name = file_name;
237       ssize idx = file_name.find (".otf");
238       if (idx == NPOS)
239         idx = file_name.find (".cff");
240
241       name = name.substr (0, idx);
242
243       ssize slash_idx = name.rfind ('/');
244       if (slash_idx != NPOS)
245         {
246           slash_idx ++; 
247           name = name.substr (slash_idx,
248                               name.length () - slash_idx);
249         }
250       
251       string initial = name.substr (0, 1);
252       initial = String_convert::to_upper (initial);
253       name = name.substr (1, name.length () - 1);
254       name = String_convert::to_lower (name);
255       ps_name = initial + name;
256     }
257   else if (ps_name_str0)
258     ps_name = ps_name_str0;
259
260   if (ps_name.length ())
261     {
262       ((Pango_font *) this)->register_font_file (file_name, ps_name);
263       pango_fc_font_unlock_face (fcfont);
264
265       SCM expr = scm_list_5 (ly_symbol2scm ("glyph-string"),
266                              ly_string2scm (ps_name),
267                              scm_from_double (size),
268                              scm_from_bool (cid_keyed),
269                              ly_quote_scm (glyph_exprs));
270
271       return Stencil (b, expr);
272     }
273
274   warning (_ ("FreeType face has no PostScript font name"));
275   return Stencil ();
276 }
277
278 SCM
279 Pango_font::physical_font_tab () const
280 {
281   return physical_font_tab_;
282 }
283
284
285 Stencil
286 Pango_font::word_stencil (string str) const
287 {
288   return text_stencil (str, true);
289 }
290   
291 Stencil
292 Pango_font::text_stencil (string str) const
293 {
294   return text_stencil (str, false);
295 }
296
297 Stencil
298 Pango_font::text_stencil (string str, bool tight) const
299 {
300   GList *items
301     = pango_itemize (context_,
302                      str.c_str (),
303                      0, str.length (), attribute_list_,
304                      NULL);
305
306   Stencil dest;
307
308   Real last_x = 0.0;
309
310   Direction text_dir = RIGHT;
311   for (GList *p = items; p; p = p->next)
312     {
313       PangoItem *item = (PangoItem *) p->data;
314       if (item->analysis.level == PANGO_DIRECTION_RTL)
315         text_dir = LEFT;
316     }
317  
318   for (GList *ptr = items; ptr; ptr = ptr->next)
319     {
320       PangoItem *item = (PangoItem *) ptr->data;
321
322       Stencil item_stencil = pango_item_string_stencil (item, str, tight);
323
324       if (text_dir == RIGHT)
325         {
326           item_stencil.translate_axis (last_x, X_AXIS);
327           last_x = item_stencil.extent (X_AXIS)[RIGHT];
328         }
329       else if (text_dir == LEFT)
330         {
331           dest.translate_axis (item_stencil.extent (X_AXIS)[RIGHT], X_AXIS);
332         }
333
334 #if 0 /* Check extents.  */
335       if (!item_stencil.extent_box ()[X_AXIS].is_empty ())
336         {
337           Stencil frame = Lookup::frame (item_stencil.extent_box (), 0.1, 0.1);
338           Box empty;
339           empty.set_empty ();
340           Stencil dimless_frame (empty, frame.expr ());
341           dest.add_stencil (frame);
342         }
343 #endif
344   
345       dest.add_stencil (item_stencil);
346     }
347
348   /*
349     UGH. Should have flags per output format signifying supported
350     options.
351   */
352   if (output_backend_global != "ps"
353       && output_backend_global != "eps")
354     {
355       /*
356         For Pango based backends, we take a shortcut.
357       */
358       SCM exp
359         = scm_list_3 (ly_symbol2scm ("utf-8-string"),
360                       ly_string2scm (description_string ()),
361                       ly_string2scm (str));
362
363       Box b (Interval (0, 0), Interval (0, 0));
364       b.unite (dest.extent_box ());
365       return Stencil (b, exp);
366     }
367
368   g_list_free (items);
369
370   return dest;
371 }
372
373 string
374 Pango_font::description_string () const
375 {
376   char *descr_string = pango_font_description_to_string (pango_description_);
377   string s (descr_string);
378   g_free (descr_string);
379   return s;
380 }
381
382
383 SCM
384 Pango_font::font_file_name () const
385 {
386   return SCM_BOOL_F;
387 }
388
389 #endif