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