Various HTML backend cleanups.
[sgt/halibut] / bk_pdf.c
index fd1424a..6aba554 100644 (file)
--- a/bk_pdf.c
+++ b/bk_pdf.c
 
 paragraph *pdf_config_filename(char *filename)
 {
-    paragraph *p;
-    wchar_t *ufilename, *up;
-    int len;
-
-    p = mknew(paragraph);
-    memset(p, 0, sizeof(*p));
-    p->type = para_Config;
-    p->next = NULL;
-    p->fpos.filename = "<command line>";
-    p->fpos.line = p->fpos.col = -1;
-
-    ufilename = ufroma_dup(filename);
-    len = ustrlen(ufilename) + 2 + lenof(L"pdf-filename");
-    p->keyword = mknewa(wchar_t, len);
-    up = p->keyword;
-    ustrcpy(up, L"pdf-filename");
-    up = uadv(up);
-    ustrcpy(up, ufilename);
-    up = uadv(up);
-    *up = L'\0';
-    assert(up - p->keyword < len);
-    sfree(ufilename);
-
-    return p;
+    return cmdline_cfg_simple("pdf-filename", filename, NULL);
 }
 
 typedef struct object_Tag object;
@@ -56,12 +33,17 @@ struct objlist_Tag {
 static object *new_object(objlist *list);
 static void objtext(object *o, char const *text);
 static void objstream(object *o, char const *text);
+static void pdf_string(void (*add)(object *, char const *),
+                      object *, char const *);
+static void pdf_string_len(void (*add)(object *, char const *),
+                          object *, char const *, int);
 static void objref(object *o, object *dest);
 
 static void make_pages_node(object *node, object *parent, page_data *first,
                            page_data *last, object *resources);
 static int make_outline(object *parent, outline_element *start, int n,
                        int open);
+static int pdf_versionid(FILE *fp, word *words);
 
 void pdf_backend(paragraph *sourceform, keywordlist *keywords,
                 indexdata *idx, void *vdoc) {
@@ -85,7 +67,7 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords,
        if (p->type == para_Config && p->parent) {
            if (!ustricmp(p->keyword, L"pdf-filename")) {
                sfree(filename);
-               filename = utoa_dup(uadv(p->keyword));
+               filename = dupstr(adv(p->origkeyword));
            }
        }
     }
@@ -94,7 +76,10 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords,
     olist.number = 1;
 
     cat = new_object(&olist);
-    outlines = new_object(&olist);
+    if (doc->n_outline_elements > 0)
+       outlines = new_object(&olist);
+    else
+       outlines = NULL;
     pages = new_object(&olist);
     resources = new_object(&olist);
 
@@ -102,11 +87,16 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords,
      * The catalogue just contains references to the outlines and
      * pages objects.
      */
-    objtext(cat, "<<\n/Type /Catalog\n/Outlines ");
-    objref(cat, outlines);
+    objtext(cat, "<<\n/Type /Catalog");
+    if (outlines) {
+       objtext(cat, "\n/Outlines ");
+       objref(cat, outlines);
+    }
     objtext(cat, "\n/Pages ");
     objref(cat, pages);
-    objtext(cat, "\n/PageMode /UseOutlines\n>>\n");
+    if (outlines)
+       objtext(cat, "\n/PageMode /UseOutlines");
+    objtext(cat, "\n>>\n");
 
     /*
      * Set up the resources dictionary, which mostly means
@@ -194,8 +184,9 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords,
     for (page = doc->pages; page; page = page->next) {
        object *opage, *cstr;
        rect *r;
-       text_fragment *frag;
+       text_fragment *frag, *frag_end;
        char buf[256];
+       int x, y, lx, ly;
 
        opage = (object *)page->spare;
        /*
@@ -235,24 +226,89 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords,
        }
 
        objstream(cstr, "BT\n");
-       for (frag = page->first_text; frag; frag = frag->next) {
-           char *c;
 
+       /*
+        * PDF tracks two separate current positions: the position
+        * given in the `line matrix' and the position given in the
+        * `text matrix'. We must therefore track both as well.
+        * They start off at -1 (unset).
+        */
+       lx = ly = -1;
+       x = y = -1;
+
+       frag = page->first_text;
+       while (frag) {
+           /*
+            * For compactness, I'm going to group text fragments
+            * into subsequences that use the same font+size. So
+            * first find the end of this subsequence.
+            */
+           for (frag_end = frag;
+                (frag_end &&
+                 frag_end->fe == frag->fe &&
+                 frag_end->fontsize == frag->fontsize);
+                frag_end = frag_end->next);
+
+           /*
+            * Now select the text fragment, and prepare to display
+            * the text.
+            */
            objstream(cstr, "/");
            objstream(cstr, frag->fe->name);
-           sprintf(buf, " %d Tf 1 0 0 1 %g %g Tm (", frag->fontsize,
-                   frag->x/4096.0, frag->y/4096.0);
+           sprintf(buf, " %d Tf ", frag->fontsize);
            objstream(cstr, buf);
 
-           for (c = frag->text; *c; c++) {
-               if (*c == '(' || *c == ')' || *c == '\\')
-                   objstream(cstr, "\\");
-               buf[0] = *c;
-               buf[1] = '\0';
+           while (frag && frag != frag_end) {
+               /*
+                * Place the text position for the first piece of
+                * text.
+                */
+               if (lx < 0) {
+                   sprintf(buf, "1 0 0 1 %g %g Tm ",
+                           frag->x/4096.0, frag->y/4096.0);
+               } else {
+                   sprintf(buf, "%g %g Td ",
+                           (frag->x - lx)/4096.0, (frag->y - ly)/4096.0);
+               }
                objstream(cstr, buf);
+               lx = x = frag->x;
+               ly = y = frag->y;
+
+               /*
+                * See if we're going to use Tj (show a single
+                * string) or TJ (show an array of strings with
+                * x-spacings between them). We determine this by
+                * seeing if there's more than one text fragment in
+                * sequence with the same y-coordinate.
+                */
+               if (frag->next && frag->next != frag_end &&
+                   frag->next->y == y) {
+                   /*
+                    * The TJ strategy.
+                    */
+                   objstream(cstr, "[");
+                   while (frag && frag != frag_end && frag->y == y) {
+                       if (frag->x != x) {
+                           sprintf(buf, "%g",
+                                   (x - frag->x) * 1000.0 /
+                                   (4096.0 * frag->fontsize));
+                           objstream(cstr, buf);
+                       }
+                       pdf_string(objstream, cstr, frag->text);
+                       x = frag->x + frag->width;
+                       frag = frag->next;
+                   }
+                   objstream(cstr, "]TJ\n");
+               } else
+               {
+                   /*
+                    * The Tj strategy.
+                    */
+                   pdf_string(objstream, cstr, frag->text);
+                   objstream(cstr, "Tj\n");
+                   frag = frag->next;
+               }
            }
-
-           objstream(cstr, ") Tj\n");
        }
        objstream(cstr, "ET");
 
@@ -284,18 +340,9 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords,
                    objref(annot, (object *)xr->dest.page->spare);
                    objtext(annot, " /XYZ null null null]\n");
                } else {
-                   char *p;
-
-                   objtext(annot, "/A <<\n/Type /Action\n/S /URI\n/URI (");
-                   for (p = xr->dest.url; *p; p++) {
-                       char c[2];
-                       c[0] = *p;
-                       c[1] = '\0';
-                       if (*p == '(' || *p == ')' || *p == '\\')
-                           objtext(annot, "\\");
-                       objtext(annot, c);
-                   }
-                   objtext(annot, ")\n>>\n");
+                   objtext(annot, "/A <<\n/Type /Action\n/S /URI\n/URI ");
+                   pdf_string(objtext, annot, xr->dest.url);
+                   objtext(annot, "\n>>\n");
                }
 
                objtext(annot, ">>\n");
@@ -310,7 +357,7 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords,
     /*
      * Set up the outlines dictionary.
      */
-    {
+    if (outlines) {
        int topcount;
        char buf[80];
 
@@ -372,9 +419,13 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords,
     }
 
     /*
-     * Header
+     * Header. I'm going to put the version IDs in the header as
+     * well, simply in PDF comments.
      */
     fileoff = fprintf(fp, "%%PDF-1.3\n");
+    for (p = sourceform; p; p = p->next)
+       if (p->type == para_VersionID)
+           fileoff += pdf_versionid(fp, p->words);
 
     /*
      * Body
@@ -413,7 +464,7 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords,
 
 static object *new_object(objlist *list)
 {
-    object *obj = mknew(object);
+    object *obj = snew(object);
 
     obj->list = list;
 
@@ -539,101 +590,32 @@ static void make_pages_node(object *node, object *parent, page_data *first,
  * means that glyphs are identified by PS strings and hence font
  * encoding can be managed independently of the supplied encoding
  * of the font. However, in the document outline, the PDF spec
- * simply asks for ordinary text strings without mentioning what
- * character set they are supposed to be interpreted in.
- * 
- * Therefore, for the moment, I'm going to assume they're US-ASCII
- * only. If anyone knows better, they should let me know :-/
+ * encodes in either PDFDocEncoding (a custom superset of
+ * ISO-8859-1) or UTF-16BE.
  */
-static int pdf_convert(wchar_t *s, char **result) {
-    int doing = (result != 0);
-    int ok = TRUE;
-    char *p = NULL;
-    int plen = 0, psize = 0;
-
-    for (; *s; s++) {
-       wchar_t c = *s;
-       char outc;
-
-       if (c >= 32 && c <= 126) {
-           /* Char is OK. */
-           outc = (char)c;
-       } else {
-           /* Char is not OK. */
-           ok = FALSE;
-           outc = 0xBF;               /* approximate the good old DEC `uh?' */
-       }
-       if (doing) {
-           if (plen >= psize) {
-               psize = plen + 256;
-               p = resize(p, psize);
-           }
-           p[plen++] = outc;
-       }
-    }
-    if (doing) {
-       p = resize(p, plen+1);
-       p[plen] = '\0';
-       *result = p;
+static char *pdf_outline_convert(wchar_t *s, int *len) {
+    char *ret;
+
+    ret = utoa_careful_dup(s, CS_PDF);
+
+    /*
+     * Very silly special case: if the returned string begins with
+     * FE FF, then the PDF reader will mistake it for a UTF-16BE
+     * string. So in this case we give up on PDFDocEncoding and
+     * encode it in UTF-16 straight away.
+     */
+    if (ret && ret[0] == '\xFE' && ret[1] == '\xFF') {
+       sfree(ret);
+       ret = NULL;
     }
-    return ok;
-}
 
-static void pdf_rdaddwc(rdstringc *rs, word *text) {
-    char *c;
-
-    for (; text; text = text->next) switch (text->type) {
-      case word_HyperLink:
-      case word_HyperEnd:
-      case word_UpperXref:
-      case word_LowerXref:
-      case word_XrefEnd:
-      case word_IndexRef:
-       break;
-
-      case word_Normal:
-      case word_Emph:
-      case word_Code:
-      case word_WeakCode:
-      case word_WhiteSpace:
-      case word_EmphSpace:
-      case word_CodeSpace:
-      case word_WkCodeSpace:
-      case word_Quote:
-      case word_EmphQuote:
-      case word_CodeQuote:
-      case word_WkCodeQuote:
-       assert(text->type != word_CodeQuote &&
-              text->type != word_WkCodeQuote);
-       if (towordstyle(text->type) == word_Emph &&
-           (attraux(text->aux) == attr_First ||
-            attraux(text->aux) == attr_Only))
-           rdaddc(rs, '_');           /* FIXME: configurability */
-       else if (towordstyle(text->type) == word_Code &&
-                (attraux(text->aux) == attr_First ||
-                 attraux(text->aux) == attr_Only))
-           rdaddc(rs, '\'');          /* FIXME: configurability */
-       if (removeattr(text->type) == word_Normal) {
-           if (pdf_convert(text->text, &c))
-               rdaddsc(rs, c);
-           else
-               pdf_rdaddwc(rs, text->alt);
-           sfree(c);
-       } else if (removeattr(text->type) == word_WhiteSpace) {
-           rdaddc(rs, ' ');
-       } else if (removeattr(text->type) == word_Quote) {
-           rdaddc(rs, '\''); /* FIXME: configurability */
-       }
-       if (towordstyle(text->type) == word_Emph &&
-           (attraux(text->aux) == attr_Last ||
-            attraux(text->aux) == attr_Only))
-           rdaddc(rs, '_');           /* FIXME: configurability */
-       else if (towordstyle(text->type) == word_Code &&
-                (attraux(text->aux) == attr_Last ||
-                 attraux(text->aux) == attr_Only))
-           rdaddc(rs, '\'');          /* FIXME: configurability */
-       break;
+    if (!ret) {
+       ret = utoa_dup_len(s, CS_UTF16BE, len);
+    } else {
+       *len = strlen(ret);
     }
+
+    return ret;
 }
 
 static int make_outline(object *parent, outline_element *items, int n,
@@ -642,15 +624,14 @@ static int make_outline(object *parent, outline_element *items, int n,
     int level, totalcount = 0;
     outline_element *itemp;
     object *curr, *prev = NULL, *first = NULL, *last = NULL;
-    para_data *pdata;
 
     assert(n > 0);
 
     level = items->level;
 
     while (n > 0) {
-       rdstringc rs = {0, 0, NULL};
-       char *p;
+       char *title;
+       int titlelen;
 
        /*
         * Here we expect to be sitting on an item at the given
@@ -659,33 +640,18 @@ static int make_outline(object *parent, outline_element *items, int n,
         */
        assert(items->level == level);
 
-       if (level == 1 && items->para->kwtext) {
-           pdf_rdaddwc(&rs, items->para->kwtext);
-           rdaddsc(&rs, ": ");
-       } else if (level > 1 && items->para->kwtext2) {
-           pdf_rdaddwc(&rs, items->para->kwtext2);
-           rdaddsc(&rs, " ");
-       }
-       pdf_rdaddwc(&rs, items->para->words);
+       title = pdf_outline_convert(items->pdata->outline_title, &titlelen);
 
        totalcount++;
        curr = new_object(parent->list);
        if (!first) first = curr;
        last = curr;
-       objtext(curr, "<<\n/Title (");
-       for (p = rs.text; p < rs.text+rs.pos; p++) {
-           char c[2];
-           if (*p == '\\' || *p == '(' || *p == ')')
-               objtext(curr, "\\");
-           c[0] = *p;
-           c[1] = '\0';
-           objtext(curr, c);
-       }
-       objtext(curr, ")\n/Parent ");
+       objtext(curr, "<<\n/Title ");
+       pdf_string_len(objtext, curr, title, titlelen);
+       objtext(curr, "\n/Parent ");
        objref(curr, parent);
        objtext(curr, "\n/Dest [");
-       pdata = (para_data *)items->para->private_data;
-       objref(curr, (object *)pdata->first->page->spare);
+       objref(curr, (object *)items->pdata->first->page->spare);
        objtext(curr, " /XYZ null null null]\n");
        if (prev) {
            objtext(curr, "/Prev ");
@@ -727,3 +693,75 @@ static int make_outline(object *parent, outline_element *items, int n,
 
     return totalcount;
 }
+
+static int pdf_versionid(FILE *fp, word *words)
+{
+    int ret;
+
+    ret = fprintf(fp, "%% ");
+
+    for (; words; words = words->next) {
+       char *text;
+       int type;
+
+       switch (words->type) {
+         case word_HyperLink:
+         case word_HyperEnd:
+         case word_UpperXref:
+         case word_LowerXref:
+         case word_XrefEnd:
+         case word_IndexRef:
+           continue;
+       }
+
+       type = removeattr(words->type);
+
+       switch (type) {
+         case word_Normal:
+           text = utoa_dup(words->text, CS_ASCII);
+           break;
+         case word_WhiteSpace:
+           text = dupstr(" ");
+           break;
+         case word_Quote:
+           text = dupstr("'");
+           break;
+       }
+
+       fputs(text, fp);
+       ret += strlen(text);
+       sfree(text);
+    }
+
+    ret += fprintf(fp, "\n");
+
+    return ret;
+}
+
+static void pdf_string_len(void (*add)(object *, char const *),
+                          object *o, char const *str, int len)
+{
+    char const *p;
+
+    add(o, "(");
+    for (p = str; len > 0; p++, len--) {
+       char c[10];
+       if (*p < ' ' || *p > '~') {
+           sprintf(c, "\\%03o", 0xFF & (int)*p);
+       } else {
+           int n = 0;
+           if (*p == '\\' || *p == '(' || *p == ')')
+               c[n++] = '\\';
+           c[n++] = *p;
+           c[n] = '\0';
+       }
+       add(o, c);
+    }
+    add(o, ")");
+}
+
+static void pdf_string(void (*add)(object *, char const *),
+                      object *o, char const *str)
+{
+    pdf_string_len(add, o, str, strlen(str));
+}