Now that we've got definitive metrics for the standard fonts, there's no need
[sgt/halibut] / bk_pdf.c
1 /*
2 * PDF backend for Halibut
3 */
4
5 #include <assert.h>
6 #include "halibut.h"
7 #include "paper.h"
8
9 #define TREE_BRANCH 2 /* max branching factor in page tree */
10
11 paragraph *pdf_config_filename(char *filename)
12 {
13 return cmdline_cfg_simple("pdf-filename", filename, NULL);
14 }
15
16 typedef struct object_Tag object;
17 typedef struct objlist_Tag objlist;
18
19 struct object_Tag {
20 objlist *list;
21 object *next;
22 int number;
23 rdstringc main, stream;
24 int size, fileoff;
25 char *final;
26 };
27
28 struct objlist_Tag {
29 int number;
30 object *head, *tail;
31 };
32
33 static object *new_object(objlist *list);
34 static void objtext(object *o, char const *text);
35 static void objstream(object *o, char const *text);
36 static void pdf_string(void (*add)(object *, char const *),
37 object *, char const *);
38 static void pdf_string_len(void (*add)(object *, char const *),
39 object *, char const *, int);
40 static void objref(object *o, object *dest);
41 static char *pdf_outline_convert(wchar_t *s, int *len);
42
43 static int is_std_font(char const *name);
44
45 static void make_pages_node(object *node, object *parent, page_data *first,
46 page_data *last, object *resources,
47 object *mediabox);
48 static int make_outline(object *parent, outline_element *start, int n,
49 int open);
50 static int pdf_versionid(FILE *fp, word *words);
51
52 void pdf_backend(paragraph *sourceform, keywordlist *keywords,
53 indexdata *idx, void *vdoc) {
54 document *doc = (document *)vdoc;
55 int font_index;
56 font_encoding *fe;
57 page_data *page;
58 int pageno;
59 FILE *fp;
60 char *filename;
61 paragraph *p;
62 objlist olist;
63 object *o, *info, *cat, *outlines, *pages, *resources, *mediabox;
64 int fileoff;
65
66 IGNORE(keywords);
67 IGNORE(idx);
68
69 filename = dupstr("output.pdf");
70 for (p = sourceform; p; p = p->next) {
71 if (p->type == para_Config) {
72 if (!ustricmp(p->keyword, L"pdf-filename")) {
73 sfree(filename);
74 filename = dupstr(adv(p->origkeyword));
75 }
76 }
77 }
78
79 olist.head = olist.tail = NULL;
80 olist.number = 1;
81
82 {
83 char buf[256];
84
85 info = new_object(&olist);
86 objtext(info, "<<\n");
87 if (doc->n_outline_elements > 0) {
88 char *title;
89 int titlelen;
90
91 title =
92 pdf_outline_convert(doc->outline_elements->pdata->outline_title,
93 &titlelen);
94 objtext(info, "/Title ");
95 pdf_string_len(objtext, info, title, titlelen);
96 sfree(title);
97 objtext(info, "\n");
98 }
99 objtext(info, "/Producer ");
100 sprintf(buf, "Halibut, %s", version);
101 pdf_string(objtext, info, buf);
102 objtext(info, "\n>>\n");
103 }
104
105 cat = new_object(&olist);
106 if (doc->n_outline_elements > 0)
107 outlines = new_object(&olist);
108 else
109 outlines = NULL;
110 pages = new_object(&olist);
111 resources = new_object(&olist);
112
113 /*
114 * The catalogue just contains references to the outlines and
115 * pages objects.
116 */
117 objtext(cat, "<<\n/Type /Catalog");
118 if (outlines) {
119 objtext(cat, "\n/Outlines ");
120 objref(cat, outlines);
121 }
122 objtext(cat, "\n/Pages ");
123 objref(cat, pages);
124 if (outlines)
125 objtext(cat, "\n/PageMode /UseOutlines");
126 objtext(cat, "\n>>\n");
127
128 /*
129 * Set up the resources dictionary, which mostly means
130 * providing all the font objects and names to call them by.
131 */
132 font_index = 0;
133 objtext(resources, "<<\n/Font <<\n");
134 for (fe = doc->fonts->head; fe; fe = fe->next) {
135 char fname[40];
136 int i;
137 object *font;
138
139 sprintf(fname, "f%d", font_index++);
140 fe->name = dupstr(fname);
141
142 font = new_object(&olist);
143
144 objtext(resources, "/");
145 objtext(resources, fe->name);
146 objtext(resources, " ");
147 objref(resources, font);
148 objtext(resources, "\n");
149
150 objtext(font, "<<\n/Type /Font\n/Subtype /Type1\n/Name /");
151 objtext(font, fe->name);
152 objtext(font, "\n/BaseFont /");
153 objtext(font, fe->font->info->name);
154 objtext(font, "\n/Encoding <<\n/Type /Encoding\n/Differences [");
155
156 for (i = 0; i < 256; i++) {
157 char buf[20];
158 if (!fe->vector[i])
159 continue;
160 sprintf(buf, "\n%d /", i);
161 objtext(font, buf);
162 objtext(font, fe->vector[i] ? fe->vector[i] : ".notdef");
163 }
164
165 objtext(font, "\n]\n>>\n");
166
167 if (!is_std_font(fe->font->info->name)){
168 object *widths = new_object(&olist);
169 int firstchar = -1, lastchar = -1;
170 char buf[80];
171 for (i = 0; i < 256; i++)
172 if (fe->indices[i] >= 0) {
173 if (firstchar < 0) firstchar = i;
174 lastchar = i;
175 }
176 sprintf(buf, "/FirstChar %d\n/LastChar %d\n/Widths ",
177 firstchar, lastchar);
178 objtext(font, buf);
179 objref(font, widths);
180 objtext(font, "\n");
181 objtext(widths, "[\n");
182 for (i = firstchar; i <= lastchar; i++) {
183 char buf[80];
184 double width;
185 if (fe->indices[i] < 0)
186 width = 0.0;
187 else
188 width = fe->font->info->widths[fe->indices[i]];
189 sprintf(buf, "%g\n", 1000.0 * width / FUNITS_PER_PT);
190 objtext(widths, buf);
191 }
192 objtext(widths, "]\n");
193 }
194
195 objtext(font, ">>\n");
196 }
197 objtext(resources, ">>\n>>\n");
198
199 {
200 char buf[255];
201 mediabox = new_object(&olist);
202 sprintf(buf, "[0 0 %g %g]\n",
203 doc->paper_width / FUNITS_PER_PT,
204 doc->paper_height / FUNITS_PER_PT);
205 objtext(mediabox, buf);
206 }
207
208 /*
209 * Define the page objects for each page, and get each one
210 * ready to have a `Parent' specification added to it.
211 */
212 for (page = doc->pages; page; page = page->next) {
213 object *opage;
214
215 opage = new_object(&olist);
216 page->spare = opage;
217 objtext(opage, "<<\n/Type /Page\n");
218 }
219
220 /*
221 * Recursively build the page tree.
222 */
223 make_pages_node(pages, NULL, doc->pages, NULL, resources, mediabox);
224
225 /*
226 * Create and render the individual pages.
227 */
228 pageno = 0;
229 for (page = doc->pages; page; page = page->next) {
230 object *opage, *cstr;
231 rect *r;
232 text_fragment *frag, *frag_end;
233 char buf[256];
234 int x, y, lx, ly;
235
236 opage = (object *)page->spare;
237 /*
238 * At this point the page dictionary is already
239 * half-written, with /Type and /Parent already present. We
240 * continue from there.
241 */
242
243 /*
244 * The PDF spec says /Resources is required, but also says
245 * that it's inheritable and may be omitted if it's present
246 * in a Pages node. In our case it is: it's present in the
247 * topmost /Pages node because we carefully put it there.
248 * So we don't need a /Resources entry here. The same applies
249 * to /MediaBox.
250 */
251
252 /*
253 * Now we're ready to define a content stream containing
254 * the actual text on the page.
255 */
256 cstr = new_object(&olist);
257 objtext(opage, "/Contents ");
258 objref(opage, cstr);
259 objtext(opage, "\n");
260
261 /*
262 * Render any rectangles on the page.
263 */
264 for (r = page->first_rect; r; r = r->next) {
265 char buf[512];
266 sprintf(buf, "%g %g %g %g re f\n",
267 r->x / FUNITS_PER_PT, r->y / FUNITS_PER_PT,
268 r->w / FUNITS_PER_PT, r->h / FUNITS_PER_PT);
269 objstream(cstr, buf);
270 }
271
272 objstream(cstr, "BT\n");
273
274 /*
275 * PDF tracks two separate current positions: the position
276 * given in the `line matrix' and the position given in the
277 * `text matrix'. We must therefore track both as well.
278 * They start off at -1 (unset).
279 */
280 lx = ly = -1;
281 x = y = -1;
282
283 frag = page->first_text;
284 while (frag) {
285 /*
286 * For compactness, I'm going to group text fragments
287 * into subsequences that use the same font+size. So
288 * first find the end of this subsequence.
289 */
290 for (frag_end = frag;
291 (frag_end &&
292 frag_end->fe == frag->fe &&
293 frag_end->fontsize == frag->fontsize);
294 frag_end = frag_end->next);
295
296 /*
297 * Now select the text fragment, and prepare to display
298 * the text.
299 */
300 objstream(cstr, "/");
301 objstream(cstr, frag->fe->name);
302 sprintf(buf, " %d Tf ", frag->fontsize);
303 objstream(cstr, buf);
304
305 while (frag && frag != frag_end) {
306 /*
307 * Place the text position for the first piece of
308 * text.
309 */
310 if (lx < 0) {
311 sprintf(buf, "1 0 0 1 %g %g Tm ",
312 frag->x/FUNITS_PER_PT, frag->y/FUNITS_PER_PT);
313 } else {
314 sprintf(buf, "%g %g Td ",
315 (frag->x - lx)/FUNITS_PER_PT,
316 (frag->y - ly)/FUNITS_PER_PT);
317 }
318 objstream(cstr, buf);
319 lx = x = frag->x;
320 ly = y = frag->y;
321
322 /*
323 * See if we're going to use Tj (show a single
324 * string) or TJ (show an array of strings with
325 * x-spacings between them). We determine this by
326 * seeing if there's more than one text fragment in
327 * sequence with the same y-coordinate.
328 */
329 if (frag->next && frag->next != frag_end &&
330 frag->next->y == y) {
331 /*
332 * The TJ strategy.
333 */
334 objstream(cstr, "[");
335 while (frag && frag != frag_end && frag->y == y) {
336 if (frag->x != x) {
337 sprintf(buf, "%g",
338 (x - frag->x) * 1000.0 /
339 (FUNITS_PER_PT * frag->fontsize));
340 objstream(cstr, buf);
341 }
342 pdf_string(objstream, cstr, frag->text);
343 x = frag->x + frag->width;
344 frag = frag->next;
345 }
346 objstream(cstr, "]TJ\n");
347 } else
348 {
349 /*
350 * The Tj strategy.
351 */
352 pdf_string(objstream, cstr, frag->text);
353 objstream(cstr, "Tj\n");
354 frag = frag->next;
355 }
356 }
357 }
358 objstream(cstr, "ET");
359
360 /*
361 * Also, we want an annotation dictionary containing the
362 * cross-references from this page.
363 */
364 if (page->first_xref) {
365 xref *xr;
366 objtext(opage, "/Annots [\n");
367
368 for (xr = page->first_xref; xr; xr = xr->next) {
369 object *annot;
370 char buf[256];
371
372 annot = new_object(&olist);
373 objref(opage, annot);
374 objtext(opage, "\n");
375
376 objtext(annot, "<<\n/Type /Annot\n/Subtype /Link\n/Rect [");
377 sprintf(buf, "%g %g %g %g",
378 xr->lx / FUNITS_PER_PT, xr->by / FUNITS_PER_PT,
379 xr->rx / FUNITS_PER_PT, xr->ty / FUNITS_PER_PT);
380 objtext(annot, buf);
381 objtext(annot, "]\n/Border [0 0 0]\n");
382
383 if (xr->dest.type == PAGE) {
384 objtext(annot, "/Dest [");
385 objref(annot, (object *)xr->dest.page->spare);
386 objtext(annot, " /XYZ null null null]\n");
387 } else {
388 objtext(annot, "/A <<\n/Type /Action\n/S /URI\n/URI ");
389 pdf_string(objtext, annot, xr->dest.url);
390 objtext(annot, "\n>>\n");
391 }
392
393 objtext(annot, ">>\n");
394 }
395
396 objtext(opage, "]\n");
397 }
398
399 objtext(opage, ">>\n");
400 }
401
402 /*
403 * Set up the outlines dictionary.
404 */
405 if (outlines) {
406 int topcount;
407 char buf[80];
408
409 objtext(outlines, "<<\n/Type /Outlines\n");
410 topcount = make_outline(outlines, doc->outline_elements,
411 doc->n_outline_elements, TRUE);
412 sprintf(buf, "/Count %d\n>>\n", topcount);
413 objtext(outlines, buf);
414 }
415
416 /*
417 * Assemble the final linear form of every object.
418 */
419 for (o = olist.head; o; o = o->next) {
420 rdstringc rs = {0, 0, NULL};
421 char text[80];
422
423 sprintf(text, "%d 0 obj\n", o->number);
424 rdaddsc(&rs, text);
425
426 if (!o->main.text && o->stream.text) {
427 sprintf(text, "<<\n/Length %d\n>>\n", o->stream.pos);
428 rdaddsc(&o->main, text);
429 }
430
431 assert(o->main.text);
432 rdaddsc(&rs, o->main.text);
433 sfree(o->main.text);
434
435 if (rs.text[rs.pos-1] != '\n')
436 rdaddc(&rs, '\n');
437
438 if (o->stream.text) {
439 /*
440 * FIXME: If we ever start compressing stream data then
441 * it will have zero bytes in it, so we'll have to be
442 * more careful than this.
443 */
444 rdaddsc(&rs, "stream\n");
445 rdaddsc(&rs, o->stream.text);
446 rdaddsc(&rs, "\nendstream\n");
447 sfree(o->stream.text);
448 }
449
450 rdaddsc(&rs, "endobj\n");
451
452 o->final = rs.text;
453 o->size = rs.pos;
454 }
455
456 /*
457 * Write out the PDF file.
458 */
459
460 fp = fopen(filename, "wb");
461 if (!fp) {
462 error(err_cantopenw, filename);
463 return;
464 }
465
466 /*
467 * Header. I'm going to put the version IDs in the header as
468 * well, simply in PDF comments.
469 */
470 fileoff = fprintf(fp, "%%PDF-1.3\n");
471 for (p = sourceform; p; p = p->next)
472 if (p->type == para_VersionID)
473 fileoff += pdf_versionid(fp, p->words);
474
475 /*
476 * Body
477 */
478 for (o = olist.head; o; o = o->next) {
479 o->fileoff = fileoff;
480 fwrite(o->final, 1, o->size, fp);
481 fileoff += o->size;
482 }
483
484 /*
485 * Cross-reference table
486 */
487 fprintf(fp, "xref\n");
488 assert(olist.head->number == 1);
489 fprintf(fp, "0 %d\n", olist.tail->number + 1);
490 fprintf(fp, "0000000000 65535 f \n");
491 for (o = olist.head; o; o = o->next) {
492 char entry[40];
493 sprintf(entry, "%010d 00000 n \n", o->fileoff);
494 assert(strlen(entry) == 20);
495 fputs(entry, fp);
496 }
497
498 /*
499 * Trailer
500 */
501 fprintf(fp, "trailer\n<<\n/Size %d\n/Root %d 0 R\n/Info %d 0 R\n>>\n",
502 olist.tail->number + 1, cat->number, info->number);
503 fprintf(fp, "startxref\n%d\n%%%%EOF\n", fileoff);
504
505 fclose(fp);
506
507 sfree(filename);
508 }
509
510 static object *new_object(objlist *list)
511 {
512 object *obj = snew(object);
513
514 obj->list = list;
515
516 obj->main.text = NULL;
517 obj->main.pos = obj->main.size = 0;
518 obj->stream.text = NULL;
519 obj->stream.pos = obj->stream.size = 0;
520
521 obj->number = list->number++;
522
523 obj->next = NULL;
524 if (list->tail)
525 list->tail->next = obj;
526 else
527 list->head = obj;
528 list->tail = obj;
529
530 obj->size = 0;
531 obj->final = NULL;
532
533 return obj;
534 }
535
536 static void objtext(object *o, char const *text)
537 {
538 rdaddsc(&o->main, text);
539 }
540
541 static void objstream(object *o, char const *text)
542 {
543 rdaddsc(&o->stream, text);
544 }
545
546 static void objref(object *o, object *dest)
547 {
548 char buf[40];
549 sprintf(buf, "%d 0 R", dest->number);
550 rdaddsc(&o->main, buf);
551 }
552
553 static char const * const stdfonts[] = {
554 "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic",
555 "Helvetica", "Helvetica-Bold", "Helvetica-Oblique","Helvetica-BoldOblique",
556 "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique",
557 "Symbol", "ZapfDingbats"
558 };
559
560 static int is_std_font(char const *name) {
561 unsigned i;
562 for (i = 0; i < lenof(stdfonts); i++)
563 if (strcmp(name, stdfonts[i]) == 0)
564 return TRUE;
565 return FALSE;
566 }
567
568 static void make_pages_node(object *node, object *parent, page_data *first,
569 page_data *last, object *resources,
570 object *mediabox)
571 {
572 int count;
573 page_data *page;
574 char buf[80];
575
576 objtext(node, "<<\n/Type /Pages\n");
577 if (parent) {
578 objtext(node, "/Parent ");
579 objref(node, parent);
580 objtext(node, "\n");
581 }
582
583 /*
584 * Count the pages in this stretch, to see if there are few
585 * enough to reference directly.
586 */
587 count = 0;
588 for (page = first; page; page = page->next) {
589 count++;
590 if (page == last)
591 break;
592 }
593
594 sprintf(buf, "/Count %d\n/Kids [\n", count);
595 objtext(node, buf);
596
597 if (count > TREE_BRANCH) {
598 int i;
599 page_data *thisfirst, *thislast;
600
601 page = first;
602
603 for (i = 0; i < TREE_BRANCH; i++) {
604 int number = (i+1) * count / TREE_BRANCH - i * count / TREE_BRANCH;
605 thisfirst = page;
606 while (number--) {
607 thislast = page;
608 page = page->next;
609 }
610
611 if (thisfirst == thislast) {
612 objref(node, (object *)thisfirst->spare);
613 objtext((object *)thisfirst->spare, "/Parent ");
614 objref((object *)thisfirst->spare, node);
615 objtext((object *)thisfirst->spare, "\n");
616 } else {
617 object *newnode = new_object(node->list);
618 make_pages_node(newnode, node, thisfirst, thislast,
619 NULL, NULL);
620 objref(node, newnode);
621 }
622 objtext(node, "\n");
623 }
624
625 assert(thislast == last || page == NULL);
626
627 } else {
628 for (page = first; page; page = page->next) {
629 objref(node, (object *)page->spare);
630 objtext(node, "\n");
631 objtext((object *)page->spare, "/Parent ");
632 objref((object *)page->spare, node);
633 objtext((object *)page->spare, "\n");
634 if (page == last)
635 break;
636 }
637 }
638
639 objtext(node, "]\n");
640
641 if (resources) {
642 objtext(node, "/Resources ");
643 objref(node, resources);
644 objtext(node, "\n");
645 }
646 if (mediabox) {
647 objtext(node, "/MediaBox ");
648 objref(node, mediabox);
649 objtext(node, "\n");
650 }
651
652 objtext(node, ">>\n");
653 }
654
655 /*
656 * In text on the page, PDF uses the PostScript font model, which
657 * means that glyphs are identified by PS strings and hence font
658 * encoding can be managed independently of the supplied encoding
659 * of the font. However, in the document outline, the PDF spec
660 * encodes in either PDFDocEncoding (a custom superset of
661 * ISO-8859-1) or UTF-16BE.
662 */
663 static char *pdf_outline_convert(wchar_t *s, int *len) {
664 char *ret;
665
666 ret = utoa_careful_dup(s, CS_PDF);
667
668 /*
669 * Very silly special case: if the returned string begins with
670 * FE FF, then the PDF reader will mistake it for a UTF-16BE
671 * string. So in this case we give up on PDFDocEncoding and
672 * encode it in UTF-16 straight away.
673 */
674 if (ret && ret[0] == '\xFE' && ret[1] == '\xFF') {
675 sfree(ret);
676 ret = NULL;
677 }
678
679 if (!ret) {
680 ret = utoa_dup_len(s, CS_UTF16BE, len);
681 } else {
682 *len = strlen(ret);
683 }
684
685 return ret;
686 }
687
688 static int make_outline(object *parent, outline_element *items, int n,
689 int open)
690 {
691 int level, totalcount = 0;
692 outline_element *itemp;
693 object *curr, *prev = NULL, *first = NULL, *last = NULL;
694
695 assert(n > 0);
696
697 level = items->level;
698
699 while (n > 0) {
700 char *title;
701 int titlelen;
702
703 /*
704 * Here we expect to be sitting on an item at the given
705 * level. So we start by constructing an outline entry for
706 * that item.
707 */
708 assert(items->level == level);
709
710 title = pdf_outline_convert(items->pdata->outline_title, &titlelen);
711
712 totalcount++;
713 curr = new_object(parent->list);
714 if (!first) first = curr;
715 last = curr;
716 objtext(curr, "<<\n/Title ");
717 pdf_string_len(objtext, curr, title, titlelen);
718 sfree(title);
719 objtext(curr, "\n/Parent ");
720 objref(curr, parent);
721 objtext(curr, "\n/Dest [");
722 objref(curr, (object *)items->pdata->first->page->spare);
723 objtext(curr, " /XYZ null null null]\n");
724 if (prev) {
725 objtext(curr, "/Prev ");
726 objref(curr, prev);
727 objtext(curr, "\n");
728
729 objtext(prev, "/Next ");
730 objref(prev, curr);
731 objtext(prev, "\n>>\n");
732 }
733 prev = curr;
734
735 items++, n--;
736 for (itemp = items; itemp < items+n && itemp->level > level;
737 itemp++);
738
739 if (itemp > items) {
740 char buf[80];
741 int count = make_outline(curr, items, itemp - items, FALSE);
742 if (!open)
743 count = -count;
744 else
745 totalcount += count;
746 sprintf(buf, "/Count %d\n", count);
747 objtext(curr, buf);
748 }
749
750 n -= itemp - items;
751 items = itemp;
752 }
753 objtext(prev, ">>\n");
754
755 assert(first && last);
756 objtext(parent, "/First ");
757 objref(parent, first);
758 objtext(parent, "\n/Last ");
759 objref(parent, last);
760 objtext(parent, "\n");
761
762 return totalcount;
763 }
764
765 static int pdf_versionid(FILE *fp, word *words)
766 {
767 int ret;
768
769 ret = fprintf(fp, "%% ");
770
771 for (; words; words = words->next) {
772 char *text;
773 int type;
774
775 switch (words->type) {
776 case word_HyperLink:
777 case word_HyperEnd:
778 case word_UpperXref:
779 case word_LowerXref:
780 case word_XrefEnd:
781 case word_IndexRef:
782 continue;
783 }
784
785 type = removeattr(words->type);
786
787 switch (type) {
788 case word_Normal:
789 text = utoa_dup(words->text, CS_ASCII);
790 break;
791 case word_WhiteSpace:
792 text = dupstr(" ");
793 break;
794 case word_Quote:
795 text = dupstr("'");
796 break;
797 }
798
799 fputs(text, fp);
800 ret += strlen(text);
801 sfree(text);
802 }
803
804 ret += fprintf(fp, "\n");
805
806 return ret;
807 }
808
809 static void pdf_string_len(void (*add)(object *, char const *),
810 object *o, char const *str, int len)
811 {
812 char const *p;
813
814 add(o, "(");
815 for (p = str; len > 0; p++, len--) {
816 char c[10];
817 if (*p < ' ' || *p > '~') {
818 sprintf(c, "\\%03o", 0xFF & (int)*p);
819 } else {
820 int n = 0;
821 if (*p == '\\' || *p == '(' || *p == ')')
822 c[n++] = '\\';
823 c[n++] = *p;
824 c[n] = '\0';
825 }
826 add(o, c);
827 }
828 add(o, ")");
829 }
830
831 static void pdf_string(void (*add)(object *, char const *),
832 object *o, char const *str)
833 {
834 pdf_string_len(add, o, str, strlen(str));
835 }