Add support for compressed PDF streams, using Simon's new deflate library.
[sgt/halibut] / misc.c
1 /*
2 * misc.c: miscellaneous useful items
3 */
4
5 #include <stdarg.h>
6 #include "halibut.h"
7
8 char *adv(char *s) {
9 return s + 1 + strlen(s);
10 }
11
12 struct stackTag {
13 void **data;
14 int sp;
15 int size;
16 };
17
18 stack stk_new(void) {
19 stack s;
20
21 s = snew(struct stackTag);
22 s->sp = 0;
23 s->size = 0;
24 s->data = NULL;
25
26 return s;
27 }
28
29 void stk_free(stack s) {
30 sfree(s->data);
31 sfree(s);
32 }
33
34 void stk_push(stack s, void *item) {
35 if (s->size <= s->sp) {
36 s->size = s->sp + 32;
37 s->data = sresize(s->data, s->size, void *);
38 }
39 s->data[s->sp++] = item;
40 }
41
42 void *stk_pop(stack s) {
43 if (s->sp > 0)
44 return s->data[--s->sp];
45 else
46 return NULL;
47 }
48
49 void *stk_top(stack s) {
50 if (s->sp > 0)
51 return s->data[s->sp-1];
52 else
53 return NULL;
54 }
55
56 /*
57 * Small routines to amalgamate a string from an input source.
58 */
59 const rdstring empty_rdstring = {0, 0, NULL};
60 const rdstringc empty_rdstringc = {0, 0, NULL};
61
62 void rdadd(rdstring *rs, wchar_t c) {
63 if (rs->pos >= rs->size-1) {
64 rs->size = rs->pos + 128;
65 rs->text = sresize(rs->text, rs->size, wchar_t);
66 }
67 rs->text[rs->pos++] = c;
68 rs->text[rs->pos] = 0;
69 }
70 void rdadds(rdstring *rs, wchar_t const *p) {
71 int len = ustrlen(p);
72 if (rs->pos >= rs->size - len) {
73 rs->size = rs->pos + len + 128;
74 rs->text = sresize(rs->text, rs->size, wchar_t);
75 }
76 ustrcpy(rs->text + rs->pos, p);
77 rs->pos += len;
78 }
79 wchar_t *rdtrim(rdstring *rs) {
80 rs->text = sresize(rs->text, rs->pos + 1, wchar_t);
81 return rs->text;
82 }
83
84 void rdaddc(rdstringc *rs, char c) {
85 if (rs->pos >= rs->size-1) {
86 rs->size = rs->pos + 128;
87 rs->text = sresize(rs->text, rs->size, char);
88 }
89 rs->text[rs->pos++] = c;
90 rs->text[rs->pos] = 0;
91 }
92 void rdaddsc(rdstringc *rs, char const *p) {
93 rdaddsn(rs, p, strlen(p));
94 }
95 void rdaddsn(rdstringc *rs, char const *p, int len) {
96 if (rs->pos >= rs->size - len) {
97 rs->size = rs->pos + len + 128;
98 rs->text = sresize(rs->text, rs->size, char);
99 }
100 memcpy(rs->text + rs->pos, p, len);
101 rs->pos += len;
102 rs->text[rs->pos] = 0;
103 }
104 char *rdtrimc(rdstringc *rs) {
105 rs->text = sresize(rs->text, rs->pos + 1, char);
106 return rs->text;
107 }
108
109 static int compare_wordlists_literally(word *a, word *b) {
110 int t;
111 while (a && b) {
112 if (a->type != b->type)
113 return (a->type < b->type ? -1 : +1); /* FIXME? */
114 t = a->type;
115 if ((t != word_Normal && t != word_Code &&
116 t != word_WeakCode && t != word_Emph) ||
117 a->alt || b->alt) {
118 int c;
119 if (a->text && b->text) {
120 c = ustricmp(a->text, b->text);
121 if (c)
122 return c;
123 }
124 c = compare_wordlists_literally(a->alt, b->alt);
125 if (c)
126 return c;
127 a = a->next;
128 b = b->next;
129 } else {
130 wchar_t *ap = a->text, *bp = b->text;
131 while (*ap && *bp) {
132 wchar_t ac = *ap, bc = *bp;
133 if (ac != bc)
134 return (ac < bc ? -1 : +1);
135 if (!*++ap && a->next && a->next->type == t && !a->next->alt)
136 a = a->next, ap = a->text;
137 if (!*++bp && b->next && b->next->type == t && !b->next->alt)
138 b = b->next, bp = b->text;
139 }
140 if (*ap || *bp)
141 return (*ap ? +1 : -1);
142 a = a->next;
143 b = b->next;
144 }
145 }
146
147 if (a || b)
148 return (a ? +1 : -1);
149 else
150 return 0;
151 }
152
153 int compare_wordlists(word *a, word *b) {
154 /*
155 * First we compare only the alphabetic content of the word
156 * lists, with case not a factor. If that comes out equal,
157 * _then_ we compare the word lists literally.
158 */
159 struct {
160 word *w;
161 int i;
162 wchar_t c;
163 } pos[2];
164
165 pos[0].w = a;
166 pos[1].w = b;
167 pos[0].i = pos[1].i = 0;
168
169 while (1) {
170 /*
171 * Find the next alphabetic character in each word list.
172 */
173 int k;
174
175 for (k = 0; k < 2; k++) {
176 /*
177 * Advance until we hit either an alphabetic character
178 * or the end of the word list.
179 */
180 while (1) {
181 if (!pos[k].w) {
182 /* End of word list. */
183 pos[k].c = 0;
184 break;
185 } else if (!pos[k].w->text || !pos[k].w->text[pos[k].i]) {
186 /* No characters remaining in this word; move on. */
187 pos[k].w = pos[k].w->next;
188 pos[k].i = 0;
189 } else if (!uisalpha(pos[k].w->text[pos[k].i])) {
190 /* This character isn't alphabetic; move on. */
191 pos[k].i++;
192 } else {
193 /* We have an alphabetic! Lowercase it and continue. */
194 pos[k].c = utolower(pos[k].w->text[pos[k].i]);
195 break;
196 }
197 }
198 }
199
200 #ifdef HAS_WCSCOLL
201 {
202 wchar_t a[2], b[2];
203 int ret;
204
205 a[0] = pos[0].c;
206 b[0] = pos[1].c;
207 a[1] = b[1] = L'\0';
208
209 ret = wcscoll(a, b);
210 if (ret)
211 return ret;
212 }
213 #else
214 if (pos[0].c < pos[1].c)
215 return -1;
216 else if (pos[0].c > pos[1].c)
217 return +1;
218 #endif
219
220 if (!pos[0].c)
221 break; /* they're equal */
222
223 pos[0].i++;
224 pos[1].i++;
225 }
226
227 /*
228 * If we reach here, the strings were alphabetically equal, so
229 * compare in more detail.
230 */
231 return compare_wordlists_literally(a, b);
232 }
233
234 void mark_attr_ends(word *words)
235 {
236 word *w, *wp;
237
238 wp = NULL;
239 for (w = words; w; w = w->next) {
240 if (isattr(w->type)) {
241 int before = (wp && isattr(wp->type) &&
242 sameattr(wp->type, w->type));
243 int after = (w->next && isattr(w->next->type) &&
244 sameattr(w->next->type, w->type));
245 w->aux |= (before ?
246 (after ? attr_Always : attr_Last) :
247 (after ? attr_First : attr_Only));
248 }
249 wp = w;
250 }
251 }
252
253 /*
254 * This function implements the optimal paragraph wrapping
255 * algorithm, pretty much as used in TeX. A cost function is
256 * defined for each line of the wrapped paragraph (typically some
257 * convex function of the difference between the line's length and
258 * its desired length), and a dynamic programming approach is used
259 * to optimise globally across all possible layouts of the
260 * paragraph to find the one with the minimum total cost.
261 *
262 * The function as implemented here gives a choice of two options
263 * for the cost function:
264 *
265 * - If `natural_space' is zero, then the algorithm attempts to
266 * make each line the maximum possible width (either `width' or
267 * `subsequentwidth' depending on whether it's the first line of
268 * the paragraph or not), and the cost function is simply the
269 * square of the unused space at the end of each line. This is a
270 * simple mechanism suitable for use in fixed-pitch environments
271 * such as plain text displayed on a terminal.
272 *
273 * - However, if `natural_space' is positive, the algorithm
274 * assumes the medium is fully graphical and that the width of
275 * space characters can be adjusted finely, and it attempts to
276 * make each _space character_ the width given in
277 * `natural_space'. (The provided width function should return
278 * the _minimum_ acceptable width of a space character in this
279 * case.) Therefore, the cost function for a line is dependent
280 * on the number of spaces on that line as well as the amount by
281 * which the line width differs from the optimum.
282 */
283 wrappedline *wrap_para(word *text, int width, int subsequentwidth,
284 int (*widthfn)(void *, word *), void *ctx,
285 int natural_space) {
286 wrappedline *head = NULL, **ptr = &head;
287 int nwords, wordsize;
288 struct wrapword {
289 word *begin, *end;
290 int width;
291 int spacewidth;
292 int cost;
293 int nwords;
294 } *wrapwords;
295 int i, j, n;
296
297 /*
298 * Break the line up into wrappable components.
299 */
300 nwords = wordsize = 0;
301 wrapwords = NULL;
302 while (text) {
303 if (nwords >= wordsize) {
304 wordsize = nwords + 64;
305 wrapwords = srealloc(wrapwords, wordsize * sizeof(*wrapwords));
306 }
307 wrapwords[nwords].width = 0;
308 wrapwords[nwords].begin = text;
309 while (text) {
310 wrapwords[nwords].width += widthfn(ctx, text);
311 wrapwords[nwords].end = text->next;
312 if (text->next && (text->next->type == word_WhiteSpace ||
313 text->next->type == word_EmphSpace ||
314 text->breaks))
315 break;
316 text = text->next;
317 }
318 if (text && text->next && (text->next->type == word_WhiteSpace ||
319 text->next->type == word_EmphSpace)) {
320 wrapwords[nwords].spacewidth = widthfn(ctx, text->next);
321 text = text->next;
322 } else {
323 wrapwords[nwords].spacewidth = 0;
324 }
325 nwords++;
326 if (text)
327 text = text->next;
328 }
329
330 /*
331 * Perform the dynamic wrapping algorithm: work backwards from
332 * nwords-1, determining the optimal wrapping for each terminal
333 * subsequence of the paragraph.
334 */
335 for (i = nwords; i-- ;) {
336 int best = -1;
337 int bestcost = 0;
338 int cost;
339 int linelen = 0, spacewidth = 0, minspacewidth = 0;
340 int nspaces;
341 int thiswidth = (i == 0 ? width : subsequentwidth);
342
343 j = 0;
344 nspaces = 0;
345 while (i+j < nwords) {
346 /*
347 * See what happens if we put j+1 words on this line.
348 */
349 if (spacewidth) {
350 nspaces++;
351 minspacewidth = spacewidth;
352 }
353 linelen += spacewidth + wrapwords[i+j].width;
354 spacewidth = wrapwords[i+j].spacewidth;
355 j++;
356 if (linelen > thiswidth) {
357 /*
358 * If we're over the width limit, abandon ship,
359 * _unless_ there is no best-effort yet (which will
360 * only happen if the first word is too long all by
361 * itself).
362 */
363 if (best > 0)
364 break;
365 }
366
367 /*
368 * Compute the cost of this line. The method of doing
369 * this differs hugely depending on whether
370 * natural_space is nonzero or not.
371 */
372 if (natural_space) {
373 if (!nspaces && linelen > thiswidth) {
374 /*
375 * Special case: if there are no spaces at all
376 * on the line because one single word is too
377 * long for its line, cost is zero because
378 * there's nothing we can do about it anyway.
379 */
380 cost = 0;
381 } else {
382 int shortfall = thiswidth - linelen;
383 int spaceextra = shortfall / (nspaces ? nspaces : 1);
384 int spaceshortfall = natural_space -
385 (minspacewidth + spaceextra);
386
387 if (i+j == nwords && spaceshortfall < 0) {
388 /*
389 * Special case: on the very last line of
390 * the paragraph, we don't score penalty
391 * points for having to _stretch_ the line,
392 * since we won't stretch it anyway.
393 * However, we score penalties as normal
394 * for having to squeeze it.
395 */
396 cost = 0;
397 } else {
398 /*
399 * Squaring this number is tricky since
400 * it's liable to be quite big. Let's
401 * divide it through by 256.
402 */
403 int x = spaceshortfall >> 8;
404 int xf = spaceshortfall & 0xFF;
405
406 /*
407 * Not counting strange variable-fixed-
408 * point oddities, we are computing
409 *
410 * (x+xf)^2 = x^2 + 2*x*xf + xf*xf
411 *
412 * except that _our_ xf is 256 times the
413 * one listed there.
414 */
415
416 cost = x * x;
417 cost += (2 * x * xf) >> 8;
418 }
419 }
420 } else {
421 if (i+j == nwords) {
422 /*
423 * Special case: if we're at the very end of the
424 * paragraph, we don't score penalty points for the
425 * white space left on the line.
426 */
427 cost = 0;
428 } else {
429 cost = (thiswidth-linelen) * (thiswidth-linelen);
430 }
431 }
432
433 /*
434 * Add in the cost of wrapping all lines after this
435 * point too.
436 */
437 if (i+j < nwords)
438 cost += wrapwords[i+j].cost;
439
440 /*
441 * We compare bestcost >= cost, not bestcost > cost,
442 * because in cases where the costs are identical we
443 * want to try to look like the greedy algorithm,
444 * because readers are likely to have spent a lot of
445 * time looking at greedy-wrapped paragraphs and
446 * there's no point violating the Principle of Least
447 * Surprise if it doesn't actually gain anything.
448 */
449 if (best < 0 || bestcost >= cost) {
450 bestcost = cost;
451 best = j;
452 }
453 }
454 /*
455 * Now we know the optimal answer for this terminal
456 * subsequence, so put it in wrapwords.
457 */
458 wrapwords[i].cost = bestcost;
459 wrapwords[i].nwords = best;
460 }
461
462 /*
463 * We've wrapped the paragraph. Now build the output
464 * `wrappedline' list.
465 */
466 i = 0;
467 while (i < nwords) {
468 wrappedline *w = snew(wrappedline);
469 *ptr = w;
470 ptr = &w->next;
471 w->next = NULL;
472
473 n = wrapwords[i].nwords;
474 w->begin = wrapwords[i].begin;
475 w->end = wrapwords[i+n-1].end;
476
477 /*
478 * Count along the words to find nspaces and shortfall.
479 */
480 w->nspaces = 0;
481 w->shortfall = width;
482 for (j = 0; j < n; j++) {
483 w->shortfall -= wrapwords[i+j].width;
484 if (j < n-1 && wrapwords[i+j].spacewidth) {
485 w->nspaces++;
486 w->shortfall -= wrapwords[i+j].spacewidth;
487 }
488 }
489 i += n;
490 }
491
492 sfree(wrapwords);
493
494 return head;
495 }
496
497 void wrap_free(wrappedline *w) {
498 while (w) {
499 wrappedline *t = w->next;
500 sfree(w);
501 w = t;
502 }
503 }
504
505 void cmdline_cfg_add(paragraph *cfg, char *string)
506 {
507 wchar_t *ustring;
508 int upos, ulen, pos, len;
509
510 ulen = 0;
511 while (cfg->keyword[ulen])
512 ulen += 1 + ustrlen(cfg->keyword+ulen);
513 len = 0;
514 while (cfg->origkeyword[len])
515 len += 1 + strlen(cfg->origkeyword+len);
516
517 ustring = ufroma_locale_dup(string);
518
519 upos = ulen;
520 ulen += 2 + ustrlen(ustring);
521 cfg->keyword = sresize(cfg->keyword, ulen, wchar_t);
522 ustrcpy(cfg->keyword+upos, ustring);
523 cfg->keyword[ulen-1] = L'\0';
524
525 pos = len;
526 len += 2 + strlen(string);
527 cfg->origkeyword = sresize(cfg->origkeyword, len, char);
528 strcpy(cfg->origkeyword+pos, string);
529 cfg->origkeyword[len-1] = '\0';
530
531 sfree(ustring);
532 }
533
534 paragraph *cmdline_cfg_new(void)
535 {
536 paragraph *p;
537
538 p = snew(paragraph);
539 memset(p, 0, sizeof(*p));
540 p->type = para_Config;
541 p->next = NULL;
542 p->fpos.filename = "<command line>";
543 p->fpos.line = p->fpos.col = -1;
544 p->keyword = ustrdup(L"\0");
545 p->origkeyword = dupstr("\0");
546
547 return p;
548 }
549
550 paragraph *cmdline_cfg_simple(char *string, ...)
551 {
552 va_list ap;
553 char *s;
554 paragraph *p;
555
556 p = cmdline_cfg_new();
557 cmdline_cfg_add(p, string);
558
559 va_start(ap, string);
560 while ((s = va_arg(ap, char *)) != NULL)
561 cmdline_cfg_add(p, s);
562 va_end(ap);
563
564 return p;
565 }