cairo: Get rid of unused PangoLayouts.
[pspp] / src / output / cairo.c
index 0a2190ebe5c9ad643fe2417a54429b357ee86cac..558f9e56a5771f30367d114bb9212a85d8edf83c 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 "output/cairo.h"
+
+#include "libpspp/assertion.h"
+#include "libpspp/cast.h"
+#include "libpspp/hash-functions.h"
+#include "libpspp/message.h"
+#include "libpspp/pool.h"
+#include "libpspp/start-date.h"
+#include "libpspp/str.h"
+#include "libpspp/string-map.h"
+#include "libpspp/version.h"
+#include "data/file-handle-def.h"
+#include "output/cairo-chart.h"
+#include "output/cairo-fsm.h"
+#include "output/chart-item-provider.h"
+#include "output/charts/boxplot.h"
+#include "output/charts/np-plot.h"
+#include "output/charts/piechart.h"
+#include "output/charts/barchart.h"
+#include "output/charts/plot-hist.h"
+#include "output/charts/roc-chart.h"
+#include "output/charts/spreadlevel-plot.h"
+#include "output/charts/scree.h"
+#include "output/charts/scatterplot.h"
+#include "output/driver-provider.h"
+#include "output/group-item.h"
+#include "output/message-item.h"
+#include "output/options.h"
+#include "output/page-eject-item.h"
+#include "output/page-setup-item.h"
+#include "output/render.h"
+#include "output/table-item.h"
+#include "output/table.h"
+#include "output/text-item.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-ctype.h"
+#include "gl/c-strcase.h"
+#include "gl/intprops.h"
+#include "gl/minmax.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
+/* This file uses TABLE_HORZ and TABLE_VERT enough to warrant abbreviating. */
+#define H TABLE_HORZ
+#define V TABLE_VERT
 
-   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
+/* The unit used for internal measurements is inch/(72 * XR_POINT).
+   (Thus, XR_POINT units represent one point.) */
+#define XR_POINT PANGO_SCALE
 
-   line-gutter=1pt
-   line-spacing=1pt
-   line-width=0.5pt
- */
+/* Conversions to and from points. */
+static double
+xr_to_pt (int x)
+{
+  return x / (double) XR_POINT;
+}
 
-/* Measurements.  We use the same scale as Pango, for simplicity. */
-#define XR_POINT PANGO_SCALE
-#define XR_INCH (XR_POINT * 72)
+/* Dimensions for drawing lines in tables. */
+#define XR_LINE_WIDTH (XR_POINT / 2) /* Width of an ordinary line. */
+#define XR_LINE_SPACE XR_POINT       /* Space between double lines. */
 
 /* Output types. */
 enum xr_output_type
@@ -77,753 +100,774 @@ enum xr_output_type
     XR_SVG
   };
 
-/* 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;
+    /* User parameters. */
+    PangoFontDescription *fonts[XR_N_FONTS];
 
-    bool draw_headers;          /* Draw headers at top of page? */
-    int page_number;           /* Current page number. */
+    int width;                  /* Page width minus margins. */
+    int length;                 /* Page length minus margins and header. */
+
+    int left_margin;            /* Left margin in inch/(72 * XR_POINT). */
+    int right_margin;           /* Right margin in inch/(72 * XR_POINT). */
+    int top_margin;             /* Top margin in inch/(72 * XR_POINT). */
+    int bottom_margin;          /* Bottom margin in inch/(72 * XR_POINT). */
+
+    int min_break[TABLE_N_AXES]; /* Min cell size to break across pages. */
+    int object_spacing;         /* Space between output objects. */
 
-    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. */
+    struct cell_color bg;       /* Background color */
+    struct cell_color fg;       /* Foreground color */
+    bool transparent;           /* true -> do not render background */
+    bool systemcolors;          /* true -> do not change colors     */
 
-    int line_gutter;           /* Space around lines. */
-    int line_space;            /* Space between lines. */
-    int line_width;            /* Width of lines. */
+    int initial_page_number;
 
-    struct xr_font fonts[OUTP_FONT_CNT];
+    struct page_heading headings[2]; /* Top and bottom headings. */
+    int headings_height[2];
+
+    /* Internal state. */
+    struct xr_fsm_style *style;
+    double font_scale;
+    int char_width, char_height;
+    cairo_t *cairo;
+    cairo_surface_t *surface;
+    int page_number;           /* Current page number. */
+    int y;
+    struct xr_fsm *fsm;
   };
 
-static bool handle_option (struct outp_driver *this, const char *key,
-                           const struct string *val);
-static void draw_headers (struct outp_driver *this);
+static const struct output_driver_class cairo_driver_class;
 
-static bool load_font (struct outp_driver *this, struct xr_font *);
-static void free_font (struct xr_font *);
+static void xr_driver_destroy_fsm (struct xr_driver *);
+static void xr_driver_run_fsm (struct xr_driver *);
 \f
-/* Driver initialization. */
+/* Output driver basics. */
 
-static bool
-xr_open_driver (struct outp_driver *this, struct substring options)
+static struct xr_driver *
+xr_driver_cast (struct output_driver *driver)
 {
-  cairo_surface_t *surface;
-  cairo_status_t status;
-  struct xr_driver_ext *x;
-  double width_pt, length_pt;
-  size_t i;
+  assert (driver->class == &cairo_driver_class);
+  return UP_CAST (driver, struct xr_driver, driver);
+}
 
-  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;
-    }
+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);
+}
 
-  outp_parse_options (options, handle_option, this);
+static PangoFontDescription *
+parse_font (const char *font, int default_size, bool bold, bool italic)
+{
+  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->portrait)
-    {
-      this->width = x->paper_width;
-      this->length = x->paper_length;
-    }
-  else
+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)
     {
-      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 ();
+      msg (MW, _("`%s': bad font specification"), string);
 
-  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;
+      /* 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);
 
-  x->cairo = cairo_create (surface);
-  cairo_surface_destroy (surface);
+  return desc;
+}
 
-  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);
+static void
+apply_options (struct xr_driver *xr, struct string_map *o)
+{
+  struct output_driver *d = &xr->driver;
+
+  /* In inch/72000 units used by parse_paper_size() and parse_dimension(). */
+  int left_margin, right_margin;
+  int top_margin, bottom_margin;
+  int paper_width, paper_length;
+  int font_size;
+  int min_break[TABLE_N_AXES];
+
+  /* Scale factor from inch/72000 to inch/(72 * XR_POINT). */
+  const double scale = XR_POINT / 1000.;
+
+  int i;
+
+  for (i = 0; i < XR_N_FONTS; i++)
+    if (xr->fonts[i] != NULL)
+      pango_font_description_free (xr->fonts[i]);
+
+  font_size = parse_int (opt (d, o, "font-size", "10000"), 1000, 1000000);
+  xr->fonts[XR_FONT_FIXED] = parse_font_option
+    (d, o, "fixed-font", "monospace", font_size, false, false);
+  xr->fonts[XR_FONT_PROPORTIONAL] = parse_font_option (
+    d, o, "prop-font", "sans serif", font_size, false, false);
+
+  xr->fg = parse_color (opt (d, o, "foreground-color", "#000000000000"));
+  xr->bg = parse_color (opt (d, o, "background-color", "#FFFFFFFFFFFF"));
+
+  xr->transparent = parse_boolean (opt (d, o, "transparent", "false"));
+  xr->systemcolors = parse_boolean (opt (d, o, "systemcolors", "false"));
+
+  /* Get dimensions.  */
+  parse_paper_size (opt (d, o, "paper-size", ""), &paper_width, &paper_length);
+  left_margin = parse_dimension (opt (d, o, "left-margin", ".5in"));
+  right_margin = parse_dimension (opt (d, o, "right-margin", ".5in"));
+  top_margin = parse_dimension (opt (d, o, "top-margin", ".5in"));
+  bottom_margin = parse_dimension (opt (d, o, "bottom-margin", ".5in"));
+
+  min_break[H] = parse_dimension (opt (d, o, "min-hbreak", NULL)) * scale;
+  min_break[V] = parse_dimension (opt (d, o, "min-vbreak", NULL)) * scale;
+
+  int object_spacing = (parse_dimension (opt (d, o, "object-spacing", NULL))
+                        * scale);
+
+  /* Convert to inch/(XR_POINT * 72). */
+  xr->left_margin = left_margin * scale;
+  xr->right_margin = right_margin * scale;
+  xr->top_margin = top_margin * scale;
+  xr->bottom_margin = bottom_margin * scale;
+  xr->width = (paper_width - left_margin - right_margin) * scale;
+  xr->length = (paper_length - top_margin - bottom_margin) * scale;
+  xr->min_break[H] = min_break[H] >= 0 ? min_break[H] : xr->width / 2;
+  xr->min_break[V] = min_break[V] >= 0 ? min_break[V] : xr->length / 2;
+  xr->object_spacing = object_spacing >= 0 ? object_spacing : XR_POINT * 12;
+
+  /* There are no headings so headings_height can stay 0. */
+}
 
-  for (i = 0; i < OUTP_FONT_CNT; i++)
-    if (!load_font (this, &x->fonts[i]))
-      goto error;
+static struct xr_driver *
+xr_allocate (const char *name, int device_type, struct string_map *o,
+             double font_scale)
+{
+  struct xr_driver *xr = xzalloc (sizeof *xr);
+  struct output_driver *d = &xr->driver;
 
-  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;
-    }
+  output_driver_init (d, &cairo_driver_class, name, device_type);
 
-  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);
+  /* This is a nasty kluge for an issue that does not make sense.  On any
+     surface other than a screen (e.g. for output to PDF or PS or SVG), the
+     fonts are way too big by default.  A "9-point" font seems to appear about
+     16 points tall.  We use a scale factor for these surfaces to help, but the
+     underlying issue is a mystery. */
+  xr->font_scale = font_scale;
 
-  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);
+  apply_options (xr, o);
 
-  return true;
+  return xr;
+}
 
- error:
-  this->class->close_driver (this);
-  return false;
+static int
+pango_to_xr (int pango)
+{
+  return (XR_POINT != PANGO_SCALE
+          ? ceil (pango * (1. * XR_POINT / PANGO_SCALE))
+          : pango);
 }
 
-static bool
-xr_close_driver (struct outp_driver *this)
+static int
+xr_to_pango (int xr)
 {
-  struct xr_driver_ext *x = this->ext;
-  bool ok = true;
-  size_t i;
+  return (XR_POINT != PANGO_SCALE
+          ? ceil (xr * (1. / XR_POINT * PANGO_SCALE))
+          : xr);
+}
 
-  if (x->cairo != NULL)
+static void
+xr_measure_fonts (cairo_t *cairo, PangoFontDescription *fonts[XR_N_FONTS],
+                  int *char_width, int *char_height)
+{
+  *char_width = 0;
+  *char_height = 0;
+  for (int i = 0; i < XR_N_FONTS; i++)
     {
-      cairo_status_t status;
+      PangoLayout *layout = pango_cairo_create_layout (cairo);
+      pango_layout_set_font_description (layout, fonts[i]);
 
-      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);
-    }
+      pango_layout_set_text (layout, "0", 1);
 
-  free (x->file_name);
-  for (i = 0; i < OUTP_FONT_CNT; i++)
-    free_font (&x->fonts[i]);
-  free (x);
+      int cw, ch;
+      pango_layout_get_size (layout, &cw, &ch);
+      *char_width = MAX (*char_width, pango_to_xr (cw));
+      *char_height = MAX (*char_height, pango_to_xr (ch));
 
-  return ok;
+      g_object_unref (G_OBJECT (layout));
+    }
 }
 
-/* Generic option types. */
-enum
+static int
+get_layout_height (PangoLayout *layout)
 {
-  output_file_arg,
-  output_type_arg,
-  paper_size_arg,
-  orientation_arg,
-  line_style_arg,
-  boolean_arg,
-  dimension_arg,
-  string_arg,
-  nonneg_int_arg
-};
-
-/* 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},
-};
+  int w, h;
+  pango_layout_get_size (layout, &w, &h);
+  return h;
+}
 
-static bool
-handle_option (struct outp_driver *this, const char *key,
-               const struct string *val)
+static int
+xr_render_page_heading (cairo_t *cairo, const PangoFontDescription *font,
+                        const struct page_heading *ph, int page_number,
+                        int width, bool draw, int base_y)
 {
-  struct xr_driver_ext *x = this->ext;
-  int subcat;
-  char *value = ds_cstr (val);
+  PangoLayout *layout = pango_cairo_create_layout (cairo);
+  pango_layout_set_font_description (layout, font);
 
-  switch (outp_match_keyword (key, option_tab, &subcat))
+  int y = 0;
+  for (size_t i = 0; i < ph->n; i++)
     {
-    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
+      const struct page_paragraph *pp = &ph->paragraphs[i];
+
+      char *markup = output_driver_substitute_heading_vars (pp->markup,
+                                                            page_number);
+      pango_layout_set_markup (layout, markup, -1);
+      free (markup);
+
+      pango_layout_set_alignment (
+        layout,
+        (pp->halign == TABLE_HALIGN_LEFT ? PANGO_ALIGN_LEFT
+         : pp->halign == TABLE_HALIGN_CENTER ? PANGO_ALIGN_CENTER
+         : pp->halign == TABLE_HALIGN_MIXED ? PANGO_ALIGN_LEFT
+         : PANGO_ALIGN_RIGHT));
+      pango_layout_set_width (layout, xr_to_pango (width));
+      if (draw)
         {
-          error (0, 0, _("boolean value expected for %s"), key);
-          return false;
+          cairo_save (cairo);
+          cairo_translate (cairo, 0, xr_to_pt (y + base_y));
+          pango_cairo_show_layout (cairo, layout);
+          cairo_restore (cairo);
         }
-      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 ();
+
+      y += pango_to_xr (get_layout_height (layout));
     }
 
-  return true;
+  g_object_unref (G_OBJECT (layout));
+
+  return y;
 }
-\f
-/* Basic file operations. */
 
-static void
-xr_open_page (struct outp_driver *this)
+static int
+xr_measure_headings (cairo_surface_t *surface,
+                     const PangoFontDescription *font,
+                     const struct page_heading headings[2],
+                     int width, int object_spacing, int height[2])
 {
-  struct xr_driver_ext *x = this->ext;
+  cairo_t *cairo = cairo_create (surface);
+  int total = 0;
+  for (int i = 0; i < 2; i++)
+    {
+      int h = xr_render_page_heading (cairo, font, &headings[i], -1,
+                                      width, false, 0);
 
-  x->page_number++;
+      /* If the top heading is nonempty, add some space below it. */
+      if (h && i == 0)
+        h += object_spacing;
 
-  if (x->draw_headers)
-    draw_headers (this);
+      if (height)
+        height[i] = h;
+      total += h;
+    }
+  cairo_destroy (cairo);
+  return total;
 }
 
-static void
-xr_close_page (struct outp_driver *this)
+static bool
+xr_check_fonts (cairo_surface_t *surface,
+                PangoFontDescription *fonts[XR_N_FONTS],
+                int usable_width, int usable_length)
 {
-  struct xr_driver_ext *x = this->ext;
-  cairo_show_page (x->cairo);
-}
+  cairo_t *cairo = cairo_create (surface);
+  int char_width, char_height;
+  xr_measure_fonts (cairo, fonts, &char_width, &char_height);
+  cairo_destroy (cairo);
 
-static void
-xr_submit (struct outp_driver *this UNUSED, struct som_entity *s)
-{
-  switch (s->type)
+  bool ok = true;
+  enum { MIN_WIDTH = 3, MIN_LENGTH = 3 };
+  if (usable_width / char_width < MIN_WIDTH)
     {
-    case SOM_CHART:
-      break;
-    default:
-      NOT_REACHED ();
+      msg (ME, _("The defined page is not wide enough to hold at least %d "
+                 "characters in the default font.  In fact, there's only "
+                 "room for %d characters."),
+           MIN_WIDTH, usable_width / char_width);
+      ok = false;
     }
-}
-\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)
-{
-  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);
+  if (usable_length / char_height < MIN_LENGTH)
+    {
+      msg (ME, _("The defined page is not long enough to hold at least %d "
+                 "lines in the default font.  In fact, there's only "
+                 "room for %d lines."),
+           MIN_LENGTH, usable_length / char_height);
+      ok = false;
+    }
+  return ok;
 }
 
-/* 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)
+xr_set_cairo (struct xr_driver *xr, cairo_t *cairo)
 {
-  if (left != OUTP_L_NONE && right != OUTP_L_NONE && !shorten)
-    dump_line (this, x0, y, x3, y);
-  else
+  xr->cairo = cairo;
+
+  cairo_set_line_width (xr->cairo, xr_to_pt (XR_LINE_WIDTH));
+
+  xr_measure_fonts (xr->cairo, xr->fonts, &xr->char_width, &xr->char_height);
+
+  if (xr->style == NULL)
     {
-      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);
+      xr->style = xmalloc (sizeof *xr->style);
+      *xr->style = (struct xr_fsm_style) {
+        .ref_cnt = 1,
+        .size = { [H] = xr->width, [V] = xr->length },
+        .min_break = { [H] = xr->min_break[H], [V] = xr->min_break[V] },
+        .use_system_colors = xr->systemcolors,
+        .transparent = xr->transparent,
+        .font_scale = xr->font_scale,
+      };
+
+      for (size_t i = 0; i < XR_N_FONTS; i++)
+        xr->style->fonts[i] = pango_font_description_copy (xr->fonts[i]);
     }
+
+  if (!xr->systemcolors)
+    cairo_set_source_rgb (xr->cairo,
+                         xr->fg.r / 255.0, xr->fg.g / 255.0, xr->fg.b / 255.0);
 }
 
-/* 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)
+static struct output_driver *
+xr_create (struct file_handle *fh, enum settings_output_devices device_type,
+           struct string_map *o, enum xr_output_type file_type)
 {
-  if (top != OUTP_L_NONE && bottom != OUTP_L_NONE && !shorten)
-    dump_line (this, x, y0, x, y3);
+  const char *file_name = fh_get_file_name (fh);
+  struct xr_driver *xr = xr_allocate (file_name, device_type, o, 72.0 / 128.0);
+  double width_pt = xr_to_pt (xr->width + xr->left_margin + xr->right_margin);
+  double length_pt = xr_to_pt (xr->length + xr->top_margin + xr->bottom_margin);
+  if (file_type == XR_PDF)
+    xr->surface = cairo_pdf_surface_create (file_name, width_pt, length_pt);
+  else if (file_type == XR_PS)
+    xr->surface = cairo_ps_surface_create (file_name, width_pt, length_pt);
+  else if (file_type == XR_SVG)
+    xr->surface = cairo_svg_surface_create (file_name, width_pt, length_pt);
   else
+    NOT_REACHED ();
+
+  cairo_status_t status = cairo_surface_status (xr->surface);
+  if (status != CAIRO_STATUS_SUCCESS)
     {
-      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);
+      msg (ME, _("error opening output file `%s': %s"),
+           file_name, cairo_status_to_string (status));
+      goto error;
     }
+
+  if (!xr_check_fonts (xr->surface, xr->fonts, xr->width, xr->length))
+    goto error;
+
+  fh_unref (fh);
+  return &xr->driver;
+
+ error:
+  fh_unref (fh);
+  output_driver_destroy (&xr->driver);
+  return NULL;
+}
+
+static struct output_driver *
+xr_pdf_create (struct  file_handle *fh, enum settings_output_devices device_type,
+               struct string_map *o)
+{
+  return xr_create (fh, device_type, o, XR_PDF);
+}
+
+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);
+}
+
+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);
 }
 
-/* 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)
-{
-  /* 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_destroy (struct output_driver *driver)
+{
+  struct xr_driver *xr = xr_driver_cast (driver);
+  size_t i;
 
-  if (!double_vert)
-    vert_line (this, y0, y1, y2, y3, xc, top, bottom, shorten_xc_line);
-  else
+  xr_driver_destroy_fsm (xr);
+
+  if (xr->cairo != NULL)
     {
-      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);
+      cairo_surface_finish (xr->surface);
+      cairo_status_t status = cairo_status (xr->cairo);
+      if (status != CAIRO_STATUS_SUCCESS)
+        fprintf (stderr,  _("error drawing output for %s driver: %s"),
+                 output_driver_get_name (driver),
+                 cairo_status_to_string (status));
+      cairo_surface_destroy (xr->surface);
+
+      cairo_destroy (xr->cairo);
     }
+
+  for (i = 0; i < XR_N_FONTS; i++)
+    if (xr->fonts[i] != NULL)
+      pango_font_description_free (xr->fonts[i]);
+
+  xr_fsm_style_unref (xr->style);
+  free (xr);
 }
 
-/* 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;
-}
-
-/* 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)
+xr_flush (struct output_driver *driver)
 {
-  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);
+  struct xr_driver *xr = xr_driver_cast (driver);
+
+  cairo_surface_flush (cairo_get_target (xr->cairo));
 }
 
-/* Draw top of page headers for THIS driver. */
 static void
-draw_headers (struct outp_driver *this)
+xr_update_page_setup (struct output_driver *driver,
+                      const struct page_setup *ps)
 {
-  struct xr_driver_ext *ext = this->ext;
-  char *r1, *r2;
-  int x0, x1;
-  int y;
-
-  y = -3 * this->font_height;
-  x0 = this->prop_em_width;
-  x1 = this->width - this->prop_em_width;
+  struct xr_driver *xr = xr_driver_cast (driver);
 
-  /* Draw box. */
-  /* XXX coordinates below might not be right, both in terms of
-     the Y transformation and width/height versus x2/y2. */
-  cairo_rectangle (ext->cairo, 0, y,
-                   this->width, 2 * this->font_height + 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);
+  xr->initial_page_number = ps->initial_page_number;
+  xr->object_spacing = ps->object_spacing * 72 * XR_POINT;
 
-  y += ext->line_width + ext->line_gutter;
+  if (xr->cairo)
+    return;
 
-  r1 = xasprintf (_("%s - Page %d"), get_start_date (), ext->page_number);
-  r2 = xasprintf ("%s - %s", version, host_system);
+  int usable[TABLE_N_AXES];
+  for (int i = 0; i < 2; i++)
+    usable[i] = (ps->paper[i]
+                 - (ps->margins[i][0] + ps->margins[i][1])) * 72 * XR_POINT;
 
-  draw_header_line (this, outp_title, r1, x0, x1, y);
-  y += this->font_height;
+  int headings_height[2];
+  usable[V] -= xr_measure_headings (
+    xr->surface, xr->fonts[XR_FONT_PROPORTIONAL], ps->headings,
+    usable[H], xr->object_spacing, headings_height);
 
-  draw_header_line (this, outp_subtitle, r2, x0, x1, y);
+  enum table_axis h = ps->orientation == PAGE_LANDSCAPE;
+  enum table_axis v = !h;
+  if (!xr_check_fonts (xr->surface, xr->fonts, usable[h], usable[v]))
+    return;
 
-  free (r1);
-  free (r2);
+  for (int i = 0; i < 2; i++)
+    {
+      page_heading_uninit (&xr->headings[i]);
+      page_heading_copy (&xr->headings[i], &ps->headings[i]);
+      xr->headings_height[i] = headings_height[i];
+    }
+  xr->width = usable[h];
+  xr->length = usable[v];
+  xr->left_margin = ps->margins[h][0] * 72 * XR_POINT;
+  xr->right_margin = ps->margins[h][1] * 72 * XR_POINT;
+  xr->top_margin = ps->margins[v][0] * 72 * XR_POINT;
+  xr->bottom_margin = ps->margins[v][1] * 72 * XR_POINT;
+  cairo_pdf_surface_set_size (xr->surface,
+                              ps->paper[h] * 72.0, ps->paper[v] * 72.0);
 }
-\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_submit (struct output_driver *driver, const struct output_item *output_item)
+{
+  struct xr_driver *xr = xr_driver_cast (driver);
+
+  if (is_page_setup_item (output_item))
     {
-      int x = text->x;
-      if (text->justification != OUTP_LEFT && text->h != INT_MAX)
-        {
-          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;
-            }
-        }
-      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);
+      xr_update_page_setup (driver,
+                            to_page_setup_item (output_item)->page_setup);
+      return;
+    }
+
+  if (!xr->cairo)
+    {
+      xr->page_number = xr->initial_page_number - 1;
+      xr_set_cairo (xr, cairo_create (xr->surface));
+      cairo_save (xr->cairo);
+      xr_driver_next_page (xr, xr->cairo);
     }
 
-  if (width != NULL || height != NULL)
+  xr_driver_output_item (xr, output_item);
+  while (xr_driver_need_new_page (xr))
     {
-      int w, h;
-      pango_layout_get_size (font->layout, &w, &h);
-      if (width != NULL)
-        *width = w;
-      if (height != NULL)
-        *height = h;
+      cairo_restore (xr->cairo);
+      cairo_show_page (xr->cairo);
+      cairo_save (xr->cairo);
+      xr_driver_next_page (xr, xr->cairo);
     }
 }
+\f
+/* Functions for rendering a series of output items to a series of Cairo
+   contexts, with pagination.
 
-static void
-xr_text_metrics (struct outp_driver *this, const struct outp_text *t,
-                 int *width, int *height)
+   Used by PSPPIRE for printing, and by the basic Cairo output driver above as
+   its underlying implementation.
+
+   See the big comment in cairo.h for intended usage. */
+
+/* Gives new page CAIRO to XR for output. */
+void
+xr_driver_next_page (struct xr_driver *xr, cairo_t *cairo)
 {
-  text (this, t, false, width, height);
+  if (!xr->transparent)
+    {
+      cairo_save (cairo);
+      cairo_set_source_rgb (cairo,
+                           xr->bg.r / 255.0, xr->bg.g / 255.0, xr->bg.b / 255.0);
+      cairo_rectangle (cairo, 0, 0, xr->width, xr->length);
+      cairo_fill (cairo);
+      cairo_restore (cairo);
+    }
+  cairo_translate (cairo,
+                   xr_to_pt (xr->left_margin),
+                   xr_to_pt (xr->top_margin + xr->headings_height[0]));
+
+  xr->page_number++;
+  xr->cairo = cairo;
+  xr->y = 0;
+
+  xr_render_page_heading (xr->cairo, xr->fonts[XR_FONT_PROPORTIONAL],
+                          &xr->headings[0], xr->page_number, xr->width, true,
+                          -xr->headings_height[0]);
+  xr_render_page_heading (xr->cairo, xr->fonts[XR_FONT_PROPORTIONAL],
+                          &xr->headings[1], xr->page_number, xr->width, true,
+                          xr->length);
+
+  xr_driver_run_fsm (xr);
 }
 
-static void
-xr_text_draw (struct outp_driver *this, const struct outp_text *t)
+/* Start rendering OUTPUT_ITEM to XR.  Only valid if XR is not in the middle of
+   rendering a previous output item, that is, only if xr_driver_need_new_page()
+   returns false. */
+void
+xr_driver_output_item (struct xr_driver *xr,
+                       const struct output_item *output_item)
 {
-  assert (this->page_open);
-  text (this, t, true, NULL, NULL);
+  assert (xr->fsm == NULL);
+  xr->fsm = xr_fsm_create (output_item, xr->style, xr->cairo);
+  xr_driver_run_fsm (xr);
 }
-\f
+
+/* Returns true if XR is in the middle of rendering an output item and needs a
+   new page to be appended using xr_driver_next_page() to make progress,
+   otherwise false. */
+bool
+xr_driver_need_new_page (const struct xr_driver *xr)
+{
+  return xr->fsm != NULL;
+}
+
+/* Returns true if the current page doesn't have any content yet. */
+bool
+xr_driver_is_page_blank (const struct xr_driver *xr)
+{
+  return xr->y == 0;
+}
+
 static void
-xr_chart_initialise (struct outp_driver *this UNUSED, struct chart *ch UNUSED)
+xr_driver_destroy_fsm (struct xr_driver *xr)
 {
-#ifdef NO_CHARTS
-  ch->lp = NULL;
-#else
-  /* XXX libplot doesn't support Cairo yet. */
-#endif
+  xr_fsm_destroy (xr->fsm);
+  xr->fsm = NULL;
 }
 
 static void
-xr_chart_finalise (struct outp_driver *this UNUSED, struct chart *ch UNUSED)
+xr_driver_run_fsm (struct xr_driver *xr)
 {
-#ifndef NO_CHARTS
-  /* XXX libplot doesn't support Cairo yet. */
-#endif
+  if (xr->fsm != NULL)
+    {
+      cairo_save (xr->cairo);
+      cairo_translate (xr->cairo, 0, xr_to_pt (xr->y));
+      int used = xr_fsm_draw_slice (xr->fsm, xr->cairo, xr->length - xr->y);
+      xr->y += used;
+      cairo_restore (xr->cairo);
+
+      if (xr_fsm_is_empty (xr->fsm))
+        xr_driver_destroy_fsm (xr);
+    }
 }
 \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 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 };
+
+static const struct output_driver_class cairo_driver_class =
 {
-  struct xr_driver_ext *x = this->ext;
-  PangoContext *context;
-  PangoLanguage *language;
+  "cairo",
+  xr_destroy,
+  xr_submit,
+  xr_flush,
+};
+\f
+struct xr_driver *
+xr_driver_create (cairo_t *cairo, struct string_map *options)
+{
+  struct xr_driver *xr = xr_allocate ("cairo", 0, options, 1.0);
+  xr_set_cairo (xr, cairo);
+  return xr;
+}
 
-  font->desc = pango_font_description_from_string (font->string);
-  if (font->desc == NULL)
+/* Destroy XR, which should have been created with xr_driver_create().  Any
+   cairo_t added to XR is not destroyed, because it is owned by the client. */
+void
+xr_driver_destroy (struct xr_driver *xr)
+{
+  if (xr != NULL)
     {
-      error (0, 0, _("\"%s\": bad font specification"), font->string);
-      return false;
+      xr->cairo = NULL;
+      output_driver_destroy (&xr->driver);
     }
-  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);
+}
+static void
+xr_draw_chart (const struct chart_item *chart_item, cairo_t *cr,
+               double x, double y, double width, double height)
+{
+  struct xrchart_geometry geom;
+
+  cairo_save (cr);
+  cairo_translate (cr, x, y + height);
+  cairo_scale (cr, 1.0, -1.0);
+  xrchart_geometry_init (cr, &geom, width, height);
+  if (is_boxplot (chart_item))
+    xrchart_draw_boxplot (chart_item, cr, &geom);
+  else if (is_histogram_chart (chart_item))
+    xrchart_draw_histogram (chart_item, cr, &geom);
+  else if (is_np_plot_chart (chart_item))
+    xrchart_draw_np_plot (chart_item, cr, &geom);
+  else if (is_piechart (chart_item))
+    xrchart_draw_piechart (chart_item, cr, &geom);
+  else if (is_barchart (chart_item))
+    xrchart_draw_barchart (chart_item, cr, &geom);
+  else if (is_roc_chart (chart_item))
+    xrchart_draw_roc (chart_item, cr, &geom);
+  else if (is_scree (chart_item))
+    xrchart_draw_scree (chart_item, cr, &geom);
+  else if (is_spreadlevel_plot_chart (chart_item))
+    xrchart_draw_spreadlevel (chart_item, cr, &geom);
+  else if (is_scatterplot_chart (chart_item))
+    xrchart_draw_scatterplot (chart_item, cr, &geom);
+  else
+    NOT_REACHED ();
+  xrchart_geometry_free (cr, &geom);
 
-  return true;
+  cairo_restore (cr);
 }
 
-/* Frees FONT. */
-static void
-free_font (struct xr_font *font)
+char *
+xr_draw_png_chart (const struct chart_item *item,
+                   const char *file_name_template, int number,
+                  const struct cell_color *fg,
+                  const struct cell_color *bg)
 {
-  free (font->string);
-  if (font->desc != NULL)
-    pango_font_description_free (font->desc);
-  pango_font_metrics_unref (font->metrics);
-  g_object_unref (font->layout);
+  const int width = 640;
+  const int length = 480;
+
+  cairo_surface_t *surface;
+  cairo_status_t status;
+  const char *number_pos;
+  char *file_name;
+  cairo_t *cr;
+
+  number_pos = strchr (file_name_template, '#');
+  if (number_pos != NULL)
+    file_name = xasprintf ("%.*s%d%s.png", (int) (number_pos - file_name_template),
+                           file_name_template, number, number_pos + 1);
+  else
+    file_name = xasprintf ("%s.png", file_name_template);
+
+  surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, length);
+  cr = cairo_create (surface);
+
+  cairo_set_source_rgb (cr, bg->r / 255.0, bg->g / 255.0, bg->b / 255.0);
+  cairo_paint (cr);
+
+  cairo_set_source_rgb (cr, fg->r / 255.0, fg->g / 255.0, fg->b / 255.0);
+
+  xr_draw_chart (item, cr, 0.0, 0.0, width, length);
+
+  status = cairo_surface_write_to_png (surface, file_name);
+  if (status != CAIRO_STATUS_SUCCESS)
+    msg (ME, _("error writing output file `%s': %s"),
+           file_name, cairo_status_to_string (status));
+
+  cairo_destroy (cr);
+  cairo_surface_destroy (surface);
+
+  return file_name;
 }
 
-/* Cairo driver class. */
-const struct outp_class cairo_class =
+
+char *
+xr_draw_eps_chart (const struct chart_item *item,
+                   const char *file_name_template, int number,
+                  const struct cell_color *fg,
+                  const struct cell_color *bg)
 {
-  "cairo",
-  0,
+  const int width = 640;
+  const int length = 480;
 
-  xr_open_driver,
-  xr_close_driver,
+  cairo_surface_t *surface;
+  const char *number_pos;
+  char *file_name;
+  cairo_t *cr;
+
+  number_pos = strchr (file_name_template, '#');
+  if (number_pos != NULL)
+    file_name = xasprintf ("%.*s%d%s.eps", (int) (number_pos - file_name_template),
+                           file_name_template, number, number_pos + 1);
+  else
+    file_name = xasprintf ("%s.eps", file_name_template);
 
-  xr_open_page,
-  xr_close_page,
-  NULL,
+  surface = cairo_ps_surface_create (file_name, width, length);
+  cairo_ps_surface_set_eps (surface, true);
+  cr = cairo_create (surface);
 
-  xr_submit,
+  cairo_set_source_rgb (cr, bg->r / 255.0, bg->g / 255.0, bg->b / 255.0);
+  cairo_paint (cr);
 
-  xr_line,
-  xr_text_metrics,
-  xr_text_draw,
+  cairo_set_source_rgb (cr, fg->r / 255.0, fg->g / 255.0, fg->b / 255.0);
+
+  xr_draw_chart (item, cr, 0.0, 0.0, width, length);
+
+  cairo_destroy (cr);
+  cairo_surface_destroy (surface);
+
+  return file_name;
+}
 
-  xr_chart_initialise,
-  xr_chart_finalise
-};