Plugged some memory leaks.
[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., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, 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.  Use `-vv' to view "
296            "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
459   return 1;
460 }
461
462 /* Display on stdout a list of all registered driver classes. */
463 void
464 outp_list_classes (void)
465 {
466   int width = get_viewwidth();
467   struct outp_driver_class_list *c;
468
469   printf (_("Driver classes:\n\t"));
470   width -= 8;
471   for (c = outp_class_list; c; c = c->next)
472     {
473       if ((int) strlen (c->class->name) + 1 > width)
474         {
475           printf ("\n\t");
476           width = get_viewwidth() - 8;
477         }
478       else
479         putc (' ', stdout);
480       fputs (c->class->name, stdout);
481     }
482   putc('\n', stdout);
483 }
484
485 static int op_token;            /* `=', 'a', 0. */
486 static struct string op_tokstr;
487 static char *prog;
488
489 /* Parses a token from prog into op_token, op_tokstr.  Sets op_token
490    to '=' on an equals sign, to 'a' on a string or identifier token,
491    or to 0 at end of line.  Returns the new op_token. */
492 static int
493 tokener (void)
494 {
495   if (op_token == 0)
496     {
497       msg (IS, _("Syntax error."));
498       return 0;
499     }
500
501   while (isspace ((unsigned char) *prog))
502     prog++;
503   if (!*prog)
504     {
505       op_token = 0;
506       return 0;
507     }
508
509   if (*prog == '=')
510     op_token = *prog++;
511   else
512     {
513       ds_clear (&op_tokstr);
514
515       if (*prog == '\'' || *prog == '"')
516         {
517           int quote = *prog++;
518
519           while (*prog && *prog != quote)
520             {
521               if (*prog != '\\')
522                 ds_putc (&op_tokstr, *prog++);
523               else
524                 {
525                   int c;
526                   
527                   prog++;
528                   assert ((int) *prog); /* How could a line end in `\'? */
529                   switch (*prog++)
530                     {
531                     case '\'':
532                       c = '\'';
533                       break;
534                     case '"':
535                       c = '"';
536                       break;
537                     case '?':
538                       c = '?';
539                       break;
540                     case '\\':
541                       c = '\\';
542                       break;
543                     case '}':
544                       c = '}';
545                       break;
546                     case 'a':
547                       c = '\a';
548                       break;
549                     case 'b':
550                       c = '\b';
551                       break;
552                     case 'f':
553                       c = '\f';
554                       break;
555                     case 'n':
556                       c = '\n';
557                       break;
558                     case 'r':
559                       c = '\r';
560                       break;
561                     case 't':
562                       c = '\t';
563                       break;
564                     case 'v':
565                       c = '\v';
566                       break;
567                     case '0':
568                     case '1':
569                     case '2':
570                     case '3':
571                     case '4':
572                     case '5':
573                     case '6':
574                     case '7':
575                       {
576                         c = prog[-1] - '0';
577                         while (*prog >= '0' && *prog <= '7')
578                           c = c * 8 + *prog++ - '0';
579                       }
580                       break;
581                     case 'x':
582                     case 'X':
583                       {
584                         c = 0;
585                         while (isxdigit ((unsigned char) *prog))
586                           {
587                             c *= 16;
588                             if (isdigit ((unsigned char) *prog))
589                               c += *prog - '0';
590                             else
591                               c += (tolower ((unsigned char) (*prog))
592                                     - 'a' + 10);
593                             prog++;
594                           }
595                       }
596                       break;
597                     default:
598                       msg (IS, _("Syntax error in string constant."));
599                       continue;
600                     }
601                   ds_putc (&op_tokstr, (unsigned char) c);
602                 }
603             }
604           prog++;
605         }
606       else
607         while (*prog && !isspace ((unsigned char) *prog) && *prog != '=')
608           ds_putc (&op_tokstr, *prog++);
609       op_token = 'a';
610     }
611
612   return 1;
613 }
614
615 /* Applies the user-specified options in string S to output driver D
616    (at configuration time). */
617 static void
618 parse_options (char *s, struct outp_driver * d)
619 {
620   prog = s;
621   op_token = -1;
622
623   ds_init (&op_tokstr, 64);
624   while (tokener ())
625     {
626       char key[65];
627
628       if (op_token != 'a')
629         {
630           msg (IS, _("Syntax error in options."));
631           break;
632         }
633
634       ds_truncate (&op_tokstr, 64);
635       strcpy (key, ds_c_str (&op_tokstr));
636
637       tokener ();
638       if (op_token != '=')
639         {
640           msg (IS, _("Syntax error in options (`=' expected)."));
641           break;
642         }
643
644       tokener ();
645       if (op_token != 'a')
646         {
647           msg (IS, _("Syntax error in options (value expected after `=')."));
648           break;
649         }
650       d->class->option (d, key, &op_tokstr);
651     }
652   ds_destroy (&op_tokstr);
653 }
654
655 /* Find the driver in outp_driver_list with name NAME. */
656 static struct outp_driver *
657 find_driver (char *name)
658 {
659   struct outp_driver *d;
660
661 #if GLOBAL_DEBUGGING
662   if (iterating_driver_list)
663     reentrancy ();
664 #endif
665   for (d = outp_driver_list; d; d = d->next)
666     if (!strcmp (d->name, name))
667       return d;
668   return NULL;
669 }
670
671 /* Tokenize string S into colon-separated fields, removing leading and
672    trailing whitespace on tokens.  Returns a pointer to the
673    null-terminated token, which is formed by setting a NUL character
674    into the string.  After the first call, subsequent calls should set
675    S to NULL.  CP should be consistent across calls.  Returns NULL
676    after all fields have been used up.
677
678    FIXME: Should ignore colons inside double quotes. */
679 static char *
680 colon_tokenize (char *s, char **cp)
681 {
682   char *token;
683   
684   if (!s)
685     {
686       s = *cp;
687       if (*s == 0)
688         return NULL;
689     }
690   token = s += strspn (s, " \t\v\r");
691   *cp = strchr (s, ':');
692   if (*cp == NULL)
693     s = *cp = strchr (s, 0);
694   else
695     s = (*cp)++;
696   while (s > token && strchr (" \t\v\r", s[-1]))
697     s--;
698   *s = 0;
699   return token;
700 }
701
702 /* String S is in format:
703    DRIVERNAME:CLASSNAME:DEVICETYPE:OPTIONS
704    Adds a driver to outp_driver_list pursuant to the specification
705    provided.  */
706 static void
707 configure_driver (char *s)
708 {
709   char *token, *cp;
710   struct outp_driver *d = NULL, *iter;
711   struct outp_driver_class_list *c = NULL;
712
713   s = fn_interp_vars (s, find_defn_value);
714
715   /* Driver name. */
716   token = colon_tokenize (s, &cp);
717   if (!token)
718     {
719       msg (IS, _("Driver name expected."));
720       goto error;
721     }
722
723   d = xmalloc (sizeof *d);
724
725   d->class = NULL;
726   d->name = xstrdup (token);
727   d->driver_open = 0;
728   d->page_open = 0;
729
730   d->next = d->prev = NULL;
731
732   d->device = OUTP_DEV_NONE;
733   
734   d->ext = NULL;
735
736   /* Class name. */
737   token = colon_tokenize (NULL, &cp);
738   if (!token)
739     {
740       msg (IS, _("Class name expected."));
741       goto error;
742     }
743
744   for (c = outp_class_list; c; c = c->next)
745     if (!strcmp (c->class->name, token))
746       break;
747   if (!c)
748     {
749       msg (IS, _("Unknown output driver class `%s'."), token);
750       goto error;
751     }
752   
753   d->class = c->class;
754   if (!c->ref_count && !d->class->open_global (d->class))
755     {
756       msg (IS, _("Can't initialize output driver class `%s'."),
757            d->class->name);
758       goto error;
759     }
760   c->ref_count++;
761   if (!d->class->preopen_driver (d))
762     {
763       msg (IS, _("Can't initialize output driver `%s' of class `%s'."),
764            d->name, d->class->name);
765       goto error;
766     }
767
768   /* Device types. */
769   token = colon_tokenize (NULL, &cp);
770   if (token)
771     {
772       char *sp, *type;
773
774       for (type = strtok_r (token, " \t\r\v", &sp); type;
775            type = strtok_r (NULL, " \t\r\v", &sp))
776         {
777           if (!strcmp (type, "listing"))
778             d->device |= OUTP_DEV_LISTING;
779           else if (!strcmp (type, "screen"))
780             d->device |= OUTP_DEV_SCREEN;
781           else if (!strcmp (type, "printer"))
782             d->device |= OUTP_DEV_PRINTER;
783           else
784             {
785               msg (IS, _("Unknown device type `%s'."), type);
786               goto error;
787             }
788         }
789     }
790   
791   /* Options. */
792   token = colon_tokenize (NULL, &cp);
793   if (token)
794     parse_options (token, d);
795   if (!d->class->postopen_driver (d))
796     {
797       msg (IS, _("Can't complete initialization of output driver `%s' of "
798            "class `%s'."), d->name, d->class->name);
799       goto error;
800     }
801
802   /* Find like-named driver and delete. */
803   iter = find_driver (d->name);
804   if (iter)
805     destroy_driver (iter);
806
807   /* Add to list. */
808   d->next = outp_driver_list;
809   d->prev = NULL;
810   if (outp_driver_list)
811     outp_driver_list->prev = d;
812   outp_driver_list = d;
813   goto exit;
814
815 error:
816   if (d)
817     destroy_driver (d);
818 exit:
819   free (s);
820 }
821
822 /* Destroys output driver D. */
823 static void
824 destroy_driver (struct outp_driver *d)
825 {
826   if (d->page_open)
827     d->class->close_page (d);
828   if (d->class)
829     {
830       struct outp_driver_class_list *c;
831
832       if (d->driver_open)
833         d->class->close_driver (d);
834
835       for (c = outp_class_list; c; c = c->next)
836         if (c->class == d->class)
837           break;
838       assert (c != NULL);
839       
840       c->ref_count--;
841       if (c->ref_count == 0)
842         {
843           if (!d->class->close_global (d->class))
844             msg (IS, _("Can't deinitialize output driver class `%s'."),
845                  d->class->name);
846         }
847     }
848   free (d->name);
849
850   /* Remove this driver from the global driver list. */
851   if (d->prev)
852     d->prev->next = d->next;
853   if (d->next)
854     d->next->prev = d->prev;
855   if (d == outp_driver_list)
856     outp_driver_list = d->next;
857 }
858
859 static int
860 option_cmp (const void *a, const void *b)
861 {
862   const struct outp_option *o1 = a;
863   const struct outp_option *o2 = b;
864   return strcmp (o1->keyword, o2->keyword);
865 }
866
867 /* Tries to match S as one of the keywords in TAB, with corresponding
868    information structure INFO.  Returns category code or 0 on failure;
869    if category code is negative then stores subcategory in *SUBCAT. */
870 int
871 outp_match_keyword (const char *s, struct outp_option *tab,
872                     struct outp_option_info *info, int *subcat)
873 {
874   char *cp;
875   struct outp_option *oip;
876
877   /* Form hash table. */
878   if (NULL == info->initial)
879     {
880       /* Count items. */
881       int count, i;
882       char s[256], *cp;
883       struct outp_option *ptr[255], **oip;
884
885       for (count = 0; tab[count].keyword[0]; count++)
886         ;
887
888       /* Sort items. */
889       qsort (tab, count, sizeof *tab, option_cmp);
890
891       cp = s;
892       oip = ptr;
893       *cp = tab[0].keyword[0];
894       *oip++ = &tab[0];
895       for (i = 0; i < count; i++)
896         if (tab[i].keyword[0] != *cp)
897           {
898             *++cp = tab[i].keyword[0];
899             *oip++ = &tab[i];
900           }
901       *++cp = 0;
902
903       info->initial = xstrdup (s);
904       info->options = xmalloc (sizeof *info->options * (cp - s));
905       memcpy (info->options, ptr, sizeof *info->options * (cp - s));
906     }
907
908   cp = info->initial;
909   oip = *info->options;
910
911   if (s[0] == 0)
912     return 0;
913   cp = strchr (info->initial, s[0]);
914   if (!cp)
915     return 0;
916 #if 0
917   printf (_("Trying to find keyword `%s'...\n"), s);
918 #endif
919   oip = info->options[cp - info->initial];
920   while (oip->keyword[0] == s[0])
921     {
922 #if 0
923       printf ("- %s\n", oip->keyword);
924 #endif
925       if (!strcmp (s, oip->keyword))
926         {
927           if (oip->cat < 0)
928             *subcat = oip->subcat;
929           return oip->cat;
930         }
931       oip++;
932     }
933
934   return 0;
935 }
936
937 /* Encapsulate two characters in a single int. */
938 #define TWO_CHARS(A, B)                         \
939         ((A) + ((B)<<8))
940
941 /* Determines the size of a dimensional measurement and returns the
942    size in units of 1/72000".  Units if not specified explicitly are
943    inches for values under 50, millimeters otherwise.  Returns 0,
944    stores NULL to *TAIL on error; otherwise returns dimension, stores
945    address of next */
946 int
947 outp_evaluate_dimension (char *dimen, char **tail)
948 {
949   char *s = dimen;
950   char *ptail;
951   double value;
952
953   value = strtod (s, &ptail);
954   if (ptail == s)
955     goto lossage;
956   if (*ptail == '-')
957     {
958       double b, c;
959       s = &ptail[1];
960       b = strtod (s, &ptail);
961       if (b <= 0.0 || ptail == s)
962         goto lossage;
963       if (*ptail != '/')
964         goto lossage;
965       s = &ptail[1];
966       c = strtod (s, &ptail);
967       if (c <= 0.0 || ptail == s)
968         goto lossage;
969       s = ptail;
970       if (c == 0.0)
971         goto lossage;
972       if (value > 0)
973         value += b / c;
974       else
975         value -= b / c;
976     }
977   else if (*ptail == '/')
978     {
979       double b;
980       s = &ptail[1];
981       b = strtod (s, &ptail);
982       if (b <= 0.0 || ptail == s)
983         goto lossage;
984       s = ptail;
985       value /= b;
986     }
987   else
988     s = ptail;
989   if (*s == 0 || isspace ((unsigned char) *s))
990     {
991       if (value < 50.0)
992         value *= 72000;
993       else
994         value *= 72000 / 25.4;
995     }
996   else
997     {
998       double factor;
999
1000       /* Standard TeX units are supported. */
1001       if (*s == '"')
1002         factor = 72000, s++;
1003       else
1004         switch (TWO_CHARS (s[0], s[1]))
1005           {
1006           case TWO_CHARS ('p', 't'):
1007             factor = 72000 / 72.27;
1008             break;
1009           case TWO_CHARS ('p', 'c'):
1010             factor = 72000 / 72.27 * 12.0;
1011             break;
1012           case TWO_CHARS ('i', 'n'):
1013             factor = 72000;
1014             break;
1015           case TWO_CHARS ('b', 'p'):
1016             factor = 72000 / 72.0;
1017             break;
1018           case TWO_CHARS ('c', 'm'):
1019             factor = 72000 / 2.54;
1020             break;
1021           case TWO_CHARS ('m', 'm'):
1022             factor = 72000 / 25.4;
1023             break;
1024           case TWO_CHARS ('d', 'd'):
1025             factor = 72000 / 72.27 * 1.0700086;
1026             break;
1027           case TWO_CHARS ('c', 'c'):
1028             factor = 72000 / 72.27 * 12.840104;
1029             break;
1030           case TWO_CHARS ('s', 'p'):
1031             factor = 72000 / 72.27 / 65536.0;
1032             break;
1033           default:
1034             msg (SE, _("Unit \"%s\" is unknown in dimension \"%s\"."), s, dimen);
1035             *tail = NULL;
1036             return 0;
1037           }
1038       ptail += 2;
1039       value *= factor;
1040     }
1041   if (value <= 0.0)
1042     goto lossage;
1043   if (tail)
1044     *tail = ptail;
1045   return value + 0.5;
1046
1047 lossage:
1048   *tail = NULL;
1049   msg (SE, _("Bad dimension \"%s\"."), dimen);
1050   return 0;
1051 }
1052
1053 /* Stores the dimensions in 1/72000" units of paper identified by
1054    SIZE, which is of form `HORZ x VERT' or `HORZ by VERT' where each
1055    of HORZ and VERT are dimensions, into *H and *V.  Return nonzero on
1056    success. */
1057 static int
1058 internal_get_paper_size (char *size, int *h, int *v)
1059 {
1060   char *tail;
1061
1062   while (isspace ((unsigned char) *size))
1063     size++;
1064   *h = outp_evaluate_dimension (size, &tail);
1065   if (tail == NULL)
1066     return 0;
1067   while (isspace ((unsigned char) *tail))
1068     tail++;
1069   if (*tail == 'x')
1070     tail++;
1071   else if (*tail == 'b' && tail[1] == 'y')
1072     tail += 2;
1073   else
1074     {
1075       msg (SE, _("`x' expected in paper size `%s'."), size);
1076       return 0;
1077     }
1078   *v = outp_evaluate_dimension (tail, &tail);
1079   if (tail == NULL)
1080     return 0;
1081   while (isspace ((unsigned char) *tail))
1082     tail++;
1083   if (*tail)
1084     {
1085       msg (SE, _("Trailing garbage `%s' on paper size `%s'."), tail, size);
1086       return 0;
1087     }
1088   
1089   return 1;
1090 }
1091
1092 /* Stores the dimensions, in 1/72000" units, of paper identified by
1093    SIZE into *H and *V.  SIZE may be a pair of dimensions of form `H x
1094    V', or it may be a case-insensitive paper identifier, which is
1095    looked up in the `papersize' configuration file.  Returns nonzero
1096    on success.  May modify SIZE. */
1097 /* Don't read further unless you've got a strong stomach. */
1098 int
1099 outp_get_paper_size (char *size, int *h, int *v)
1100 {
1101   struct paper_size
1102     {
1103       char *name;
1104       int use;
1105       int h, v;
1106     };
1107
1108   static struct paper_size cache[4];
1109   static int use;
1110
1111   FILE *f;
1112   char *pprsz_fn;
1113
1114   struct string line;
1115   struct file_locator where;
1116
1117   int free_it = 0;
1118   int result = 0;
1119   int min_value, min_index;
1120   char *ep;
1121   int i;
1122
1123   while (isspace ((unsigned char) *size))
1124     size++;
1125   if (isdigit ((unsigned char) *size))
1126     return internal_get_paper_size (size, h, v);
1127   ep = size;
1128   while (*ep)
1129     ep++;
1130   while (isspace ((unsigned char) *ep) && ep >= size)
1131     ep--;
1132   if (ep == size)
1133     {
1134       msg (SE, _("Paper size name must not be empty."));
1135       return 0;
1136     }
1137   
1138   ep++;
1139   if (*ep)
1140     *ep = 0;
1141
1142   use++;
1143   for (i = 0; i < 4; i++)
1144     if (cache[i].name != NULL && !strcasecmp (cache[i].name, size))
1145       {
1146         *h = cache[i].h;
1147         *v = cache[i].v;
1148         cache[i].use = use;
1149         return 1;
1150       }
1151
1152   pprsz_fn = fn_search_path (fn_getenv_default ("STAT_OUTPUT_PAPERSIZE_FILE",
1153                                                 "papersize"),
1154                              fn_getenv_default ("STAT_OUTPUT_INIT_PATH",
1155                                                 config_path),
1156                              NULL);
1157
1158   where.filename = pprsz_fn;
1159   where.line_number = 0;
1160   err_push_file_locator (&where);
1161   ds_init (&line, 128);
1162
1163   if (pprsz_fn == NULL)
1164     {
1165       msg (IE, _("Cannot find `papersize' configuration file."));
1166       goto exit;
1167     }
1168
1169   msg (VM (1), _("%s: Opening paper size definition file..."), pprsz_fn);
1170   f = fopen (pprsz_fn, "r");
1171   if (!f)
1172     {
1173       msg (IE, _("Opening %s: %s."), pprsz_fn, strerror (errno));
1174       goto exit;
1175     }
1176
1177   for (;;)
1178     {
1179       char *cp, *bp, *ep;
1180
1181       if (!ds_get_config_line (f, &line, &where))
1182         {
1183           if (ferror (f))
1184             msg (ME, _("Reading %s: %s."), pprsz_fn, strerror (errno));
1185           break;
1186         }
1187       for (cp = ds_c_str (&line); isspace ((unsigned char) *cp); cp++);
1188       if (*cp == 0)
1189         continue;
1190       if (*cp != '"')
1191         goto lex_error;
1192       for (bp = ep = cp + 1; *ep && *ep != '"'; ep++);
1193       if (!*ep)
1194         goto lex_error;
1195       *ep = 0;
1196       if (0 != strcasecmp (bp, size))
1197         continue;
1198
1199       for (cp = ep + 1; isspace ((unsigned char) *cp); cp++);
1200       if (*cp == '=')
1201         {
1202           size = xmalloc (ep - bp + 1);
1203           strcpy (size, bp);
1204           free_it = 1;
1205           continue;
1206         }
1207       size = &ep[1];
1208       break;
1209
1210     lex_error:
1211       msg (IE, _("Syntax error in paper size definition."));
1212     }
1213
1214   /* We found the one we want! */
1215   result = internal_get_paper_size (size, h, v);
1216   if (result)
1217     {
1218       min_value = cache[0].use;
1219       min_index = 0;
1220       for (i = 1; i < 4; i++)
1221         if (cache[0].use < min_value)
1222           {
1223             min_value = cache[i].use;
1224             min_index = i;
1225           }
1226       free (cache[min_index].name);
1227       cache[min_index].name = xstrdup (size);
1228       cache[min_index].use = use;
1229       cache[min_index].h = *h;
1230       cache[min_index].v = *v;
1231     }
1232
1233 exit:
1234   err_pop_file_locator (&where);
1235   ds_destroy (&line);
1236   if (free_it)
1237     free (size);
1238
1239   if (result)
1240     msg (VM (2), _("Paper size definition file read successfully."));
1241   else
1242     msg (VM (1), _("Error reading paper size definition file."));
1243   
1244   return result;
1245 }
1246
1247 /* If D is NULL, returns the first enabled driver if any, NULL if
1248    none.  Otherwise D must be the last driver returned by this
1249    function, in which case the next enabled driver is returned or NULL
1250    if that was the last. */
1251 struct outp_driver *
1252 outp_drivers (struct outp_driver *d)
1253 {
1254 #if GLOBAL_DEBUGGING
1255   struct outp_driver *orig_d = d;
1256 #endif
1257
1258   for (;;)
1259     {
1260       if (d == NULL)
1261         d = outp_driver_list;
1262       else
1263         d = d->next;
1264
1265       if (d == NULL
1266           || (d->driver_open
1267               && (d->device == 0
1268                   || (d->device & disabled_devices) != d->device)))
1269         break;
1270     }
1271
1272 #if GLOBAL_DEBUGGING
1273   if (d && !orig_d)
1274     {
1275       if (iterating_driver_list++)
1276         reentrancy ();
1277     }
1278   else if (orig_d && !d)
1279     {
1280       assert (iterating_driver_list == 1);
1281       iterating_driver_list = 0;
1282     }
1283 #endif
1284
1285   return d;
1286 }
1287
1288 /* Enables (if ENABLE is nonzero) or disables (if ENABLE is zero) the
1289    device(s) given in mask DEVICE. */
1290 void
1291 outp_enable_device (int enable, int device)
1292 {
1293   if (enable)
1294     disabled_devices &= ~device;
1295   else
1296     disabled_devices |= device;
1297 }
1298
1299 /* Ejects the paper on device D, if the page is not blank. */
1300 int
1301 outp_eject_page (struct outp_driver *d)
1302 {
1303   if (d->page_open == 0)
1304     return 1;
1305   
1306   if (d->cp_y != 0)
1307     {
1308       d->cp_x = d->cp_y = 0;
1309
1310       if (d->class->close_page (d) == 0)
1311         msg (ME, _("Error closing page on %s device of %s class."),
1312              d->name, d->class->name);
1313       if (d->class->open_page (d) == 0)
1314         {
1315           msg (ME, _("Error opening page on %s device of %s class."),
1316                d->name, d->class->name);
1317           return 0;
1318         }
1319     }
1320   return 1;
1321 }
1322
1323 /* Returns the width of string S, in device units, when output on
1324    device D. */
1325 int
1326 outp_string_width (struct outp_driver *d, const char *s)
1327 {
1328   struct outp_text text;
1329
1330   text.options = OUTP_T_JUST_LEFT;
1331   ls_init (&text.s, (char *) s, strlen (s));
1332   d->class->text_metrics (d, &text);
1333
1334   return text.h;
1335 }