cairo: Remove unused 'command_name', 'title', 'subtitle' from xr_driver.
[pspp] / src / output / cairo.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "output/cairo.h"
20
21 #include "libpspp/assertion.h"
22 #include "libpspp/cast.h"
23 #include "libpspp/hash-functions.h"
24 #include "libpspp/message.h"
25 #include "libpspp/pool.h"
26 #include "libpspp/start-date.h"
27 #include "libpspp/str.h"
28 #include "libpspp/string-map.h"
29 #include "libpspp/version.h"
30 #include "data/file-handle-def.h"
31 #include "output/cairo-chart.h"
32 #include "output/chart-item-provider.h"
33 #include "output/charts/boxplot.h"
34 #include "output/charts/np-plot.h"
35 #include "output/charts/piechart.h"
36 #include "output/charts/barchart.h"
37 #include "output/charts/plot-hist.h"
38 #include "output/charts/roc-chart.h"
39 #include "output/charts/spreadlevel-plot.h"
40 #include "output/charts/scree.h"
41 #include "output/charts/scatterplot.h"
42 #include "output/driver-provider.h"
43 #include "output/group-item.h"
44 #include "output/message-item.h"
45 #include "output/options.h"
46 #include "output/page-setup-item.h"
47 #include "output/render.h"
48 #include "output/table-item.h"
49 #include "output/table.h"
50 #include "output/text-item.h"
51
52 #include <cairo/cairo-pdf.h>
53 #include <cairo/cairo-ps.h>
54 #include <cairo/cairo-svg.h>
55 #include <cairo/cairo.h>
56 #include <inttypes.h>
57 #include <math.h>
58 #include <pango/pango-font.h>
59 #include <pango/pango-layout.h>
60 #include <pango/pango.h>
61 #include <pango/pangocairo.h>
62 #include <stdlib.h>
63
64 #include "gl/c-ctype.h"
65 #include "gl/c-strcase.h"
66 #include "gl/intprops.h"
67 #include "gl/minmax.h"
68 #include "gl/xalloc.h"
69
70 #include "gettext.h"
71 #define _(msgid) gettext (msgid)
72
73 /* This file uses TABLE_HORZ and TABLE_VERT enough to warrant abbreviating. */
74 #define H TABLE_HORZ
75 #define V TABLE_VERT
76
77 /* The unit used for internal measurements is inch/(72 * XR_POINT).
78    (Thus, XR_POINT units represent one point.) */
79 #define XR_POINT PANGO_SCALE
80
81 /* Conversions to and from points. */
82 static double
83 xr_to_pt (int x)
84 {
85   return x / (double) XR_POINT;
86 }
87
88 /* Conversion from 1/96" units ("pixels") to Cairo/Pango units. */
89 static int
90 px_to_xr (int x)
91 {
92   return x * (PANGO_SCALE * 72 / 96);
93 }
94
95 /* Dimensions for drawing lines in tables. */
96 #define XR_LINE_WIDTH (XR_POINT / 2) /* Width of an ordinary line. */
97 #define XR_LINE_SPACE XR_POINT       /* Space between double lines. */
98
99 /* Output types. */
100 enum xr_output_type
101   {
102     XR_PDF,
103     XR_PS,
104     XR_SVG
105   };
106
107 /* Cairo fonts. */
108 enum xr_font_type
109   {
110     XR_FONT_PROPORTIONAL,
111     XR_FONT_EMPHASIS,
112     XR_FONT_FIXED,
113     XR_N_FONTS
114   };
115
116 /* A font for use with Cairo. */
117 struct xr_font
118   {
119     PangoFontDescription *desc;
120     PangoLayout *layout;
121   };
122
123 /* An output item whose rendering is in progress. */
124 struct xr_render_fsm
125   {
126     /* Renders as much of itself as it can on the current page.  Returns true
127        if rendering is complete, false if the output item needs another
128        page. */
129     bool (*render) (struct xr_render_fsm *, struct xr_driver *);
130
131     /* Destroys the output item. */
132     void (*destroy) (struct xr_render_fsm *);
133   };
134
135 /* Cairo output driver. */
136 struct xr_driver
137   {
138     struct output_driver driver;
139
140     /* User parameters. */
141     struct xr_font fonts[XR_N_FONTS];
142
143     int width;                  /* Page width minus margins. */
144     int length;                 /* Page length minus margins and header. */
145
146     int left_margin;            /* Left margin in inch/(72 * XR_POINT). */
147     int right_margin;           /* Right margin in inch/(72 * XR_POINT). */
148     int top_margin;             /* Top margin in inch/(72 * XR_POINT). */
149     int bottom_margin;          /* Bottom margin in inch/(72 * XR_POINT). */
150
151     int line_space;             /* Space between lines. */
152     int line_width;             /* Width of lines. */
153
154     int min_break[TABLE_N_AXES]; /* Min cell size to break across pages. */
155     int object_spacing;         /* Space between output objects. */
156
157     struct cell_color bg;       /* Background color */
158     struct cell_color fg;       /* Foreground color */
159     bool transparent;           /* true -> do not render background */
160     bool systemcolors;          /* true -> do not change colors     */
161
162     int initial_page_number;
163
164     struct page_heading headings[2]; /* Top and bottom headings. */
165     int headings_height[2];
166
167     /* Internal state. */
168     struct render_params *params;
169     double font_scale;
170     int char_width, char_height;
171     cairo_t *cairo;
172     cairo_surface_t *surface;
173     int page_number;            /* Current page number. */
174     int x, y;
175     struct xr_render_fsm *fsm;
176     struct string_map heading_vars;
177   };
178
179 static const struct output_driver_class cairo_driver_class;
180
181 static void xr_driver_destroy_fsm (struct xr_driver *);
182 static void xr_driver_run_fsm (struct xr_driver *);
183
184 static void xr_draw_line (void *, int bb[TABLE_N_AXES][2],
185                           enum render_line_style styles[TABLE_N_AXES][2],
186                           struct cell_color colors[TABLE_N_AXES][2]);
187 static void xr_measure_cell_width (void *, const struct table_cell *,
188                                    int *min, int *max);
189 static int xr_measure_cell_height (void *, const struct table_cell *,
190                                    int width);
191 static void xr_draw_cell (void *, const struct table_cell *, int color_idx,
192                           int bb[TABLE_N_AXES][2], int valign_offset,
193                           int spill[TABLE_N_AXES][2],
194                           int clip[TABLE_N_AXES][2]);
195 static int xr_adjust_break (void *, const struct table_cell *,
196                             int width, int height);
197
198 static struct xr_render_fsm *xr_render_output_item (
199   struct xr_driver *, const struct output_item *);
200 \f
201 /* Output driver basics. */
202
203 static struct xr_driver *
204 xr_driver_cast (struct output_driver *driver)
205 {
206   assert (driver->class == &cairo_driver_class);
207   return UP_CAST (driver, struct xr_driver, driver);
208 }
209
210 static struct driver_option *
211 opt (struct output_driver *d, struct string_map *options, const char *key,
212      const char *default_value)
213 {
214   return driver_option_get (d, options, key, default_value);
215 }
216
217 static int
218 lookup_color_name (const char *s)
219 {
220   struct color
221     {
222       struct hmap_node hmap_node;
223       const char *name;
224       int code;
225     };
226
227   static struct color colors[] =
228     {
229       { .name = "aliceblue", .code = 0xf0f8ff },
230       { .name = "antiquewhite", .code = 0xfaebd7 },
231       { .name = "aqua", .code = 0x00ffff },
232       { .name = "aquamarine", .code = 0x7fffd4 },
233       { .name = "azure", .code = 0xf0ffff },
234       { .name = "beige", .code = 0xf5f5dc },
235       { .name = "bisque", .code = 0xffe4c4 },
236       { .name = "black", .code = 0x000000 },
237       { .name = "blanchedalmond", .code = 0xffebcd },
238       { .name = "blue", .code = 0x0000ff },
239       { .name = "blueviolet", .code = 0x8a2be2 },
240       { .name = "brown", .code = 0xa52a2a },
241       { .name = "burlywood", .code = 0xdeb887 },
242       { .name = "cadetblue", .code = 0x5f9ea0 },
243       { .name = "chartreuse", .code = 0x7fff00 },
244       { .name = "chocolate", .code = 0xd2691e },
245       { .name = "coral", .code = 0xff7f50 },
246       { .name = "cornflowerblue", .code = 0x6495ed },
247       { .name = "cornsilk", .code = 0xfff8dc },
248       { .name = "crimson", .code = 0xdc143c },
249       { .name = "cyan", .code = 0x00ffff },
250       { .name = "darkblue", .code = 0x00008b },
251       { .name = "darkcyan", .code = 0x008b8b },
252       { .name = "darkgoldenrod", .code = 0xb8860b },
253       { .name = "darkgray", .code = 0xa9a9a9 },
254       { .name = "darkgreen", .code = 0x006400 },
255       { .name = "darkgrey", .code = 0xa9a9a9 },
256       { .name = "darkkhaki", .code = 0xbdb76b },
257       { .name = "darkmagenta", .code = 0x8b008b },
258       { .name = "darkolivegreen", .code = 0x556b2f },
259       { .name = "darkorange", .code = 0xff8c00 },
260       { .name = "darkorchid", .code = 0x9932cc },
261       { .name = "darkred", .code = 0x8b0000 },
262       { .name = "darksalmon", .code = 0xe9967a },
263       { .name = "darkseagreen", .code = 0x8fbc8f },
264       { .name = "darkslateblue", .code = 0x483d8b },
265       { .name = "darkslategray", .code = 0x2f4f4f },
266       { .name = "darkslategrey", .code = 0x2f4f4f },
267       { .name = "darkturquoise", .code = 0x00ced1 },
268       { .name = "darkviolet", .code = 0x9400d3 },
269       { .name = "deeppink", .code = 0xff1493 },
270       { .name = "deepskyblue", .code = 0x00bfff },
271       { .name = "dimgray", .code = 0x696969 },
272       { .name = "dimgrey", .code = 0x696969 },
273       { .name = "dodgerblue", .code = 0x1e90ff },
274       { .name = "firebrick", .code = 0xb22222 },
275       { .name = "floralwhite", .code = 0xfffaf0 },
276       { .name = "forestgreen", .code = 0x228b22 },
277       { .name = "fuchsia", .code = 0xff00ff },
278       { .name = "gainsboro", .code = 0xdcdcdc },
279       { .name = "ghostwhite", .code = 0xf8f8ff },
280       { .name = "gold", .code = 0xffd700 },
281       { .name = "goldenrod", .code = 0xdaa520 },
282       { .name = "gray", .code = 0x808080 },
283       { .name = "green", .code = 0x008000 },
284       { .name = "greenyellow", .code = 0xadff2f },
285       { .name = "grey", .code = 0x808080 },
286       { .name = "honeydew", .code = 0xf0fff0 },
287       { .name = "hotpink", .code = 0xff69b4 },
288       { .name = "indianred", .code = 0xcd5c5c },
289       { .name = "indigo", .code = 0x4b0082 },
290       { .name = "ivory", .code = 0xfffff0 },
291       { .name = "khaki", .code = 0xf0e68c },
292       { .name = "lavender", .code = 0xe6e6fa },
293       { .name = "lavenderblush", .code = 0xfff0f5 },
294       { .name = "lawngreen", .code = 0x7cfc00 },
295       { .name = "lemonchiffon", .code = 0xfffacd },
296       { .name = "lightblue", .code = 0xadd8e6 },
297       { .name = "lightcoral", .code = 0xf08080 },
298       { .name = "lightcyan", .code = 0xe0ffff },
299       { .name = "lightgoldenrodyellow", .code = 0xfafad2 },
300       { .name = "lightgray", .code = 0xd3d3d3 },
301       { .name = "lightgreen", .code = 0x90ee90 },
302       { .name = "lightgrey", .code = 0xd3d3d3 },
303       { .name = "lightpink", .code = 0xffb6c1 },
304       { .name = "lightsalmon", .code = 0xffa07a },
305       { .name = "lightseagreen", .code = 0x20b2aa },
306       { .name = "lightskyblue", .code = 0x87cefa },
307       { .name = "lightslategray", .code = 0x778899 },
308       { .name = "lightslategrey", .code = 0x778899 },
309       { .name = "lightsteelblue", .code = 0xb0c4de },
310       { .name = "lightyellow", .code = 0xffffe0 },
311       { .name = "lime", .code = 0x00ff00 },
312       { .name = "limegreen", .code = 0x32cd32 },
313       { .name = "linen", .code = 0xfaf0e6 },
314       { .name = "magenta", .code = 0xff00ff },
315       { .name = "maroon", .code = 0x800000 },
316       { .name = "mediumaquamarine", .code = 0x66cdaa },
317       { .name = "mediumblue", .code = 0x0000cd },
318       { .name = "mediumorchid", .code = 0xba55d3 },
319       { .name = "mediumpurple", .code = 0x9370db },
320       { .name = "mediumseagreen", .code = 0x3cb371 },
321       { .name = "mediumslateblue", .code = 0x7b68ee },
322       { .name = "mediumspringgreen", .code = 0x00fa9a },
323       { .name = "mediumturquoise", .code = 0x48d1cc },
324       { .name = "mediumvioletred", .code = 0xc71585 },
325       { .name = "midnightblue", .code = 0x191970 },
326       { .name = "mintcream", .code = 0xf5fffa },
327       { .name = "mistyrose", .code = 0xffe4e1 },
328       { .name = "moccasin", .code = 0xffe4b5 },
329       { .name = "navajowhite", .code = 0xffdead },
330       { .name = "navy", .code = 0x000080 },
331       { .name = "oldlace", .code = 0xfdf5e6 },
332       { .name = "olive", .code = 0x808000 },
333       { .name = "olivedrab", .code = 0x6b8e23 },
334       { .name = "orange", .code = 0xffa500 },
335       { .name = "orangered", .code = 0xff4500 },
336       { .name = "orchid", .code = 0xda70d6 },
337       { .name = "palegoldenrod", .code = 0xeee8aa },
338       { .name = "palegreen", .code = 0x98fb98 },
339       { .name = "paleturquoise", .code = 0xafeeee },
340       { .name = "palevioletred", .code = 0xdb7093 },
341       { .name = "papayawhip", .code = 0xffefd5 },
342       { .name = "peachpuff", .code = 0xffdab9 },
343       { .name = "peru", .code = 0xcd853f },
344       { .name = "pink", .code = 0xffc0cb },
345       { .name = "plum", .code = 0xdda0dd },
346       { .name = "powderblue", .code = 0xb0e0e6 },
347       { .name = "purple", .code = 0x800080 },
348       { .name = "red", .code = 0xff0000 },
349       { .name = "rosybrown", .code = 0xbc8f8f },
350       { .name = "royalblue", .code = 0x4169e1 },
351       { .name = "saddlebrown", .code = 0x8b4513 },
352       { .name = "salmon", .code = 0xfa8072 },
353       { .name = "sandybrown", .code = 0xf4a460 },
354       { .name = "seagreen", .code = 0x2e8b57 },
355       { .name = "seashell", .code = 0xfff5ee },
356       { .name = "sienna", .code = 0xa0522d },
357       { .name = "silver", .code = 0xc0c0c0 },
358       { .name = "skyblue", .code = 0x87ceeb },
359       { .name = "slateblue", .code = 0x6a5acd },
360       { .name = "slategray", .code = 0x708090 },
361       { .name = "slategrey", .code = 0x708090 },
362       { .name = "snow", .code = 0xfffafa },
363       { .name = "springgreen", .code = 0x00ff7f },
364       { .name = "steelblue", .code = 0x4682b4 },
365       { .name = "tan", .code = 0xd2b48c },
366       { .name = "teal", .code = 0x008080 },
367       { .name = "thistle", .code = 0xd8bfd8 },
368       { .name = "tomato", .code = 0xff6347 },
369       { .name = "turquoise", .code = 0x40e0d0 },
370       { .name = "violet", .code = 0xee82ee },
371       { .name = "wheat", .code = 0xf5deb3 },
372       { .name = "white", .code = 0xffffff },
373       { .name = "whitesmoke", .code = 0xf5f5f5 },
374       { .name = "yellow", .code = 0xffff00 },
375       { .name = "yellowgreen", .code = 0x9acd32 },
376     };
377
378   static struct hmap color_table = HMAP_INITIALIZER (color_table);
379
380   if (hmap_is_empty (&color_table))
381     for (size_t i = 0; i < sizeof colors / sizeof *colors; i++)
382       hmap_insert (&color_table, &colors[i].hmap_node,
383                    hash_string (colors[i].name, 0));
384
385   const struct color *color;
386   HMAP_FOR_EACH_WITH_HASH (color, struct color, hmap_node,
387                            hash_string (s, 0), &color_table)
388     if (!strcmp (color->name, s))
389       return color->code;
390   return -1;
391 }
392
393 static bool
394 parse_color__ (const char *s, struct cell_color *color)
395 {
396   /* #rrrrggggbbbb */
397   uint16_t r16, g16, b16;
398   int len;
399   if (sscanf (s, "#%4"SCNx16"%4"SCNx16"%4"SCNx16"%n",
400               &r16, &g16, &b16, &len) == 3
401       && len == 13
402       && !s[len])
403     {
404       color->r = r16 >> 8;
405       color->g = g16 >> 8;
406       color->b = b16 >> 8;
407       return true;
408     }
409
410   /* #rrggbb */
411   uint8_t r, g, b;
412   if (sscanf (s, "#%2"SCNx8"%2"SCNx8"%2"SCNx8"%n", &r, &g, &b, &len) == 3
413       && len == 7
414       && !s[len])
415     {
416       color->r = r;
417       color->g = g;
418       color->b = b;
419       return true;
420     }
421
422   /* rrggbb */
423   if (sscanf (s, "%2"SCNx8"%2"SCNx8"%2"SCNx8"%n", &r, &g, &b, &len) == 3
424       && len == 6
425       && !s[len])
426     {
427       color->r = r;
428       color->g = g;
429       color->b = b;
430       return true;
431     }
432
433   /* rgb(r,g,b) */
434   if (sscanf (s, "rgb (%"SCNi8" , %"SCNi8" , %"SCNi8") %n",
435               &r, &g, &b, &len) == 3
436       && !s[len])
437     {
438       color->r = r;
439       color->g = g;
440       color->b = b;
441       return true;
442     }
443
444   /* rgba(r,g,b,a), ignoring a. */
445   if (sscanf (s, "rgba (%"SCNi8" , %"SCNi8" , %"SCNi8", %*f) %n",
446               &r, &g, &b, &len) == 3
447       && !s[len])
448     {
449       color->r = r;
450       color->g = g;
451       color->b = b;
452       return true;
453     }
454
455   int code = lookup_color_name (s);
456   if (code >= 0)
457     {
458       color->r = code >> 16;
459       color->g = code >> 8;
460       color->b = code;
461       return true;
462     }
463
464   return false;
465 }
466
467 /* Parse color information specified by KEY into {RED,GREEN,BLUE}.
468    Currently, the input string must be of the form "#RRRRGGGGBBBB"
469    Future implementations might allow things like "yellow" and
470    "sky-blue-ultra-brown"
471 */
472 void
473 parse_color (struct output_driver *d, struct string_map *options,
474              const char *key, const char *default_value,
475              struct cell_color *color)
476 {
477   char *string = parse_string (opt (d, options, key, default_value));
478   if (!parse_color__ (string, color) && !parse_color__ (default_value, color))
479     *color = (struct cell_color) CELL_COLOR_BLACK;
480   free (string);
481 }
482
483 static PangoFontDescription *
484 parse_font (const char *font, int default_size, bool bold, bool italic)
485 {
486   if (!c_strcasecmp (font, "Monospaced"))
487     font = "Monospace";
488
489   PangoFontDescription *desc = pango_font_description_from_string (font);
490   if (desc == NULL)
491     return NULL;
492
493   /* If the font description didn't include an explicit font size, then set it
494      to DEFAULT_SIZE, which is in inch/72000 units. */
495   if (!(pango_font_description_get_set_fields (desc) & PANGO_FONT_MASK_SIZE))
496     pango_font_description_set_size (desc,
497                                      (default_size / 1000.0) * PANGO_SCALE);
498
499   pango_font_description_set_weight (desc, (bold
500                                             ? PANGO_WEIGHT_BOLD
501                                             : PANGO_WEIGHT_NORMAL));
502   pango_font_description_set_style (desc, (italic
503                                            ? PANGO_STYLE_ITALIC
504                                            : PANGO_STYLE_NORMAL));
505
506   return desc;
507 }
508
509 static PangoFontDescription *
510 parse_font_option (struct output_driver *d, struct string_map *options,
511                    const char *key, const char *default_value,
512                    int default_size, bool bold, bool italic)
513 {
514   char *string = parse_string (opt (d, options, key, default_value));
515   PangoFontDescription *desc = parse_font (string, default_size, bold, italic);
516   if (!desc)
517     {
518       msg (MW, _("`%s': bad font specification"), string);
519
520       /* Fall back to DEFAULT_VALUE, which had better be a valid font
521          description. */
522       desc = parse_font (default_value, default_size, bold, italic);
523       assert (desc != NULL);
524     }
525   free (string);
526
527   return desc;
528 }
529
530 static void
531 apply_options (struct xr_driver *xr, struct string_map *o)
532 {
533   struct output_driver *d = &xr->driver;
534
535   /* In inch/72000 units used by parse_paper_size() and parse_dimension(). */
536   int left_margin, right_margin;
537   int top_margin, bottom_margin;
538   int paper_width, paper_length;
539   int font_size;
540   int min_break[TABLE_N_AXES];
541
542   /* Scale factor from inch/72000 to inch/(72 * XR_POINT). */
543   const double scale = XR_POINT / 1000.;
544
545   int i;
546
547   for (i = 0; i < XR_N_FONTS; i++)
548     {
549       struct xr_font *font = &xr->fonts[i];
550
551       if (font->desc != NULL)
552         pango_font_description_free (font->desc);
553     }
554
555   font_size = parse_int (opt (d, o, "font-size", "10000"), 1000, 1000000);
556   xr->fonts[XR_FONT_FIXED].desc = parse_font_option
557     (d, o, "fixed-font", "monospace", font_size, false, false);
558   xr->fonts[XR_FONT_PROPORTIONAL].desc = parse_font_option (
559     d, o, "prop-font", "sans serif", font_size, false, false);
560   xr->fonts[XR_FONT_EMPHASIS].desc = parse_font_option (
561     d, o, "emph-font", "sans serif", font_size, false, true);
562
563   parse_color (d, o, "background-color", "#FFFFFFFFFFFF", &xr->bg);
564   parse_color (d, o, "foreground-color", "#000000000000", &xr->fg);
565
566   xr->transparent = parse_boolean (opt (d, o, "transparent", "false"));
567   xr->systemcolors = parse_boolean (opt (d, o, "systemcolors", "false"));
568
569   /* Get dimensions.  */
570   parse_paper_size (opt (d, o, "paper-size", ""), &paper_width, &paper_length);
571   left_margin = parse_dimension (opt (d, o, "left-margin", ".5in"));
572   right_margin = parse_dimension (opt (d, o, "right-margin", ".5in"));
573   top_margin = parse_dimension (opt (d, o, "top-margin", ".5in"));
574   bottom_margin = parse_dimension (opt (d, o, "bottom-margin", ".5in"));
575
576   min_break[H] = parse_dimension (opt (d, o, "min-hbreak", NULL)) * scale;
577   min_break[V] = parse_dimension (opt (d, o, "min-vbreak", NULL)) * scale;
578
579   int object_spacing = (parse_dimension (opt (d, o, "object-spacing", NULL))
580                         * scale);
581
582   /* Convert to inch/(XR_POINT * 72). */
583   xr->left_margin = left_margin * scale;
584   xr->right_margin = right_margin * scale;
585   xr->top_margin = top_margin * scale;
586   xr->bottom_margin = bottom_margin * scale;
587   xr->width = (paper_width - left_margin - right_margin) * scale;
588   xr->length = (paper_length - top_margin - bottom_margin) * scale;
589   xr->min_break[H] = min_break[H] >= 0 ? min_break[H] : xr->width / 2;
590   xr->min_break[V] = min_break[V] >= 0 ? min_break[V] : xr->length / 2;
591   xr->object_spacing = object_spacing >= 0 ? object_spacing : XR_POINT * 12;
592
593   /* There are no headings so headings_height can stay 0. */
594 }
595
596 static struct xr_driver *
597 xr_allocate (const char *name, int device_type, struct string_map *o,
598              double font_scale)
599 {
600   struct xr_driver *xr = xzalloc (sizeof *xr);
601   struct output_driver *d = &xr->driver;
602
603   output_driver_init (d, &cairo_driver_class, name, device_type);
604
605   string_map_init (&xr->heading_vars);
606
607   /* This is a nasty kluge for an issue that does not make sense.  On any
608      surface other than a screen (e.g. for output to PDF or PS or SVG), the
609      fonts are way too big by default.  A "9-point" font seems to appear about
610      16 points tall.  We use a scale factor for these surfaces to help, but the
611      underlying issue is a mystery. */
612   xr->font_scale = font_scale;
613
614   apply_options (xr, o);
615
616   return xr;
617 }
618
619 static int
620 pango_to_xr (int pango)
621 {
622   return (XR_POINT != PANGO_SCALE
623           ? ceil (pango * (1. * XR_POINT / PANGO_SCALE))
624           : pango);
625 }
626
627 static int
628 xr_to_pango (int xr)
629 {
630   return (XR_POINT != PANGO_SCALE
631           ? ceil (xr * (1. / XR_POINT * PANGO_SCALE))
632           : xr);
633 }
634
635 static void
636 xr_measure_fonts (cairo_t *cairo, const struct xr_font fonts[XR_N_FONTS],
637                   int *char_width, int *char_height)
638 {
639   *char_width = 0;
640   *char_height = 0;
641   for (int i = 0; i < XR_N_FONTS; i++)
642     {
643       PangoLayout *layout = pango_cairo_create_layout (cairo);
644       pango_layout_set_font_description (layout, fonts[i].desc);
645
646       pango_layout_set_text (layout, "0", 1);
647
648       int cw, ch;
649       pango_layout_get_size (layout, &cw, &ch);
650       *char_width = MAX (*char_width, pango_to_xr (cw));
651       *char_height = MAX (*char_height, pango_to_xr (ch));
652
653       g_object_unref (G_OBJECT (layout));
654     }
655 }
656
657 static int
658 get_layout_height (PangoLayout *layout)
659 {
660   int w, h;
661   pango_layout_get_size (layout, &w, &h);
662   return h;
663 }
664
665 static int
666 xr_render_page_heading (cairo_t *cairo, const PangoFontDescription *font,
667                         const struct page_heading *ph, int page_number,
668                         int width, bool draw, int base_y)
669 {
670   PangoLayout *layout = pango_cairo_create_layout (cairo);
671   pango_layout_set_font_description (layout, font);
672
673   int y = 0;
674   for (size_t i = 0; i < ph->n; i++)
675     {
676       const struct page_paragraph *pp = &ph->paragraphs[i];
677
678       char *markup = output_driver_substitute_heading_vars (pp->markup,
679                                                             page_number);
680       pango_layout_set_markup (layout, markup, -1);
681       free (markup);
682
683       pango_layout_set_alignment (
684         layout,
685         (pp->halign == TABLE_HALIGN_LEFT ? PANGO_ALIGN_LEFT
686          : pp->halign == TABLE_HALIGN_CENTER ? PANGO_ALIGN_CENTER
687          : pp->halign == TABLE_HALIGN_MIXED ? PANGO_ALIGN_LEFT
688          : PANGO_ALIGN_RIGHT));
689       pango_layout_set_width (layout, xr_to_pango (width));
690       if (draw)
691         {
692           cairo_save (cairo);
693           cairo_translate (cairo, 0, xr_to_pt (y + base_y));
694           pango_cairo_show_layout (cairo, layout);
695           cairo_restore (cairo);
696         }
697
698       y += pango_to_xr (get_layout_height (layout));
699     }
700
701   g_object_unref (G_OBJECT (layout));
702
703   return y;
704 }
705
706 static int
707 xr_measure_headings (cairo_surface_t *surface,
708                      const PangoFontDescription *font,
709                      const struct page_heading headings[2],
710                      int width, int object_spacing, int height[2])
711 {
712   cairo_t *cairo = cairo_create (surface);
713   int total = 0;
714   for (int i = 0; i < 2; i++)
715     {
716       int h = xr_render_page_heading (cairo, font, &headings[i], -1,
717                                       width, false, 0);
718
719       /* If the top heading is nonempty, add some space below it. */
720       if (h && i == 0)
721         h += object_spacing;
722
723       if (height)
724         height[i] = h;
725       total += h;
726     }
727   cairo_destroy (cairo);
728   return total;
729 }
730
731 static bool
732 xr_check_fonts (cairo_surface_t *surface,
733                 const struct xr_font fonts[XR_N_FONTS],
734                 int usable_width, int usable_length)
735 {
736   cairo_t *cairo = cairo_create (surface);
737   int char_width, char_height;
738   xr_measure_fonts (cairo, fonts, &char_width, &char_height);
739   cairo_destroy (cairo);
740
741   bool ok = true;
742   enum { MIN_WIDTH = 3, MIN_LENGTH = 3 };
743   if (usable_width / char_width < MIN_WIDTH)
744     {
745       msg (ME, _("The defined page is not wide enough to hold at least %d "
746                  "characters in the default font.  In fact, there's only "
747                  "room for %d characters."),
748            MIN_WIDTH, usable_width / char_width);
749       ok = false;
750     }
751   if (usable_length / char_height < MIN_LENGTH)
752     {
753       msg (ME, _("The defined page is not long enough to hold at least %d "
754                  "lines in the default font.  In fact, there's only "
755                  "room for %d lines."),
756            MIN_LENGTH, usable_length / char_height);
757       ok = false;
758     }
759   return ok;
760 }
761
762 static void
763 xr_set_cairo (struct xr_driver *xr, cairo_t *cairo)
764 {
765   xr->cairo = cairo;
766
767   cairo_set_line_width (xr->cairo, xr_to_pt (XR_LINE_WIDTH));
768
769   xr_measure_fonts (xr->cairo, xr->fonts, &xr->char_width, &xr->char_height);
770
771   for (int i = 0; i < XR_N_FONTS; i++)
772     {
773       struct xr_font *font = &xr->fonts[i];
774       font->layout = pango_cairo_create_layout (cairo);
775       pango_layout_set_font_description (font->layout, font->desc);
776     }
777
778   if (xr->params == NULL)
779     {
780       xr->params = xmalloc (sizeof *xr->params);
781       xr->params->draw_line = xr_draw_line;
782       xr->params->measure_cell_width = xr_measure_cell_width;
783       xr->params->measure_cell_height = xr_measure_cell_height;
784       xr->params->adjust_break = xr_adjust_break;
785       xr->params->draw_cell = xr_draw_cell;
786       xr->params->aux = xr;
787       xr->params->size[H] = xr->width;
788       xr->params->size[V] = xr->length;
789       xr->params->font_size[H] = xr->char_width;
790       xr->params->font_size[V] = xr->char_height;
791
792       int lw = XR_LINE_WIDTH;
793       int ls = XR_LINE_SPACE;
794       for (int i = 0; i < TABLE_N_AXES; i++)
795         {
796           xr->params->line_widths[i][RENDER_LINE_NONE] = 0;
797           xr->params->line_widths[i][RENDER_LINE_SINGLE] = lw;
798           xr->params->line_widths[i][RENDER_LINE_DASHED] = lw;
799           xr->params->line_widths[i][RENDER_LINE_THICK] = lw * 2;
800           xr->params->line_widths[i][RENDER_LINE_THIN] = lw / 2;
801           xr->params->line_widths[i][RENDER_LINE_DOUBLE] = 2 * lw + ls;
802         }
803
804       for (int i = 0; i < TABLE_N_AXES; i++)
805         xr->params->min_break[i] = xr->min_break[i];
806       xr->params->supports_margins = true;
807       xr->params->rtl = render_direction_rtl ();
808     }
809
810   if (!xr->systemcolors)
811     cairo_set_source_rgb (xr->cairo,
812                           xr->fg.r / 255.0, xr->fg.g / 255.0, xr->fg.b / 255.0);
813 }
814
815 static struct output_driver *
816 xr_create (struct file_handle *fh, enum settings_output_devices device_type,
817            struct string_map *o, enum xr_output_type file_type)
818 {
819   const char *file_name = fh_get_file_name (fh);
820   struct xr_driver *xr = xr_allocate (file_name, device_type, o, 72.0 / 128.0);
821   double width_pt = xr_to_pt (xr->width + xr->left_margin + xr->right_margin);
822   double length_pt = xr_to_pt (xr->length + xr->top_margin + xr->bottom_margin);
823   if (file_type == XR_PDF)
824     xr->surface = cairo_pdf_surface_create (file_name, width_pt, length_pt);
825   else if (file_type == XR_PS)
826     xr->surface = cairo_ps_surface_create (file_name, width_pt, length_pt);
827   else if (file_type == XR_SVG)
828     xr->surface = cairo_svg_surface_create (file_name, width_pt, length_pt);
829   else
830     NOT_REACHED ();
831
832   cairo_status_t status = cairo_surface_status (xr->surface);
833   if (status != CAIRO_STATUS_SUCCESS)
834     {
835       msg (ME, _("error opening output file `%s': %s"),
836            file_name, cairo_status_to_string (status));
837       goto error;
838     }
839
840   if (!xr_check_fonts (xr->surface, xr->fonts, xr->width, xr->length))
841     goto error;
842
843   fh_unref (fh);
844   return &xr->driver;
845
846  error:
847   fh_unref (fh);
848   output_driver_destroy (&xr->driver);
849   return NULL;
850 }
851
852 static struct output_driver *
853 xr_pdf_create (struct  file_handle *fh, enum settings_output_devices device_type,
854                struct string_map *o)
855 {
856   return xr_create (fh, device_type, o, XR_PDF);
857 }
858
859 static struct output_driver *
860 xr_ps_create (struct  file_handle *fh, enum settings_output_devices device_type,
861                struct string_map *o)
862 {
863   return xr_create (fh, device_type, o, XR_PS);
864 }
865
866 static struct output_driver *
867 xr_svg_create (struct file_handle *fh, enum settings_output_devices device_type,
868                struct string_map *o)
869 {
870   return xr_create (fh, device_type, o, XR_SVG);
871 }
872
873 static void
874 xr_destroy (struct output_driver *driver)
875 {
876   struct xr_driver *xr = xr_driver_cast (driver);
877   size_t i;
878
879   xr_driver_destroy_fsm (xr);
880
881   if (xr->cairo != NULL)
882     {
883       cairo_surface_finish (xr->surface);
884       cairo_status_t status = cairo_status (xr->cairo);
885       if (status != CAIRO_STATUS_SUCCESS)
886         fprintf (stderr,  _("error drawing output for %s driver: %s"),
887                  output_driver_get_name (driver),
888                  cairo_status_to_string (status));
889       cairo_surface_destroy (xr->surface);
890
891       cairo_destroy (xr->cairo);
892     }
893
894   for (i = 0; i < XR_N_FONTS; i++)
895     {
896       struct xr_font *font = &xr->fonts[i];
897
898       if (font->desc != NULL)
899         pango_font_description_free (font->desc);
900       if (font->layout != NULL)
901         g_object_unref (font->layout);
902     }
903
904   free (xr->params);
905   free (xr);
906 }
907
908 static void
909 xr_flush (struct output_driver *driver)
910 {
911   struct xr_driver *xr = xr_driver_cast (driver);
912
913   cairo_surface_flush (cairo_get_target (xr->cairo));
914 }
915
916 static void
917 xr_update_page_setup (struct output_driver *driver,
918                       const struct page_setup *ps)
919 {
920   struct xr_driver *xr = xr_driver_cast (driver);
921
922   xr->initial_page_number = ps->initial_page_number;
923   xr->object_spacing = ps->object_spacing * 72 * XR_POINT;
924
925   if (xr->cairo)
926     return;
927
928   int usable[TABLE_N_AXES];
929   for (int i = 0; i < 2; i++)
930     usable[i] = (ps->paper[i]
931                  - (ps->margins[i][0] + ps->margins[i][1])) * 72 * XR_POINT;
932
933   int headings_height[2];
934   usable[V] -= xr_measure_headings (
935     xr->surface, xr->fonts[XR_FONT_PROPORTIONAL].desc, ps->headings,
936     usable[H], xr->object_spacing, headings_height);
937
938   enum table_axis h = ps->orientation == PAGE_LANDSCAPE;
939   enum table_axis v = !h;
940   if (!xr_check_fonts (xr->surface, xr->fonts, usable[h], usable[v]))
941     return;
942
943   for (int i = 0; i < 2; i++)
944     {
945       page_heading_uninit (&xr->headings[i]);
946       page_heading_copy (&xr->headings[i], &ps->headings[i]);
947       xr->headings_height[i] = headings_height[i];
948     }
949   xr->width = usable[h];
950   xr->length = usable[v];
951   xr->left_margin = ps->margins[h][0] * 72 * XR_POINT;
952   xr->right_margin = ps->margins[h][1] * 72 * XR_POINT;
953   xr->top_margin = ps->margins[v][0] * 72 * XR_POINT;
954   xr->bottom_margin = ps->margins[v][1] * 72 * XR_POINT;
955   cairo_pdf_surface_set_size (xr->surface,
956                               ps->paper[h] * 72.0, ps->paper[v] * 72.0);
957 }
958
959 static void
960 xr_submit (struct output_driver *driver, const struct output_item *output_item)
961 {
962   struct xr_driver *xr = xr_driver_cast (driver);
963
964   if (is_page_setup_item (output_item))
965     {
966       xr_update_page_setup (driver,
967                             to_page_setup_item (output_item)->page_setup);
968       return;
969     }
970
971   if (!xr->cairo)
972     {
973       xr->page_number = xr->initial_page_number - 1;
974       xr_set_cairo (xr, cairo_create (xr->surface));
975       cairo_save (xr->cairo);
976       xr_driver_next_page (xr, xr->cairo);
977     }
978
979   xr_driver_output_item (xr, output_item);
980   while (xr_driver_need_new_page (xr))
981     {
982       cairo_restore (xr->cairo);
983       cairo_show_page (xr->cairo);
984       cairo_save (xr->cairo);
985       xr_driver_next_page (xr, xr->cairo);
986     }
987 }
988 \f
989 /* Functions for rendering a series of output items to a series of Cairo
990    contexts, with pagination.
991
992    Used by PSPPIRE for printing, and by the basic Cairo output driver above as
993    its underlying implementation.
994
995    See the big comment in cairo.h for intended usage. */
996
997 /* Gives new page CAIRO to XR for output. */
998 void
999 xr_driver_next_page (struct xr_driver *xr, cairo_t *cairo)
1000 {
1001   if (!xr->transparent)
1002     {
1003       cairo_save (cairo);
1004       cairo_set_source_rgb (cairo,
1005                             xr->bg.r / 255.0, xr->bg.g / 255.0, xr->bg.b / 255.0);
1006       cairo_rectangle (cairo, 0, 0, xr->width, xr->length);
1007       cairo_fill (cairo);
1008       cairo_restore (cairo);
1009     }
1010   cairo_translate (cairo,
1011                    xr_to_pt (xr->left_margin),
1012                    xr_to_pt (xr->top_margin + xr->headings_height[0]));
1013
1014   xr->page_number++;
1015   xr->cairo = cairo;
1016   xr->x = xr->y = 0;
1017
1018   xr_render_page_heading (xr->cairo, xr->fonts[XR_FONT_PROPORTIONAL].desc,
1019                           &xr->headings[0], xr->page_number, xr->width, true,
1020                           -xr->headings_height[0]);
1021   xr_render_page_heading (xr->cairo, xr->fonts[XR_FONT_PROPORTIONAL].desc,
1022                           &xr->headings[1], xr->page_number, xr->width, true,
1023                           xr->length);
1024
1025   xr_driver_run_fsm (xr);
1026 }
1027
1028 /* Start rendering OUTPUT_ITEM to XR.  Only valid if XR is not in the middle of
1029    rendering a previous output item, that is, only if xr_driver_need_new_page()
1030    returns false. */
1031 void
1032 xr_driver_output_item (struct xr_driver *xr,
1033                        const struct output_item *output_item)
1034 {
1035   assert (xr->fsm == NULL);
1036   xr->fsm = xr_render_output_item (xr, output_item);
1037   xr_driver_run_fsm (xr);
1038 }
1039
1040 /* Returns true if XR is in the middle of rendering an output item and needs a
1041    new page to be appended using xr_driver_next_page() to make progress,
1042    otherwise false. */
1043 bool
1044 xr_driver_need_new_page (const struct xr_driver *xr)
1045 {
1046   return xr->fsm != NULL;
1047 }
1048
1049 /* Returns true if the current page doesn't have any content yet. */
1050 bool
1051 xr_driver_is_page_blank (const struct xr_driver *xr)
1052 {
1053   return xr->y == 0;
1054 }
1055
1056 static void
1057 xr_driver_destroy_fsm (struct xr_driver *xr)
1058 {
1059   if (xr->fsm != NULL)
1060     {
1061       xr->fsm->destroy (xr->fsm);
1062       xr->fsm = NULL;
1063     }
1064 }
1065
1066 static void
1067 xr_driver_run_fsm (struct xr_driver *xr)
1068 {
1069   if (xr->fsm != NULL && !xr->fsm->render (xr->fsm, xr))
1070     xr_driver_destroy_fsm (xr);
1071 }
1072 \f
1073 static void
1074 xr_layout_cell (struct xr_driver *, const struct table_cell *,
1075                 int bb[TABLE_N_AXES][2], int clip[TABLE_N_AXES][2],
1076                 int *width, int *height, int *brk);
1077
1078 static void
1079 set_source_rgba (cairo_t *cairo, const struct cell_color *color)
1080 {
1081   cairo_set_source_rgba (cairo,
1082                          color->r / 255., color->g / 255., color->b / 255.,
1083                          color->alpha / 255.);
1084 }
1085
1086 static void
1087 dump_line (struct xr_driver *xr, int x0, int y0, int x1, int y1, int style,
1088            const struct cell_color *color)
1089 {
1090   cairo_new_path (xr->cairo);
1091   if (!xr->systemcolors)
1092     set_source_rgba (xr->cairo, color);
1093   cairo_set_line_width (
1094     xr->cairo,
1095     xr_to_pt (style == RENDER_LINE_THICK ? XR_LINE_WIDTH * 2
1096               : style == RENDER_LINE_THIN ? XR_LINE_WIDTH / 2
1097               : XR_LINE_WIDTH));
1098   cairo_move_to (xr->cairo, xr_to_pt (x0 + xr->x), xr_to_pt (y0 + xr->y));
1099   cairo_line_to (xr->cairo, xr_to_pt (x1 + xr->x), xr_to_pt (y1 + xr->y));
1100   cairo_stroke (xr->cairo);
1101 }
1102
1103 static void UNUSED
1104 dump_rectangle (struct xr_driver *xr, int x0, int y0, int x1, int y1)
1105 {
1106   cairo_new_path (xr->cairo);
1107   cairo_set_line_width (xr->cairo, xr_to_pt (XR_LINE_WIDTH));
1108   cairo_move_to (xr->cairo, xr_to_pt (x0 + xr->x), xr_to_pt (y0 + xr->y));
1109   cairo_line_to (xr->cairo, xr_to_pt (x1 + xr->x), xr_to_pt (y0 + xr->y));
1110   cairo_line_to (xr->cairo, xr_to_pt (x1 + xr->x), xr_to_pt (y1 + xr->y));
1111   cairo_line_to (xr->cairo, xr_to_pt (x0 + xr->x), xr_to_pt (y1 + xr->y));
1112   cairo_close_path (xr->cairo);
1113   cairo_stroke (xr->cairo);
1114 }
1115
1116 static void
1117 fill_rectangle (struct xr_driver *xr, int x0, int y0, int x1, int y1)
1118 {
1119   cairo_new_path (xr->cairo);
1120   cairo_set_line_width (xr->cairo, xr_to_pt (XR_LINE_WIDTH));
1121   cairo_rectangle (xr->cairo,
1122                    xr_to_pt (x0 + xr->x), xr_to_pt (y0 + xr->y),
1123                    xr_to_pt (x1 - x0), xr_to_pt (y1 - y0));
1124   cairo_fill (xr->cairo);
1125 }
1126
1127 /* Draws a horizontal line X0...X2 at Y if LEFT says so,
1128    shortening it to X0...X1 if SHORTEN is true.
1129    Draws a horizontal line X1...X3 at Y if RIGHT says so,
1130    shortening it to X2...X3 if SHORTEN is true. */
1131 static void
1132 horz_line (struct xr_driver *xr, int x0, int x1, int x2, int x3, int y,
1133            enum render_line_style left, enum render_line_style right,
1134            const struct cell_color *left_color,
1135            const struct cell_color *right_color,
1136            bool shorten)
1137 {
1138   if (left != RENDER_LINE_NONE && right != RENDER_LINE_NONE && !shorten
1139       && cell_color_equal (left_color, right_color))
1140     dump_line (xr, x0, y, x3, y, left, left_color);
1141   else
1142     {
1143       if (left != RENDER_LINE_NONE)
1144         dump_line (xr, x0, y, shorten ? x1 : x2, y, left, left_color);
1145       if (right != RENDER_LINE_NONE)
1146         dump_line (xr, shorten ? x2 : x1, y, x3, y, right, right_color);
1147     }
1148 }
1149
1150 /* Draws a vertical line Y0...Y2 at X if TOP says so,
1151    shortening it to Y0...Y1 if SHORTEN is true.
1152    Draws a vertical line Y1...Y3 at X if BOTTOM says so,
1153    shortening it to Y2...Y3 if SHORTEN is true. */
1154 static void
1155 vert_line (struct xr_driver *xr, int y0, int y1, int y2, int y3, int x,
1156            enum render_line_style top, enum render_line_style bottom,
1157            const struct cell_color *top_color,
1158            const struct cell_color *bottom_color,
1159            bool shorten)
1160 {
1161   if (top != RENDER_LINE_NONE && bottom != RENDER_LINE_NONE && !shorten
1162       && cell_color_equal (top_color, bottom_color))
1163     dump_line (xr, x, y0, x, y3, top, top_color);
1164   else
1165     {
1166       if (top != RENDER_LINE_NONE)
1167         dump_line (xr, x, y0, x, shorten ? y1 : y2, top, top_color);
1168       if (bottom != RENDER_LINE_NONE)
1169         dump_line (xr, x, shorten ? y2 : y1, x, y3, bottom, bottom_color);
1170     }
1171 }
1172
1173 static void
1174 xr_draw_line (void *xr_, int bb[TABLE_N_AXES][2],
1175               enum render_line_style styles[TABLE_N_AXES][2],
1176               struct cell_color colors[TABLE_N_AXES][2])
1177 {
1178   const int x0 = bb[H][0];
1179   const int y0 = bb[V][0];
1180   const int x3 = bb[H][1];
1181   const int y3 = bb[V][1];
1182   const int top = styles[H][0];
1183   const int bottom = styles[H][1];
1184
1185   int start_side = render_direction_rtl();
1186   int end_side = !start_side;
1187   const int start_of_line = styles[V][start_side];
1188   const int end_of_line   = styles[V][end_side];
1189   const struct cell_color *top_color = &colors[H][0];
1190   const struct cell_color *bottom_color = &colors[H][1];
1191   const struct cell_color *start_color = &colors[V][start_side];
1192   const struct cell_color *end_color = &colors[V][end_side];
1193
1194   /* The algorithm here is somewhat subtle, to allow it to handle
1195      all the kinds of intersections that we need.
1196
1197      Three additional ordinates are assigned along the x axis.  The
1198      first is xc, midway between x0 and x3.  The others are x1 and
1199      x2; for a single vertical line these are equal to xc, and for
1200      a double vertical line they are the ordinates of the left and
1201      right half of the double line.
1202
1203      yc, y1, and y2 are assigned similarly along the y axis.
1204
1205      The following diagram shows the coordinate system and output
1206      for double top and bottom lines, single left line, and no
1207      right line:
1208
1209                  x0       x1 xc  x2      x3
1210                y0 ________________________
1211                   |        #     #       |
1212                   |        #     #       |
1213                   |        #     #       |
1214                   |        #     #       |
1215                   |        #     #       |
1216      y1 = y2 = yc |#########     #       |
1217                   |        #     #       |
1218                   |        #     #       |
1219                   |        #     #       |
1220                   |        #     #       |
1221                y3 |________#_____#_______|
1222   */
1223   struct xr_driver *xr = xr_;
1224
1225   /* Offset from center of each line in a pair of double lines. */
1226   int double_line_ofs = (XR_LINE_SPACE + XR_LINE_WIDTH) / 2;
1227
1228   /* Are the lines along each axis single or double?
1229      (It doesn't make sense to have different kinds of line on the
1230      same axis, so we don't try to gracefully handle that case.) */
1231   bool double_vert = top == RENDER_LINE_DOUBLE || bottom == RENDER_LINE_DOUBLE;
1232   bool double_horz = start_of_line == RENDER_LINE_DOUBLE || end_of_line == RENDER_LINE_DOUBLE;
1233
1234   /* When horizontal lines are doubled,
1235      the left-side line along y1 normally runs from x0 to x2,
1236      and the right-side line along y1 from x3 to x1.
1237      If the top-side line is also doubled, we shorten the y1 lines,
1238      so that the left-side line runs only to x1,
1239      and the right-side line only to x2.
1240      Otherwise, the horizontal line at y = y1 below would cut off
1241      the intersection, which looks ugly:
1242                x0       x1     x2      x3
1243              y0 ________________________
1244                 |        #     #       |
1245                 |        #     #       |
1246                 |        #     #       |
1247                 |        #     #       |
1248              y1 |#########     ########|
1249                 |                      |
1250                 |                      |
1251              y2 |######################|
1252                 |                      |
1253                 |                      |
1254              y3 |______________________|
1255      It is more of a judgment call when the horizontal line is
1256      single.  We actually choose to cut off the line anyhow, as
1257      shown in the first diagram above.
1258   */
1259   bool shorten_y1_lines = top == RENDER_LINE_DOUBLE;
1260   bool shorten_y2_lines = bottom == RENDER_LINE_DOUBLE;
1261   bool shorten_yc_line = shorten_y1_lines && shorten_y2_lines;
1262   int horz_line_ofs = double_vert ? double_line_ofs : 0;
1263   int xc = (x0 + x3) / 2;
1264   int x1 = xc - horz_line_ofs;
1265   int x2 = xc + horz_line_ofs;
1266
1267   bool shorten_x1_lines = start_of_line == RENDER_LINE_DOUBLE;
1268   bool shorten_x2_lines = end_of_line == RENDER_LINE_DOUBLE;
1269   bool shorten_xc_line = shorten_x1_lines && shorten_x2_lines;
1270   int vert_line_ofs = double_horz ? double_line_ofs : 0;
1271   int yc = (y0 + y3) / 2;
1272   int y1 = yc - vert_line_ofs;
1273   int y2 = yc + vert_line_ofs;
1274
1275   if (!double_horz)
1276     horz_line (xr, x0, x1, x2, x3, yc, start_of_line, end_of_line,
1277                start_color, end_color, shorten_yc_line);
1278   else
1279     {
1280       horz_line (xr, x0, x1, x2, x3, y1, start_of_line, end_of_line,
1281                  start_color, end_color, shorten_y1_lines);
1282       horz_line (xr, x0, x1, x2, x3, y2, start_of_line, end_of_line,
1283                  start_color, end_color, shorten_y2_lines);
1284     }
1285
1286   if (!double_vert)
1287     vert_line (xr, y0, y1, y2, y3, xc, top, bottom, top_color, bottom_color,
1288                shorten_xc_line);
1289   else
1290     {
1291       vert_line (xr, y0, y1, y2, y3, x1, top, bottom, top_color, bottom_color,
1292                  shorten_x1_lines);
1293       vert_line (xr, y0, y1, y2, y3, x2, top, bottom, top_color, bottom_color,
1294                  shorten_x2_lines);
1295     }
1296 }
1297
1298 static void
1299 xr_measure_cell_width (void *xr_, const struct table_cell *cell,
1300                        int *min_width, int *max_width)
1301 {
1302   struct xr_driver *xr = xr_;
1303   int bb[TABLE_N_AXES][2];
1304   int clip[TABLE_N_AXES][2];
1305   int h;
1306
1307   bb[H][0] = 0;
1308   bb[H][1] = INT_MAX;
1309   bb[V][0] = 0;
1310   bb[V][1] = INT_MAX;
1311   clip[H][0] = clip[H][1] = clip[V][0] = clip[V][1] = 0;
1312   xr_layout_cell (xr, cell, bb, clip, max_width, &h, NULL);
1313
1314   bb[H][1] = 1;
1315   xr_layout_cell (xr, cell, bb, clip, min_width, &h, NULL);
1316
1317   if (*min_width > 0)
1318     *min_width += px_to_xr (cell->style->cell_style.margin[H][0]
1319                             + cell->style->cell_style.margin[H][1]);
1320   if (*max_width > 0)
1321     *max_width += px_to_xr (cell->style->cell_style.margin[H][0]
1322                             + cell->style->cell_style.margin[H][1]);
1323 }
1324
1325 static int
1326 xr_measure_cell_height (void *xr_, const struct table_cell *cell, int width)
1327 {
1328   struct xr_driver *xr = xr_;
1329   int bb[TABLE_N_AXES][2];
1330   int clip[TABLE_N_AXES][2];
1331   int w, h;
1332
1333   bb[H][0] = 0;
1334   bb[H][1] = width - px_to_xr (cell->style->cell_style.margin[H][0]
1335                                + cell->style->cell_style.margin[H][1]);
1336   bb[V][0] = 0;
1337   bb[V][1] = INT_MAX;
1338   clip[H][0] = clip[H][1] = clip[V][0] = clip[V][1] = 0;
1339   xr_layout_cell (xr, cell, bb, clip, &w, &h, NULL);
1340   h += px_to_xr (cell->style->cell_style.margin[V][0]
1341                  + cell->style->cell_style.margin[V][1]);
1342   return h;
1343 }
1344
1345 static void xr_clip (struct xr_driver *, int clip[TABLE_N_AXES][2]);
1346
1347 static void
1348 xr_draw_cell (void *xr_, const struct table_cell *cell, int color_idx,
1349               int bb[TABLE_N_AXES][2], int valign_offset,
1350               int spill[TABLE_N_AXES][2],
1351               int clip[TABLE_N_AXES][2])
1352 {
1353   struct xr_driver *xr = xr_;
1354   int w, h, brk;
1355
1356   if (!xr->transparent)
1357     {
1358       cairo_save (xr->cairo);
1359       int bg_clip[TABLE_N_AXES][2];
1360       for (int axis = 0; axis < TABLE_N_AXES; axis++)
1361         {
1362           bg_clip[axis][0] = clip[axis][0];
1363           if (bb[axis][0] == clip[axis][0])
1364             bg_clip[axis][0] -= spill[axis][0];
1365
1366           bg_clip[axis][1] = clip[axis][1];
1367           if (bb[axis][1] == clip[axis][1])
1368             bg_clip[axis][1] += spill[axis][1];
1369         }
1370       xr_clip (xr, bg_clip);
1371       set_source_rgba (xr->cairo, &cell->style->font_style.bg[color_idx]);
1372       fill_rectangle (xr,
1373                       bb[H][0] - spill[H][0],
1374                       bb[V][0] - spill[V][0],
1375                       bb[H][1] + spill[H][1],
1376                       bb[V][1] + spill[V][1]);
1377       cairo_restore (xr->cairo);
1378     }
1379   cairo_save (xr->cairo);
1380   if (!xr->systemcolors)
1381     set_source_rgba (xr->cairo, &cell->style->font_style.fg[color_idx]);
1382
1383   bb[V][0] += valign_offset;
1384
1385   for (int axis = 0; axis < TABLE_N_AXES; axis++)
1386     {
1387       bb[axis][0] += px_to_xr (cell->style->cell_style.margin[axis][0]);
1388       bb[axis][1] -= px_to_xr (cell->style->cell_style.margin[axis][1]);
1389     }
1390   if (bb[H][0] < bb[H][1] && bb[V][0] < bb[V][1])
1391     xr_layout_cell (xr, cell, bb, clip, &w, &h, &brk);
1392   cairo_restore (xr->cairo);
1393 }
1394
1395 static int
1396 xr_adjust_break (void *xr_, const struct table_cell *cell,
1397                  int width, int height)
1398 {
1399   struct xr_driver *xr = xr_;
1400   int bb[TABLE_N_AXES][2];
1401   int clip[TABLE_N_AXES][2];
1402   int w, h, brk;
1403
1404   if (xr_measure_cell_height (xr_, cell, width) < height)
1405     return -1;
1406
1407   bb[H][0] = 0;
1408   bb[H][1] = width - px_to_xr (cell->style->cell_style.margin[H][0]
1409                                + cell->style->cell_style.margin[H][1]);
1410   if (bb[H][1] <= 0)
1411     return 0;
1412   bb[V][0] = 0;
1413   bb[V][1] = height - px_to_xr (cell->style->cell_style.margin[V][0]
1414                                 + cell->style->cell_style.margin[V][1]);
1415   clip[H][0] = clip[H][1] = clip[V][0] = clip[V][1] = 0;
1416   xr_layout_cell (xr, cell, bb, clip, &w, &h, &brk);
1417   return brk;
1418 }
1419 \f
1420 static void
1421 xr_clip (struct xr_driver *xr, int clip[TABLE_N_AXES][2])
1422 {
1423   if (clip[H][1] != INT_MAX || clip[V][1] != INT_MAX)
1424     {
1425       double x0 = xr_to_pt (clip[H][0] + xr->x);
1426       double y0 = xr_to_pt (clip[V][0] + xr->y);
1427       double x1 = xr_to_pt (clip[H][1] + xr->x);
1428       double y1 = xr_to_pt (clip[V][1] + xr->y);
1429
1430       cairo_rectangle (xr->cairo, x0, y0, x1 - x0, y1 - y0);
1431       cairo_clip (xr->cairo);
1432     }
1433 }
1434
1435 static void
1436 add_attr (PangoAttrList *list, PangoAttribute *attr,
1437           guint start_index, guint end_index)
1438 {
1439   attr->start_index = start_index;
1440   attr->end_index = end_index;
1441   pango_attr_list_insert (list, attr);
1442 }
1443
1444 static void
1445 markup_escape (struct string *out, unsigned int options,
1446                const char *in, size_t len)
1447 {
1448   if (!(options & TAB_MARKUP))
1449     {
1450       ds_put_substring (out, ss_buffer (in, len == -1 ? strlen (in) : len));
1451       return;
1452     }
1453
1454   while (len-- > 0)
1455     {
1456       int c = *in++;
1457       switch (c)
1458         {
1459         case 0:
1460           return;
1461         case '&':
1462           ds_put_cstr (out, "&amp;");
1463           break;
1464         case '<':
1465           ds_put_cstr (out, "&lt;");
1466           break;
1467         case '>':
1468           ds_put_cstr (out, "&gt;");
1469           break;
1470         default:
1471           ds_put_byte (out, c);
1472           break;
1473         }
1474     }
1475 }
1476
1477 static int
1478 get_layout_dimension (PangoLayout *layout, enum table_axis axis)
1479 {
1480   int size[TABLE_N_AXES];
1481   pango_layout_get_size (layout, &size[H], &size[V]);
1482   return size[axis];
1483 }
1484
1485 static int
1486 xr_layout_cell_text (struct xr_driver *xr, const struct table_cell *cell,
1487                      int bb[TABLE_N_AXES][2], int clip[TABLE_N_AXES][2],
1488                      int *widthp, int *brk)
1489 {
1490   const struct font_style *font_style = &cell->style->font_style;
1491   const struct cell_style *cell_style = &cell->style->cell_style;
1492   unsigned int options = cell->options;
1493
1494   enum table_axis X = options & TAB_ROTATE ? V : H;
1495   enum table_axis Y = !X;
1496   int R = options & TAB_ROTATE ? 0 : 1;
1497
1498   struct xr_font *font = (options & TAB_FIX ? &xr->fonts[XR_FONT_FIXED]
1499                           : &xr->fonts[XR_FONT_PROPORTIONAL]);
1500   struct xr_font local_font;
1501   if (font_style->typeface)
1502     {
1503       PangoFontDescription *desc = parse_font (
1504         font_style->typeface,
1505         font_style->size ? font_style->size * 1000 * xr->font_scale : 10000,
1506         font_style->bold, font_style->italic);
1507       if (desc)
1508         {
1509           PangoLayout *layout = pango_cairo_create_layout (xr->cairo);
1510           pango_layout_set_font_description (layout, desc);
1511
1512           local_font.desc = desc;
1513           local_font.layout = layout;
1514           font = &local_font;
1515         }
1516     }
1517
1518   const char *text = cell->text;
1519   enum table_halign halign = table_halign_interpret (
1520     cell_style->halign, cell->options & TAB_NUMERIC);
1521   if (cell_style->halign == TABLE_HALIGN_DECIMAL && !(options & TAB_ROTATE))
1522     {
1523       int margin_adjustment = -px_to_xr (cell_style->decimal_offset);
1524
1525       const char *decimal = strrchr (text, cell_style->decimal_char);
1526       if (decimal)
1527         {
1528           pango_layout_set_text (font->layout, decimal, strlen (decimal));
1529           pango_layout_set_width (font->layout, -1);
1530           margin_adjustment += get_layout_dimension (font->layout, H);
1531         }
1532
1533       if (margin_adjustment < 0)
1534         bb[H][1] += margin_adjustment;
1535     }
1536
1537   struct string tmp = DS_EMPTY_INITIALIZER;
1538   PangoAttrList *attrs = NULL;
1539
1540   /* Deal with an oddity of the Unicode line-breaking algorithm (or perhaps in
1541      Pango's implementation of it): it will break after a period or a comma
1542      that precedes a digit, e.g. in ".000" it will break after the period.
1543      This code looks for such a situation and inserts a U+2060 WORD JOINER
1544      to prevent the break.
1545
1546      This isn't necessary when the decimal point is between two digits
1547      (e.g. "0.000" won't be broken) or when the display width is not limited so
1548      that word wrapping won't happen.
1549
1550      It isn't necessary to look for more than one period or comma, as would
1551      happen with grouping like 1,234,567.89 or 1.234.567,89 because if groups
1552      are present then there will always be a digit on both sides of every
1553      period and comma. */
1554   if (options & TAB_MARKUP)
1555     {
1556       PangoAttrList *new_attrs;
1557       char *new_text;
1558       if (pango_parse_markup (text, -1, 0, &new_attrs, &new_text, NULL, NULL))
1559         {
1560           attrs = new_attrs;
1561           tmp.ss = ss_cstr (new_text);
1562           tmp.capacity = tmp.ss.length;
1563         }
1564       else
1565         {
1566           /* XXX should we report the error? */
1567           ds_put_cstr (&tmp, text);
1568         }
1569     }
1570   else if (options & TAB_ROTATE || bb[H][1] != INT_MAX)
1571     {
1572       const char *decimal = text + strcspn (text, ".,");
1573       if (decimal[0]
1574           && c_isdigit (decimal[1])
1575           && (decimal == text || !c_isdigit (decimal[-1])))
1576         {
1577           ds_extend (&tmp, strlen (text) + 16);
1578           markup_escape (&tmp, options, text, decimal - text + 1);
1579           ds_put_unichar (&tmp, 0x2060 /* U+2060 WORD JOINER */);
1580           markup_escape (&tmp, options, decimal + 1, -1);
1581         }
1582     }
1583
1584   if (font_style->underline)
1585     {
1586       if (!attrs)
1587         attrs = pango_attr_list_new ();
1588       pango_attr_list_insert (attrs, pango_attr_underline_new (
1589                                 PANGO_UNDERLINE_SINGLE));
1590     }
1591
1592   if (cell->n_footnotes || cell->n_subscripts || cell->superscript)
1593     {
1594       /* If we haven't already put TEXT into tmp, do it now. */
1595       if (ds_is_empty (&tmp))
1596         {
1597           ds_extend (&tmp, strlen (text) + 16);
1598           markup_escape (&tmp, options, text, -1);
1599         }
1600
1601       size_t subscript_ofs = ds_length (&tmp);
1602       for (size_t i = 0; i < cell->n_subscripts; i++)
1603         {
1604           if (i)
1605             ds_put_byte (&tmp, ',');
1606           ds_put_cstr (&tmp, cell->subscripts[i]);
1607         }
1608
1609       size_t superscript_ofs = ds_length (&tmp);
1610       if (cell->superscript)
1611         ds_put_cstr (&tmp, cell->superscript);
1612
1613       size_t footnote_ofs = ds_length (&tmp);
1614       for (size_t i = 0; i < cell->n_footnotes; i++)
1615         {
1616           if (i)
1617             ds_put_byte (&tmp, ',');
1618           ds_put_cstr (&tmp, cell->footnotes[i]->marker);
1619         }
1620
1621       /* Allow footnote markers to occupy the right margin.  That way, numbers
1622          in the column are still aligned. */
1623       if (cell->n_footnotes && halign == TABLE_HALIGN_RIGHT)
1624         {
1625           /* Measure the width of the footnote marker, so we know how much we
1626              need to make room for. */
1627           pango_layout_set_text (font->layout, ds_cstr (&tmp) + footnote_ofs,
1628                                  ds_length (&tmp) - footnote_ofs);
1629
1630           PangoAttrList *fn_attrs = pango_attr_list_new ();
1631           pango_attr_list_insert (
1632             fn_attrs, pango_attr_scale_new (PANGO_SCALE_SMALL));
1633           pango_attr_list_insert (fn_attrs, pango_attr_rise_new (3000));
1634           pango_layout_set_attributes (font->layout, fn_attrs);
1635           pango_attr_list_unref (fn_attrs);
1636           int footnote_width = get_layout_dimension (font->layout, X);
1637
1638           /* Bound the adjustment by the width of the right margin. */
1639           int right_margin = px_to_xr (cell_style->margin[X][R]);
1640           int footnote_adjustment = MIN (footnote_width, right_margin);
1641
1642           /* Adjust the bounding box. */
1643           if (options & TAB_ROTATE)
1644             footnote_adjustment = -footnote_adjustment;
1645           bb[X][R] += footnote_adjustment;
1646
1647           /* Clean up. */
1648           pango_layout_set_attributes (font->layout, NULL);
1649         }
1650
1651       /* Set attributes. */
1652       if (!attrs)
1653         attrs = pango_attr_list_new ();
1654       add_attr (attrs, pango_attr_font_desc_new (font->desc), subscript_ofs,
1655                 PANGO_ATTR_INDEX_TO_TEXT_END);
1656       add_attr (attrs, pango_attr_scale_new (PANGO_SCALE_SMALL),
1657                 subscript_ofs, PANGO_ATTR_INDEX_TO_TEXT_END);
1658       if (cell->n_subscripts)
1659         add_attr (attrs, pango_attr_rise_new (-3000), subscript_ofs,
1660                   superscript_ofs - subscript_ofs);
1661       if (cell->superscript || cell->n_footnotes)
1662         add_attr (attrs, pango_attr_rise_new (3000), superscript_ofs,
1663                   PANGO_ATTR_INDEX_TO_TEXT_END);
1664     }
1665
1666   /* Set the attributes, if any. */
1667   if (attrs)
1668     {
1669       pango_layout_set_attributes (font->layout, attrs);
1670       pango_attr_list_unref (attrs);
1671     }
1672
1673   /* Set the text. */
1674   if (ds_is_empty (&tmp))
1675     pango_layout_set_text (font->layout, text, -1);
1676   else
1677     pango_layout_set_text (font->layout, ds_cstr (&tmp), ds_length (&tmp));
1678   ds_destroy (&tmp);
1679
1680   pango_layout_set_alignment (font->layout,
1681                               (halign == TABLE_HALIGN_RIGHT ? PANGO_ALIGN_RIGHT
1682                                : halign == TABLE_HALIGN_LEFT ? PANGO_ALIGN_LEFT
1683                                : PANGO_ALIGN_CENTER));
1684   pango_layout_set_width (
1685     font->layout,
1686     bb[X][1] == INT_MAX ? -1 : xr_to_pango (bb[X][1] - bb[X][0]));
1687   pango_layout_set_wrap (font->layout, PANGO_WRAP_WORD);
1688
1689   if (clip[H][0] != clip[H][1])
1690     {
1691       cairo_save (xr->cairo);
1692       if (!(options & TAB_ROTATE))
1693         xr_clip (xr, clip);
1694       if (options & TAB_ROTATE)
1695         {
1696           cairo_translate (xr->cairo,
1697                            xr_to_pt (bb[H][0] + xr->x),
1698                            xr_to_pt (bb[V][1] + xr->y));
1699           cairo_rotate (xr->cairo, -M_PI_2);
1700         }
1701       else
1702         cairo_translate (xr->cairo,
1703                          xr_to_pt (bb[H][0] + xr->x),
1704                          xr_to_pt (bb[V][0] + xr->y));
1705       pango_cairo_show_layout (xr->cairo, font->layout);
1706
1707       /* If enabled, this draws a blue rectangle around the extents of each
1708          line of text, which can be rather useful for debugging layout
1709          issues. */
1710       if (0)
1711         {
1712           PangoLayoutIter *iter;
1713           iter = pango_layout_get_iter (font->layout);
1714           do
1715             {
1716               PangoRectangle extents;
1717
1718               pango_layout_iter_get_line_extents (iter, &extents, NULL);
1719               cairo_save (xr->cairo);
1720               cairo_set_source_rgb (xr->cairo, 1, 0, 0);
1721               dump_rectangle (xr,
1722                               pango_to_xr (extents.x) - xr->x,
1723                               pango_to_xr (extents.y) - xr->y,
1724                               pango_to_xr (extents.x + extents.width) - xr->x,
1725                               pango_to_xr (extents.y + extents.height) - xr->y);
1726               cairo_restore (xr->cairo);
1727             }
1728           while (pango_layout_iter_next_line (iter));
1729           pango_layout_iter_free (iter);
1730         }
1731
1732       cairo_restore (xr->cairo);
1733     }
1734
1735   int size[TABLE_N_AXES];
1736   pango_layout_get_size (font->layout, &size[H], &size[V]);
1737   int w = pango_to_xr (size[X]);
1738   int h = pango_to_xr (size[Y]);
1739   if (w > *widthp)
1740     *widthp = w;
1741   if (bb[V][0] + h >= bb[V][1] && !(options & TAB_ROTATE))
1742     {
1743       PangoLayoutIter *iter;
1744       int best = 0;
1745
1746       /* Choose a breakpoint between lines instead of in the middle of one. */
1747       iter = pango_layout_get_iter (font->layout);
1748       do
1749         {
1750           PangoRectangle extents;
1751           int y0, y1;
1752           int bottom;
1753
1754           pango_layout_iter_get_line_extents (iter, NULL, &extents);
1755           pango_layout_iter_get_line_yrange (iter, &y0, &y1);
1756           extents.x = pango_to_xr (extents.x);
1757           extents.y = pango_to_xr (y0);
1758           extents.width = pango_to_xr (extents.width);
1759           extents.height = pango_to_xr (y1 - y0);
1760           bottom = bb[V][0] + extents.y + extents.height;
1761           if (bottom < bb[V][1])
1762             {
1763               if (brk && clip[H][0] != clip[H][1])
1764                 best = bottom;
1765               if (brk)
1766                 *brk = bottom;
1767             }
1768           else
1769             break;
1770         }
1771       while (pango_layout_iter_next_line (iter));
1772       pango_layout_iter_free (iter);
1773
1774       /* If enabled, draws a green line across the chosen breakpoint, which can
1775          be useful for debugging issues with breaking.  */
1776       if (0)
1777         {
1778           if (best)
1779             dump_line (xr, -xr->left_margin, best,
1780                        xr->width + xr->right_margin, best,
1781                        RENDER_LINE_SINGLE,
1782                        &(struct cell_color) CELL_COLOR (0, 255, 0));
1783         }
1784     }
1785
1786   pango_layout_set_attributes (font->layout, NULL);
1787
1788   if (font == &local_font)
1789     {
1790       g_object_unref (G_OBJECT (font->layout));
1791       pango_font_description_free (font->desc);
1792     }
1793
1794   return h;
1795 }
1796
1797 static void
1798 xr_layout_cell (struct xr_driver *xr, const struct table_cell *cell,
1799                 int bb[TABLE_N_AXES][2], int clip[TABLE_N_AXES][2],
1800                 int *width, int *height, int *brk)
1801 {
1802   *width = 0;
1803   *height = 0;
1804
1805   /* If enabled, draws a blue rectangle around the cell extents, which can be
1806      useful for debugging layout. */
1807   if (0)
1808     {
1809       if (clip[H][0] != clip[H][1])
1810         {
1811           cairo_save (xr->cairo);
1812           cairo_set_source_rgb (xr->cairo, 0, 0, 1);
1813           dump_rectangle (xr, bb[H][0], bb[V][0], bb[H][1], bb[V][1]);
1814           cairo_restore (xr->cairo);
1815         }
1816     }
1817
1818   if (brk)
1819     *brk = bb[V][0];
1820   *height = xr_layout_cell_text (xr, cell, bb, clip, width, brk);
1821 }
1822 \f
1823 struct output_driver_factory pdf_driver_factory =
1824   { "pdf", "pspp.pdf", xr_pdf_create };
1825 struct output_driver_factory ps_driver_factory =
1826   { "ps", "pspp.ps", xr_ps_create };
1827 struct output_driver_factory svg_driver_factory =
1828   { "svg", "pspp.svg", xr_svg_create };
1829
1830 static const struct output_driver_class cairo_driver_class =
1831 {
1832   "cairo",
1833   xr_destroy,
1834   xr_submit,
1835   xr_flush,
1836 };
1837 \f
1838 /* GUI rendering helpers. */
1839
1840 struct xr_rendering
1841   {
1842     struct output_item *item;
1843
1844     /* Table items. */
1845     struct render_pager *p;
1846     struct xr_driver *xr;
1847   };
1848
1849 #define CHART_WIDTH 500
1850 #define CHART_HEIGHT 375
1851
1852
1853
1854 struct xr_driver *
1855 xr_driver_create (cairo_t *cairo, struct string_map *options)
1856 {
1857   struct xr_driver *xr = xr_allocate ("cairo", 0, options, 1.0);
1858   xr_set_cairo (xr, cairo);
1859   return xr;
1860 }
1861
1862 /* Destroy XR, which should have been created with xr_driver_create().  Any
1863    cairo_t added to XR is not destroyed, because it is owned by the client. */
1864 void
1865 xr_driver_destroy (struct xr_driver *xr)
1866 {
1867   if (xr != NULL)
1868     {
1869       xr->cairo = NULL;
1870       output_driver_destroy (&xr->driver);
1871     }
1872 }
1873
1874 static struct xr_rendering *
1875 xr_rendering_create_text (struct xr_driver *xr, const char *text, cairo_t *cr)
1876 {
1877   struct table_item *table_item;
1878   struct xr_rendering *r;
1879
1880   table_item = table_item_create (table_from_string (text), NULL, NULL);
1881   r = xr_rendering_create (xr, &table_item->output_item, cr);
1882   table_item_unref (table_item);
1883
1884   return r;
1885 }
1886
1887 void
1888 xr_rendering_apply_options (struct xr_rendering *xr, struct string_map *o)
1889 {
1890   if (is_table_item (xr->item))
1891     apply_options (xr->xr, o);
1892 }
1893
1894 struct xr_rendering *
1895 xr_rendering_create (struct xr_driver *xr, const struct output_item *item,
1896                      cairo_t *cr)
1897 {
1898   struct xr_rendering *r = NULL;
1899
1900   if (is_text_item (item))
1901     r = xr_rendering_create_text (xr, text_item_get_text (to_text_item (item)),
1902                                   cr);
1903   else if (is_message_item (item))
1904     {
1905       const struct message_item *message_item = to_message_item (item);
1906       char *s = msg_to_string (message_item_get_msg (message_item));
1907       r = xr_rendering_create_text (xr, s, cr);
1908       free (s);
1909     }
1910   else if (is_table_item (item))
1911     {
1912       r = xzalloc (sizeof *r);
1913       r->item = output_item_ref (item);
1914       r->xr = xr;
1915       xr_set_cairo (xr, cr);
1916       r->p = render_pager_create (xr->params, to_table_item (item));
1917     }
1918   else if (is_chart_item (item))
1919     {
1920       r = xzalloc (sizeof *r);
1921       r->item = output_item_ref (item);
1922     }
1923   else if (is_group_open_item (item))
1924     r = xr_rendering_create_text (xr, to_group_open_item (item)->command_name,
1925                                   cr);
1926
1927   return r;
1928 }
1929
1930 void
1931 xr_rendering_destroy (struct xr_rendering *r)
1932 {
1933   if (r)
1934     {
1935       output_item_unref (r->item);
1936       render_pager_destroy (r->p);
1937       free (r);
1938     }
1939 }
1940
1941 void
1942 xr_rendering_measure (const struct xr_rendering *r, int *wp, int *hp)
1943 {
1944   int w, h;
1945
1946   if (is_table_item (r->item))
1947     {
1948       w = render_pager_get_size (r->p, H) / XR_POINT;
1949       h = render_pager_get_size (r->p, V) / XR_POINT;
1950     }
1951   else
1952     {
1953       w = CHART_WIDTH;
1954       h = CHART_HEIGHT;
1955     }
1956
1957   if (wp)
1958     *wp = w;
1959   if (hp)
1960     *hp = h;
1961 }
1962
1963 static void xr_draw_chart (const struct chart_item *, cairo_t *,
1964                     double x, double y, double width, double height);
1965
1966 /* Draws onto CR */
1967 void
1968 xr_rendering_draw (struct xr_rendering *r, cairo_t *cr,
1969                    int x0, int y0, int x1, int y1)
1970 {
1971   if (is_table_item (r->item))
1972     {
1973       struct xr_driver *xr = r->xr;
1974
1975       xr_set_cairo (xr, cr);
1976
1977       render_pager_draw_region (r->p, x0 * XR_POINT, y0 * XR_POINT,
1978                                 (x1 - x0) * XR_POINT, (y1 - y0) * XR_POINT);
1979     }
1980   else
1981     xr_draw_chart (to_chart_item (r->item), cr,
1982                    0, 0, CHART_WIDTH, CHART_HEIGHT);
1983 }
1984
1985 static void
1986 xr_draw_chart (const struct chart_item *chart_item, cairo_t *cr,
1987                double x, double y, double width, double height)
1988 {
1989   struct xrchart_geometry geom;
1990
1991   cairo_save (cr);
1992   cairo_translate (cr, x, y + height);
1993   cairo_scale (cr, 1.0, -1.0);
1994   xrchart_geometry_init (cr, &geom, width, height);
1995   if (is_boxplot (chart_item))
1996     xrchart_draw_boxplot (chart_item, cr, &geom);
1997   else if (is_histogram_chart (chart_item))
1998     xrchart_draw_histogram (chart_item, cr, &geom);
1999   else if (is_np_plot_chart (chart_item))
2000     xrchart_draw_np_plot (chart_item, cr, &geom);
2001   else if (is_piechart (chart_item))
2002     xrchart_draw_piechart (chart_item, cr, &geom);
2003   else if (is_barchart (chart_item))
2004     xrchart_draw_barchart (chart_item, cr, &geom);
2005   else if (is_roc_chart (chart_item))
2006     xrchart_draw_roc (chart_item, cr, &geom);
2007   else if (is_scree (chart_item))
2008     xrchart_draw_scree (chart_item, cr, &geom);
2009   else if (is_spreadlevel_plot_chart (chart_item))
2010     xrchart_draw_spreadlevel (chart_item, cr, &geom);
2011   else if (is_scatterplot_chart (chart_item))
2012     xrchart_draw_scatterplot (chart_item, cr, &geom);
2013   else
2014     NOT_REACHED ();
2015   xrchart_geometry_free (cr, &geom);
2016
2017   cairo_restore (cr);
2018 }
2019
2020 char *
2021 xr_draw_png_chart (const struct chart_item *item,
2022                    const char *file_name_template, int number,
2023                    const struct cell_color *fg,
2024                    const struct cell_color *bg)
2025 {
2026   const int width = 640;
2027   const int length = 480;
2028
2029   cairo_surface_t *surface;
2030   cairo_status_t status;
2031   const char *number_pos;
2032   char *file_name;
2033   cairo_t *cr;
2034
2035   number_pos = strchr (file_name_template, '#');
2036   if (number_pos != NULL)
2037     file_name = xasprintf ("%.*s%d%s.png", (int) (number_pos - file_name_template),
2038                            file_name_template, number, number_pos + 1);
2039   else
2040     file_name = xasprintf ("%s.png", file_name_template);
2041
2042   surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, length);
2043   cr = cairo_create (surface);
2044
2045   cairo_set_source_rgb (cr, bg->r / 255.0, bg->g / 255.0, bg->b / 255.0);
2046   cairo_paint (cr);
2047
2048   cairo_set_source_rgb (cr, fg->r / 255.0, fg->g / 255.0, fg->b / 255.0);
2049
2050   xr_draw_chart (item, cr, 0.0, 0.0, width, length);
2051
2052   status = cairo_surface_write_to_png (surface, file_name);
2053   if (status != CAIRO_STATUS_SUCCESS)
2054     msg (ME, _("error writing output file `%s': %s"),
2055            file_name, cairo_status_to_string (status));
2056
2057   cairo_destroy (cr);
2058   cairo_surface_destroy (surface);
2059
2060   return file_name;
2061 }
2062
2063
2064 char *
2065 xr_draw_eps_chart (const struct chart_item *item,
2066                    const char *file_name_template, int number,
2067                    const struct cell_color *fg,
2068                    const struct cell_color *bg)
2069 {
2070   const int width = 640;
2071   const int length = 480;
2072
2073   cairo_surface_t *surface;
2074   const char *number_pos;
2075   char *file_name;
2076   cairo_t *cr;
2077
2078   number_pos = strchr (file_name_template, '#');
2079   if (number_pos != NULL)
2080     file_name = xasprintf ("%.*s%d%s.eps", (int) (number_pos - file_name_template),
2081                            file_name_template, number, number_pos + 1);
2082   else
2083     file_name = xasprintf ("%s.eps", file_name_template);
2084
2085   surface = cairo_ps_surface_create (file_name, width, length);
2086   cairo_ps_surface_set_eps (surface, true);
2087   cr = cairo_create (surface);
2088
2089   cairo_set_source_rgb (cr, bg->r / 255.0, bg->g / 255.0, bg->b / 255.0);
2090   cairo_paint (cr);
2091
2092   cairo_set_source_rgb (cr, fg->r / 255.0, fg->g / 255.0, fg->b / 255.0);
2093
2094   xr_draw_chart (item, cr, 0.0, 0.0, width, length);
2095
2096   cairo_destroy (cr);
2097   cairo_surface_destroy (surface);
2098
2099   return file_name;
2100 }
2101
2102 \f
2103
2104 struct xr_table_state
2105   {
2106     struct xr_render_fsm fsm;
2107     struct render_pager *p;
2108   };
2109
2110 static bool
2111 xr_table_render (struct xr_render_fsm *fsm, struct xr_driver *xr)
2112 {
2113   struct xr_table_state *ts = UP_CAST (fsm, struct xr_table_state, fsm);
2114
2115   while (render_pager_has_next (ts->p))
2116     {
2117       int used;
2118
2119       used = render_pager_draw_next (ts->p, xr->length - xr->y);
2120       if (!used)
2121         {
2122           assert (xr->y > 0);
2123           return true;
2124         }
2125       else
2126         xr->y += used;
2127     }
2128   return false;
2129 }
2130
2131 static void
2132 xr_table_destroy (struct xr_render_fsm *fsm)
2133 {
2134   struct xr_table_state *ts = UP_CAST (fsm, struct xr_table_state, fsm);
2135
2136   render_pager_destroy (ts->p);
2137   free (ts);
2138 }
2139
2140 static struct xr_render_fsm *
2141 xr_render_table (struct xr_driver *xr, struct table_item *table_item)
2142 {
2143   struct xr_table_state *ts;
2144
2145   ts = xmalloc (sizeof *ts);
2146   ts->fsm.render = xr_table_render;
2147   ts->fsm.destroy = xr_table_destroy;
2148
2149   if (xr->y > 0)
2150     xr->y += xr->char_height;
2151
2152   ts->p = render_pager_create (xr->params, table_item);
2153   table_item_unref (table_item);
2154
2155   return &ts->fsm;
2156 }
2157 \f
2158 struct xr_chart_state
2159   {
2160     struct xr_render_fsm fsm;
2161     struct chart_item *chart_item;
2162   };
2163
2164 static bool
2165 xr_chart_render (struct xr_render_fsm *fsm, struct xr_driver *xr)
2166 {
2167   struct xr_chart_state *cs = UP_CAST (fsm, struct xr_chart_state, fsm);
2168
2169   const int chart_height = 0.8 * (xr->length < xr->width ? xr->length : xr->width);
2170
2171   if (xr->y > xr->length - chart_height)
2172     return true;
2173
2174   if (xr->cairo != NULL)
2175     {
2176       xr_draw_chart (cs->chart_item, xr->cairo,
2177                      0.0,
2178                      xr_to_pt (xr->y),
2179                      xr_to_pt (xr->width),
2180                      xr_to_pt (chart_height));
2181     }
2182   xr->y += chart_height;
2183
2184   return false;
2185 }
2186
2187 static void
2188 xr_chart_destroy (struct xr_render_fsm *fsm)
2189 {
2190   struct xr_chart_state *cs = UP_CAST (fsm, struct xr_chart_state, fsm);
2191
2192   chart_item_unref (cs->chart_item);
2193   free (cs);
2194 }
2195
2196 static struct xr_render_fsm *
2197 xr_render_chart (const struct chart_item *chart_item)
2198 {
2199   struct xr_chart_state *cs;
2200
2201   cs = xmalloc (sizeof *cs);
2202   cs->fsm.render = xr_chart_render;
2203   cs->fsm.destroy = xr_chart_destroy;
2204   cs->chart_item = chart_item_ref (chart_item);
2205
2206   return &cs->fsm;
2207 }
2208 \f
2209 static bool
2210 xr_eject_render (struct xr_render_fsm *fsm UNUSED, struct xr_driver *xr)
2211 {
2212   return xr->y > 0;
2213 }
2214
2215 static void
2216 xr_eject_destroy (struct xr_render_fsm *fsm UNUSED)
2217 {
2218   /* Nothing to do. */
2219 }
2220
2221 static struct xr_render_fsm *
2222 xr_render_eject (void)
2223 {
2224   static struct xr_render_fsm eject_renderer =
2225     {
2226       xr_eject_render,
2227       xr_eject_destroy
2228     };
2229
2230   return &eject_renderer;
2231 }
2232 \f
2233 static struct xr_render_fsm *
2234 xr_render_text (struct xr_driver *xr, const struct text_item *text_item)
2235 {
2236   enum text_item_type type = text_item_get_type (text_item);
2237   const char *text = text_item_get_text (text_item);
2238
2239   switch (type)
2240     {
2241     case TEXT_ITEM_PAGE_TITLE:
2242       string_map_replace (&xr->heading_vars, "PageTitle", text);
2243       break;
2244
2245     case TEXT_ITEM_EJECT_PAGE:
2246       if (xr->y > 0)
2247         return xr_render_eject ();
2248       break;
2249
2250     default:
2251       return xr_render_table (
2252         xr, text_item_to_table_item (text_item_ref (text_item)));
2253     }
2254
2255   return NULL;
2256 }
2257
2258 static struct xr_render_fsm *
2259 xr_render_message (struct xr_driver *xr,
2260                    const struct message_item *message_item)
2261 {
2262   char *s = msg_to_string (message_item_get_msg (message_item));
2263   struct text_item *item = text_item_create (TEXT_ITEM_LOG, s);
2264   free (s);
2265   return xr_render_table (xr, text_item_to_table_item (item));
2266 }
2267
2268 static struct xr_render_fsm *
2269 xr_render_output_item (struct xr_driver *xr,
2270                        const struct output_item *output_item)
2271 {
2272   if (is_table_item (output_item))
2273     return xr_render_table (xr, table_item_ref (to_table_item (output_item)));
2274   else if (is_chart_item (output_item))
2275     return xr_render_chart (to_chart_item (output_item));
2276   else if (is_text_item (output_item))
2277     return xr_render_text (xr, to_text_item (output_item));
2278   else if (is_message_item (output_item))
2279     return xr_render_message (xr, to_message_item (output_item));
2280   else
2281     return NULL;
2282 }
2283
2284 bool
2285 xr_draw_svg_file (struct xr_rendering *r,
2286                   const char *filename)
2287 {
2288   int width, height;
2289   g_assert (r);
2290   xr_rendering_measure (r, &width, &height);
2291   cairo_surface_t *surface = cairo_svg_surface_create (filename, width, height);
2292   if (!surface)
2293     {
2294       g_error ("Could not create cairo svg surface with file %s", filename);
2295       return FALSE;
2296     }
2297   cairo_t *cr = cairo_create (surface);
2298   xr_rendering_draw (r, cr, 0, 0, width, height);
2299   cairo_destroy (cr);
2300   cairo_surface_destroy (surface);
2301   return TRUE;
2302 }