b9f465dbfcb78351f2adfb35b6ced889c7ae353d
[pspp-builds.git] / src / output.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18    02110-1301, USA. */
19
20 #include <config.h>
21 #include "output.h"
22 #include "error.h"
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <ctype.h>
27 #include "alloc.h"
28 #include "devind.h"
29 #include "error.h"
30 #include "filename.h"
31 #include "htmlP.h"
32 #include "lexer.h"
33 #include "misc.h"
34 #include "settings.h"
35 #include "str.h"
36
37 /* FIXME? Should the output configuration format be changed to
38    drivername:classname:devicetype:options, where devicetype is zero
39    or more of screen, printer, listing? */
40
41 /* FIXME: Have the reentrancy problems been solved? */
42
43 /* Where the output driver name came from. */
44 enum
45   {
46     OUTP_S_COMMAND_LINE,        /* Specified by the user. */
47     OUTP_S_INIT_FILE            /* `default' or the init file. */
48   };
49
50 /* Names the output drivers to be used. */
51 struct outp_names
52   {
53     char *name;                 /* Name of the output driver. */
54     int source;                 /* OUTP_S_* */
55     struct outp_names *next, *prev;
56   };
57
58 /* Defines an init file macro. */
59 struct outp_defn
60   {
61     char *key;
62     char *value;
63     struct outp_defn *next, *prev;
64   };
65
66 static struct outp_defn *outp_macros;
67 static struct outp_names *outp_configure_vec;
68
69 struct outp_driver_class_list *outp_class_list;
70 struct outp_driver *outp_driver_list;
71
72 char *outp_title;
73 char *outp_subtitle;
74
75 /* A set of OUTP_DEV_* bits indicating the devices that are
76    disabled. */
77 static int disabled_devices;
78
79 static void destroy_driver (struct outp_driver *);
80 static void configure_driver (char *);
81
82 #if GLOBAL_DEBUGGING
83 /* This mechanism attempts to catch reentrant use of outp_driver_list. */
84 static int iterating_driver_list;
85
86 #define reentrancy() msg (FE, _("Attempt to iterate driver list reentrantly."))
87 #endif
88
89 /* Add a class to the class list. */
90 static void
91 add_class (struct outp_class *class)
92 {
93   struct outp_driver_class_list *new_list = xmalloc (sizeof *new_list);
94
95   new_list->class = class;
96   new_list->ref_count = 0;
97
98   if (!outp_class_list)
99     {
100       outp_class_list = new_list;
101       new_list->next = NULL;
102     }
103   else
104     {
105       new_list->next = outp_class_list;
106       outp_class_list = new_list;
107     }
108 }
109
110 /* Finds the outp_names in outp_configure_vec with name between BP and
111    EP exclusive. */
112 static struct outp_names *
113 search_names (char *bp, char *ep)
114 {
115   struct outp_names *n;
116
117   for (n = outp_configure_vec; n; n = n->next)
118     if ((int) strlen (n->name) == ep - bp && !memcmp (n->name, bp, ep - bp))
119       return n;
120   return NULL;
121 }
122
123 /* Deletes outp_names NAME from outp_configure_vec. */
124 static void
125 delete_name (struct outp_names * n)
126 {
127   free (n->name);
128   if (n->prev)
129     n->prev->next = n->next;
130   if (n->next)
131     n->next->prev = n->prev;
132   if (n == outp_configure_vec)
133     outp_configure_vec = n->next;
134   free (n);
135 }
136
137 /* Adds the name between BP and EP exclusive to list
138    outp_configure_vec with source SOURCE. */
139 static void
140 add_name (char *bp, char *ep, int source)
141 {
142   struct outp_names *n = xmalloc (sizeof *n);
143   n->name = xmalloc (ep - bp + 1);
144   memcpy (n->name, bp, ep - bp);
145   n->name[ep - bp] = 0;
146   n->source = source;
147   n->next = outp_configure_vec;
148   n->prev = NULL;
149   if (outp_configure_vec)
150     outp_configure_vec->prev = n;
151   outp_configure_vec = n;
152 }
153
154 /* Checks that outp_configure_vec is empty, bitches & clears it if it
155    isn't. */
156 static void
157 check_configure_vec (void)
158 {
159   struct outp_names *n;
160
161   for (n = outp_configure_vec; n; n = n->next)
162     if (n->source == OUTP_S_COMMAND_LINE)
163       msg (ME, _("Unknown output driver `%s'."), n->name);
164     else
165       msg (IE, _("Output driver `%s' referenced but never defined."), n->name);
166   outp_configure_clear ();
167 }
168
169 /* Searches outp_configure_vec for the name between BP and EP
170    exclusive.  If found, it is deleted, then replaced by the names
171    given in EP+1, if any. */
172 static void
173 expand_name (char *bp, char *ep)
174 {
175   struct outp_names *n = search_names (bp, ep);
176   if (!n)
177     return;
178   delete_name (n);
179
180   bp = ep + 1;
181   for (;;)
182     {
183       while (isspace ((unsigned char) *bp))
184         bp++;
185       ep = bp;
186       while (*ep && !isspace ((unsigned char) *ep))
187         ep++;
188       if (bp == ep)
189         return;
190       if (!search_names (bp, ep))
191         add_name (bp, ep, OUTP_S_INIT_FILE);
192       bp = ep;
193     }
194 }
195
196 /* Looks for a macro with key KEY, and returns the corresponding value
197    if found, or NULL if not. */
198 static const char *
199 find_defn_value (const char *key)
200 {
201   static char buf[INT_DIGITS + 1];
202   struct outp_defn *d;
203
204   for (d = outp_macros; d; d = d->next)
205     if (!strcmp (key, d->key))
206       return d->value;
207   if (!strcmp (key, "viewwidth"))
208     {
209       sprintf (buf, "%d", get_viewwidth());
210       return buf;
211     }
212   else if (!strcmp (key, "viewlength"))
213     {
214       sprintf (buf, "%d", get_viewlength());
215       return buf;
216     }
217   else
218     return getenv (key);
219 }
220
221 /* Initializes global variables. */
222 int
223 outp_init (void)
224 {
225   extern struct outp_class ascii_class;
226 #if !NO_POSTSCRIPT
227   extern struct outp_class postscript_class;
228   extern struct outp_class epsf_class;
229 #endif
230   extern struct outp_class html_class;
231   extern struct outp_class devind_class;
232
233   char def[] = "default";
234
235 #if !NO_HTML
236   add_class (&html_class);
237 #endif
238 #if !NO_POSTSCRIPT
239   add_class (&epsf_class);
240   add_class (&postscript_class);
241 #endif
242   add_class (&devind_class);
243   add_class (&ascii_class);
244
245   add_name (def, &def[strlen (def)], OUTP_S_INIT_FILE);
246
247   return 1;
248 }
249
250 /* Deletes all the output macros. */
251 static void
252 delete_macros (void)
253 {
254   struct outp_defn *d, *next;
255
256   for (d = outp_macros; d; d = next)
257     {
258       next = d->next;
259       free (d->key);
260       free (d->value);
261       free (d);
262     }
263 }
264
265 /* Reads the initialization file; initializes outp_driver_list. */
266 int
267 outp_read_devices (void)
268 {
269   int result = 0;
270
271   char *init_fn;
272
273   FILE *f = NULL;
274   struct string line;
275   struct file_locator where;
276
277 #if GLOBAL_DEBUGGING
278   if (iterating_driver_list)
279     reentrancy ();
280 #endif
281
282   init_fn = fn_search_path (fn_getenv_default ("STAT_OUTPUT_INIT_FILE",
283                                                "devices"),
284                             fn_getenv_default ("STAT_OUTPUT_INIT_PATH",
285                                                config_path),
286                             NULL);
287   where.filename = init_fn;
288   where.line_number = 0;
289   err_push_file_locator (&where);
290
291   ds_init (&line, 128);
292
293   if (init_fn == NULL)
294     {
295       msg (IE, _("Cannot find output initialization file.  "
296                  "Use `-vvvv' to view search path."));
297       goto exit;
298     }
299
300   msg (VM (1), _("%s: Opening device description file..."), init_fn);
301   f = fopen (init_fn, "r");
302   if (f == NULL)
303     {
304       msg (IE, _("Opening %s: %s."), init_fn, strerror (errno));
305       goto exit;
306     }
307
308   for (;;)
309     {
310       char *cp;
311
312       if (!ds_get_config_line (f, &line, &where))
313         {
314           if (ferror (f))
315             msg (ME, _("Reading %s: %s."), init_fn, strerror (errno));
316           break;
317         }
318       for (cp = ds_c_str (&line); isspace ((unsigned char) *cp); cp++);
319       if (!strncmp ("define", cp, 6) && isspace ((unsigned char) cp[6]))
320         outp_configure_macro (&cp[7]);
321       else if (*cp)
322         {
323           char *ep;
324           for (ep = cp; *ep && *ep != ':' && *ep != '='; ep++);
325           if (*ep == '=')
326             expand_name (cp, ep);
327           else if (*ep == ':')
328             {
329               struct outp_names *n = search_names (cp, ep);
330               if (n)
331                 {
332                   configure_driver (cp);
333                   delete_name (n);
334                 }
335             }
336           else
337             msg (IS, _("Syntax error."));
338         }
339     }
340   result = 1;
341
342   check_configure_vec ();
343
344 exit:
345   err_pop_file_locator (&where);
346   if (f && -1 == fclose (f))
347     msg (MW, _("Closing %s: %s."), init_fn, strerror (errno));
348   free (init_fn);
349   ds_destroy (&line);
350   delete_macros ();
351   if (outp_driver_list == NULL)
352     msg (MW, _("No output drivers are active."));
353
354   if (result)
355     msg (VM (2), _("Device definition file read successfully."));
356   else
357     msg (VM (1), _("Error reading device definition file."));
358   return result;
359 }
360
361 /* Clear the list of drivers to configure. */
362 void
363 outp_configure_clear (void)
364 {
365   struct outp_names *n, *next;
366
367   for (n = outp_configure_vec; n; n = next)
368     {
369       next = n->next;
370       free (n->name);
371       free (n);
372     }
373   outp_configure_vec = NULL;
374 }
375
376 /* Adds the name BP to the list of drivers to configure into
377    outp_driver_list. */
378 void
379 outp_configure_add (char *bp)
380 {
381   char *ep = &bp[strlen (bp)];
382   if (!search_names (bp, ep))
383     add_name (bp, ep, OUTP_S_COMMAND_LINE);
384 }
385
386 /* Defines one configuration macro based on the text in BP, which
387    should be of the form `KEY=VALUE'. */
388 void
389 outp_configure_macro (char *bp)
390 {
391   struct outp_defn *d;
392   char *ep;
393
394   while (isspace ((unsigned char) *bp))
395     bp++;
396   ep = bp;
397   while (*ep && !isspace ((unsigned char) *ep) && *ep != '=')
398     ep++;
399
400   d = xmalloc (sizeof *d);
401   d->key = xmalloc (ep - bp + 1);
402   memcpy (d->key, bp, ep - bp);
403   d->key[ep - bp] = 0;
404
405   /* Earlier definitions for a particular KEY override later ones. */
406   if (find_defn_value (d->key))
407     {
408       free (d->key);
409       free (d);
410       return;
411     }
412   
413   if (*ep == '=')
414     ep++;
415   while (isspace ((unsigned char) *ep))
416     ep++;
417   d->value = fn_interp_vars (ep, find_defn_value);
418   d->next = outp_macros;
419   d->prev = NULL;
420   if (outp_macros)
421     outp_macros->prev = d;
422   outp_macros = d;
423 }
424
425 /* Destroys all the drivers in driver list *DL and sets *DL to
426    NULL. */
427 static void
428 destroy_list (struct outp_driver ** dl)
429 {
430   struct outp_driver *d, *next;
431
432   for (d = *dl; d; d = next)
433     {
434       destroy_driver (d);
435       next = d->next;
436       free (d);
437     }
438   *dl = NULL;
439 }
440
441 /* Closes all the output drivers. */
442 int
443 outp_done (void)
444 {
445   struct outp_driver_class_list *n = outp_class_list ; 
446 #if GLOBAL_DEBUGGING
447   if (iterating_driver_list)
448     reentrancy ();
449 #endif
450   destroy_list (&outp_driver_list);
451
452   while (n) 
453     {
454       struct outp_driver_class_list *next = n->next;
455       free(n);
456       n = next;
457     }
458   outp_class_list = NULL;
459
460   free (outp_title);
461   outp_title = NULL;
462   
463   free (outp_subtitle);
464   outp_subtitle = NULL;
465
466   return 1;
467 }
468
469 /* Display on stdout a list of all registered driver classes. */
470 void
471 outp_list_classes (void)
472 {
473   int width = get_viewwidth();
474   struct outp_driver_class_list *c;
475
476   printf (_("Driver classes:\n\t"));
477   width -= 8;
478   for (c = outp_class_list; c; c = c->next)
479     {
480       if ((int) strlen (c->class->name) + 1 > width)
481         {
482           printf ("\n\t");
483           width = get_viewwidth() - 8;
484         }
485       else
486         putc (' ', stdout);
487       fputs (c->class->name, stdout);
488     }
489   putc('\n', stdout);
490 }
491
492 static int op_token;            /* `=', 'a', 0. */
493 static struct string op_tokstr;
494 static char *prog;
495
496 /* Parses a token from prog into op_token, op_tokstr.  Sets op_token
497    to '=' on an equals sign, to 'a' on a string or identifier token,
498    or to 0 at end of line.  Returns the new op_token. */
499 static int
500 tokener (void)
501 {
502   if (op_token == 0)
503     {
504       msg (IS, _("Syntax error."));
505       return 0;
506     }
507
508   while (isspace ((unsigned char) *prog))
509     prog++;
510   if (!*prog)
511     {
512       op_token = 0;
513       return 0;
514     }
515
516   if (*prog == '=')
517     op_token = *prog++;
518   else
519     {
520       ds_clear (&op_tokstr);
521
522       if (*prog == '\'' || *prog == '"')
523         {
524           int quote = *prog++;
525
526           while (*prog && *prog != quote)
527             {
528               if (*prog != '\\')
529                 ds_putc (&op_tokstr, *prog++);
530               else
531                 {
532                   int c;
533                   
534                   prog++;
535                   assert ((int) *prog); /* How could a line end in `\'? */
536                   switch (*prog++)
537                     {
538                     case '\'':
539                       c = '\'';
540                       break;
541                     case '"':
542                       c = '"';
543                       break;
544                     case '?':
545                       c = '?';
546                       break;
547                     case '\\':
548                       c = '\\';
549                       break;
550                     case '}':
551                       c = '}';
552                       break;
553                     case 'a':
554                       c = '\a';
555                       break;
556                     case 'b':
557                       c = '\b';
558                       break;
559                     case 'f':
560                       c = '\f';
561                       break;
562                     case 'n':
563                       c = '\n';
564                       break;
565                     case 'r':
566                       c = '\r';
567                       break;
568                     case 't':
569                       c = '\t';
570                       break;
571                     case 'v':
572                       c = '\v';
573                       break;
574                     case '0':
575                     case '1':
576                     case '2':
577                     case '3':
578                     case '4':
579                     case '5':
580                     case '6':
581                     case '7':
582                       {
583                         c = prog[-1] - '0';
584                         while (*prog >= '0' && *prog <= '7')
585                           c = c * 8 + *prog++ - '0';
586                       }
587                       break;
588                     case 'x':
589                     case 'X':
590                       {
591                         c = 0;
592                         while (isxdigit ((unsigned char) *prog))
593                           {
594                             c *= 16;
595                             if (isdigit ((unsigned char) *prog))
596                               c += *prog - '0';
597                             else
598                               c += (tolower ((unsigned char) (*prog))
599                                     - 'a' + 10);
600                             prog++;
601                           }
602                       }
603                       break;
604                     default:
605                       msg (IS, _("Syntax error in string constant."));
606                       continue;
607                     }
608                   ds_putc (&op_tokstr, (unsigned char) c);
609                 }
610             }
611           prog++;
612         }
613       else
614         while (*prog && !isspace ((unsigned char) *prog) && *prog != '=')
615           ds_putc (&op_tokstr, *prog++);
616       op_token = 'a';
617     }
618
619   return 1;
620 }
621
622 /* Applies the user-specified options in string S to output driver D
623    (at configuration time). */
624 static void
625 parse_options (char *s, struct outp_driver * d)
626 {
627   prog = s;
628   op_token = -1;
629
630   ds_init (&op_tokstr, 64);
631   while (tokener ())
632     {
633       char key[65];
634
635       if (op_token != 'a')
636         {
637           msg (IS, _("Syntax error in options."));
638           break;
639         }
640
641       ds_truncate (&op_tokstr, 64);
642       strcpy (key, ds_c_str (&op_tokstr));
643
644       tokener ();
645       if (op_token != '=')
646         {
647           msg (IS, _("Syntax error in options (`=' expected)."));
648           break;
649         }
650
651       tokener ();
652       if (op_token != 'a')
653         {
654           msg (IS, _("Syntax error in options (value expected after `=')."));
655           break;
656         }
657       d->class->option (d, key, &op_tokstr);
658     }
659   ds_destroy (&op_tokstr);
660 }
661
662 /* Find the driver in outp_driver_list with name NAME. */
663 static struct outp_driver *
664 find_driver (char *name)
665 {
666   struct outp_driver *d;
667
668 #if GLOBAL_DEBUGGING
669   if (iterating_driver_list)
670     reentrancy ();
671 #endif
672   for (d = outp_driver_list; d; d = d->next)
673     if (!strcmp (d->name, name))
674       return d;
675   return NULL;
676 }
677
678 /* Tokenize string S into colon-separated fields, removing leading and
679    trailing whitespace on tokens.  Returns a pointer to the
680    null-terminated token, which is formed by setting a NUL character
681    into the string.  After the first call, subsequent calls should set
682    S to NULL.  CP should be consistent across calls.  Returns NULL
683    after all fields have been used up.
684
685    FIXME: Should ignore colons inside double quotes. */
686 static char *
687 colon_tokenize (char *s, char **cp)
688 {
689   char *token;
690   
691   if (!s)
692     {
693       s = *cp;
694       if (*s == 0)
695         return NULL;
696     }
697   token = s += strspn (s, " \t\v\r");
698   *cp = strchr (s, ':');
699   if (*cp == NULL)
700     s = *cp = strchr (s, 0);
701   else
702     s = (*cp)++;
703   while (s > token && strchr (" \t\v\r", s[-1]))
704     s--;
705   *s = 0;
706   return token;
707 }
708
709 /* String S is in format:
710    DRIVERNAME:CLASSNAME:DEVICETYPE:OPTIONS
711    Adds a driver to outp_driver_list pursuant to the specification
712    provided.  */
713 static void
714 configure_driver (char *s)
715 {
716   char *token, *cp;
717   struct outp_driver *d = NULL, *iter;
718   struct outp_driver_class_list *c = NULL;
719
720   s = fn_interp_vars (s, find_defn_value);
721
722   /* Driver name. */
723   token = colon_tokenize (s, &cp);
724   if (!token)
725     {
726       msg (IS, _("Driver name expected."));
727       goto error;
728     }
729
730   d = xmalloc (sizeof *d);
731
732   d->class = NULL;
733   d->name = xstrdup (token);
734   d->driver_open = 0;
735   d->page_open = 0;
736
737   d->next = d->prev = NULL;
738
739   d->device = OUTP_DEV_NONE;
740   
741   d->ext = NULL;
742
743   /* Class name. */
744   token = colon_tokenize (NULL, &cp);
745   if (!token)
746     {
747       msg (IS, _("Class name expected."));
748       goto error;
749     }
750
751   for (c = outp_class_list; c; c = c->next)
752     if (!strcmp (c->class->name, token))
753       break;
754   if (!c)
755     {
756       msg (IS, _("Unknown output driver class `%s'."), token);
757       goto error;
758     }
759   
760   d->class = c->class;
761   if (!c->ref_count && !d->class->open_global (d->class))
762     {
763       msg (IS, _("Can't initialize output driver class `%s'."),
764            d->class->name);
765       goto error;
766     }
767   c->ref_count++;
768   if (!d->class->preopen_driver (d))
769     {
770       msg (IS, _("Can't initialize output driver `%s' of class `%s'."),
771            d->name, d->class->name);
772       goto error;
773     }
774
775   /* Device types. */
776   token = colon_tokenize (NULL, &cp);
777   if (token)
778     {
779       char *sp, *type;
780
781       for (type = strtok_r (token, " \t\r\v", &sp); type;
782            type = strtok_r (NULL, " \t\r\v", &sp))
783         {
784           if (!strcmp (type, "listing"))
785             d->device |= OUTP_DEV_LISTING;
786           else if (!strcmp (type, "screen"))
787             d->device |= OUTP_DEV_SCREEN;
788           else if (!strcmp (type, "printer"))
789             d->device |= OUTP_DEV_PRINTER;
790           else
791             {
792               msg (IS, _("Unknown device type `%s'."), type);
793               goto error;
794             }
795         }
796     }
797   
798   /* Options. */
799   token = colon_tokenize (NULL, &cp);
800   if (token)
801     parse_options (token, d);
802   if (!d->class->postopen_driver (d))
803     {
804       msg (IS, _("Can't complete initialization of output driver `%s' of "
805            "class `%s'."), d->name, d->class->name);
806       goto error;
807     }
808
809   /* Find like-named driver and delete. */
810   iter = find_driver (d->name);
811   if (iter)
812     destroy_driver (iter);
813
814   /* Add to list. */
815   d->next = outp_driver_list;
816   d->prev = NULL;
817   if (outp_driver_list)
818     outp_driver_list->prev = d;
819   outp_driver_list = d;
820   goto exit;
821
822 error:
823   if (d)
824     destroy_driver (d);
825 exit:
826   free (s);
827 }
828
829 /* Destroys output driver D. */
830 static void
831 destroy_driver (struct outp_driver *d)
832 {
833   if (d->page_open)
834     d->class->close_page (d);
835   if (d->class)
836     {
837       struct outp_driver_class_list *c;
838
839       if (d->driver_open)
840         d->class->close_driver (d);
841
842       for (c = outp_class_list; c; c = c->next)
843         if (c->class == d->class)
844           break;
845       assert (c != NULL);
846       
847       c->ref_count--;
848       if (c->ref_count == 0)
849         {
850           if (!d->class->close_global (d->class))
851             msg (IS, _("Can't deinitialize output driver class `%s'."),
852                  d->class->name);
853         }
854     }
855   free (d->name);
856
857   /* Remove this driver from the global driver list. */
858   if (d->prev)
859     d->prev->next = d->next;
860   if (d->next)
861     d->next->prev = d->prev;
862   if (d == outp_driver_list)
863     outp_driver_list = d->next;
864 }
865
866 static int
867 option_cmp (const void *a, const void *b)
868 {
869   const struct outp_option *o1 = a;
870   const struct outp_option *o2 = b;
871   return strcmp (o1->keyword, o2->keyword);
872 }
873
874 /* Tries to match S as one of the keywords in TAB, with corresponding
875    information structure INFO.  Returns category code or 0 on failure;
876    if category code is negative then stores subcategory in *SUBCAT. */
877 int
878 outp_match_keyword (const char *s, struct outp_option *tab,
879                     struct outp_option_info *info, int *subcat)
880 {
881   char *cp;
882   struct outp_option *oip;
883
884   /* Form hash table. */
885   if (NULL == info->initial)
886     {
887       /* Count items. */
888       int count, i;
889       char s[256], *cp;
890       struct outp_option *ptr[255], **oip;
891
892       for (count = 0; tab[count].keyword[0]; count++)
893         ;
894
895       /* Sort items. */
896       qsort (tab, count, sizeof *tab, option_cmp);
897
898       cp = s;
899       oip = ptr;
900       *cp = tab[0].keyword[0];
901       *oip++ = &tab[0];
902       for (i = 0; i < count; i++)
903         if (tab[i].keyword[0] != *cp)
904           {
905             *++cp = tab[i].keyword[0];
906             *oip++ = &tab[i];
907           }
908       *++cp = 0;
909
910       info->initial = xstrdup (s);
911       info->options = xmalloc (sizeof *info->options * (cp - s));
912       memcpy (info->options, ptr, sizeof *info->options * (cp - s));
913     }
914
915   cp = info->initial;
916   oip = *info->options;
917
918   if (s[0] == 0)
919     return 0;
920   cp = strchr (info->initial, s[0]);
921   if (!cp)
922     return 0;
923 #if 0
924   printf (_("Trying to find keyword `%s'...\n"), s);
925 #endif
926   oip = info->options[cp - info->initial];
927   while (oip->keyword[0] == s[0])
928     {
929 #if 0
930       printf ("- %s\n", oip->keyword);
931 #endif
932       if (!strcmp (s, oip->keyword))
933         {
934           if (oip->cat < 0)
935             *subcat = oip->subcat;
936           return oip->cat;
937         }
938       oip++;
939     }
940
941   return 0;
942 }
943
944 /* Encapsulate two characters in a single int. */
945 #define TWO_CHARS(A, B)                         \
946         ((A) + ((B)<<8))
947
948 /* Determines the size of a dimensional measurement and returns the
949    size in units of 1/72000".  Units if not specified explicitly are
950    inches for values under 50, millimeters otherwise.  Returns 0,
951    stores NULL to *TAIL on error; otherwise returns dimension, stores
952    address of next */
953 int
954 outp_evaluate_dimension (char *dimen, char **tail)
955 {
956   char *s = dimen;
957   char *ptail;
958   double value;
959
960   value = strtod (s, &ptail);
961   if (ptail == s)
962     goto lossage;
963   if (*ptail == '-')
964     {
965       double b, c;
966       s = &ptail[1];
967       b = strtod (s, &ptail);
968       if (b <= 0.0 || ptail == s)
969         goto lossage;
970       if (*ptail != '/')
971         goto lossage;
972       s = &ptail[1];
973       c = strtod (s, &ptail);
974       if (c <= 0.0 || ptail == s)
975         goto lossage;
976       s = ptail;
977       if (c == 0.0)
978         goto lossage;
979       if (value > 0)
980         value += b / c;
981       else
982         value -= b / c;
983     }
984   else if (*ptail == '/')
985     {
986       double b;
987       s = &ptail[1];
988       b = strtod (s, &ptail);
989       if (b <= 0.0 || ptail == s)
990         goto lossage;
991       s = ptail;
992       value /= b;
993     }
994   else
995     s = ptail;
996   if (*s == 0 || isspace ((unsigned char) *s))
997     {
998       if (value < 50.0)
999         value *= 72000;
1000       else
1001         value *= 72000 / 25.4;
1002     }
1003   else
1004     {
1005       double factor;
1006
1007       /* Standard TeX units are supported. */
1008       if (*s == '"')
1009         factor = 72000, s++;
1010       else
1011         switch (TWO_CHARS (s[0], s[1]))
1012           {
1013           case TWO_CHARS ('p', 't'):
1014             factor = 72000 / 72.27;
1015             break;
1016           case TWO_CHARS ('p', 'c'):
1017             factor = 72000 / 72.27 * 12.0;
1018             break;
1019           case TWO_CHARS ('i', 'n'):
1020             factor = 72000;
1021             break;
1022           case TWO_CHARS ('b', 'p'):
1023             factor = 72000 / 72.0;
1024             break;
1025           case TWO_CHARS ('c', 'm'):
1026             factor = 72000 / 2.54;
1027             break;
1028           case TWO_CHARS ('m', 'm'):
1029             factor = 72000 / 25.4;
1030             break;
1031           case TWO_CHARS ('d', 'd'):
1032             factor = 72000 / 72.27 * 1.0700086;
1033             break;
1034           case TWO_CHARS ('c', 'c'):
1035             factor = 72000 / 72.27 * 12.840104;
1036             break;
1037           case TWO_CHARS ('s', 'p'):
1038             factor = 72000 / 72.27 / 65536.0;
1039             break;
1040           default:
1041             msg (SE, _("Unit \"%s\" is unknown in dimension \"%s\"."), s, dimen);
1042             *tail = NULL;
1043             return 0;
1044           }
1045       ptail += 2;
1046       value *= factor;
1047     }
1048   if (value <= 0.0)
1049     goto lossage;
1050   if (tail)
1051     *tail = ptail;
1052   return value + 0.5;
1053
1054 lossage:
1055   *tail = NULL;
1056   msg (SE, _("Bad dimension \"%s\"."), dimen);
1057   return 0;
1058 }
1059
1060 /* Stores the dimensions in 1/72000" units of paper identified by
1061    SIZE, which is of form `HORZ x VERT' or `HORZ by VERT' where each
1062    of HORZ and VERT are dimensions, into *H and *V.  Return nonzero on
1063    success. */
1064 static int
1065 internal_get_paper_size (char *size, int *h, int *v)
1066 {
1067   char *tail;
1068
1069   while (isspace ((unsigned char) *size))
1070     size++;
1071   *h = outp_evaluate_dimension (size, &tail);
1072   if (tail == NULL)
1073     return 0;
1074   while (isspace ((unsigned char) *tail))
1075     tail++;
1076   if (*tail == 'x')
1077     tail++;
1078   else if (*tail == 'b' && tail[1] == 'y')
1079     tail += 2;
1080   else
1081     {
1082       msg (SE, _("`x' expected in paper size `%s'."), size);
1083       return 0;
1084     }
1085   *v = outp_evaluate_dimension (tail, &tail);
1086   if (tail == NULL)
1087     return 0;
1088   while (isspace ((unsigned char) *tail))
1089     tail++;
1090   if (*tail)
1091     {
1092       msg (SE, _("Trailing garbage `%s' on paper size `%s'."), tail, size);
1093       return 0;
1094     }
1095   
1096   return 1;
1097 }
1098
1099 /* Stores the dimensions, in 1/72000" units, of paper identified by
1100    SIZE into *H and *V.  SIZE may be a pair of dimensions of form `H x
1101    V', or it may be a case-insensitive paper identifier, which is
1102    looked up in the `papersize' configuration file.  Returns nonzero
1103    on success.  May modify SIZE. */
1104 /* Don't read further unless you've got a strong stomach. */
1105 int
1106 outp_get_paper_size (char *size, int *h, int *v)
1107 {
1108   struct paper_size
1109     {
1110       char *name;
1111       int use;
1112       int h, v;
1113     };
1114
1115   static struct paper_size cache[4];
1116   static int use;
1117
1118   FILE *f;
1119   char *pprsz_fn;
1120
1121   struct string line;
1122   struct file_locator where;
1123
1124   int free_it = 0;
1125   int result = 0;
1126   int min_value, min_index;
1127   char *ep;
1128   int i;
1129
1130   while (isspace ((unsigned char) *size))
1131     size++;
1132   if (isdigit ((unsigned char) *size))
1133     return internal_get_paper_size (size, h, v);
1134   ep = size;
1135   while (*ep)
1136     ep++;
1137   while (isspace ((unsigned char) *ep) && ep >= size)
1138     ep--;
1139   if (ep == size)
1140     {
1141       msg (SE, _("Paper size name must not be empty."));
1142       return 0;
1143     }
1144   
1145   ep++;
1146   if (*ep)
1147     *ep = 0;
1148
1149   use++;
1150   for (i = 0; i < 4; i++)
1151     if (cache[i].name != NULL && !strcasecmp (cache[i].name, size))
1152       {
1153         *h = cache[i].h;
1154         *v = cache[i].v;
1155         cache[i].use = use;
1156         return 1;
1157       }
1158
1159   pprsz_fn = fn_search_path (fn_getenv_default ("STAT_OUTPUT_PAPERSIZE_FILE",
1160                                                 "papersize"),
1161                              fn_getenv_default ("STAT_OUTPUT_INIT_PATH",
1162                                                 config_path),
1163                              NULL);
1164
1165   where.filename = pprsz_fn;
1166   where.line_number = 0;
1167   err_push_file_locator (&where);
1168   ds_init (&line, 128);
1169
1170   if (pprsz_fn == NULL)
1171     {
1172       msg (IE, _("Cannot find `papersize' configuration file."));
1173       goto exit;
1174     }
1175
1176   msg (VM (1), _("%s: Opening paper size definition file..."), pprsz_fn);
1177   f = fopen (pprsz_fn, "r");
1178   if (!f)
1179     {
1180       msg (IE, _("Opening %s: %s."), pprsz_fn, strerror (errno));
1181       goto exit;
1182     }
1183
1184   for (;;)
1185     {
1186       char *cp, *bp, *ep;
1187
1188       if (!ds_get_config_line (f, &line, &where))
1189         {
1190           if (ferror (f))
1191             msg (ME, _("Reading %s: %s."), pprsz_fn, strerror (errno));
1192           break;
1193         }
1194       for (cp = ds_c_str (&line); isspace ((unsigned char) *cp); cp++);
1195       if (*cp == 0)
1196         continue;
1197       if (*cp != '"')
1198         goto lex_error;
1199       for (bp = ep = cp + 1; *ep && *ep != '"'; ep++);
1200       if (!*ep)
1201         goto lex_error;
1202       *ep = 0;
1203       if (0 != strcasecmp (bp, size))
1204         continue;
1205
1206       for (cp = ep + 1; isspace ((unsigned char) *cp); cp++);
1207       if (*cp == '=')
1208         {
1209           size = xmalloc (ep - bp + 1);
1210           strcpy (size, bp);
1211           free_it = 1;
1212           continue;
1213         }
1214       size = &ep[1];
1215       break;
1216
1217     lex_error:
1218       msg (IE, _("Syntax error in paper size definition."));
1219     }
1220
1221   /* We found the one we want! */
1222   result = internal_get_paper_size (size, h, v);
1223   if (result)
1224     {
1225       min_value = cache[0].use;
1226       min_index = 0;
1227       for (i = 1; i < 4; i++)
1228         if (cache[0].use < min_value)
1229           {
1230             min_value = cache[i].use;
1231             min_index = i;
1232           }
1233       free (cache[min_index].name);
1234       cache[min_index].name = xstrdup (size);
1235       cache[min_index].use = use;
1236       cache[min_index].h = *h;
1237       cache[min_index].v = *v;
1238     }
1239
1240 exit:
1241   err_pop_file_locator (&where);
1242   ds_destroy (&line);
1243   if (free_it)
1244     free (size);
1245
1246   if (result)
1247     msg (VM (2), _("Paper size definition file read successfully."));
1248   else
1249     msg (VM (1), _("Error reading paper size definition file."));
1250   
1251   return result;
1252 }
1253
1254 /* If D is NULL, returns the first enabled driver if any, NULL if
1255    none.  Otherwise D must be the last driver returned by this
1256    function, in which case the next enabled driver is returned or NULL
1257    if that was the last. */
1258 struct outp_driver *
1259 outp_drivers (struct outp_driver *d)
1260 {
1261 #if GLOBAL_DEBUGGING
1262   struct outp_driver *orig_d = d;
1263 #endif
1264
1265   for (;;)
1266     {
1267       if (d == NULL)
1268         d = outp_driver_list;
1269       else
1270         d = d->next;
1271
1272       if (d == NULL
1273           || (d->driver_open
1274               && (d->device == 0
1275                   || (d->device & disabled_devices) != d->device)))
1276         break;
1277     }
1278
1279 #if GLOBAL_DEBUGGING
1280   if (d && !orig_d)
1281     {
1282       if (iterating_driver_list++)
1283         reentrancy ();
1284     }
1285   else if (orig_d && !d)
1286     {
1287       assert (iterating_driver_list == 1);
1288       iterating_driver_list = 0;
1289     }
1290 #endif
1291
1292   return d;
1293 }
1294
1295 /* Enables (if ENABLE is nonzero) or disables (if ENABLE is zero) the
1296    device(s) given in mask DEVICE. */
1297 void
1298 outp_enable_device (int enable, int device)
1299 {
1300   if (enable)
1301     disabled_devices &= ~device;
1302   else
1303     disabled_devices |= device;
1304 }
1305
1306 /* Ejects the paper on device D, if the page is not blank. */
1307 int
1308 outp_eject_page (struct outp_driver *d)
1309 {
1310   if (d->page_open == 0)
1311     return 1;
1312   
1313   if (d->cp_y != 0)
1314     {
1315       d->cp_x = d->cp_y = 0;
1316
1317       if (d->class->close_page (d) == 0)
1318         msg (ME, _("Error closing page on %s device of %s class."),
1319              d->name, d->class->name);
1320       if (d->class->open_page (d) == 0)
1321         {
1322           msg (ME, _("Error opening page on %s device of %s class."),
1323                d->name, d->class->name);
1324           return 0;
1325         }
1326     }
1327   return 1;
1328 }
1329
1330 /* Returns the width of string S, in device units, when output on
1331    device D. */
1332 int
1333 outp_string_width (struct outp_driver *d, const char *s)
1334 {
1335   struct outp_text text;
1336
1337   text.options = OUTP_T_JUST_LEFT;
1338   ls_init (&text.s, (char *) s, strlen (s));
1339   d->class->text_metrics (d, &text);
1340
1341   return text.h;
1342 }