cairo: Remove write-only member 'file_type' from struct xr_driver.
[pspp-builds.git] / src / output / cairo.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009, 2010 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/message.h"
24 #include "libpspp/start-date.h"
25 #include "libpspp/str.h"
26 #include "libpspp/string-map.h"
27 #include "libpspp/version.h"
28 #include "output/cairo-chart.h"
29 #include "output/chart-item-provider.h"
30 #include "output/charts/boxplot.h"
31 #include "output/charts/np-plot.h"
32 #include "output/charts/piechart.h"
33 #include "output/charts/plot-hist.h"
34 #include "output/charts/roc-chart.h"
35 #include "output/charts/scree.h"
36 #include "output/driver-provider.h"
37 #include "output/message-item.h"
38 #include "output/options.h"
39 #include "output/render.h"
40 #include "output/tab.h"
41 #include "output/table-item.h"
42 #include "output/table.h"
43 #include "output/text-item.h"
44
45 #include <cairo/cairo-pdf.h>
46 #include <cairo/cairo-ps.h>
47 #include <cairo/cairo-svg.h>
48 #include <cairo/cairo.h>
49 #include <pango/pango-font.h>
50 #include <pango/pango-layout.h>
51 #include <pango/pango.h>
52 #include <pango/pangocairo.h>
53 #include <stdlib.h>
54
55 #include "gl/error.h"
56 #include "gl/intprops.h"
57 #include "gl/minmax.h"
58 #include "gl/xalloc.h"
59
60 #include "gettext.h"
61 #define _(msgid) gettext (msgid)
62
63 /* This file uses TABLE_HORZ and TABLE_VERT enough to warrant abbreviating. */
64 #define H TABLE_HORZ
65 #define V TABLE_VERT
66
67 /* Measurements as we present to the rest of PSPP. */
68 #define XR_POINT PANGO_SCALE
69 #define XR_INCH (XR_POINT * 72)
70
71 /* Conversions to and from points. */
72 static double
73 xr_to_pt (int x)
74 {
75   return x / (double) XR_POINT;
76 }
77
78 /* Output types. */
79 enum xr_output_type
80   {
81     XR_PDF,
82     XR_PS,
83     XR_SVG
84   };
85
86 /* Cairo fonts. */
87 enum xr_font_type
88   {
89     XR_FONT_PROPORTIONAL,
90     XR_FONT_EMPHASIS,
91     XR_FONT_FIXED,
92     XR_N_FONTS
93   };
94
95 /* A font for use with Cairo. */
96 struct xr_font
97   {
98     char *string;
99     PangoFontDescription *desc;
100     PangoLayout *layout;
101     PangoFontMetrics *metrics;
102   };
103
104 /* An output item whose rendering is in progress. */
105 struct xr_render_fsm
106   {
107     /* Renders as much of itself as it can on the current page.  Returns true
108        if rendering is complete, false if the output item needs another
109        page. */
110     bool (*render) (struct xr_render_fsm *, struct xr_driver *);
111
112     /* Destroys the output item. */
113     void (*destroy) (struct xr_render_fsm *);
114   };
115
116 /* Cairo output driver. */
117 struct xr_driver
118   {
119     struct output_driver driver;
120
121     /* User parameters. */
122     bool headers;               /* Draw headers at top of page? */
123
124     struct xr_font fonts[XR_N_FONTS];
125     int font_height;            /* In XR units. */
126
127     int width;                  /* Page width minus margins. */
128     int length;                 /* Page length minus margins and header. */
129
130     int left_margin;            /* Left margin in XR units. */
131     int right_margin;           /* Right margin in XR units. */
132     int top_margin;             /* Top margin in XR units. */
133     int bottom_margin;          /* Bottom margin in XR units. */
134
135     int line_gutter;            /* Space around lines. */
136     int line_space;             /* Space between lines. */
137     int line_width;             /* Width of lines. */
138
139     /* Internal state. */
140     struct render_params *params;
141     char *command_name;
142     char *title;
143     char *subtitle;
144     cairo_t *cairo;
145     int page_number;            /* Current page number. */
146     int y;
147     struct xr_render_fsm *fsm;
148   };
149
150 static const struct output_driver_class cairo_driver_class;
151
152 static void draw_headers (struct xr_driver *);
153 static void xr_driver_destroy_fsm (struct xr_driver *);
154 static void xr_driver_run_fsm (struct xr_driver *);
155
156 static bool load_font (struct xr_driver *, struct xr_font *);
157 static void free_font (struct xr_font *);
158
159 static void xr_draw_line (void *, int bb[TABLE_N_AXES][2],
160                           enum render_line_style styles[TABLE_N_AXES][2]);
161 static void xr_measure_cell_width (void *, const struct table_cell *,
162                                    int *min, int *max);
163 static int xr_measure_cell_height (void *, const struct table_cell *,
164                                    int width);
165 static void xr_draw_cell (void *, const struct table_cell *,
166                           int bb[TABLE_N_AXES][2],
167                           int clip[TABLE_N_AXES][2]);
168
169 static struct xr_render_fsm *xr_render_output_item (
170   struct xr_driver *, const struct output_item *);
171 \f
172 /* Output driver basics. */
173
174 static struct xr_driver *
175 xr_driver_cast (struct output_driver *driver)
176 {
177   assert (driver->class == &cairo_driver_class);
178   return UP_CAST (driver, struct xr_driver, driver);
179 }
180
181 static struct driver_option *
182 opt (struct output_driver *d, struct string_map *options, const char *key,
183      const char *default_value)
184 {
185   return driver_option_get (d, options, key, default_value);
186 }
187
188 static struct xr_driver *
189 xr_allocate (const char *name, int device_type, struct string_map *o)
190 {
191   struct output_driver *d;
192   struct xr_driver *xr;
193
194   xr = xzalloc (sizeof *xr);
195   d = &xr->driver;
196   output_driver_init (d, &cairo_driver_class, name, device_type);
197   xr->headers = true;
198   xr->font_height = XR_POINT * 10;
199   xr->fonts[XR_FONT_FIXED].string
200     = parse_string (opt (d, o, "fixed-font", "monospace"));
201   xr->fonts[XR_FONT_PROPORTIONAL].string
202     = parse_string (opt (d, o, "prop-font", "serif"));
203   xr->fonts[XR_FONT_EMPHASIS].string
204     = parse_string (opt (d, o, "emph-font", "serif italic"));
205   xr->line_gutter = XR_POINT;
206   xr->line_space = XR_POINT;
207   xr->line_width = XR_POINT / 2;
208   xr->page_number = 1;
209
210   return xr;
211 }
212
213 static bool
214 xr_set_cairo (struct xr_driver *xr, cairo_t *cairo)
215 {
216   int i;
217
218   xr->cairo = cairo;
219
220   cairo_set_line_width (xr->cairo, xr_to_pt (xr->line_width));
221
222   for (i = 0; i < XR_N_FONTS; i++)
223     if (!load_font (xr, &xr->fonts[i]))
224       return false;
225
226   if (xr->params == NULL)
227     {
228       int single_width, double_width;
229
230       xr->params = xmalloc (sizeof *xr->params);
231       xr->params->draw_line = xr_draw_line;
232       xr->params->measure_cell_width = xr_measure_cell_width;
233       xr->params->measure_cell_height = xr_measure_cell_height;
234       xr->params->draw_cell = xr_draw_cell;
235       xr->params->aux = xr;
236       xr->params->size[H] = xr->width;
237       xr->params->size[V] = xr->length;
238       xr->params->font_size[H] = xr->font_height / 2; /* XXX */
239       xr->params->font_size[V] = xr->font_height;
240
241       single_width = 2 * xr->line_gutter + xr->line_width;
242       double_width = 2 * xr->line_gutter + xr->line_space + 2 * xr->line_width;
243       for (i = 0; i < TABLE_N_AXES; i++)
244         {
245           xr->params->line_widths[i][RENDER_LINE_NONE] = 0;
246           xr->params->line_widths[i][RENDER_LINE_SINGLE] = single_width;
247           xr->params->line_widths[i][RENDER_LINE_DOUBLE] = double_width;
248         }
249     }
250
251   return true;
252 }
253
254 static struct output_driver *
255 xr_create (const char *file_name, enum settings_output_devices device_type,
256            struct string_map *o, enum xr_output_type file_type)
257 {
258   enum { MIN_WIDTH = 3, MIN_LENGTH = 3 };
259   struct output_driver *d;
260   struct xr_driver *xr;
261   cairo_surface_t *surface;
262   cairo_status_t status;
263   double width_pt, length_pt;
264   int paper_width, paper_length;
265
266   xr = xr_allocate (file_name, device_type, o);
267   d = &xr->driver;
268
269   xr->headers = parse_boolean (opt (d, o, "headers", "true"));
270
271   parse_paper_size (opt (d, o, "paper-size", ""), &paper_width, &paper_length);
272   xr->left_margin = parse_dimension (opt (d, o, "left-margin", ".5in"));
273   xr->right_margin = parse_dimension (opt (d, o, "right-margin", ".5in"));
274   xr->top_margin = parse_dimension (opt (d, o, "top-margin", ".5in"));
275   xr->bottom_margin = parse_dimension (opt (d, o, "bottom-margin", ".5in"));
276
277   if (xr->headers)
278     xr->top_margin += 3 * xr->font_height;
279   xr->width = paper_width - xr->left_margin - xr->right_margin;
280   xr->length = paper_length - xr->top_margin - xr->bottom_margin;
281
282   width_pt = paper_width / 1000.0;
283   length_pt = paper_length / 1000.0;
284   if (file_type == XR_PDF)
285     surface = cairo_pdf_surface_create (file_name, width_pt, length_pt);
286   else if (file_type == XR_PS)
287     surface = cairo_ps_surface_create (file_name, width_pt, length_pt);
288   else if (file_type == XR_SVG)
289     surface = cairo_svg_surface_create (file_name, width_pt, length_pt);
290   else
291     NOT_REACHED ();
292
293   status = cairo_surface_status (surface);
294   if (status != CAIRO_STATUS_SUCCESS)
295     {
296       error (0, 0, _("error opening output file \"%s\": %s"),
297              file_name, cairo_status_to_string (status));
298       cairo_surface_destroy (surface);
299       goto error;
300     }
301
302   xr->cairo = cairo_create (surface);
303   cairo_surface_destroy (surface);
304
305   cairo_translate (xr->cairo,
306                    xr_to_pt (xr->left_margin),
307                    xr_to_pt (xr->top_margin));
308
309   if (!xr_set_cairo (xr, xr->cairo))
310     goto error;
311
312   if (xr->width / (xr->font_height / 2) < MIN_WIDTH)
313     {
314       error (0, 0, _("The defined page is not wide enough to hold at least %d "
315                      "characters in the default font.  In fact, there's only "
316                      "room for %d characters."),
317              MIN_WIDTH,
318              xr->width / (xr->font_height / 2));
319       goto error;
320     }
321
322   if (xr->length / xr->font_height < MIN_LENGTH)
323     {
324       error (0, 0, _("The defined page is not long "
325                      "enough to hold margins and headers, plus least %d "
326                      "lines of the default fonts.  In fact, there's only "
327                      "room for %d lines."),
328              MIN_LENGTH,
329              xr->length / xr->font_height);
330       goto error;
331     }
332
333   draw_headers (xr);
334
335   return &xr->driver;
336
337  error:
338   output_driver_destroy (&xr->driver);
339   return NULL;
340 }
341
342 static struct output_driver *
343 xr_pdf_create (const char *file_name, enum settings_output_devices device_type,
344                struct string_map *o)
345 {
346   return xr_create (file_name, device_type, o, XR_PDF);
347 }
348
349 static struct output_driver *
350 xr_ps_create (const char *file_name, enum settings_output_devices device_type,
351                struct string_map *o)
352 {
353   return xr_create (file_name, device_type, o, XR_PS);
354 }
355
356 static struct output_driver *
357 xr_svg_create (const char *file_name, enum settings_output_devices device_type,
358                struct string_map *o)
359 {
360   return xr_create (file_name, device_type, o, XR_SVG);
361 }
362
363 static void
364 xr_destroy (struct output_driver *driver)
365 {
366   struct xr_driver *xr = xr_driver_cast (driver);
367   size_t i;
368
369   xr_driver_destroy_fsm (xr);
370
371   if (xr->cairo != NULL)
372     {
373       cairo_status_t status;
374
375       cairo_surface_finish (cairo_get_target (xr->cairo));
376       status = cairo_status (xr->cairo);
377       if (status != CAIRO_STATUS_SUCCESS)
378         error (0, 0, _("error drawing output for %s driver: %s"),
379                output_driver_get_name (driver),
380                cairo_status_to_string (status));
381       cairo_destroy (xr->cairo);
382     }
383
384   free (xr->command_name);
385   for (i = 0; i < XR_N_FONTS; i++)
386     free_font (&xr->fonts[i]);
387   free (xr->params);
388   free (xr);
389 }
390
391 static void
392 xr_flush (struct output_driver *driver)
393 {
394   struct xr_driver *xr = xr_driver_cast (driver);
395
396   cairo_surface_flush (cairo_get_target (xr->cairo));
397 }
398
399 static void
400 xr_init_caption_cell (const char *caption, struct table_cell *cell)
401 {
402   cell->contents = caption;
403   cell->options = TAB_LEFT;
404   cell->destructor = NULL;
405 }
406
407 static struct render_page *
408 xr_render_table_item (struct xr_driver *xr, const struct table_item *item,
409                       int *caption_heightp)
410 {
411   const char *caption = table_item_get_caption (item);
412
413   if (caption != NULL)
414     {
415       /* XXX doesn't do well with very large captions */
416       struct table_cell cell;
417       xr_init_caption_cell (caption, &cell);
418       *caption_heightp = xr_measure_cell_height (xr, &cell, xr->width);
419     }
420   else
421     *caption_heightp = 0;
422
423   return render_page_create (xr->params, table_item_get_table (item));
424 }
425
426 static void
427 xr_submit (struct output_driver *driver, const struct output_item *output_item)
428 {
429   struct xr_driver *xr = xr_driver_cast (driver);
430
431   xr_driver_output_item (xr, output_item);
432   while (xr_driver_need_new_page (xr))
433     {
434       cairo_show_page (xr->cairo);
435       xr_driver_next_page (xr, xr->cairo);
436     }
437 }
438 \f
439 /* Functions for rendering a series of output items to a series of Cairo
440    contexts, with pagination, possibly including headers.
441
442    Used by PSPPIRE for printing, and by the basic Cairo output driver above as
443    its underlying implementation.
444
445    See the big comment in cairo.h for intended usage. */
446
447 /* Gives new page CAIRO to XR for output.  CAIRO may be null to skip actually
448    rendering the page (which might be useful to find out how many pages an
449    output document has without actually rendering it). */
450 void
451 xr_driver_next_page (struct xr_driver *xr, cairo_t *cairo)
452 {
453   xr->page_number++;
454   xr->cairo = cairo;
455   xr->y = 0;
456   draw_headers (xr);
457   xr_driver_run_fsm (xr);
458 }
459
460 /* Start rendering OUTPUT_ITEM to XR.  Only valid if XR is not in the middle of
461    rendering a previous output item, that is, only if xr_driver_need_new_page()
462    returns false. */
463 void
464 xr_driver_output_item (struct xr_driver *xr,
465                        const struct output_item *output_item)
466 {
467   assert (xr->fsm == NULL);
468   xr->fsm = xr_render_output_item (xr, output_item);
469   xr_driver_run_fsm (xr);
470 }
471
472 /* Returns true if XR is in the middle of rendering an output item and needs a
473    new page to be appended using xr_driver_next_page() to make progress,
474    otherwise false. */
475 bool
476 xr_driver_need_new_page (const struct xr_driver *xr)
477 {
478   return xr->fsm != NULL;
479 }
480
481 /* Returns true if the current page doesn't have any content yet (besides
482    headers, if enabled). */
483 bool
484 xr_driver_is_page_blank (const struct xr_driver *xr)
485 {
486   return xr->y == 0;
487 }
488
489 static void
490 xr_driver_destroy_fsm (struct xr_driver *xr)
491 {
492   if (xr->fsm != NULL)
493     {
494       xr->fsm->destroy (xr->fsm);
495       xr->fsm = NULL;
496     }
497 }
498
499 static void
500 xr_driver_run_fsm (struct xr_driver *xr)
501 {
502   if (xr->fsm != NULL && !xr->fsm->render (xr->fsm, xr))
503     xr_driver_destroy_fsm (xr);
504 }
505 \f
506 static void
507 xr_layout_cell (struct xr_driver *, const struct table_cell *,
508                 int bb[TABLE_N_AXES][2], int clip[TABLE_N_AXES][2],
509                 PangoWrapMode, int *width, int *height);
510
511 static void
512 dump_line (struct xr_driver *xr, int x0, int y0, int x1, int y1)
513 {
514   cairo_new_path (xr->cairo);
515   cairo_move_to (xr->cairo, xr_to_pt (x0), xr_to_pt (y0 + xr->y));
516   cairo_line_to (xr->cairo, xr_to_pt (x1), xr_to_pt (y1 + xr->y));
517   cairo_stroke (xr->cairo);
518 }
519
520 /* Draws a horizontal line X0...X2 at Y if LEFT says so,
521    shortening it to X0...X1 if SHORTEN is true.
522    Draws a horizontal line X1...X3 at Y if RIGHT says so,
523    shortening it to X2...X3 if SHORTEN is true. */
524 static void
525 horz_line (struct xr_driver *xr, int x0, int x1, int x2, int x3, int y,
526            enum render_line_style left, enum render_line_style right,
527            bool shorten)
528 {
529   if (left != RENDER_LINE_NONE && right != RENDER_LINE_NONE && !shorten)
530     dump_line (xr, x0, y, x3, y);
531   else
532     {
533       if (left != RENDER_LINE_NONE)
534         dump_line (xr, x0, y, shorten ? x1 : x2, y);
535       if (right != RENDER_LINE_NONE)
536         dump_line (xr, shorten ? x2 : x1, y, x3, y);
537     }
538 }
539
540 /* Draws a vertical line Y0...Y2 at X if TOP says so,
541    shortening it to Y0...Y1 if SHORTEN is true.
542    Draws a vertical line Y1...Y3 at X if BOTTOM says so,
543    shortening it to Y2...Y3 if SHORTEN is true. */
544 static void
545 vert_line (struct xr_driver *xr, int y0, int y1, int y2, int y3, int x,
546            enum render_line_style top, enum render_line_style bottom,
547            bool shorten)
548 {
549   if (top != RENDER_LINE_NONE && bottom != RENDER_LINE_NONE && !shorten)
550     dump_line (xr, x, y0, x, y3);
551   else
552     {
553       if (top != RENDER_LINE_NONE)
554         dump_line (xr, x, y0, x, shorten ? y1 : y2);
555       if (bottom != RENDER_LINE_NONE)
556         dump_line (xr, x, shorten ? y2 : y1, x, y3);
557     }
558 }
559
560 static void
561 xr_draw_line (void *xr_, int bb[TABLE_N_AXES][2],
562               enum render_line_style styles[TABLE_N_AXES][2])
563 {
564   const int x0 = bb[H][0];
565   const int y0 = bb[V][0];
566   const int x3 = bb[H][1];
567   const int y3 = bb[V][1];
568   const int top = styles[H][0];
569   const int left = styles[V][0];
570   const int bottom = styles[H][1];
571   const int right = styles[V][1];
572
573   /* The algorithm here is somewhat subtle, to allow it to handle
574      all the kinds of intersections that we need.
575
576      Three additional ordinates are assigned along the x axis.  The
577      first is xc, midway between x0 and x3.  The others are x1 and
578      x2; for a single vertical line these are equal to xc, and for
579      a double vertical line they are the ordinates of the left and
580      right half of the double line.
581
582      yc, y1, and y2 are assigned similarly along the y axis.
583
584      The following diagram shows the coordinate system and output
585      for double top and bottom lines, single left line, and no
586      right line:
587
588                  x0       x1 xc  x2      x3
589                y0 ________________________
590                   |        #     #       |
591                   |        #     #       |
592                   |        #     #       |
593                   |        #     #       |
594                   |        #     #       |
595      y1 = y2 = yc |#########     #       |
596                   |        #     #       |
597                   |        #     #       |
598                   |        #     #       |
599                   |        #     #       |
600                y3 |________#_____#_______|
601   */
602   struct xr_driver *xr = xr_;
603
604   /* Offset from center of each line in a pair of double lines. */
605   int double_line_ofs = (xr->line_space + xr->line_width) / 2;
606
607   /* Are the lines along each axis single or double?
608      (It doesn't make sense to have different kinds of line on the
609      same axis, so we don't try to gracefully handle that case.) */
610   bool double_vert = top == RENDER_LINE_DOUBLE || bottom == RENDER_LINE_DOUBLE;
611   bool double_horz = left == RENDER_LINE_DOUBLE || right == RENDER_LINE_DOUBLE;
612
613   /* When horizontal lines are doubled,
614      the left-side line along y1 normally runs from x0 to x2,
615      and the right-side line along y1 from x3 to x1.
616      If the top-side line is also doubled, we shorten the y1 lines,
617      so that the left-side line runs only to x1,
618      and the right-side line only to x2.
619      Otherwise, the horizontal line at y = y1 below would cut off
620      the intersection, which looks ugly:
621                x0       x1     x2      x3
622              y0 ________________________
623                 |        #     #       |
624                 |        #     #       |
625                 |        #     #       |
626                 |        #     #       |
627              y1 |#########     ########|
628                 |                      |
629                 |                      |
630              y2 |######################|
631                 |                      |
632                 |                      |
633              y3 |______________________|
634      It is more of a judgment call when the horizontal line is
635      single.  We actually choose to cut off the line anyhow, as
636      shown in the first diagram above.
637   */
638   bool shorten_y1_lines = top == RENDER_LINE_DOUBLE;
639   bool shorten_y2_lines = bottom == RENDER_LINE_DOUBLE;
640   bool shorten_yc_line = shorten_y1_lines && shorten_y2_lines;
641   int horz_line_ofs = double_vert ? double_line_ofs : 0;
642   int xc = (x0 + x3) / 2;
643   int x1 = xc - horz_line_ofs;
644   int x2 = xc + horz_line_ofs;
645
646   bool shorten_x1_lines = left == RENDER_LINE_DOUBLE;
647   bool shorten_x2_lines = right == RENDER_LINE_DOUBLE;
648   bool shorten_xc_line = shorten_x1_lines && shorten_x2_lines;
649   int vert_line_ofs = double_horz ? double_line_ofs : 0;
650   int yc = (y0 + y3) / 2;
651   int y1 = yc - vert_line_ofs;
652   int y2 = yc + vert_line_ofs;
653
654   if (!double_horz)
655     horz_line (xr, x0, x1, x2, x3, yc, left, right, shorten_yc_line);
656   else
657     {
658       horz_line (xr, x0, x1, x2, x3, y1, left, right, shorten_y1_lines);
659       horz_line (xr, x0, x1, x2, x3, y2, left, right, shorten_y2_lines);
660     }
661
662   if (!double_vert)
663     vert_line (xr, y0, y1, y2, y3, xc, top, bottom, shorten_xc_line);
664   else
665     {
666       vert_line (xr, y0, y1, y2, y3, x1, top, bottom, shorten_x1_lines);
667       vert_line (xr, y0, y1, y2, y3, x2, top, bottom, shorten_x2_lines);
668     }
669 }
670
671 static void
672 xr_measure_cell_width (void *xr_, const struct table_cell *cell,
673                        int *min_width, int *max_width)
674 {
675   struct xr_driver *xr = xr_;
676   int bb[TABLE_N_AXES][2];
677   int clip[TABLE_N_AXES][2];
678   int h;
679
680   bb[H][0] = 0;
681   bb[H][1] = INT_MAX;
682   bb[V][0] = 0;
683   bb[V][1] = INT_MAX;
684   clip[H][0] = clip[H][1] = clip[V][0] = clip[V][1] = 0;
685   xr_layout_cell (xr, cell, bb, clip, PANGO_WRAP_WORD, max_width, &h);
686
687   bb[H][1] = 1;
688   xr_layout_cell (xr, cell, bb, clip, PANGO_WRAP_WORD, min_width, &h);
689 }
690
691 static int
692 xr_measure_cell_height (void *xr_, const struct table_cell *cell, int width)
693 {
694   struct xr_driver *xr = xr_;
695   int bb[TABLE_N_AXES][2];
696   int clip[TABLE_N_AXES][2];
697   int w, h;
698
699   bb[H][0] = 0;
700   bb[H][1] = width;
701   bb[V][0] = 0;
702   bb[V][1] = INT_MAX;
703   clip[H][0] = clip[H][1] = clip[V][0] = clip[V][1] = 0;
704   xr_layout_cell (xr, cell, bb, clip, PANGO_WRAP_WORD, &w, &h);
705   return h;
706 }
707
708 static void
709 xr_draw_cell (void *xr_, const struct table_cell *cell,
710               int bb[TABLE_N_AXES][2], int clip[TABLE_N_AXES][2])
711 {
712   struct xr_driver *xr = xr_;
713   int w, h;
714
715   xr_layout_cell (xr, cell, bb, clip, PANGO_WRAP_WORD, &w, &h);
716 }
717 \f
718 /* Writes STRING at location (X,Y) trimmed to the given MAX_WIDTH
719    and with the given cell OPTIONS for XR. */
720 static int
721 draw_text (struct xr_driver *xr, const char *string, int x, int y,
722            int max_width, unsigned int options)
723 {
724   struct table_cell cell;
725   int bb[TABLE_N_AXES][2];
726   int w, h;
727
728   cell.contents = string;
729   cell.options = options;
730   bb[H][0] = x;
731   bb[V][0] = y - xr->y;
732   bb[H][1] = x + max_width;
733   bb[V][1] = xr->font_height - xr->y;
734   xr_layout_cell (xr, &cell, bb, bb, PANGO_WRAP_WORD_CHAR, &w, &h);
735   return w;
736 }
737
738 /* Writes LEFT left-justified and RIGHT right-justified within
739    (X0...X1) at Y.  LEFT or RIGHT or both may be null. */
740 static void
741 draw_header_line (struct xr_driver *xr, const char *left, const char *right,
742                   int x0, int x1, int y)
743 {
744   int right_width = 0;
745   if (right != NULL)
746     right_width = (draw_text (xr, right, x0, y, x1 - x0, TAB_RIGHT)
747                    + xr->font_height / 2);
748   if (left != NULL)
749     draw_text (xr, left, x0, y, x1 - x0 - right_width, TAB_LEFT);
750 }
751
752 /* Draw top of page headers for XR. */
753 static void
754 draw_headers (struct xr_driver *xr)
755 {
756   char *r1, *r2;
757   int x0, x1;
758   int y;
759
760   if (!xr->headers || xr->cairo == NULL)
761     return;
762
763   y = -3 * xr->font_height;
764   x0 = xr->font_height / 2;
765   x1 = xr->width - xr->font_height / 2;
766
767   /* Draw box. */
768   cairo_rectangle (xr->cairo, 0, xr_to_pt (y), xr_to_pt (xr->width),
769                    xr_to_pt (2 * (xr->font_height
770                                   + xr->line_width + xr->line_gutter)));
771   cairo_save (xr->cairo);
772   cairo_set_source_rgb (xr->cairo, 0.9, 0.9, 0.9);
773   cairo_fill_preserve (xr->cairo);
774   cairo_restore (xr->cairo);
775   cairo_stroke (xr->cairo);
776
777   y += xr->line_width + xr->line_gutter;
778
779   r1 = xasprintf (_("%s - Page %d"), get_start_date (), xr->page_number);
780   r2 = xasprintf ("%s - %s", version, host_system);
781
782   draw_header_line (xr, xr->title, r1, x0, x1, y);
783   y += xr->font_height;
784
785   draw_header_line (xr, xr->subtitle, r2, x0, x1, y);
786
787   free (r1);
788   free (r2);
789 }
790 \f
791 static void
792 xr_layout_cell (struct xr_driver *xr, const struct table_cell *cell,
793                 int bb[TABLE_N_AXES][2], int clip[TABLE_N_AXES][2],
794                 PangoWrapMode wrap, int *width, int *height)
795 {
796   struct xr_font *font;
797
798   font = (cell->options & TAB_FIX ? &xr->fonts[XR_FONT_FIXED]
799           : cell->options & TAB_EMPH ? &xr->fonts[XR_FONT_EMPHASIS]
800           : &xr->fonts[XR_FONT_PROPORTIONAL]);
801
802   pango_layout_set_text (font->layout, cell->contents, -1);
803
804   pango_layout_set_alignment (
805     font->layout,
806     ((cell->options & TAB_ALIGNMENT) == TAB_RIGHT ? PANGO_ALIGN_RIGHT
807      : (cell->options & TAB_ALIGNMENT) == TAB_LEFT ? PANGO_ALIGN_LEFT
808      : PANGO_ALIGN_CENTER));
809   pango_layout_set_width (font->layout,
810                           bb[H][1] == INT_MAX ? -1 : bb[H][1] - bb[H][0]);
811   pango_layout_set_wrap (font->layout, wrap);
812
813   if (clip[H][0] != clip[H][1])
814     {
815       cairo_save (xr->cairo);
816
817       if (clip[H][1] != INT_MAX || clip[V][1] != INT_MAX)
818         {
819           double x0 = xr_to_pt (clip[H][0]);
820           double y0 = xr_to_pt (clip[V][0] + xr->y);
821           double x1 = xr_to_pt (clip[H][1]);
822           double y1 = xr_to_pt (clip[V][1] + xr->y);
823
824           cairo_rectangle (xr->cairo, x0, y0, x1 - x0, y1 - y0);
825           cairo_clip (xr->cairo);
826         }
827
828       cairo_translate (xr->cairo,
829                        xr_to_pt (bb[H][0]),
830                        xr_to_pt (bb[V][0] + xr->y));
831       pango_cairo_show_layout (xr->cairo, font->layout);
832       cairo_restore (xr->cairo);
833     }
834
835   if (width != NULL || height != NULL)
836     {
837       int w, h;
838
839       pango_layout_get_size (font->layout, &w, &h);
840       if (width != NULL)
841         *width = w;
842       if (height != NULL)
843         *height = h;
844     }
845 }
846 \f
847 /* Attempts to load FONT, initializing its other members based on
848    its 'string' member and the information in DRIVER.  Returns true
849    if successful, otherwise false. */
850 static bool
851 load_font (struct xr_driver *xr, struct xr_font *font)
852 {
853   PangoContext *context;
854   PangoLanguage *language;
855
856   font->desc = pango_font_description_from_string (font->string);
857   if (font->desc == NULL)
858     {
859       error (0, 0, _("\"%s\": bad font specification"), font->string);
860       return false;
861     }
862   pango_font_description_set_absolute_size (font->desc, xr->font_height);
863
864   font->layout = pango_cairo_create_layout (xr->cairo);
865   pango_layout_set_font_description (font->layout, font->desc);
866
867   language = pango_language_get_default ();
868   context = pango_layout_get_context (font->layout);
869   font->metrics = pango_context_get_metrics (context, font->desc, language);
870
871   return true;
872 }
873
874 /* Frees FONT. */
875 static void
876 free_font (struct xr_font *font)
877 {
878   free (font->string);
879   if (font->desc != NULL)
880     pango_font_description_free (font->desc);
881   pango_font_metrics_unref (font->metrics);
882   if (font->layout != NULL)
883     g_object_unref (font->layout);
884 }
885
886 struct output_driver_factory pdf_driver_factory = { "pdf", xr_pdf_create };
887 struct output_driver_factory ps_driver_factory = { "ps", xr_ps_create };
888 struct output_driver_factory svg_driver_factory = { "svg", xr_svg_create };
889
890 static const struct output_driver_class cairo_driver_class =
891 {
892   "cairo",
893   xr_destroy,
894   xr_submit,
895   xr_flush,
896 };
897 \f
898 /* GUI rendering helpers. */
899
900 struct xr_rendering
901   {
902     /* Table items. */
903     struct render_page *page;
904     struct xr_driver *xr;
905     int title_height;
906
907     /* Chart items. */
908     struct chart_item *chart;
909   };
910
911 #define CHART_WIDTH 500
912 #define CHART_HEIGHT 375
913
914 struct xr_driver *
915 xr_driver_create (cairo_t *cairo, struct string_map *options)
916 {
917   struct xr_driver *xr = xr_allocate ("cairo", 0, options);
918   xr->width = INT_MAX / 8;
919   xr->length = INT_MAX / 8;
920   if (!xr_set_cairo (xr, cairo))
921     {
922       output_driver_destroy (&xr->driver);
923       return NULL;
924     }
925   return xr;
926 }
927
928 static struct xr_rendering *
929 xr_rendering_create_text (struct xr_driver *xr, const char *text, cairo_t *cr)
930 {
931   struct table_item *table_item;
932   struct xr_rendering *r;
933
934   table_item = table_item_create (table_from_string (0, text), NULL);
935   r = xr_rendering_create (xr, &table_item->output_item, cr);
936   table_item_unref (table_item);
937
938   return r;
939 }
940
941 struct xr_rendering *
942 xr_rendering_create (struct xr_driver *xr, const struct output_item *item,
943                      cairo_t *cr)
944 {
945   struct xr_rendering *r = NULL;
946
947   if (is_text_item (item))
948     r = xr_rendering_create_text (xr, text_item_get_text (to_text_item (item)),
949                                   cr);
950   else if (is_message_item (item))
951     {
952       const struct message_item *message_item = to_message_item (item);
953       const struct msg *msg = message_item_get_msg (message_item);
954       char *s = msg_to_string (msg, NULL);
955       r = xr_rendering_create_text (xr, s, cr);
956       free (s);
957     }
958   else if (is_table_item (item))
959     {
960       r = xzalloc (sizeof *r);
961       r->xr = xr;
962       xr_set_cairo (xr, cr);
963       r->page = xr_render_table_item (xr, to_table_item (item),
964                                       &r->title_height);
965     }
966   else if (is_chart_item (item))
967     {
968       r = xzalloc (sizeof *r);
969       r->chart = to_chart_item (output_item_ref (item));
970     }
971
972   return r;
973 }
974
975 void
976 xr_rendering_measure (struct xr_rendering *r, int *w, int *h)
977 {
978   if (r->chart == NULL)
979     {
980       *w = render_page_get_size (r->page, H) / 1024;
981       *h = (render_page_get_size (r->page, V) + r->title_height) / 1024;
982     }
983   else
984     {
985       *w = CHART_WIDTH;
986       *h = CHART_HEIGHT;
987     }
988 }
989
990 void
991 xr_rendering_draw (struct xr_rendering *r, cairo_t *cr)
992 {
993   if (r->chart == NULL)
994     {
995       struct xr_driver *xr = r->xr;
996
997       xr_set_cairo (xr, cr);
998       xr->y = 0;
999       render_page_draw (r->page);
1000     }
1001   else
1002     xr_draw_chart (r->chart, cr, 0, 0, CHART_WIDTH, CHART_HEIGHT);
1003 }
1004
1005 void
1006 xr_draw_chart (const struct chart_item *chart_item, cairo_t *cr,
1007                double x, double y, double width, double height)
1008 {
1009   struct xrchart_geometry geom;
1010
1011   cairo_save (cr);
1012   cairo_translate (cr, x, y + height);
1013   cairo_scale (cr, 1.0, -1.0);
1014   xrchart_geometry_init (cr, &geom, width, height);
1015   if (is_boxplot (chart_item))
1016     xrchart_draw_boxplot (chart_item, cr, &geom);
1017   else if (is_histogram_chart (chart_item))
1018     xrchart_draw_histogram (chart_item, cr, &geom);
1019   else if (is_np_plot_chart (chart_item))
1020     xrchart_draw_np_plot (chart_item, cr, &geom);
1021   else if (is_piechart (chart_item))
1022     xrchart_draw_piechart (chart_item, cr, &geom);
1023   else if (is_roc_chart (chart_item))
1024     xrchart_draw_roc (chart_item, cr, &geom);
1025   else if (is_scree (chart_item))
1026     xrchart_draw_scree (chart_item, cr, &geom);
1027   else
1028     NOT_REACHED ();
1029   xrchart_geometry_free (cr, &geom);
1030
1031   cairo_restore (cr);
1032 }
1033
1034 char *
1035 xr_draw_png_chart (const struct chart_item *item,
1036                    const char *file_name_template, int number)
1037 {
1038   const int width = 640;
1039   const int length = 480;
1040
1041   cairo_surface_t *surface;
1042   cairo_status_t status;
1043   const char *number_pos;
1044   char *file_name;
1045   cairo_t *cr;
1046
1047   number_pos = strchr (file_name_template, '#');
1048   if (number_pos != NULL)
1049     file_name = xasprintf ("%.*s%d%s", (int) (number_pos - file_name_template),
1050                            file_name_template, number, number_pos + 1);
1051   else
1052     file_name = xstrdup (file_name_template);
1053
1054   surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, length);
1055   cr = cairo_create (surface);
1056
1057   cairo_save (cr);
1058   cairo_set_source_rgb (cr, 1.0, 1.0, 1.0);
1059   cairo_rectangle (cr, 0, 0, width, length);
1060   cairo_fill (cr);
1061   cairo_restore (cr);
1062
1063   cairo_set_source_rgb (cr, 0.0, 0.0, 0.0);
1064
1065   xr_draw_chart (item, cr, 0.0, 0.0, width, length);
1066
1067   status = cairo_surface_write_to_png (surface, file_name);
1068   if (status != CAIRO_STATUS_SUCCESS)
1069     error (0, 0, _("error writing output file \"%s\": %s"),
1070            file_name, cairo_status_to_string (status));
1071
1072   cairo_destroy (cr);
1073   cairo_surface_destroy (surface);
1074
1075   return file_name;
1076 }
1077 \f
1078 struct xr_table_state
1079   {
1080     struct xr_render_fsm fsm;
1081     struct table_item *table_item;
1082     struct render_break x_break;
1083     struct render_break y_break;
1084     int caption_height;
1085   };
1086
1087 static bool
1088 xr_table_render (struct xr_render_fsm *fsm, struct xr_driver *xr)
1089 {
1090   struct xr_table_state *ts = UP_CAST (fsm, struct xr_table_state, fsm);
1091
1092   for (;;)
1093     {
1094       struct render_page *y_slice;
1095       int space;
1096
1097       while (!render_break_has_next (&ts->y_break))
1098         {
1099           struct render_page *x_slice;
1100
1101           render_break_destroy (&ts->y_break);
1102           if (!render_break_has_next (&ts->x_break))
1103             return false;
1104
1105           x_slice = render_break_next (&ts->x_break, xr->width);
1106           render_break_init (&ts->y_break, x_slice, V);
1107         }
1108
1109       space = xr->length - xr->y;
1110       if (render_break_next_size (&ts->y_break) > space)
1111         {
1112           assert (xr->y > 0);
1113           return true;
1114         }
1115
1116       y_slice = render_break_next (&ts->y_break, space);
1117       if (ts->caption_height)
1118         {
1119           if (xr->cairo)
1120             {
1121               struct table_cell cell;
1122               int bb[TABLE_N_AXES][2];
1123
1124               xr_init_caption_cell (table_item_get_caption (ts->table_item),
1125                                     &cell);
1126               bb[H][0] = 0;
1127               bb[H][1] = xr->width;
1128               bb[V][0] = 0;
1129               bb[V][1] = ts->caption_height;
1130               xr_draw_cell (xr, &cell, bb, bb);
1131             }
1132           xr->y += ts->caption_height;
1133           ts->caption_height = 0;
1134         }
1135
1136       if (xr->cairo)
1137         render_page_draw (y_slice);
1138       xr->y += render_page_get_size (y_slice, V);
1139       render_page_unref (y_slice);
1140     }
1141 }
1142
1143 static void
1144 xr_table_destroy (struct xr_render_fsm *fsm)
1145 {
1146   struct xr_table_state *ts = UP_CAST (fsm, struct xr_table_state, fsm);
1147
1148   table_item_unref (ts->table_item);
1149   render_break_destroy (&ts->x_break);
1150   render_break_destroy (&ts->y_break);
1151   free (ts);
1152 }
1153
1154 static struct xr_render_fsm *
1155 xr_render_table (struct xr_driver *xr, const struct table_item *table_item)
1156 {
1157   struct xr_table_state *ts;
1158   struct render_page *page;
1159
1160   ts = xmalloc (sizeof *ts);
1161   ts->fsm.render = xr_table_render;
1162   ts->fsm.destroy = xr_table_destroy;
1163   ts->table_item = table_item_ref (table_item);
1164
1165   if (xr->y > 0)
1166     xr->y += xr->font_height;
1167
1168   page = xr_render_table_item (xr, table_item, &ts->caption_height);
1169   xr->params->size[V] = xr->length - ts->caption_height;
1170
1171   render_break_init (&ts->x_break, page, H);
1172   render_break_init_empty (&ts->y_break);
1173
1174   return &ts->fsm;
1175 }
1176 \f
1177 struct xr_chart_state
1178   {
1179     struct xr_render_fsm fsm;
1180     struct chart_item *chart_item;
1181   };
1182
1183 static bool
1184 xr_chart_render (struct xr_render_fsm *fsm, struct xr_driver *xr)
1185 {
1186   struct xr_chart_state *cs = UP_CAST (fsm, struct xr_chart_state, fsm);
1187
1188   if (xr->y > 0)
1189     return true;
1190
1191   if (xr->cairo != NULL)
1192     xr_draw_chart (cs->chart_item, xr->cairo, 0.0, 0.0,
1193                    xr_to_pt (xr->width), xr_to_pt (xr->length));
1194   xr->y = xr->length;
1195
1196   return false;
1197 }
1198
1199 static void
1200 xr_chart_destroy (struct xr_render_fsm *fsm)
1201 {
1202   struct xr_chart_state *cs = UP_CAST (fsm, struct xr_chart_state, fsm);
1203
1204   chart_item_unref (cs->chart_item);
1205   free (cs);
1206 }
1207
1208 static struct xr_render_fsm *
1209 xr_render_chart (const struct chart_item *chart_item)
1210 {
1211   struct xr_chart_state *cs;
1212
1213   cs = xmalloc (sizeof *cs);
1214   cs->fsm.render = xr_chart_render;
1215   cs->fsm.destroy = xr_chart_destroy;
1216   cs->chart_item = chart_item_ref (chart_item);
1217
1218   return &cs->fsm;
1219 }
1220 \f
1221 static bool
1222 xr_eject_render (struct xr_render_fsm *fsm UNUSED, struct xr_driver *xr)
1223 {
1224   return xr->y > 0;
1225 }
1226
1227 static void
1228 xr_eject_destroy (struct xr_render_fsm *fsm UNUSED)
1229 {
1230   /* Nothing to do. */
1231 }
1232
1233 static struct xr_render_fsm *
1234 xr_render_eject (void)
1235 {
1236   static struct xr_render_fsm eject_renderer =
1237     {
1238       xr_eject_render,
1239       xr_eject_destroy
1240     };
1241
1242   return &eject_renderer;
1243 }
1244 \f
1245 static struct xr_render_fsm *
1246 xr_create_text_renderer (struct xr_driver *xr, const char *text)
1247 {
1248   struct table_item *table_item;
1249   struct xr_render_fsm *fsm;
1250
1251   table_item = table_item_create (table_from_string (TAB_LEFT, text), NULL);
1252   fsm = xr_render_table (xr, table_item);
1253   table_item_unref (table_item);
1254
1255   return fsm;
1256 }
1257
1258 static struct xr_render_fsm *
1259 xr_render_text (struct xr_driver *xr, const struct text_item *text_item)
1260 {
1261   enum text_item_type type = text_item_get_type (text_item);
1262   const char *text = text_item_get_text (text_item);
1263
1264   switch (type)
1265     {
1266     case TEXT_ITEM_TITLE:
1267       free (xr->title);
1268       xr->title = xstrdup (text);
1269       draw_headers (xr);
1270       break;
1271
1272     case TEXT_ITEM_SUBTITLE:
1273       free (xr->subtitle);
1274       xr->subtitle = xstrdup (text);
1275       draw_headers (xr);
1276       break;
1277
1278     case TEXT_ITEM_COMMAND_CLOSE:
1279       break;
1280
1281     case TEXT_ITEM_BLANK_LINE:
1282       if (xr->y > 0)
1283         xr->y += xr->font_height;
1284       break;
1285
1286     case TEXT_ITEM_EJECT_PAGE:
1287       if (xr->y > 0)
1288         return xr_render_eject ();
1289       break;
1290
1291     default:
1292       return xr_create_text_renderer (xr, text);
1293     }
1294
1295   return NULL;
1296 }
1297
1298 static struct xr_render_fsm *
1299 xr_render_message (struct xr_driver *xr,
1300                    const struct message_item *message_item)
1301 {
1302   const struct msg *msg = message_item_get_msg (message_item);
1303   struct xr_render_fsm *fsm;
1304   char *s;
1305
1306   s = msg_to_string (msg, xr->command_name);
1307   fsm = xr_create_text_renderer (xr, s);
1308   free (s);
1309
1310   return fsm;
1311 }
1312
1313 static struct xr_render_fsm *
1314 xr_render_output_item (struct xr_driver *xr,
1315                        const struct output_item *output_item)
1316 {
1317   if (is_table_item (output_item))
1318     return xr_render_table (xr, to_table_item (output_item));
1319   else if (is_chart_item (output_item))
1320     return xr_render_chart (to_chart_item (output_item));
1321   else if (is_text_item (output_item))
1322     return xr_render_text (xr, to_text_item (output_item));
1323   else if (is_message_item (output_item))
1324     return xr_render_message (xr, to_message_item (output_item));
1325   else
1326     return NULL;
1327 }