summaryrefslogtreecommitdiff
path: root/lily/ttf.cc
blob: e46628ab0c183661964837d5e7f69c8d36d591d1 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
/*
  This file is part of LilyPond, the GNU music typesetter.

  Copyright (C) 2005--2014 Han-Wen Nienhuys <hanwen@xs4all.nl>

  LilyPond is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  LilyPond is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <cstdio>
#include "freetype.hh"

#include FT_TRUETYPE_TABLES_H

#include "international.hh"
#include "memory-stream.hh"
#include "warn.hh"
#include "lily-guile.hh"
#include "main.hh"
#include "open-type-font.hh"

Index_to_charcode_map
make_index_to_charcode_map (FT_Face face)
{
  Index_to_charcode_map m;
  FT_ULong charcode;
  FT_UInt gindex;

  FT_CharMap current_cmap = face->charmap;
  FT_Select_Charmap (face, FT_ENCODING_UNICODE);

  int j = 0;
  for (charcode = FT_Get_First_Char (face, &gindex); gindex != 0;
       charcode = FT_Get_Next_Char (face, charcode, &gindex))
    {
      m[gindex] = charcode;
      j++;
    }
  FT_Set_Charmap (face, current_cmap);

  return m;
}

/*
  Based on ttfps by Juliusz Chroboczek
*/
static void
print_header (void *out, FT_Face face)
{
  lily_cookie_fprintf (out, "%%!PS-TrueTypeFont\n");

  TT_Postscript *pt
    = (TT_Postscript *) FT_Get_Sfnt_Table (face, ft_sfnt_post);

  if (pt->maxMemType42)
    lily_cookie_fprintf (out, "%%%%VMUsage: %d %d\n", 0, 0);

  lily_cookie_fprintf (out, "%d dict begin\n", 11);
  lily_cookie_fprintf (out, "/FontName /%s def\n",
                       FT_Get_Postscript_Name (face));

  lily_cookie_fprintf (out, "/Encoding StandardEncoding def\n");
  lily_cookie_fprintf (out, "/PaintType 0 def\n");
  lily_cookie_fprintf (out, "/FontMatrix [1 0 0 1 0 0] def\n");

  TT_Header *ht
    = (TT_Header *)FT_Get_Sfnt_Table (face, ft_sfnt_head);

  lily_cookie_fprintf (out, "/FontBBox [%lf %lf %lf %lf] def\n",
                       float (ht->xMin) / float (ht->Units_Per_EM),
                       float (ht->yMin) / float (ht->Units_Per_EM),
                       float (ht->xMax) / float (ht->Units_Per_EM),
                       float (ht->yMax) / float (ht->Units_Per_EM));

  lily_cookie_fprintf (out, "/FontType 42 def\n");
  lily_cookie_fprintf (out, "/FontInfo 8 dict dup begin\n");
  lily_cookie_fprintf (out, "/version (%.3f) def\n",
                       ht->Font_Revision / 65536.0);

#if 0
  if (strings[0])
    {
      lily_cookie_fprintf (out, "/Notice (");
      fputpss (strings[0], out);
      lily_cookie_fprintf (out, ") def\n");
    }
  if (strings[4])
    {
      lily_cookie_fprintf (out, "/FullName (");
      fputpss (strings[4], out);
      lily_cookie_fprintf (out, ") def\n");
    }
  if (strings[1])
    {
      lily_cookie_fprintf (out, "/FamilyName (");
      fputpss (strings[1], out);
      lily_cookie_fprintf (out, ") def\n");
    }
#endif

  lily_cookie_fprintf (out, "/isFixedPitch %s def\n",
                       pt->isFixedPitch ? "true" : "false");
  lily_cookie_fprintf (out, "/UnderlinePosition %lf def\n",
                       float (pt->underlinePosition)
                       / float (ht->Units_Per_EM));
  lily_cookie_fprintf (out, "/UnderlineThickness %lf def\n",
                       float (pt->underlineThickness)
                       / float (ht->Units_Per_EM));
  lily_cookie_fprintf (out, "end readonly def\n");
}

#define CHUNKSIZE 65534

const FT_ULong FT_ENC_TAG (glyf_tag, 'g', 'l', 'y', 'f');
const FT_ULong FT_ENC_TAG (head_tag, 'h', 'e', 'a', 'd');
const FT_ULong FT_ENC_TAG (loca_tag, 'l', 'o', 'c', 'a');

static
void t42_write_table (void *out, FT_Face face, unsigned char const *buffer,
                      size_t s, bool is_glyf,
                      FT_ULong head_length, FT_ULong loca_length)
{
  vector<FT_UShort> chunks;

  if (is_glyf)
    {
      /* compute chunk sizes */
      unsigned char *head_buf = new unsigned char[head_length];
      FT_Error error = FT_Load_Sfnt_Table (face, head_tag, 0, head_buf, NULL);
      if (error)
        programming_error ("FT_Load_Sfnt_Table (): error.");

      /* we access the lower byte of indexToLocFormat */
      bool long_offsets = head_buf[4 * 4 + 2 * 2 + 2 * 8 + 4 * 2 + 3 * 2 + 1] == 1;

      delete[] head_buf;

      unsigned char *loca_buf = new unsigned char[loca_length];
      error = FT_Load_Sfnt_Table (face, loca_tag, 0, loca_buf, NULL);
      if (error)
        programming_error ("FT_Load_Sfnt_Table (): error.");

      unsigned char *p = loca_buf;
      unsigned char *endp = loca_buf + loca_length;

      FT_ULong offset = 0, last_offset = 0, last_chunk = 0;
      while (p < endp)
        {
          if (long_offsets)
            {
              offset = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
              p += 4;
            }
          else
            {
              offset = ((p[0] << 8) | p[1]) << 1;
              p += 2;
            }
          if (offset > last_offset + CHUNKSIZE)
            {
              if (last_chunk != last_offset)
                chunks.push_back (FT_UShort (last_offset - last_chunk));
              /*
                a single glyph with more than 64k data
                is a pathological case but...
               */
              FT_ULong rest = offset - last_offset;
              while (rest > CHUNKSIZE)
                {
                  chunks.push_back (CHUNKSIZE);
                  rest -= CHUNKSIZE;
                }
              chunks.push_back (FT_UShort (rest));
              last_chunk = offset;
            }
          else if (offset > last_chunk + CHUNKSIZE)
            {
              chunks.push_back (FT_UShort (last_offset - last_chunk));
              last_chunk = last_offset;
            }

          last_offset = offset;
        }
      chunks.push_back (FT_UShort (s - last_chunk));

      delete[] loca_buf;
    }
  else if (s > CHUNKSIZE)
    {
      FT_ULong rest = s;
      while (rest > CHUNKSIZE)
        {
          chunks.push_back (CHUNKSIZE);
          rest -= CHUNKSIZE;
        }
      chunks.push_back (FT_UShort (rest));
    }
  else
    chunks.push_back (CHUNKSIZE);

  lily_cookie_fprintf (out, "\n"
                       " <");

  int l = 0;
  static char xdigits[] = "0123456789ABCDEF";

  int cur_chunk_idx = 0;
  for (size_t j = 0; j < s; j++)
    {
      if (l >= chunks[cur_chunk_idx])
        {
          lily_cookie_fprintf (out, "\n"
                               " 00>\n"
                               " <");
          l = 0;
          cur_chunk_idx++;
        }

      if (l % 31 == 0)
        lily_cookie_fprintf (out, "\n"
                             "  ");

      /* lily_cookie_fprintf (out,"%02X",(int)buffer[j]) is too slow */
      lily_cookie_putc (xdigits[(buffer[j] & 0xF0) >> 4], out);
      lily_cookie_putc (xdigits[buffer[j] & 0x0F], out);

      l++;
    }

  /* pad to four-byte boundary */
  while ((s++) % 4 != 0)
    lily_cookie_fprintf (out, "00");

  lily_cookie_fprintf (out, "\n"
                       "  00\n"
                       " >");
}

static void
print_body (void *out, FT_Face face)
{
  FT_UInt idx = 0;
  FT_ULong head_length = 0, loca_length = 0;
  FT_ULong tag, length;
  vector<FT_ULong> lengths, tags;

  /*
    we must build our own TTF header -- the original font
    might be a TTC where tables are not contiguous, or the font
    contains tables which aren't indexed at all
   */
  while (FT_Sfnt_Table_Info (face, idx, &tag, &length)
         != FT_Err_Table_Missing)
    {
      lengths.push_back (length);
      tags.push_back (tag);
      if (tag == head_tag)
        head_length = length;
      else if (tag == loca_tag)
        loca_length = length;
      idx++;
    }

  FT_ULong hlength = 12 + 16 * idx;

  unsigned char *hbuf = new unsigned char[hlength];
  unsigned char *p;

  hbuf[0] = 0x00;                                       /* version */
  hbuf[1] = 0x01;
  hbuf[2] = 0x00;
  hbuf[3] = 0x00;
  hbuf[4] = (unsigned char) ((idx & 0xFF00) >> 8);      /* numTables */
  hbuf[5] = idx & 0x00FF;

  FT_UInt searchRange, entrySelector, rangeShift;
  FT_UInt i, j;
  for (i = 1, j = 2; j <= idx; i++, j <<= 1)
    ;
  entrySelector = i - 1;
  searchRange = 0x10 << entrySelector;
  rangeShift = (idx << 4) - searchRange;

  hbuf[6] = (unsigned char) ((searchRange & 0xFF00) >> 8);
  hbuf[7] = searchRange & 0x00FF;
  hbuf[8] = (unsigned char) ((entrySelector & 0xFF00) >> 8);
  hbuf[9] = entrySelector & 0x00FF;
  hbuf[10] = (unsigned char) ((rangeShift & 0xFF00) >> 8);
  hbuf[11] = rangeShift & 0x00FF;

  p = &hbuf[12];

  FT_ULong checksum, font_checksum = 0;

  FT_ULong offset = hlength;            /* first table offset */

  for (FT_UInt i = 0; i < idx; i++)
    {
      /* here, the buffer length must be a multiple of 4 */
      FT_ULong len = (lengths[i] + 3) & ~3;
      unsigned char *buf = new unsigned char[len];

      buf[len - 1] = 0x00;                /* assure padding with zeros */
      buf[len - 2] = 0x00;
      buf[len - 3] = 0x00;

      FT_Error error = FT_Load_Sfnt_Table (face, tags[i], 0, buf, NULL);
      if (error)
        programming_error ("FT_Load_Sfnt_Table (): error.");

      if (tag == head_tag)
        {
          /*
            first pass of computing the font checksum
            needs checkSumAdjustment = 0
           */
          buf[8] = 0x00;
          buf[9] = 0x00;
          buf[10] = 0x00;
          buf[11] = 0x00;
        }

      checksum = 0;
      unsigned char *endq = buf + len;
      for (unsigned char *q = buf; q < endq; q += 4)
        checksum += (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
      font_checksum += checksum;

      delete[] buf;

      *(p++) = (unsigned char) ((tags[i] & 0xFF000000UL) >> 24);
      *(p++) = (unsigned char) ((tags[i] & 0x00FF0000UL) >> 16);
      *(p++) = (unsigned char) ((tags[i] & 0x0000FF00UL) >> 8);
      *(p++) = tags[i] & 0x000000FFUL;

      *(p++) = (unsigned char) ((checksum & 0xFF000000UL) >> 24);
      *(p++) = (unsigned char) ((checksum & 0x00FF0000UL) >> 16);
      *(p++) = (unsigned char) ((checksum & 0x0000FF00UL) >> 8);
      *(p++) = checksum & 0x000000FFUL;

      *(p++) = (unsigned char) ((offset & 0xFF000000UL) >> 24);
      *(p++) = (unsigned char) ((offset & 0x00FF0000UL) >> 16);
      *(p++) = (unsigned char) ((offset & 0x0000FF00UL) >> 8);
      *(p++) = offset & 0x000000FFUL;

      *(p++) = (unsigned char) ((lengths[i] & 0xFF000000UL) >> 24);
      *(p++) = (unsigned char) ((lengths[i] & 0x00FF0000UL) >> 16);
      *(p++) = (unsigned char) ((lengths[i] & 0x0000FF00UL) >> 8);
      *(p++) = lengths[i] & 0x000000FFUL;

      /* offset must be a multiple of 4 */
      offset += (lengths[i] + 3) & ~3;
    }

  /* add checksum of TTF header */
  checksum = 0;
  for (unsigned char *q = hbuf; q < p; q += 4)
    checksum += (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
  font_checksum += checksum;
  font_checksum = 0xB1B0AFBAUL - font_checksum;

  /*
    see Adobe technical note 5012.Type42_Spec.pdf for details how
    the /sfnts array must be constructed
   */
  lily_cookie_fprintf (out, "/sfnts [");
  t42_write_table (out, face, hbuf, hlength, false,
                   head_length, loca_length);
  delete[] hbuf;

  idx = 0;

  while (FT_Sfnt_Table_Info (face, idx, &tag, &length)
         != FT_Err_Table_Missing)
    {
      unsigned char *buf = new unsigned char[length];
      FT_Error error = FT_Load_Sfnt_Table (face, tag, 0, buf, NULL);
      if (error)
        programming_error ("FT_Load_Sfnt_Table (): error.");

      if (tag == head_tag)
        {
          /* in the second pass simply store the computed font checksum */
          buf[8] = (unsigned char) ((font_checksum & 0xFF000000UL) >> 24);
          buf[9] = (unsigned char) ((font_checksum & 0x00FF0000UL) >> 16);
          buf[10] = (unsigned char) ((font_checksum & 0x0000FF00UL) >> 8);
          buf[11] = font_checksum & 0x000000FFUL;
        }

      bool is_glyf_table = tag == glyf_tag && length > CHUNKSIZE;
      t42_write_table (out, face, buf, length, is_glyf_table,
                       head_length, loca_length);

      delete[] buf;
      idx++;
    }
  lily_cookie_fprintf (out, "\n] def\n");
}

static void
print_trailer (void *out,
               FT_Face face)
{
  const int GLYPH_NAME_LEN = 256;
  char glyph_name[GLYPH_NAME_LEN];

  TT_MaxProfile *mp
    = (TT_MaxProfile *)FT_Get_Sfnt_Table (face, ft_sfnt_maxp);

  lily_cookie_fprintf (out, "/CharStrings %d dict dup begin\n", mp->numGlyphs);

  Index_to_charcode_map ic_map (make_index_to_charcode_map (face));

  int output_count = 0;
  for (int i = 0; i < mp->numGlyphs; i++)
    {
      glyph_name[0] = 0;
      if (face->face_flags & FT_FACE_FLAG_GLYPH_NAMES)
        {
          FT_Error error = FT_Get_Glyph_Name (face, i, glyph_name,
                                              GLYPH_NAME_LEN);
          if (error)
            {
              programming_error ("FT_Get_Glyph_Name (): error.");
              glyph_name[0] = 0;
            }
        }

      if (!glyph_name[0] && ic_map.find (i) != ic_map.end ())
        {
          FT_ULong ucode = ic_map[i];
          get_unicode_name (glyph_name, ucode);
        }

      if (i == 0)
        sprintf (glyph_name, ".notdef");
      else if (glyph_name == string (".notdef"))
        glyph_name[0] = '\0';

      if (!glyph_name[0])
        get_glyph_index_name (glyph_name, i);

      if (glyph_name[0])
        {
          lily_cookie_fprintf (out, "(%s) cvn %d def ", glyph_name, i);
          output_count++;
        }
      else
        programming_error (to_string ("no name for glyph %d", i));

      if (! (output_count % 5))
        lily_cookie_fprintf (out, "\n");
    }

  lily_cookie_fprintf (out, "end readonly def\n");
  lily_cookie_fprintf (out, "FontName currentdict end definefont pop\n");
}

static void
create_type42_font (void *out, const string &name, int idx)
{
  FT_Face face;

  /* check whether font index is valid */
  if (idx > 0)
    {
      face = open_ft_face (name, -1);
      if (idx >= face->num_faces)
        {
          warning (_f ("font index %d too large for font `%s', using index 0",
                       idx, name.c_str ()));
          idx = 0;
        }
      FT_Done_Face (face);
    }

  face = open_ft_face (name, idx);

  print_header (out, face);
  print_body (out, face);
  print_trailer (out, face);

  FT_Done_Face (face);
}

LY_DEFINE (ly_ttf_ps_name, "ly:ttf-ps-name",
           1, 1, 0, (SCM ttf_file_name, SCM idx),
           "Extract the PostScript name from a TrueType font.  The optional"
           " @var{idx} argument is useful for TrueType collections (TTC)"
           " only; it specifies the font index within the TTC.  The default"
           " value of @var{idx} is@tie{}0.")
{
  LY_ASSERT_TYPE (scm_is_string, ttf_file_name, 1);

  int i = 0;
  if (idx != SCM_UNDEFINED)
    {
      LY_ASSERT_TYPE (scm_is_integer, idx, 2);
      i = scm_to_int (idx);
      if (i < 0)
        {
          warning (_ ("font index must be non-negative, using index 0"));
          i = 0;
        }
    }

  string file_name = ly_scm2string (ttf_file_name);
  debug_output ("\n[" + file_name, false);

  FT_Face face;

  /* check whether font index is valid */
  if (i > 0)
    {
      face = open_ft_face (file_name, -1);
      if (i >= face->num_faces)
        {
          warning (_f ("font index %d too large for font `%s', using index 0",
                       i, file_name.c_str ()));
          i = 0;
        }
      FT_Done_Face (face);
    }

  face = open_ft_face (file_name, i);
  char const *ps_name_str0 = FT_Get_Postscript_Name (face);
  SCM ps_name = scm_from_locale_string (ps_name_str0 ? ps_name_str0 : "");
  FT_Done_Face (face);

  debug_output ("]", false);

  return ps_name;
}

LY_DEFINE (ly_ttf_2_pfa, "ly:ttf->pfa",
           1, 1, 0, (SCM ttf_file_name, SCM idx),
           "Convert the contents of a TrueType font file to PostScript"
           " Type@tie{}42 font, returning it as a string.  The optional"
           " @var{idx} argument is useful for TrueType collections (TTC)"
           " only; it specifies the font index within the TTC.  The default"
           " value of @var{idx} is@tie{}0.")
{
  LY_ASSERT_TYPE (scm_is_string, ttf_file_name, 1);

  int i = 0;
  if (idx != SCM_UNDEFINED)
    {
      LY_ASSERT_TYPE (scm_is_integer, idx, 2);
      i = scm_to_int (idx);
      if (i < 0)
        {
          warning (_ ("font index must be non-negative, using index 0"));
          i = 0;
        }
    }

  string file_name = ly_scm2string (ttf_file_name);
  debug_output ("[" + file_name); // Debug message should start on a new line

  Memory_out_stream stream;

  create_type42_font (&stream, file_name, i);
  SCM asscm = scm_from_locale_stringn (stream.get_string (),
                                       stream.get_length ());

  debug_output ("]", false);

  return asscm;
}