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