0390e1af73c7f56563def75ca14a9c9f2c6af2f7
[pspp-builds.git] / src / output / 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 <libpspp/message.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <ctype.h>
27 #include <libpspp/alloc.h>
28 #include <libpspp/message.h>
29 #include <data/filename.h>
30 #include "htmlP.h"
31 #include "intprops.h"
32 #include <libpspp/misc.h>
33 #include <data/settings.h>
34 #include <libpspp/str.h>
35
36 #include "gettext.h"
37 #define _(msgid) gettext (msgid)
38
39 /* FIXME? Should the output configuration format be changed to
40    drivername:classname:devicetype:options, where devicetype is zero
41    or more of screen, printer, listing? */
42
43 /* FIXME: Have the reentrancy problems been solved? */
44
45 /* Where the output driver name came from. */
46 enum
47   {
48     OUTP_S_COMMAND_LINE,        /* Specified by the user. */
49     OUTP_S_INIT_FILE            /* `default' or the init file. */
50   };
51
52 /* Names the output drivers to be used. */
53 struct outp_names
54   {
55     char *name;                 /* Name of the output driver. */
56     int source;                 /* OUTP_S_* */
57     struct outp_names *next, *prev;
58   };
59
60 /* Defines an init file macro. */
61 struct outp_defn
62   {
63     char *key;
64     struct string value;
65     struct outp_defn *next, *prev;
66   };
67
68 static struct outp_defn *outp_macros;
69 static struct outp_names *outp_configure_vec;
70
71 struct outp_driver_class_list *outp_class_list;
72 struct outp_driver *outp_driver_list;
73
74 char *outp_title;
75 char *outp_subtitle;
76
77 /* A set of OUTP_DEV_* bits indicating the devices that are
78    disabled. */
79 static int disabled_devices;
80
81 static void destroy_driver (struct outp_driver *);
82 static void configure_driver_line (struct string *);
83 static void configure_driver (const char *, const char *,
84                               const char *, const char *);
85
86 /* Add a class to the class list. */
87 static void
88 add_class (struct outp_class *class)
89 {
90   struct outp_driver_class_list *new_list = xmalloc (sizeof *new_list);
91
92   new_list->class = class;
93   new_list->ref_count = 0;
94
95   if (!outp_class_list)
96     {
97       outp_class_list = new_list;
98       new_list->next = NULL;
99     }
100   else
101     {
102       new_list->next = outp_class_list;
103       outp_class_list = new_list;
104     }
105 }
106
107 /* Finds the outp_names in outp_configure_vec with name between BP and
108    EP exclusive. */
109 static struct outp_names *
110 search_names (char *bp, char *ep)
111 {
112   struct outp_names *n;
113
114   for (n = outp_configure_vec; n; n = n->next)
115     if ((int) strlen (n->name) == ep - bp && !memcmp (n->name, bp, ep - bp))
116       return n;
117   return NULL;
118 }
119
120 /* Deletes outp_names NAME from outp_configure_vec. */
121 static void
122 delete_name (struct outp_names * n)
123 {
124   free (n->name);
125   if (n->prev)
126     n->prev->next = n->next;
127   if (n->next)
128     n->next->prev = n->prev;
129   if (n == outp_configure_vec)
130     outp_configure_vec = n->next;
131   free (n);
132 }
133
134 /* Adds the name between BP and EP exclusive to list
135    outp_configure_vec with source SOURCE. */
136 static void
137 add_name (char *bp, char *ep, int source)
138 {
139   struct outp_names *n = xmalloc (sizeof *n);
140   n->name = xmalloc (ep - bp + 1);
141   memcpy (n->name, bp, ep - bp);
142   n->name[ep - bp] = 0;
143   n->source = source;
144   n->next = outp_configure_vec;
145   n->prev = NULL;
146   if (outp_configure_vec)
147     outp_configure_vec->prev = n;
148   outp_configure_vec = n;
149 }
150
151 /* Checks that outp_configure_vec is empty, bitches & clears it if it
152    isn't. */
153 static void
154 check_configure_vec (void)
155 {
156   struct outp_names *n;
157
158   for (n = outp_configure_vec; n; n = n->next)
159     if (n->source == OUTP_S_COMMAND_LINE)
160       msg (ME, _("Unknown output driver `%s'."), n->name);
161     else
162       msg (IE, _("Output driver `%s' referenced but never defined."), n->name);
163   outp_configure_clear ();
164 }
165
166 /* Searches outp_configure_vec for the name between BP and EP
167    exclusive.  If found, it is deleted, then replaced by the names
168    given in EP+1, if any. */
169 static void
170 expand_name (char *bp, char *ep)
171 {
172   struct outp_names *n = search_names (bp, ep);
173   if (!n)
174     return;
175   delete_name (n);
176
177   bp = ep + 1;
178   for (;;)
179     {
180       while (isspace ((unsigned char) *bp))
181         bp++;
182       ep = bp;
183       while (*ep && !isspace ((unsigned char) *ep))
184         ep++;
185       if (bp == ep)
186         return;
187       if (!search_names (bp, ep))
188         add_name (bp, ep, OUTP_S_INIT_FILE);
189       bp = ep;
190     }
191 }
192
193 /* Looks for a macro with key KEY, and returns the corresponding value
194    if found, or NULL if not. */
195 static const char *
196 find_defn_value (const char *key)
197 {
198   static char buf[INT_STRLEN_BOUND (int) + 1];
199   struct outp_defn *d;
200
201   for (d = outp_macros; d; d = d->next)
202     if (!strcmp (key, d->key))
203       return ds_c_str(&d->value);
204   if (!strcmp (key, "viewwidth"))
205     {
206       sprintf (buf, "%d", get_viewwidth ());
207       return buf;
208     }
209   else if (!strcmp (key, "viewlength"))
210     {
211       sprintf (buf, "%d", get_viewlength ());
212       return buf;
213     }
214   else
215     return getenv (key);
216 }
217
218 /* Initializes global variables. */
219 void
220 outp_init (void)
221 {
222   extern struct outp_class ascii_class;
223   extern struct outp_class postscript_class;
224   extern struct outp_class epsf_class;
225   extern struct outp_class html_class;
226
227   char def[] = "default";
228
229   add_class (&html_class);
230   add_class (&epsf_class);
231   add_class (&postscript_class);
232   add_class (&ascii_class);
233
234   add_name (def, &def[strlen (def)], OUTP_S_INIT_FILE);
235 }
236
237 /* Deletes all the output macros. */
238 static void
239 delete_macros (void)
240 {
241   struct outp_defn *d, *next;
242
243   for (d = outp_macros; d; d = next)
244     {
245       next = d->next;
246       free (d->key);
247       ds_destroy (&d->value);
248       free (d);
249     }
250 }
251
252 static void
253 init_default_drivers (void) 
254 {
255   msg (MM, _("Using default output driver configuration."));
256   configure_driver ("list-ascii", "ascii", "listing",
257                     "length=66 width=79 char-set=ascii "
258                     "output-file=\"pspp.list\" "
259                     "bold-on=\"\" italic-on=\"\" bold-italic-on=\"\"");
260 }
261
262 /* Reads the initialization file; initializes
263    outp_driver_list. */
264 void
265 outp_read_devices (void)
266 {
267   int result = 0;
268
269   char *init_fn;
270
271   FILE *f = NULL;
272   struct string line;
273   struct file_locator where;
274
275   init_fn = fn_search_path (fn_getenv_default ("STAT_OUTPUT_INIT_FILE",
276                                                "devices"),
277                             fn_getenv_default ("STAT_OUTPUT_INIT_PATH",
278                                                config_path),
279                             NULL);
280   where.filename = init_fn;
281   where.line_number = 0;
282   err_push_file_locator (&where);
283
284   ds_init (&line, 128);
285
286   if (init_fn == NULL)
287     {
288       msg (IE, _("Cannot find output initialization file.  "
289                  "Use `-vvvvv' to view search path."));
290       goto exit;
291     }
292
293   msg (VM (1), _("%s: Opening device description file..."), init_fn);
294   f = fopen (init_fn, "r");
295   if (f == NULL)
296     {
297       msg (IE, _("Opening %s: %s."), init_fn, strerror (errno));
298       goto exit;
299     }
300
301   for (;;)
302     {
303       char *cp;
304
305       if (!ds_get_config_line (f, &line, &where.line_number))
306         {
307           if (ferror (f))
308             msg (ME, _("Reading %s: %s."), init_fn, strerror (errno));
309           break;
310         }
311       for (cp = ds_c_str (&line); isspace ((unsigned char) *cp); cp++);
312       if (!strncmp ("define", cp, 6) && isspace ((unsigned char) cp[6]))
313         outp_configure_macro (&cp[7]);
314       else if (*cp)
315         {
316           char *ep;
317           for (ep = cp; *ep && *ep != ':' && *ep != '='; ep++);
318           if (*ep == '=')
319             expand_name (cp, ep);
320           else if (*ep == ':')
321             {
322               struct outp_names *n = search_names (cp, ep);
323               if (n)
324                 {
325                   configure_driver_line (&line);
326                   delete_name (n);
327                 }
328             }
329           else
330             msg (IS, _("Syntax error."));
331         }
332     }
333   result = 1;
334
335   check_configure_vec ();
336
337 exit:
338   err_pop_file_locator (&where);
339   if (f && -1 == fclose (f))
340     msg (MW, _("Closing %s: %s."), init_fn, strerror (errno));
341   free (init_fn);
342   ds_destroy (&line);
343   delete_macros ();
344
345   if (result) 
346     {
347       msg (VM (2), _("Device definition file read successfully."));
348       if (outp_driver_list == NULL) 
349         msg (MW, _("No output drivers are active.")); 
350     }
351   else
352     msg (VM (1), _("Error reading device definition file."));
353
354   if (!result || outp_driver_list == NULL)
355     init_default_drivers ();
356 }
357
358 /* Clear the list of drivers to configure. */
359 void
360 outp_configure_clear (void)
361 {
362   struct outp_names *n, *next;
363
364   for (n = outp_configure_vec; n; n = next)
365     {
366       next = n->next;
367       free (n->name);
368       free (n);
369     }
370   outp_configure_vec = NULL;
371 }
372
373 /* Adds the name BP to the list of drivers to configure into
374    outp_driver_list. */
375 void
376 outp_configure_add (char *bp)
377 {
378   char *ep = &bp[strlen (bp)];
379   if (!search_names (bp, ep))
380     add_name (bp, ep, OUTP_S_COMMAND_LINE);
381 }
382
383 /* Defines one configuration macro based on the text in BP, which
384    should be of the form `KEY=VALUE'. */
385 void
386 outp_configure_macro (char *bp)
387 {
388   struct outp_defn *d;
389   char *ep;
390
391   while (isspace ((unsigned char) *bp))
392     bp++;
393   ep = bp;
394   while (*ep && !isspace ((unsigned char) *ep) && *ep != '=')
395     ep++;
396
397   d = xmalloc (sizeof *d);
398   d->key = xmalloc (ep - bp + 1);
399   memcpy (d->key, bp, ep - bp);
400   d->key[ep - bp] = 0;
401
402   /* Earlier definitions for a particular KEY override later ones. */
403   if (find_defn_value (d->key))
404     {
405       free (d->key);
406       free (d);
407       return;
408     }
409   
410   if (*ep == '=')
411     ep++;
412   while (isspace ((unsigned char) *ep))
413     ep++;
414
415   ds_create(&d->value, ep);
416   fn_interp_vars(&d->value, find_defn_value);
417   d->next = outp_macros;
418   d->prev = NULL;
419   if (outp_macros)
420     outp_macros->prev = d;
421   outp_macros = d;
422 }
423
424 /* Destroys all the drivers in driver list *DL and sets *DL to
425    NULL. */
426 static void
427 destroy_list (struct outp_driver ** dl)
428 {
429   struct outp_driver *d, *next;
430
431   for (d = *dl; d; d = next)
432     {
433       destroy_driver (d);
434       next = d->next;
435       free (d);
436     }
437   *dl = NULL;
438 }
439
440 /* Closes all the output drivers. */
441 void
442 outp_done (void)
443 {
444   struct outp_driver_class_list *n = outp_class_list ; 
445   destroy_list (&outp_driver_list);
446
447   while (n) 
448     {
449       struct outp_driver_class_list *next = n->next;
450       free(n);
451       n = next;
452     }
453   outp_class_list = NULL;
454
455   free (outp_title);
456   outp_title = NULL;
457   
458   free (outp_subtitle);
459   outp_subtitle = NULL;
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 const 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 (const 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   for (d = outp_driver_list; d; d = d->next)
662     if (!strcmp (d->name, name))
663       return d;
664   return NULL;
665 }
666
667 /* String S is in format:
668    DRIVERNAME:CLASSNAME:DEVICETYPE:OPTIONS
669    Adds a driver to outp_driver_list pursuant to the specification
670    provided.  */
671 static void
672 configure_driver (const char *driver_name, const char *class_name,
673                   const char *device_type, const char *options)
674 {
675   struct outp_driver *d = NULL, *iter;
676   struct outp_driver_class_list *c = NULL;
677
678   d = xmalloc (sizeof *d);
679   d->class = NULL;
680   d->name = xstrdup (driver_name);
681   d->driver_open = 0;
682   d->page_open = 0;
683   d->next = d->prev = NULL;
684   d->device = OUTP_DEV_NONE;
685   d->ext = NULL;
686
687   for (c = outp_class_list; c; c = c->next)
688     if (!strcmp (c->class->name, class_name))
689       break;
690   if (!c)
691     {
692       msg (IS, _("Unknown output driver class `%s'."), class_name);
693       goto error;
694     }
695   
696   d->class = c->class;
697   if (!c->ref_count && !d->class->open_global (d->class))
698     {
699       msg (IS, _("Can't initialize output driver class `%s'."),
700            d->class->name);
701       goto error;
702     }
703   c->ref_count++;
704   if (!d->class->preopen_driver (d))
705     {
706       msg (IS, _("Can't initialize output driver `%s' of class `%s'."),
707            d->name, d->class->name);
708       goto error;
709     }
710
711   /* Device types. */
712   if (device_type != NULL)
713     {
714       char *copy = xstrdup (device_type);
715       char *sp, *type;
716
717       for (type = strtok_r (copy, " \t\r\v", &sp); type;
718            type = strtok_r (NULL, " \t\r\v", &sp))
719         {
720           if (!strcmp (type, "listing"))
721             d->device |= OUTP_DEV_LISTING;
722           else if (!strcmp (type, "screen"))
723             d->device |= OUTP_DEV_SCREEN;
724           else if (!strcmp (type, "printer"))
725             d->device |= OUTP_DEV_PRINTER;
726           else
727             {
728               msg (IS, _("Unknown device type `%s'."), type);
729               free (copy);
730               goto error;
731             }
732         }
733       free (copy);
734     }
735   
736   /* Options. */
737   if (options != NULL)
738     parse_options (options, d);
739   if (!d->class->postopen_driver (d))
740     {
741       msg (IS, _("Can't complete initialization of output driver `%s' of "
742            "class `%s'."), d->name, d->class->name);
743       goto error;
744     }
745
746   /* Find like-named driver and delete. */
747   iter = find_driver (d->name);
748   if (iter)
749     destroy_driver (iter);
750
751   /* Add to list. */
752   d->next = outp_driver_list;
753   d->prev = NULL;
754   if (outp_driver_list)
755     outp_driver_list->prev = d;
756   outp_driver_list = d;
757   return;
758
759 error:
760   if (d)
761     destroy_driver (d);
762   return;
763 }
764
765 /* String LINE is in format:
766    DRIVERNAME:CLASSNAME:DEVICETYPE:OPTIONS
767    Adds a driver to outp_driver_list pursuant to the specification
768    provided.  */
769 static void
770 configure_driver_line (struct string *line)
771 {
772   struct string tokens[4];
773   int save_idx;
774   size_t i;
775
776   fn_interp_vars (line, find_defn_value);
777
778   save_idx = -1;
779   for (i = 0; i < 4; i++) 
780     {
781       struct string *token = &tokens[i];
782       ds_init (token, 0);
783       ds_separate (line, token, i < 3 ? ":" : "", &save_idx);
784       ds_trim_spaces (token);
785     }
786
787   if (!ds_is_empty (&tokens[0]) && !ds_is_empty (&tokens[1]))
788     configure_driver (ds_c_str (&tokens[0]), ds_c_str (&tokens[1]), 
789                       ds_c_str (&tokens[2]), ds_c_str (&tokens[3]));
790   else
791     msg (IS, _("Driver definition line missing driver name or class name"));
792
793   for (i = 0; i < 4; i++) 
794     ds_destroy (&tokens[i]);
795 }
796
797 /* Destroys output driver D. */
798 static void
799 destroy_driver (struct outp_driver *d)
800 {
801   if (d->page_open)
802     d->class->close_page (d);
803   if (d->class)
804     {
805       struct outp_driver_class_list *c;
806
807       if (d->driver_open)
808         d->class->close_driver (d);
809
810       for (c = outp_class_list; c; c = c->next)
811         if (c->class == d->class)
812           break;
813       assert (c != NULL);
814       
815       c->ref_count--;
816       if (c->ref_count == 0)
817         {
818           if (!d->class->close_global (d->class))
819             msg (IS, _("Can't deinitialize output driver class `%s'."),
820                  d->class->name);
821         }
822     }
823   free (d->name);
824
825   /* Remove this driver from the global driver list. */
826   if (d->prev)
827     d->prev->next = d->next;
828   if (d->next)
829     d->next->prev = d->prev;
830   if (d == outp_driver_list)
831     outp_driver_list = d->next;
832 }
833
834 static int
835 option_cmp (const void *a, const void *b)
836 {
837   const struct outp_option *o1 = a;
838   const struct outp_option *o2 = b;
839   return strcmp (o1->keyword, o2->keyword);
840 }
841
842 /* Tries to match S as one of the keywords in TAB, with corresponding
843    information structure INFO.  Returns category code or 0 on failure;
844    if category code is negative then stores subcategory in *SUBCAT. */
845 int
846 outp_match_keyword (const char *s, struct outp_option *tab,
847                     struct outp_option_info *info, int *subcat)
848 {
849   char *cp;
850   struct outp_option *oip;
851
852   /* Form hash table. */
853   if (NULL == info->initial)
854     {
855       /* Count items. */
856       int count, i;
857       char s[256], *cp;
858       struct outp_option *ptr[255], **oip;
859
860       for (count = 0; tab[count].keyword[0]; count++)
861         ;
862
863       /* Sort items. */
864       qsort (tab, count, sizeof *tab, option_cmp);
865
866       cp = s;
867       oip = ptr;
868       *cp = tab[0].keyword[0];
869       *oip++ = &tab[0];
870       for (i = 0; i < count; i++)
871         if (tab[i].keyword[0] != *cp)
872           {
873             *++cp = tab[i].keyword[0];
874             *oip++ = &tab[i];
875           }
876       *++cp = 0;
877
878       info->initial = xstrdup (s);
879       info->options = xnmalloc (cp - s, sizeof *info->options);
880       memcpy (info->options, ptr, sizeof *info->options * (cp - s));
881     }
882
883   cp = info->initial;
884   oip = *info->options;
885
886   if (s[0] == 0)
887     return 0;
888   cp = strchr (info->initial, s[0]);
889   if (!cp)
890     return 0;
891 #if 0
892   printf (_("Trying to find keyword `%s'...\n"), s);
893 #endif
894   oip = info->options[cp - info->initial];
895   while (oip->keyword[0] == s[0])
896     {
897 #if 0
898       printf ("- %s\n", oip->keyword);
899 #endif
900       if (!strcmp (s, oip->keyword))
901         {
902           if (oip->cat < 0)
903             *subcat = oip->subcat;
904           return oip->cat;
905         }
906       oip++;
907     }
908
909   return 0;
910 }
911
912 /* Encapsulate two characters in a single int. */
913 #define TWO_CHARS(A, B)                         \
914         ((A) + ((B)<<8))
915
916 /* Determines the size of a dimensional measurement and returns the
917    size in units of 1/72000".  Units if not specified explicitly are
918    inches for values under 50, millimeters otherwise.  Returns 0,
919    stores NULL to *TAIL on error; otherwise returns dimension, stores
920    address of next */
921 int
922 outp_evaluate_dimension (char *dimen, char **tail)
923 {
924   char *s = dimen;
925   char *ptail;
926   double value;
927
928   value = strtod (s, &ptail);
929   if (ptail == s)
930     goto lossage;
931   if (*ptail == '-')
932     {
933       double b, c;
934       s = &ptail[1];
935       b = strtod (s, &ptail);
936       if (b <= 0.0 || ptail == s)
937         goto lossage;
938       if (*ptail != '/')
939         goto lossage;
940       s = &ptail[1];
941       c = strtod (s, &ptail);
942       if (c <= 0.0 || ptail == s)
943         goto lossage;
944       s = ptail;
945       if (c == 0.0)
946         goto lossage;
947       if (value > 0)
948         value += b / c;
949       else
950         value -= b / c;
951     }
952   else if (*ptail == '/')
953     {
954       double b;
955       s = &ptail[1];
956       b = strtod (s, &ptail);
957       if (b <= 0.0 || ptail == s)
958         goto lossage;
959       s = ptail;
960       value /= b;
961     }
962   else
963     s = ptail;
964   if (*s == 0 || isspace ((unsigned char) *s))
965     {
966       if (value < 50.0)
967         value *= 72000;
968       else
969         value *= 72000 / 25.4;
970     }
971   else
972     {
973       double factor;
974
975       /* Standard TeX units are supported. */
976       if (*s == '"')
977         factor = 72000, s++;
978       else
979         switch (TWO_CHARS (s[0], s[1]))
980           {
981           case TWO_CHARS ('p', 't'):
982             factor = 72000 / 72.27;
983             break;
984           case TWO_CHARS ('p', 'c'):
985             factor = 72000 / 72.27 * 12.0;
986             break;
987           case TWO_CHARS ('i', 'n'):
988             factor = 72000;
989             break;
990           case TWO_CHARS ('b', 'p'):
991             factor = 72000 / 72.0;
992             break;
993           case TWO_CHARS ('c', 'm'):
994             factor = 72000 / 2.54;
995             break;
996           case TWO_CHARS ('m', 'm'):
997             factor = 72000 / 25.4;
998             break;
999           case TWO_CHARS ('d', 'd'):
1000             factor = 72000 / 72.27 * 1.0700086;
1001             break;
1002           case TWO_CHARS ('c', 'c'):
1003             factor = 72000 / 72.27 * 12.840104;
1004             break;
1005           case TWO_CHARS ('s', 'p'):
1006             factor = 72000 / 72.27 / 65536.0;
1007             break;
1008           default:
1009             msg (SE, _("Unit \"%s\" is unknown in dimension \"%s\"."), s, dimen);
1010             *tail = NULL;
1011             return 0;
1012           }
1013       ptail += 2;
1014       value *= factor;
1015     }
1016   if (value <= 0.0)
1017     goto lossage;
1018   if (tail)
1019     *tail = ptail;
1020   return value + 0.5;
1021
1022 lossage:
1023   *tail = NULL;
1024   msg (SE, _("Bad dimension \"%s\"."), dimen);
1025   return 0;
1026 }
1027
1028 /* Stores the dimensions in 1/72000" units of paper identified by
1029    SIZE, which is of form `HORZ x VERT' or `HORZ by VERT' where each
1030    of HORZ and VERT are dimensions, into *H and *V.  Return nonzero on
1031    success. */
1032 static int
1033 internal_get_paper_size (char *size, int *h, int *v)
1034 {
1035   char *tail;
1036
1037   while (isspace ((unsigned char) *size))
1038     size++;
1039   *h = outp_evaluate_dimension (size, &tail);
1040   if (tail == NULL)
1041     return 0;
1042   while (isspace ((unsigned char) *tail))
1043     tail++;
1044   if (*tail == 'x')
1045     tail++;
1046   else if (*tail == 'b' && tail[1] == 'y')
1047     tail += 2;
1048   else
1049     {
1050       msg (SE, _("`x' expected in paper size `%s'."), size);
1051       return 0;
1052     }
1053   *v = outp_evaluate_dimension (tail, &tail);
1054   if (tail == NULL)
1055     return 0;
1056   while (isspace ((unsigned char) *tail))
1057     tail++;
1058   if (*tail)
1059     {
1060       msg (SE, _("Trailing garbage `%s' on paper size `%s'."), tail, size);
1061       return 0;
1062     }
1063   
1064   return 1;
1065 }
1066
1067 /* Stores the dimensions, in 1/72000" units, of paper identified by
1068    SIZE into *H and *V.  SIZE may be a pair of dimensions of form `H x
1069    V', or it may be a case-insensitive paper identifier, which is
1070    looked up in the `papersize' configuration file.  Returns nonzero
1071    on success.  May modify SIZE. */
1072 /* Don't read further unless you've got a strong stomach. */
1073 int
1074 outp_get_paper_size (char *size, int *h, int *v)
1075 {
1076   struct paper_size
1077     {
1078       char *name;
1079       int use;
1080       int h, v;
1081     };
1082
1083   static struct paper_size cache[4];
1084   static int use;
1085
1086   FILE *f;
1087   char *pprsz_fn;
1088
1089   struct string line;
1090   struct file_locator where;
1091
1092   int free_it = 0;
1093   int result = 0;
1094   int min_value, min_index;
1095   char *ep;
1096   int i;
1097
1098   while (isspace ((unsigned char) *size))
1099     size++;
1100   if (isdigit ((unsigned char) *size))
1101     return internal_get_paper_size (size, h, v);
1102   ep = size;
1103   while (*ep)
1104     ep++;
1105   while (isspace ((unsigned char) *ep) && ep >= size)
1106     ep--;
1107   if (ep == size)
1108     {
1109       msg (SE, _("Paper size name must not be empty."));
1110       return 0;
1111     }
1112   
1113   ep++;
1114   if (*ep)
1115     *ep = 0;
1116
1117   use++;
1118   for (i = 0; i < 4; i++)
1119     if (cache[i].name != NULL && !strcasecmp (cache[i].name, size))
1120       {
1121         *h = cache[i].h;
1122         *v = cache[i].v;
1123         cache[i].use = use;
1124         return 1;
1125       }
1126
1127   pprsz_fn = fn_search_path (fn_getenv_default ("STAT_OUTPUT_PAPERSIZE_FILE",
1128                                                 "papersize"),
1129                              fn_getenv_default ("STAT_OUTPUT_INIT_PATH",
1130                                                 config_path),
1131                              NULL);
1132
1133   where.filename = pprsz_fn;
1134   where.line_number = 0;
1135   err_push_file_locator (&where);
1136   ds_init (&line, 128);
1137
1138   if (pprsz_fn == NULL)
1139     {
1140       msg (IE, _("Cannot find `papersize' configuration file."));
1141       goto exit;
1142     }
1143
1144   msg (VM (1), _("%s: Opening paper size definition file..."), pprsz_fn);
1145   f = fopen (pprsz_fn, "r");
1146   if (!f)
1147     {
1148       msg (IE, _("Opening %s: %s."), pprsz_fn, strerror (errno));
1149       goto exit;
1150     }
1151
1152   for (;;)
1153     {
1154       char *cp, *bp, *ep;
1155
1156       if (!ds_get_config_line (f, &line, &where.line_number))
1157         {
1158           if (ferror (f))
1159             msg (ME, _("Reading %s: %s."), pprsz_fn, strerror (errno));
1160           break;
1161         }
1162       for (cp = ds_c_str (&line); isspace ((unsigned char) *cp); cp++);
1163       if (*cp == 0)
1164         continue;
1165       if (*cp != '"')
1166         goto lex_error;
1167       for (bp = ep = cp + 1; *ep && *ep != '"'; ep++);
1168       if (!*ep)
1169         goto lex_error;
1170       *ep = 0;
1171       if (0 != strcasecmp (bp, size))
1172         continue;
1173
1174       for (cp = ep + 1; isspace ((unsigned char) *cp); cp++);
1175       if (*cp == '=')
1176         {
1177           size = xmalloc (ep - bp + 1);
1178           strcpy (size, bp);
1179           free_it = 1;
1180           continue;
1181         }
1182       size = &ep[1];
1183       break;
1184
1185     lex_error:
1186       msg (IE, _("Syntax error in paper size definition."));
1187     }
1188
1189   /* We found the one we want! */
1190   result = internal_get_paper_size (size, h, v);
1191   if (result)
1192     {
1193       min_value = cache[0].use;
1194       min_index = 0;
1195       for (i = 1; i < 4; i++)
1196         if (cache[0].use < min_value)
1197           {
1198             min_value = cache[i].use;
1199             min_index = i;
1200           }
1201       free (cache[min_index].name);
1202       cache[min_index].name = xstrdup (size);
1203       cache[min_index].use = use;
1204       cache[min_index].h = *h;
1205       cache[min_index].v = *v;
1206     }
1207
1208 exit:
1209   err_pop_file_locator (&where);
1210   ds_destroy (&line);
1211   if (free_it)
1212     free (size);
1213
1214   if (result)
1215     msg (VM (2), _("Paper size definition file read successfully."));
1216   else
1217     msg (VM (1), _("Error reading paper size definition file."));
1218   
1219   return result;
1220 }
1221
1222 /* If D is NULL, returns the first enabled driver if any, NULL if
1223    none.  Otherwise D must be the last driver returned by this
1224    function, in which case the next enabled driver is returned or NULL
1225    if that was the last. */
1226 struct outp_driver *
1227 outp_drivers (struct outp_driver *d)
1228 {
1229 #if DEBUGGING
1230   struct outp_driver *orig_d = d;
1231 #endif
1232
1233   for (;;)
1234     {
1235       if (d == NULL)
1236         d = outp_driver_list;
1237       else
1238         d = d->next;
1239
1240       if (d == NULL
1241           || (d->driver_open
1242               && (d->device == 0
1243                   || (d->device & disabled_devices) != d->device)))
1244         break;
1245     }
1246
1247   return d;
1248 }
1249
1250 /* Enables (if ENABLE is nonzero) or disables (if ENABLE is zero) the
1251    device(s) given in mask DEVICE. */
1252 void
1253 outp_enable_device (int enable, int device)
1254 {
1255   if (enable)
1256     disabled_devices &= ~device;
1257   else
1258     disabled_devices |= device;
1259 }
1260
1261 /* Ejects the paper on device D, if the page is not blank. */
1262 int
1263 outp_eject_page (struct outp_driver *d)
1264 {
1265   if (d->page_open == 0)
1266     return 1;
1267   
1268   if (d->cp_y != 0)
1269     {
1270       d->cp_x = d->cp_y = 0;
1271
1272       if (d->class->close_page (d) == 0)
1273         msg (ME, _("Error closing page on %s device of %s class."),
1274              d->name, d->class->name);
1275       if (d->class->open_page (d) == 0)
1276         {
1277           msg (ME, _("Error opening page on %s device of %s class."),
1278                d->name, d->class->name);
1279           return 0;
1280         }
1281     }
1282   return 1;
1283 }
1284
1285 /* Returns the width of string S, in device units, when output on
1286    device D. */
1287 int
1288 outp_string_width (struct outp_driver *d, const char *s)
1289 {
1290   struct outp_text text;
1291
1292   text.options = OUTP_T_JUST_LEFT;
1293   ls_init (&text.s, (char *) s, strlen (s));
1294   d->class->text_metrics (d, &text);
1295
1296   return text.h;
1297 }