a556ad81e8e7b1f49584261829459988b83b732b
[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   add_class (&odt_class);
234
235   add_name (def, &def[strlen (def)], OUTP_S_INIT_FILE);
236 }
237
238 /* Deletes all the output macros. */
239 static void
240 delete_macros (void)
241 {
242   struct outp_defn *d, *next;
243
244   for (d = outp_macros; d; d = next)
245     {
246       next = d->next;
247       free (d->key);
248       ds_destroy (&d->value);
249       free (d);
250     }
251 }
252
253 static void
254 init_default_drivers (void)
255 {
256   error (0, 0, _("using default output driver configuration"));
257   configure_driver (ss_cstr ("list"),
258                     ss_cstr ("ascii"),
259                     ss_cstr ("listing"),
260                     ss_cstr ("length=66 width=79 output-file=\"pspp.list\""));
261 }
262
263 /* Reads the initialization file; initializes
264    outp_driver_list. */
265 void
266 outp_read_devices (void)
267 {
268   int result = 0;
269
270   char *init_fn;
271
272   FILE *f = NULL;
273   struct string line;
274   int line_number;
275
276   init_fn = fn_search_path (fn_getenv_default ("STAT_OUTPUT_INIT_FILE",
277                                                "devices"),
278                             fn_getenv_default ("STAT_OUTPUT_INIT_PATH",
279                                                config_path));
280
281   ds_init_empty (&line);
282
283   if (init_fn == NULL)
284     {
285       error (0, 0, _("cannot find output initialization file "
286                      "(use `-vv' to view search path)"));
287       goto exit;
288     }
289
290   f = fopen (init_fn, "r");
291   if (f == NULL)
292     {
293       error (0, errno, _("cannot open \"%s\""), init_fn);
294       goto exit;
295     }
296
297   line_number = 0;
298   for (;;)
299     {
300       char *cp;
301
302       if (!ds_read_config_line (&line, &line_number, f))
303         {
304           if (ferror (f))
305             error (0, errno, _("reading \"%s\""), init_fn);
306           break;
307         }
308       for (cp = ds_cstr (&line); isspace ((unsigned char) *cp); cp++);
309       if (!strncmp ("define", cp, 6) && isspace ((unsigned char) cp[6]))
310         outp_configure_macro (&cp[7]);
311       else if (*cp)
312         {
313           char *ep;
314           for (ep = cp; *ep && *ep != ':' && *ep != '='; ep++);
315           if (*ep == '=')
316             expand_name (cp, ep);
317           else if (*ep == ':')
318             {
319               struct outp_names *n = search_names (cp, ep);
320               if (n)
321                 {
322                   outp_configure_driver_line (ds_ss (&line));
323                   delete_name (n);
324                 }
325             }
326           else
327             error_at_line (0, 0, init_fn, line_number, _("syntax error"));
328         }
329     }
330   result = 1;
331
332   check_configure_vec ();
333
334 exit:
335   if (f && -1 == fclose (f))
336     error (0, errno, _("error closing \"%s\""), init_fn);
337   free (init_fn);
338   ds_destroy (&line);
339   delete_macros ();
340
341   if (result)
342     {
343       if (ll_is_empty (&outp_driver_list))
344         error (0, 0, _("no active output drivers"));
345     }
346   else
347     error (0, 0, _("error reading device definition file"));
348
349   if (!result || ll_is_empty (&outp_driver_list))
350     init_default_drivers ();
351 }
352
353 /* Clear the list of drivers to configure. */
354 void
355 outp_configure_clear (void)
356 {
357   struct outp_names *n, *next;
358
359   for (n = outp_configure_vec; n; n = next)
360     {
361       next = n->next;
362       free (n->name);
363       free (n);
364     }
365   outp_configure_vec = NULL;
366 }
367
368 /* Adds the name BP to the list of drivers to configure into
369    outp_driver_list. */
370 void
371 outp_configure_add (char *bp)
372 {
373   char *ep = &bp[strlen (bp)];
374   if (!search_names (bp, ep))
375     add_name (bp, ep, OUTP_S_COMMAND_LINE);
376 }
377
378 /* Defines one configuration macro based on the text in BP, which
379    should be of the form `KEY=VALUE'. */
380 void
381 outp_configure_macro (char *bp)
382 {
383   struct outp_defn *d;
384   char *ep;
385
386   while (isspace ((unsigned char) *bp))
387     bp++;
388   ep = bp;
389   while (*ep && !isspace ((unsigned char) *ep) && *ep != '=')
390     ep++;
391
392   d = xmalloc (sizeof *d);
393   d->key = xmalloc (ep - bp + 1);
394   memcpy (d->key, bp, ep - bp);
395   d->key[ep - bp] = 0;
396
397   /* Earlier definitions for a particular KEY override later ones. */
398   if (find_defn_value (d->key))
399     {
400       free (d->key);
401       free (d);
402       return;
403     }
404
405   if (*ep == '=')
406     ep++;
407   while (isspace ((unsigned char) *ep))
408     ep++;
409
410   ds_init_cstr (&d->value, ep);
411   fn_interp_vars (ds_ss (&d->value), find_defn_value, &d->value);
412   d->next = outp_macros;
413   d->prev = NULL;
414   if (outp_macros)
415     outp_macros->prev = d;
416   outp_macros = d;
417 }
418
419 /* Closes all the output drivers. */
420 void
421 outp_done (void)
422 {
423   struct outp_driver_class_list *n = outp_class_list ;
424   outp_configure_clear ();
425   while (!ll_is_empty (&outp_driver_list))
426     {
427       struct outp_driver *d = ll_data (ll_head (&outp_driver_list),
428                                        struct outp_driver, node);
429       destroy_driver (d);
430     }
431
432   while (n)
433     {
434       struct outp_driver_class_list *next = n->next;
435       free(n);
436       n = next;
437     }
438   outp_class_list = NULL;
439
440   free (outp_title);
441   outp_title = NULL;
442
443   free (outp_subtitle);
444   outp_subtitle = NULL;
445 }
446
447 /* Display on stdout a list of all registered driver classes. */
448 void
449 outp_list_classes (void)
450 {
451   int width = settings_get_viewwidth ();
452   struct outp_driver_class_list *c;
453
454   printf (_("Driver classes:\n\t"));
455   width -= 8;
456   for (c = outp_class_list; c; c = c->next)
457     {
458       if ((int) strlen (c->class->name) + 1 > width)
459         {
460           printf ("\n\t");
461           width = settings_get_viewwidth () - 8;
462         }
463       else
464         putc (' ', stdout);
465       fputs (c->class->name, stdout);
466     }
467   putc('\n', stdout);
468 }
469
470 /* Obtains a token from S and advances its position.  Errors are
471    reported against the given DRIVER_NAME.
472    The token is stored in TOKEN.  Returns true if successful,
473    false on syntax error.
474
475    Caller is responsible for skipping leading spaces. */
476 static bool
477 get_option_token (struct substring *s, const char *driver_name,
478                   struct string *token)
479 {
480   int c;
481
482   ds_clear (token);
483   c = ss_get_char (s);
484   if (c == EOF)
485     {
486       error (0, 0, _("syntax error parsing options for \"%s\" driver"),
487              driver_name);
488       return false;
489     }
490   else if (c == '\'' || c == '"')
491     {
492       int quote = c;
493
494       for (;;)
495         {
496           c = ss_get_char (s);
497           if (c == quote)
498             break;
499           else if (c == EOF)
500             {
501               error (0, 0,
502                      _("reached end of options inside quoted string "
503                        "parsing options for \"%s\" driver"),
504                      driver_name);
505               return false;
506             }
507           else if (c != '\\')
508             ds_put_char (token, c);
509           else
510             {
511               int out;
512
513               c = ss_get_char (s);
514               switch (c)
515                 {
516                 case '\'':
517                   out = '\'';
518                   break;
519                 case '"':
520                   out = '"';
521                   break;
522                 case '\\':
523                   out = '\\';
524                   break;
525                 case 'a':
526                   out = '\a';
527                   break;
528                 case 'b':
529                   out = '\b';
530                   break;
531                 case 'f':
532                   out = '\f';
533                   break;
534                 case 'n':
535                   out = '\n';
536                   break;
537                 case 'r':
538                   out = '\r';
539                   break;
540                 case 't':
541                   out = '\t';
542                   break;
543                 case 'v':
544                   out = '\v';
545                   break;
546                 case '0':
547                 case '1':
548                 case '2':
549                 case '3':
550                 case '4':
551                 case '5':
552                 case '6':
553                 case '7':
554                   out = c - '0';
555                   while (ss_first (*s) >= '0' && ss_first (*s) <= '7')
556                     out = out * 8 + (ss_get_char (s) - '0');
557                   break;
558                 case 'x':
559                 case 'X':
560                   out = 0;
561                   while (isxdigit (ss_first (*s)))
562                     {
563                       c = ss_get_char (s);
564                       out *= 16;
565                       if (isdigit (c))
566                         out += c - '0';
567                       else
568                         out += tolower (c) - 'a' + 10;
569                     }
570                   break;
571                 default:
572                   error (0, 0, _("syntax error in string constant "
573                                  "parsing options for \"%s\" driver"),
574                          driver_name);
575                   return false;
576                 }
577               ds_put_char (token, out);
578             }
579         }
580     }
581   else
582     {
583       for (;;)
584         {
585           ds_put_char (token, c);
586
587           c = ss_first (*s);
588           if (c == EOF || c == '=' || isspace (c))
589             break;
590           ss_advance (s, 1);
591         }
592     }
593
594   return 1;
595 }
596
597 bool
598 outp_parse_options (const char *driver_name, struct substring options,
599                     bool (*callback) (void *aux, const char *key,
600                                       const struct string *value), void *aux)
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 (aux, 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   return d;
711 }
712
713 /* Frees driver D and the data that it owns directly.  The
714    driver's class must already have unregistered D (if it was
715    registered) and freed data private to its class.
716
717    This function is intended to be used by output drivers, not
718    by their clients. */
719 void
720 outp_free_driver (struct outp_driver *d)
721 {
722   free (d->name);
723   free (d);
724 }
725
726 /* Adds D to the list of drivers that will be used for output. */
727 void
728 outp_register_driver (struct outp_driver *d)
729 {
730   struct outp_driver *victim;
731
732   /* Find like-named driver and delete. */
733   victim = find_driver (d->name);
734   if (victim != NULL)
735     destroy_driver (victim);
736
737   /* Add D to list. */
738   ll_push_tail (&outp_driver_list, &d->node);
739 }
740
741 /* Remove driver D from the list of drivers that will be used for
742    output. */
743 void
744 outp_unregister_driver (struct outp_driver *d)
745 {
746   ll_remove (&d->node);
747 }
748
749 /* String LINE is in format:
750    DRIVERNAME:CLASSNAME:DEVICETYPE:OPTIONS
751    Adds a driver to outp_driver_list pursuant to the specification
752    provided.  */
753 void
754 outp_configure_driver_line (struct substring line_)
755 {
756   struct string line = DS_EMPTY_INITIALIZER;
757   struct substring tokens[4];
758   size_t save_idx;
759   size_t i;
760
761   fn_interp_vars (line_, find_defn_value, &line);
762
763   save_idx = 0;
764   for (i = 0; i < 4; i++)
765     {
766       struct substring *token = &tokens[i];
767       ds_separate (&line, ss_cstr (i < 3 ? ":" : ""), &save_idx, token);
768       ss_trim (token, ss_cstr (CC_SPACES));
769     }
770
771   if (!ss_is_empty (tokens[0]) && !ss_is_empty (tokens[1]))
772     configure_driver (tokens[0], tokens[1], tokens[2], tokens[3]);
773   else
774     error (0, 0,
775            _("driver definition line missing driver name or class name"));
776
777   ds_destroy (&line);
778 }
779
780 /* Destroys output driver D. */
781 static void
782 destroy_driver (struct outp_driver *d)
783 {
784   outp_close_page (d);
785   if (d->class && d->class->close_driver)
786     d->class->close_driver (d);
787   outp_unregister_driver (d);
788   outp_free_driver (d);
789 }
790
791 /* Tries to match S as one of the keywords in TAB, with
792    corresponding information structure INFO.  Returns category
793    code and stores subcategory in *SUBCAT on success.  Returns -1
794    on failure. */
795 int
796 outp_match_keyword (const char *s, const struct outp_option *tab, int *subcat)
797 {
798   for (; tab->keyword != NULL; tab++)
799     if (!strcmp (s, tab->keyword))
800       {
801         *subcat = tab->subcat;
802         return tab->cat;
803       }
804   return -1;
805 }
806
807 /* Parses UNIT as a dimensional unit.  Returns the multiplicative
808    factor needed to change a quantity measured in that unit into
809    1/72000" units.  If UNIT is empty, it is treated as
810    millimeters.  If the unit is unrecognized, returns 0. */
811 static double
812 parse_unit (const char *unit)
813 {
814   struct unit
815     {
816       char name[3];
817       double factor;
818     };
819
820   static const struct unit units[] =
821     {
822       {"pt", 72000 / 72},
823       {"pc", 72000 / 72 * 12.0},
824       {"in", 72000},
825       {"cm", 72000 / 2.54},
826       {"mm", 72000 / 25.4},
827       {"", 72000 / 25.4},
828     };
829
830   const struct unit *p;
831
832   unit += strspn (unit, CC_SPACES);
833   for (p = units; p < units + sizeof units / sizeof *units; p++)
834     if (!strcasecmp (unit, p->name))
835       return p->factor;
836   return 0.0;
837 }
838
839 /* Determines the size of a dimensional measurement and returns
840    the size in units of 1/72000".  Units are assumed to be
841    millimeters unless otherwise specified.  Returns 0 on
842    error. */
843 int
844 outp_evaluate_dimension (const char *dimen)
845 {
846   double raw, factor;
847   char *tail;
848
849   /* Number. */
850   raw = strtod (dimen, &tail);
851   if (raw <= 0.0)
852     goto syntax_error;
853
854   /* Unit. */
855   factor = parse_unit (tail);
856   if (factor == 0.0)
857     goto syntax_error;
858
859   return raw * factor;
860
861 syntax_error:
862   error (0, 0, _("`%s' is not a valid length."), dimen);
863   return 0;
864 }
865
866 /* Stores the dimensions in 1/72000" units of paper identified by
867    SIZE, which is of form `HORZ x VERT [UNIT]' where HORZ and
868    VERT are numbers and UNIT is an optional unit of measurement,
869    into *H and *V.  Return true on success. */
870 static bool
871 parse_paper_size (const char *size, int *h, int *v)
872 {
873   double raw_h, raw_v, factor;
874   char *tail;
875
876   /* Width. */
877   raw_h = strtod (size, &tail);
878   if (raw_h <= 0.0)
879     return false;
880
881   /* Delimiter. */
882   tail += strspn (tail, CC_SPACES "x,");
883
884   /* Length. */
885   raw_v = strtod (tail, &tail);
886   if (raw_v <= 0.0)
887     return false;
888
889   /* Unit. */
890   factor = parse_unit (tail);
891   if (factor == 0.0)
892     return false;
893
894   *h = raw_h * factor + .5;
895   *v = raw_v * factor + .5;
896   return true;
897 }
898
899 static bool
900 get_standard_paper_size (struct substring name, int *h, int *v)
901 {
902   static const char *sizes[][2] =
903     {
904       {"a0", "841 x 1189 mm"},
905       {"a1", "594 x 841 mm"},
906       {"a2", "420 x 594 mm"},
907       {"a3", "297 x 420 mm"},
908       {"a4", "210 x 297 mm"},
909       {"a5", "148 x 210 mm"},
910       {"b5", "176 x 250 mm"},
911       {"a6", "105 x 148 mm"},
912       {"a7", "74 x 105 mm"},
913       {"a8", "52 x 74 mm"},
914       {"a9", "37 x 52 mm"},
915       {"a10", "26 x 37 mm"},
916       {"b0", "1000 x 1414 mm"},
917       {"b1", "707 x 1000 mm"},
918       {"b2", "500 x 707 mm"},
919       {"b3", "353 x 500 mm"},
920       {"b4", "250 x 353 mm"},
921       {"letter", "612 x 792 pt"},
922       {"legal", "612 x 1008 pt"},
923       {"executive", "522 x 756 pt"},
924       {"note", "612 x 792 pt"},
925       {"11x17", "792 x 1224 pt"},
926       {"tabloid", "792 x 1224 pt"},
927       {"statement", "396 x 612 pt"},
928       {"halfletter", "396 x 612 pt"},
929       {"halfexecutive", "378 x 522 pt"},
930       {"folio", "612 x 936 pt"},
931       {"quarto", "610 x 780 pt"},
932       {"ledger", "1224 x 792 pt"},
933       {"archA", "648 x 864 pt"},
934       {"archB", "864 x 1296 pt"},
935       {"archC", "1296 x 1728 pt"},
936       {"archD", "1728 x 2592 pt"},
937       {"archE", "2592 x 3456 pt"},
938       {"flsa", "612 x 936 pt"},
939       {"flse", "612 x 936 pt"},
940       {"csheet", "1224 x 1584 pt"},
941       {"dsheet", "1584 x 2448 pt"},
942       {"esheet", "2448 x 3168 pt"},
943     };
944
945   size_t i;
946
947   for (i = 0; i < sizeof sizes / sizeof *sizes; i++)
948     if (ss_equals_case (ss_cstr (sizes[i][0]), name))
949       {
950         bool ok = parse_paper_size (sizes[i][1], h, v);
951         assert (ok);
952         return ok;
953       }
954   error (0, 0, _("unknown paper type `%.*s'"),
955          (int) ss_length (name), ss_data (name));
956   return false;
957 }
958
959 /* Reads file FILE_NAME to find a paper size.  Stores the
960    dimensions, in 1/72000" units, into *H and *V.  Returns true
961    on success, false on failure. */
962 static bool
963 read_paper_conf (const char *file_name, int *h, int *v)
964 {
965   struct string line = DS_EMPTY_INITIALIZER;
966   int line_number = 0;
967   FILE *file;
968
969   file = fopen (file_name, "r");
970   if (file == NULL)
971     {
972       error (0, errno, _("error opening \"%s\""), file_name);
973       return false;
974     }
975
976   for (;;)
977     {
978       struct substring name;
979
980       if (!ds_read_config_line (&line, &line_number, file))
981         {
982           if (ferror (file))
983             error (0, errno, _("error reading \"%s\""), file_name);
984           break;
985         }
986
987       name = ds_ss (&line);
988       ss_trim (&name, ss_cstr (CC_SPACES));
989       if (!ss_is_empty (name))
990         {
991           bool ok = get_standard_paper_size (name, h, v);
992           fclose (file);
993           ds_destroy (&line);
994           return ok;
995         }
996     }
997
998   fclose (file);
999   ds_destroy (&line);
1000   error (0, 0, _("paper size file \"%s\" does not state a paper size"),
1001          file_name);
1002   return false;
1003 }
1004
1005 /* The user didn't specify a paper size, so let's choose a
1006    default based on his environment.  Stores the
1007    dimensions, in 1/72000" units, into *H and *V.  Returns true
1008    on success, false on failure. */
1009 static bool
1010 get_default_paper_size (int *h, int *v)
1011 {
1012   /* libpaper in Debian (and other distributions?) allows the
1013      paper size to be specified in $PAPERSIZE or in a file
1014      specified in $PAPERCONF. */
1015   if (getenv ("PAPERSIZE") != NULL)
1016     return get_standard_paper_size (ss_cstr (getenv ("PAPERSIZE")), h, v);
1017   if (getenv ("PAPERCONF") != NULL)
1018     return read_paper_conf (getenv ("PAPERCONF"), h, v);
1019
1020 #if HAVE_LC_PAPER
1021   /* LC_PAPER is a non-standard glibc extension. */
1022   *h = (int) nl_langinfo(_NL_PAPER_WIDTH) * (72000 / 25.4);
1023   *v = (int) nl_langinfo(_NL_PAPER_HEIGHT) * (72000 / 25.4);
1024   if (*h > 0 && *v > 0)
1025      return true;
1026 #endif
1027
1028   /* libpaper defaults to /etc/papersize. */
1029   if (fn_exists ("/etc/papersize"))
1030     return read_paper_conf ("/etc/papersize", h, v);
1031
1032   /* Can't find a default. */
1033   return false;
1034 }
1035
1036 /* Stores the dimensions, in 1/72000" units, of paper identified
1037    by SIZE into *H and *V.  SIZE can be the name of a kind of
1038    paper ("a4", "letter", ...) or a pair of dimensions
1039    ("210x297", "8.5x11in", ...).  Returns true on success, false
1040    on failure.  On failure, *H and *V are set for A4 paper. */
1041 bool
1042 outp_get_paper_size (const char *size, int *h, int *v)
1043 {
1044   struct substring s;
1045   bool ok;
1046
1047   s = ss_cstr (size);
1048   ss_trim (&s, ss_cstr (CC_SPACES));
1049
1050   if (ss_is_empty (s))
1051     {
1052       /* Treat empty string as default paper size. */
1053       ok = get_default_paper_size (h, v);
1054     }
1055   else if (isdigit (ss_first (s)))
1056     {
1057       /* Treat string that starts with digit as explicit size. */
1058       ok = parse_paper_size (size, h, v);
1059       if (!ok)
1060         error (0, 0, _("syntax error in paper size `%s'"), size);
1061     }
1062   else
1063     {
1064       /* Check against standard paper sizes. */
1065       ok = get_standard_paper_size (s, h, v);
1066     }
1067
1068   /* Default to A4 on error. */
1069   if (!ok)
1070     {
1071       *h = 210 * (72000 / 25.4);
1072       *v = 297 * (72000 / 25.4);
1073     }
1074   return ok;
1075 }
1076
1077 /* If D is NULL, returns the first enabled driver if any, NULL if
1078    none.  Otherwise D must be the last driver returned by this
1079    function, in which case the next enabled driver is returned or NULL
1080    if that was the last. */
1081 struct outp_driver *
1082 outp_drivers (struct outp_driver *d)
1083 {
1084   do
1085     {
1086       struct ll *next;
1087
1088       next = d == NULL ? ll_head (&outp_driver_list) : ll_next (&d->node);
1089       if (next == ll_null (&outp_driver_list))
1090         return NULL;
1091
1092       d = ll_data (next, struct outp_driver, node);
1093     }
1094   while (d->device != 0 && (d->device & disabled_devices) == d->device);
1095
1096   return d;
1097 }
1098
1099 /* Enables (if ENABLE is true) or disables (if ENABLE is false) the
1100    device(s) given in mask DEVICE. */
1101 void
1102 outp_enable_device (bool enable, int device)
1103 {
1104   if (enable)
1105     disabled_devices &= ~device;
1106   else
1107     disabled_devices |= device;
1108 }
1109
1110 /* Opens a page on driver D (if one is not open). */
1111 void
1112 outp_open_page (struct outp_driver *d)
1113 {
1114   if (!d->page_open)
1115     {
1116       d->cp_x = d->cp_y = 0;
1117
1118       d->page_open = true;
1119       if (d->class->open_page != NULL)
1120         d->class->open_page (d);
1121     }
1122 }
1123
1124 /* Closes the page on driver D (if one is open). */
1125 void
1126 outp_close_page (struct outp_driver *d)
1127 {
1128   if (d->page_open)
1129     {
1130       if (d->class->close_page != NULL)
1131         d->class->close_page (d);
1132       d->page_open = false;
1133     }
1134 }
1135
1136 /* Ejects the page on device D, if a page is open and non-blank,
1137    and opens a new page.  */
1138 void
1139 outp_eject_page (struct outp_driver *d)
1140 {
1141   if (d->page_open && d->cp_y != 0)
1142     outp_close_page (d);
1143   outp_open_page (d);
1144 }
1145
1146 /* Flushes output to screen devices, so that the user can see
1147    output that doesn't fill up an entire page. */
1148 void
1149 outp_flush (struct outp_driver *d)
1150 {
1151   if (d->device & OUTP_DEV_SCREEN && d->class->flush != NULL)
1152     {
1153       outp_close_page (d);
1154       d->class->flush (d);
1155     }
1156 }
1157
1158 /* Returns the width of string S, in device units, when output on
1159    device D. */
1160 int
1161 outp_string_width (struct outp_driver *d, const char *s, enum outp_font font)
1162 {
1163   struct outp_text text;
1164   int width;
1165
1166   text.font = font;
1167   text.justification = OUTP_LEFT;
1168   text.string = ss_cstr (s);
1169   text.h = text.v = INT_MAX;
1170   d->class->text_metrics (d, &text, &width, NULL);
1171
1172   return width;
1173 }