Debian Codegraph @

texk/xdvipsk/bitmapenc.c

raw
1 /*
2 * This file implements support for adding proper character encodings to
3 * bitmap fonts, so searching and copying text works better in PDFs
4 * generated by the dvips Postscript output that uses bitmap fonts.
5 *
6 * Written by Tomas Rokicki in June/July 2019. Public domain.
7 * The dvips-all.enc file used here is also public domain.
8 *
9 * It turns out we need to do more than just add encodings to the fonts
10 * for most PDF viewers, so this file also takes care of those issues.
11 */
12 /*
13 * Our first concern is finding and reading encoding files for bitmap
14 * fonts, and, if such cannot be found, determining a reasonable
15 * alternative.
16 *
17 * We could use the code in writet1 to read an encoding file, but
18 * we would need to make some messy changes for that to work, and we
19 * really want this to be a minimal impact to existing code (especially
20 * code such as write_t1 that we don't have a good handle on).
21 *
22 * We want to deduplicate (combine identical) encodings to lower the
23 * memory and file size impact. But we have to be careful; if the
24 * document requires multiple sections, we need to redownload encodings
25 * just like we do fonts.
26 */
27 #include <stdio.h>
28 #include <string.h>
29 #ifndef STANDALONE
30 #include <kpathsea/config.h>
31 #endif
32 #ifndef XDVIPSK
33 #include "dvips.h"
34 #else
35 #include "xdvips.h"
36 #endif /* XDVIPSK */
37 #include "protos.h"
38 /*
39 * Do we use this functionality? If 0, then no; if 1, then yes, but
40 * suppress warnings; if 2, then warn.
41 */
42 int encodetype3 = 1 ;
43 void bitmapencopt(int v) {
44 if (0 <= v && v <= 2)
45 encodetype3 = v ;
46 else
47 error("! Bad option to J") ;
48 }
49 /*
50 * TODO
51 *
52 * Initially we support standalone compilation for testing but
53 * this code will be ripped out before release.
54 */
55 #ifdef STANDALONE
56 #undef fopen
57 #undef fclose
58 #endif
59 /*
60 * Reading the encodings.
61 *
62 * Encodings we read are returned as an array C strings. We do not
63 * attempt to parse the contents of the encodings, because they
64 * may contain additional dictionaries or other PostScript code
65 * that can possibly do more advanced things.
66 */
67 #define MAX_LINE_LENGTH 256
68 /*
69 * A structure for storing deduplicated encodings. These are deduplicated
70 * in dvips memory on load. We also store information on whether the
71 * encoding has been downloaded in a particular section. This is stored
72 * as a singly-linked list for all distinct encodings we have used so
73 * far.
74 */
75 struct bmenc {
76 const char **enc ; // the encoding itself
77 int downloaded_seq ; // -1: not downloaded; else, sequence number
78 struct bmenc *next ; // next encoding in linear linked list
79 unsigned char existsbm[32] ; // a bitmap of characters with names
80 } ;
81 static struct bmenc *bmlist ;
82 /*
83 * This structure maintains a relationship between a font name and a
84 * bitmap encoding. Again, linear search is used.
85 */
86 struct bmfontenc {
87 const char *fontname ; // dvi font name
88 struct bmenc *enc ; // the encoding to use
89 struct bmfontenc *next ; // next encoding
90 } ;
91 static struct bmfontenc *bmfontenclist ;
92 /*
93 * We load the default encodings for all fonts en masse from he
94 * dvips-all.enc file, and store them here. We use an array and
95 * sort the input for quicker search. We don't need to deduplicate
96 * because we assume whatever generated dvips-all.enc already did
97 * deduplication.
98 */
99 static int numstatic ;
100 static struct allfontenc {
101 const char *fontname ;
102 const char **enc ;
103 } *bmfontarr ;
104 /*
105 * While loading dvips-all.enc, we track the capacity of our allfontenc
106 * array, how many have names, the capacity in strings of our encoding
107 * that is being built up, and how many strings we still can store in
108 * the encoding built up.
109 */
110 static int capstatic, namedstatic ;
111 static int in_working_enc, working_enc_left ;
112 const char **working_enc ;
113 /*
114 * Add another fontname to the list (from the dvips-all.enc file).
115 * If needed expand the working arrays. If there is currently
116 * an encoding, that means that we need to first assign that
117 * encoding to the list of font names we have built up, so do
118 * that first. If the fontname passed is the null string, this is
119 * the last call done just to finish up the last encoding.
120 */
121 static void add_fontname(const char *fontname) {
122 int i ;
123 if (in_working_enc) { // flush
124 const char **e = working_enc ;
125 while (numstatic < namedstatic)
126 bmfontarr[numstatic++].enc = e ;
127 working_enc += in_working_enc + 1 ;
128 working_enc_left -= in_working_enc + 1 ;
129 in_working_enc = 0 ;
130 }
131 if (fontname == 0)
132 return ;
133 if (namedstatic >= capstatic) {
134 int ncapstatic = capstatic * 2 + 20 ;
135 struct allfontenc *nbmfontarr =
136 (struct allfontenc *)mymalloc(sizeof(struct allfontenc) * ncapstatic) ;
137 if (capstatic) {
138 memcpy(nbmfontarr, bmfontarr, sizeof(struct allfontenc)*capstatic) ;
139 free(bmfontarr) ;
140 }
141 bmfontarr = nbmfontarr ;
142 for (i=capstatic; i<ncapstatic; i++) {
143 bmfontarr[i].fontname = 0 ;
144 bmfontarr[i].enc = 0 ;
145 }
146 capstatic = ncapstatic ;
147 }
148 bmfontarr[namedstatic].fontname = fontname ;
149 bmfontarr[namedstatic].enc = 0 ;
150 namedstatic++ ;
151 }
152 /*
153 * Add an encoding line to the working encoding; if needed, reallocate
154 * the working array.
155 */
156 static void add_encline(const char *encline) {
157 if (in_working_enc + 1 >= working_enc_left) {
158 int i ;
159 int new_enc_size = 100 + 2 * in_working_enc ;
160 const char **new_working_enc =
161 (const char **)mymalloc(sizeof(const char **) * new_enc_size) ;
162 for (i=0; i<new_enc_size; i++)
163 new_working_enc[i] = 0 ;
164 for (i=0; i<in_working_enc; i++)
165 new_working_enc[i] = working_enc[i] ;
166 working_enc = new_working_enc ;
167 working_enc_left = new_enc_size - in_working_enc ;
168 }
169 working_enc[in_working_enc++] = encline ;
170 }
171 /*
172 * Parse the encoding file. If use_all flag is set then we are parsing
173 * the dvips_all file which can have multiple encodings, each preceded
174 * by a set of lines with font names followed by a colon character.
175 *
176 * If we are parsing them all, we build a sorted global list of entries
177 * for later lookup, and always return 0. Otherwise we just expect a
178 * single encoding and we store that away.
179 */
180 static const char **parseencodingfile(FILE *f, int use_all) {
181 char encbuf[MAX_LINE_LENGTH+1] ;
182 size_t i ;
183 for (i=0; i<sizeof(encbuf); i++)
184 encbuf[i] = 0 ;
185 while (fgets(encbuf, MAX_LINE_LENGTH, f) != 0) {
186 char *p = encbuf ;
187 char *q = p + strlen(p) - 1 ;
188 while (q > p && *q < ' ') // kill line terminators
189 *q-- = 0 ;
190 q = p ;
191 while (*q && *q != ' ' && *q != ':')
192 q++ ;
193 if (use_all && *q == ':') { // looks like a font name
194 if (q[1] >= ' ' || !use_all)
195 error(
196 "! unexpected colon or extra stuff at end of line in encoding file?") ;
197 *q = 0 ;
198 add_fontname(strdup(p)) ;
199 } else {
200 add_encline(strdup(p)) ;
201 }
202 }
203 if (use_all)
204 add_fontname(0) ; // flushes last encoding
205 if (use_all) {
206 // sort the static fonts for quicker search; Shell sort
207 int h = 1 ;
208 while (h < numstatic)
209 h = 3 * h + 1 ;
210 while (h > 1) {
211 int i ;
212 h /= 3 ;
213 for (i=h; i<numstatic; i++) {
214 int j = i ;
215 while (j >= h &&
216 strcmp(bmfontarr[j-h].fontname, bmfontarr[j].fontname) > 0) {
217 const char *na = bmfontarr[j-h].fontname ;
218 const char **en = bmfontarr[j-h].enc ;
219 bmfontarr[j-h].fontname = bmfontarr[j].fontname ;
220 bmfontarr[j-h].enc = bmfontarr[j].enc ;
221 bmfontarr[j].fontname = na ;
222 bmfontarr[j].enc = en ;
223 j -= h ;
224 }
225 }
226 }
227 return 0 ;
228 } else {
229 const char **e = working_enc ;
230 if (e == 0)
231 error("! No lines in encoding?") ;
232 return e ;
233 }
234 }
235 /*
236 * Given a font name, find an encoding file. We prefix all encoding
237 * files with "dvips-" to distinguish these encodings from those used
238 * in the psfonts.map, since the syntax, requirements, and function
239 * is somewhat different.
240 */
241 #define MAX_NAME_SIZE 256
242 static FILE *bitmap_enc_search(const char *fontname) {
243 char namebuf[MAX_NAME_SIZE+1] ;
244 if (fontname == 0 || strlen(fontname) > 128)
245 error("! excessively long font name") ;
246 sprintf(namebuf, "dvips-%s.enc", fontname) ;
247 #ifdef STANDALONE
248 return fopen(namebuf, FOPEN_RBIN_MODE) ;
249 #else
250 return search(kpse_enc_format, namebuf, FOPEN_RBIN_MODE) ;
251 #endif
252 }
253 /*
254 * Are two raw encodings identical? They must be exactly the same; there
255 * is no effort towards comparing semantics, just precise text.
256 */
257 static int eqencoding(const char **a, const char **b) {
258 int i ;
259 if (a == b)
260 return 1 ;
261 for (i=0; a[i] != 0 && b[i] != 0; i++)
262 if (a[i] != b[i] && (a[i] == 0 || b[i] == 0 || strcmp(a[i], b[i]) != 0))
263 return 0 ;
264 return 1 ;
265 }
266 /*
267 * Try to parse an encoding to identify which names exist and which don't.
268 * If we can't trivially parse it we just mark all names as existing.
269 * We properly parse the following types of tokens:
270 * [ (at start) ] (at end) : ignored
271 * /name
272 * digits { /.notdef } repeat
273 *
274 * In all cases the spaces and linebreaks are arbitrary.
275 *
276 * The state machine works as follows:
277 *
278 * 'B': begin; expect [
279 * 'N': between entries; expect name or digits or ]
280 * 'E': finished (saw ]); expect nothing more
281 * '#': just saw digits; expect only {
282 * '{': just saw {; expect only name and should be /.notdef
283 * 'L': just saw a name inside {}; expect only }
284 * '}': just saw }; expect only repeat
285 */
286 static int trytoparseenc(struct bmenc *bme) {
287 int i ;
288 const char **enc = bme->enc ;
289 const char *p ;
290 int seenchars = 0 ;
291 int num = 0 ;
292 char state = 'B' ;
293 for (i=0; i<32; i++)
294 bme->existsbm[i] = 255 ;
295 while (*enc != 0) {
296 p = *enc ;
297 enc++ ;
298 while (*p && *p <= ' ')
299 p++ ;
300 while (*p != 0) {
301 switch (state) {
302 case 'B': if (*p != '[') return 0 ;
303 p++ ;
304 state = 'N' ;
305 break ;
306 case 'N': if (*p == ']') {
307 p++ ;
308 state = 'E' ;
309 } else if (*p == '/') {
310 if (seenchars >= 256)
311 return 0 ;
312 if (strncmp(p, "/.notdef", 8) == 0 &&
313 (p[8] <= ' ' || strchr("{}[]<>()%/", p[8]) == 0)) {
314 bme->existsbm[seenchars>>3] &= ~(1<<(seenchars & 7)) ;
315 }
316 // see PostScript language reference manual syntax for this
317 p++ ;
318 while (*p > ' ' && strchr("{}[]<>()%/", *p) == 0)
319 p++ ;
320 seenchars++ ;
321 } else if ('0' <= *p && *p <= '9') {
322 num = 0 ;
323 while (num < 256 && '0' <= *p && *p <= '9')
324 num = 10 * num + *p++ - '0' ;
325 state = '#' ;
326 } else
327 return 0 ;
328 break ;
329 case '#': if (*p != '{') return 0 ;
330 p++ ;
331 state = '{' ;
332 break ;
333 case '{': if (strncmp(p, "/.notdef", 8) != 0)
334 return 0 ;
335 p += 8 ;
336 if (*p > ' ' && strchr("{}[]<>()%/", *p) == 0)
337 return 0 ;
338 while (num > 0) {
339 if (seenchars >= 256)
340 return 0 ;
341 bme->existsbm[seenchars>>3] &= ~(1<<(seenchars & 7)) ;
342 seenchars++ ;
343 num-- ;
344 }
345 state = 'L' ;
346 break ;
347 case 'L': if (*p != '}')
348 return 0 ;
349 p++ ;
350 state = '}' ;
351 break ;
352 case '}': if (strncmp(p, "repeat", 6) != 0)
353 return 0 ;
354 p += 6 ;
355 state = 'N' ;
356 break ;
357 default:
358 error("! internal error in encoding vector parse") ;
359 }
360 while (*p && *p <= ' ')
361 p++ ;
362 }
363 }
364 if (seenchars != 256)
365 return 0 ;
366 return 1 ;
367 }
368 static void parseenc(struct bmenc *bme) {
369 int i ;
370 if (trytoparseenc(bme) == 0) {
371 printf("Failed to parse it.\n") ;
372 for (i=0; i<32; i++)
373 bme->existsbm[i] = 255 ;
374 }
375 }
376 /*
377 * Add an encoding to our list of deduplicated encodings.
378 */
379 struct bmenc *addbmenc(const char **enc) {
380 struct bmenc *r = (struct bmenc *)mymalloc(sizeof(struct bmenc)) ;
381 r->downloaded_seq = -1 ;
382 r->enc = enc ;
383 r->next = bmlist ;
384 parseenc(r) ;
385 bmlist = r ;
386 return r ;
387 }
388 /*
389 * Given a particular encoding, walk through our encoding list and
390 * see if it already exists; if so, return the existing one.
391 * The set of distinct encodings in a particular document is
392 * expected to be small (a few dozen at most).
393 */
394 static struct bmenc *deduplicateencoding(const char **enc) {
395 struct bmenc *p ;
396 for (p=bmlist; p!=0; p=p->next)
397 if (eqencoding(p->enc, enc))
398 return p ;
399 return addbmenc(enc) ;
400 }
401 /*
402 * Attempt to load an encoding; first, find the file, and then parse
403 * the file.
404 */
405 static const char **bitmap_enc_load(const char *fontname, int use_all) {
406 FILE *f = bitmap_enc_search(use_all ? "all" : fontname) ;
407 if (f != 0) {
408 const char **r = parseencodingfile(f, use_all) ;
409 fclose(f) ;
410 return r ;
411 }
412 return 0 ;
413 }
414 /*
415 * Start a section: mark all encodings as not downloaded yet.
416 */
417 static int curbmseq ;
418 void bmenc_startsection() {
419 struct bmenc *p ;
420 for (p=bmlist; p!=0; p=p->next)
421 p->downloaded_seq = -1 ;
422 curbmseq = 0 ;
423 }
424 /*
425 * Try to find a font in the all encoding list. This list is sorted
426 * so we can use binary search.
427 */
428 static const char **bitmap_all_find(const char *fontname) {
429 int ptr, bit;
430 if (numstatic == 0)
431 return 0 ;
432 ptr = 0 ;
433 bit = 1 ;
434 while ((bit << 1) < numstatic)
435 bit <<= 1 ;
436 while (bit > 0) {
437 int t = ptr + bit ;
438 if (t < numstatic && strcmp(fontname, bmfontarr[t].fontname) >= 0)
439 ptr = t ;
440 bit >>= 1 ;
441 }
442 if (strcmp(fontname, bmfontarr[ptr].fontname) == 0)
443 return bmfontarr[ptr].enc ;
444 else
445 return 0 ;
446 }
447 /*
448 * Download the encoding and set the sequence number.
449 */
450 static void downloadenc(struct bmenc *enc) {
451 int fresh = 0 ;
452 char cmdbuf[16] ;
453 if (enc->downloaded_seq < 0) {
454 int i ;
455 newline() ;
456 for (i=0; enc->enc[i]; i++)
457 pslineout(enc->enc[i]) ;
458 enc->downloaded_seq = curbmseq++ ;
459 fresh = 1 ;
460 }
461 newline() ;
462 sprintf(cmdbuf, "/EN%d", enc->downloaded_seq) ;
463 if (fresh) {
464 cmdout("A") ;
465 psnameout(cmdbuf) ;
466 cmdout("X") ;
467 } else {
468 // we use load here specifically to defer execution until the
469 // new font dictionary is on the stack and being built.
470 psnameout(cmdbuf) ;
471 cmdout("load") ;
472 }
473 }
474 /*
475 * Send out the new encoding, font bounding box, and font matrix.
476 * If we cannot find an encoding file for this font, do what we
477 * used to do instead (don't give it an encoding or resize or
478 * rescale).
479 */
480 static struct bmenc *getencoding_seq(const char *fontname) ;
481 int downloadbmencoding(const char *name, double scale, fontdesctype *curfnt) {
482 int slop;
483 int i ;
484 int seq ;
485 int llx = curfnt->llx ;
486 int lly = curfnt->lly ;
487 int urx = curfnt->urx ;
488 int ury = curfnt->ury ;
489 struct bmenc *bme = getencoding_seq(name) ;
490 if (bme == 0)
491 return -1 ;
492 seq = bme->downloaded_seq ;
493 /*
494 * Check that every character defined in the font has a name in the
495 * PostScript vector, and complain if this is not the case.
496 */
497 for (i=0; i<256 && i<curfnt->maxchars; i++) {
498 #ifndef XDVIPSK
499 if ((curfnt->chardesc[i].flags2 & EXISTS) &&
500 #else
501 if ((curfnt->chardesc_hh[i].flags2 & EXISTS) &&
502 #endif /* XDVIPSK */
503 !(bme->existsbm[i>>3] & (1 << (i & 7)))) {
504 fprintf_str(stderr,
505 "Can't use PostScript encoding vector for font %s; character %d has no name.\n",
506 name, i) ;
507 return -1 ;
508 }
509 }
510 cmdout("IEn") ;
511 cmdout("S") ;
512 psnameout("/IEn") ;
513 cmdout("X") ;
514 cmdout("FBB") ;
515 cmdout("FMat") ;
516 psnameout("/FMat") ;
517 specialout('[') ;
518 doubleout(1.0/scale) ;
519 numout(0) ;
520 numout(0) ;
521 doubleout(-1.0/scale) ;
522 numout(0) ;
523 numout(0) ;
524 specialout(']') ;
525 cmdout("N") ;
526 psnameout("/FBB") ;
527 // we add a bit of slop here, because this is only used for
528 // highlighting, and in theory if the bounding box is too
529 // tight, on some RIPs, characters could be clipped.
530 slop = 1;
531 specialout('[') ;
532 numout(llx-slop) ;
533 numout(lly-slop) ;
534 numout(urx+slop) ;
535 numout(ury+slop) ;
536 specialout(']') ;
537 cmdout("N") ;
538 newline() ;
539 return seq ;
540 }
541 /*
542 * Finish up the downloaded encoding; scale the font, and restore the
543 * previous global definitions.
544 */
545 void finishbitmapencoding(const char *name, double scale) {
546 psnameout(name) ;
547 cmdout("load") ;
548 numout(0) ;
549 cmdout(name+1) ;
550 cmdout("currentfont") ;
551 doubleout(scale) ;
552 cmdout("scalefont") ;
553 cmdout("put") ;
554 psnameout("/FMat") ;
555 cmdout("X") ;
556 psnameout("/FBB") ;
557 cmdout("X") ;
558 psnameout("/IEn") ;
559 cmdout("X") ;
560 newline();
561 }
562 /*
563 * We warn if we have to use a built-in encoding, and set this value to 1.
564 * We warn again if we cannot find a built-in encoding and have to
565 * default to previous behavior, and set this value to 2. In any case,
566 * we only issue warnings if the encodetype3 flag is set to a value greater
567 * than one; we don't want to bother folks about this new functionality.
568 */
569 static int warned_about_missing_encoding = 0 ;
570 /*
571 * Print a warning message.
572 */
573 static void bmenc_warn(const char *fontname, const char *msg) {
574 if (encodetype3 > 1)
575 fprintf_str(stderr,
576 "dvips: Static bitmap font encoding for font %s (and others?): %s.\n",
577 fontname, msg) ;
578 }
579 /*
580 * About to download a font; find the encoding sequence number.
581 * If needed, download a new sequence. If we can't find one, use
582 * -1; this font may not work as well for copy/paste and text search.
583 */
584 static int tried_all = 0 ; // have we tried to load dvips-all.enc
585 static struct bmenc *getencoding_seq(const char *fontname) {
586 struct bmenc *enc = 0 ;
587 struct bmfontenc *p = bmfontenclist ;
588 for (; p!=0; p=p->next)
589 if (strcmp(fontname, p->fontname) == 0) {
590 enc = p->enc ;
591 if (enc == 0) // remember failures
592 return 0 ;
593 break ;
594 }
595 // not in list; try to load it from a file
596 if (enc == 0) {
597 const char **e = bitmap_enc_load(fontname, 0) ;
598 // did not find it; try to load it from the dvips-all list.
599 if (e == 0) {
600 if (!tried_all) {
601 bitmap_enc_load(fontname, 1) ;
602 tried_all = 1 ;
603 }
604 e = bitmap_all_find(fontname) ;
605 }
606 if (e)
607 enc = deduplicateencoding(e) ;
608 }
609 // did not find this in the list; add it to the list
610 if (p == 0) {
611 p = (struct bmfontenc *)mymalloc(sizeof(struct bmfontenc)) ;
612 p->fontname = strdup(fontname) ;
613 p->enc = enc ;
614 p->next = bmfontenclist ;
615 // parseenc(enc) ;
616 bmfontenclist = p ;
617 }
618 if (enc == 0) {
619 if (warned_about_missing_encoding < 2) {
620 bmenc_warn(fontname, "no encoding found") ;
621 warned_about_missing_encoding = 2 ;
622 }
623 return 0 ; // don't download an encoding
624 }
625 downloadenc(enc) ;
626 return enc ;
627 }
628 #ifdef STANDALONE
629 /*
630 * Standalone test code:
631 */
632 void error(const char *s) {
633 fprintf(stderr, "Failed: %s\n", s) ;
634 if (*s == '!')
635 exit(0) ;
636 }
637 char *mymalloc(int sz) {
638 return (char *)malloc(sz) ;
639 }
640 int pos = 0 ;
641 int idok = 1 ;
642 const int MAXLINE = 75 ;
643 void newline() {
644 printf("\n") ;
645 idok = 1 ;
646 pos = 0 ;
647 }
648 void doubleout(double f) {
649 printf("%g", f) ;
650 pos += 8 ;
651 }
652 void pslineout(const char *s) {
653 printf("%s\n", s) ;
654 }
655 void numout(int num) {
656 int len = 1 ;
657 int t = num / 10 ;
658 while (t>0) {
659 len++ ;
660 t /= 10 ;
661 }
662 if (pos + len >= MAXLINE)
663 newline() ;
664 if (!idok)
665 specialout(' ') ;
666 printf("%d", num) ;
667 pos += len ;
668 idok = 0 ;
669 }
670 void cmdout(const char *s) {
671 if (pos + strlen(s) >= MAXLINE)
672 newline() ;
673 if (*s != '/' && !idok)
674 specialout(' ') ;
675 printf("%s", s) ;
676 pos += strlen(s) ;
677 idok = 0 ;
678 }
679 void psnameout(const char *s) {
680 cmdout(s) ;
681 }
682 void specialout(char c) {
683 if (pos + 1 >= MAXLINE)
684 newline() ;
685 printf("%c", c) ;
686 pos++ ;
687 idok = 1 ;
688 }
689 int main(int argc, char *argv[]) {
690 bmenc_startsection() ;
691 for (int i=1; i<argc; i++) {
692 struct bmenc *r = getencoding_seq(argv[i]) ;
693 int seq = r ? r->downloaded_seq : -1 ;
694 printf("\n") ;
695 printf("Result for %s is %d\n", argv[i], seq) ;
696 }
697 }
698 #endif