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