Remove BLP_INT_DIGITS. Now we use the intprops.h header file instead.
[pspp-builds.git] / src / output / postscript.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
22 /*this #if encloses the remainder of the file. */
23 #if !NO_POSTSCRIPT
24
25 #include <ctype.h>
26 #include "chart.h"
27 #include "message.h"
28 #include <errno.h>
29 #include <limits.h>
30 #include <stdlib.h>
31 #include <time.h>
32
33 #if HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36
37 #include "alloc.h"
38 #include "bit-vector.h"
39 #include "message.h"
40 #include "filename.h"
41 #include "font.h"
42 #include "getline.h"
43 #include "hash.h"
44 #include "intprops.h"
45 #include "misc.h"
46 #include "output.h"
47 #include "manager.h"
48 #include "start-date.h"
49 #include "version.h"
50
51 #include "gettext.h"
52 #define _(msgid) gettext (msgid)
53
54 /* FIXMEs:
55
56    optimize-text-size not implemented.
57    
58    Line buffering is the only possibility; page buffering should also
59    be possible.
60
61    max-fonts-simult
62    
63    Should add a field to give a file that has a list of fonts
64    typically used.
65    
66    Should add an option that tells the driver it can emit %%Include:'s.
67    
68    Should have auto-encode=true stream-edit or whatever to allow
69    addition to list of encodings.
70    
71    Should align fonts of different sizes along their baselines (see
72    text()).  */
73
74 /* PostScript driver options: (defaults listed first)
75
76    output-file="pspp.ps"
77    color=yes|no
78    data=clean7bit|clean8bit|binary
79    line-ends=lf|crlf
80
81    paper-size=letter (see "papersize" file)
82    orientation=portrait|landscape
83    headers=on|off
84    
85    left-margin=0.5in
86    right-margin=0.5in
87    top-margin=0.5in
88    bottom-margin=0.5in
89
90    font-dir=devps
91    prologue-file=ps-prologue
92    device-file=DESC
93    encoding-file=ps-encodings
94    auto-encode=true|false
95
96    prop-font-family=T
97    fixed-font-family=C
98    font-size=10000
99
100    line-style=thick|double
101    line-gutter=0.5pt
102    line-spacing=0.5pt
103    line-width=0.5pt
104    line-width-thick=1pt
105
106    optimize-text-size=1|0|2
107    optimize-line-size=1|0
108    max-fonts-simult=0     Max # of fonts in printer memory at once (0=infinite)
109  */
110
111 /* The number of `psus' (PostScript driver UnitS) per inch.  Although
112    this is a #define, the value is expected never to change.  If it
113    does, review all uses.  */
114 #define PSUS 72000
115
116 /* Magic numbers for PostScript and EPSF drivers. */
117 enum
118   {
119     MAGIC_PS,
120     MAGIC_EPSF
121   };
122
123 /* Orientations. */
124 enum
125   {
126     OTN_PORTRAIT,               /* Portrait. */
127     OTN_LANDSCAPE               /* Landscape. */
128   };
129
130 /* Output options. */
131 enum
132   {
133     OPO_MIRROR_HORZ = 001,      /* 1=Mirror across a horizontal axis. */
134     OPO_MIRROR_VERT = 002,      /* 1=Mirror across a vertical axis. */
135     OPO_ROTATE_180 = 004,       /* 1=Rotate the page 180 degrees. */
136     OPO_COLOR = 010,            /* 1=Enable color. */
137     OPO_HEADERS = 020,          /* 1=Draw headers at top of page. */
138     OPO_AUTO_ENCODE = 040,      /* 1=Add encodings semi-intelligently. */
139     OPO_DOUBLE_LINE = 0100      /* 1=Double lines instead of thick lines. */
140   };
141
142 /* Data allowed in output. */
143 enum
144   {
145     ODA_CLEAN7BIT,              /* 0x09, 0x0a, 0x0d, 0x1b...0x7e */
146     ODA_CLEAN8BIT,              /* 0x09, 0x0a, 0x0d, 0x1b...0xff */
147     ODA_BINARY,                 /* 0x00...0xff */
148     ODA_COUNT
149   };
150
151 /* Types of lines for purpose of caching. */
152 enum
153   {
154     horz,                       /* Single horizontal. */
155     dbl_horz,                   /* Double horizontal. */
156     spl_horz,                   /* Special horizontal. */
157     vert,                       /* Single vertical. */
158     dbl_vert,                   /* Double vertical. */
159     spl_vert,                   /* Special vertical. */
160     n_line_types
161   };
162
163 /* Cached line. */
164 struct line_form
165   {
166     int ind;                    /* Independent var.  Don't reorder. */
167     int mdep;                   /* Maximum number of dependent var pairs. */
168     int ndep;                   /* Current number of dependent var pairs. */
169     int dep[1][2];              /* Dependent var pairs. */
170   };
171
172 /* Contents of ps_driver_ext.loaded. */
173 struct font_entry
174   {
175     char *dit;                  /* Font Groff name. */
176     struct font_desc *font;     /* Font descriptor. */
177   };
178
179 /* Combines a font with a font size for benefit of generated code. */
180 struct ps_font_combo
181   {
182     struct font_entry *font;    /* Font. */
183     int size;                   /* Font size. */
184     int index;                  /* PostScript index. */
185   };
186
187 /* A font encoding. */
188 struct ps_encoding
189   {
190     char *filename;             /* Normalized filename of this encoding. */
191     int index;                  /* Index value. */
192   };
193
194 /* PostScript output driver extension record. */
195 struct ps_driver_ext
196   {
197     /* User parameters. */
198     int orientation;            /* OTN_PORTRAIT or OTN_LANDSCAPE. */
199     int output_options;         /* OPO_*. */
200     int data;                   /* ODA_*. */
201
202     int left_margin;            /* Left margin in psus. */
203     int right_margin;           /* Right margin in psus. */
204     int top_margin;             /* Top margin in psus. */
205     int bottom_margin;          /* Bottom margin in psus. */
206
207     char eol[3];                /* End of line--CR, LF, or CRLF. */
208     
209     char *font_dir;             /* Font directory relative to font path. */
210     char *prologue_fn;          /* Prologue's filename relative to font dir. */
211     char *desc_fn;              /* DESC filename relative to font dir. */
212     char *encoding_fn;          /* Encoding's filename relative to font dir. */
213
214     char *prop_family;          /* Default proportional font family. */
215     char *fixed_family;         /* Default fixed-pitch font family. */
216     int font_size;              /* Default font size (psus). */
217
218     int line_gutter;            /* Space around lines. */
219     int line_space;             /* Space between lines. */
220     int line_width;             /* Width of lines. */
221     int line_width_thick;       /* Width of thick lines. */
222
223     int text_opt;               /* Text optimization level. */
224     int line_opt;               /* Line optimization level. */
225     int max_fonts;              /* Max # of simultaneous fonts (0=infinite). */
226
227     /* Internal state. */
228     struct file_ext file;       /* Output file. */
229     int page_number;            /* Current page number. */
230     int file_page_number;       /* Page number in this file. */
231     int w, l;                   /* Paper size. */
232     struct hsh_table *lines[n_line_types];      /* Line buffers. */
233     
234     struct font_entry *prop;    /* Default Roman proportional font. */
235     struct font_entry *fixed;   /* Default Roman fixed-pitch font. */
236     struct hsh_table *loaded;   /* Fonts in memory. */
237
238     struct hsh_table *combos;   /* Combinations of fonts with font sizes. */
239     struct ps_font_combo *last_font;    /* PostScript selected font. */
240     int next_combo;             /* Next font combo position index. */
241
242     struct hsh_table *encodings;/* Set of encodings. */
243     int next_encoding;          /* Next font encoding index. */
244
245     /* Currently selected font. */
246     struct font_entry *current; /* Current font. */
247     char *family;               /* Font family. */
248     int size;                   /* Size in psus. */
249   }
250 ps_driver_ext;
251
252 /* Transform logical y-ordinate Y into a page ordinate. */
253 #define YT(Y) (this->length - (Y))
254
255 /* Prototypes. */
256 static int postopen (struct file_ext *);
257 static int preclose (struct file_ext *);
258 static void draw_headers (struct outp_driver *this);
259
260 static int compare_font_entry (const void *, const void *, void *param);
261 static unsigned hash_font_entry (const void *, void *param);
262 static void free_font_entry (void *, void *foo);
263 static struct font_entry *load_font (struct outp_driver *, const char *dit);
264 static void init_fonts (void);
265 static void done_fonts (void);
266
267 static void dump_lines (struct outp_driver *this);
268
269 static void read_ps_encodings (struct outp_driver *this);
270 static int compare_ps_encoding (const void *pa, const void *pb, void *foo);
271 static unsigned hash_ps_encoding (const void *pa, void *foo);
272 static void free_ps_encoding (void *a, void *foo);
273 static void add_encoding (struct outp_driver *this, char *filename);
274 static struct ps_encoding *default_encoding (struct outp_driver *this);
275
276 static int compare_ps_combo (const void *pa, const void *pb, void *foo);
277 static unsigned hash_ps_combo (const void *pa, void *foo);
278 static void free_ps_combo (void *a, void *foo);
279
280 static char *quote_ps_name (char *dest, const char *string);
281 static char *quote_ps_string (char *dest, const char *string);
282 \f
283 /* Driver initialization. */
284
285 static int
286 ps_open_global (struct outp_class *this UNUSED)
287 {
288   init_fonts ();
289   groff_init ();
290   return 1;
291 }
292
293 static int
294 ps_close_global (struct outp_class *this UNUSED)
295 {
296   groff_done ();
297   done_fonts ();
298   return 1;
299 }
300
301 static int *
302 ps_font_sizes (struct outp_class *this UNUSED, int *n_valid_sizes)
303 {
304   /* Allow fonts up to 1" in height. */
305   static int valid_sizes[] =
306   {1, PSUS, 0, 0};
307
308   assert (n_valid_sizes != NULL);
309   *n_valid_sizes = 1;
310   return valid_sizes;
311 }
312
313 static int
314 ps_preopen_driver (struct outp_driver *this)
315 {
316   struct ps_driver_ext *x;
317   
318   int i;
319
320   assert (this->driver_open == 0);
321   msg (VM (1), _("PostScript driver initializing as `%s'..."), this->name);
322         
323   this->ext = x = xmalloc (sizeof *x);
324   this->res = PSUS;
325   this->horiz = this->vert = 1;
326   this->width = this->length = 0;
327
328   x->orientation = OTN_PORTRAIT;
329   x->output_options = OPO_COLOR | OPO_HEADERS | OPO_AUTO_ENCODE;
330   x->data = ODA_CLEAN7BIT;
331         
332   x->left_margin = x->right_margin =
333     x->top_margin = x->bottom_margin = PSUS / 2;
334         
335   strcpy (x->eol, "\n");
336
337   x->font_dir = NULL;
338   x->prologue_fn = NULL;
339   x->desc_fn = NULL;
340   x->encoding_fn = NULL;
341
342   x->prop_family = NULL;
343   x->fixed_family = NULL;
344   x->font_size = PSUS * 10 / 72;
345
346   x->line_gutter = PSUS / 144;
347   x->line_space = PSUS / 144;
348   x->line_width = PSUS / 144;
349   x->line_width_thick = PSUS / 48;
350
351   x->text_opt = -1;
352   x->line_opt = -1;
353   x->max_fonts = 0;
354
355   x->file.filename = NULL;
356   x->file.mode = "wb";
357   x->file.file = NULL;
358   x->file.sequence_no = &x->page_number;
359   x->file.param = this;
360   x->file.postopen = postopen;
361   x->file.preclose = preclose;
362   x->page_number = 0;
363   x->w = x->l = 0;
364
365   x->file_page_number = 0;
366   for (i = 0; i < n_line_types; i++)
367     x->lines[i] = NULL;
368   x->last_font = NULL;
369
370   x->prop = NULL;
371   x->fixed = NULL;
372   x->loaded = NULL;
373
374   x->next_combo = 0;
375   x->combos = NULL;
376
377   x->encodings = hsh_create (31, compare_ps_encoding, hash_ps_encoding,
378                              free_ps_encoding, NULL);
379   x->next_encoding = 0;
380
381   x->current = NULL;
382   x->family = NULL;
383   x->size = 0;
384
385   return 1;
386 }
387
388 static int
389 ps_postopen_driver (struct outp_driver *this)
390 {
391   struct ps_driver_ext *x = this->ext;
392   
393   assert (this->driver_open == 0);
394
395   if (this->width == 0)
396     {
397       this->width = PSUS * 17 / 2;      /* Defaults to 8.5"x11". */
398       this->length = PSUS * 11;
399     }
400
401   if (x->text_opt == -1)
402     x->text_opt = (this->device & OUTP_DEV_SCREEN) ? 0 : 1;
403   if (x->line_opt == -1)
404     x->line_opt = (this->device & OUTP_DEV_SCREEN) ? 0 : 1;
405
406   x->w = this->width;
407   x->l = this->length;
408   if (x->orientation == OTN_LANDSCAPE)
409     {
410       int temp = this->width;
411       this->width = this->length;
412       this->length = temp;
413     }
414   this->width -= x->left_margin + x->right_margin;
415   this->length -= x->top_margin + x->bottom_margin;
416   if (x->output_options & OPO_HEADERS)
417     {
418       this->length -= 3 * x->font_size;
419       x->top_margin += 3 * x->font_size;
420     }
421   if (NULL == x->file.filename)
422     x->file.filename = xstrdup ("pspp.ps");
423
424   if (x->font_dir == NULL)
425     x->font_dir = xstrdup ("devps");
426   if (x->prologue_fn == NULL)
427     x->prologue_fn = xstrdup ("ps-prologue");
428   if (x->desc_fn == NULL)
429     x->desc_fn = xstrdup ("DESC");
430   if (x->encoding_fn == NULL)
431     x->encoding_fn = xstrdup ("ps-encodings");
432
433   if (x->prop_family == NULL)
434     x->prop_family = xstrdup ("H");
435   if (x->fixed_family == NULL)
436     x->fixed_family = xstrdup ("C");
437
438   read_ps_encodings (this);
439
440   x->family = NULL;
441   x->size = PSUS / 6;
442
443   if (this->length / x->font_size < 15)
444     {
445       msg (SE, _("PostScript driver: The defined page is not long "
446                  "enough to hold margins and headers, plus least 15 "
447                  "lines of the default fonts.  In fact, there's only "
448                  "room for %d lines of each font at the default size "
449                  "of %d.%03d points."),
450            this->length / x->font_size,
451            x->font_size / 1000, x->font_size % 1000);
452       return 0;
453     }
454
455   this->driver_open = 1;
456   msg (VM (2), _("%s: Initialization complete."), this->name);
457
458   return 1;
459 }
460
461 static int
462 ps_close_driver (struct outp_driver *this)
463 {
464   struct ps_driver_ext *x = this->ext;
465   
466   int i;
467
468   assert (this->driver_open == 1);
469   msg (VM (2), _("%s: Beginning closing..."), this->name);
470   
471   fn_close_ext (&x->file);
472   free (x->file.filename);
473   free (x->font_dir);
474   free (x->prologue_fn);
475   free (x->desc_fn);
476   free (x->encoding_fn);
477   free (x->prop_family);
478   free (x->fixed_family);
479   free (x->family);
480   for (i = 0; i < n_line_types; i++)
481     hsh_destroy (x->lines[i]);
482   hsh_destroy (x->encodings);
483   hsh_destroy (x->combos);
484   hsh_destroy (x->loaded);
485   free (x);
486   
487   this->driver_open = 0;
488   msg (VM (3), _("%s: Finished closing."), this->name);
489
490   return 1;
491 }
492
493 /* font_entry comparison function for hash tables. */
494 static int
495 compare_font_entry (const void *a, const void *b, void *foobar UNUSED)
496 {
497   return strcmp (((struct font_entry *) a)->dit, ((struct font_entry *) b)->dit);
498 }
499
500 /* font_entry hash function for hash tables. */
501 static unsigned
502 hash_font_entry (const void *fe_, void *foobar UNUSED)
503 {
504   const struct font_entry *fe = fe_;
505   return hsh_hash_string (fe->dit);
506 }
507
508 /* font_entry destructor function for hash tables. */
509 static void
510 free_font_entry (void *pa, void *foo UNUSED)
511 {
512   struct font_entry *a = pa;
513   free (a->dit);
514   free (a);
515 }
516
517 /* Generic option types. */
518 enum
519 {
520   boolean_arg = -10,
521   pos_int_arg,
522   dimension_arg,
523   string_arg,
524   nonneg_int_arg
525 };
526
527 /* All the options that the PostScript driver supports. */
528 static struct outp_option option_tab[] =
529 {
530   /* *INDENT-OFF* */
531   {"output-file",               1,              0},
532   {"paper-size",                2,              0},
533   {"orientation",               3,              0},
534   {"color",                     boolean_arg,    0},
535   {"data",                      4,              0},
536   {"auto-encode",               boolean_arg,    5},
537   {"headers",                   boolean_arg,    1},
538   {"left-margin",               pos_int_arg,    0},
539   {"right-margin",              pos_int_arg,    1},
540   {"top-margin",                pos_int_arg,    2},
541   {"bottom-margin",             pos_int_arg,    3},
542   {"font-dir",                  string_arg,     0},
543   {"prologue-file",             string_arg,     1},
544   {"device-file",               string_arg,     2},
545   {"encoding-file",             string_arg,     3},
546   {"prop-font-family",          string_arg,     5},
547   {"fixed-font-family",         string_arg,     6},
548   {"font-size",                 pos_int_arg,    4},
549   {"optimize-text-size",        nonneg_int_arg, 0},
550   {"optimize-line-size",        nonneg_int_arg, 1},
551   {"max-fonts-simult",          nonneg_int_arg, 2},
552   {"line-ends",                 6,              0},
553   {"line-style",                7,              0},
554   {"line-width",                dimension_arg,  2},
555   {"line-gutter",               dimension_arg,  3},
556   {"line-width",                dimension_arg,  4},
557   {"line-width-thick",          dimension_arg,  5},
558   {"", 0, 0},
559   /* *INDENT-ON* */
560 };
561 static struct outp_option_info option_info;
562
563 static void
564 ps_option (struct outp_driver *this, const char *key, const struct string *val)
565 {
566   struct ps_driver_ext *x = this->ext;
567   int cat, subcat;
568   char *value = ds_c_str (val);
569
570   cat = outp_match_keyword (key, option_tab, &option_info, &subcat);
571
572   switch (cat)
573     {
574     case 0:
575       msg (SE, _("Unknown configuration parameter `%s' for PostScript device "
576            "driver."), key);
577       break;
578     case 1:
579       free (x->file.filename);
580       x->file.filename = xstrdup (value);
581       break;
582     case 2:
583       outp_get_paper_size (value, &this->width, &this->length);
584       break;
585     case 3:
586       if (!strcmp (value, "portrait"))
587         x->orientation = OTN_PORTRAIT;
588       else if (!strcmp (value, "landscape"))
589         x->orientation = OTN_LANDSCAPE;
590       else
591         msg (SE, _("Unknown orientation `%s'.  Valid orientations are "
592              "`portrait' and `landscape'."), value);
593       break;
594     case 4:
595       if (!strcmp (value, "clean7bit") || !strcmp (value, "Clean7Bit"))
596         x->data = ODA_CLEAN7BIT;
597       else if (!strcmp (value, "clean8bit")
598                || !strcmp (value, "Clean8Bit"))
599         x->data = ODA_CLEAN8BIT;
600       else if (!strcmp (value, "binary") || !strcmp (value, "Binary"))
601         x->data = ODA_BINARY;
602       else
603         msg (SE, _("Unknown value for `data'.  Valid values are `clean7bit', "
604              "`clean8bit', and `binary'."));
605       break;
606     case 6:
607       if (!strcmp (value, "lf"))
608         strcpy (x->eol, "\n");
609       else if (!strcmp (value, "crlf"))
610         strcpy (x->eol, "\r\n");
611       else
612         msg (SE, _("Unknown value for `line-ends'.  Valid values are `lf' and "
613                    "`crlf'."));
614       break;
615     case 7:
616       if (!strcmp (value, "thick"))
617         x->output_options &= ~OPO_DOUBLE_LINE;
618       else if (!strcmp (value, "double"))
619         x->output_options |= OPO_DOUBLE_LINE;
620       else
621         msg (SE, _("Unknown value for `line-style'.  Valid values are `thick' "
622                    "and `double'."));
623       break;
624     case boolean_arg:
625       {
626         int setting;
627         int mask;
628
629         if (!strcmp (value, "on") || !strcmp (value, "true")
630             || !strcmp (value, "yes") || atoi (value))
631           setting = 1;
632         else if (!strcmp (value, "off") || !strcmp (value, "false")
633                  || !strcmp (value, "no") || !strcmp (value, "0"))
634           setting = 0;
635         else
636           {
637             msg (SE, _("Boolean value expected for %s."), key);
638             return;
639           }
640         switch (subcat)
641           {
642           case 0:
643             mask = OPO_COLOR;
644             break;
645           case 1:
646             mask = OPO_HEADERS;
647             break;
648           case 2:
649             mask = OPO_MIRROR_HORZ;
650             break;
651           case 3:
652             mask = OPO_MIRROR_VERT;
653             break;
654           case 4:
655             mask = OPO_ROTATE_180;
656             break;
657           case 5:
658             mask = OPO_AUTO_ENCODE;
659             break;
660           default:
661             assert (0);
662             abort ();
663           }
664         if (setting)
665           x->output_options |= mask;
666         else
667           x->output_options &= ~mask;
668       }
669       break;
670     case pos_int_arg:
671       {
672         char *tail;
673         int arg;
674
675         errno = 0;
676         arg = strtol (value, &tail, 0);
677         if (arg < 1 || errno == ERANGE || *tail)
678           {
679             msg (SE, _("Positive integer required as value for `%s'."), key);
680             break;
681           }
682         if ((subcat == 4 || subcat == 5) && arg < 1000)
683           {
684             msg (SE, _("Default font size must be at least 1 point (value "
685                  "of 1000 for key `%s')."), key);
686             break;
687           }
688         switch (subcat)
689           {
690           case 0:
691             x->left_margin = arg;
692             break;
693           case 1:
694             x->right_margin = arg;
695             break;
696           case 2:
697             x->top_margin = arg;
698             break;
699           case 3:
700             x->bottom_margin = arg;
701             break;
702           case 4:
703             x->font_size = arg;
704             break;
705           default:
706             assert (0);
707           }
708       }
709       break;
710     case dimension_arg:
711       {
712         int dimension = outp_evaluate_dimension (value, NULL);
713
714         if (dimension <= 0)
715           {
716             msg (SE, _("Value for `%s' must be a dimension of positive "
717                  "length (i.e., `1in')."), key);
718             break;
719           }
720         switch (subcat)
721           {
722           case 2:
723             x->line_width = dimension;
724             break;
725           case 3:
726             x->line_gutter = dimension;
727             break;
728           case 4:
729             x->line_width = dimension;
730             break;
731           case 5:
732             x->line_width_thick = dimension;
733             break;
734           default:
735             assert (0);
736           }
737       }
738       break;
739     case string_arg:
740       {
741         char **dest;
742         switch (subcat)
743           {
744           case 0:
745             dest = &x->font_dir;
746             break;
747           case 1:
748             dest = &x->prologue_fn;
749             break;
750           case 2:
751             dest = &x->desc_fn;
752             break;
753           case 3:
754             dest = &x->encoding_fn;
755             break;
756           case 5:
757             dest = &x->prop_family;
758             break;
759           case 6:
760             dest = &x->fixed_family;
761             break;
762           default:
763             assert (0);
764             abort ();
765           }
766         if (*dest)
767           free (*dest);
768         *dest = xstrdup (value);
769       }
770       break;
771     case nonneg_int_arg:
772       {
773         char *tail;
774         int arg;
775
776         errno = 0;
777         arg = strtol (value, &tail, 0);
778         if (arg < 0 || errno == ERANGE || *tail)
779           {
780             msg (SE, _("Nonnegative integer required as value for `%s'."), key);
781             break;
782           }
783         switch (subcat)
784           {
785           case 0:
786             x->text_opt = arg;
787             break;
788           case 1:
789             x->line_opt = arg;
790             break;
791           case 2:
792             x->max_fonts = arg;
793             break;
794           default:
795             assert (0);
796           }
797       }
798       break;
799     default:
800       assert (0);
801     }
802 }
803
804 /* Looks for a PostScript font file or config file in all the
805    appropriate places.  Returns the filename on success, NULL on
806    failure. */
807 /* PORTME: Filename operations. */
808 static char *
809 find_ps_file (struct outp_driver *this, const char *name)
810 {
811   struct ps_driver_ext *x = this->ext;
812   char *cp;
813
814   /* x->font_dir + name: "devps/ps-encodings". */
815   char *basename;
816
817   /* Usually equal to groff_font_path. */
818   char *pathname;
819
820   /* Final filename. */
821   char *fn;
822
823   /* Make basename. */
824   basename = local_alloc (strlen (x->font_dir) + 1 + strlen (name) + 1);
825   cp = stpcpy (basename, x->font_dir);
826   *cp++ = DIR_SEPARATOR;
827   strcpy (cp, name);
828
829   /* Decide on search path. */
830   {
831     const char *pre_pathname;
832     
833     pre_pathname = getenv ("STAT_GROFF_FONT_PATH");
834     if (pre_pathname == NULL)
835       pre_pathname = getenv ("GROFF_FONT_PATH");
836     if (pre_pathname == NULL)
837       pre_pathname = groff_font_path;
838     pathname = fn_tilde_expand (pre_pathname);
839   }
840
841   /* Search all possible places for the file. */
842   fn = fn_search_path (basename, pathname, NULL);
843   if (fn == NULL)
844     fn = fn_search_path (basename, config_path, NULL);
845   if (fn == NULL)
846     fn = fn_search_path (name, pathname, NULL);
847   if (fn == NULL)
848     fn = fn_search_path (name, config_path, NULL);
849   free (pathname);
850   local_free (basename);
851
852   return fn;
853 }
854 \f
855 /* Encodings. */
856
857 /* Hash table comparison function for ps_encoding's. */
858 static int
859 compare_ps_encoding (const void *pa, const void *pb, void *foo UNUSED)
860 {
861   const struct ps_encoding *a = pa;
862   const struct ps_encoding *b = pb;
863
864   return strcmp (a->filename, b->filename);
865 }
866
867 /* Hash table hash function for ps_encoding's. */
868 static unsigned
869 hash_ps_encoding (const void *pa, void *foo UNUSED)
870 {
871   const struct ps_encoding *a = pa;
872
873   return hsh_hash_string (a->filename);
874 }
875
876 /* Hash table free function for ps_encoding's. */
877 static void
878 free_ps_encoding (void *pa, void *foo UNUSED)
879 {
880   struct ps_encoding *a = pa;
881
882   free (a->filename);
883   free (a);
884 }
885
886 /* Iterates through the list of encodings used for this driver
887    instance, reads each of them from disk, and writes them as
888    PostScript code to the output file. */
889 static void
890 output_encodings (struct outp_driver *this)
891 {
892   struct ps_driver_ext *x = this->ext;
893
894   struct hsh_iterator iter;
895   struct ps_encoding *pe;
896
897   struct string line, buf;
898
899   ds_init (&line, 128);
900   ds_init (&buf, 128);
901   for (pe = hsh_first (x->encodings, &iter); pe != NULL;
902        pe = hsh_next (x->encodings, &iter)) 
903     {
904       FILE *f;
905
906       msg (VM (1), _("%s: %s: Opening PostScript font encoding..."),
907            this->name, pe->filename);
908       
909       f = fopen (pe->filename, "r");
910       if (!f)
911         {
912           msg (IE, _("PostScript driver: Cannot open encoding file `%s': %s.  "
913                "Substituting ISOLatin1Encoding for missing encoding."),
914                pe->filename, strerror (errno));
915           fprintf (x->file.file, "/E%x ISOLatin1Encoding def%s",
916                    pe->index, x->eol);
917         }
918       else
919         {
920           struct file_locator where;
921           
922           const char *tab[256];
923
924           char *pschar;
925           char *code;
926           int code_val;
927           char *fubar;
928
929           const char *notdef = ".notdef";
930
931           int i;
932
933           for (i = 0; i < 256; i++)
934             tab[i] = notdef;
935
936           where.filename = pe->filename;
937           where.line_number = 0;
938           err_push_file_locator (&where);
939
940           while (ds_get_config_line (f, &buf, &where))
941             {
942               char *sp; 
943
944               if (buf.length == 0) 
945                 continue;
946
947               pschar = strtok_r (ds_c_str (&buf), " \t\r\n", &sp);
948               code = strtok_r (NULL, " \t\r\n", &sp);
949               if (*pschar == 0 || *code == 0)
950                 continue;
951               code_val = strtol (code, &fubar, 0);
952               if (*fubar)
953                 {
954                   msg (IS, _("PostScript driver: Invalid numeric format."));
955                   continue;
956                 }
957               if (code_val < 0 || code_val > 255)
958                 {
959                   msg (IS, _("PostScript driver: Codes must be between 0 "
960                              "and 255.  (%d is not allowed.)"), code_val);
961                   break;
962                 }
963               tab[code_val] = local_alloc (strlen (pschar) + 1);
964               strcpy ((char *) (tab[code_val]), pschar);
965             }
966           err_pop_file_locator (&where);
967
968           ds_clear (&line);
969           ds_printf (&line, "/E%x[", pe->index);
970           for (i = 0; i < 257; i++)
971             {
972               char temp[288];
973
974               if (i < 256)
975                 {
976                   quote_ps_name (temp, tab[i]);
977                   if (tab[i] != notdef)
978                     local_free (tab[i]);
979                 }
980               else
981                 strcpy (temp, "]def");
982               
983               if (ds_length (&line) + strlen (temp) > 70)
984                 {
985                   ds_puts (&line, x->eol);
986                   fputs (ds_c_str (&line), x->file.file);
987                   ds_clear (&line);
988                 }
989               ds_puts (&line, temp);
990             }
991           ds_puts (&line, x->eol);
992           fputs (ds_c_str (&line), x->file.file);
993
994           if (fclose (f) == EOF)
995             msg (MW, _("PostScript driver: Error closing encoding file `%s'."),
996                  pe->filename);
997
998           msg (VM (2), _("%s: PostScript font encoding read successfully."),
999                this->name);
1000         }
1001     }
1002   ds_destroy (&line);
1003   ds_destroy (&buf);
1004 }
1005
1006 /* Finds the ps_encoding in THIS that corresponds to the file with
1007    name NORM_FILENAME, which must have previously been normalized with
1008    normalize_filename(). */
1009 static struct ps_encoding *
1010 get_encoding (struct outp_driver *this, const char *norm_filename)
1011 {
1012   struct ps_driver_ext *x = this->ext;
1013   struct ps_encoding *pe;
1014
1015   pe = (struct ps_encoding *) hsh_find (x->encodings, (void *) &norm_filename);
1016   return pe;
1017 }
1018
1019 /* Searches the filesystem for an encoding file with name FILENAME;
1020    returns its malloc'd, normalized name if found, otherwise NULL. */
1021 static char *
1022 find_encoding_file (struct outp_driver *this, char *filename)
1023 {
1024   char *cp, *temp;
1025
1026   if (filename == NULL)
1027     return NULL;
1028   while (isspace ((unsigned char) *filename))
1029     filename++;
1030   for (cp = filename; *cp && !isspace ((unsigned char) *cp); cp++)
1031     ;
1032   if (cp == filename)
1033     return NULL;
1034   *cp = 0;
1035
1036   temp = find_ps_file (this, filename);
1037   if (temp == NULL)
1038     return NULL;
1039
1040   filename = fn_normalize (temp);
1041   assert (filename != NULL);
1042   free (temp);
1043
1044   return filename;
1045 }
1046
1047 /* Adds the encoding represented by the not-necessarily-normalized
1048    file FILENAME to the list of encodings, if it exists and is not
1049    already in the list. */
1050 static void
1051 add_encoding (struct outp_driver *this, char *filename)
1052 {
1053   struct ps_driver_ext *x = this->ext;
1054   struct ps_encoding **pe;
1055
1056   filename = find_encoding_file (this, filename);
1057   if (!filename)
1058     return;
1059
1060   pe = (struct ps_encoding **) hsh_probe (x->encodings, &filename);
1061   if (*pe)
1062     {
1063       free (filename);
1064       return;
1065     }
1066   *pe = xmalloc (sizeof **pe);
1067   (*pe)->filename = filename;
1068   (*pe)->index = x->next_encoding++;
1069 }
1070
1071 /* Finds the file on disk that contains the list of encodings to
1072    include in the output file, then adds those encodings to the list
1073    of encodings. */
1074 static void
1075 read_ps_encodings (struct outp_driver *this)
1076 {
1077   struct ps_driver_ext *x = this->ext;
1078
1079   /* Encodings file. */
1080   char *encoding_fn;            /* `ps-encodings' filename. */
1081   FILE *f;
1082
1083   struct string line;
1084   struct file_locator where;
1085
1086   /* It's okay if there's no list of encodings; not everyone cares. */
1087   encoding_fn = find_ps_file (this, x->encoding_fn);
1088   if (encoding_fn == NULL)
1089     return;
1090   free (encoding_fn);
1091
1092   msg (VM (1), _("%s: %s: Opening PostScript encoding list file."),
1093        this->name, encoding_fn);
1094   f = fopen (encoding_fn, "r");
1095   if (!f)
1096     {
1097       msg (IE, _("Opening %s: %s."), encoding_fn, strerror (errno));
1098       return;
1099     }
1100
1101   where.filename = encoding_fn;
1102   where.line_number = 0;
1103   err_push_file_locator (&where);
1104
1105   ds_init (&line, 128);
1106     
1107   for (;;)
1108     {
1109       if (!ds_get_config_line (f, &line, &where))
1110         {
1111           if (ferror (f))
1112             msg (ME, _("Reading %s: %s."), encoding_fn, strerror (errno));
1113           break;
1114         }
1115
1116       add_encoding (this, line.string);
1117     }
1118
1119   ds_destroy (&line);
1120   err_pop_file_locator (&where);
1121   
1122   if (-1 == fclose (f))
1123     msg (MW, _("Closing %s: %s."), encoding_fn, strerror (errno));
1124
1125   msg (VM (2), _("%s: PostScript encoding list file read successfully."), this->name);
1126 }
1127
1128 /* Creates a default encoding for driver D that can be substituted for
1129    an unavailable encoding. */
1130 struct ps_encoding *
1131 default_encoding (struct outp_driver *d)
1132 {
1133   struct ps_driver_ext *x = d->ext;
1134   static struct ps_encoding *enc;
1135
1136   if (!enc)
1137     {
1138       enc = xmalloc (sizeof *enc);
1139       enc->filename = xstrdup (_("<<default encoding>>"));
1140       enc->index = x->next_encoding++;
1141     }
1142   return enc;
1143 }
1144 \f
1145 /* Basic file operations. */
1146
1147 /* Variables for the prologue. */
1148 struct ps_variable
1149   {
1150     const char *key;
1151     const char *value;
1152   };
1153
1154 static struct ps_variable *ps_var_tab;
1155
1156 /* Searches ps_var_tab for a ps_variable with key KEY, and returns the
1157    associated value. */
1158 static const char *
1159 ps_get_var (const char *key)
1160 {
1161   struct ps_variable *v;
1162
1163   for (v = ps_var_tab; v->key; v++)
1164     if (!strcmp (key, v->key))
1165       return v->value;
1166   return NULL;
1167 }
1168
1169 /* Writes the PostScript prologue to file F. */
1170 static int
1171 postopen (struct file_ext *f)
1172 {
1173   static struct ps_variable dict[] =
1174   {
1175     {"bounding-box", 0},
1176     {"creator", 0},
1177     {"date", 0},
1178     {"data", 0},
1179     {"orientation", 0},
1180     {"user", 0},
1181     {"host", 0},
1182     {"prop-font", 0},
1183     {"fixed-font", 0},
1184     {"scale-factor", 0},
1185     {"paper-width", 0},
1186     {"paper-length", 0},
1187     {"left-margin", 0},
1188     {"top-margin", 0},
1189     {"line-width", 0},
1190     {"line-width-thick", 0},
1191     {"title", 0},
1192     {0, 0},
1193   };
1194   char boundbox[INT_STRLEN_BOUND (int) * 4 + 4];
1195 #if HAVE_UNISTD_H
1196   char host[128];
1197 #endif
1198   char scaling[INT_STRLEN_BOUND (int) + 5];
1199   time_t curtime;
1200   struct tm *loctime;
1201   char *p, *cp;
1202   char paper_width[INT_STRLEN_BOUND (int) + 1];
1203   char paper_length[INT_STRLEN_BOUND (int) + 1];
1204   char left_margin[INT_STRLEN_BOUND (int) + 1];
1205   char top_margin[INT_STRLEN_BOUND (int) + 1];
1206   char line_width[INT_STRLEN_BOUND (int) + 1];
1207   char line_width_thick[INT_STRLEN_BOUND (int) + 1];
1208
1209   struct outp_driver *this = f->param;
1210   struct ps_driver_ext *x = this->ext;
1211
1212   char *prologue_fn = find_ps_file (this, x->prologue_fn);
1213   FILE *prologue_file;
1214
1215   char *buf = NULL;
1216   size_t buf_size = 0;
1217
1218   x->loaded = hsh_create (31, compare_font_entry, hash_font_entry,
1219                           free_font_entry, NULL);
1220   
1221   {
1222     char *font_name = local_alloc (2 + max (strlen (x->prop_family),
1223                                             strlen (x->fixed_family)));
1224     
1225     strcpy (stpcpy (font_name, x->prop_family), "R");
1226     x->prop = load_font (this, font_name);
1227
1228     strcpy (stpcpy (font_name, x->fixed_family), "R");
1229     x->fixed = load_font (this, font_name);
1230
1231     local_free(font_name);
1232   }
1233
1234   x->current = x->prop;
1235   x->family = xstrdup (x->prop_family);
1236   x->size = x->font_size;
1237   
1238   {
1239     int *h = this->horiz_line_width, *v = this->vert_line_width;
1240     
1241     this->cp_x = this->cp_y = 0;
1242     this->font_height = x->font_size;
1243     {
1244       struct char_metrics *metric;
1245
1246       metric = font_get_char_metrics (x->prop->font, '0');
1247       this->prop_em_width = ((metric
1248                               ? metric->width : x->prop->font->space_width)
1249                              * x->font_size / 1000);
1250
1251       metric = font_get_char_metrics (x->fixed->font, '0');
1252       this->fixed_width = ((metric
1253                             ? metric->width : x->fixed->font->space_width)
1254                            * x->font_size / 1000);
1255     }
1256         
1257     h[0] = v[0] = 0;
1258     h[1] = v[1] = 2 * x->line_gutter + x->line_width;
1259     if (x->output_options & OPO_DOUBLE_LINE)
1260       h[2] = v[2] = 2 * x->line_gutter + 2 * x->line_width + x->line_space;
1261     else
1262       h[2] = v[2] = 2 * x->line_gutter + x->line_width_thick;
1263     h[3] = v[3] = 2 * x->line_gutter + x->line_width;
1264     
1265     {
1266       int i;
1267       
1268       for (i = 0; i < (1 << OUTP_L_COUNT); i++)
1269         {
1270           int bit;
1271
1272           /* Maximum width of any line type so far. */
1273           int max = 0;
1274
1275           for (bit = 0; bit < OUTP_L_COUNT; bit++)
1276             if ((i & (1 << bit)) && h[bit] > max)
1277               max = h[bit];
1278           this->horiz_line_spacing[i] = this->vert_line_spacing[i] = max;
1279         }
1280     }
1281   }
1282
1283   if (x->output_options & OPO_AUTO_ENCODE)
1284     {
1285       /* It's okay if this is done more than once since add_encoding()
1286          is idempotent over identical encodings. */
1287       add_encoding (this, x->prop->font->encoding);
1288       add_encoding (this, x->fixed->font->encoding);
1289     }
1290
1291   x->file_page_number = 0;
1292
1293   errno = 0;
1294   if (prologue_fn == NULL)
1295     {
1296       msg (IE, _("Cannot find PostScript prologue.  The use of `-vv' "
1297                  "on the command line is suggested as a debugging aid."));
1298       return 0;
1299     }
1300
1301   msg (VM (1), _("%s: %s: Opening PostScript prologue..."),
1302        this->name, prologue_fn);
1303   prologue_file = fopen (prologue_fn, "rb");
1304   if (prologue_file == NULL)
1305     {
1306       fclose (prologue_file);
1307       free (prologue_fn);
1308       msg (IE, "%s: %s", prologue_fn, strerror (errno));
1309       goto error;
1310     }
1311
1312   sprintf (boundbox, "0 0 %d %d",
1313            x->w / (PSUS / 72) + (x->w % (PSUS / 72) > 0),
1314            x->l / (PSUS / 72) + (x->l % (PSUS / 72) > 0));
1315   dict[0].value = boundbox;
1316
1317   dict[1].value = (char *) version;
1318
1319   curtime = time (NULL);
1320   loctime = localtime (&curtime);
1321   dict[2].value = asctime (loctime);
1322   cp = strchr (dict[2].value, '\n');
1323   if (cp)
1324     *cp = 0;
1325
1326   switch (x->data)
1327     {
1328     case ODA_CLEAN7BIT:
1329       dict[3].value = "Clean7Bit";
1330       break;
1331     case ODA_CLEAN8BIT:
1332       dict[3].value = "Clean8Bit";
1333       break;
1334     case ODA_BINARY:
1335       dict[3].value = "Binary";
1336       break;
1337     default:
1338       assert (0);
1339     }
1340
1341   if (x->orientation == OTN_PORTRAIT)
1342     dict[4].value = "Portrait";
1343   else
1344     dict[4].value = "Landscape";
1345
1346   /* PORTME: Determine username, net address. */
1347 #if HAVE_UNISTD_H
1348   dict[5].value = getenv ("LOGNAME");
1349   if (!dict[5].value)
1350     dict[5].value = getlogin ();
1351   if (!dict[5].value)
1352     dict[5].value = _("nobody");
1353
1354   if (gethostname (host, 128) == -1)
1355     {
1356       if (errno == ENAMETOOLONG)
1357         host[127] = 0;
1358       else
1359         strcpy (host, _("nowhere"));
1360     }
1361   dict[6].value = host;
1362 #else /* !HAVE_UNISTD_H */
1363   dict[5].value = _("nobody");
1364   dict[6].value = _("nowhere");
1365 #endif /* !HAVE_UNISTD_H */
1366
1367   cp = stpcpy (p = local_alloc (288), "font ");
1368   quote_ps_string (cp, x->prop->font->internal_name);
1369   dict[7].value = p;
1370
1371   cp = stpcpy (p = local_alloc (288), "font ");
1372   quote_ps_string (cp, x->fixed->font->internal_name);
1373   dict[8].value = p;
1374
1375   sprintf (scaling, "%.3f", PSUS / 72.0);
1376   dict[9].value = scaling;
1377
1378   sprintf (paper_width, "%g", x->w / (PSUS / 72.0));
1379   dict[10].value = paper_width;
1380
1381   sprintf (paper_length, "%g", x->l / (PSUS / 72.0));
1382   dict[11].value = paper_length;
1383
1384   sprintf (left_margin, "%d", x->left_margin);
1385   dict[12].value = left_margin;
1386
1387   sprintf (top_margin, "%d", x->top_margin);
1388   dict[13].value = top_margin;
1389
1390   sprintf (line_width, "%d", x->line_width);
1391   dict[14].value = line_width;
1392
1393   sprintf (line_width, "%d", x->line_width_thick);
1394   dict[15].value = line_width_thick;
1395   
1396   if (!outp_title)
1397     {
1398       dict[16].value = cp = local_alloc (strlen (dict[17].value) + 30);
1399       sprintf (cp, "PSPP (%s)", dict[17].value);
1400     }
1401   else
1402     {
1403       dict[16].value = local_alloc (strlen (outp_title) + 1);
1404       strcpy ((char *) (dict[16].value), outp_title);
1405     }
1406   
1407   ps_var_tab = dict;
1408   while (-1 != getline (&buf, &buf_size, prologue_file))
1409     {
1410       char *cp;
1411       char *buf2;
1412       int len;
1413
1414       cp = strstr (buf, "!eps");
1415       if (cp)
1416         {
1417           if (this->class->magic == MAGIC_PS)
1418             continue;
1419           else
1420             *cp = '\0';
1421         }
1422       else
1423         {
1424           cp = strstr (buf, "!ps");
1425           if (cp)
1426             {
1427               if (this->class->magic == MAGIC_EPSF)
1428                 continue;
1429               else
1430                 *cp = '\0';
1431             } else {
1432               if (strstr (buf, "!!!"))
1433                 continue;
1434             }
1435         }
1436
1437       if (!strncmp (buf, "!encodings", 10))
1438         output_encodings (this);
1439       else
1440         {
1441           char *beg;
1442           beg = buf2 = fn_interp_vars (buf, ps_get_var);
1443           len = strlen (buf2);
1444           while (isspace ((unsigned char) *beg))
1445             beg++, len--;
1446           if (beg[len - 1] == '\n')
1447             len--;
1448           if (beg[len - 1] == '\r')
1449             len--;
1450           fwrite (beg, len, 1, f->file);
1451           fputs (x->eol, f->file);
1452           free (buf2);
1453         }
1454     }
1455   if (ferror (f->file))
1456     msg (IE, _("Reading `%s': %s."), prologue_fn, strerror (errno));
1457   fclose (prologue_file);
1458
1459   free (prologue_fn);
1460   free (buf);
1461
1462   local_free (dict[7].value);
1463   local_free (dict[8].value);
1464   local_free (dict[16].value);
1465
1466   if (ferror (f->file))
1467     goto error;
1468
1469   msg (VM (2), _("%s: PostScript prologue read successfully."), this->name);
1470   return 1;
1471
1472 error:
1473   msg (VM (1), _("%s: Error reading PostScript prologue."), this->name);
1474   return 0;
1475 }
1476
1477 /* Writes the string STRING to buffer DEST (of at least 288
1478    characters) as a PostScript name object.  Returns a pointer
1479    to the null terminator of the resultant string. */
1480 static char *
1481 quote_ps_name (char *dest, const char *string)
1482 {
1483   const char *sp;
1484
1485   for (sp = string; *sp; sp++)
1486     switch (*sp)
1487       {
1488       case 'a':
1489       case 'f':
1490       case 'k':
1491       case 'p':
1492       case 'u':
1493       case 'b':
1494       case 'g':
1495       case 'l':
1496       case 'q':
1497       case 'v':
1498       case 'c':
1499       case 'h':
1500       case 'm':
1501       case 'r':
1502       case 'w':
1503       case 'd':
1504       case 'i':
1505       case 'n':
1506       case 's':
1507       case 'x':
1508       case 'e':
1509       case 'j':
1510       case 'o':
1511       case 't':
1512       case 'y':
1513       case 'z':
1514       case 'A':
1515       case 'F':
1516       case 'K':
1517       case 'P':
1518       case 'U':
1519       case 'B':
1520       case 'G':
1521       case 'L':
1522       case 'Q':
1523       case 'V':
1524       case 'C':
1525       case 'H':
1526       case 'M':
1527       case 'R':
1528       case 'W':
1529       case 'D':
1530       case 'I':
1531       case 'N':
1532       case 'S':
1533       case 'X':
1534       case 'E':
1535       case 'J':
1536       case 'O':
1537       case 'T':
1538       case 'Y':
1539       case 'Z':
1540       case '@':
1541       case '^':
1542       case '_':
1543       case '|':
1544       case '!':
1545       case '$':
1546       case '&':
1547       case ':':
1548       case ';':
1549       case '.':
1550       case ',':
1551       case '-':
1552       case '+':
1553         break;
1554       default:
1555         {
1556           char *dp = dest;
1557
1558           *dp++ = '<';
1559           for (sp = string; *sp && dp < &dest[256]; sp++)
1560             {
1561               sprintf (dp, "%02x", (unsigned char) *sp);
1562               dp += 2;
1563             }
1564           return stpcpy (dp, ">cvn");
1565         }
1566       }
1567   dest[0] = '/';
1568   return stpcpy (&dest[1], string);
1569 }
1570
1571 /* Adds the string STRING to buffer DEST as a PostScript quoted
1572    string; returns a pointer to the null terminator added.  Will not
1573    add more than 235 characters. */
1574 static char *
1575 quote_ps_string (char *dest, const char *string)
1576 {
1577   const char *sp = string;
1578   char *dp = dest;
1579
1580   *dp++ = '(';
1581   for (; *sp && dp < &dest[235]; sp++)
1582     if (*sp == '(')
1583       dp = stpcpy (dp, "\\(");
1584     else if (*sp == ')')
1585       dp = stpcpy (dp, "\\)");
1586     else if (*sp < 32 || (unsigned char) *sp > 127)
1587       dp = spprintf (dp, "\\%3o", *sp);
1588     else
1589       *dp++ = *sp;
1590   return stpcpy (dp, ")");
1591 }
1592
1593 /* Writes the PostScript epilogue to file F. */
1594 static int
1595 preclose (struct file_ext *f)
1596 {
1597   struct outp_driver *this = f->param;
1598   struct ps_driver_ext *x = this->ext;
1599   struct hsh_iterator iter;
1600   struct font_entry *fe;
1601
1602   fprintf (f->file,
1603            ("%%%%Trailer%s"
1604             "%%%%Pages: %d%s"
1605             "%%%%DocumentNeededResources:%s"),
1606            x->eol, x->file_page_number, x->eol, x->eol);
1607
1608   for (fe = hsh_first (x->loaded, &iter); fe != NULL;
1609        fe = hsh_next (x->loaded, &iter)) 
1610     {
1611       char buf[256], *cp;
1612
1613       cp = stpcpy (buf, "%%+ font ");
1614       cp = quote_ps_string (cp, fe->font->internal_name);
1615       strcpy (cp, x->eol);
1616       fputs (buf, f->file);
1617     }
1618
1619   hsh_destroy (x->loaded);
1620   x->loaded = NULL;
1621   hsh_destroy (x->combos);
1622   x->combos = NULL;
1623   x->last_font = NULL;
1624   x->next_combo = 0;
1625
1626   fprintf (f->file, "%%EOF%s", x->eol);
1627   if (ferror (f->file))
1628     return 0;
1629   return 1;
1630 }
1631
1632 static int
1633 ps_open_page (struct outp_driver *this)
1634 {
1635   struct ps_driver_ext *x = this->ext;
1636
1637   assert (this->driver_open && !this->page_open);
1638       
1639   x->page_number++;
1640   if (!fn_open_ext (&x->file))
1641     {
1642       if (errno)
1643         msg (ME, _("PostScript output driver: %s: %s"), x->file.filename,
1644              strerror (errno));
1645       return 0;
1646     }
1647   x->file_page_number++;
1648
1649   hsh_destroy (x->combos);
1650   x->combos = hsh_create (31, compare_ps_combo, hash_ps_combo,
1651                           free_ps_combo, NULL);
1652   x->last_font = NULL;
1653   x->next_combo = 0;
1654
1655   fprintf (x->file.file,
1656            "%%%%Page: %d %d%s"
1657            "%%%%BeginPageSetup%s"
1658            "/pg save def 0.001 dup scale%s",
1659            x->page_number, x->file_page_number, x->eol,
1660            x->eol,
1661            x->eol);
1662
1663   if (x->orientation == OTN_LANDSCAPE)
1664     fprintf (x->file.file,
1665              "%d 0 translate 90 rotate%s",
1666              x->w, x->eol);
1667
1668   if (x->bottom_margin != 0 || x->left_margin != 0)
1669     fprintf (x->file.file,
1670              "%d %d translate%s",
1671              x->left_margin, x->bottom_margin, x->eol);
1672
1673   fprintf (x->file.file,
1674            "/LW %d def/TW %d def %d setlinewidth%s"
1675            "%%%%EndPageSetup%s",
1676            x->line_width, x->line_width_thick, x->line_width, x->eol,
1677            x->eol);
1678
1679   if (!ferror (x->file.file))
1680     {
1681       this->page_open = 1;
1682       if (x->output_options & OPO_HEADERS)
1683         draw_headers (this);
1684     }
1685
1686   this->cp_y = 0;
1687
1688   return !ferror (x->file.file);
1689 }
1690
1691 static int
1692 ps_close_page (struct outp_driver *this)
1693 {
1694   struct ps_driver_ext *x = this->ext;
1695
1696   assert (this->driver_open && this->page_open);
1697   
1698   if (x->line_opt)
1699     dump_lines (this);
1700
1701   fprintf (x->file.file,
1702            "%%PageTrailer%s"
1703            "EP%s",
1704            x->eol, x->eol);
1705
1706   this->page_open = 0;
1707   return !ferror (x->file.file);
1708 }
1709
1710 static void
1711 ps_submit (struct outp_driver *this UNUSED, struct som_entity *s)
1712 {
1713   switch (s->type) 
1714     {
1715     case SOM_CHART:
1716       break;
1717     default:
1718       assert(0);
1719       break;
1720     }
1721 }
1722 \f
1723 /* Lines. */
1724
1725 /* qsort() comparison function for int tuples. */
1726 static int
1727 int_2_compare (const void *a_, const void *b_)
1728 {
1729   const int *a = a_;
1730   const int *b = b_;
1731
1732   return *a < *b ? -1 : *a > *b;
1733 }
1734
1735 /* Hash table comparison function for cached lines. */
1736 static int
1737 compare_line (const void *a_, const void *b_, void *foo UNUSED)
1738 {
1739   const struct line_form *a = a_;
1740   const struct line_form *b = b_;
1741
1742   return a->ind < b->ind ? -1 : a->ind > b->ind;
1743 }
1744
1745 /* Hash table hash function for cached lines. */
1746 static unsigned
1747 hash_line (const void *pa, void *foo UNUSED)
1748 {
1749   const struct line_form *a = pa;
1750
1751   return a->ind;
1752 }
1753
1754 /* Hash table free function for cached lines. */
1755 static void
1756 free_line (void *pa, void *foo UNUSED)
1757 {
1758   free (pa);
1759 }
1760
1761 /* Writes PostScript code to draw a line from (x1,y1) to (x2,y2) to
1762    the output file. */
1763 #define dump_line(x1, y1, x2, y2)                       \
1764         fprintf (ext->file.file, "%d %d %d %d L%s",     \
1765                  x1, YT (y1), x2, YT (y2), ext->eol)
1766
1767 /* Write PostScript code to draw a thick line from (x1,y1) to (x2,y2)
1768    to the output file. */
1769 #define dump_thick_line(x1, y1, x2, y2)                 \
1770         fprintf (ext->file.file, "%d %d %d %d TL%s",    \
1771                  x1, YT (y1), x2, YT (y2), ext->eol)
1772
1773 /* Writes a line of type TYPE to THIS driver's output file.  The line
1774    (or its center, in the case of double lines) has its independent
1775    axis coordinate at IND; it extends from DEP1 to DEP2 on the
1776    dependent axis. */
1777 static void
1778 dump_fancy_line (struct outp_driver *this, int type, int ind, int dep1, int dep2)
1779 {
1780   struct ps_driver_ext *ext = this->ext;
1781   int ofs = ext->line_space / 2 + ext->line_width / 2;
1782
1783   switch (type)
1784     {
1785     case horz:
1786       dump_line (dep1, ind, dep2, ind);
1787       break;
1788     case dbl_horz:
1789       if (ext->output_options & OPO_DOUBLE_LINE)
1790         {
1791           dump_line (dep1, ind - ofs, dep2, ind - ofs);
1792           dump_line (dep1, ind + ofs, dep2, ind + ofs);
1793         }
1794       else
1795         dump_thick_line (dep1, ind, dep2, ind);
1796       break;
1797     case spl_horz:
1798       assert (0);
1799     case vert:
1800       dump_line (ind, dep1, ind, dep2);
1801       break;
1802     case dbl_vert:
1803       if (ext->output_options & OPO_DOUBLE_LINE)
1804         {
1805           dump_line (ind - ofs, dep1, ind - ofs, dep2);
1806           dump_line (ind + ofs, dep1, ind + ofs, dep2);
1807         }
1808       else
1809         dump_thick_line (ind, dep1, ind, dep2);
1810       break;
1811     case spl_vert:
1812       assert (0);
1813     default:
1814       assert (0);
1815     }
1816 }
1817
1818 #undef dump_line
1819
1820 /* Writes all the cached lines to the output file, then clears the
1821    cache. */
1822 static void
1823 dump_lines (struct outp_driver *this)
1824 {
1825   struct ps_driver_ext *x = this->ext;
1826
1827   struct hsh_iterator iter;
1828   int type;
1829
1830   for (type = 0; type < n_line_types; type++)
1831     {
1832       struct line_form *line;
1833
1834       if (x->lines[type] == NULL) 
1835         continue;
1836
1837       for (line = hsh_first (x->lines[type], &iter); line != NULL;
1838            line = hsh_next (x->lines[type], &iter)) 
1839         {
1840           int i;
1841           int lo = INT_MIN, hi;
1842
1843           qsort (line->dep, line->ndep, sizeof *line->dep, int_2_compare);
1844           lo = line->dep[0][0];
1845           hi = line->dep[0][1];
1846           for (i = 1; i < line->ndep; i++)
1847             if (line->dep[i][0] <= hi + 1)
1848               {
1849                 int min_hi = line->dep[i][1];
1850                 if (min_hi > hi)
1851                   hi = min_hi;
1852               }
1853             else
1854               {
1855                 dump_fancy_line (this, type, line->ind, lo, hi);
1856                 lo = line->dep[i][0];
1857                 hi = line->dep[i][1];
1858               }
1859           dump_fancy_line (this, type, line->ind, lo, hi);
1860         }
1861
1862       hsh_destroy (x->lines[type]);
1863       x->lines[type] = NULL;
1864     }
1865 }
1866
1867 /* (Same args as dump_fancy_line()).  Either dumps the line directly
1868    to the output file, or adds it to the cache, depending on the
1869    user-selected line optimization mode. */
1870 static void
1871 line (struct outp_driver *this, int type, int ind, int dep1, int dep2)
1872 {
1873   struct ps_driver_ext *ext = this->ext;
1874   struct line_form **f;
1875
1876   assert (dep2 >= dep1);
1877   if (ext->line_opt == 0)
1878     {
1879       dump_fancy_line (this, type, ind, dep1, dep2);
1880       return;
1881     }
1882
1883   if (ext->lines[type] == NULL)
1884     ext->lines[type] = hsh_create (31, compare_line, hash_line,
1885                                    free_line, NULL);
1886   f = (struct line_form **) hsh_probe (ext->lines[type], &ind);
1887   if (*f == NULL)
1888     {
1889       *f = xmalloc (sizeof **f + sizeof (int[15][2]));
1890       (*f)->ind = ind;
1891       (*f)->mdep = 16;
1892       (*f)->ndep = 1;
1893       (*f)->dep[0][0] = dep1;
1894       (*f)->dep[0][1] = dep2;
1895       return;
1896     }
1897   if ((*f)->ndep >= (*f)->mdep)
1898     {
1899       (*f)->mdep += 16;
1900       *f = xrealloc (*f, sizeof **f + sizeof (int[2]) * ((*f)->mdep - 1));
1901     }
1902   (*f)->dep[(*f)->ndep][0] = dep1;
1903   (*f)->dep[(*f)->ndep][1] = dep2;
1904   (*f)->ndep++;
1905 }
1906
1907 static void
1908 ps_line_horz (struct outp_driver *this, const struct rect *r,
1909               const struct color *c UNUSED, int style)
1910 {
1911   /* Must match output.h:OUTP_L_*. */
1912   static const int types[OUTP_L_COUNT] =
1913   {-1, horz, dbl_horz, spl_horz};
1914
1915   int y = (r->y1 + r->y2) / 2;
1916
1917   assert (this->driver_open && this->page_open);
1918   assert (style >= 0 && style < OUTP_L_COUNT);
1919   style = types[style];
1920   if (style != -1)
1921     line (this, style, y, r->x1, r->x2);
1922 }
1923
1924 static void
1925 ps_line_vert (struct outp_driver *this, const struct rect *r,
1926               const struct color *c UNUSED, int style)
1927 {
1928   /* Must match output.h:OUTP_L_*. */
1929   static const int types[OUTP_L_COUNT] =
1930   {-1, vert, dbl_vert, spl_vert};
1931
1932   int x = (r->x1 + r->x2) / 2;
1933
1934   assert (this->driver_open && this->page_open);
1935   assert (style >= 0 && style < OUTP_L_COUNT);
1936   style = types[style];
1937   if (style != -1)
1938     line (this, style, x, r->y1, r->y2);
1939 }
1940
1941 #define L (style->l != OUTP_L_NONE)
1942 #define R (style->r != OUTP_L_NONE)
1943 #define T (style->t != OUTP_L_NONE)
1944 #define B (style->b != OUTP_L_NONE)
1945
1946 static void
1947 ps_line_intersection (struct outp_driver *this, const struct rect *r,
1948                       const struct color *c UNUSED,
1949                       const struct outp_styles *style)
1950 {
1951   struct ps_driver_ext *ext = this->ext;
1952
1953   int x = (r->x1 + r->x2) / 2;
1954   int y = (r->y1 + r->y2) / 2;
1955   int ofs = (ext->line_space + ext->line_width) / 2;
1956   int x1 = x - ofs, x2 = x + ofs;
1957   int y1 = y - ofs, y2 = y + ofs;
1958
1959   assert (this->driver_open && this->page_open);
1960   assert (!((style->l != style->r && style->l != OUTP_L_NONE
1961              && style->r != OUTP_L_NONE)
1962             || (style->t != style->b && style->t != OUTP_L_NONE
1963                 && style->b != OUTP_L_NONE)));
1964
1965   switch ((style->l | style->r) | ((style->t | style->b) << 8))
1966     {
1967     case (OUTP_L_SINGLE) | (OUTP_L_SINGLE << 8):
1968     case (OUTP_L_SINGLE) | (OUTP_L_NONE << 8):
1969     case (OUTP_L_NONE) | (OUTP_L_SINGLE << 8):
1970       if (L)
1971         line (this, horz, y, r->x1, x);
1972       if (R)
1973         line (this, horz, y, x, r->x2);
1974       if (T)
1975         line (this, vert, x, r->y1, y);
1976       if (B)
1977         line (this, vert, x, y, r->y2);
1978       break;
1979     case (OUTP_L_SINGLE) | (OUTP_L_DOUBLE << 8):
1980     case (OUTP_L_NONE) | (OUTP_L_DOUBLE << 8):
1981       if (L)
1982         line (this, horz, y, r->x1, x1);
1983       if (R)
1984         line (this, horz, y, x2, r->x2);
1985       if (T)
1986         line (this, dbl_vert, x, r->y1, y);
1987       if (B)
1988         line (this, dbl_vert, x, y, r->y2);
1989       if ((L && R) && !(T && B))
1990         line (this, horz, y, x1, x2);
1991       break;
1992     case (OUTP_L_DOUBLE) | (OUTP_L_SINGLE << 8):
1993     case (OUTP_L_DOUBLE) | (OUTP_L_NONE << 8):
1994       if (L)
1995         line (this, dbl_horz, y, r->x1, x);
1996       if (R)
1997         line (this, dbl_horz, y, x, r->x2);
1998       if (T)
1999         line (this, vert, x, r->y1, y);
2000       if (B)
2001         line (this, vert, x, y, r->y2);
2002       if ((T && B) && !(L && R))
2003         line (this, vert, x, y1, y2);
2004       break;
2005     case (OUTP_L_DOUBLE) | (OUTP_L_DOUBLE << 8):
2006       if (L)
2007         line (this, dbl_horz, y, r->x1, x);
2008       if (R)
2009         line (this, dbl_horz, y, x, r->x2);
2010       if (T)
2011         line (this, dbl_vert, x, r->y1, y);
2012       if (B)
2013         line (this, dbl_vert, x, y, r->y2);
2014       if (T && B && !L)
2015         line (this, vert, x1, y1, y2);
2016       if (T && B && !R)
2017         line (this, vert, x2, y1, y2);
2018       if (L && R && !T)
2019         line (this, horz, y1, x1, x2);
2020       if (L && R && !B)
2021         line (this, horz, y2, x1, x2);
2022       break;
2023     default:
2024       assert (0);
2025     }
2026 }
2027
2028 static void
2029 ps_box (struct outp_driver *this UNUSED, const struct rect *r UNUSED,
2030         const struct color *bord UNUSED, const struct color *fill UNUSED)
2031 {
2032   assert (this->driver_open && this->page_open);
2033 }
2034
2035 static void 
2036 ps_polyline_begin (struct outp_driver *this UNUSED,
2037                    const struct color *c UNUSED)
2038 {
2039   assert (this->driver_open && this->page_open);
2040 }
2041 static void 
2042 ps_polyline_point (struct outp_driver *this UNUSED, int x UNUSED, int y UNUSED)
2043 {
2044   assert (this->driver_open && this->page_open);
2045 }
2046 static void 
2047 ps_polyline_end (struct outp_driver *this UNUSED)
2048 {
2049   assert (this->driver_open && this->page_open);
2050 }
2051
2052 /* Returns the width of string S for THIS driver. */
2053 static int
2054 text_width (struct outp_driver *this, char *s)
2055 {
2056   struct outp_text text;
2057
2058   text.options = OUTP_T_JUST_LEFT;
2059   ls_init (&text.s, s, strlen (s));
2060   this->class->text_metrics (this, &text);
2061   return text.h;
2062 }
2063
2064 /* Write string S at location (X,Y) with width W for THIS driver. */
2065 static void
2066 out_text_plain (struct outp_driver *this, char *s, int x, int y, int w)
2067 {
2068   struct outp_text text;
2069
2070   text.options = OUTP_T_JUST_LEFT | OUTP_T_HORZ | OUTP_T_VERT;
2071   ls_init (&text.s, s, strlen (s));
2072   text.h = w;
2073   text.v = this->font_height;
2074   text.x = x;
2075   text.y = y;
2076   this->class->text_draw (this, &text);
2077 }
2078
2079 /* Draw top of page headers for THIS driver. */
2080 static void
2081 draw_headers (struct outp_driver *this)
2082 {
2083   struct ps_driver_ext *ext = this->ext;
2084   
2085   struct font_entry *old_current = ext->current;
2086   char *old_family = xstrdup (ext->family); /* FIXME */
2087   int old_size = ext->size;
2088
2089   int fh = this->font_height;
2090   int y = -3 * fh;
2091
2092   fprintf (ext->file.file, "%d %d %d %d GB%s",
2093            0, YT (y), this->width, YT (y + 2 * fh + ext->line_gutter),
2094            ext->eol);
2095   this->class->text_set_font_family (this, "T");
2096
2097   y += ext->line_width + ext->line_gutter;
2098   
2099   {
2100     int rh_width;
2101     char buf[128];
2102
2103     sprintf (buf, _("%s - Page %d"), get_start_date (), ext->page_number);
2104     rh_width = text_width (this, buf);
2105
2106     out_text_plain (this, buf, this->width - this->prop_em_width - rh_width,
2107                     y, rh_width);
2108
2109     if (outp_title && outp_subtitle)
2110       out_text_plain (this, outp_title, this->prop_em_width, y,
2111                       this->width - 3 * this->prop_em_width - rh_width);
2112
2113     y += fh;
2114   }
2115   
2116   {
2117     int rh_width;
2118     char buf[128];
2119     char *string = outp_subtitle ? outp_subtitle : outp_title;
2120
2121     sprintf (buf, "%s - %s", version, host_system);
2122     rh_width = text_width (this, buf);
2123     
2124     out_text_plain (this, buf, this->width - this->prop_em_width - rh_width,
2125                     y, rh_width);
2126
2127     if (string)
2128       out_text_plain (this, string, this->prop_em_width, y,
2129                       this->width - 3 * this->prop_em_width - rh_width);
2130
2131     y += fh;
2132   }
2133
2134   ext->current = old_current;
2135   free (ext->family);
2136   ext->family = old_family;
2137   ext->size = old_size;
2138 }
2139
2140 \f
2141 /* Text. */
2142
2143 static void
2144 ps_text_set_font_by_name (struct outp_driver *this, const char *dit)
2145 {
2146   struct ps_driver_ext *x = this->ext;
2147   struct font_entry *fe;
2148
2149   assert (this->driver_open && this->page_open);
2150   
2151   /* Short-circuit common fonts. */
2152   if (!strcmp (dit, "PROP"))
2153     {
2154       x->current = x->prop;
2155       x->size = x->font_size;
2156       return;
2157     }
2158   else if (!strcmp (dit, "FIXED"))
2159     {
2160       x->current = x->fixed;
2161       x->size = x->font_size;
2162       return;
2163     }
2164
2165   /* Find font_desc corresponding to Groff name dit. */
2166   fe = hsh_find (x->loaded, &dit);
2167   if (fe == NULL)
2168     fe = load_font (this, dit);
2169   x->current = fe;
2170 }
2171
2172 static void
2173 ps_text_set_font_by_position (struct outp_driver *this, int pos)
2174 {
2175   struct ps_driver_ext *x = this->ext;
2176   char *dit;
2177
2178   assert (this->driver_open && this->page_open);
2179
2180   /* Determine font name by suffixing position string to font family
2181      name. */
2182   {
2183     char *cp;
2184
2185     dit = local_alloc (strlen (x->family) + 3);
2186     cp = stpcpy (dit, x->family);
2187     switch (pos)
2188       {
2189       case OUTP_F_R:
2190         *cp++ = 'R';
2191         break;
2192       case OUTP_F_I:
2193         *cp++ = 'I';
2194         break;
2195       case OUTP_F_B:
2196         *cp++ = 'B';
2197         break;
2198       case OUTP_F_BI:
2199         *cp++ = 'B';
2200         *cp++ = 'I';
2201         break;
2202       default:
2203         assert(0);
2204       }
2205     *cp++ = 0;
2206   }
2207   
2208   /* Find font_desc corresponding to Groff name dit. */
2209   {
2210     struct font_entry *fe = hsh_find (x->loaded, &dit);
2211     if (fe == NULL)
2212       fe = load_font (this, dit);
2213     x->current = fe;
2214   }
2215
2216   local_free (dit);
2217 }
2218
2219 static void
2220 ps_text_set_font_family (struct outp_driver *this, const char *s)
2221 {
2222   struct ps_driver_ext *x = this->ext;
2223
2224   assert (this->driver_open && this->page_open);
2225   
2226   free(x->family);
2227   x->family = xstrdup (s);
2228 }
2229
2230 static const char *
2231 ps_text_get_font_name (struct outp_driver *this)
2232 {
2233   struct ps_driver_ext *x = this->ext;
2234
2235   assert (this->driver_open && this->page_open);
2236   return x->current->font->name;
2237 }
2238
2239 static const char *
2240 ps_text_get_font_family (struct outp_driver *this)
2241 {
2242   struct ps_driver_ext *x = this->ext;
2243   
2244   assert (this->driver_open && this->page_open);
2245   return x->family;
2246 }
2247
2248 static int
2249 ps_text_set_size (struct outp_driver *this, int size)
2250 {
2251   struct ps_driver_ext *x = this->ext;
2252
2253   assert (this->driver_open && this->page_open);
2254   x->size = PSUS / 72000 * size;
2255   return 1;
2256 }
2257
2258 static int
2259 ps_text_get_size (struct outp_driver *this, int *em_width)
2260 {
2261   struct ps_driver_ext *x = this->ext;
2262
2263   assert (this->driver_open && this->page_open);
2264   if (em_width)
2265     *em_width = (x->current->font->space_width * x->size) / 1000;
2266   return x->size / (PSUS / 72000);
2267 }
2268
2269 /* An output character. */
2270 struct output_char
2271   {
2272     struct font_entry *font;    /* Font of character. */
2273     int size;                   /* Size of character. */
2274     int x, y;                   /* Location of character. */
2275     unsigned char ch;           /* Character. */
2276     char separate;              /* Must be separate from previous char. */
2277   };
2278
2279 /* Hash table comparison function for ps_combo structs. */
2280 static int
2281 compare_ps_combo (const void *pa, const void *pb, void *foo UNUSED)
2282 {
2283   const struct ps_font_combo *a = pa;
2284   const struct ps_font_combo *b = pb;
2285
2286   return !((a->font == b->font) && (a->size == b->size));
2287 }
2288
2289 /* Hash table hash function for ps_combo structs. */
2290 static unsigned
2291 hash_ps_combo (const void *pa, void *foo UNUSED)
2292 {
2293   const struct ps_font_combo *a = pa;
2294   unsigned name_hash = hsh_hash_string (a->font->font->internal_name);
2295   return name_hash ^ hsh_hash_int (a->size);
2296 }
2297
2298 /* Hash table free function for ps_combo structs. */
2299 static void
2300 free_ps_combo (void *a, void *foo UNUSED)
2301 {
2302   free (a);
2303 }
2304
2305 /* Causes PostScript code to be output that switches to the font
2306    CP->FONT and font size CP->SIZE.  The first time a particular
2307    font/size combination is used on a particular page, this involves
2308    outputting PostScript code to load the font. */
2309 static void
2310 switch_font (struct outp_driver *this, const struct output_char *cp)
2311 {
2312   struct ps_driver_ext *ext = this->ext;
2313   struct ps_font_combo srch, **fc;
2314
2315   srch.font = cp->font;
2316   srch.size = cp->size;
2317
2318   fc = (struct ps_font_combo **) hsh_probe (ext->combos, &srch);
2319   if (*fc)
2320     {
2321       fprintf (ext->file.file, "F%x%s", (*fc)->index, ext->eol);
2322     }
2323   else
2324     {
2325       char *filename;
2326       struct ps_encoding *encoding;
2327       char buf[512], *bp;
2328
2329       *fc = xmalloc (sizeof **fc);
2330       (*fc)->font = cp->font;
2331       (*fc)->size = cp->size;
2332       (*fc)->index = ext->next_combo++;
2333
2334       filename = find_encoding_file (this, cp->font->font->encoding);
2335       if (filename)
2336         {
2337           encoding = get_encoding (this, filename);
2338           free (filename);
2339         }
2340       else
2341         {
2342           msg (IE, _("PostScript driver: Cannot find encoding `%s' for "
2343                "PostScript font `%s'."), cp->font->font->encoding,
2344                cp->font->font->internal_name);
2345           encoding = default_encoding (this);
2346         }
2347
2348       if (cp->font != ext->fixed && cp->font != ext->prop)
2349         {
2350           bp = stpcpy (buf, "%%IncludeResource: font ");
2351           bp = quote_ps_string (bp, cp->font->font->internal_name);
2352           bp = stpcpy (bp, ext->eol);
2353         }
2354       else
2355         bp = buf;
2356
2357       bp = spprintf (bp, "/F%x E%x %d", (*fc)->index, encoding->index,
2358                      cp->size);
2359       bp = quote_ps_name (bp, cp->font->font->internal_name);
2360       sprintf (bp, " SF%s", ext->eol);
2361       fputs (buf, ext->file.file);
2362     }
2363   ext->last_font = *fc;
2364 }
2365
2366 /* (write_text) Writes the accumulated line buffer to the output
2367    file. */
2368 #define output_line()                           \
2369         do                                      \
2370           {                                     \
2371             lp = stpcpy (lp, ext->eol);         \
2372             *lp = 0;                            \
2373             fputs (line, ext->file.file);       \
2374             lp = line;                          \
2375           }                                     \
2376         while (0)
2377
2378 /* (write_text) Adds the string representing number X to the line
2379    buffer, flushing the buffer to disk beforehand if necessary. */
2380 #define put_number(X)                           \
2381         do                                      \
2382           {                                     \
2383             int n = nsprintf (number, "%d", X); \
2384             if (n + lp > &line[75])             \
2385               output_line ();                   \
2386             lp = stpcpy (lp, number);           \
2387           }                                     \
2388         while (0)
2389
2390 /* Outputs PostScript code to THIS driver's output file to display the
2391    characters represented by the output_char's between CP and END,
2392    using the associated outp_text T to determine formatting.  WIDTH is
2393    the width of the output region; WIDTH_LEFT is the amount of the
2394    WIDTH that is not taken up by text (so it can be used to determine
2395    justification). */
2396 static void
2397 write_text (struct outp_driver *this,
2398             const struct output_char *cp, const struct output_char *end,
2399             struct outp_text *t, int width UNUSED, int width_left)
2400 {
2401   struct ps_driver_ext *ext = this->ext;
2402   int ofs;
2403
2404   int last_y;
2405
2406   char number[INT_STRLEN_BOUND (int) + 1];
2407   char line[80];
2408   char *lp;
2409
2410   switch (t->options & OUTP_T_JUST_MASK)
2411     {
2412     case OUTP_T_JUST_LEFT:
2413       ofs = 0;
2414       break;
2415     case OUTP_T_JUST_RIGHT:
2416       ofs = width_left;
2417       break;
2418     case OUTP_T_JUST_CENTER:
2419       ofs = width_left / 2;
2420       break;
2421     default:
2422       assert (0);
2423       abort ();
2424     }
2425
2426   lp = line;
2427   last_y = INT_MIN;
2428   while (cp < end)
2429     {
2430       int x = cp->x + ofs;
2431       int y = cp->y + (cp->font->font->ascent * cp->size / 1000);
2432
2433       if (ext->last_font == NULL
2434           || cp->font != ext->last_font->font
2435           || cp->size != ext->last_font->size)
2436         switch_font (this, cp);
2437
2438       *lp++ = '(';
2439       do
2440         {
2441           /* PORTME! */
2442           static unsigned char literal_chars[ODA_COUNT][32] =
2443           {
2444             {0x00, 0x00, 0x00, 0xf8, 0xff, 0xfc, 0xff, 0xff,
2445              0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
2446              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2447              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2448             },
2449             {0x00, 0x00, 0x00, 0xf8, 0xff, 0xfc, 0xff, 0xff,
2450              0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
2451              0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
2452              0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
2453             },
2454             {0x7e, 0xd6, 0xff, 0xfb, 0xff, 0xfc, 0xff, 0xff,
2455              0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
2456              0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
2457              0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
2458             }
2459           };
2460
2461           if (TEST_BIT (literal_chars[ext->data], cp->ch))
2462             *lp++ = cp->ch;
2463           else
2464             switch ((char) cp->ch)
2465               {
2466               case '(':
2467                 lp = stpcpy (lp, "\\(");
2468                 break;
2469               case ')':
2470                 lp = stpcpy (lp, "\\)");
2471                 break;
2472               default:
2473                 lp = spprintf (lp, "\\%03o", cp->ch);
2474                 break;
2475               }
2476           cp++;
2477         }
2478       while (cp < end && lp < &line[70] && cp->separate == 0);
2479       *lp++ = ')';
2480
2481       put_number (x);
2482
2483       if (y != last_y)
2484         {
2485           *lp++ = ' ';
2486           put_number (YT (y));
2487           *lp++ = ' ';
2488           *lp++ = 'S';
2489           last_y = y;
2490         }
2491       else
2492         {
2493           *lp++ = ' ';
2494           *lp++ = 'T';
2495         }
2496
2497       if (lp >= &line[70])
2498         output_line ();
2499     }
2500   if (lp != line)
2501     output_line ();
2502 }
2503
2504 #undef output_line
2505 #undef put_number
2506
2507 /* Displays the text in outp_text T, if DRAW is nonzero; or, merely
2508    determine the text metrics, if DRAW is zero. */
2509 static void
2510 text (struct outp_driver *this, struct outp_text *t, int draw)
2511 {
2512   struct ps_driver_ext *ext = this->ext;
2513
2514   /* Output. */
2515   struct output_char *buf;      /* Output buffer. */
2516   struct output_char *buf_end;  /* End of output buffer. */
2517   struct output_char *buf_loc;  /* Current location in output buffer. */
2518
2519   /* Saved state. */
2520   struct font_entry *old_current = ext->current;
2521   char *old_family = xstrdup (ext->family); /* FIXME */
2522   int old_size = ext->size;
2523
2524   /* Input string. */
2525   char *cp, *end;
2526
2527   /* Current location. */
2528   int x, y;
2529
2530   /* Keeping track of what's left over. */
2531   int width;                    /* Width available for characters. */
2532   int width_left, height_left;  /* Width, height left over. */
2533   int max_height;               /* Tallest character on this line so far. */
2534
2535   /* Previous character. */
2536   int prev_char;
2537
2538   /* Information about location of previous space. */
2539   char *space_char;             /* Character after space. */
2540   struct output_char *space_buf_loc; /* Buffer location after space. */
2541   int space_width_left;         /* Width of characters before space. */
2542
2543   /* Name of the current character. */
2544   const char *char_name;
2545   char local_char_name[2] = {0, 0};
2546
2547   local_char_name[0] = local_char_name[1] = 0;
2548
2549   buf = local_alloc (sizeof *buf * 128);
2550   buf_end = &buf[128];
2551   buf_loc = buf;
2552
2553   assert (!ls_null_p (&t->s));
2554   cp = ls_c_str (&t->s);
2555   end = ls_end (&t->s);
2556   if (draw)
2557     {
2558       x = t->x;
2559       y = t->y;
2560     }
2561   else
2562     x = y = 0;
2563   width = width_left = (t->options & OUTP_T_HORZ) ? t->h : INT_MAX;
2564   height_left = (t->options & OUTP_T_VERT) ? t->v : INT_MAX;
2565   max_height = 0;
2566   prev_char = -1;
2567   space_char = NULL;
2568   space_buf_loc = NULL;
2569   space_width_left = 0;
2570   
2571
2572   if (!width || !height_left)
2573     goto exit;
2574
2575   while (cp < end)
2576     {
2577       struct char_metrics *metric;
2578       int cur_char;
2579       int kern_amt;
2580       int char_width;
2581       int separate = 0;
2582
2583       /* Set char_name to the name of the character or ligature at
2584          *cp. */
2585       local_char_name[0] = *cp;
2586       char_name = local_char_name;
2587       if (ext->current->font->ligatures && *cp == 'f')
2588         {
2589           int lig = 0;
2590           char_name = NULL;
2591
2592           if (cp < end - 1)
2593             switch (cp[1])
2594               {
2595               case 'i':
2596                 lig = LIG_fi, char_name = "fi";
2597                 break;
2598               case 'l':
2599                 lig = LIG_fl, char_name = "fl";
2600                 break;
2601               case 'f':
2602                 if (cp < end - 2)
2603                   switch (cp[2])
2604                     {
2605                     case 'i':
2606                       lig = LIG_ffi, char_name = "ffi";
2607                       goto got_ligature;
2608                     case 'l':
2609                       lig = LIG_ffl, char_name = "ffl";
2610                       goto got_ligature;
2611                     }
2612                 lig = LIG_ff, char_name = "ff";
2613               got_ligature:
2614                 break;
2615               }
2616           if ((lig & ext->current->font->ligatures) == 0)
2617             {
2618               local_char_name[0] = *cp; /* 'f' */
2619               char_name = local_char_name;
2620             }
2621         }
2622       else if (*cp == '\n')
2623         {
2624           if (draw)
2625             {
2626               write_text (this, buf, buf_loc, t, width, width_left);
2627               buf_loc = buf;
2628               x = t->x;
2629               y += max_height;
2630             }
2631
2632           width_left = width;
2633           height_left -= max_height;
2634           max_height = 0;
2635           kern_amt = 0;
2636           separate = 1;
2637           cp++;
2638
2639           /* FIXME: when we're page buffering it will be necessary to
2640              set separate to 1. */
2641           continue;
2642         }
2643       cp += strlen (char_name);
2644
2645       /* Figure out what size this character is, and what kern
2646          adjustment we need. */
2647       cur_char = font_char_name_to_index (char_name);
2648       metric = font_get_char_metrics (ext->current->font, cur_char);
2649       if (!metric)
2650         {
2651           static struct char_metrics m;
2652           metric = &m;
2653           m.width = ext->current->font->space_width;
2654           m.code = *char_name;
2655         }
2656       kern_amt = font_get_kern_adjust (ext->current->font, prev_char,
2657                                        cur_char);
2658       if (kern_amt)
2659         {
2660           kern_amt = (kern_amt * ext->size / 1000);
2661           separate = 1;
2662         }
2663       char_width = metric->width * ext->size / 1000;
2664
2665       /* Record the current status if this is a space character. */
2666       if (cur_char == space_index && buf_loc > buf)
2667         {
2668           space_char = cp;
2669           space_buf_loc = buf_loc;
2670           space_width_left = width_left;
2671         }
2672
2673       /* Drop down to a new line if there's no room left on this
2674          line. */
2675       if (char_width + kern_amt > width_left)
2676         {
2677           /* Regress to previous space, if any. */
2678           if (space_char)
2679             {
2680               cp = space_char;
2681               width_left = space_width_left;
2682               buf_loc = space_buf_loc;
2683             }
2684
2685           if (draw)
2686             {
2687               write_text (this, buf, buf_loc, t, width, width_left);
2688               buf_loc = buf;
2689               x = t->x;
2690               y += max_height;
2691             }
2692
2693           width_left = width;
2694           height_left -= max_height;
2695           max_height = 0;
2696           kern_amt = 0;
2697
2698           if (space_char)
2699             {
2700               space_char = NULL;
2701               prev_char = -1;
2702               /* FIXME: when we're page buffering it will be
2703                  necessary to set separate to 1. */
2704               continue;
2705             }
2706           separate = 1;
2707         }
2708       if (ext->size > max_height)
2709         max_height = ext->size;
2710       if (max_height > height_left)
2711         goto exit;
2712
2713       /* Actually draw the character. */
2714       if (draw)
2715         {
2716           if (buf_loc >= buf_end)
2717             {
2718               int buf_len = buf_end - buf;
2719
2720               if (buf_len == 128)
2721                 {
2722                   struct output_char *new_buf;
2723
2724                   new_buf = xmalloc (sizeof *new_buf * 256);
2725                   memcpy (new_buf, buf, sizeof *new_buf * 128);
2726                   buf_loc = new_buf + 128;
2727                   buf_end = new_buf + 256;
2728                   local_free (buf);
2729                   buf = new_buf;
2730                 }
2731               else
2732                 {
2733                   buf = xnrealloc (buf, buf_len * 2, sizeof *buf);
2734                   buf_loc = buf + buf_len;
2735                   buf_end = buf + buf_len * 2;
2736                 }
2737             }
2738
2739           x += kern_amt;
2740           buf_loc->font = ext->current;
2741           buf_loc->size = ext->size;
2742           buf_loc->x = x;
2743           buf_loc->y = y;
2744           buf_loc->ch = metric->code;
2745           buf_loc->separate = separate;
2746           buf_loc++;
2747           x += char_width;
2748         }
2749
2750       /* Prepare for next iteration. */
2751       width_left -= char_width + kern_amt;
2752       prev_char = cur_char;
2753     }
2754   height_left -= max_height;
2755   if (buf_loc > buf && draw)
2756     write_text (this, buf, buf_loc, t, width, width_left);
2757
2758 exit:
2759   if (!(t->options & OUTP_T_HORZ))
2760     t->h = INT_MAX - width_left;
2761   if (!(t->options & OUTP_T_VERT))
2762     t->v = INT_MAX - height_left;
2763   else
2764     t->v -= height_left;
2765   if (buf_end - buf == 128)
2766     local_free (buf);
2767   else
2768     free (buf);
2769   ext->current = old_current;
2770   free (ext->family);
2771   ext->family = old_family;
2772   ext->size = old_size;
2773 }
2774
2775 static void
2776 ps_text_metrics (struct outp_driver *this, struct outp_text *t)
2777 {
2778   assert (this->driver_open && this->page_open);
2779   text (this, t, 0);
2780 }
2781
2782 static void
2783 ps_text_draw (struct outp_driver *this, struct outp_text *t)
2784 {
2785   assert (this->driver_open && this->page_open);
2786   text (this, t, 1);
2787 }
2788 \f
2789 /* Font loader. */
2790
2791 /* Translate a filename to a font. */
2792 struct filename2font
2793   {
2794     char *filename;             /* Normalized filename. */
2795     struct font_desc *font;
2796   };
2797
2798 /* Table of `filename2font's. */
2799 static struct hsh_table *ps_fonts;
2800
2801 /* Hash table comparison function for filename2font structs. */
2802 static int
2803 compare_filename2font (const void *a, const void *b, void *param UNUSED)
2804 {
2805   return strcmp (((struct filename2font *) a)->filename,
2806                  ((struct filename2font *) b)->filename);
2807 }
2808
2809 /* Hash table hash function for filename2font structs. */
2810 static unsigned
2811 hash_filename2font (const void *f2f_, void *param UNUSED)
2812 {
2813   const struct filename2font *f2f = f2f_;
2814   return hsh_hash_string (f2f->filename);
2815 }
2816
2817 /* Initializes the global font list by creating the hash table for
2818    translation of filenames to font_desc structs. */
2819 static void
2820 init_fonts (void)
2821 {
2822   ps_fonts = hsh_create (31, compare_filename2font, hash_filename2font,
2823                          NULL, NULL);
2824 }
2825
2826 static void
2827 done_fonts (void)
2828 {
2829  hsh_destroy (ps_fonts);
2830 }
2831
2832 /* Loads the font having Groff name DIT into THIS driver instance.
2833    Specifically, adds it into the THIS driver's `loaded' hash
2834    table. */
2835 static struct font_entry *
2836 load_font (struct outp_driver *this, const char *dit)
2837 {
2838   struct ps_driver_ext *x = this->ext;
2839   char *filename1, *filename2;
2840   void **entry;
2841   struct font_entry *fe;
2842
2843   filename1 = find_ps_file (this, dit);
2844   if (!filename1)
2845     filename1 = xstrdup (dit);
2846   filename2 = fn_normalize (filename1);
2847   free (filename1);
2848
2849   entry = hsh_probe (ps_fonts, &filename2);
2850   if (*entry == NULL)
2851     {
2852       struct filename2font *f2f;
2853       struct font_desc *f = groff_read_font (filename2);
2854
2855       if (f == NULL)
2856         {
2857           if (x->fixed)
2858             f = x->fixed->font;
2859           else
2860             f = default_font ();
2861         }
2862       
2863       f2f = xmalloc (sizeof *f2f);
2864       f2f->filename = filename2;
2865       f2f->font = f;
2866       *entry = f2f;
2867     }
2868   else
2869     free (filename2);
2870
2871   fe = xmalloc (sizeof *fe);
2872   fe->dit = xstrdup (dit);
2873   fe->font = ((struct filename2font *) * entry)->font;
2874   *hsh_probe (x->loaded, &dit) = fe;
2875
2876   return fe;
2877 }
2878
2879 static void
2880 ps_chart_initialise (struct outp_driver *this UNUSED, struct chart *ch)
2881 {
2882 #ifdef NO_CHARTS
2883   ch->lp = NULL;
2884 #else
2885   struct ps_driver_ext *x = this->ext;
2886   char page_size[128];
2887   int size;
2888   int x_origin, y_origin;
2889
2890   ch->file = tmpfile ();
2891   if (ch->file == NULL) 
2892     {
2893       ch->lp = NULL;
2894       return;
2895     }
2896   
2897   size = this->width < this->length ? this->width : this->length;
2898   x_origin = x->left_margin + (size - this->width) / 2;
2899   y_origin = x->bottom_margin + (size - this->length) / 2;
2900
2901   snprintf (page_size, sizeof page_size,
2902             "a,xsize=%.3f,ysize=%.3f,xorigin=%.3f,yorigin=%.3f",
2903             (double) size / PSUS, (double) size / PSUS,
2904             (double) x_origin / PSUS, (double) y_origin / PSUS);
2905
2906   ch->pl_params = pl_newplparams ();
2907   pl_setplparam (ch->pl_params, "PAGESIZE", page_size);
2908   ch->lp = pl_newpl_r ("ps", NULL, ch->file, stderr, ch->pl_params);
2909 #endif
2910 }
2911
2912 static void 
2913 ps_chart_finalise (struct outp_driver *this UNUSED, struct chart *ch UNUSED)
2914 {
2915 #ifndef NO_CHARTS
2916   struct ps_driver_ext *x = this->ext;
2917   char buf[BUFSIZ];
2918   static int doc_num = 0;
2919
2920   if (this->page_open) 
2921     {
2922       this->class->close_page (this);
2923       this->page_open = 0; 
2924     }
2925   this->class->open_page (this);
2926   fprintf (x->file.file,
2927            "/sp save def%s"
2928            "%d %d translate 1000 dup scale%s"
2929            "userdict begin%s"
2930            "/showpage { } def%s"
2931            "0 setgray 0 setlinecap 1 setlinewidth%s"
2932            "0 setlinejoin 10 setmiterlimit [ ] 0 setdash newpath clear%s"
2933            "%%%%BeginDocument: %d%s",
2934            x->eol,
2935            -x->left_margin, -x->bottom_margin, x->eol,
2936            x->eol,
2937            x->eol,
2938            x->eol,
2939            x->eol,
2940            doc_num++, x->eol);
2941
2942   rewind (ch->file);
2943   while (fwrite (buf, 1, fread (buf, 1, sizeof buf, ch->file), x->file.file))
2944     continue;
2945   fclose (ch->file);
2946
2947   fprintf (x->file.file,
2948            "%%%%EndDocument%s"
2949            "end%s"
2950            "sp restore%s",
2951            x->eol,
2952            x->eol,
2953            x->eol);
2954   this->class->close_page (this);
2955   this->page_open = 0;
2956 #endif
2957 }
2958
2959 /* PostScript driver class. */
2960 struct outp_class postscript_class =
2961 {
2962   "postscript",
2963   MAGIC_PS,
2964   0,
2965
2966   ps_open_global,
2967   ps_close_global,
2968   ps_font_sizes,
2969
2970   ps_preopen_driver,
2971   ps_option,
2972   ps_postopen_driver,
2973   ps_close_driver,
2974
2975   ps_open_page,
2976   ps_close_page,
2977
2978   ps_submit,
2979
2980   ps_line_horz,
2981   ps_line_vert,
2982   ps_line_intersection,
2983
2984   ps_box,
2985   ps_polyline_begin,
2986   ps_polyline_point,
2987   ps_polyline_end,
2988
2989   ps_text_set_font_by_name,
2990   ps_text_set_font_by_position,
2991   ps_text_set_font_family,
2992   ps_text_get_font_name,
2993   ps_text_get_font_family,
2994   ps_text_set_size,
2995   ps_text_get_size,
2996   ps_text_metrics,
2997   ps_text_draw,
2998
2999   ps_chart_initialise,
3000   ps_chart_finalise
3001 };
3002
3003 /* EPSF driver class.  FIXME: Probably doesn't work right. */
3004 struct outp_class epsf_class =
3005 {
3006   "epsf",
3007   MAGIC_EPSF,
3008   0,
3009
3010   ps_open_global,
3011   ps_close_global,
3012   ps_font_sizes,
3013
3014   ps_preopen_driver,
3015   ps_option,
3016   ps_postopen_driver,
3017   ps_close_driver,
3018
3019   ps_open_page,
3020   ps_close_page,
3021
3022   ps_submit,
3023
3024   ps_line_horz,
3025   ps_line_vert,
3026   ps_line_intersection,
3027
3028   ps_box,
3029   ps_polyline_begin,
3030   ps_polyline_point,
3031   ps_polyline_end,
3032
3033   ps_text_set_font_by_name,
3034   ps_text_set_font_by_position,
3035   ps_text_set_font_family,
3036   ps_text_get_font_name,
3037   ps_text_get_font_family,
3038   ps_text_set_size,
3039   ps_text_get_size,
3040   ps_text_metrics,
3041   ps_text_draw,
3042
3043   ps_chart_initialise,
3044   ps_chart_finalise
3045
3046 };
3047
3048 #endif /* NO_POSTSCRIPT */