1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3 
4   Copyright (C) 2004--2021 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 #include "open-type-font.hh"
21 #include "freetype.hh"
22 
23 #ifdef FT_FONT_FORMATS_H
24 /* FreeType 2.6+ */
25 #include FT_FONT_FORMATS_H
26 #else
27 /* FreeType 2.5.5 and earlier */
28 #include FT_XFREE86_H
29 #define FT_Get_Font_Format FT_Get_X11_Font_Format
30 #endif
31 
32 #include FT_TRUETYPE_TABLES_H
33 
34 #include "dimensions.hh"
35 #include "international.hh"
36 #include "modified-font-metric.hh"
37 #include "warn.hh"
38 
39 #include <cstdio>
40 #include <memory>
41 #include <utility>
42 
43 using std::map;
44 using std::pair;
45 using std::make_pair;
46 using std::string;
47 
48 std::unique_ptr<FT_Byte[]>
load_table(char const * tag_str,FT_Face face,FT_ULong * length)49 load_table (char const *tag_str, FT_Face face, FT_ULong *length)
50 {
51   *length = 0;
52 
53 #pragma GCC diagnostic push
54 #pragma GCC diagnostic ignored "-Wold-style-cast"
55   // The FT_MAKE_TAG macro has C-style casts and GCC is not smart enough to
56   // ignore them.
57   FT_ULong tag = FT_MAKE_TAG (tag_str[0], tag_str[1], tag_str[2], tag_str[3]);
58 #pragma GCC diagnostic pop
59 
60   FT_Error error_code = FT_Load_Sfnt_Table (face, tag, 0, NULL, length);
61   if (!error_code)
62     {
63       std::unique_ptr<FT_Byte[]> buffer (new FT_Byte[*length]);
64       if (!buffer)
65         error (_f ("cannot allocate %lu bytes", *length));
66 
67       error_code = FT_Load_Sfnt_Table (face, tag, 0, buffer.get (), length);
68       if (error_code)
69         {
70           error (_f ("cannot load font table: %s", tag_str));
71           buffer.reset ();
72         }
73 
74       return buffer;
75     }
76   else
77     programming_error (_f ("FreeType error: %s",
78                            freetype_error_string (error_code).c_str ()
79                           ));
80 
81   return 0;
82 }
83 
84 string
get_otf_table(const string & tag) const85 Open_type_font::get_otf_table (const string &tag) const
86 {
87   return ::get_otf_table (face_, tag);
88 }
89 
90 SCM
load_scheme_table(char const * tag_str,FT_Face face)91 load_scheme_table (char const *tag_str, FT_Face face)
92 {
93   FT_ULong length = 0;
94   auto buffer (load_table (tag_str, face, &length));
95 
96   SCM tab = SCM_EOL;
97   if (buffer)
98     {
99       string contents (reinterpret_cast<char const *> (buffer.get ()), length);
100       contents = "(quote (" + contents + "))";
101 
102 #if GUILEV2
103       tab = scm_eval_string (scm_from_utf8_string (contents.c_str ()));
104 #else
105       tab = scm_c_eval_string (contents.c_str ());
106 #endif
107     }
108   return tab;
109 }
110 
~Open_type_font()111 Open_type_font::~Open_type_font ()
112 {
113   FT_Done_Face (face_);
114 }
115 
116 /*
117   UGH fix naming
118 */
119 string
get_otf_table(FT_Face face,const string & tag)120 get_otf_table (FT_Face face, const string &tag)
121 {
122   string ret;
123   FT_ULong len;
124   auto tab (load_table (tag.c_str (), face, &len));
125   if (tab)
126     {
127       ret.assign (reinterpret_cast<char const *> (tab.get ()), len);
128     }
129   return ret;
130 }
131 
132 FT_Face
open_ft_face(const string & str,FT_Long idx)133 open_ft_face (const string &str, FT_Long idx)
134 {
135   FT_Face face;
136   FT_Error error_code = FT_New_Face (freetype2_library, str.c_str (), idx, &face);
137 
138   if (error_code == FT_Err_Unknown_File_Format)
139     error (_f ("unsupported font format: %s", str.c_str ()));
140   else if (error_code)
141     error (_f ("error reading font file %s: %s",
142                str.c_str (),
143                freetype_error_string (error_code).c_str ()));
144   return face;
145 }
146 
147 string
get_postscript_name(FT_Face face)148 get_postscript_name (FT_Face face)
149 {
150   string face_ps_name;
151   const char *psname = FT_Get_Postscript_Name (face);
152   if (psname)
153     face_ps_name = psname;
154   else
155     {
156       warning (_ ("cannot get postscript name"));
157       return "";
158     }
159 
160   const char *fmt = FT_Get_Font_Format (face);
161   if (fmt)
162     {
163       if (static_cast<string> (fmt) != "CFF")
164         return face_ps_name;  // For non-CFF font, pass it through.
165     }
166   else
167     {
168       warning (_f ("cannot get font %s format", face_ps_name.c_str ()));
169       return face_ps_name;
170     }
171 
172   // For OTF and OTC fonts, we use data from the font's 'CFF' table only
173   // because other tables are not embedded in the output PS file.
174   // However, parsing CFF takes time, so we use a cache.
175   std::string cff_name;
176   static std::map<std::string, std::string> cff_name_cache;
177   auto it = cff_name_cache.find (face_ps_name);
178   if (it == cff_name_cache.end ())
179     {
180       cff_name = get_cff_name (face);
181 
182       if (cff_name == "")
183         {
184           warning (_f ("cannot get CFF name from font %s",
185                        face_ps_name.c_str ()));
186           return face_ps_name;
187         }
188       if (face_ps_name != cff_name)
189         {
190           debug_output (_f ("Subsitute font name: %s => %s",
191                             face_ps_name.c_str (),
192                             cff_name.c_str ()));
193         }
194       else
195         {
196           debug_output (_f ("CFF name for font %s is the same.",
197                             cff_name.c_str ()));
198         }
199 
200       cff_name_cache[face_ps_name] = cff_name;
201     }
202   else
203     {
204       cff_name = it->second;
205     }
206 
207   return cff_name;
208 }
209 
210 std::string
get_cff_name(FT_Face face)211 get_cff_name (FT_Face face)
212 {
213   string cff_table = get_otf_table (face, "CFF ");
214 
215   FT_Open_Args args;
216   args.flags = FT_OPEN_MEMORY;
217   args.memory_base = static_cast<const FT_Byte *>
218                      (static_cast<const void *> (cff_table.data ()));
219   args.memory_size = cff_table.size ();
220 
221   FT_Face cff_face;
222   // According to OpenType Specification ver 1.7,
223   // the CFF (derived from OTF and OTC) has only one name.
224   // So we use zero as the font index.
225   FT_Error error_code = FT_Open_Face (freetype2_library, &args,
226                                       0 /* font index */,
227                                       &cff_face);
228   if (error_code)
229     {
230       warning (_f ("cannot read CFF: %s",
231                    freetype_error_string (error_code).c_str ()));
232       return "";
233     }
234 
235   string ret;
236   const char *cffname = FT_Get_Postscript_Name (cff_face);
237   if (cffname)
238     ret = cffname;
239   else
240     {
241       // FreeType 2.6 and 2.6.1 cannot get PS name from pure-CFF.
242       // (FreeType 2.5.5 and earlier does not have this issue.
243       //  FreeType 2.6.2+ has this bug fixed.)
244       // So we need direct parsing of the 'CFF' table, in this case.
245 
246       debug_output (_ ("Directly parsing 'CFF' table of font."));
247 
248       // See Adobe technote '5176.CFF.pdf', sections 2 and 5-7.
249       size_t hdrsize = static_cast<unsigned char> (cff_table.at (2));
250       string::iterator it = cff_table.begin () + hdrsize;
251 
252       unsigned int name_index_count;
253       name_index_count = static_cast<unsigned char> (*it++) << 8;
254       name_index_count |= static_cast<unsigned char> (*it++);
255 
256       size_t offsize = static_cast<unsigned char> (*it++);
257 
258       if (name_index_count && 1 <= offsize && offsize <= 4)
259         {
260           // We get the first name in the CFF's name index
261           // because this CFF (derived from OTF and OTC)
262           // has only one name.
263           size_t off1 = 0, off2 = 0;
264           for (size_t t = 0; t < offsize; t++)
265             off1 = ( off1 << 8) | static_cast<unsigned char> (*it++);
266           if (off1)
267             {
268               for (size_t t = 0; t < offsize; t++)
269                 off2 = ( off2 << 8) | static_cast<unsigned char> (*it++);
270             }
271           if (off1 && off1 < off2)
272             {
273               ret.assign (&cff_table.at (hdrsize + 3
274                                          + offsize * (name_index_count + 1)
275                                          + off1 - 1),
276                           &cff_table.at (hdrsize + 3
277                                          + offsize * (name_index_count + 1)
278                                          + off2 - 1));
279             }
280         }
281 
282       if (ret.empty ())
283         {
284           warning (_ ("cannot get CFF name"));
285           ret = "";
286         }
287     }
288 
289   FT_Done_Face (cff_face);
290 
291   return ret;
292 }
293 
294 SCM
make_otf(const string & str)295 Open_type_font::make_otf (const string &str)
296 {
297   FT_Face face = open_ft_face (str, 0 /* index */);
298   Open_type_font *otf = new Open_type_font (face);
299 
300   return otf->self_scm ();
301 }
302 
Preinit_Open_type_font()303 Preinit_Open_type_font::Preinit_Open_type_font ()
304 {
305   lily_character_table_ = SCM_EOL;
306   lily_global_table_ = SCM_EOL;
307   lily_subfonts_ = SCM_EOL;
308 }
309 
Open_type_font(FT_Face face)310 Open_type_font::Open_type_font (FT_Face face)
311 {
312   face_ = face;
313 
314   lily_character_table_ = alist_to_hashq (load_scheme_table ("LILC", face_));
315   lily_global_table_ = alist_to_hashq (load_scheme_table ("LILY", face_));
316   lily_subfonts_ = load_scheme_table ("LILF", face_);
317   index_to_charcode_map_ = make_index_to_charcode_map (face_);
318 
319   postscript_name_ = get_postscript_name (face_);
320 }
321 
322 void
derived_mark() const323 Open_type_font::derived_mark () const
324 {
325   scm_gc_mark (lily_character_table_);
326   scm_gc_mark (lily_global_table_);
327   scm_gc_mark (lily_subfonts_);
328 }
329 
330 /*
331   Get stem attachment point for a note head glyph.  This reads either
332   attachment or attachment-down depending on the direction, for compliance
333   with SMuFL.  However, when d is DOWN and attachment-down is not found,
334   we fall back to rotating attachment around the note head's center, for
335   backwards compatibility with fonts created earlier than the introduction of
336   attachment-down.  We need the center of the note head for that, so we
337   just delegate the work to Note_head::get_stem_attachment.
338 */
339 
340 pair<Offset, bool>
attachment_point(const string & glyph_name,Direction d) const341 Open_type_font::attachment_point (const string &glyph_name, Direction d) const
342 {
343   SCM sym = ly_symbol2scm (glyph_name.c_str ());
344   SCM entry = scm_hashq_ref (lily_character_table_, sym, SCM_BOOL_F);
345 
346   Offset o;
347   if (scm_is_false (entry))
348     return make_pair (o, false); // TODO: error out?
349 
350   SCM char_alist = entry;
351   SCM att_scm;
352   bool rotate = false;
353   if (d == DOWN)
354     {
355       att_scm = scm_assq_ref (char_alist, ly_symbol2scm ("attachment-down"));
356       if (scm_is_false (att_scm))
357         {
358           rotate = true;
359         }
360     }
361 
362   if (d == UP || rotate)
363     {
364       att_scm = scm_assq_ref (char_alist, ly_symbol2scm ("attachment"));
365       if (scm_is_false (att_scm))
366         {
367           warning (_f ("no stem attachment found in font for glyph %s",
368                        glyph_name));
369           return make_pair (o, false);
370         }
371     }
372 
373   return make_pair (point_constant * from_scm<Offset> (att_scm), rotate);
374 }
375 
376 Box
get_indexed_char_dimensions(size_t signed_idx) const377 Open_type_font::get_indexed_char_dimensions (size_t signed_idx) const
378 {
379   auto const &bbox_it = lily_index_to_bbox_table_.find (signed_idx);
380   if (bbox_it != lily_index_to_bbox_table_.end ())
381     {
382       return bbox_it->second;
383     }
384 
385   const size_t len = 256;
386   char name[len];
387   FT_Error code = FT_Get_Glyph_Name (face_, FT_UInt (signed_idx),
388                                      name, FT_UInt (len));
389   if (code)
390     warning (_f ("FT_Get_Glyph_Name () Freetype error: %s",
391                  freetype_error_string (code)));
392 
393   SCM sym = ly_symbol2scm (name);
394   SCM alist = scm_hashq_ref (lily_character_table_, sym, SCM_BOOL_F);
395 
396   if (scm_is_true (alist))
397     {
398       SCM bbox = scm_cdr (scm_assq (ly_symbol2scm ("bbox"), alist));
399 
400       Box b;
401       b[X_AXIS][LEFT] = scm_to_double (scm_car (bbox));
402       bbox = scm_cdr (bbox);
403       b[Y_AXIS][LEFT] = scm_to_double (scm_car (bbox));
404       bbox = scm_cdr (bbox);
405       b[X_AXIS][RIGHT] = scm_to_double (scm_car (bbox));
406       bbox = scm_cdr (bbox);
407       b[Y_AXIS][RIGHT] = scm_to_double (scm_car (bbox));
408       bbox = scm_cdr (bbox);
409 
410       b.scale (point_constant);
411 
412       lily_index_to_bbox_table_[signed_idx] = b;
413       return b;
414     }
415 
416   Box b = get_unscaled_indexed_char_dimensions (signed_idx);
417 
418   b.scale (design_size () / static_cast<Real> (face_->units_per_EM));
419   return b;
420 }
421 
422 Real
get_units_per_EM() const423 Open_type_font::get_units_per_EM () const
424 {
425   return face_->units_per_EM;
426 }
427 
428 size_t
name_to_index(string nm) const429 Open_type_font::name_to_index (string nm) const
430 {
431   auto it = name_to_index_map_.find (nm);
432   if (it != name_to_index_map_.end ())
433     {
434       return it->second;
435     }
436 
437   FT_UInt idx = FT_Get_Name_Index (face_, const_cast<char *> (nm.c_str ()));
438   size_t result = (idx != 0) ? idx : GLYPH_INDEX_INVALID;
439   name_to_index_map_[nm] = result;
440   return result;
441 }
442 
443 Box
get_unscaled_indexed_char_dimensions(size_t signed_idx) const444 Open_type_font::get_unscaled_indexed_char_dimensions (size_t signed_idx) const
445 {
446   return ly_FT_get_unscaled_indexed_char_dimensions (face_, signed_idx);
447 }
448 
449 Box
get_glyph_outline_bbox(size_t signed_idx) const450 Open_type_font::get_glyph_outline_bbox (size_t signed_idx) const
451 {
452   return ly_FT_get_glyph_outline_bbox (face_, signed_idx);
453 }
454 
455 void
add_outline_to_skyline(Lazy_skyline_pair * lazy,Transform const & transform,size_t signed_idx) const456 Open_type_font::add_outline_to_skyline (Lazy_skyline_pair *lazy,
457                                         Transform const &transform,
458                                         size_t signed_idx) const
459 {
460   ly_FT_add_outline_to_skyline (lazy, transform, face_, signed_idx);
461 }
462 
463 size_t
index_to_charcode(size_t i) const464 Open_type_font::index_to_charcode (size_t i) const
465 {
466   map<FT_UInt, FT_ULong>::const_iterator iter;
467   iter = index_to_charcode_map_.find (FT_UInt (i));
468 
469   if (iter != index_to_charcode_map_.end ())
470     return static_cast<size_t> (iter->second);
471   else
472     {
473       programming_error ("Invalid index for character");
474       return 0;
475     }
476 }
477 
478 size_t
count() const479 Open_type_font::count () const
480 {
481   return index_to_charcode_map_.size ();
482 }
483 
484 Real
design_size() const485 Open_type_font::design_size () const
486 {
487   SCM entry = scm_hashq_ref (lily_global_table_,
488                              ly_symbol2scm ("design_size"),
489 
490                              /*
491                                Hmm. Design size is arbitrary for
492                                non-design-size fonts. I vote for 1 -
493                                which will trip errors more
494                                quickly. --hwn.
495                              */
496                              to_scm (1));
497   return scm_to_double (entry) * static_cast<Real> (point_constant);
498 }
499 
500 SCM
sub_fonts() const501 Open_type_font::sub_fonts () const
502 {
503   return lily_subfonts_;
504 }
505 
506 SCM
get_char_table() const507 Open_type_font::get_char_table () const
508 {
509   return lily_character_table_;
510 }
511 
512 SCM
get_subfonts() const513 Open_type_font::get_subfonts () const
514 {
515   return lily_subfonts_;
516 }
517 
518 SCM
get_global_table() const519 Open_type_font::get_global_table () const
520 {
521   return lily_global_table_;
522 }
523 
524 string
font_name() const525 Open_type_font::font_name () const
526 {
527   return postscript_name_;
528 }
529 
530 SCM
glyph_list() const531 Open_type_font::glyph_list () const
532 {
533   SCM retval = SCM_EOL;
534   SCM *tail = &retval;
535 
536   for (int i = 0; i < face_->num_glyphs; i++)
537     {
538       const size_t len = 256;
539       char name[len];
540       FT_Error code = FT_Get_Glyph_Name (face_, i, name, len);
541       if (code)
542         warning (_f ("FT_Get_Glyph_Name () error: %s",
543                      freetype_error_string (code).c_str ()));
544 
545       *tail = scm_cons (scm_from_ascii_string (name), SCM_EOL);
546       tail = SCM_CDRLOC (*tail);
547     }
548 
549   return retval;
550 }
551