xref: /openbsd-src/usr.bin/mandoc/term_ps.c (revision cb39b41371628601fbe4c618205356d538b9d08a)
1 /*	$OpenBSD: term_ps.c,v 1.39 2015/04/04 17:46:58 schwarze Exp $ */
2 /*
3  * Copyright (c) 2010, 2011 Kristaps Dzonsons <kristaps@bsd.lv>
4  * Copyright (c) 2014, 2015 Ingo Schwarze <schwarze@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 #include <sys/types.h>
19 
20 #include <assert.h>
21 #include <stdarg.h>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 
28 #include "mandoc_aux.h"
29 #include "out.h"
30 #include "term.h"
31 #include "manconf.h"
32 #include "main.h"
33 
34 /* These work the buffer used by the header and footer. */
35 #define	PS_BUFSLOP	  128
36 
37 /* Convert PostScript point "x" to an AFM unit. */
38 #define	PNT2AFM(p, x) \
39 	(size_t)((double)(x) * (1000.0 / (double)(p)->ps->scale))
40 
41 /* Convert an AFM unit "x" to a PostScript points */
42 #define	AFM2PNT(p, x) \
43 	((double)(x) / (1000.0 / (double)(p)->ps->scale))
44 
45 struct	glyph {
46 	unsigned short	  wx; /* WX in AFM */
47 };
48 
49 struct	font {
50 	const char	 *name; /* FontName in AFM */
51 #define	MAXCHAR		  95 /* total characters we can handle */
52 	struct glyph	  gly[MAXCHAR]; /* glyph metrics */
53 };
54 
55 struct	termp_ps {
56 	int		  flags;
57 #define	PS_INLINE	 (1 << 0)	/* we're in a word */
58 #define	PS_MARGINS	 (1 << 1)	/* we're in the margins */
59 #define	PS_NEWPAGE	 (1 << 2)	/* new page, no words yet */
60 #define	PS_BACKSP	 (1 << 3)	/* last character was backspace */
61 	size_t		  pscol;	/* visible column (AFM units) */
62 	size_t		  pscolnext;	/* used for overstrike */
63 	size_t		  psrow;	/* visible row (AFM units) */
64 	char		 *psmarg;	/* margin buf */
65 	size_t		  psmargsz;	/* margin buf size */
66 	size_t		  psmargcur;	/* cur index in margin buf */
67 	char		  last;		/* last non-backspace seen */
68 	enum termfont	  lastf;	/* last set font */
69 	enum termfont	  nextf;	/* building next font here */
70 	size_t		  scale;	/* font scaling factor */
71 	size_t		  pages;	/* number of pages shown */
72 	size_t		  lineheight;	/* line height (AFM units) */
73 	size_t		  top;		/* body top (AFM units) */
74 	size_t		  bottom;	/* body bottom (AFM units) */
75 	size_t		  height;	/* page height (AFM units */
76 	size_t		  width;	/* page width (AFM units) */
77 	size_t		  lastwidth;	/* page width before last ll */
78 	size_t		  left;		/* body left (AFM units) */
79 	size_t		  header;	/* header pos (AFM units) */
80 	size_t		  footer;	/* footer pos (AFM units) */
81 	size_t		  pdfbytes;	/* current output byte */
82 	size_t		  pdflastpg;	/* byte of last page mark */
83 	size_t		  pdfbody;	/* start of body object */
84 	size_t		 *pdfobjs;	/* table of object offsets */
85 	size_t		  pdfobjsz;	/* size of pdfobjs */
86 };
87 
88 static	int		  ps_hspan(const struct termp *,
89 				const struct roffsu *);
90 static	size_t		  ps_width(const struct termp *, int);
91 static	void		  ps_advance(struct termp *, size_t);
92 static	void		  ps_begin(struct termp *);
93 static	void		  ps_closepage(struct termp *);
94 static	void		  ps_end(struct termp *);
95 static	void		  ps_endline(struct termp *);
96 static	void		  ps_fclose(struct termp *);
97 static	void		  ps_growbuf(struct termp *, size_t);
98 static	void		  ps_letter(struct termp *, int);
99 static	void		  ps_pclose(struct termp *);
100 static	void		  ps_pletter(struct termp *, int);
101 static	void		  ps_printf(struct termp *, const char *, ...);
102 static	void		  ps_putchar(struct termp *, char);
103 static	void		  ps_setfont(struct termp *, enum termfont);
104 static	void		  ps_setwidth(struct termp *, int, int);
105 static	struct termp	 *pspdf_alloc(const struct mchars *,
106 				const struct manoutput *);
107 static	void		  pdf_obj(struct termp *, size_t);
108 
109 /*
110  * We define, for the time being, three fonts: bold, oblique/italic, and
111  * normal (roman).  The following table hard-codes the font metrics for
112  * ASCII, i.e., 32--127.
113  */
114 
115 static	const struct font fonts[TERMFONT__MAX] = {
116 	{ "Times-Roman", {
117 		{ 250 },
118 		{ 333 },
119 		{ 408 },
120 		{ 500 },
121 		{ 500 },
122 		{ 833 },
123 		{ 778 },
124 		{ 333 },
125 		{ 333 },
126 		{ 333 },
127 		{ 500 },
128 		{ 564 },
129 		{ 250 },
130 		{ 333 },
131 		{ 250 },
132 		{ 278 },
133 		{ 500 },
134 		{ 500 },
135 		{ 500 },
136 		{ 500 },
137 		{ 500 },
138 		{ 500 },
139 		{ 500 },
140 		{ 500 },
141 		{ 500 },
142 		{ 500 },
143 		{ 278 },
144 		{ 278 },
145 		{ 564 },
146 		{ 564 },
147 		{ 564 },
148 		{ 444 },
149 		{ 921 },
150 		{ 722 },
151 		{ 667 },
152 		{ 667 },
153 		{ 722 },
154 		{ 611 },
155 		{ 556 },
156 		{ 722 },
157 		{ 722 },
158 		{ 333 },
159 		{ 389 },
160 		{ 722 },
161 		{ 611 },
162 		{ 889 },
163 		{ 722 },
164 		{ 722 },
165 		{ 556 },
166 		{ 722 },
167 		{ 667 },
168 		{ 556 },
169 		{ 611 },
170 		{ 722 },
171 		{ 722 },
172 		{ 944 },
173 		{ 722 },
174 		{ 722 },
175 		{ 611 },
176 		{ 333 },
177 		{ 278 },
178 		{ 333 },
179 		{ 469 },
180 		{ 500 },
181 		{ 333 },
182 		{ 444 },
183 		{ 500 },
184 		{ 444 },
185 		{  500},
186 		{  444},
187 		{  333},
188 		{  500},
189 		{  500},
190 		{  278},
191 		{  278},
192 		{  500},
193 		{  278},
194 		{  778},
195 		{  500},
196 		{  500},
197 		{  500},
198 		{  500},
199 		{  333},
200 		{  389},
201 		{  278},
202 		{  500},
203 		{  500},
204 		{  722},
205 		{  500},
206 		{  500},
207 		{  444},
208 		{  480},
209 		{  200},
210 		{  480},
211 		{  541},
212 	} },
213 	{ "Times-Bold", {
214 		{ 250  },
215 		{ 333  },
216 		{ 555  },
217 		{ 500  },
218 		{ 500  },
219 		{ 1000 },
220 		{ 833  },
221 		{ 333  },
222 		{ 333  },
223 		{ 333  },
224 		{ 500  },
225 		{ 570  },
226 		{ 250  },
227 		{ 333  },
228 		{ 250  },
229 		{ 278  },
230 		{ 500  },
231 		{ 500  },
232 		{ 500  },
233 		{ 500  },
234 		{ 500  },
235 		{ 500  },
236 		{ 500  },
237 		{ 500  },
238 		{ 500  },
239 		{ 500  },
240 		{ 333  },
241 		{ 333  },
242 		{ 570  },
243 		{ 570  },
244 		{ 570  },
245 		{ 500  },
246 		{ 930  },
247 		{ 722  },
248 		{ 667  },
249 		{ 722  },
250 		{ 722  },
251 		{ 667  },
252 		{ 611  },
253 		{ 778  },
254 		{ 778  },
255 		{ 389  },
256 		{ 500  },
257 		{ 778  },
258 		{ 667  },
259 		{ 944  },
260 		{ 722  },
261 		{ 778  },
262 		{ 611  },
263 		{ 778  },
264 		{ 722  },
265 		{ 556  },
266 		{ 667  },
267 		{ 722  },
268 		{ 722  },
269 		{ 1000 },
270 		{ 722  },
271 		{ 722  },
272 		{ 667  },
273 		{ 333  },
274 		{ 278  },
275 		{ 333  },
276 		{ 581  },
277 		{ 500  },
278 		{ 333  },
279 		{ 500  },
280 		{ 556  },
281 		{ 444  },
282 		{  556 },
283 		{  444 },
284 		{  333 },
285 		{  500 },
286 		{  556 },
287 		{  278 },
288 		{  333 },
289 		{  556 },
290 		{  278 },
291 		{  833 },
292 		{  556 },
293 		{  500 },
294 		{  556 },
295 		{  556 },
296 		{  444 },
297 		{  389 },
298 		{  333 },
299 		{  556 },
300 		{  500 },
301 		{  722 },
302 		{  500 },
303 		{  500 },
304 		{  444 },
305 		{  394 },
306 		{  220 },
307 		{  394 },
308 		{  520 },
309 	} },
310 	{ "Times-Italic", {
311 		{ 250  },
312 		{ 333  },
313 		{ 420  },
314 		{ 500  },
315 		{ 500  },
316 		{ 833  },
317 		{ 778  },
318 		{ 333  },
319 		{ 333  },
320 		{ 333  },
321 		{ 500  },
322 		{ 675  },
323 		{ 250  },
324 		{ 333  },
325 		{ 250  },
326 		{ 278  },
327 		{ 500  },
328 		{ 500  },
329 		{ 500  },
330 		{ 500  },
331 		{ 500  },
332 		{ 500  },
333 		{ 500  },
334 		{ 500  },
335 		{ 500  },
336 		{ 500  },
337 		{ 333  },
338 		{ 333  },
339 		{ 675  },
340 		{ 675  },
341 		{ 675  },
342 		{ 500  },
343 		{ 920  },
344 		{ 611  },
345 		{ 611  },
346 		{ 667  },
347 		{ 722  },
348 		{ 611  },
349 		{ 611  },
350 		{ 722  },
351 		{ 722  },
352 		{ 333  },
353 		{ 444  },
354 		{ 667  },
355 		{ 556  },
356 		{ 833  },
357 		{ 667  },
358 		{ 722  },
359 		{ 611  },
360 		{ 722  },
361 		{ 611  },
362 		{ 500  },
363 		{ 556  },
364 		{ 722  },
365 		{ 611  },
366 		{ 833  },
367 		{ 611  },
368 		{ 556  },
369 		{ 556  },
370 		{ 389  },
371 		{ 278  },
372 		{ 389  },
373 		{ 422  },
374 		{ 500  },
375 		{ 333  },
376 		{ 500  },
377 		{ 500  },
378 		{ 444  },
379 		{  500 },
380 		{  444 },
381 		{  278 },
382 		{  500 },
383 		{  500 },
384 		{  278 },
385 		{  278 },
386 		{  444 },
387 		{  278 },
388 		{  722 },
389 		{  500 },
390 		{  500 },
391 		{  500 },
392 		{  500 },
393 		{  389 },
394 		{  389 },
395 		{  278 },
396 		{  500 },
397 		{  444 },
398 		{  667 },
399 		{  444 },
400 		{  444 },
401 		{  389 },
402 		{  400 },
403 		{  275 },
404 		{  400 },
405 		{  541 },
406 	} },
407 	{ "Times-BoldItalic", {
408 		{  250 },
409 		{  389 },
410 		{  555 },
411 		{  500 },
412 		{  500 },
413 		{  833 },
414 		{  778 },
415 		{  333 },
416 		{  333 },
417 		{  333 },
418 		{  500 },
419 		{  570 },
420 		{  250 },
421 		{  333 },
422 		{  250 },
423 		{  278 },
424 		{  500 },
425 		{  500 },
426 		{  500 },
427 		{  500 },
428 		{  500 },
429 		{  500 },
430 		{  500 },
431 		{  500 },
432 		{  500 },
433 		{  500 },
434 		{  333 },
435 		{  333 },
436 		{  570 },
437 		{  570 },
438 		{  570 },
439 		{  500 },
440 		{  832 },
441 		{  667 },
442 		{  667 },
443 		{  667 },
444 		{  722 },
445 		{  667 },
446 		{  667 },
447 		{  722 },
448 		{  778 },
449 		{  389 },
450 		{  500 },
451 		{  667 },
452 		{  611 },
453 		{  889 },
454 		{  722 },
455 		{  722 },
456 		{  611 },
457 		{  722 },
458 		{  667 },
459 		{  556 },
460 		{  611 },
461 		{  722 },
462 		{  667 },
463 		{  889 },
464 		{  667 },
465 		{  611 },
466 		{  611 },
467 		{  333 },
468 		{  278 },
469 		{  333 },
470 		{  570 },
471 		{  500 },
472 		{  333 },
473 		{  500 },
474 		{  500 },
475 		{  444 },
476 		{  500 },
477 		{  444 },
478 		{  333 },
479 		{  500 },
480 		{  556 },
481 		{  278 },
482 		{  278 },
483 		{  500 },
484 		{  278 },
485 		{  778 },
486 		{  556 },
487 		{  500 },
488 		{  500 },
489 		{  500 },
490 		{  389 },
491 		{  389 },
492 		{  278 },
493 		{  556 },
494 		{  444 },
495 		{  667 },
496 		{  500 },
497 		{  444 },
498 		{  389 },
499 		{  348 },
500 		{  220 },
501 		{  348 },
502 		{  570 },
503 	} },
504 };
505 
506 void *
507 pdf_alloc(const struct mchars *mchars, const struct manoutput *outopts)
508 {
509 	struct termp	*p;
510 
511 	if (NULL != (p = pspdf_alloc(mchars, outopts)))
512 		p->type = TERMTYPE_PDF;
513 
514 	return(p);
515 }
516 
517 void *
518 ps_alloc(const struct mchars *mchars, const struct manoutput *outopts)
519 {
520 	struct termp	*p;
521 
522 	if (NULL != (p = pspdf_alloc(mchars, outopts)))
523 		p->type = TERMTYPE_PS;
524 
525 	return(p);
526 }
527 
528 static struct termp *
529 pspdf_alloc(const struct mchars *mchars, const struct manoutput *outopts)
530 {
531 	struct termp	*p;
532 	unsigned int	 pagex, pagey;
533 	size_t		 marginx, marginy, lineheight;
534 	const char	*pp;
535 
536 	p = mandoc_calloc(1, sizeof(struct termp));
537 	p->symtab = mchars;
538 	p->enc = TERMENC_ASCII;
539 	p->fontq = mandoc_reallocarray(NULL,
540 	    (p->fontsz = 8), sizeof(enum termfont));
541 	p->fontq[0] = p->fontl = TERMFONT_NONE;
542 	p->ps = mandoc_calloc(1, sizeof(struct termp_ps));
543 
544 	p->advance = ps_advance;
545 	p->begin = ps_begin;
546 	p->end = ps_end;
547 	p->endline = ps_endline;
548 	p->hspan = ps_hspan;
549 	p->letter = ps_letter;
550 	p->setwidth = ps_setwidth;
551 	p->width = ps_width;
552 
553 	/* Default to US letter (millimetres). */
554 
555 	pagex = 216;
556 	pagey = 279;
557 
558 	/*
559 	 * The ISO-269 paper sizes can be calculated automatically, but
560 	 * it would require bringing in -lm for pow() and I'd rather not
561 	 * do that.  So just do it the easy way for now.  Since this
562 	 * only happens once, I'm not terribly concerned.
563 	 */
564 
565 	pp = outopts->paper;
566 	if (pp && strcasecmp(pp, "letter")) {
567 		if (0 == strcasecmp(pp, "a3")) {
568 			pagex = 297;
569 			pagey = 420;
570 		} else if (0 == strcasecmp(pp, "a4")) {
571 			pagex = 210;
572 			pagey = 297;
573 		} else if (0 == strcasecmp(pp, "a5")) {
574 			pagex = 148;
575 			pagey = 210;
576 		} else if (0 == strcasecmp(pp, "legal")) {
577 			pagex = 216;
578 			pagey = 356;
579 		} else if (2 != sscanf(pp, "%ux%u", &pagex, &pagey))
580 			fprintf(stderr, "%s: Unknown paper\n", pp);
581 	}
582 
583 	/*
584 	 * This MUST be defined before any PNT2AFM or AFM2PNT
585 	 * calculations occur.
586 	 */
587 
588 	p->ps->scale = 11;
589 
590 	/* Remember millimetres -> AFM units. */
591 
592 	pagex = PNT2AFM(p, ((double)pagex * 2.834));
593 	pagey = PNT2AFM(p, ((double)pagey * 2.834));
594 
595 	/* Margins are 1/9 the page x and y. */
596 
597 	marginx = (size_t)((double)pagex / 9.0);
598 	marginy = (size_t)((double)pagey / 9.0);
599 
600 	/* Line-height is 1.4em. */
601 
602 	lineheight = PNT2AFM(p, ((double)p->ps->scale * 1.4));
603 
604 	p->ps->width = p->ps->lastwidth = (size_t)pagex;
605 	p->ps->height = (size_t)pagey;
606 	p->ps->header = pagey - (marginy / 2) - (lineheight / 2);
607 	p->ps->top = pagey - marginy;
608 	p->ps->footer = (marginy / 2) - (lineheight / 2);
609 	p->ps->bottom = marginy;
610 	p->ps->left = marginx;
611 	p->ps->lineheight = lineheight;
612 
613 	p->defrmargin = pagex - (marginx * 2);
614 	return(p);
615 }
616 
617 static void
618 ps_setwidth(struct termp *p, int iop, int width)
619 {
620 	size_t	 lastwidth;
621 
622 	lastwidth = p->ps->width;
623 	if (iop > 0)
624 		p->ps->width += width;
625 	else if (iop == 0)
626 		p->ps->width = width ? (size_t)width : p->ps->lastwidth;
627 	else if (p->ps->width > (size_t)width)
628 		p->ps->width -= width;
629 	else
630 		p->ps->width = 0;
631 	p->ps->lastwidth = lastwidth;
632 }
633 
634 void
635 pspdf_free(void *arg)
636 {
637 	struct termp	*p;
638 
639 	p = (struct termp *)arg;
640 
641 	if (p->ps->psmarg)
642 		free(p->ps->psmarg);
643 	if (p->ps->pdfobjs)
644 		free(p->ps->pdfobjs);
645 
646 	free(p->ps);
647 	term_free(p);
648 }
649 
650 static void
651 ps_printf(struct termp *p, const char *fmt, ...)
652 {
653 	va_list		 ap;
654 	int		 pos, len;
655 
656 	va_start(ap, fmt);
657 
658 	/*
659 	 * If we're running in regular mode, then pipe directly into
660 	 * vprintf().  If we're processing margins, then push the data
661 	 * into our growable margin buffer.
662 	 */
663 
664 	if ( ! (PS_MARGINS & p->ps->flags)) {
665 		len = vprintf(fmt, ap);
666 		va_end(ap);
667 		p->ps->pdfbytes += len < 0 ? 0 : (size_t)len;
668 		return;
669 	}
670 
671 	/*
672 	 * XXX: I assume that the in-margin print won't exceed
673 	 * PS_BUFSLOP (128 bytes), which is reasonable but still an
674 	 * assumption that will cause pukeage if it's not the case.
675 	 */
676 
677 	ps_growbuf(p, PS_BUFSLOP);
678 
679 	pos = (int)p->ps->psmargcur;
680 	vsnprintf(&p->ps->psmarg[pos], PS_BUFSLOP, fmt, ap);
681 
682 	va_end(ap);
683 
684 	p->ps->psmargcur = strlen(p->ps->psmarg);
685 }
686 
687 static void
688 ps_putchar(struct termp *p, char c)
689 {
690 	int		 pos;
691 
692 	/* See ps_printf(). */
693 
694 	if ( ! (PS_MARGINS & p->ps->flags)) {
695 		putchar(c);
696 		p->ps->pdfbytes++;
697 		return;
698 	}
699 
700 	ps_growbuf(p, 2);
701 
702 	pos = (int)p->ps->psmargcur++;
703 	p->ps->psmarg[pos++] = c;
704 	p->ps->psmarg[pos] = '\0';
705 }
706 
707 static void
708 pdf_obj(struct termp *p, size_t obj)
709 {
710 
711 	assert(obj > 0);
712 
713 	if ((obj - 1) >= p->ps->pdfobjsz) {
714 		p->ps->pdfobjsz = obj + 128;
715 		p->ps->pdfobjs = mandoc_reallocarray(p->ps->pdfobjs,
716 		    p->ps->pdfobjsz, sizeof(size_t));
717 	}
718 
719 	p->ps->pdfobjs[(int)obj - 1] = p->ps->pdfbytes;
720 	ps_printf(p, "%zu 0 obj\n", obj);
721 }
722 
723 static void
724 ps_closepage(struct termp *p)
725 {
726 	int		 i;
727 	size_t		 len, base;
728 
729 	/*
730 	 * Close out a page that we've already flushed to output.  In
731 	 * PostScript, we simply note that the page must be showed.  In
732 	 * PDF, we must now create the Length, Resource, and Page node
733 	 * for the page contents.
734 	 */
735 
736 	assert(p->ps->psmarg && p->ps->psmarg[0]);
737 	ps_printf(p, "%s", p->ps->psmarg);
738 
739 	if (TERMTYPE_PS != p->type) {
740 		ps_printf(p, "ET\n");
741 
742 		len = p->ps->pdfbytes - p->ps->pdflastpg;
743 		base = p->ps->pages * 4 + p->ps->pdfbody;
744 
745 		ps_printf(p, "endstream\nendobj\n");
746 
747 		/* Length of content. */
748 		pdf_obj(p, base + 1);
749 		ps_printf(p, "%zu\nendobj\n", len);
750 
751 		/* Resource for content. */
752 		pdf_obj(p, base + 2);
753 		ps_printf(p, "<<\n/ProcSet [/PDF /Text]\n");
754 		ps_printf(p, "/Font <<\n");
755 		for (i = 0; i < (int)TERMFONT__MAX; i++)
756 			ps_printf(p, "/F%d %d 0 R\n", i, 3 + i);
757 		ps_printf(p, ">>\n>>\n");
758 
759 		/* Page node. */
760 		pdf_obj(p, base + 3);
761 		ps_printf(p, "<<\n");
762 		ps_printf(p, "/Type /Page\n");
763 		ps_printf(p, "/Parent 2 0 R\n");
764 		ps_printf(p, "/Resources %zu 0 R\n", base + 2);
765 		ps_printf(p, "/Contents %zu 0 R\n", base);
766 		ps_printf(p, ">>\nendobj\n");
767 	} else
768 		ps_printf(p, "showpage\n");
769 
770 	p->ps->pages++;
771 	p->ps->psrow = p->ps->top;
772 	assert( ! (PS_NEWPAGE & p->ps->flags));
773 	p->ps->flags |= PS_NEWPAGE;
774 }
775 
776 static void
777 ps_end(struct termp *p)
778 {
779 	size_t		 i, xref, base;
780 
781 	/*
782 	 * At the end of the file, do one last showpage.  This is the
783 	 * same behaviour as groff(1) and works for multiple pages as
784 	 * well as just one.
785 	 */
786 
787 	if ( ! (PS_NEWPAGE & p->ps->flags)) {
788 		assert(0 == p->ps->flags);
789 		assert('\0' == p->ps->last);
790 		ps_closepage(p);
791 	}
792 
793 	if (TERMTYPE_PS == p->type) {
794 		ps_printf(p, "%%%%Trailer\n");
795 		ps_printf(p, "%%%%Pages: %zu\n", p->ps->pages);
796 		ps_printf(p, "%%%%EOF\n");
797 		return;
798 	}
799 
800 	pdf_obj(p, 2);
801 	ps_printf(p, "<<\n/Type /Pages\n");
802 	ps_printf(p, "/MediaBox [0 0 %zu %zu]\n",
803 			(size_t)AFM2PNT(p, p->ps->width),
804 			(size_t)AFM2PNT(p, p->ps->height));
805 
806 	ps_printf(p, "/Count %zu\n", p->ps->pages);
807 	ps_printf(p, "/Kids [");
808 
809 	for (i = 0; i < p->ps->pages; i++)
810 		ps_printf(p, " %zu 0 R", i * 4 + p->ps->pdfbody + 3);
811 
812 	base = (p->ps->pages - 1) * 4 + p->ps->pdfbody + 4;
813 
814 	ps_printf(p, "]\n>>\nendobj\n");
815 	pdf_obj(p, base);
816 	ps_printf(p, "<<\n");
817 	ps_printf(p, "/Type /Catalog\n");
818 	ps_printf(p, "/Pages 2 0 R\n");
819 	ps_printf(p, ">>\n");
820 	xref = p->ps->pdfbytes;
821 	ps_printf(p, "xref\n");
822 	ps_printf(p, "0 %zu\n", base + 1);
823 	ps_printf(p, "0000000000 65535 f \n");
824 
825 	for (i = 0; i < base; i++)
826 		ps_printf(p, "%.10zu 00000 n \n",
827 		    p->ps->pdfobjs[(int)i]);
828 
829 	ps_printf(p, "trailer\n");
830 	ps_printf(p, "<<\n");
831 	ps_printf(p, "/Size %zu\n", base + 1);
832 	ps_printf(p, "/Root %zu 0 R\n", base);
833 	ps_printf(p, "/Info 1 0 R\n");
834 	ps_printf(p, ">>\n");
835 	ps_printf(p, "startxref\n");
836 	ps_printf(p, "%zu\n", xref);
837 	ps_printf(p, "%%%%EOF\n");
838 }
839 
840 static void
841 ps_begin(struct termp *p)
842 {
843 	int		 i;
844 
845 	/*
846 	 * Print margins into margin buffer.  Nothing gets output to the
847 	 * screen yet, so we don't need to initialise the primary state.
848 	 */
849 
850 	if (p->ps->psmarg) {
851 		assert(p->ps->psmargsz);
852 		p->ps->psmarg[0] = '\0';
853 	}
854 
855 	/*p->ps->pdfbytes = 0;*/
856 	p->ps->psmargcur = 0;
857 	p->ps->flags = PS_MARGINS;
858 	p->ps->pscol = p->ps->left;
859 	p->ps->psrow = p->ps->header;
860 
861 	ps_setfont(p, TERMFONT_NONE);
862 
863 	(*p->headf)(p, p->argf);
864 	(*p->endline)(p);
865 
866 	p->ps->pscol = p->ps->left;
867 	p->ps->psrow = p->ps->footer;
868 
869 	(*p->footf)(p, p->argf);
870 	(*p->endline)(p);
871 
872 	p->ps->flags &= ~PS_MARGINS;
873 
874 	assert(0 == p->ps->flags);
875 	assert(p->ps->psmarg);
876 	assert('\0' != p->ps->psmarg[0]);
877 
878 	/*
879 	 * Print header and initialise page state.  Following this,
880 	 * stuff gets printed to the screen, so make sure we're sane.
881 	 */
882 
883 	if (TERMTYPE_PS == p->type) {
884 		ps_printf(p, "%%!PS-Adobe-3.0\n");
885 		ps_printf(p, "%%%%DocumentData: Clean7Bit\n");
886 		ps_printf(p, "%%%%Orientation: Portrait\n");
887 		ps_printf(p, "%%%%Pages: (atend)\n");
888 		ps_printf(p, "%%%%PageOrder: Ascend\n");
889 		ps_printf(p, "%%%%DocumentMedia: "
890 		    "Default %zu %zu 0 () ()\n",
891 		    (size_t)AFM2PNT(p, p->ps->width),
892 		    (size_t)AFM2PNT(p, p->ps->height));
893 		ps_printf(p, "%%%%DocumentNeededResources: font");
894 
895 		for (i = 0; i < (int)TERMFONT__MAX; i++)
896 			ps_printf(p, " %s", fonts[i].name);
897 
898 		ps_printf(p, "\n%%%%EndComments\n");
899 	} else {
900 		ps_printf(p, "%%PDF-1.1\n");
901 		pdf_obj(p, 1);
902 		ps_printf(p, "<<\n");
903 		ps_printf(p, ">>\n");
904 		ps_printf(p, "endobj\n");
905 
906 		for (i = 0; i < (int)TERMFONT__MAX; i++) {
907 			pdf_obj(p, (size_t)i + 3);
908 			ps_printf(p, "<<\n");
909 			ps_printf(p, "/Type /Font\n");
910 			ps_printf(p, "/Subtype /Type1\n");
911 			ps_printf(p, "/Name /F%d\n", i);
912 			ps_printf(p, "/BaseFont /%s\n", fonts[i].name);
913 			ps_printf(p, ">>\n");
914 		}
915 	}
916 
917 	p->ps->pdfbody = (size_t)TERMFONT__MAX + 3;
918 	p->ps->pscol = p->ps->left;
919 	p->ps->psrow = p->ps->top;
920 	p->ps->flags |= PS_NEWPAGE;
921 	ps_setfont(p, TERMFONT_NONE);
922 }
923 
924 static void
925 ps_pletter(struct termp *p, int c)
926 {
927 	int		 f;
928 
929 	/*
930 	 * If we haven't opened a page context, then output that we're
931 	 * in a new page and make sure the font is correctly set.
932 	 */
933 
934 	if (PS_NEWPAGE & p->ps->flags) {
935 		if (TERMTYPE_PS == p->type) {
936 			ps_printf(p, "%%%%Page: %zu %zu\n",
937 			    p->ps->pages + 1, p->ps->pages + 1);
938 			ps_printf(p, "/%s %zu selectfont\n",
939 			    fonts[(int)p->ps->lastf].name,
940 			    p->ps->scale);
941 		} else {
942 			pdf_obj(p, p->ps->pdfbody +
943 			    p->ps->pages * 4);
944 			ps_printf(p, "<<\n");
945 			ps_printf(p, "/Length %zu 0 R\n",
946 			    p->ps->pdfbody + 1 + p->ps->pages * 4);
947 			ps_printf(p, ">>\nstream\n");
948 		}
949 		p->ps->pdflastpg = p->ps->pdfbytes;
950 		p->ps->flags &= ~PS_NEWPAGE;
951 	}
952 
953 	/*
954 	 * If we're not in a PostScript "word" context, then open one
955 	 * now at the current cursor.
956 	 */
957 
958 	if ( ! (PS_INLINE & p->ps->flags)) {
959 		if (TERMTYPE_PS != p->type) {
960 			ps_printf(p, "BT\n/F%d %zu Tf\n",
961 			    (int)p->ps->lastf, p->ps->scale);
962 			ps_printf(p, "%.3f %.3f Td\n(",
963 			    AFM2PNT(p, p->ps->pscol),
964 			    AFM2PNT(p, p->ps->psrow));
965 		} else
966 			ps_printf(p, "%.3f %.3f moveto\n(",
967 			    AFM2PNT(p, p->ps->pscol),
968 			    AFM2PNT(p, p->ps->psrow));
969 		p->ps->flags |= PS_INLINE;
970 	}
971 
972 	assert( ! (PS_NEWPAGE & p->ps->flags));
973 
974 	/*
975 	 * We need to escape these characters as per the PostScript
976 	 * specification.  We would also escape non-graphable characters
977 	 * (like tabs), but none of them would get to this point and
978 	 * it's superfluous to abort() on them.
979 	 */
980 
981 	switch (c) {
982 	case '(':
983 		/* FALLTHROUGH */
984 	case ')':
985 		/* FALLTHROUGH */
986 	case '\\':
987 		ps_putchar(p, '\\');
988 		break;
989 	default:
990 		break;
991 	}
992 
993 	/* Write the character and adjust where we are on the page. */
994 
995 	f = (int)p->ps->lastf;
996 
997 	if (c <= 32 || c - 32 >= MAXCHAR)
998 		c = 32;
999 
1000 	ps_putchar(p, (char)c);
1001 	c -= 32;
1002 	p->ps->pscol += (size_t)fonts[f].gly[c].wx;
1003 }
1004 
1005 static void
1006 ps_pclose(struct termp *p)
1007 {
1008 
1009 	/*
1010 	 * Spit out that we're exiting a word context (this is a
1011 	 * "partial close" because we don't check the last-char buffer
1012 	 * or anything).
1013 	 */
1014 
1015 	if ( ! (PS_INLINE & p->ps->flags))
1016 		return;
1017 
1018 	if (TERMTYPE_PS != p->type) {
1019 		ps_printf(p, ") Tj\nET\n");
1020 	} else
1021 		ps_printf(p, ") show\n");
1022 
1023 	p->ps->flags &= ~PS_INLINE;
1024 }
1025 
1026 static void
1027 ps_fclose(struct termp *p)
1028 {
1029 
1030 	/*
1031 	 * Strong closure: if we have a last-char, spit it out after
1032 	 * checking that we're in the right font mode.  This will of
1033 	 * course open a new scope, if applicable.
1034 	 *
1035 	 * Following this, close out any scope that's open.
1036 	 */
1037 
1038 	if (p->ps->last != '\0') {
1039 		assert( ! (p->ps->flags & PS_BACKSP));
1040 		if (p->ps->nextf != p->ps->lastf) {
1041 			ps_pclose(p);
1042 			ps_setfont(p, p->ps->nextf);
1043 		}
1044 		p->ps->nextf = TERMFONT_NONE;
1045 		ps_pletter(p, p->ps->last);
1046 		p->ps->last = '\0';
1047 	}
1048 
1049 	if ( ! (PS_INLINE & p->ps->flags))
1050 		return;
1051 
1052 	ps_pclose(p);
1053 }
1054 
1055 static void
1056 ps_letter(struct termp *p, int arg)
1057 {
1058 	size_t		savecol, wx;
1059 	char		c;
1060 
1061 	c = arg >= 128 || arg <= 0 ? '?' : arg;
1062 
1063 	/*
1064 	 * When receiving a backspace, merely flag it.
1065 	 * We don't know yet whether it is
1066 	 * a font instruction or an overstrike.
1067 	 */
1068 
1069 	if (c == '\b') {
1070 		assert(p->ps->last != '\0');
1071 		assert( ! (p->ps->flags & PS_BACKSP));
1072 		p->ps->flags |= PS_BACKSP;
1073 		return;
1074 	}
1075 
1076 	/*
1077 	 * Decode font instructions.
1078 	 */
1079 
1080 	if (p->ps->flags & PS_BACKSP) {
1081 		if (p->ps->last == '_') {
1082 			switch (p->ps->nextf) {
1083 			case TERMFONT_BI:
1084 				break;
1085 			case TERMFONT_BOLD:
1086 				p->ps->nextf = TERMFONT_BI;
1087 				break;
1088 			default:
1089 				p->ps->nextf = TERMFONT_UNDER;
1090 			}
1091 			p->ps->last = c;
1092 			p->ps->flags &= ~PS_BACKSP;
1093 			return;
1094 		}
1095 		if (p->ps->last == c) {
1096 			switch (p->ps->nextf) {
1097 			case TERMFONT_BI:
1098 				break;
1099 			case TERMFONT_UNDER:
1100 				p->ps->nextf = TERMFONT_BI;
1101 				break;
1102 			default:
1103 				p->ps->nextf = TERMFONT_BOLD;
1104 			}
1105 			p->ps->flags &= ~PS_BACKSP;
1106 			return;
1107 		}
1108 
1109 		/*
1110 		 * This is not a font instruction, but rather
1111 		 * the next character.  Prepare for overstrike.
1112 		 */
1113 
1114 		savecol = p->ps->pscol;
1115 	} else
1116 		savecol = SIZE_MAX;
1117 
1118 	/*
1119 	 * We found the next character, so the font instructions
1120 	 * for the previous one are complete.
1121 	 * Use them and print it.
1122 	 */
1123 
1124 	if (p->ps->last != '\0') {
1125 		if (p->ps->nextf != p->ps->lastf) {
1126 			ps_pclose(p);
1127 			ps_setfont(p, p->ps->nextf);
1128 		}
1129 		p->ps->nextf = TERMFONT_NONE;
1130 
1131 		/*
1132 		 * For an overstrike, if a previous character
1133 		 * was wider, advance to center the new one.
1134 		 */
1135 
1136 		if (p->ps->pscolnext) {
1137 			wx = fonts[p->ps->lastf].gly[(int)p->ps->last-32].wx;
1138 			if (p->ps->pscol + wx < p->ps->pscolnext)
1139 				p->ps->pscol = (p->ps->pscol +
1140 				    p->ps->pscolnext - wx) / 2;
1141 		}
1142 
1143 		ps_pletter(p, p->ps->last);
1144 
1145 		/*
1146 		 * For an overstrike, if a previous character
1147 		 * was wider, advance to the end of the old one.
1148 		 */
1149 
1150 		if (p->ps->pscol < p->ps->pscolnext) {
1151 			ps_pclose(p);
1152 			p->ps->pscol = p->ps->pscolnext;
1153 		}
1154 	}
1155 
1156 	/*
1157 	 * Do not print the current character yet because font
1158 	 * instructions might follow; only remember it.
1159 	 * For the first character, nothing else is done.
1160 	 * The final character will get printed from ps_fclose().
1161 	 */
1162 
1163 	p->ps->last = c;
1164 
1165 	/*
1166 	 * For an overstrike, back up to the previous position.
1167 	 * If the previous character is wider than any it overstrikes,
1168 	 * remember the current position, because it might also be
1169 	 * wider than all that will overstrike it.
1170 	 */
1171 
1172 	if (savecol != SIZE_MAX) {
1173 		if (p->ps->pscolnext < p->ps->pscol)
1174 			p->ps->pscolnext = p->ps->pscol;
1175 		ps_pclose(p);
1176 		p->ps->pscol = savecol;
1177 		p->ps->flags &= ~PS_BACKSP;
1178 	} else
1179 		p->ps->pscolnext = 0;
1180 }
1181 
1182 static void
1183 ps_advance(struct termp *p, size_t len)
1184 {
1185 
1186 	/*
1187 	 * Advance some spaces.  This can probably be made smarter,
1188 	 * i.e., to have multiple space-separated words in the same
1189 	 * scope, but this is easier:  just close out the current scope
1190 	 * and readjust our column settings.
1191 	 */
1192 
1193 	ps_fclose(p);
1194 	p->ps->pscol += len;
1195 }
1196 
1197 static void
1198 ps_endline(struct termp *p)
1199 {
1200 
1201 	/* Close out any scopes we have open: we're at eoln. */
1202 
1203 	ps_fclose(p);
1204 
1205 	/*
1206 	 * If we're in the margin, don't try to recalculate our current
1207 	 * row.  XXX: if the column tries to be fancy with multiple
1208 	 * lines, we'll do nasty stuff.
1209 	 */
1210 
1211 	if (PS_MARGINS & p->ps->flags)
1212 		return;
1213 
1214 	/* Left-justify. */
1215 
1216 	p->ps->pscol = p->ps->left;
1217 
1218 	/* If we haven't printed anything, return. */
1219 
1220 	if (PS_NEWPAGE & p->ps->flags)
1221 		return;
1222 
1223 	/*
1224 	 * Put us down a line.  If we're at the page bottom, spit out a
1225 	 * showpage and restart our row.
1226 	 */
1227 
1228 	if (p->ps->psrow >= p->ps->lineheight + p->ps->bottom) {
1229 		p->ps->psrow -= p->ps->lineheight;
1230 		return;
1231 	}
1232 
1233 	ps_closepage(p);
1234 }
1235 
1236 static void
1237 ps_setfont(struct termp *p, enum termfont f)
1238 {
1239 
1240 	assert(f < TERMFONT__MAX);
1241 	p->ps->lastf = f;
1242 
1243 	/*
1244 	 * If we're still at the top of the page, let the font-setting
1245 	 * be delayed until we actually have stuff to print.
1246 	 */
1247 
1248 	if (PS_NEWPAGE & p->ps->flags)
1249 		return;
1250 
1251 	if (TERMTYPE_PS == p->type)
1252 		ps_printf(p, "/%s %zu selectfont\n",
1253 		    fonts[(int)f].name, p->ps->scale);
1254 	else
1255 		ps_printf(p, "/F%d %zu Tf\n",
1256 		    (int)f, p->ps->scale);
1257 }
1258 
1259 static size_t
1260 ps_width(const struct termp *p, int c)
1261 {
1262 
1263 	if (c <= 32 || c - 32 >= MAXCHAR)
1264 		c = 0;
1265 	else
1266 		c -= 32;
1267 
1268 	return((size_t)fonts[(int)TERMFONT_NONE].gly[c].wx);
1269 }
1270 
1271 static int
1272 ps_hspan(const struct termp *p, const struct roffsu *su)
1273 {
1274 	double		 r;
1275 
1276 	/*
1277 	 * All of these measurements are derived by converting from the
1278 	 * native measurement to AFM units.
1279 	 */
1280 	switch (su->unit) {
1281 	case SCALE_BU:
1282 		/*
1283 		 * Traditionally, the default unit is fixed to the
1284 		 * output media.  So this would refer to the point.  In
1285 		 * mandoc(1), however, we stick to the default terminal
1286 		 * scaling unit so that output is the same regardless
1287 		 * the media.
1288 		 */
1289 		r = PNT2AFM(p, su->scale * 72.0 / 240.0);
1290 		break;
1291 	case SCALE_CM:
1292 		r = PNT2AFM(p, su->scale * 72.0 / 2.54);
1293 		break;
1294 	case SCALE_EM:
1295 		r = su->scale *
1296 		    fonts[(int)TERMFONT_NONE].gly[109 - 32].wx;
1297 		break;
1298 	case SCALE_EN:
1299 		r = su->scale *
1300 		    fonts[(int)TERMFONT_NONE].gly[110 - 32].wx;
1301 		break;
1302 	case SCALE_IN:
1303 		r = PNT2AFM(p, su->scale * 72.0);
1304 		break;
1305 	case SCALE_MM:
1306 		r = su->scale *
1307 		    fonts[(int)TERMFONT_NONE].gly[109 - 32].wx / 100.0;
1308 		break;
1309 	case SCALE_PC:
1310 		r = PNT2AFM(p, su->scale * 12.0);
1311 		break;
1312 	case SCALE_PT:
1313 		r = PNT2AFM(p, su->scale * 1.0);
1314 		break;
1315 	case SCALE_VS:
1316 		r = su->scale * p->ps->lineheight;
1317 		break;
1318 	default:
1319 		r = su->scale;
1320 		break;
1321 	}
1322 
1323 	return(r * 24.0);
1324 }
1325 
1326 static void
1327 ps_growbuf(struct termp *p, size_t sz)
1328 {
1329 	if (p->ps->psmargcur + sz <= p->ps->psmargsz)
1330 		return;
1331 
1332 	if (sz < PS_BUFSLOP)
1333 		sz = PS_BUFSLOP;
1334 
1335 	p->ps->psmargsz += sz;
1336 	p->ps->psmarg = mandoc_realloc(p->ps->psmarg, p->ps->psmargsz);
1337 }
1338