Debian Codegraph @

texk/seetexk/dvitodvi.c

raw
1 /* Copyright (c) 1987, 1989, 2012, 2020 University of Maryland Department of
2 Computer Science.
3
4 Permission is hereby granted, free of charge, to any person obtaining
5 a copy of this software and associated documentation files (the
6 "Software"), to deal in the Software without restriction, including
7 without limitation, the rights to use, copy, modify, merge, publish,
8 distribute, sublicense, and/or sell copies of the Software, and to
9 permit persons to whom the Software is furnished to do so, subject to
10 the following conditions: The above copyright notice, this permission
11 notice and the disclaimer statement shall be included in all copies
12 or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 */
22
23 /*
24 * DVI page rearrangement program
25 *
26 * Reads DVI version 2 files and rearranges pages,
27 * writing a new DVI file.
28 */
29
30 #ifdef HAVE_CONFIG_H
31 #include <config.h>
32 #endif
33
34 #ifdef KPATHSEA
35 #include <kpathsea/config.h>
36 #include <kpathsea/c-fopen.h>
37 #include <kpathsea/getopt.h>
38 #if defined(WIN32)
39 #include <kpathsea/variable.h>
40 #endif
41 #else
42 #define FOPEN_RBIN_MODE "rb"
43 #define FOPEN_WBIN_MODE "wb"
44 #define SET_BINARY(x) (void)0
45 extern char *optarg;
46 extern int optind;
47 #endif
48
49 #include "types.h"
50 #include "dviclass.h"
51 #include "dvicodes.h"
52 #include "error.h"
53 #include "fio.h"
54 #include "gripes.h"
55 #include "search.h"
56 #include <stdio.h>
57 #include <ctype.h>
58 #include "seek.h"
59 #include "common.h"
60
61 #define white(x) ((x) == ' ' || (x) == '\t' || (x) == ',')
62
63 char *ProgName;
64
65 /* Globals */
66 char serrbuf[BUFSIZ]; /* buffer for stderr */
67
68 /*
69 * We will try to keep output lines shorter than MAXCOL characters.
70 */
71 #define MAXCOL 75
72
73 /*
74 * We use the following structure to keep track of fonts we have seen.
75 * The final DVI file lists only the fonts it uses.
76 */
77 struct fontinfo {
78 i32 fi_newindex; /* font number in output file */
79 int fi_reallyused; /* true => used on a page we copied */
80 i32 fi_checksum; /* the checksum */
81 i32 fi_mag; /* the magnification */
82 i32 fi_designsize; /* the design size */
83 short fi_n1; /* the name header length */
84 short fi_n2; /* the name body length */
85 char *fi_name; /* the name itself */
86 };
87
88
89 i32 Width; /* width of page */
90 i32 Height; /* height of page */
91 i32 Magnification; /* Magnification of pages */
92 int Modulo; /* page spec modulo */
93 struct pagespec *PageSpecs; /* page specification list */
94
95 int SFlag; /* true => -s, silent operation */
96
97 struct search *FontFinder; /* maps from input indicies to fontinfo */
98 i32 NextOutputFontIndex; /* generates output indicies */
99 i32 CurrentFontIndex; /* current (old) index in input */
100 i32 OutputFontIndex; /* current (new) index in ouput */
101
102 const char *DVIFileName; /* name of input DVI file */
103 FILE *inf; /* the input file itself */
104 FILE *outf; /* the output DVI file */
105
106 long *StartOfPage; /* The file positions of the input pages */
107 long StartOfPageSpace; /* Number of entries of StartOfPage array */
108
109 long StartOfLastPage; /* The file position just before we
110 started the last page */
111 long CurrentPosition; /* The current position of the file */
112
113 int UseThisPage; /* true => current page is selected */
114
115 int WritingPage; /* true while writing a page */
116
117 i32 InputPageNumber; /* current absolute page in old DVI file */
118 int NumberOfOutputPages; /* number of pages in new DVI file */
119 #ifdef ASCIIPTEX
120 int ptexdvi; /* true if dvi file is extended (TATEKUMI) */
121 #endif
122
123 i32 Numerator; /* numerator from DVI file */
124 i32 Denominator; /* denominator from DVI file */
125 i32 DVIMag; /* magnification from DVI file */
126
127 i32 Count[10]; /* the 10 \count variables */
128
129 /* save some string space: we use this a lot */
130 char writeerr[] = "error writing DVI file";
131 #ifndef KPATHSEA
132 void *malloc(), *realloc();
133 void free();
134 #endif
135
136 static void WriteFont(struct fontinfo *fi);
137 static void PutFontSelector(i32 index);
138 static void ScanDVIFile(void);
139 static void HandleDVIFile(void);
140
141 /*
142 * You may get lint warnings about sprintf's return value.
143 * Older versions of 4BSD have `char *sprintf()'. ANSI and
144 * SysV use `int sprintf()'; so ignore the warnings.
145 */
146
147 /*
148 * Lint gets somewhat confused over putc.
149 */
150 #ifdef lint
151 #undef putc
152 #ifdef ultrix /* grr */
153 #define putc(c, f) fputc((char)(c), f)
154 #else
155 #define putc(c, f) fputc((int)(c), f)
156 #endif
157 #endif
158
159 static void
160 specusage(void)
161 {
162 error(1, -1, "page specification error:\n\
163 <pagespecs> = [modulo:][mag@]<spec>\n\
164 <spec> = [-]pageno[(xoff,yoff)][,spec|+spec]\n\
165 modulo>=1, 0<=pageno<modulo");
166 }
167
168 /*
169 * This function calculates approximately (whole + num/den) * sf.
170 * No need for real extreme accuracy; one ten thousandth of an
171 * inch should be sufficient.
172 *
173 * Assumptions:
174 *
175 * 0 <= num < den <= 10000
176 * 0 <= whole
177 */
178 i32 defaultscale = 4736286 ;
179
180 static i32
181 scale(i32 whole, int num, int den, i32 sf)
182 {
183 i32 v ;
184
185 if (!sf)
186 sf = defaultscale ;
187 v = whole * sf + num * (sf / den) ;
188 if (v / sf != whole || v < 0 || v > 0x40000000L)
189 error(1, -1, "arithmetic overflow in dimension") ;
190 sf = sf % den ;
191 v += (sf * num * 2 + den) / (2 * den) ;
192 return (v) ;
193 }
194
195 struct pagespec {
196 int reversed, pageno, add;
197 i32 xoff, yoff;
198 struct pagespec *next;
199 };
200
201 static struct pagespec *
202 newspec(void)
203 {
204 struct pagespec *temp = (struct pagespec *)malloc(sizeof(struct pagespec));
205 temp->reversed = temp->pageno = temp->add = 0;
206 temp->xoff = temp->yoff = 0;
207 temp->next = NULL;
208 return (temp);
209 }
210
211 static int
212 parseint(char **sp)
213 {
214 char *s = *sp;
215 int n = 0, neg = 0;
216
217 if (*s == '-') {
218 neg = 1;
219 s++;
220 }
221 for (; isdigit((unsigned char)*s); s++)
222 n = n*10 + (*s-'0');
223 if (*sp == s) specusage();
224 *sp = s;
225 return (neg ? -n : n);
226 }
227
228 static i32
229 parsedimen(char **sp)
230 {
231 i32 whole = 0;
232 int num = 0, den = 1, neg = 0;
233 i32 fac = 0L;
234 char *s = *sp;
235
236 if (*s == '-') {
237 neg = 1;
238 *sp = ++s;
239 }
240 for (; isdigit((unsigned char)*s); s++)
241 whole = whole*10 + (*s-'0');
242
243 if (*s == '.') {
244 *sp = ++s;
245 for (; isdigit((unsigned char)*s); s++) {
246 if (den < 10000) { /* limit precision for scale to work */
247 num = num*10 + (*s-'0');
248 den *= 10;
249 }
250 }
251 }
252 if (*sp == s) specusage();
253 *sp = s;
254
255 /*
256 * Allowed units are `in', `cm', `mm', `pt', `sp', `cc', `dd', and `pc';
257 * must be in lower case.
258 */
259 if (*s == 'c' && s[1] == 'm') {
260 /* centimeters need to be scaled by 72.27 * 216 / 2.54, or 1 864 680 */
261 fac = 1864680L ;
262 s += 2;
263 } else if (*s == 'p' && s[1] == 't') {
264 /* real points need to be scaled by 65536 */
265 fac = 65536L ;
266 s += 2;
267 } else if (*s == 'p' && s[1] == 'c') {
268 /* picas need to be scaled by 65536 * 12, or 786 432 */
269 fac = 786432L ;
270 s += 2;
271 } else if (*s == 'm' && s[1] == 'm') {
272 /* millimeters need to be scaled by 72.27 * 216 / 25.4, or 186 468 */
273 fac = 186468L ;
274 s += 2;
275 } else if (*s == 's' && s[1] == 'p') {
276 /* scaled points are already taken care of; simply round */
277 fac = 1L ;
278 s += 2;
279 } else if (*s == 'b' && s[1] == 'p') {
280 /* big points need to be scaled by 72.27 * 65536 / 72, or 65782 */
281 fac = 65782L ;
282 s += 2;
283 } else if (*s == 'd' && s[1] == 'd') {
284 /* didot points need to be scaled by 65536 * 1238 / 1157, or 70124 */
285 fac = 70124L ;
286 s += 2;
287 } else if (*s == 'c' && s[1] == 'c') {
288 /* cicero need to be scaled by 65536 * 1238 / 1157 * 12, or 841 489 */
289 fac = 841489L ;
290 s += 2;
291 } else if (*s == 'i' && s[1] == 'n') {
292 /* inches need to be scaled by 72.27 * 65536, or 4 736 286 */
293 fac = 4736286L ;
294 s += 2;
295 } else if (*s == 'w') {
296 fac = Width;
297 s++;
298 } else if (*s == 'h') {
299 fac = Height;
300 s++;
301 }
302 whole = scale(whole, num, den, fac) ;
303 *sp = s;
304 return (neg ? -whole : whole);
305 }
306
307 static struct pagespec *
308 ParseSpecs(char *str, int make)
309 {
310 struct pagespec *result, *head, *tail;
311 int other = 0;
312 int num = -1;
313 struct pagespec spare;
314
315 if (make)
316 result = head = tail = newspec();
317 else {
318 result = NULL;
319 head = tail = &spare;
320 }
321 while (*str) {
322 if (isdigit((unsigned char)*str)) {
323 num = parseint(&str);
324 } else {
325 switch (*str++) {
326 case ':':
327 if (other || head != tail || num < 1) specusage();
328 Modulo = num;
329 num = -1;
330 break;
331 case '@':
332 if (other || head != tail || num < 1) specusage();
333 Magnification = num;
334 num = -1;
335 break;
336 case '-':
337 tail->reversed = !tail->reversed;
338 other = 1;
339 break;
340 case '(':
341 tail->xoff += parsedimen(&str);
342 if (*str++ != ',') specusage();
343 tail->yoff += parsedimen(&str);
344 if (*str++ != ')') specusage();
345 other = 1;
346 break;
347 case '+':
348 tail->add = 1;
349 case ',':
350 if (num < 0 || num >= Modulo) specusage();
351 tail->pageno = num;
352 if (make) {
353 tail->next = newspec();
354 tail = tail->next;
355 }
356 num = -1;
357 other = 1;
358 break;
359 default:
360 specusage();
361 }
362 }
363 }
364 if (num >= Modulo)
365 specusage();
366 else if (num >= 0)
367 tail->pageno = num;
368 return result;
369 }
370
371 static i32
372 singledimen(char *str)
373 {
374 i32 num = parsedimen(&str);
375 if (*str) return (0);
376 return (num);
377 }
378
379 /*
380 * Print a message to stderr, with an optional leading space, and handling
381 * long line wraps.
382 */
383 static void
384 message(int space, const char *str, int len)
385 {
386 static int beenhere;
387 static int col;
388
389 if (!beenhere)
390 space = 0, beenhere++;
391 if (len == 0)
392 len = strlen(str);
393 col += len;
394 if (space) {
395 if (col >= MAXCOL)
396 (void) putc('\n', stderr), col = len;
397 else
398 (void) putc(' ', stderr), col++;
399 }
400 while (--len >= 0)
401 (void) putc(*str++, stderr);
402 (void) fflush(stderr);
403 }
404
405 /*
406 * Start a page (process a DVI_BOP).
407 */
408 static void
409 BeginPage(int really)
410 {
411 register i32 *i;
412
413 OutputFontIndex = -1; /* new page requires respecifying font */
414 for (i = Count; i < &Count[10]; i++)
415 fGetLong(inf, *i);
416 (void) GetLong(inf); /* previous page pointer */
417
418 if (!UseThisPage || !really)
419 return;
420
421 putbyte(outf, DVI_BOP);
422 for (i = Count; i < &Count[10]; i++)
423 PutLong(outf, *i);
424 PutLong(outf, StartOfLastPage);
425 if (ferror(outf))
426 error(1, -1, writeerr);
427
428 StartOfLastPage = CurrentPosition;
429 CurrentPosition += 45; /* we just wrote this much */
430
431 if (!SFlag) { /* write nice page usage messages */
432 register int z = 0;
433 register int mlen = 0;
434 char msg[80];
435
436 (void) sprintf(msg, "[%ld", (long)Count[0]);
437 mlen = strlen(msg);
438 for (i = &Count[1]; i < &Count[10]; i++) {
439 if (*i == 0) {
440 z++;
441 continue;
442 }
443 while (--z >= 0)
444 msg[mlen++] = '.', msg[mlen++] = '0';
445 z = 0;
446 (void) sprintf(msg + mlen, ".%ld", (long)*i);
447 mlen += strlen(msg + mlen);
448 }
449 message(1, msg, mlen);
450 }
451 WritingPage = 1;
452 }
453
454 /*
455 * End a page (process a DVI_EOP).
456 */
457 static void
458 EndPage(int really)
459 {
460
461 if (!UseThisPage || !really)
462 return;
463 if (!SFlag)
464 message(0, "]", 1);
465 putbyte(outf, DVI_EOP);
466 if (ferror(outf))
467 error(1, -1, writeerr);
468 CurrentPosition++;
469 NumberOfOutputPages++;
470 WritingPage = 0;
471 }
472
473 /*
474 * For each of the fonts used in the new DVI file, write out a definition.
475 */
476 /* ARGSUSED */
477 static void
478 PostAmbleFontEnumerator(char *addr, i32 key)
479 {
480
481 if (((struct fontinfo *)addr)->fi_reallyused)
482 WriteFont((struct fontinfo *)addr);
483 }
484
485 static void
486 HandlePostAmble(void)
487 {
488 register i32 c;
489
490 (void) GetLong(inf); /* previous page pointer */
491 if (GetLong(inf) != Numerator)
492 GripeMismatchedValue("numerator");
493 if (GetLong(inf) != Denominator)
494 GripeMismatchedValue("denominator");
495 if (GetLong(inf) * Magnification / 1000 != DVIMag)
496 GripeMismatchedValue("\\magnification");
497
498 putbyte(outf, DVI_POST);
499 PutLong(outf, StartOfLastPage);
500 PutLong(outf, Numerator);
501 PutLong(outf, Denominator);
502 PutLong(outf, DVIMag);
503 c = GetLong(inf);
504 PutLong(outf, c); /* tallest page height */
505 c = GetLong(inf);
506 PutLong(outf, c); /* widest page width */
507 c = GetWord(inf)+1;
508 PutWord(outf, c); /* DVI stack size */
509 PutWord(outf, NumberOfOutputPages);
510 StartOfLastPage = CurrentPosition; /* point at post */
511 CurrentPosition += 29; /* count all those `put's */
512 #ifdef notdef
513 (void) GetWord(inf); /* skip original number of pages */
514 #endif
515
516 /*
517 * just ignore all the incoming font definitions; we are done with
518 * input file
519 */
520
521 /*
522 * run through the FontFinder table and dump definitions for the
523 * fonts we have used.
524 */
525 SEnumerate(FontFinder, PostAmbleFontEnumerator);
526
527 putbyte(outf, DVI_POSTPOST);
528 PutLong(outf, StartOfLastPage); /* actually start of postamble */
529 #ifdef ASCIIPTEX
530 if(ptexdvi)
531 putbyte(outf, DVI_PTEXVERSION);
532 else
533 #endif
534 putbyte(outf, DVI_VERSION);
535 putbyte(outf, DVI_FILLER);
536 putbyte(outf, DVI_FILLER);
537 putbyte(outf, DVI_FILLER);
538 putbyte(outf, DVI_FILLER);
539 CurrentPosition += 10;
540 while (CurrentPosition & 3) {
541 putbyte(outf, DVI_FILLER);
542 CurrentPosition++;
543 }
544 if (ferror(outf))
545 error(1, -1, writeerr);
546 }
547
548 /*
549 * Write a font definition to the output file
550 */
551 static void
552 WriteFont(struct fontinfo *fi)
553 {
554 register int l;
555 register char *s;
556
557 if (fi->fi_newindex < 256) {
558 putbyte(outf, DVI_FNTDEF1);
559 putbyte(outf, fi->fi_newindex);
560 CurrentPosition += 2;
561 } else if (fi->fi_newindex < 65536) {
562 putbyte(outf, DVI_FNTDEF2);
563 PutWord(outf, fi->fi_newindex);
564 CurrentPosition += 3;
565 } else if (fi->fi_newindex < 16777216) {
566 putbyte(outf, DVI_FNTDEF3);
567 Put3Byte(outf, fi->fi_newindex);
568 CurrentPosition += 4;
569 } else {
570 putbyte(outf, DVI_FNTDEF4);
571 PutLong(outf, fi->fi_newindex);
572 CurrentPosition += 5;
573 }
574 PutLong(outf, fi->fi_checksum);
575 PutLong(outf, fi->fi_mag);
576 PutLong(outf, fi->fi_designsize);
577 putbyte(outf, fi->fi_n1);
578 putbyte(outf, fi->fi_n2);
579 l = fi->fi_n1 + fi->fi_n2;
580 CurrentPosition += 14 + l;
581 s = fi->fi_name;
582 while (--l >= 0)
583 putbyte(outf, *s++);
584 }
585
586 /*
587 * Handle the preamble. Someday we should update the comment field.
588 */
589 static void
590 HandlePreAmble(void)
591 {
592 register int n, c;
593
594 c = getc(inf);
595 if (c == EOF)
596 GripeUnexpectedDVIEOF();
597 if (c != DVI_PRE)
598 GripeMissingOp("PRE");
599 if (getc(inf) != DVI_VERSION)
600 error(1, 0, "%s is not a DVI version %d file",
601 DVIFileName, DVI_VERSION);
602 Numerator = GetLong(inf);
603 Denominator = GetLong(inf);
604 DVIMag = GetLong(inf) * Magnification / 1000;
605 putbyte(outf, DVI_PRE);
606 putbyte(outf, DVI_VERSION);
607 PutLong(outf, Numerator);
608 PutLong(outf, Denominator);
609 PutLong(outf, DVIMag);
610
611 n = UnSign8(GetByte(inf));
612 CurrentPosition = 15 + n; /* well, almost */
613 putbyte(outf, n);
614 while (--n >= 0) {
615 c = GetByte(inf);
616 putbyte(outf, c);
617 }
618 }
619
620 int
621 main(int argc, char **argv)
622 {
623 register int c;
624 register char *s;
625 char *outname = NULL;
626 char *specstring = NULL;
627 #if defined(WIN32) && defined(KPATHSEA)
628 int ac;
629 char **av, *enc;
630
631 if (argc>1) {
632 kpse_set_program_name(argv[0], "dvitodvi");
633 enc = kpse_var_value("command_line_encoding");
634 if (get_command_line_args_utf8(enc, &ac, &av)) {
635 argc = ac;
636 argv = av;
637 }
638 }
639 #endif
640
641 Width = 0;
642 Height = 0;
643 Magnification = 1000;
644 Modulo = 1;
645
646 ProgName = *argv;
647 setbuf(stderr, serrbuf);
648
649 while ((c = getopt(argc, argv, "i:o:w:h:q")) != EOF) {
650 switch (c) {
651
652 case 'q': /* silent */
653 SFlag++;
654 break;
655
656 case 'i':
657 if (DVIFileName != NULL)
658 goto usage;
659 DVIFileName = optarg;
660 break;
661
662 case 'o':
663 if (outname != NULL)
664 goto usage;
665 outname = optarg;
666 break;
667
668 case 'w':
669 if (Width != 0)
670 goto usage;
671 Width = singledimen(optarg);
672 if (Width <= 0)
673 error(1, -1, "-w parameter must be > 0");
674 break;
675
676 case 'h':
677 if (Height != 0)
678 goto usage;
679 Height = singledimen(optarg);
680 if (Height <= 0)
681 error(1, -1, "-h parameter must be > 0");
682 break;
683
684 case '?':
685 usage:
686 (void) fprintf(stderr,
687 "dvitodvi in SeeTeX Ver.%s (%s)\n", VERSION, TL_VERSION);
688 (void) fprintf(stderr, "\
689 Usage: %s [-q] [-i infile] [-o outfile] [-w width] [-h height] <pagespecs> [infile [outfile]]\n",
690 ProgName);
691 (void) fprintf(stderr,
692 "\nEmail bug reports to %s.\n", BUG_ADDRESS);
693 (void) fflush(stderr);
694 exit(1);
695 }
696 }
697
698 while (optind < argc) {
699 s = argv[optind++];
700 c = *s;
701 if (specstring == NULL)
702 (void) ParseSpecs((specstring = s), 0);
703 else if (DVIFileName == NULL)
704 DVIFileName = s;
705 else if (outname == NULL)
706 outname = s;
707 else
708 goto usage;
709 }
710
711 if (specstring == NULL)
712 goto usage;
713
714 if (DVIFileName == NULL) {
715 DVIFileName = "`stdin'";
716 inf = stdin;
717 if (!isatty(fileno(inf)))
718 SET_BINARY(fileno(inf));
719 else
720 goto usage;
721 } else if ((inf = fopen(DVIFileName, FOPEN_RBIN_MODE)) == 0)
722 error(1, -1, "cannot read %s", DVIFileName);
723 if (outname == NULL) {
724 outf = stdout;
725 if (!isatty(fileno(outf)))
726 SET_BINARY(fileno(outf));
727 }
728 else if ((outf = fopen(outname, FOPEN_WBIN_MODE)) == 0)
729 error(1, -1, "cannot write %s", outname);
730
731 if ((FontFinder = SCreate(sizeof(struct fontinfo))) == 0)
732 error(1, 0, "cannot create font finder (out of memory?)");
733
734 /* copy inf to TEMP file if not seekable */
735 if ((inf = SeekFile(inf)) == NULL) {
736 error(1, 0, "can't seek file");
737 }
738
739 #ifdef ASCIIPTEX
740 ptexdvi = 0;
741 #endif
742 InputPageNumber = 0;
743 StartOfPageSpace = 32;
744 StartOfLastPage = -1;
745 StartOfPage = malloc(sizeof(long) * StartOfPageSpace);
746 if (!StartOfPage) {
747 error(1, -1, "cannot allocate list of pages; out of memory");
748 }
749
750 HandlePreAmble();
751 ScanDVIFile();
752 if (fseek(inf, 16L, 1) == -1)
753 error(1, -1, "can't seek postamble");
754 if (Height == 0) /* get height from postamble */
755 Height = GetLong(inf);
756 else
757 (void) GetLong(inf); /* ignore height */
758 if (Width == 0) /* get width from postamble */
759 Width = GetLong(inf);
760 PageSpecs = ParseSpecs(specstring, 1);
761
762 HandleDVIFile();
763 free(StartOfPage);
764 if (WritingPage)
765 EndPage(1);
766 HandlePostAmble();
767 if (!SFlag)
768 (void) fprintf(stderr, "\nWrote %d page%s, %ld bytes\n",
769 NumberOfOutputPages, NumberOfOutputPages == 1 ? "" : "s",
770 (long)CurrentPosition);
771 return 0;
772 }
773
774 /*
775 * Handle a font definition.
776 */
777 static void
778 HandleFontDef(i32 index)
779 {
780 register struct fontinfo *fi;
781 register int i;
782 register char *s;
783 int def = S_CREATE | S_EXCL;
784
785 if (!UseThisPage) {
786 if ((fi = (struct fontinfo *)SSearch(FontFinder, index, &def)) == 0) {
787 if (def & S_COLL)
788 error(1, 0, "font %ld already defined", (long)index);
789 else
790 error(1, 0, "cannot stash font %ld (out of memory?)",
791 (long)index);
792 }
793 fi->fi_reallyused = 0;
794 fi->fi_checksum = GetLong(inf);
795 fi->fi_mag = GetLong(inf);
796 fi->fi_designsize = GetLong(inf);
797 fi->fi_n1 = UnSign8(GetByte(inf));
798 fi->fi_n2 = UnSign8(GetByte(inf));
799 i = fi->fi_n1 + fi->fi_n2;
800 if ((s = malloc((unsigned)i)) == 0)
801 GripeOutOfMemory(i, "font name");
802 fi->fi_name = s;
803 while (--i >= 0)
804 *s++ = GetByte(inf);
805 } else {
806 (void) GetLong(inf);
807 (void) GetLong(inf);
808 (void) GetLong(inf);
809 i = UnSign8(GetByte(inf));
810 i += UnSign8(GetByte(inf));
811 while (--i >= 0)
812 (void) GetByte(inf);
813 }
814 }
815
816 /*
817 * Handle a \special.
818 */
819 static void
820 HandleSpecial(int c, int l, i32 p)
821 {
822 register int i;
823
824 if (UseThisPage) {
825 putbyte(outf, c);
826 switch (l) {
827
828 case DPL_UNS1:
829 putbyte(outf, p);
830 CurrentPosition += 2;
831 break;
832
833 case DPL_UNS2:
834 PutWord(outf, p);
835 CurrentPosition += 3;
836 break;
837
838 case DPL_UNS3:
839 Put3Byte(outf, p);
840 CurrentPosition += 4;
841 break;
842
843 case DPL_SGN4:
844 PutLong(outf, p);
845 CurrentPosition += 5;
846 break;
847
848 default:
849 panic("HandleSpecial l=%d", l);
850 /* NOTREACHED */
851 }
852 CurrentPosition += p;
853 while (--p >= 0) {
854 i = getc(inf);
855 putbyte(outf, i);
856 }
857 if (feof(inf))
858 GripeUnexpectedDVIEOF();
859 if (ferror(outf))
860 error(1, -1, writeerr);
861 } else
862 while (--p >= 0)
863 (void) getc(inf);
864 }
865
866 static void
867 ReallyUseFont(void)
868 {
869 register struct fontinfo *fi;
870 int look = S_LOOKUP;
871
872 fi = (struct fontinfo *)SSearch(FontFinder, CurrentFontIndex, &look);
873 if (fi == NULL)
874 error(1, 0, "DVI file requested font %ld without defining it",
875 (long)CurrentFontIndex);
876 if (fi->fi_reallyused == 0) {
877 fi->fi_reallyused++;
878 fi->fi_newindex = NextOutputFontIndex++;
879 WriteFont(fi);
880 }
881 if (fi->fi_newindex != OutputFontIndex) {
882 PutFontSelector(fi->fi_newindex);
883 OutputFontIndex = fi->fi_newindex;
884 }
885 }
886
887 /*
888 * Write a font selection command to the output file
889 */
890 static void
891 PutFontSelector(i32 index)
892 {
893
894 if (index < 64) {
895 putbyte(outf, index + DVI_FNTNUM0);
896 CurrentPosition++;
897 } else if (index < 256) {
898 putbyte(outf, DVI_FNT1);
899 putbyte(outf, index);
900 CurrentPosition += 2;
901 } else if (index < 65536) {
902 putbyte(outf, DVI_FNT2);
903 PutWord(outf, index);
904 CurrentPosition += 3;
905 } else if (index < 16777216) {
906 putbyte(outf, DVI_FNT3);
907 Put3Byte(outf, index);
908 CurrentPosition += 4;
909 } else {
910 putbyte(outf, DVI_FNT4);
911 PutLong(outf, index);
912 CurrentPosition += 5;
913 }
914 }
915
916 /*
917 * The following table describes the length (in bytes) of each of the DVI
918 * commands that we can simply copy, starting with DVI_SET1 (128).
919 */
920 char oplen[128] = {
921 0, 0, 0, 0, /* DVI_SET1 .. DVI_SET4 */
922 9, /* DVI_SETRULE */
923 0, 0, 0, 0, /* DVI_PUT1 .. DVI_PUT4 */
924 9, /* DVI_PUTRULE */
925 1, /* DVI_NOP */
926 0, /* DVI_BOP */
927 0, /* DVI_EOP */
928 1, /* DVI_PUSH */
929 1, /* DVI_POP */
930 2, 3, 4, 5, /* DVI_RIGHT1 .. DVI_RIGHT4 */
931 1, /* DVI_W0 */
932 2, 3, 4, 5, /* DVI_W1 .. DVI_W4 */
933 1, /* DVI_X0 */
934 2, 3, 4, 5, /* DVI_X1 .. DVI_X4 */
935 2, 3, 4, 5, /* DVI_DOWN1 .. DVI_DOWN4 */
936 1, /* DVI_Y0 */
937 2, 3, 4, 5, /* DVI_Y1 .. DVI_Y4 */
938 1, /* DVI_Z0 */
939 2, 3, 4, 5, /* DVI_Z1 .. DVI_Z4 */
940 0, /* DVI_FNTNUM0 (171) */
941 0, 0, 0, 0, 0, 0, 0, 0, /* 172 .. 179 */
942 0, 0, 0, 0, 0, 0, 0, 0, /* 180 .. 187 */
943 0, 0, 0, 0, 0, 0, 0, 0, /* 188 .. 195 */
944 0, 0, 0, 0, 0, 0, 0, 0, /* 196 .. 203 */
945 0, 0, 0, 0, 0, 0, 0, 0, /* 204 .. 211 */
946 0, 0, 0, 0, 0, 0, 0, 0, /* 212 .. 219 */
947 0, 0, 0, 0, 0, 0, 0, 0, /* 220 .. 227 */
948 0, 0, 0, 0, 0, 0, 0, /* 228 .. 234 */
949 0, 0, 0, 0, /* DVI_FNT1 .. DVI_FNT4 */
950 0, 0, 0, 0, /* DVI_XXX1 .. DVI_XXX4 */
951 0, 0, 0, 0, /* DVI_FNTDEF1 .. DVI_FNTDEF4 */
952 0, /* DVI_PRE */
953 0, /* DVI_POST */
954 0, /* DVI_POSTPOST */
955 #ifdef ASCIIPTEX
956 0, 0, 0, 0, 0, /* 250 .. 254 */
957 0, /* DVI_DIR */
958 #else
959 0, 0, 0, 0, 0, 0, /* 250 .. 255 */
960 #endif
961 };
962
963 static int
964 HandlePage(int first, int last, i32 hoffset, i32 voffset)
965 {
966 register int c, l;
967 register i32 p = 0; /* avoid uninitialized warning */
968 register int CurrentFontOK = 0;
969 int doingpage = 0;
970
971 /* Only way out is via "return" statement */
972 for (;;) {
973 c = getc(inf); /* getc() returns unsigned values */
974 if (DVI_IsChar(c)) {
975 /*
976 * Copy chars, note font usage, but ignore if
977 * page is not interesting.
978 */
979 if (!UseThisPage)
980 continue;
981 if (!CurrentFontOK) {
982 ReallyUseFont();
983 CurrentFontOK++;
984 }
985 putbyte(outf, c);
986 CurrentPosition++;
987 continue;
988 }
989 if (DVI_IsFont(c)) { /* note font change */
990 CurrentFontIndex = c - DVI_FNTNUM0;
991 CurrentFontOK = 0;
992 continue;
993 }
994 if (c == EOF)
995 GripeUnexpectedDVIEOF();
996 if ((l = (oplen - 128)[c]) != 0) { /* simple copy */
997 if (!UseThisPage) {
998 while (--l > 0)
999 (void) getc(inf);
1000 continue;
1001 }
1002 CurrentPosition += l;
1003 putbyte(outf, c);
1004 while (--l > 0) {
1005 c = getc(inf);
1006 putbyte(outf, c);
1007 }
1008 if (ferror(outf))
1009 error(1, -1, writeerr);
1010 continue;
1011 }
1012 if ((l = DVI_OpLen(c)) != 0) {
1013 /*
1014 * Handle other generics.
1015 * N.B.: there should only be unsigned parameters
1016 * here (save SGN4), for commands with negative
1017 * parameters have been taken care of above.
1018 */
1019 switch (l) {
1020
1021 case DPL_UNS1:
1022 p = getc(inf);
1023 break;
1024
1025 case DPL_UNS2:
1026 fGetWord(inf, p);
1027 break;
1028
1029 case DPL_UNS3:
1030 fGet3Byte(inf, p);
1031 break;
1032
1033 case DPL_SGN4:
1034 fGetLong(inf, p);
1035 break;
1036
1037 default:
1038 panic("HandleDVIFile l=%d", l);
1039 }
1040
1041 /*
1042 * Now that we have the parameter, perform the
1043 * command.
1044 */
1045 switch (DVI_DT(c)) {
1046
1047 case DT_SET:
1048 case DT_PUT:
1049 if (!UseThisPage)
1050 continue;
1051 if (!CurrentFontOK) {
1052 ReallyUseFont();
1053 CurrentFontOK++;
1054 }
1055 putbyte(outf, c);
1056 switch (l) {
1057
1058 case DPL_UNS1:
1059 putbyte(outf, p);
1060 CurrentPosition += 2;
1061 continue;
1062
1063 case DPL_UNS2:
1064 PutWord(outf, p);
1065 CurrentPosition += 3;
1066 continue;
1067
1068 case DPL_UNS3:
1069 Put3Byte(outf, p);
1070 CurrentPosition += 4;
1071 continue;
1072
1073 case DPL_SGN4:
1074 PutLong(outf, p);
1075 CurrentPosition += 5;
1076 continue;
1077 }
1078
1079 case DT_FNT:
1080 CurrentFontIndex = p;
1081 CurrentFontOK = 0;
1082 continue;
1083
1084 case DT_XXX:
1085 HandleSpecial(c, l, p);
1086 continue;
1087
1088 case DT_FNTDEF:
1089 HandleFontDef(p);
1090 continue;
1091
1092 #ifdef ASCIIPTEX
1093 case DT_DIR:
1094 if (!UseThisPage)
1095 continue;
1096 ptexdvi = 1;
1097
1098 putbyte(outf, c);
1099 putbyte(outf, p);
1100 CurrentPosition += 2;
1101 continue;
1102 #endif
1103
1104 default:
1105 panic("HandleDVIFile DVI_DT(%d)=%d",
1106 c, DVI_DT(c));
1107 }
1108 continue;
1109 }
1110
1111 switch (c) { /* handle the few remaining cases */
1112
1113 case DVI_BOP:
1114 if (doingpage)
1115 GripeUnexpectedOp("BOP (during page)");
1116 BeginPage(first);
1117 if (UseThisPage) {
1118 if (!last) {
1119 putbyte(outf, DVI_PUSH);
1120 CurrentPosition++;
1121 }
1122 if (hoffset != 0) {
1123 putbyte(outf, DVI_RIGHT4) ;
1124 PutLong(outf, hoffset) ;
1125 CurrentPosition += 5;
1126 }
1127 if (voffset != 0) {
1128 putbyte(outf, DVI_DOWN4) ;
1129 PutLong(outf, voffset) ;
1130 CurrentPosition += 5;
1131 }
1132 }
1133 doingpage = 1;
1134 break;
1135
1136 case DVI_EOP:
1137 if (!doingpage)
1138 GripeUnexpectedOp("EOP (outside page)");
1139 if (!last && UseThisPage) {
1140 putbyte(outf, DVI_POP);
1141 CurrentPosition++;
1142 }
1143 EndPage(last);
1144 doingpage = 0;
1145 return(1);
1146
1147 case DVI_PRE:
1148 GripeUnexpectedOp("PRE");
1149 /* NOTREACHED */
1150
1151 case DVI_POST:
1152 if (doingpage)
1153 GripeUnexpectedOp("POST (inside page)");
1154 return(0);
1155
1156 case DVI_POSTPOST:
1157 GripeUnexpectedOp("POSTPOST");
1158 /* NOTREACHED */
1159
1160 default:
1161 GripeUndefinedOp(c);
1162 /* NOTREACHED */
1163 }
1164 }
1165 }
1166
1167 /* write an empty page to fill out space */
1168 static void
1169 PutEmptyPage(void)
1170 {
1171 int i;
1172
1173 putbyte(outf, DVI_BOP);
1174 PutLong(outf, -1L);
1175 for (i = 1; i < 10; i++) /* set all sub counts to 0 */
1176 PutLong(outf, 0L);
1177 PutLong(outf, StartOfLastPage);
1178 putbyte(outf, DVI_EOP);
1179 if (!SFlag) { /* write nice page usage messages */
1180 const char *msg = "[*]";
1181 message(1, msg, strlen(msg));
1182 }
1183 if (ferror(outf))
1184 error(1, -1, writeerr);
1185
1186 StartOfLastPage = CurrentPosition;
1187 CurrentPosition += 46; /* we just wrote this much */
1188 NumberOfOutputPages++;
1189 }
1190
1191 /*
1192 * Here we scan the input DVI file and record pointers to the pages.
1193 */
1194 static void
1195 ScanDVIFile(void)
1196 {
1197 long *tmp;
1198
1199 UseThisPage = 0;
1200
1201 StartOfPage[InputPageNumber] = ftell(inf);
1202 while (HandlePage(0, 0, 0, 0)) { /* scan DVI file */
1203 ++InputPageNumber;
1204 if (InputPageNumber >= StartOfPageSpace) {
1205 StartOfPageSpace *= 2;
1206 tmp = realloc(StartOfPage, sizeof(long) * StartOfPageSpace);
1207 if (!tmp) {
1208 error(1, -1, "cannot grow list of pages; out of memory");
1209 }
1210 StartOfPage = tmp;
1211 }
1212
1213 StartOfPage[InputPageNumber] = ftell(inf);
1214 }
1215 }
1216
1217 /*
1218 * Here we read the input DVI file and write relevant pages to the
1219 * output DVI file. We also keep track of font changes, handle font
1220 * definitions, and perform some other housekeeping.
1221 */
1222 static void
1223 HandleDVIFile(void)
1224 {
1225 int CurrentPage, ActualPage, MaxPage;
1226
1227 UseThisPage = 1;
1228
1229 MaxPage = ((InputPageNumber+Modulo-1)/Modulo)*Modulo;
1230
1231 for (CurrentPage = 0; CurrentPage < MaxPage; CurrentPage += Modulo) {
1232 int add_last = 0;
1233 struct pagespec *ps;
1234 for (ps = PageSpecs; ps != NULL; ps = ps->next) {
1235 int add_next = ps->add;
1236 if (ps->reversed)
1237 ActualPage = MaxPage-CurrentPage-Modulo+ps->pageno;
1238 else
1239 ActualPage = CurrentPage+ps->pageno;
1240 if (ActualPage < InputPageNumber) {
1241 if (fseek(inf, StartOfPage[ActualPage], 0) == -1)
1242 error(1, -1,
1243 "can't seek page %d", ActualPage+1);
1244 HandlePage(!add_last, !add_next, ps->xoff, ps->yoff);
1245 } else if (!add_last && !add_next)
1246 PutEmptyPage();
1247 add_last = add_next;
1248 }
1249 }
1250 if (fseek(inf, StartOfPage[InputPageNumber]+1, 0) == -1)
1251 error(1, -1, "can't seek last page");
1252 }