output-item: Collapse the inheritance hierarchy into a single struct.
[pspp] / src / output / cairo.c
index 23a93287c6496b722336131aa277ead6eb369108..e5ac93bcf0635a63d5c0d094fd39dbc62f647cc1 100644 (file)
@@ -1,5 +1,5 @@
 /* PSPP - a program for statistical analysis.
-   Copyright (C) 2009 Free Software Foundation, Inc.
+   Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Free Software Foundation, Inc.
 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
 
 #include <config.h>
 
-#include <libpspp/assertion.h>
-#include <libpspp/start-date.h>
-#include <libpspp/version.h>
-#include <output/afm.h>
-#include <output/chart.h>
-#include <output/manager.h>
-#include <output/output.h>
+#include "libpspp/assertion.h"
+#include "libpspp/cast.h"
+#include "libpspp/message.h"
+#include "libpspp/str.h"
+#include "libpspp/string-map.h"
+#include "data/file-handle-def.h"
+#include "output/cairo-fsm.h"
+#include "output/cairo-pager.h"
+#include "output/driver-provider.h"
+#include "output/options.h"
+#include "output/output-item.h"
+#include "output/table.h"
 
 #include <cairo/cairo-pdf.h>
 #include <cairo/cairo-ps.h>
 #include <cairo/cairo-svg.h>
+
 #include <cairo/cairo.h>
+#include <inttypes.h>
+#include <math.h>
 #include <pango/pango-font.h>
-#include <pango/pango-layout.h>
-#include <pango/pango.h>
-#include <pango/pangocairo.h>
 #include <stdlib.h>
 
-#include "error.h"
-#include "intprops.h"
-#include "minmax.h"
-#include "xalloc.h"
+#include "gl/c-strcase.h"
+#include "gl/xalloc.h"
 
 #include "gettext.h"
 #define _(msgid) gettext (msgid)
 
-/* Cairo driver options: (defaults listed first)
-
-   output-file="pspp.pdf"
-   output-type=pdf|ps|png|svg
-   paper-size=letter (see "papersize" file)
-   orientation=portrait|landscape
-   headers=on|off
-
-   left-margin=0.5in
-   right-margin=0.5in
-   top-margin=0.5in
-   bottom-margin=0.5in
-
-   prop-font=Times-Roman
-   emph-font=Times-Italic
-   fixed-font=Courier
-   font-size=10000
-
-   line-gutter=1pt
-   line-spacing=1pt
-   line-width=0.5pt
- */
+/* This file uses TABLE_HORZ and TABLE_VERT enough to warrant abbreviating. */
+#define H TABLE_HORZ
+#define V TABLE_VERT
 
-/* Measurements.  We use the same scale as Pango, for simplicity. */
+/* The unit used for internal measurements is inch/(72 * XR_POINT).
+   (Thus, XR_POINT units represent one point.) */
 #define XR_POINT PANGO_SCALE
-#define XR_INCH (XR_POINT * 72)
+
+/* Conversions to and from points. */
+static double
+xr_to_pt (int x)
+{
+  return x / (double) XR_POINT;
+}
 
 /* Output types. */
 enum xr_output_type
   {
     XR_PDF,
     XR_PS,
-    XR_SVG
+    XR_SVG,
+    XR_PNG
   };
 
-/* A font for use with Cairo. */
-struct xr_font
+/* Cairo output driver. */
+struct xr_driver
   {
-    char *string;
-    PangoFontDescription *desc;
-    PangoLayout *layout;
-    PangoFontMetrics *metrics;
-  };
+    struct output_driver driver;
 
-/* Cairo output driver extension record. */
-struct xr_driver_ext
-  {
-    char *file_name;            /* Output file name. */
-    enum xr_output_type file_type; /* Type of output file. */
-    cairo_t *cairo;
-
-    bool draw_headers;          /* Draw headers at top of page? */
-    int page_number;           /* Current page number. */
-
-    bool portrait;              /* Portrait mode? */
-    int paper_width;            /* Width of paper before dropping margins. */
-    int paper_length;           /* Length of paper before dropping margins. */
-    int left_margin;           /* Left margin in XR units. */
-    int right_margin;          /* Right margin in XR units. */
-    int top_margin;            /* Top margin in XR units. */
-    int bottom_margin;         /* Bottom margin in XR units. */
-
-    int line_gutter;           /* Space around lines. */
-    int line_space;            /* Space between lines. */
-    int line_width;            /* Width of lines. */
-
-    struct xr_font fonts[OUTP_FONT_CNT];
-  };
+    enum xr_output_type output_type;
+    struct xr_fsm_style *fsm_style;
+    struct xr_page_style *page_style;
+    struct xr_pager *pager;
+    bool trim;
 
-static bool handle_option (struct outp_driver *this, const char *key,
-                           const struct string *val);
-static void draw_headers (struct outp_driver *this);
+    /* This is the surface where we're currently drawing.  It is always
+       nonnull.
 
-static bool load_font (struct outp_driver *this, struct xr_font *);
-static void free_font (struct xr_font *);
-\f
-/* Driver initialization. */
+       If 'trim' is true, this is a special Cairo "recording surface" that we
+       are using to save output temporarily just to find out the bounding box,
+       then later replay it into the destination surface.
 
-static bool
-xr_open_driver (struct outp_driver *this, struct substring options)
-{
-  cairo_surface_t *surface;
-  cairo_status_t status;
-  struct xr_driver_ext *x;
-  double width_pt, length_pt;
-  size_t i;
-
-  this->width = this->length = 0;
-  this->font_height = XR_POINT * 10;
-
-  this->ext = x = xmalloc (sizeof *x);
-  x->file_name = xstrdup ("pspp.pdf");
-  x->file_type = XR_PDF;
-  x->draw_headers = true;
-  x->page_number = 0;
-  x->portrait = true;
-  outp_get_paper_size ("", &x->paper_width, &x->paper_length);
-  x->left_margin = XR_INCH / 2;
-  x->right_margin = XR_INCH / 2;
-  x->top_margin = XR_INCH / 2;
-  x->bottom_margin = XR_INCH / 2;
-  x->line_gutter = XR_POINT;
-  x->line_space = XR_POINT;
-  x->line_width = XR_POINT / 2;
-  x->fonts[OUTP_FIXED].string = xstrdup ("monospace");
-  x->fonts[OUTP_PROPORTIONAL].string = xstrdup ("serif");
-  x->fonts[OUTP_EMPHASIS].string = xstrdup ("serif italic");
-  for (i = 0; i < OUTP_FONT_CNT; i++)
-    {
-      struct xr_font *font = &x->fonts[i];
-      font->desc = NULL;
-      font->metrics = NULL;
-      font->layout = NULL;
-    }
+       If 'trim' is false:
 
-  outp_parse_options (options, handle_option, this);
+         - For output to a PDF or PostScript file, it is the same pointer as
+           'dest_surface'.
 
-  if (x->portrait)
-    {
-      this->width = x->paper_width;
-      this->length = x->paper_length;
-    }
-  else
-    {
-      this->width = x->paper_length;
-      this->length = x->paper_width;
-    }
-  if (x->draw_headers)
-    x->top_margin += 3 * this->font_height;
-  this->width -= x->left_margin + x->right_margin;
-  this->length -= x->top_margin + x->bottom_margin;
-
-  width_pt = x->paper_width / (double) XR_POINT;
-  length_pt = x->paper_length / (double) XR_POINT;
-  if (x->file_type == XR_PDF)
-    surface = cairo_pdf_surface_create (x->file_name, width_pt, length_pt);
-  else if (x->file_type == XR_PS)
-    surface = cairo_ps_surface_create (x->file_name, width_pt, length_pt);
-  else if (x->file_type == XR_SVG)
-    surface = cairo_svg_surface_create (x->file_name, width_pt, length_pt);
-  else
-    NOT_REACHED ();
+         - For output to a PNG file, it is an image surface.
 
-  status = cairo_surface_status (surface);
-  if (status != CAIRO_STATUS_SUCCESS)
-    {
-      error (0, 0, _("opening output file \"%s\": %s"),
-             x->file_name, cairo_status_to_string (status));
-      cairo_surface_destroy (surface);
-      goto error;
-    }
+         - For output to an SVG file, it is a recording surface.
+    */
+    cairo_surface_t *drawing_surface;
 
-  x->cairo = cairo_create (surface);
-  cairo_surface_destroy (surface);
+    /* - For output to a PDF or PostScript file, this is the surface for the
+         PDF or PostScript file where the output is ultimately going.
 
-  cairo_scale (x->cairo, 1.0 / PANGO_SCALE, 1.0 / PANGO_SCALE);
-  cairo_translate (x->cairo, x->left_margin, x->top_margin);
-  cairo_set_line_width (x->cairo, x->line_width);
+       - For output to a PNG file, this is NULL, because Cairo has very
+         limited support for PNG.  Cairo can't open a PNG file for writing as
+         a surface, it can only save an existing surface to a PNG file.
 
-  for (i = 0; i < OUTP_FONT_CNT; i++)
-    if (!load_font (this, &x->fonts[i]))
-      goto error;
+       - For output to a SVG file, this is NULL, because Cairo does not
+         permit resizing the SVG page size after creating the file, whereas
+         this driver needs to do that sometimes.  Also, SVG is not multi-page
+         (according to https://wiki.inkscape.org/wiki/index.php/Multipage).
+    */
+    cairo_surface_t *dest_surface;
 
-  if (this->length / this->font_height < 15)
-    {
-      error (0, 0, _("The defined page is not long "
-                     "enough to hold margins and headers, plus least 15 "
-                     "lines of the default fonts.  In fact, there's only "
-                     "room for %d lines."),
-             this->length / this->font_height);
-      goto error;
-    }
+    /* Used only in file names, for PNG and SVG output where we can only write
+       one page per file. */
+    int page_number;
+  };
 
-  this->fixed_width = pango_font_metrics_get_approximate_char_width (
-    x->fonts[OUTP_FIXED].metrics);
-  this->prop_em_width = pango_font_metrics_get_approximate_char_width (
-      x->fonts[OUTP_PROPORTIONAL].metrics);
+static const struct output_driver_class cairo_driver_class;
 
-  this->horiz_line_width[OUTP_L_NONE] = 0;
-  this->horiz_line_width[OUTP_L_SINGLE] = 2 * x->line_gutter + x->line_width;
-  this->horiz_line_width[OUTP_L_DOUBLE] = (2 * x->line_gutter + x->line_space
-                                           + 2 * x->line_width);
-  memcpy (this->vert_line_width, this->horiz_line_width,
-          sizeof this->vert_line_width);
+\f
+/* Output driver basics. */
 
-  return true;
+static struct xr_driver *
+xr_driver_cast (struct output_driver *driver)
+{
+  assert (driver->class == &cairo_driver_class);
+  return UP_CAST (driver, struct xr_driver, driver);
+}
 
- error:
-  this->class->close_driver (this);
-  return false;
+static struct driver_option *
+opt (struct output_driver *d, struct string_map *options, const char *key,
+     const char *default_value)
+{
+  return driver_option_get (d, options, key, default_value);
 }
 
-static bool
-xr_close_driver (struct outp_driver *this)
+static PangoFontDescription *
+parse_font (const char *font, int default_size, bool bold, bool italic)
 {
-  struct xr_driver_ext *x = this->ext;
-  bool ok = true;
-  size_t i;
+  if (!c_strcasecmp (font, "Monospaced"))
+    font = "Monospace";
+
+  PangoFontDescription *desc = pango_font_description_from_string (font);
+  if (desc == NULL)
+    return NULL;
+
+  /* If the font description didn't include an explicit font size, then set it
+     to DEFAULT_SIZE, which is in inch/72000 units. */
+  if (!(pango_font_description_get_set_fields (desc) & PANGO_FONT_MASK_SIZE))
+    pango_font_description_set_size (desc,
+                                     (default_size / 1000.0) * PANGO_SCALE);
+
+  pango_font_description_set_weight (desc, (bold
+                                            ? PANGO_WEIGHT_BOLD
+                                            : PANGO_WEIGHT_NORMAL));
+  pango_font_description_set_style (desc, (italic
+                                           ? PANGO_STYLE_ITALIC
+                                           : PANGO_STYLE_NORMAL));
+
+  return desc;
+}
 
-  if (x->cairo != NULL)
+static PangoFontDescription *
+parse_font_option (struct output_driver *d, struct string_map *options,
+                   const char *key, const char *default_value,
+                   int default_size, bool bold, bool italic)
+{
+  char *string = parse_string (opt (d, options, key, default_value));
+  PangoFontDescription *desc = parse_font (string, default_size, bold, italic);
+  if (!desc)
     {
-      cairo_status_t status;
+      msg (MW, _("`%s': bad font specification"), string);
 
-      cairo_surface_finish (cairo_get_target (x->cairo));
-      status = cairo_status (x->cairo);
-      if (status != CAIRO_STATUS_SUCCESS)
-        error (0, 0, _("writing output file \"%s\": %s"),
-               x->file_name, cairo_status_to_string (status));
-      cairo_destroy (x->cairo);
+      /* Fall back to DEFAULT_VALUE, which had better be a valid font
+         description. */
+      desc = parse_font (default_value, default_size, bold, italic);
+      assert (desc != NULL);
     }
+  free (string);
 
-  free (x->file_name);
-  for (i = 0; i < OUTP_FONT_CNT; i++)
-    free_font (&x->fonts[i]);
-  free (x);
-
-  return ok;
+  return desc;
 }
 
-/* Generic option types. */
-enum
+static struct xr_driver *
+xr_allocate (const char *name, int device_type,
+             enum xr_output_type output_type, struct string_map *o)
 {
-  output_file_arg,
-  output_type_arg,
-  paper_size_arg,
-  orientation_arg,
-  line_style_arg,
-  boolean_arg,
-  dimension_arg,
-  string_arg,
-  nonneg_int_arg
-};
+  struct xr_driver *xr = xzalloc (sizeof *xr);
+  struct output_driver *d = &xr->driver;
+
+  output_driver_init (d, &cairo_driver_class, name, device_type);
+  xr->output_type = output_type;
+
+  /* Scale factor from inch/72000 to inch/(72 * XR_POINT). */
+  const double scale = XR_POINT / 1000.;
+
+  int paper[TABLE_N_AXES];
+  parse_paper_size (opt (d, o, "paper-size", ""), &paper[H], &paper[V]);
+  for (int a = 0; a < TABLE_N_AXES; a++)
+    paper[a] *= scale;
+
+  int margins[TABLE_N_AXES][2];
+  margins[H][0] = parse_dimension (opt (d, o, "left-margin", ".5in")) * scale;
+  margins[H][1] = parse_dimension (opt (d, o, "right-margin", ".5in")) * scale;
+  margins[V][0] = parse_dimension (opt (d, o, "top-margin", ".5in")) * scale;
+  margins[V][1] = parse_dimension (opt (d, o, "bottom-margin", ".5in")) * scale;
+
+  int size[TABLE_N_AXES];
+  for (int a = 0; a < TABLE_N_AXES; a++)
+    size[a] = paper[a] - margins[a][0] - margins[a][1];
+
+  int min_break[TABLE_N_AXES];
+  min_break[H] = parse_dimension (opt (d, o, "min-hbreak", NULL)) * scale;
+  min_break[V] = parse_dimension (opt (d, o, "min-vbreak", NULL)) * scale;
+  for (int a = 0; a < TABLE_N_AXES; a++)
+    if (min_break[a] <= 0)
+      min_break[a] = size[a] / 2;
+
+  int font_size = parse_int (opt (d, o, "font-size", "10000"), 1000, 1000000);
+  PangoFontDescription *font = parse_font_option (
+    d, o, "prop-font", "Sans Serif", font_size, false, false);
+
+  struct cell_color fg = parse_color (opt (d, o, "foreground-color", "black"));
+
+  bool systemcolors = parse_boolean (opt (d, o, "systemcolors", "false"));
+
+  int object_spacing
+    = parse_dimension (opt (d, o, "object-spacing", NULL)) * scale;
+  if (object_spacing <= 0)
+    object_spacing = XR_POINT * 12;
+
+  const char *default_resolution = (output_type == XR_PNG ? "96" : "72");
+  int font_resolution = parse_int (opt (d, o, "font-resolution",
+                                        default_resolution), 10, 1000);
+
+  xr->trim = parse_boolean (opt (d, o, "trim", "false"));
+
+  /* Cairo 1.16.0 has a bug that causes crashes if outlines are enabled at the
+     same time as trimming:
+     https://lists.cairographics.org/archives/cairo/2020-December/029151.html
+     For now, just disable the outline if trimming is enabled. */
+  bool include_outline
+    = (output_type == XR_PDF
+       && parse_boolean (opt (d, o, "outline", xr->trim ? "false" : "true")));
+
+  xr->page_style = xmalloc (sizeof *xr->page_style);
+  *xr->page_style = (struct xr_page_style) {
+    .ref_cnt = 1,
+
+    .margins = {
+      [H] = { margins[H][0], margins[H][1], },
+      [V] = { margins[V][0], margins[V][1], },
+    },
+
+    .initial_page_number = 1,
+    .include_outline = include_outline,
+  };
 
-/* All the options that the Cairo driver supports. */
-static const struct outp_option option_tab[] =
-{
-  {"output-file",              output_file_arg,0},
-  {"output-type",               output_type_arg,0},
-  {"paper-size",               paper_size_arg, 0},
-  {"orientation",              orientation_arg,0},
-
-  {"headers",                  boolean_arg,    1},
-
-  {"prop-font",                string_arg,     OUTP_PROPORTIONAL},
-  {"emph-font",                string_arg,     OUTP_EMPHASIS},
-  {"fixed-font",               string_arg,     OUTP_FIXED},
-
-  {"left-margin",              dimension_arg,  0},
-  {"right-margin",             dimension_arg,  1},
-  {"top-margin",               dimension_arg,  2},
-  {"bottom-margin",            dimension_arg,  3},
-  {"font-size",                        dimension_arg,  4},
-  {"line-width",               dimension_arg,  5},
-  {"line-gutter",              dimension_arg,  6},
-  {"line-width",               dimension_arg,  7},
-  {NULL, 0, 0},
-};
+  xr->fsm_style = xmalloc (sizeof *xr->fsm_style);
+  *xr->fsm_style = (struct xr_fsm_style) {
+    .ref_cnt = 1,
+    .size = { [H] = size[H], [V] = size[V] },
+    .min_break = { [H] = min_break[H], [V] = min_break[V] },
+    .font = font,
+    .fg = fg,
+    .use_system_colors = systemcolors,
+    .object_spacing = object_spacing,
+    .font_resolution = font_resolution,
+  };
 
-static bool
-handle_option (struct outp_driver *this, const char *key,
-               const struct string *val)
-{
-  struct xr_driver_ext *x = this->ext;
-  int subcat;
-  char *value = ds_cstr (val);
+  return xr;
+}
 
-  switch (outp_match_keyword (key, option_tab, &subcat))
+static struct output_driver *
+xr_create (struct file_handle *fh, enum settings_output_devices device_type,
+           struct string_map *o, enum xr_output_type output_type)
+{
+  const char *file_name = fh_get_file_name (fh);
+  struct xr_driver *xr = xr_allocate (file_name, device_type, output_type, o);
+
+  double paper[TABLE_N_AXES];
+  for (int a = 0; a < TABLE_N_AXES; a++)
+    paper[a] = xr_to_pt (xr_page_style_paper_size (xr->page_style,
+                                                   xr->fsm_style, a));
+
+  xr->dest_surface
+    = (output_type == XR_PDF
+       ? cairo_pdf_surface_create (file_name, paper[H], paper[V])
+       : output_type == XR_PS
+       ? cairo_ps_surface_create (file_name, paper[H], paper[V])
+       : NULL);
+  if (xr->dest_surface)
     {
-    case -1:
-      error (0, 0,
-             _("unknown configuration parameter `%s' for Cairo device "
-               "driver"), key);
-      break;
-    case output_file_arg:
-      free (x->file_name);
-      x->file_name = xstrdup (value);
-      break;
-    case output_type_arg:
-      if (!strcmp (value, "pdf"))
-        x->file_type = XR_PDF;
-      else if (!strcmp (value, "ps"))
-        x->file_type = XR_PS;
-      else if (!strcmp (value, "svg"))
-        x->file_type = XR_SVG;
-      else
-        {
-          error (0, 0, _("unknown Cairo output type \"%s\""), value);
-          return false;
-        }
-      break;
-    case paper_size_arg:
-      outp_get_paper_size (value, &x->paper_width, &x->paper_length);
-      break;
-    case orientation_arg:
-      if (!strcmp (value, "portrait"))
-       x->portrait = true;
-      else if (!strcmp (value, "landscape"))
-       x->portrait = false;
-      else
-       error (0, 0, _("unknown orientation `%s' (valid orientations are "
-                       "`portrait' and `landscape')"), value);
-      break;
-    case boolean_arg:
-      if (!strcmp (value, "on") || !strcmp (value, "true")
-          || !strcmp (value, "yes") || atoi (value))
-        x->draw_headers = true;
-      else if (!strcmp (value, "off") || !strcmp (value, "false")
-               || !strcmp (value, "no") || !strcmp (value, "0"))
-        x->draw_headers = false;
-      else
+      cairo_status_t status = cairo_surface_status (xr->dest_surface);
+      if (status != CAIRO_STATUS_SUCCESS)
         {
-          error (0, 0, _("boolean value expected for %s"), key);
-          return false;
+          msg (ME, _("error opening output file `%s': %s"),
+               file_name, cairo_status_to_string (status));
+          goto error;
         }
-      break;
-    case dimension_arg:
-      {
-       int dimension = outp_evaluate_dimension (value);
-
-       if (dimension <= 0)
-          break;
-       switch (subcat)
-         {
-         case 0:
-           x->left_margin = dimension;
-           break;
-         case 1:
-           x->right_margin = dimension;
-           break;
-         case 2:
-           x->top_margin = dimension;
-           break;
-         case 3:
-           x->bottom_margin = dimension;
-           break;
-         case 4:
-           this->font_height = dimension;
-           break;
-         case 5:
-           x->line_width = dimension;
-           break;
-         case 6:
-           x->line_gutter = dimension;
-           break;
-         case 7:
-           x->line_width = dimension;
-           break;
-         default:
-           NOT_REACHED ();
-         }
-      }
-      break;
-    case string_arg:
-      free (x->fonts[subcat].string);
-      x->fonts[subcat].string = ds_xstrdup (val);
-      break;
-    default:
-      NOT_REACHED ();
     }
 
-  return true;
+  xr->drawing_surface
+    = (xr->trim || output_type == XR_SVG
+       ? cairo_recording_surface_create (CAIRO_CONTENT_COLOR_ALPHA,
+                                         &(cairo_rectangle_t) {
+                                           .width = paper[H],
+                                           .height = paper[V] })
+       : output_type == XR_PNG
+       ? cairo_image_surface_create (CAIRO_FORMAT_ARGB32, paper[H], paper[V])
+       : xr->dest_surface);
+
+  fh_unref (fh);
+  return &xr->driver;
+
+ error:
+  fh_unref (fh);
+  output_driver_destroy (&xr->driver);
+  return NULL;
 }
-\f
-/* Basic file operations. */
 
-static void
-xr_open_page (struct outp_driver *this)
+static struct output_driver *
+xr_pdf_create (struct  file_handle *fh, enum settings_output_devices device_type,
+               struct string_map *o)
 {
-  struct xr_driver_ext *x = this->ext;
+  return xr_create (fh, device_type, o, XR_PDF);
+}
 
-  x->page_number++;
+static struct output_driver *
+xr_ps_create (struct  file_handle *fh, enum settings_output_devices device_type,
+               struct string_map *o)
+{
+  return xr_create (fh, device_type, o, XR_PS);
+}
 
-  if (x->draw_headers)
-    draw_headers (this);
+static struct output_driver *
+xr_svg_create (struct file_handle *fh, enum settings_output_devices device_type,
+               struct string_map *o)
+{
+  return xr_create (fh, device_type, o, XR_SVG);
 }
 
-static void
-xr_close_page (struct outp_driver *this)
+static struct output_driver *
+xr_png_create (struct file_handle *fh, enum settings_output_devices device_type,
+               struct string_map *o)
 {
-  struct xr_driver_ext *x = this->ext;
-  cairo_show_page (x->cairo);
+  return xr_create (fh, device_type, o, XR_PNG);
 }
 
 static void
-xr_submit (struct outp_driver *this UNUSED, struct som_entity *s)
+xr_set_surface_size (cairo_surface_t *surface, enum xr_output_type output_type,
+                     double width, double height)
 {
-  switch (s->type)
+  switch (output_type)
     {
-    case SOM_CHART:
+    case XR_PDF:
+      cairo_pdf_surface_set_size (surface, width, height);
+      break;
+
+    case XR_PS:
+      cairo_ps_surface_set_size (surface, width, height);
       break;
-    default:
+
+    case XR_SVG:
+    case XR_PNG:
       NOT_REACHED ();
     }
 }
-\f
-/* Draws a line from (x0,y0) to (x1,y1). */
+
 static void
-dump_line (struct outp_driver *this, int x0, int y0, int x1, int y1)
+xr_copy_surface (cairo_surface_t *dst, cairo_surface_t *src,
+                 double x, double y)
 {
-  struct xr_driver_ext *x = this->ext;
-  cairo_new_path (x->cairo);
-  cairo_move_to (x->cairo, x0, y0);
-  cairo_line_to (x->cairo, x1, y1);
-  cairo_stroke (x->cairo);
+  cairo_t *cr = cairo_create (dst);
+  cairo_set_source_surface (cr, src, x, y);
+  cairo_paint (cr);
+  cairo_destroy (cr);
 }
 
-/* Draws a horizontal line X0...X2 at Y if LEFT says so,
-   shortening it to X0...X1 if SHORTEN is true.
-   Draws a horizontal line X1...X3 at Y if RIGHT says so,
-   shortening it to X2...X3 if SHORTEN is true. */
 static void
-horz_line (struct outp_driver *this,
-           int x0, int x1, int x2, int x3, int y,
-           enum outp_line_style left, enum outp_line_style right,
-           bool shorten)
+clear_rectangle (cairo_surface_t *surface,
+                 double x0, double y0, double x1, double y1)
 {
-  if (left != OUTP_L_NONE && right != OUTP_L_NONE && !shorten)
-    dump_line (this, x0, y, x3, y);
-  else
-    {
-      if (left != OUTP_L_NONE)
-        dump_line (this, x0, y, shorten ? x1 : x2, y);
-      if (right != OUTP_L_NONE)
-        dump_line (this, shorten ? x2 : x1, y, x3, y);
-    }
+  cairo_t *cr = cairo_create (surface);
+  cairo_set_source_rgb (cr, 1, 1, 1);
+  cairo_new_path (cr);
+  cairo_rectangle (cr, x0, y0, x1 - x0, y1 - y0);
+  cairo_fill (cr);
+  cairo_destroy (cr);
 }
 
-/* Draws a vertical line Y0...Y2 at X if TOP says so,
-   shortening it to Y0...Y1 if SHORTEN is true.
-   Draws a vertical line Y1...Y3 at X if BOTTOM says so,
-   shortening it to Y2...Y3 if SHORTEN is true. */
 static void
-vert_line (struct outp_driver *this,
-           int y0, int y1, int y2, int y3, int x,
-           enum outp_line_style top, enum outp_line_style bottom,
-           bool shorten)
+xr_report_error (cairo_status_t status, const char *file_name)
 {
-  if (top != OUTP_L_NONE && bottom != OUTP_L_NONE && !shorten)
-    dump_line (this, x, y0, x, y3);
-  else
-    {
-      if (top != OUTP_L_NONE)
-        dump_line (this, x, y0, x, shorten ? y1 : y2);
-      if (bottom != OUTP_L_NONE)
-        dump_line (this, x, shorten ? y2 : y1, x, y3);
-    }
+  if (status != CAIRO_STATUS_SUCCESS)
+    fprintf (stderr,  "%s: %s\n", file_name, cairo_status_to_string (status));
 }
 
-/* Draws a generalized intersection of lines in the rectangle
-   (X0,Y0)-(X3,Y3).  The line coming from the top to the center
-   is of style TOP, from left to center of style LEFT, from
-   bottom to center of style BOTTOM, and from right to center of
-   style RIGHT. */
 static void
-xr_line (struct outp_driver *this,
-         int x0, int y0, int x3, int y3,
-         enum outp_line_style top, enum outp_line_style left,
-         enum outp_line_style bottom, enum outp_line_style right)
+xr_finish_page (struct xr_driver *xr)
 {
-  /* The algorithm here is somewhat subtle, to allow it to handle
-     all the kinds of intersections that we need.
-
-     Three additional ordinates are assigned along the x axis.  The
-     first is xc, midway between x0 and x3.  The others are x1 and
-     x2; for a single vertical line these are equal to xc, and for
-     a double vertical line they are the ordinates of the left and
-     right half of the double line.
-
-     yc, y1, and y2 are assigned similarly along the y axis.
-
-     The following diagram shows the coordinate system and output
-     for double top and bottom lines, single left line, and no
-     right line:
-
-                 x0       x1 xc  x2      x3
-               y0 ________________________
-                  |        #     #       |
-                  |        #     #       |
-                  |        #     #       |
-                  |        #     #       |
-                  |        #     #       |
-     y1 = y2 = yc |#########     #       |
-                  |        #     #       |
-                  |        #     #       |
-                  |        #     #       |
-                  |        #     #       |
-               y3 |________#_____#_______|
-  */
-  struct xr_driver_ext *ext = this->ext;
-
-  /* Offset from center of each line in a pair of double lines. */
-  int double_line_ofs = (ext->line_space + ext->line_width) / 2;
-
-  /* Are the lines along each axis single or double?
-     (It doesn't make sense to have different kinds of line on the
-     same axis, so we don't try to gracefully handle that case.) */
-  bool double_vert = top == OUTP_L_DOUBLE || bottom == OUTP_L_DOUBLE;
-  bool double_horz = left == OUTP_L_DOUBLE || right == OUTP_L_DOUBLE;
-
-  /* When horizontal lines are doubled,
-     the left-side line along y1 normally runs from x0 to x2,
-     and the right-side line along y1 from x3 to x1.
-     If the top-side line is also doubled, we shorten the y1 lines,
-     so that the left-side line runs only to x1,
-     and the right-side line only to x2.
-     Otherwise, the horizontal line at y = y1 below would cut off
-     the intersection, which looks ugly:
-               x0       x1     x2      x3
-             y0 ________________________
-                |        #     #       |
-                |        #     #       |
-                |        #     #       |
-                |        #     #       |
-             y1 |#########     ########|
-                |                      |
-                |                      |
-             y2 |######################|
-                |                      |
-                |                      |
-             y3 |______________________|
-     It is more of a judgment call when the horizontal line is
-     single.  We actually choose to cut off the line anyhow, as
-     shown in the first diagram above.
-  */
-  bool shorten_y1_lines = top == OUTP_L_DOUBLE;
-  bool shorten_y2_lines = bottom == OUTP_L_DOUBLE;
-  bool shorten_yc_line = shorten_y1_lines && shorten_y2_lines;
-  int horz_line_ofs = double_vert ? double_line_ofs : 0;
-  int xc = (x0 + x3) / 2;
-  int x1 = xc - horz_line_ofs;
-  int x2 = xc + horz_line_ofs;
-
-  bool shorten_x1_lines = left == OUTP_L_DOUBLE;
-  bool shorten_x2_lines = right == OUTP_L_DOUBLE;
-  bool shorten_xc_line = shorten_x1_lines && shorten_x2_lines;
-  int vert_line_ofs = double_horz ? double_line_ofs : 0;
-  int yc = (y0 + y3) / 2;
-  int y1 = yc - vert_line_ofs;
-  int y2 = yc + vert_line_ofs;
-
-  if (!double_horz)
-    horz_line (this, x0, x1, x2, x3, yc, left, right, shorten_yc_line);
-  else
-    {
-      horz_line (this, x0, x1, x2, x3, y1, left, right, shorten_y1_lines);
-      horz_line (this, x0, x1, x2, x3, y2, left, right, shorten_y2_lines);
-    }
+  xr_pager_finish_page (xr->pager);
 
-  if (!double_vert)
-    vert_line (this, y0, y1, y2, y3, xc, top, bottom, shorten_xc_line);
-  else
-    {
-      vert_line (this, y0, y1, y2, y3, x1, top, bottom, shorten_x1_lines);
-      vert_line (this, y0, y1, y2, y3, x2, top, bottom, shorten_x2_lines);
-    }
-}
+  /* For 'trim' true:
 
-/* Writes STRING at location (X,Y) trimmed to the given MAX_WIDTH
-   and with the given JUSTIFICATION for THIS driver. */
-static int
-draw_text (struct outp_driver *this,
-           const char *string, int x, int y, int max_width,
-           enum outp_justification justification)
-{
-  struct outp_text text;
-  int width;
-
-  text.font = OUTP_PROPORTIONAL;
-  text.justification = justification;
-  text.string = ss_cstr (string);
-  text.h = max_width;
-  text.v = this->font_height;
-  text.x = x;
-  text.y = y;
-  this->class->text_metrics (this, &text, &width, NULL);
-  this->class->text_draw (this, &text);
-  return width;
-}
+    - If the destination is PDF or PostScript, set the dest surface size, copy
+      ink extent, show_page.
 
-/* Writes LEFT left-justified and RIGHT right-justified within
-   (X0...X1) at Y.  LEFT or RIGHT or both may be null. */
-static void
-draw_header_line (struct outp_driver *this,
-                  const char *left, const char *right,
-                  int x0, int x1, int y)
-{
-  int right_width = 0;
-  if (right != NULL)
-    right_width = (draw_text (this, right, x0, y, x1 - x0, OUTP_RIGHT)
-                   + this->prop_em_width);
-  if (left != NULL)
-    draw_text (this, left, x0, y, x1 - x0 - right_width, OUTP_LEFT);
-}
+    - If the destination is PNG, create image surface, copy ink extent,
+      cairo_surface_write_to_png(), destroy image surface.
 
-/* Draw top of page headers for THIS driver. */
-static void
-draw_headers (struct outp_driver *this)
-{
-  struct xr_driver_ext *ext = this->ext;
-  char *r1, *r2;
-  int x0, x1;
-  int y;
+    - If the destination is SVG, create svg surface, copy ink extent, close.
 
-  y = -3 * this->font_height;
-  x0 = this->prop_em_width;
-  x1 = this->width - this->prop_em_width;
+    then destroy drawing_surface and make a new one.
 
-  /* Draw box. */
-  cairo_rectangle (ext->cairo, 0, y, this->width,
-                   2 * (this->font_height
-                        + ext->line_width + ext->line_gutter));
-  cairo_save (ext->cairo);
-  cairo_set_source_rgb (ext->cairo, 0.9, 0.9, 0.9);
-  cairo_fill_preserve (ext->cairo);
-  cairo_restore (ext->cairo);
-  cairo_stroke (ext->cairo);
+    For 'trim' false:
 
-  y += ext->line_width + ext->line_gutter;
+    - If the destination is PDF or PostScript, show_page.
 
-  r1 = xasprintf (_("%s - Page %d"), get_start_date (), ext->page_number);
-  r2 = xasprintf ("%s - %s", version, host_system);
+    - If the destination is PNG, cairo_surface_write_to_png(), destroy image
+      surface, create new image surface.
 
-  draw_header_line (this, outp_title, r1, x0, x1, y);
-  y += this->font_height;
+    - If the destination is SVG, create svg surface, copy whole thing, close.
 
-  draw_header_line (this, outp_subtitle, r2, x0, x1, y);
+    */
+  double paper[TABLE_N_AXES];
+  for (int a = 0; a < TABLE_N_AXES; a++)
+    paper[a] = xr_to_pt (xr_page_style_paper_size (
+                           xr->page_style, xr->fsm_style, a));
 
-  free (r1);
-  free (r2);
-}
-\f
-/* Format TEXT on THIS driver.
-   If DRAW is nonzero, draw the text.
-   The width of the widest line is stored into *WIDTH, if WIDTH
-   is nonnull.
-   The total height of the text written is stored into *HEIGHT,
-   if HEIGHT is nonnull. */
-static void
-text (struct outp_driver *this, const struct outp_text *text, bool draw,
-      int *width, int *height)
-{
-  struct xr_driver_ext *ext = this->ext;
-  struct xr_font *font = &ext->fonts[text->font];
-
-  pango_layout_set_text (font->layout,
-                         text->string.string, text->string.length);
-  pango_layout_set_alignment (
-    font->layout,
-    (text->justification == OUTP_RIGHT ? PANGO_ALIGN_RIGHT
-     : text->justification == OUTP_LEFT ? PANGO_ALIGN_LEFT
-     : PANGO_ALIGN_CENTER));
-  pango_layout_set_width (font->layout, text->h == INT_MAX ? -1 : text->h);
-  pango_layout_set_wrap (font->layout, PANGO_WRAP_WORD_CHAR);
-  /* XXX need to limit number of lines to those that fit in text->v. */
-
-  if (draw)
+  xr->page_number++;
+  char *file_name = (xr->page_number > 1
+                     ? xasprintf ("%s-%d", xr->driver.name, xr->page_number)
+                     : xr->driver.name);
+
+  if (xr->trim)
     {
-      int x = text->x;
-      if (text->justification != OUTP_LEFT && text->h != INT_MAX)
+      /* Get the bounding box for the drawing surface. */
+      double ofs[TABLE_N_AXES], size[TABLE_N_AXES];
+      cairo_recording_surface_ink_extents (xr->drawing_surface,
+                                           &ofs[H], &ofs[V],
+                                           &size[H], &size[V]);
+      const int (*margins)[2] = xr->page_style->margins;
+      for (int a = 0; a < TABLE_N_AXES; a++)
         {
-          int w, h, excess;
-          pango_layout_get_size (font->layout, &w, &h);
-          excess = text->h - w;
-          if (excess > 0)
-            {
-              if (text->justification == OUTP_CENTER)
-                x += excess / 2;
-              else
-                x += excess;
-            }
+          double scale = XR_POINT;
+          size[a] += (margins[a][0] + margins[a][1]) / scale;
+          ofs[a] = -ofs[a] + margins[a][0] / scale;
         }
-      cairo_save (ext->cairo);
-      cairo_translate (ext->cairo, text->x, text->y);
-      cairo_scale (ext->cairo, PANGO_SCALE, PANGO_SCALE);
-      pango_cairo_show_layout (ext->cairo, font->layout);
-      cairo_restore (ext->cairo);
-      pango_cairo_update_layout (ext->cairo, font->layout);
-    }
 
-  if (width != NULL || height != NULL)
+      switch (xr->output_type)
+        {
+        case XR_PDF:
+        case XR_PS:
+          xr_set_surface_size (xr->dest_surface, xr->output_type,
+                               size[H], size[V]);
+          xr_copy_surface (xr->dest_surface, xr->drawing_surface,
+                           ofs[H], ofs[V]);
+          cairo_surface_show_page (xr->dest_surface);
+          break;
+
+        case XR_SVG:
+          {
+            cairo_surface_t *svg = cairo_svg_surface_create (
+              file_name, size[H], size[V]);
+            xr_copy_surface (svg, xr->drawing_surface, ofs[H], ofs[V]);
+            xr_report_error (cairo_surface_status (svg), file_name);
+            cairo_surface_destroy (svg);
+          }
+          break;
+
+        case XR_PNG:
+          {
+            cairo_surface_t *png = cairo_image_surface_create (
+              CAIRO_FORMAT_ARGB32, size[H], size[V]);
+            clear_rectangle (png, 0, 0, size[H], size[V]);
+            xr_copy_surface (png, xr->drawing_surface, ofs[H], ofs[V]);
+            xr_report_error (cairo_surface_write_to_png (png, file_name),
+                             file_name);
+            cairo_surface_destroy (png);
+          }
+          break;
+        }
+
+      /* Destroy the recording surface and create a fresh one of the same
+         size. */
+      cairo_surface_destroy (xr->drawing_surface);
+      xr->drawing_surface = cairo_recording_surface_create (
+        CAIRO_CONTENT_COLOR_ALPHA,
+        &(cairo_rectangle_t) { .width = paper[H], .height = paper[V] });
+    }
+  else
     {
-      int w, h;
-      pango_layout_get_size (font->layout, &w, &h);
-      if (width != NULL)
-        *width = w;
-      if (height != NULL)
-        *height = h;
+      switch (xr->output_type)
+        {
+        case XR_PDF:
+        case XR_PS:
+          cairo_surface_show_page (xr->dest_surface);
+          break;
+
+        case XR_SVG:
+          {
+            cairo_surface_t *svg = cairo_svg_surface_create (
+              file_name, paper[H], paper[V]);
+            xr_copy_surface (svg, xr->drawing_surface, 0.0, 0.0);
+            xr_report_error (cairo_surface_status (svg), file_name);
+            cairo_surface_destroy (svg);
+          }
+          break;
+
+        case XR_PNG:
+          xr_report_error (cairo_surface_write_to_png (xr->drawing_surface,
+                                                       file_name), file_name);
+          cairo_surface_destroy (xr->drawing_surface);
+          xr->drawing_surface = cairo_image_surface_create (
+            CAIRO_FORMAT_ARGB32, paper[H], paper[V]);
+          break;
+        }
     }
-}
 
-static void
-xr_text_metrics (struct outp_driver *this, const struct outp_text *t,
-                 int *width, int *height)
-{
-  text (this, t, false, width, height);
+  if (file_name != xr->driver.name)
+    free (file_name);
 }
 
 static void
-xr_text_draw (struct outp_driver *this, const struct outp_text *t)
-{
-  assert (this->page_open);
-  text (this, t, true, NULL, NULL);
-}
-\f
-static void
-xr_chart_initialise (struct outp_driver *this UNUSED, struct chart *ch UNUSED)
+xr_destroy (struct output_driver *driver)
 {
-#ifdef NO_CHARTS
-  ch->lp = NULL;
-#else
-  /* XXX libplot doesn't support Cairo yet. */
-#endif
-}
+  struct xr_driver *xr = xr_driver_cast (driver);
 
-static void
-xr_chart_finalise (struct outp_driver *this UNUSED, struct chart *ch UNUSED)
-{
-#ifndef NO_CHARTS
-  /* XXX libplot doesn't support Cairo yet. */
-#endif
-}
-\f
-/* Attempts to load FONT, initializing its other members based on
-   its 'string' member and the information in THIS.  Returns true
-   if successful, otherwise false. */
-static bool
-load_font (struct outp_driver *this, struct xr_font *font)
-{
-  struct xr_driver_ext *x = this->ext;
-  PangoContext *context;
-  PangoLanguage *language;
+  if (xr->pager)
+    xr_finish_page (xr);
+
+  xr_pager_destroy (xr->pager);
 
-  font->desc = pango_font_description_from_string (font->string);
-  if (font->desc == NULL)
+  if (xr->drawing_surface && xr->drawing_surface != xr->dest_surface)
+    cairo_surface_destroy (xr->drawing_surface);
+  if (xr->dest_surface)
     {
-      error (0, 0, _("\"%s\": bad font specification"), font->string);
-      return false;
+      cairo_surface_finish (xr->dest_surface);
+      cairo_status_t status = cairo_surface_status (xr->dest_surface);
+      if (status != CAIRO_STATUS_SUCCESS)
+        fprintf (stderr,  _("error drawing output for %s driver: %s\n"),
+                 output_driver_get_name (driver),
+                 cairo_status_to_string (status));
+      cairo_surface_destroy (xr->dest_surface);
     }
-  pango_font_description_set_size (font->desc, this->font_height * 5 / 6);
-
-  font->layout = pango_cairo_create_layout (x->cairo);
-  pango_layout_set_font_description (font->layout, font->desc);
-  pango_layout_set_spacing (font->layout, this->font_height / 6);
-
-  language = pango_language_get_default ();
-  context = pango_layout_get_context (font->layout);
-  font->metrics = pango_context_get_metrics (context, font->desc, language);
 
-  return true;
+  xr_page_style_unref (xr->page_style);
+  xr_fsm_style_unref (xr->fsm_style);
+  free (xr);
 }
 
-/* Frees FONT. */
 static void
-free_font (struct xr_font *font)
+xr_update_page_setup (struct output_driver *driver,
+                      const struct page_setup *setup)
 {
-  free (font->string);
-  if (font->desc != NULL)
-    pango_font_description_free (font->desc);
-  pango_font_metrics_unref (font->metrics);
-  g_object_unref (font->layout);
+  struct xr_driver *xr = xr_driver_cast (driver);
+
+  const double scale = 72 * XR_POINT;
+
+  int swap = setup->orientation == PAGE_LANDSCAPE;
+  enum table_axis h = H ^ swap;
+  enum table_axis v = V ^ swap;
+
+  struct xr_page_style *old_ps = xr->page_style;
+  xr->page_style = xmalloc (sizeof *xr->page_style);
+  *xr->page_style = (struct xr_page_style) {
+    .ref_cnt = 1,
+
+    .margins = {
+      [H] = { setup->margins[h][0] * scale, setup->margins[h][1] * scale },
+      [V] = { setup->margins[v][0] * scale, setup->margins[v][1] * scale },
+    },
+
+    .initial_page_number = setup->initial_page_number,
+    .include_outline = old_ps->include_outline,
+  };
+  for (size_t i = 0; i < 2; i++)
+    page_heading_copy (&xr->page_style->headings[i], &setup->headings[i]);
+  xr_page_style_unref (old_ps);
+
+  struct xr_fsm_style *old_fs = xr->fsm_style;
+  xr->fsm_style = xmalloc (sizeof *xr->fsm_style);
+  *xr->fsm_style = (struct xr_fsm_style) {
+    .ref_cnt = 1,
+    .size = { [H] = setup->paper[H] * scale, [V] = setup->paper[V] * scale },
+    .min_break = {
+      [H] = setup->paper[H] * scale / 2,
+      [V] = setup->paper[V] * scale / 2,
+    },
+    .font = pango_font_description_copy (old_fs->font),
+    .fg = old_fs->fg,
+    .use_system_colors = old_fs->use_system_colors,
+    .object_spacing = setup->object_spacing * 72 * XR_POINT,
+    .font_resolution = old_fs->font_resolution,
+  };
+  xr_fsm_style_unref (old_fs);
+
+  xr_set_surface_size (xr->dest_surface, xr->output_type,
+                       setup->paper[H] * 72.0, setup->paper[V] * 72.0);
 }
 
-/* Cairo driver class. */
-const struct outp_class cairo_class =
+static void
+xr_submit (struct output_driver *driver, const struct output_item *item)
 {
-  "cairo",
-  0,
+  struct xr_driver *xr = xr_driver_cast (driver);
 
-  xr_open_driver,
-  xr_close_driver,
+  if (item->type == OUTPUT_ITEM_PAGE_SETUP)
+    {
+      if (!xr->pager)
+        xr_update_page_setup (driver, item->page_setup);
+      return;
+    }
 
-  xr_open_page,
-  xr_close_page,
-  NULL,
+  if (!xr->pager)
+    {
+      xr->pager = xr_pager_create (xr->page_style, xr->fsm_style);
+      xr_pager_add_page (xr->pager, cairo_create (xr->drawing_surface));
+    }
 
+  xr_pager_add_item (xr->pager, item);
+  while (xr_pager_needs_new_page (xr->pager))
+    {
+      xr_finish_page (xr);
+      xr_pager_add_page (xr->pager, cairo_create (xr->drawing_surface));
+    }
+}
+\f
+struct output_driver_factory pdf_driver_factory =
+  { "pdf", "pspp.pdf", xr_pdf_create };
+struct output_driver_factory ps_driver_factory =
+  { "ps", "pspp.ps", xr_ps_create };
+struct output_driver_factory svg_driver_factory =
+  { "svg", "pspp.svg", xr_svg_create };
+struct output_driver_factory png_driver_factory =
+  { "png", "pspp.png", xr_png_create };
+
+static const struct output_driver_class cairo_driver_class =
+{
+  "cairo",
+  xr_destroy,
   xr_submit,
-
-  xr_line,
-  xr_text_metrics,
-  xr_text_draw,
-
-  xr_chart_initialise,
-  xr_chart_finalise
+  NULL,
 };