More constness/namespace policing
[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 <stdlib.h>
23 #include <stdio.h>
24 #include <errno.h>
25 #include <ctype.h>
26 #include <libpspp/alloc.h>
27 #include <data/file-name.h>
28 #include "htmlP.h"
29 #include "intprops.h"
30 #include <libpspp/misc.h>
31 #include <data/settings.h>
32 #include <libpspp/str.h>
33 #include "error.h"
34
35 #include "gettext.h"
36 #define _(msgid) gettext (msgid)
37
38 /* FIXME? Should the output configuration format be changed to
39    drivername:classname:devicetype:options, where devicetype is zero
40    or more of screen, printer, listing? */
41
42 /* FIXME: Have the reentrancy problems been solved? */
43
44 /* Where the output driver name came from. */
45 enum
46   {
47     OUTP_S_COMMAND_LINE,        /* Specified by the user. */
48     OUTP_S_INIT_FILE            /* `default' or the init file. */
49   };
50
51 /* Names the output drivers to be used. */
52 struct outp_names
53   {
54     char *name;                 /* Name of the output driver. */
55     int source;                 /* OUTP_S_* */
56     struct outp_names *next, *prev;
57   };
58
59 /* Defines an init file macro. */
60 struct outp_defn
61   {
62     char *key;
63     struct string value;
64     struct outp_defn *next, *prev;
65   };
66
67 static struct outp_defn *outp_macros;
68 static struct outp_names *outp_configure_vec;
69
70 /* A list of driver classes. */
71 struct outp_driver_class_list
72   {
73     const struct outp_class *class;
74     struct outp_driver_class_list *next;
75   };
76
77 static struct outp_driver_class_list *outp_class_list;
78 static struct outp_driver *outp_driver_list;
79
80 char *outp_title;
81 char *outp_subtitle;
82
83 /* A set of OUTP_DEV_* bits indicating the devices that are
84    disabled. */
85 static int disabled_devices;
86
87 static void destroy_driver (struct outp_driver *);
88 static void configure_driver_line (struct substring);
89 static void configure_driver (const struct substring, const struct substring,
90                               const struct substring, const struct substring);
91
92 /* Add a class to the class list. */
93 static void
94 add_class (const struct outp_class *class)
95 {
96   struct outp_driver_class_list *new_list = xmalloc (sizeof *new_list);
97
98   new_list->class = class;
99
100   if (!outp_class_list)
101     {
102       outp_class_list = new_list;
103       new_list->next = NULL;
104     }
105   else
106     {
107       new_list->next = outp_class_list;
108       outp_class_list = new_list;
109     }
110 }
111
112 /* Finds the outp_names in outp_configure_vec with name between BP and
113    EP exclusive. */
114 static struct outp_names *
115 search_names (char *bp, char *ep)
116 {
117   struct outp_names *n;
118
119   for (n = outp_configure_vec; n; n = n->next)
120     if ((int) strlen (n->name) == ep - bp && !memcmp (n->name, bp, ep - bp))
121       return n;
122   return NULL;
123 }
124
125 /* Deletes outp_names NAME from outp_configure_vec. */
126 static void
127 delete_name (struct outp_names * n)
128 {
129   free (n->name);
130   if (n->prev)
131     n->prev->next = n->next;
132   if (n->next)
133     n->next->prev = n->prev;
134   if (n == outp_configure_vec)
135     outp_configure_vec = n->next;
136   free (n);
137 }
138
139 /* Adds the name between BP and EP exclusive to list
140    outp_configure_vec with source SOURCE. */
141 static void
142 add_name (char *bp, char *ep, int source)
143 {
144   struct outp_names *n = xmalloc (sizeof *n);
145   n->name = xmalloc (ep - bp + 1);
146   memcpy (n->name, bp, ep - bp);
147   n->name[ep - bp] = 0;
148   n->source = source;
149   n->next = outp_configure_vec;
150   n->prev = NULL;
151   if (outp_configure_vec)
152     outp_configure_vec->prev = n;
153   outp_configure_vec = n;
154 }
155
156 /* Checks that outp_configure_vec is empty, bitches & clears it if it
157    isn't. */
158 static void
159 check_configure_vec (void)
160 {
161   struct outp_names *n;
162
163   for (n = outp_configure_vec; n; n = n->next)
164     if (n->source == OUTP_S_COMMAND_LINE)
165       error (0, 0, _("unknown output driver `%s'"), n->name);
166     else
167       error (0, 0, _("output driver `%s' referenced but never defined"),
168              n->name);
169   outp_configure_clear ();
170 }
171
172 /* Searches outp_configure_vec for the name between BP and EP
173    exclusive.  If found, it is deleted, then replaced by the names
174    given in EP+1, if any. */
175 static void
176 expand_name (char *bp, char *ep)
177 {
178   struct outp_names *n = search_names (bp, ep);
179   if (!n)
180     return;
181   delete_name (n);
182
183   bp = ep + 1;
184   for (;;)
185     {
186       while (isspace ((unsigned char) *bp))
187         bp++;
188       ep = bp;
189       while (*ep && !isspace ((unsigned char) *ep))
190         ep++;
191       if (bp == ep)
192         return;
193       if (!search_names (bp, ep))
194         add_name (bp, ep, OUTP_S_INIT_FILE);
195       bp = ep;
196     }
197 }
198
199 /* Looks for a macro with key KEY, and returns the corresponding value
200    if found, or NULL if not. */
201 static const char *
202 find_defn_value (const char *key)
203 {
204   static char buf[INT_STRLEN_BOUND (int) + 1];
205   struct outp_defn *d;
206
207   for (d = outp_macros; d; d = d->next)
208     if (!strcmp (key, d->key))
209       return ds_cstr (&d->value);
210   if (!strcmp (key, "viewwidth"))
211     {
212       sprintf (buf, "%d", get_viewwidth ());
213       return buf;
214     }
215   else if (!strcmp (key, "viewlength"))
216     {
217       sprintf (buf, "%d", get_viewlength ());
218       return buf;
219     }
220   else
221     return getenv (key);
222 }
223
224 /* Initializes global variables. */
225 void
226 outp_init (void)
227 {
228   extern struct outp_class ascii_class;
229   extern struct outp_class postscript_class;
230
231   char def[] = "default";
232
233   add_class (&html_class);
234   add_class (&postscript_class);
235   add_class (&ascii_class);
236
237   add_name (def, &def[strlen (def)], OUTP_S_INIT_FILE);
238 }
239
240 /* Deletes all the output macros. */
241 static void
242 delete_macros (void)
243 {
244   struct outp_defn *d, *next;
245
246   for (d = outp_macros; d; d = next)
247     {
248       next = d->next;
249       free (d->key);
250       ds_destroy (&d->value);
251       free (d);
252     }
253 }
254
255 static void
256 init_default_drivers (void) 
257 {
258   error (0, 0, _("using default output driver configuration"));
259   configure_driver (ss_cstr ("list"),
260                     ss_cstr ("ascii"),
261                     ss_cstr ("listing"),
262                     ss_cstr ("length=66 width=79 output-file=\"pspp.list\""));
263 }
264
265 /* Reads the initialization file; initializes
266    outp_driver_list. */
267 void
268 outp_read_devices (void)
269 {
270   int result = 0;
271
272   char *init_fn;
273
274   FILE *f = NULL;
275   struct string line;
276   int line_number;
277
278   init_fn = fn_search_path (fn_getenv_default ("STAT_OUTPUT_INIT_FILE",
279                                                "devices"),
280                             fn_getenv_default ("STAT_OUTPUT_INIT_PATH",
281                                                config_path),
282                             NULL);
283
284   ds_init_empty (&line);
285
286   if (init_fn == NULL)
287     {
288       error (0, 0, _("cannot find output initialization file "
289                      "(use `-vv' to view search path)"));
290       goto exit;
291     }
292
293   f = fopen (init_fn, "r");
294   if (f == NULL)
295     {
296       error (0, errno, _("cannot open \"%s\""), init_fn);
297       goto exit;
298     }
299
300   line_number = 0;
301   for (;;)
302     {
303       char *cp;
304
305       if (!ds_read_config_line (&line, &line_number, f))
306         {
307           if (ferror (f))
308             error (0, errno, _("reading \"%s\""), init_fn);
309           break;
310         }
311       for (cp = ds_cstr (&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 (ds_ss (&line));
326                   delete_name (n);
327                 }
328             }
329           else
330             error_at_line (0, 0, init_fn, line_number, _("syntax error"));
331         }
332     }
333   result = 1;
334
335   check_configure_vec ();
336
337 exit:
338   if (f && -1 == fclose (f))
339     error (0, errno, _("error closing \"%s\""), init_fn);
340   free (init_fn);
341   ds_destroy (&line);
342   delete_macros ();
343
344   if (result) 
345     {
346       if (outp_driver_list == NULL) 
347         error (0, 0, _("no active output drivers")); 
348     }
349   else
350     error (0, 0, _("error reading device definition file"));
351
352   if (!result || outp_driver_list == NULL)
353     init_default_drivers ();
354 }
355
356 /* Clear the list of drivers to configure. */
357 void
358 outp_configure_clear (void)
359 {
360   struct outp_names *n, *next;
361
362   for (n = outp_configure_vec; n; n = next)
363     {
364       next = n->next;
365       free (n->name);
366       free (n);
367     }
368   outp_configure_vec = NULL;
369 }
370
371 /* Adds the name BP to the list of drivers to configure into
372    outp_driver_list. */
373 void
374 outp_configure_add (char *bp)
375 {
376   char *ep = &bp[strlen (bp)];
377   if (!search_names (bp, ep))
378     add_name (bp, ep, OUTP_S_COMMAND_LINE);
379 }
380
381 /* Defines one configuration macro based on the text in BP, which
382    should be of the form `KEY=VALUE'. */
383 void
384 outp_configure_macro (char *bp)
385 {
386   struct outp_defn *d;
387   char *ep;
388
389   while (isspace ((unsigned char) *bp))
390     bp++;
391   ep = bp;
392   while (*ep && !isspace ((unsigned char) *ep) && *ep != '=')
393     ep++;
394
395   d = xmalloc (sizeof *d);
396   d->key = xmalloc (ep - bp + 1);
397   memcpy (d->key, bp, ep - bp);
398   d->key[ep - bp] = 0;
399
400   /* Earlier definitions for a particular KEY override later ones. */
401   if (find_defn_value (d->key))
402     {
403       free (d->key);
404       free (d);
405       return;
406     }
407   
408   if (*ep == '=')
409     ep++;
410   while (isspace ((unsigned char) *ep))
411     ep++;
412
413   ds_init_cstr (&d->value, ep);
414   fn_interp_vars (ds_ss (&d->value), find_defn_value, &d->value);
415   d->next = outp_macros;
416   d->prev = NULL;
417   if (outp_macros)
418     outp_macros->prev = d;
419   outp_macros = d;
420 }
421
422 /* Destroys all the drivers in driver list *DL and sets *DL to
423    NULL. */
424 static void
425 destroy_list (struct outp_driver ** dl)
426 {
427   struct outp_driver *d, *next;
428
429   for (d = *dl; d; d = next)
430     {
431       destroy_driver (d);
432       next = d->next;
433       free (d);
434     }
435   *dl = NULL;
436 }
437
438 /* Closes all the output drivers. */
439 void
440 outp_done (void)
441 {
442   struct outp_driver_class_list *n = outp_class_list ; 
443   destroy_list (&outp_driver_list);
444
445   while (n) 
446     {
447       struct outp_driver_class_list *next = n->next;
448       free(n);
449       n = next;
450     }
451   outp_class_list = NULL;
452
453   free (outp_title);
454   outp_title = NULL;
455   
456   free (outp_subtitle);
457   outp_subtitle = NULL;
458 }
459
460 /* Display on stdout a list of all registered driver classes. */
461 void
462 outp_list_classes (void)
463 {
464   int width = get_viewwidth();
465   struct outp_driver_class_list *c;
466
467   printf (_("Driver classes:\n\t"));
468   width -= 8;
469   for (c = outp_class_list; c; c = c->next)
470     {
471       if ((int) strlen (c->class->name) + 1 > width)
472         {
473           printf ("\n\t");
474           width = get_viewwidth() - 8;
475         }
476       else
477         putc (' ', stdout);
478       fputs (c->class->name, stdout);
479     }
480   putc('\n', stdout);
481 }
482
483 /* Obtains a token from S and advances its position.  Errors are
484    reported against the given DRIVER_NAME.
485    The token is stored in TOKEN.  Returns true if successful,
486    false on syntax error.
487
488    Caller is responsible for skipping leading spaces. */
489 static bool
490 get_option_token (struct substring *s, const char *driver_name,
491                   struct string *token)
492 {
493   int c;
494   
495   ds_clear (token);
496   c = ss_get_char (s);
497   if (c == EOF)
498     {
499       error (0, 0, _("syntax error parsing options for \"%s\" driver"),
500              driver_name);
501       return false;
502     }
503   else if (c == '\'' || c == '"')
504     {
505       int quote = c;
506
507       for (;;)
508         {
509           c = ss_get_char (s);
510           if (c == quote)
511             break;
512           else if (c == EOF) 
513             {
514               error (0, 0,
515                      _("reached end of options inside quoted string "
516                        "parsing options for \"%s\" driver"),
517                      driver_name);
518               return false;
519             }
520           else if (c != '\\')
521             ds_put_char (token, c);
522           else
523             {
524               int out;
525
526               c = ss_get_char (s);
527               switch (c)
528                 {
529                 case '\'':
530                   out = '\'';
531                   break;
532                 case '"':
533                   out = '"';
534                   break;
535                 case '\\':
536                   out = '\\';
537                   break;
538                 case 'a':
539                   out = '\a';
540                   break;
541                 case 'b':
542                   out = '\b';
543                   break;
544                 case 'f':
545                   out = '\f';
546                   break;
547                 case 'n':
548                   out = '\n';
549                   break;
550                 case 'r':
551                   out = '\r';
552                   break;
553                 case 't':
554                   out = '\t';
555                   break;
556                 case 'v':
557                   out = '\v';
558                   break;
559                 case '0':
560                 case '1':
561                 case '2':
562                 case '3':
563                 case '4':
564                 case '5':
565                 case '6':
566                 case '7':
567                   out = c - '0';
568                   while (ss_first (*s) >= '0' && ss_first (*s) <= '7')
569                     out = c * 8 + (ss_get_char (s) - '0');
570                   break;
571                 case 'x':
572                 case 'X':
573                   out = 0;
574                   while (isxdigit (ss_first (*s)))
575                     {
576                       c = ss_get_char (s);
577                       out *= 16;
578                       if (isdigit (c))
579                         out += c - '0';
580                       else
581                         out += tolower (c) - 'a' + 10;
582                     }
583                   break;
584                 default:
585                   error (0, 0, _("syntax error in string constant "
586                                  "parsing options for \"%s\" driver"),
587                          driver_name);
588                   return false;
589                 }
590               ds_put_char (token, out);
591             }
592         }
593     }
594   else 
595     {
596       for (;;)
597         {
598           ds_put_char (token, c);
599
600           c = ss_first (*s);
601           if (c == EOF || c == '=' || isspace (c))
602             break;
603           ss_advance (s, 1);
604         }
605     }
606   
607   return 1;
608 }
609
610 bool
611 outp_parse_options (struct substring options,
612                     bool (*callback) (struct outp_driver *, const char *key,
613                                       const struct string *value),
614                     struct outp_driver *driver)
615 {
616   struct string key = DS_EMPTY_INITIALIZER;
617   struct string value = DS_EMPTY_INITIALIZER;
618   struct substring left = options;
619   bool ok = true;
620
621   do
622     {
623       ss_ltrim (&left, ss_cstr (CC_SPACES));
624       if (ss_is_empty (left))
625         break;
626       
627       if (!get_option_token (&left, driver->name, &key))
628         break;
629
630       ss_ltrim (&left, ss_cstr (CC_SPACES));
631       if (!ss_match_char (&left, '='))
632         {
633           error (0, 0, _("syntax error expecting `=' "
634                          "parsing options for driver \"%s\""),
635                  driver->name);
636           break;
637         }
638
639       ss_ltrim (&left, ss_cstr (CC_SPACES));
640       if (!get_option_token (&left, driver->name, &value))
641         break;
642
643       ok = callback (driver, ds_cstr (&key), &value);
644     }
645   while (ok);
646   
647   ds_destroy (&key);
648   ds_destroy (&value);
649
650   return ok;
651 }
652
653 /* Find the driver in outp_driver_list with name NAME. */
654 static struct outp_driver *
655 find_driver (char *name)
656 {
657   struct outp_driver *d;
658
659   for (d = outp_driver_list; d; d = d->next)
660     if (!strcmp (d->name, name))
661       return d;
662   return NULL;
663 }
664
665 /* Adds a driver to outp_driver_list pursuant to the
666    specification provided.  */
667 static void
668 configure_driver (struct substring driver_name, struct substring class_name,
669                   struct substring device_type, struct substring options)
670 {
671   struct outp_driver *d, *iter;
672   struct outp_driver_class_list *c;
673
674   struct substring token;
675   size_t save_idx = 0;
676   int device;
677
678   /* Find class. */
679   for (c = outp_class_list; c; c = c->next)
680     if (!ss_compare (ss_cstr (c->class->name), class_name))
681       break;
682   if (c == NULL)
683     {
684       error (0, 0, _("unknown output driver class `%.*s'"),
685              (int) ss_length (class_name), ss_data (class_name));
686       return;
687     }
688   
689   /* Parse device type. */
690   device = 0;
691   while (ss_tokenize (device_type, ss_cstr (CC_SPACES), &save_idx, &token))
692     if (!ss_compare (token, ss_cstr ("listing")))
693       device |= OUTP_DEV_LISTING;
694     else if (!ss_compare (token, ss_cstr ("screen")))
695       device |= OUTP_DEV_SCREEN;
696     else if (!ss_compare (token, ss_cstr ("printer")))
697       device |= OUTP_DEV_PRINTER;
698     else
699       error (0, 0, _("unknown device type `%.*s'"),
700              (int) ss_length (token), ss_data (token));
701
702   /* Open the device. */
703   d = xmalloc (sizeof *d);
704   d->next = d->prev = NULL;
705   d->class = c->class;
706   d->name = ss_xstrdup (driver_name);
707   d->page_open = false;
708   d->device = OUTP_DEV_NONE;
709   d->cp_x = d->cp_y = 0;
710   d->ext = NULL;
711   d->prc = NULL;
712
713   /* Open driver. */
714   if (!d->class->open_driver (d, options))
715     {
716       error (0, 0, _("cannot initialize output driver `%s' of class `%s'"),
717              d->name, d->class->name);
718       free (d->name);
719       free (d);
720       return;
721     }
722
723   /* Find like-named driver and delete. */
724   iter = find_driver (d->name);
725   if (iter != NULL)
726     destroy_driver (iter);
727
728   /* Add to list. */
729   d->next = outp_driver_list;
730   d->prev = NULL;
731   if (outp_driver_list != NULL)
732     outp_driver_list->prev = d;
733   outp_driver_list = d;
734 }
735
736 /* String LINE is in format:
737    DRIVERNAME:CLASSNAME:DEVICETYPE:OPTIONS
738    Adds a driver to outp_driver_list pursuant to the specification
739    provided.  */
740 static void
741 configure_driver_line (struct substring line_)
742 {
743   struct string line = DS_EMPTY_INITIALIZER;
744   struct substring tokens[4];
745   size_t save_idx;
746   size_t i;
747
748   fn_interp_vars (line_, find_defn_value, &line);
749
750   save_idx = 0;
751   for (i = 0; i < 4; i++) 
752     {
753       struct substring *token = &tokens[i];
754       ds_separate (&line, ss_cstr (i < 3 ? ":" : ""), &save_idx, token);
755       ss_trim (token, ss_cstr (CC_SPACES));
756     }
757
758   if (!ss_is_empty (tokens[0]) && !ss_is_empty (tokens[1]))
759     configure_driver (tokens[0], tokens[1], tokens[2], tokens[3]);
760   else
761     error (0, 0,
762            _("driver definition line missing driver name or class name"));
763
764   ds_destroy (&line);
765 }
766
767 /* Destroys output driver D. */
768 static void
769 destroy_driver (struct outp_driver *d)
770 {
771   outp_close_page (d);
772   if (d->class)
773     {
774       struct outp_driver_class_list *c;
775
776       d->class->close_driver (d);
777
778       for (c = outp_class_list; c; c = c->next)
779         if (c->class == d->class)
780           break;
781       assert (c != NULL);
782     }
783   free (d->name);
784
785   /* Remove this driver from the global driver list. */
786   if (d->prev)
787     d->prev->next = d->next;
788   if (d->next)
789     d->next->prev = d->prev;
790   if (d == outp_driver_list)
791     outp_driver_list = d->next;
792 }
793
794 /* Tries to match S as one of the keywords in TAB, with
795    corresponding information structure INFO.  Returns category
796    code and stores subcategory in *SUBCAT on success.  Returns -1
797    on failure. */
798 int
799 outp_match_keyword (const char *s, const struct outp_option *tab, int *subcat)
800 {
801   for (; tab->keyword != NULL; tab++)
802     if (!strcmp (s, tab->keyword))
803       {
804         *subcat = tab->subcat;
805         return tab->cat;
806       }
807   return -1;
808 }
809
810 /* Encapsulate two characters in a single int. */
811 #define TWO_CHARS(A, B)                         \
812         ((A) + ((B)<<8))
813
814 /* Determines the size of a dimensional measurement and returns the
815    size in units of 1/72000".  Units if not specified explicitly are
816    inches for values under 50, millimeters otherwise.  Returns 0,
817    stores NULL to *TAIL on error; otherwise returns dimension, stores
818    address of next */
819 int
820 outp_evaluate_dimension (char *dimen, char **tail)
821 {
822   char *s = dimen;
823   char *ptail;
824   double value;
825
826   value = strtod (s, &ptail);
827   if (ptail == s)
828     goto lossage;
829   if (*ptail == '-')
830     {
831       double b, c;
832       s = &ptail[1];
833       b = strtod (s, &ptail);
834       if (b <= 0.0 || ptail == s)
835         goto lossage;
836       if (*ptail != '/')
837         goto lossage;
838       s = &ptail[1];
839       c = strtod (s, &ptail);
840       if (c <= 0.0 || ptail == s)
841         goto lossage;
842       s = ptail;
843       if (c == 0.0)
844         goto lossage;
845       if (value > 0)
846         value += b / c;
847       else
848         value -= b / c;
849     }
850   else if (*ptail == '/')
851     {
852       double b;
853       s = &ptail[1];
854       b = strtod (s, &ptail);
855       if (b <= 0.0 || ptail == s)
856         goto lossage;
857       s = ptail;
858       value /= b;
859     }
860   else
861     s = ptail;
862   if (*s == 0 || isspace ((unsigned char) *s))
863     {
864       if (value < 50.0)
865         value *= 72000;
866       else
867         value *= 72000 / 25.4;
868     }
869   else
870     {
871       double factor;
872
873       /* Standard TeX units are supported. */
874       if (*s == '"')
875         factor = 72000, s++;
876       else
877         switch (TWO_CHARS (s[0], s[1]))
878           {
879           case TWO_CHARS ('p', 't'):
880             factor = 72000 / 72.27;
881             break;
882           case TWO_CHARS ('p', 'c'):
883             factor = 72000 / 72.27 * 12.0;
884             break;
885           case TWO_CHARS ('i', 'n'):
886             factor = 72000;
887             break;
888           case TWO_CHARS ('b', 'p'):
889             factor = 72000 / 72.0;
890             break;
891           case TWO_CHARS ('c', 'm'):
892             factor = 72000 / 2.54;
893             break;
894           case TWO_CHARS ('m', 'm'):
895             factor = 72000 / 25.4;
896             break;
897           case TWO_CHARS ('d', 'd'):
898             factor = 72000 / 72.27 * 1.0700086;
899             break;
900           case TWO_CHARS ('c', 'c'):
901             factor = 72000 / 72.27 * 12.840104;
902             break;
903           case TWO_CHARS ('s', 'p'):
904             factor = 72000 / 72.27 / 65536.0;
905             break;
906           default:
907             error (0, 0,
908                    _("unit \"%s\" is unknown in dimension \"%s\""), s, dimen);
909             *tail = NULL;
910             return 0;
911           }
912       ptail += 2;
913       value *= factor;
914     }
915   if (value <= 0.0)
916     goto lossage;
917   if (tail)
918     *tail = ptail;
919   return value + 0.5;
920
921 lossage:
922   *tail = NULL;
923   error (0, 0, _("bad dimension \"%s\""), dimen);
924   return 0;
925 }
926
927 /* Stores the dimensions in 1/72000" units of paper identified by
928    SIZE, which is of form `HORZ x VERT' or `HORZ by VERT' where each
929    of HORZ and VERT are dimensions, into *H and *V.  Return true on
930    success. */
931 static bool
932 internal_get_paper_size (char *size, int *h, int *v)
933 {
934   char *tail;
935
936   while (isspace ((unsigned char) *size))
937     size++;
938   *h = outp_evaluate_dimension (size, &tail);
939   if (tail == NULL)
940     return false;
941   while (isspace ((unsigned char) *tail))
942     tail++;
943   if (*tail == 'x')
944     tail++;
945   else if (*tail == 'b' && tail[1] == 'y')
946     tail += 2;
947   else
948     {
949       error (0, 0, _("`x' expected in paper size `%s'"), size);
950       return false;
951     }
952   *v = outp_evaluate_dimension (tail, &tail);
953   if (tail == NULL)
954     return 0;
955   while (isspace ((unsigned char) *tail))
956     tail++;
957   if (*tail)
958     {
959       error (0, 0, _("trailing garbage `%s' on paper size `%s'"), tail, size);
960       return false;
961     }
962   
963   return true;
964 }
965
966 /* Stores the dimensions, in 1/72000" units, of paper identified by
967    SIZE into *H and *V.  SIZE may be a pair of dimensions of form `H x
968    V', or it may be a case-insensitive paper identifier, which is
969    looked up in the `papersize' configuration file.  Returns true
970    on success.  May modify SIZE. */
971 /* Don't read further unless you've got a strong stomach. */
972 bool
973 outp_get_paper_size (char *size, int *h, int *v)
974 {
975   struct paper_size
976     {
977       char *name;
978       int use;
979       int h, v;
980     };
981
982   FILE *f;
983   char *pprsz_fn;
984
985   struct string line;
986   int line_number = 0;
987
988   bool free_it = false;
989   bool result = false;
990   char *ep;
991
992   while (isspace ((unsigned char) *size))
993     size++;
994   if (isdigit ((unsigned char) *size))
995     return internal_get_paper_size (size, h, v);
996   ep = size;
997   while (*ep)
998     ep++;
999   while (isspace ((unsigned char) *ep) && ep >= size)
1000     ep--;
1001   if (ep == size)
1002     {
1003       error (0, 0, _("paper size name cannot be empty"));
1004       return 0;
1005     }
1006   
1007   ep++;
1008   if (*ep)
1009     *ep = 0;
1010
1011   pprsz_fn = fn_search_path (fn_getenv_default ("STAT_OUTPUT_PAPERSIZE_FILE",
1012                                                 "papersize"),
1013                              fn_getenv_default ("STAT_OUTPUT_INIT_PATH",
1014                                                 config_path),
1015                              NULL);
1016
1017   ds_init_empty (&line);
1018
1019   if (pprsz_fn == NULL)
1020     {
1021       error (0, 0, _("cannot find `papersize' configuration file"));
1022       goto exit;
1023     }
1024
1025   f = fopen (pprsz_fn, "r");
1026   if (!f)
1027     {
1028       error (0, errno, _("error opening \"%s\""), pprsz_fn);
1029       goto exit;
1030     }
1031
1032   for (;;)
1033     {
1034       struct substring p, name;
1035
1036       if (!ds_read_config_line (&line, &line_number, f))
1037         {
1038           if (ferror (f))
1039             error (0, errno, _("error reading \"%s\""), pprsz_fn);
1040           break;
1041         }
1042
1043       p = ds_ss (&line);
1044       ss_ltrim (&p, ss_cstr (CC_SPACES));
1045       if (!ss_match_char (&p, '"') || !ss_get_until (&p, '"', &name))
1046         goto lex_error;
1047       if (ss_compare (name, ss_cstr (size)))
1048         continue;
1049
1050       ss_ltrim (&p, ss_cstr (CC_SPACES));
1051       if (ss_match_char (&p, '='))
1052         {
1053           if (free_it)
1054             free (size);
1055           ss_trim (&p, ss_cstr (CC_SPACES));
1056           size = ss_xstrdup (p);
1057           free_it = true;
1058           continue;
1059         }
1060       size = ss_data (p);
1061       break;
1062
1063     lex_error:
1064       error_at_line (0, 0, pprsz_fn, line_number,
1065                      _("syntax error in paper size definition"));
1066     }
1067
1068   /* We found the one we want! */
1069   result = internal_get_paper_size (size, h, v);
1070
1071 exit:
1072   ds_destroy (&line);
1073   if (free_it)
1074     free (size);
1075
1076   if (!result)
1077     error (0, 0, _("error reading paper size definition file"));
1078   
1079   return result;
1080 }
1081
1082 /* If D is NULL, returns the first enabled driver if any, NULL if
1083    none.  Otherwise D must be the last driver returned by this
1084    function, in which case the next enabled driver is returned or NULL
1085    if that was the last. */
1086 struct outp_driver *
1087 outp_drivers (struct outp_driver *d)
1088 {
1089   for (;;)
1090     {
1091       if (d == NULL)
1092         d = outp_driver_list;
1093       else
1094         d = d->next;
1095
1096       if (d == NULL
1097           || (d->device == 0 || (d->device & disabled_devices) != d->device))
1098         break;
1099     }
1100
1101   return d;
1102 }
1103
1104 /* Enables (if ENABLE is nonzero) or disables (if ENABLE is zero) the
1105    device(s) given in mask DEVICE. */
1106 void
1107 outp_enable_device (int enable, int device)
1108 {
1109   if (enable)
1110     disabled_devices &= ~device;
1111   else
1112     disabled_devices |= device;
1113 }
1114
1115 /* Opens a page on driver D (if one is not open). */
1116 void
1117 outp_open_page (struct outp_driver *d) 
1118 {
1119   if (!d->page_open) 
1120     {
1121       d->cp_x = d->cp_y = 0;
1122
1123       d->page_open = true;
1124       if (d->class->open_page != NULL)
1125         d->class->open_page (d);
1126     }
1127 }
1128
1129 /* Closes the page on driver D (if one is open). */
1130 void
1131 outp_close_page (struct outp_driver *d) 
1132 {
1133   if (d->page_open) 
1134     {
1135       if (d->class->close_page != NULL)
1136         d->class->close_page (d);
1137       d->page_open = false;
1138     }
1139 }
1140
1141 /* Ejects the page on device D, if a page is open and non-blank,
1142    and opens a new page.  */
1143 void
1144 outp_eject_page (struct outp_driver *d)
1145 {
1146   if (d->page_open && d->cp_y != 0)
1147     outp_close_page (d);
1148   outp_open_page (d);
1149 }
1150
1151 /* Returns the width of string S, in device units, when output on
1152    device D. */
1153 int
1154 outp_string_width (struct outp_driver *d, const char *s, enum outp_font font)
1155 {
1156   struct outp_text text;
1157   int width;
1158   
1159   text.font = font;
1160   text.justification = OUTP_LEFT;
1161   text.string = ss_cstr (s);
1162   text.h = text.v = INT_MAX;
1163   d->class->text_metrics (d, &text, &width, NULL);
1164
1165   return width;
1166 }