Add an error check for correct formatting in Deflate uncompressed
[sgt/halibut] / bk_ps.c
CommitLineData
43341922 1/*
2 * PostScript backend for Halibut
3 */
4
5#include <assert.h>
2bf6e538 6#include <stdarg.h>
43341922 7#include "halibut.h"
8#include "paper.h"
9
2bf6e538 10/* Ideal number of characters per line, for use in PostScript code */
11#define PS_WIDTH 79
12/* Absolute maxiumum characters per line, for use in DSC comments */
13#define PS_MAXWIDTH 255
14
b0f1f943 15static void ps_comment(FILE *fp, char const *leader, word *words);
2bf6e538 16static void ps_string_len(FILE *fp, int *cc, char const *str, int len);
17static void ps_string(FILE *fp, int *cc, char const *str);
09358aa7 18
43341922 19paragraph *ps_config_filename(char *filename)
20{
e4ea58f8 21 return cmdline_cfg_simple("ps-filename", filename, NULL);
43341922 22}
23
24void ps_backend(paragraph *sourceform, keywordlist *keywords,
25 indexdata *idx, void *vdoc) {
26 document *doc = (document *)vdoc;
27 int font_index;
28 font_encoding *fe;
29 page_data *page;
30 int pageno;
31 FILE *fp;
32 char *filename;
33 paragraph *p;
f8194b21 34 outline_element *oe;
35 int noe;
2bf6e538 36 int cc; /* Character count on current line */
43341922 37
38 IGNORE(keywords);
39 IGNORE(idx);
40
41 filename = dupstr("output.ps");
42 for (p = sourceform; p; p = p->next) {
7738a2fb 43 if (p->type == para_Config) {
43341922 44 if (!ustricmp(p->keyword, L"ps-filename")) {
45 sfree(filename);
e4ea58f8 46 filename = dupstr(adv(p->origkeyword));
43341922 47 }
48 }
49 }
50
0041ffdb 51 if (!strcmp(filename, "-"))
52 fp = stdout;
53 else
54 fp = fopen(filename, "w");
43341922 55 if (!fp) {
56 error(err_cantopenw, filename);
57 return;
58 }
59
b0f1f943 60 fprintf(fp, "%%!PS-Adobe-3.0\n");
61 fprintf(fp, "%%%%Creator: Halibut, %s\n", version);
d4319ca3 62 fprintf(fp, "%%%%DocumentData: Clean7Bit\n");
b0f1f943 63 fprintf(fp, "%%%%LanguageLevel: 1\n");
43341922 64 for (pageno = 0, page = doc->pages; page; page = page->next)
65 pageno++;
66 fprintf(fp, "%%%%Pages: %d\n", pageno);
b0f1f943 67 for (p = sourceform; p; p = p->next)
68 if (p->type == para_Title)
69 ps_comment(fp, "%%Title: ", p->words);
70 fprintf(fp, "%%%%DocumentNeededResources:\n");
71 for (fe = doc->fonts->head; fe; fe = fe->next)
72 /* XXX This may request the same font multiple times. */
3e2dd889 73 if (!fe->font->info->fontfile)
44407fea 74 fprintf(fp, "%%%%+ font %s\n", fe->font->info->name);
7d7f8de9 75 fprintf(fp, "%%%%DocumentSuppliedResources: procset Halibut 0 3\n");
44407fea 76 for (fe = doc->fonts->head; fe; fe = fe->next)
77 /* XXX This may request the same font multiple times. */
3e2dd889 78 if (fe->font->info->fontfile)
44407fea 79 fprintf(fp, "%%%%+ font %s\n", fe->font->info->name);
43341922 80 fprintf(fp, "%%%%EndComments\n");
81
82 fprintf(fp, "%%%%BeginProlog\n");
7d7f8de9 83 fprintf(fp, "%%%%BeginResource: procset Halibut 0 3\n");
7c8c4239 84 /*
85 * Supply a prologue function which allows a reasonably
86 * compressed representation of the text on the pages.
87 *
7b980ef7 88 * "t" expects two arguments: a y-coordinate, and then an array.
7c8c4239 89 * Elements of the array are processed sequentially as follows:
90 *
91 * - a number is treated as an x-coordinate
92 * - an array is treated as a (font, size) pair
93 * - a string is shown
7b980ef7 94 *
95 * "r" takes four arguments, and behaves like "rectfill".
7c8c4239 96 */
97 fprintf(fp,
67f13fa7 98 "/tdict 4 dict dup begin\n"
99 " /arraytype {aload pop scalefont setfont} bind def\n"
100 " /realtype {1 index moveto} bind def\n"
101 " /integertype /realtype load def\n"
102 " /stringtype {show} bind def\n"
103 "end def\n"
7b980ef7 104 "/t { tdict begin {dup type exec} forall end pop } bind def\n"
105 "/r { 4 2 roll moveto 1 index 0 rlineto 0 exch rlineto\n"
106 " neg 0 rlineto closepath fill } bind def\n");
3f167769 107 /*
108 * pdfmark wrappers
109 *
110 * "p" generates a named destination referencing this page.
111 * "x" generates a link to a named destination.
112 * "u" generates a link to a URI.
7d7f8de9 113 * "o" generates an outline entry.
114 * "m" generates a general pdfmark.
3f167769 115 *
116 * They all do nothing if pdfmark is undefined.
117 */
118 fprintf(fp,
119 "/pdfmark where { pop\n"
120 " /p { [ /Dest 3 -1 roll /View [ /XYZ null null null ]\n"
121 " /DEST pdfmark } bind def\n"
766c3188 122 " /x { [ /Dest 3 -1 roll /Rect 5 -1 roll /Border [0 0 0]\n"
3f167769 123 " /Subtype /Link /ANN pdfmark } bind def\n"
124 " /u { 2 dict dup /Subtype /URI put dup /URI 4 -1 roll put\n"
766c3188 125 " [ /Action 3 -1 roll /Rect 5 -1 roll /Border [0 0 0]\n"
3f167769 126 " /Subtype /Link /ANN pdfmark } bind def\n"
7d7f8de9 127 " /o { [ /Count 3 -1 roll /Dest 5 -1 roll /Title 7 -1 roll\n"
128 " /OUT pdfmark } bind def\n"
129 " /m /pdfmark load def\n"
130 "}\n");
131 fprintf(fp, "{\n"
a80ef2f1 132 " /p { pop } bind def\n"
133 " /x { pop pop } bind def\n"
134 " /u /x load def\n"
7d7f8de9 135 " /o { pop pop pop } bind def\n"
136 " /m /cleartomark load def\n"
3f167769 137 "} ifelse\n");
7c8c4239 138
b0f1f943 139 fprintf(fp, "%%%%EndResource\n");
43341922 140 fprintf(fp, "%%%%EndProlog\n");
141
142 fprintf(fp, "%%%%BeginSetup\n");
09358aa7 143
144 /*
f8194b21 145 * Assign a destination name to each page for pdfmark purposes.
146 */
147 pageno = 0;
148 for (page = doc->pages; page; page = page->next) {
149 char *buf;
150 pageno++;
151 buf = snewn(12, char);
152 sprintf(buf, "/p%d", pageno);
153 page->spare = buf;
154 }
155
156 /*
09358aa7 157 * This is as good a place as any to put version IDs.
158 */
159 for (p = sourceform; p; p = p->next)
160 if (p->type == para_VersionID)
b0f1f943 161 ps_comment(fp, "% ", p->words);
162
2bf6e538 163 cc = 0;
a10f193f 164 /*
165 * Request the correct page size. We might want to bracket this
166 * with "%%BeginFeature: *PageSize A4" or similar, and "%%EndFeature",
167 * but that would require us to have a way of getting the name of
168 * the page size given its dimensions.
169 */
2bf6e538 170 ps_token(fp, &cc, "/setpagedevice where {\n");
171 ps_token(fp, &cc, " pop 2 dict dup /PageSize [%g %g] put setpagedevice\n",
172 doc->paper_width / FUNITS_PER_PT,
173 doc->paper_height / FUNITS_PER_PT);
174 ps_token(fp, &cc, "} if\n");
a10f193f 175
7d7f8de9 176 ps_token(fp, &cc, "[/PageMode/UseOutlines/DOCVIEW m\n");
f8194b21 177 noe = doc->n_outline_elements;
178 for (oe = doc->outline_elements; noe; oe++, noe--) {
179 char *title;
180 int titlelen, count, i;
181
182 title = pdf_outline_convert(oe->pdata->outline_title, &titlelen);
66f70c4f 183 if (oe->level == 0) {
7d7f8de9 184 ps_token(fp, &cc, "[/Title");
2bf6e538 185 ps_string_len(fp, &cc, title, titlelen);
7d7f8de9 186 ps_token(fp, &cc, "/DOCINFO m\n");
66f70c4f 187 }
f8194b21 188
189 count = 0;
190 for (i = 1; i < noe && oe[i].level > oe->level; i++)
191 if (oe[i].level == oe->level + 1)
192 count++;
193 if (oe->level > 0) count = -count;
194
2bf6e538 195 ps_string_len(fp, &cc, title, titlelen);
f8194b21 196 sfree(title);
7d7f8de9 197 ps_token(fp, &cc, "%s %d o\n",
f8194b21 198 (char *)oe->pdata->first->page->spare, count);
199 }
3f167769 200
44407fea 201 for (fe = doc->fonts->head; fe; fe = fe->next) {
b0f1f943 202 /* XXX This may request the same font multiple times. */
3e2dd889 203 if (fe->font->info->fontfile) {
44407fea 204 fprintf(fp, "%%%%BeginResource: font %s\n", fe->font->info->name);
babfe3e2 205 if (fe->font->info->filetype == TYPE1)
206 pf_writeps(fe->font->info, fp);
207 else
208 sfnt_writeps(fe->font->info, fp);
44407fea 209 fprintf(fp, "%%%%EndResource\n");
210 } else {
211 fprintf(fp, "%%%%IncludeResource: font %s\n",
212 fe->font->info->name);
213 }
214 }
09358aa7 215
43341922 216 /*
32ca74bb 217 * Re-encode the fonts.
43341922 218 */
219 font_index = 0;
220 for (fe = doc->fonts->head; fe; fe = fe->next) {
221 char fname[40];
222 int i;
223
224 sprintf(fname, "f%d", font_index++);
225 fe->name = dupstr(fname);
226
2bf6e538 227 ps_token(fp, &cc, "/%s findfont dup length dict begin\n",
ba0fe3ec 228 fe->font->info->name);
2bf6e538 229 ps_token(fp, &cc, "{1 index /FID ne {def} {pop pop} ifelse} forall\n");
230 ps_token(fp, &cc, "/Encoding [\n");
43341922 231 for (i = 0; i < 256; i++)
d5bc1c48 232 ps_token(fp, &cc, "/%s", glyph_extern(fe->vector[i]));
2bf6e538 233 ps_token(fp, &cc, "] def\n");
234 ps_token(fp, &cc, "currentdict end\n");
235 ps_token(fp, &cc, "/fontname-%s exch definefont /%s exch def\n",
236 fe->name, fe->name);
43341922 237 }
238 fprintf(fp, "%%%%EndSetup\n");
239
240 /*
23765aeb 241 * Output the text and graphics.
43341922 242 */
243 pageno = 0;
244 for (page = doc->pages; page; page = page->next) {
7c8c4239 245 text_fragment *frag, *frag_end;
23765aeb 246 rect *r;
3f167769 247 xref *xr;
3e32e06c 248 font_encoding *fe;
249 int fs;
43341922 250
251 pageno++;
252 fprintf(fp, "%%%%Page: %d %d\n", pageno, pageno);
2bf6e538 253 cc = 0;
254 ps_token(fp, &cc, "save %s p\n", (char *)page->spare);
3f167769 255
256 for (xr = page->first_xref; xr; xr = xr->next) {
2bf6e538 257 ps_token(fp, &cc, "[%g %g %g %g]",
3f167769 258 xr->lx/FUNITS_PER_PT, xr->by/FUNITS_PER_PT,
259 xr->rx/FUNITS_PER_PT, xr->ty/FUNITS_PER_PT);
260 if (xr->dest.type == PAGE) {
2bf6e538 261 ps_token(fp, &cc, "%s x\n", (char *)xr->dest.page->spare);
3f167769 262 } else {
2bf6e538 263 ps_string(fp, &cc, xr->dest.url);
264 ps_token(fp, &cc, "u\n");
138d7ffb 265 }
266 }
138d7ffb 267
23765aeb 268 for (r = page->first_rect; r; r = r->next) {
2bf6e538 269 ps_token(fp, &cc, "%g %g %g %g r\n",
17c71b41 270 r->x / FUNITS_PER_PT, r->y / FUNITS_PER_PT,
7b980ef7 271 r->w / FUNITS_PER_PT, r->h / FUNITS_PER_PT);
23765aeb 272 }
273
7c8c4239 274 frag = page->first_text;
3e32e06c 275 fe = NULL;
276 fs = -1;
7c8c4239 277 while (frag) {
7c8c4239 278 /*
279 * Collect all the adjacent text fragments with the
280 * same y-coordinate.
281 */
282 for (frag_end = frag;
283 frag_end && frag_end->y == frag->y;
284 frag_end = frag_end->next);
285
2bf6e538 286 ps_token(fp, &cc, "%g[", frag->y / FUNITS_PER_PT);
7c8c4239 287
7c8c4239 288 while (frag && frag != frag_end) {
289
290 if (frag->fe != fe || frag->fontsize != fs)
2bf6e538 291 ps_token(fp, &cc, "[%s %d]",
292 frag->fe->name, frag->fontsize);
7c8c4239 293 fe = frag->fe;
294 fs = frag->fontsize;
295
2bf6e538 296 ps_token(fp, &cc, "%g", frag->x/FUNITS_PER_PT);
297 ps_string(fp, &cc, frag->text);
43341922 298
7c8c4239 299 frag = frag->next;
43341922 300 }
301
2bf6e538 302 ps_token(fp, &cc, "]t\n");
43341922 303 }
304
2bf6e538 305 ps_token(fp, &cc, "restore showpage\n");
43341922 306 }
307
308 fprintf(fp, "%%%%EOF\n");
309
0041ffdb 310 if (fp != stdout)
311 fclose(fp);
43341922 312
313 sfree(filename);
314}
09358aa7 315
2bf6e538 316static void ps_comment(FILE *fp, char const *leader, word *words) {
317 int cc = 0;
318
319 cc += fprintf(fp, "%s", leader);
09358aa7 320
321 for (; words; words = words->next) {
322 char *text;
323 int type;
324
325 switch (words->type) {
326 case word_HyperLink:
327 case word_HyperEnd:
328 case word_UpperXref:
329 case word_LowerXref:
330 case word_XrefEnd:
331 case word_IndexRef:
332 continue;
333 }
334
335 type = removeattr(words->type);
336
337 switch (type) {
338 case word_Normal:
e4ea58f8 339 text = utoa_dup(words->text, CS_ASCII);
09358aa7 340 break;
341 case word_WhiteSpace:
342 text = dupstr(" ");
343 break;
344 case word_Quote:
345 text = dupstr("'");
346 break;
347 }
348
2bf6e538 349 if (cc + strlen(text) > PS_MAXWIDTH)
350 text[PS_MAXWIDTH - cc] = 0;
351 cc += fprintf(fp, "%s", text);
09358aa7 352 sfree(text);
353 }
354
355 fprintf(fp, "\n");
356}
3f167769 357
c358bf5b 358void ps_token(FILE *fp, int *cc, char const *fmt, ...) {
2bf6e538 359 va_list ap;
360
361 va_start(ap, fmt);
362 if (*cc >= PS_WIDTH - 10) {
363 fprintf(fp, "\n");
364 *cc = 0;
365 }
366 *cc += vfprintf(fp, fmt, ap);
367 /* Assume that \n only occurs at the end of a string */
368 if (fmt[strlen(fmt) - 1] == '\n')
369 *cc = 0;
370}
371
372static void ps_string_len(FILE *fp, int *cc, char const *str, int len) {
3f167769 373 char const *c;
f8194b21 374 int score = 0;
375
376 for (c = str; c < str+len; c++) {
377 if (*c < ' ' || *c > '~')
378 score += 2;
379 else if (*c == '(' || *c == ')' || *c == '\\')
380 score += 0;
381 else
382 score -= 1;
383 }
384 if (score > 0) {
2bf6e538 385 ps_token(fp, cc, "<");
f8194b21 386 for (c = str; c < str+len; c++) {
2bf6e538 387 ps_token(fp, cc, "%02X", 0xFF & (int)*c);
d4319ca3 388 }
2bf6e538 389 ps_token(fp, cc, ">");
f8194b21 390 } else {
2bf6e538 391 *cc += fprintf(fp, "(");
f8194b21 392 for (c = str; c < str+len; c++) {
2bf6e538 393 if (*cc >= PS_WIDTH - 4) {
394 fprintf(fp, "\\\n");
395 *cc = 0;
396 }
f8194b21 397 if (*c < ' ' || *c > '~') {
2bf6e538 398 *cc += fprintf(fp, "\\%03o", 0xFF & (int)*c);
f8194b21 399 } else {
2bf6e538 400 if (*c == '(' || *c == ')' || *c == '\\') {
f8194b21 401 fputc('\\', fp);
2bf6e538 402 (*cc)++;
403 }
f8194b21 404 fputc(*c, fp);
2bf6e538 405 (*cc)++;
f8194b21 406 }
407 }
2bf6e538 408 *cc += fprintf(fp, ")");
3f167769 409 }
f8194b21 410}
411
2bf6e538 412static void ps_string(FILE *fp, int *cc, char const *str) {
413 ps_string_len(fp, cc, str, strlen(str));
3f167769 414}