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