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