6082d2490c0e6091477cebd67f1e26f0d8219709
[pspp-builds.git] / src / output / output.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <ctype.h>
20 #include <errno.h>
21 #if HAVE_LC_PAPER
22 #include <langinfo.h>
23 #endif
24 #include <locale.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27
28 #include <data/file-name.h>
29 #include <data/settings.h>
30 #include <libpspp/misc.h>
31 #include <libpspp/str.h>
32 #include <output/htmlP.h>
33 #include <output/output.h>
34
35 #include "error.h"
36 #include "intprops.h"
37 #include "xalloc.h"
38
39 #include "gettext.h"
40 #define _(msgid) gettext (msgid)
41
42 /* Where the output driver name came from. */
43 enum
44   {
45     OUTP_S_COMMAND_LINE,        /* Specified by the user. */
46     OUTP_S_INIT_FILE            /* `default' or the init file. */
47   };
48
49 /* Names the output drivers to be used. */
50 struct outp_names
51   {
52     char *name;                 /* Name of the output driver. */
53     int source;                 /* OUTP_S_* */
54     struct outp_names *next, *prev;
55   };
56
57 /* Defines an init file macro. */
58 struct outp_defn
59   {
60     char *key;
61     struct string value;
62     struct outp_defn *next, *prev;
63   };
64
65 static struct outp_defn *outp_macros;
66 static struct outp_names *outp_configure_vec;
67
68 /* A list of driver classes. */
69 struct outp_driver_class_list
70   {
71     const struct outp_class *class;
72     struct outp_driver_class_list *next;
73   };
74
75 static struct outp_driver_class_list *outp_class_list;
76 static struct ll_list outp_driver_list = LL_INITIALIZER (outp_driver_list);
77
78 char *outp_title;
79 char *outp_subtitle;
80
81 /* A set of OUTP_DEV_* bits indicating the devices that are
82    disabled. */
83 static int disabled_devices;
84
85 static void destroy_driver (struct outp_driver *);
86 static void configure_driver (const struct substring, const struct substring,
87                               const struct substring, const struct substring);
88
89 /* Add a class to the class list. */
90 static void
91 add_class (const struct outp_class *class)
92 {
93   struct outp_driver_class_list *new_list = xmalloc (sizeof *new_list);
94
95   new_list->class = class;
96
97   if (!outp_class_list)
98     {
99       outp_class_list = new_list;
100       new_list->next = NULL;
101     }
102   else
103     {
104       new_list->next = outp_class_list;
105       outp_class_list = new_list;
106     }
107 }
108
109 /* Finds the outp_names in outp_configure_vec with name between BP and
110    EP exclusive. */
111 static struct outp_names *
112 search_names (char *bp, char *ep)
113 {
114   struct outp_names *n;
115
116   for (n = outp_configure_vec; n; n = n->next)
117     if ((int) strlen (n->name) == ep - bp && !memcmp (n->name, bp, ep - bp))
118       return n;
119   return NULL;
120 }
121
122 /* Deletes outp_names NAME from outp_configure_vec. */
123 static void
124 delete_name (struct outp_names * n)
125 {
126   free (n->name);
127   if (n->prev)
128     n->prev->next = n->next;
129   if (n->next)
130     n->next->prev = n->prev;
131   if (n == outp_configure_vec)
132     outp_configure_vec = n->next;
133   free (n);
134 }
135
136 /* Adds the name between BP and EP exclusive to list
137    outp_configure_vec with source SOURCE. */
138 static void
139 add_name (char *bp, char *ep, int source)
140 {
141   struct outp_names *n = xmalloc (sizeof *n);
142   n->name = xmalloc (ep - bp + 1);
143   memcpy (n->name, bp, ep - bp);
144   n->name[ep - bp] = 0;
145   n->source = source;
146   n->next = outp_configure_vec;
147   n->prev = NULL;
148   if (outp_configure_vec)
149     outp_configure_vec->prev = n;
150   outp_configure_vec = n;
151 }
152
153 /* Checks that outp_configure_vec is empty, complains and clears
154    it if it isn't. */
155 static void
156 check_configure_vec (void)
157 {
158   struct outp_names *n;
159
160   for (n = outp_configure_vec; n; n = n->next)
161     if (n->source == OUTP_S_COMMAND_LINE)
162       error (0, 0, _("unknown output driver `%s'"), n->name);
163     else
164       error (0, 0, _("output driver `%s' referenced but never defined"),
165              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_STRLEN_BOUND (int) + 1];
202   struct outp_defn *d;
203
204   for (d = outp_macros; d; d = d->next)
205     if (!strcmp (key, d->key))
206       return ds_cstr (&d->value);
207   if (!strcmp (key, "viewwidth"))
208     {
209       sprintf (buf, "%d", settings_get_viewwidth ());
210       return buf;
211     }
212   else if (!strcmp (key, "viewlength"))
213     {
214       sprintf (buf, "%d", settings_get_viewlength ());
215       return buf;
216     }
217   else
218     return getenv (key);
219 }
220
221 /* Initializes global variables. */
222 void
223 outp_init (void)
224 {
225   char def[] = "default";
226
227   add_class (&html_class);
228   add_class (&postscript_class);
229   add_class (&ascii_class);
230 #ifdef HAVE_CAIRO
231   add_class (&cairo_class);
232 #endif
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   error (0, 0, _("using default output driver configuration"));
256   configure_driver (ss_cstr ("list"),
257                     ss_cstr ("ascii"),
258                     ss_cstr ("listing"),
259                     ss_cstr ("length=66 width=79 output-file=\"pspp.list\""));
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   int line_number;
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
280   ds_init_empty (&line);
281
282   if (init_fn == NULL)
283     {
284       error (0, 0, _("cannot find output initialization file "
285                      "(use `-vv' to view search path)"));
286       goto exit;
287     }
288
289   f = fopen (init_fn, "r");
290   if (f == NULL)
291     {
292       error (0, errno, _("cannot open \"%s\""), init_fn);
293       goto exit;
294     }
295
296   line_number = 0;
297   for (;;)
298     {
299       char *cp;
300
301       if (!ds_read_config_line (&line, &line_number, f))
302         {
303           if (ferror (f))
304             error (0, errno, _("reading \"%s\""), init_fn);
305           break;
306         }
307       for (cp = ds_cstr (&line); isspace ((unsigned char) *cp); cp++);
308       if (!strncmp ("define", cp, 6) && isspace ((unsigned char) cp[6]))
309         outp_configure_macro (&cp[7]);
310       else if (*cp)
311         {
312           char *ep;
313           for (ep = cp; *ep && *ep != ':' && *ep != '='; ep++);
314           if (*ep == '=')
315             expand_name (cp, ep);
316           else if (*ep == ':')
317             {
318               struct outp_names *n = search_names (cp, ep);
319               if (n)
320                 {
321                   outp_configure_driver_line (ds_ss (&line));
322                   delete_name (n);
323                 }
324             }
325           else
326             error_at_line (0, 0, init_fn, line_number, _("syntax error"));
327         }
328     }
329   result = 1;
330
331   check_configure_vec ();
332
333 exit:
334   if (f && -1 == fclose (f))
335     error (0, errno, _("error closing \"%s\""), init_fn);
336   free (init_fn);
337   ds_destroy (&line);
338   delete_macros ();
339
340   if (result)
341     {
342       if (ll_is_empty (&outp_driver_list))
343         error (0, 0, _("no active output drivers"));
344     }
345   else
346     error (0, 0, _("error reading device definition file"));
347
348   if (!result || ll_is_empty (&outp_driver_list))
349     init_default_drivers ();
350 }
351
352 /* Clear the list of drivers to configure. */
353 void
354 outp_configure_clear (void)
355 {
356   struct outp_names *n, *next;
357
358   for (n = outp_configure_vec; n; n = next)
359     {
360       next = n->next;
361       free (n->name);
362       free (n);
363     }
364   outp_configure_vec = NULL;
365 }
366
367 /* Adds the name BP to the list of drivers to configure into
368    outp_driver_list. */
369 void
370 outp_configure_add (char *bp)
371 {
372   char *ep = &bp[strlen (bp)];
373   if (!search_names (bp, ep))
374     add_name (bp, ep, OUTP_S_COMMAND_LINE);
375 }
376
377 /* Defines one configuration macro based on the text in BP, which
378    should be of the form `KEY=VALUE'. */
379 void
380 outp_configure_macro (char *bp)
381 {
382   struct outp_defn *d;
383   char *ep;
384
385   while (isspace ((unsigned char) *bp))
386     bp++;
387   ep = bp;
388   while (*ep && !isspace ((unsigned char) *ep) && *ep != '=')
389     ep++;
390
391   d = xmalloc (sizeof *d);
392   d->key = xmalloc (ep - bp + 1);
393   memcpy (d->key, bp, ep - bp);
394   d->key[ep - bp] = 0;
395
396   /* Earlier definitions for a particular KEY override later ones. */
397   if (find_defn_value (d->key))
398     {
399       free (d->key);
400       free (d);
401       return;
402     }
403
404   if (*ep == '=')
405     ep++;
406   while (isspace ((unsigned char) *ep))
407     ep++;
408
409   ds_init_cstr (&d->value, ep);
410   fn_interp_vars (ds_ss (&d->value), find_defn_value, &d->value);
411   d->next = outp_macros;
412   d->prev = NULL;
413   if (outp_macros)
414     outp_macros->prev = d;
415   outp_macros = d;
416 }
417
418 /* Closes all the output drivers. */
419 void
420 outp_done (void)
421 {
422   struct outp_driver_class_list *n = outp_class_list ;
423   outp_configure_clear ();
424   while (!ll_is_empty (&outp_driver_list))
425     {
426       struct outp_driver *d = ll_data (ll_head (&outp_driver_list),
427                                        struct outp_driver, node);
428       destroy_driver (d);
429     }
430
431   while (n)
432     {
433       struct outp_driver_class_list *next = n->next;
434       free(n);
435       n = next;
436     }
437   outp_class_list = NULL;
438
439   free (outp_title);
440   outp_title = NULL;
441
442   free (outp_subtitle);
443   outp_subtitle = NULL;
444 }
445
446 /* Display on stdout a list of all registered driver classes. */
447 void
448 outp_list_classes (void)
449 {
450   int width = settings_get_viewwidth ();
451   struct outp_driver_class_list *c;
452
453   printf (_("Driver classes:\n\t"));
454   width -= 8;
455   for (c = outp_class_list; c; c = c->next)
456     {
457       if ((int) strlen (c->class->name) + 1 > width)
458         {
459           printf ("\n\t");
460           width = settings_get_viewwidth () - 8;
461         }
462       else
463         putc (' ', stdout);
464       fputs (c->class->name, stdout);
465     }
466   putc('\n', stdout);
467 }
468
469 /* Obtains a token from S and advances its position.  Errors are
470    reported against the given DRIVER_NAME.
471    The token is stored in TOKEN.  Returns true if successful,
472    false on syntax error.
473
474    Caller is responsible for skipping leading spaces. */
475 static bool
476 get_option_token (struct substring *s, const char *driver_name,
477                   struct string *token)
478 {
479   int c;
480
481   ds_clear (token);
482   c = ss_get_char (s);
483   if (c == EOF)
484     {
485       error (0, 0, _("syntax error parsing options for \"%s\" driver"),
486              driver_name);
487       return false;
488     }
489   else if (c == '\'' || c == '"')
490     {
491       int quote = c;
492
493       for (;;)
494         {
495           c = ss_get_char (s);
496           if (c == quote)
497             break;
498           else if (c == EOF)
499             {
500               error (0, 0,
501                      _("reached end of options inside quoted string "
502                        "parsing options for \"%s\" driver"),
503                      driver_name);
504               return false;
505             }
506           else if (c != '\\')
507             ds_put_char (token, c);
508           else
509             {
510               int out;
511
512               c = ss_get_char (s);
513               switch (c)
514                 {
515                 case '\'':
516                   out = '\'';
517                   break;
518                 case '"':
519                   out = '"';
520                   break;
521                 case '\\':
522                   out = '\\';
523                   break;
524                 case 'a':
525                   out = '\a';
526                   break;
527                 case 'b':
528                   out = '\b';
529                   break;
530                 case 'f':
531                   out = '\f';
532                   break;
533                 case 'n':
534                   out = '\n';
535                   break;
536                 case 'r':
537                   out = '\r';
538                   break;
539                 case 't':
540                   out = '\t';
541                   break;
542                 case 'v':
543                   out = '\v';
544                   break;
545                 case '0':
546                 case '1':
547                 case '2':
548                 case '3':
549                 case '4':
550                 case '5':
551                 case '6':
552                 case '7':
553                   out = c - '0';
554                   while (ss_first (*s) >= '0' && ss_first (*s) <= '7')
555                     out = out * 8 + (ss_get_char (s) - '0');
556                   break;
557                 case 'x':
558                 case 'X':
559                   out = 0;
560                   while (isxdigit (ss_first (*s)))
561                     {
562                       c = ss_get_char (s);
563                       out *= 16;
564                       if (isdigit (c))
565                         out += c - '0';
566                       else
567                         out += tolower (c) - 'a' + 10;
568                     }
569                   break;
570                 default:
571                   error (0, 0, _("syntax error in string constant "
572                                  "parsing options for \"%s\" driver"),
573                          driver_name);
574                   return false;
575                 }
576               ds_put_char (token, out);
577             }
578         }
579     }
580   else
581     {
582       for (;;)
583         {
584           ds_put_char (token, c);
585
586           c = ss_first (*s);
587           if (c == EOF || c == '=' || isspace (c))
588             break;
589           ss_advance (s, 1);
590         }
591     }
592
593   return 1;
594 }
595
596 bool
597 outp_parse_options (struct substring options,
598                     bool (*callback) (struct outp_driver *, const char *key,
599                                       const struct string *value),
600                     struct outp_driver *driver)
601 {
602   struct string key = DS_EMPTY_INITIALIZER;
603   struct string value = DS_EMPTY_INITIALIZER;
604   struct substring left = options;
605   bool ok = true;
606
607   do
608     {
609       ss_ltrim (&left, ss_cstr (CC_SPACES));
610       if (ss_is_empty (left))
611         break;
612
613       if (!get_option_token (&left, driver->name, &key))
614         break;
615
616       ss_ltrim (&left, ss_cstr (CC_SPACES));
617       if (!ss_match_char (&left, '='))
618         {
619           error (0, 0, _("syntax error expecting `=' "
620                          "parsing options for driver \"%s\""),
621                  driver->name);
622           break;
623         }
624
625       ss_ltrim (&left, ss_cstr (CC_SPACES));
626       if (!get_option_token (&left, driver->name, &value))
627         break;
628
629       ok = callback (driver, ds_cstr (&key), &value);
630     }
631   while (ok);
632
633   ds_destroy (&key);
634   ds_destroy (&value);
635
636   return ok;
637 }
638
639 /* Find the driver in outp_driver_list with name NAME. */
640 static struct outp_driver *
641 find_driver (char *name)
642 {
643   struct outp_driver *d;
644   ll_for_each (d, struct outp_driver, node, &outp_driver_list)
645     if (!strcmp (d->name, name))
646       return d;
647   return NULL;
648 }
649
650 /* Adds a driver to outp_driver_list pursuant to the
651    specification provided.  */
652 static void
653 configure_driver (struct substring driver_name, struct substring class_name,
654                   struct substring device_type, struct substring options)
655 {
656   struct outp_driver_class_list *c;
657   struct substring token;
658   size_t save_idx = 0;
659   char *name;
660   int device;
661
662   /* Find class. */
663   for (c = outp_class_list; c; c = c->next)
664     if (!ss_compare (ss_cstr (c->class->name), class_name))
665       break;
666   if (c == NULL)
667     {
668       error (0, 0, _("unknown output driver class `%.*s'"),
669              (int) ss_length (class_name), ss_data (class_name));
670       return;
671     }
672
673   /* Parse device type. */
674   device = 0;
675   while (ss_tokenize (device_type, ss_cstr (CC_SPACES), &save_idx, &token))
676     if (!ss_compare (token, ss_cstr ("listing")))
677       device |= OUTP_DEV_LISTING;
678     else if (!ss_compare (token, ss_cstr ("screen")))
679       device |= OUTP_DEV_SCREEN;
680     else if (!ss_compare (token, ss_cstr ("printer")))
681       device |= OUTP_DEV_PRINTER;
682     else
683       error (0, 0, _("unknown device type `%.*s'"),
684              (int) ss_length (token), ss_data (token));
685
686   /* Open driver. */
687   name = ss_xstrdup (driver_name);
688   if (!c->class->open_driver (name, device, options))
689     error (0, 0, _("cannot initialize output driver `%s' of class `%s'"),
690            name, c->class->name);
691   free (name);
692 }
693
694 /* Allocates and returns a new outp_driver for a device with the
695    given NAME and CLASS and the OUTP_DEV_* type(s) in TYPES
696
697    This function is intended to be used by output drivers, not
698    by their clients. */
699 struct outp_driver *
700 outp_allocate_driver (const struct outp_class *class,
701                       const char *name, int types)
702 {
703   struct outp_driver *d = xmalloc (sizeof *d);
704   d->class = class;
705   d->name = xstrdup (name);
706   d->page_open = false;
707   d->device = types;
708   d->cp_x = d->cp_y = 0;
709   d->ext = NULL;
710   d->prc = NULL;
711   return d;
712 }
713
714 /* Frees driver D and the data that it owns directly.  The
715    driver's class must already have unregistered D (if it was
716    registered) and freed data private to its class.
717
718    This function is intended to be used by output drivers, not
719    by their clients. */
720 void
721 outp_free_driver (struct outp_driver *d)
722 {
723   free (d->name);
724   free (d);
725 }
726
727 /* Adds D to the list of drivers that will be used for output. */
728 void
729 outp_register_driver (struct outp_driver *d)
730 {
731   struct outp_driver *victim;
732
733   /* Find like-named driver and delete. */
734   victim = find_driver (d->name);
735   if (victim != NULL)
736     destroy_driver (victim);
737
738   /* Add D to list. */
739   ll_push_tail (&outp_driver_list, &d->node);
740 }
741
742 /* Remove driver D from the list of drivers that will be used for
743    output. */
744 void
745 outp_unregister_driver (struct outp_driver *d)
746 {
747   ll_remove (&d->node);
748 }
749
750 /* String LINE is in format:
751    DRIVERNAME:CLASSNAME:DEVICETYPE:OPTIONS
752    Adds a driver to outp_driver_list pursuant to the specification
753    provided.  */
754 void
755 outp_configure_driver_line (struct substring line_)
756 {
757   struct string line = DS_EMPTY_INITIALIZER;
758   struct substring tokens[4];
759   size_t save_idx;
760   size_t i;
761
762   fn_interp_vars (line_, find_defn_value, &line);
763
764   save_idx = 0;
765   for (i = 0; i < 4; i++)
766     {
767       struct substring *token = &tokens[i];
768       ds_separate (&line, ss_cstr (i < 3 ? ":" : ""), &save_idx, token);
769       ss_trim (token, ss_cstr (CC_SPACES));
770     }
771
772   if (!ss_is_empty (tokens[0]) && !ss_is_empty (tokens[1]))
773     configure_driver (tokens[0], tokens[1], tokens[2], tokens[3]);
774   else
775     error (0, 0,
776            _("driver definition line missing driver name or class name"));
777
778   ds_destroy (&line);
779 }
780
781 /* Destroys output driver D. */
782 static void
783 destroy_driver (struct outp_driver *d)
784 {
785   outp_close_page (d);
786   if (d->class && d->class->close_driver)
787     d->class->close_driver (d);
788   outp_unregister_driver (d);
789   outp_free_driver (d);
790 }
791
792 /* Tries to match S as one of the keywords in TAB, with
793    corresponding information structure INFO.  Returns category
794    code and stores subcategory in *SUBCAT on success.  Returns -1
795    on failure. */
796 int
797 outp_match_keyword (const char *s, const struct outp_option *tab, int *subcat)
798 {
799   for (; tab->keyword != NULL; tab++)
800     if (!strcmp (s, tab->keyword))
801       {
802         *subcat = tab->subcat;
803         return tab->cat;
804       }
805   return -1;
806 }
807
808 /* Parses UNIT as a dimensional unit.  Returns the multiplicative
809    factor needed to change a quantity measured in that unit into
810    1/72000" units.  If UNIT is empty, it is treated as
811    millimeters.  If the unit is unrecognized, returns 0. */
812 static double
813 parse_unit (const char *unit)
814 {
815   struct unit
816     {
817       char name[3];
818       double factor;
819     };
820
821   static const struct unit units[] =
822     {
823       {"pt", 72000 / 72},
824       {"pc", 72000 / 72 * 12.0},
825       {"in", 72000},
826       {"cm", 72000 / 2.54},
827       {"mm", 72000 / 25.4},
828       {"", 72000 / 25.4},
829     };
830
831   const struct unit *p;
832
833   unit += strspn (unit, CC_SPACES);
834   for (p = units; p < units + sizeof units / sizeof *units; p++)
835     if (!strcasecmp (unit, p->name))
836       return p->factor;
837   return 0.0;
838 }
839
840 /* Determines the size of a dimensional measurement and returns
841    the size in units of 1/72000".  Units are assumed to be
842    millimeters unless otherwise specified.  Returns 0 on
843    error. */
844 int
845 outp_evaluate_dimension (const char *dimen)
846 {
847   double raw, factor;
848   char *tail;
849
850   /* Number. */
851   raw = strtod (dimen, &tail);
852   if (raw <= 0.0)
853     goto syntax_error;
854
855   /* Unit. */
856   factor = parse_unit (tail);
857   if (factor == 0.0)
858     goto syntax_error;
859
860   return raw * factor;
861
862 syntax_error:
863   error (0, 0, _("`%s' is not a valid length."), dimen);
864   return 0;
865 }
866
867 /* Stores the dimensions in 1/72000" units of paper identified by
868    SIZE, which is of form `HORZ x VERT [UNIT]' where HORZ and
869    VERT are numbers and UNIT is an optional unit of measurement,
870    into *H and *V.  Return true on success. */
871 static bool
872 parse_paper_size (const char *size, int *h, int *v)
873 {
874   double raw_h, raw_v, factor;
875   char *tail;
876
877   /* Width. */
878   raw_h = strtod (size, &tail);
879   if (raw_h <= 0.0)
880     return false;
881
882   /* Delimiter. */
883   tail += strspn (tail, CC_SPACES "x,");
884
885   /* Length. */
886   raw_v = strtod (tail, &tail);
887   if (raw_v <= 0.0)
888     return false;
889
890   /* Unit. */
891   factor = parse_unit (tail);
892   if (factor == 0.0)
893     return false;
894
895   *h = raw_h * factor + .5;
896   *v = raw_v * factor + .5;
897   return true;
898 }
899
900 static bool
901 get_standard_paper_size (struct substring name, int *h, int *v)
902 {
903   static const char *sizes[][2] =
904     {
905       {"a0", "841 x 1189 mm"},
906       {"a1", "594 x 841 mm"},
907       {"a2", "420 x 594 mm"},
908       {"a3", "297 x 420 mm"},
909       {"a4", "210 x 297 mm"},
910       {"a5", "148 x 210 mm"},
911       {"b5", "176 x 250 mm"},
912       {"a6", "105 x 148 mm"},
913       {"a7", "74 x 105 mm"},
914       {"a8", "52 x 74 mm"},
915       {"a9", "37 x 52 mm"},
916       {"a10", "26 x 37 mm"},
917       {"b0", "1000 x 1414 mm"},
918       {"b1", "707 x 1000 mm"},
919       {"b2", "500 x 707 mm"},
920       {"b3", "353 x 500 mm"},
921       {"b4", "250 x 353 mm"},
922       {"letter", "612 x 792 pt"},
923       {"legal", "612 x 1008 pt"},
924       {"executive", "522 x 756 pt"},
925       {"note", "612 x 792 pt"},
926       {"11x17", "792 x 1224 pt"},
927       {"tabloid", "792 x 1224 pt"},
928       {"statement", "396 x 612 pt"},
929       {"halfletter", "396 x 612 pt"},
930       {"halfexecutive", "378 x 522 pt"},
931       {"folio", "612 x 936 pt"},
932       {"quarto", "610 x 780 pt"},
933       {"ledger", "1224 x 792 pt"},
934       {"archA", "648 x 864 pt"},
935       {"archB", "864 x 1296 pt"},
936       {"archC", "1296 x 1728 pt"},
937       {"archD", "1728 x 2592 pt"},
938       {"archE", "2592 x 3456 pt"},
939       {"flsa", "612 x 936 pt"},
940       {"flse", "612 x 936 pt"},
941       {"csheet", "1224 x 1584 pt"},
942       {"dsheet", "1584 x 2448 pt"},
943       {"esheet", "2448 x 3168 pt"},
944     };
945
946   size_t i;
947
948   for (i = 0; i < sizeof sizes / sizeof *sizes; i++)
949     if (ss_equals_case (ss_cstr (sizes[i][0]), name))
950       {
951         bool ok = parse_paper_size (sizes[i][1], h, v);
952         assert (ok);
953         return ok;
954       }
955   error (0, 0, _("unknown paper type `%.*s'"),
956          (int) ss_length (name), ss_data (name));
957   return false;
958 }
959
960 /* Reads file FILE_NAME to find a paper size.  Stores the
961    dimensions, in 1/72000" units, into *H and *V.  Returns true
962    on success, false on failure. */
963 static bool
964 read_paper_conf (const char *file_name, int *h, int *v)
965 {
966   struct string line = DS_EMPTY_INITIALIZER;
967   int line_number = 0;
968   FILE *file;
969
970   file = fopen (file_name, "r");
971   if (file == NULL)
972     {
973       error (0, errno, _("error opening \"%s\""), file_name);
974       return false;
975     }
976
977   for (;;)
978     {
979       struct substring name;
980
981       if (!ds_read_config_line (&line, &line_number, file))
982         {
983           if (ferror (file))
984             error (0, errno, _("error reading \"%s\""), file_name);
985           break;
986         }
987
988       name = ds_ss (&line);
989       ss_trim (&name, ss_cstr (CC_SPACES));
990       if (!ss_is_empty (name))
991         {
992           bool ok = get_standard_paper_size (name, h, v);
993           fclose (file);
994           ds_destroy (&line);
995           return ok;
996         }
997     }
998
999   fclose (file);
1000   ds_destroy (&line);
1001   error (0, 0, _("paper size file \"%s\" does not state a paper size"),
1002          file_name);
1003   return false;
1004 }
1005
1006 /* The user didn't specify a paper size, so let's choose a
1007    default based on his environment.  Stores the
1008    dimensions, in 1/72000" units, into *H and *V.  Returns true
1009    on success, false on failure. */
1010 static bool
1011 get_default_paper_size (int *h, int *v)
1012 {
1013   /* libpaper in Debian (and other distributions?) allows the
1014      paper size to be specified in $PAPERSIZE or in a file
1015      specified in $PAPERCONF. */
1016   if (getenv ("PAPERSIZE") != NULL)
1017     return get_standard_paper_size (ss_cstr (getenv ("PAPERSIZE")), h, v);
1018   if (getenv ("PAPERCONF") != NULL)
1019     return read_paper_conf (getenv ("PAPERCONF"), h, v);
1020
1021 #if HAVE_LC_PAPER
1022   /* LC_PAPER is a non-standard glibc extension. */
1023   *h = (int) nl_langinfo(_NL_PAPER_WIDTH) * (72000 / 25.4);
1024   *v = (int) nl_langinfo(_NL_PAPER_HEIGHT) * (72000 / 25.4);
1025   if (*h > 0 && *v > 0)
1026      return true;
1027 #endif
1028
1029   /* libpaper defaults to /etc/papersize. */
1030   if (fn_exists ("/etc/papersize"))
1031     return read_paper_conf ("/etc/papersize", h, v);
1032
1033   /* Can't find a default. */
1034   return false;
1035 }
1036
1037 /* Stores the dimensions, in 1/72000" units, of paper identified
1038    by SIZE into *H and *V.  SIZE can be the name of a kind of
1039    paper ("a4", "letter", ...) or a pair of dimensions
1040    ("210x297", "8.5x11in", ...).  Returns true on success, false
1041    on failure.  On failure, *H and *V are set for A4 paper. */
1042 bool
1043 outp_get_paper_size (const char *size, int *h, int *v)
1044 {
1045   struct substring s;
1046   bool ok;
1047
1048   s = ss_cstr (size);
1049   ss_trim (&s, ss_cstr (CC_SPACES));
1050
1051   if (ss_is_empty (s))
1052     {
1053       /* Treat empty string as default paper size. */
1054       ok = get_default_paper_size (h, v);
1055     }
1056   else if (isdigit (ss_first (s)))
1057     {
1058       /* Treat string that starts with digit as explicit size. */
1059       ok = parse_paper_size (size, h, v);
1060       if (!ok)
1061         error (0, 0, _("syntax error in paper size `%s'"), size);
1062     }
1063   else
1064     {
1065       /* Check against standard paper sizes. */
1066       ok = get_standard_paper_size (s, h, v);
1067     }
1068
1069   /* Default to A4 on error. */
1070   if (!ok)
1071     {
1072       *h = 210 * (72000 / 25.4);
1073       *v = 297 * (72000 / 25.4);
1074     }
1075   return ok;
1076 }
1077
1078 /* If D is NULL, returns the first enabled driver if any, NULL if
1079    none.  Otherwise D must be the last driver returned by this
1080    function, in which case the next enabled driver is returned or NULL
1081    if that was the last. */
1082 struct outp_driver *
1083 outp_drivers (struct outp_driver *d)
1084 {
1085   do
1086     {
1087       struct ll *next;
1088
1089       next = d == NULL ? ll_head (&outp_driver_list) : ll_next (&d->node);
1090       if (next == ll_null (&outp_driver_list))
1091         return NULL;
1092
1093       d = ll_data (next, struct outp_driver, node);
1094     }
1095   while (d->device != 0 && (d->device & disabled_devices) == d->device);
1096
1097   return d;
1098 }
1099
1100 /* Enables (if ENABLE is true) or disables (if ENABLE is false) the
1101    device(s) given in mask DEVICE. */
1102 void
1103 outp_enable_device (bool enable, int device)
1104 {
1105   if (enable)
1106     disabled_devices &= ~device;
1107   else
1108     disabled_devices |= device;
1109 }
1110
1111 /* Opens a page on driver D (if one is not open). */
1112 void
1113 outp_open_page (struct outp_driver *d)
1114 {
1115   if (!d->page_open)
1116     {
1117       d->cp_x = d->cp_y = 0;
1118
1119       d->page_open = true;
1120       if (d->class->open_page != NULL)
1121         d->class->open_page (d);
1122     }
1123 }
1124
1125 /* Closes the page on driver D (if one is open). */
1126 void
1127 outp_close_page (struct outp_driver *d)
1128 {
1129   if (d->page_open)
1130     {
1131       if (d->class->close_page != NULL)
1132         d->class->close_page (d);
1133       d->page_open = false;
1134     }
1135 }
1136
1137 /* Ejects the page on device D, if a page is open and non-blank,
1138    and opens a new page.  */
1139 void
1140 outp_eject_page (struct outp_driver *d)
1141 {
1142   if (d->page_open && d->cp_y != 0)
1143     outp_close_page (d);
1144   outp_open_page (d);
1145 }
1146
1147 /* Flushes output to screen devices, so that the user can see
1148    output that doesn't fill up an entire page. */
1149 void
1150 outp_flush (struct outp_driver *d)
1151 {
1152   if (d->device & OUTP_DEV_SCREEN && d->class->flush != NULL)
1153     {
1154       outp_close_page (d);
1155       d->class->flush (d);
1156     }
1157 }
1158
1159 /* Returns the width of string S, in device units, when output on
1160    device D. */
1161 int
1162 outp_string_width (struct outp_driver *d, const char *s, enum outp_font font)
1163 {
1164   struct outp_text text;
1165   int width;
1166
1167   text.font = font;
1168   text.justification = OUTP_LEFT;
1169   text.string = ss_cstr (s);
1170   text.h = text.v = INT_MAX;
1171   d->class->text_metrics (d, &text, &width, NULL);
1172
1173   return width;
1174 }