str: Add function xstrdup_if_nonnull() and introduce many users.
[pspp] / src / output / pivot-table.c
index 9e45f244e061f6e162873e5c7a2f71e9ee304cf8..3698b78559037a955e949a2c56ce7201b03897da 100644 (file)
@@ -18,6 +18,9 @@
 
 #include "output/pivot-table.h"
 
+#include <libxml/parser.h>
+#include <libxml/tree.h>
+#include <math.h>
 #include <stdlib.h>
 
 #include "data/data-out.h"
@@ -45,8 +48,8 @@
 #define _(msgid) gettext (msgid)
 #define N_(msgid) msgid
 
-static const struct fmt_spec *pivot_table_get_format (
-  const struct pivot_table *, const char *s);
+static void pivot_table_use_rc (const struct pivot_table *, const char *s,
+                                struct fmt_spec *, bool *honor_small);
 \f
 /* Pivot table display styling. */
 
@@ -394,17 +397,19 @@ pivot_axis_iterator_next (size_t *indexes, const struct pivot_axis *axis)
 static void
 pivot_category_set_rc (struct pivot_category *category, const char *s)
 {
-  const struct fmt_spec *format = pivot_table_get_format (
-    category->dimension->table, s);
-  if (format)
-    category->format = *format;
+  if (!s)
+    return;
+
+  pivot_table_use_rc (category->dimension->table, s,
+                      &category->format, &category->honor_small);
 
   /* Ensure that the category itself, in addition to the cells within it, takes
      the format.  (It's kind of rare for a category to have a numeric format
      though.) */
   struct pivot_value *name = category->name;
   if (name->type == PIVOT_VALUE_NUMERIC && !name->numeric.format.w)
-    name->numeric.format = format ? *format : *settings_get_format ();
+    pivot_table_use_rc (category->dimension->table, s,
+                        &name->numeric.format, &name->numeric.honor_small);
 }
 
 static void
@@ -764,19 +769,35 @@ pivot_result_class_find (const char *s)
   return NULL;
 }
 
-static const struct fmt_spec *
-pivot_table_get_format (const struct pivot_table *table, const char *s)
+static void
+pivot_table_use_rc (const struct pivot_table *table, const char *s,
+                    struct fmt_spec *format, bool *honor_small)
 {
-  if (!s)
-    return NULL;
-  else if (!strcmp (s, PIVOT_RC_OTHER))
-    return settings_get_format ();
-  else if (!strcmp (s, PIVOT_RC_COUNT) && !overridden_count_format)
-    return &table->weight_format;
-  else
+  if (s)
     {
-      const struct result_class *rc = pivot_result_class_find (s);
-      return rc ? &rc->format : NULL;
+      if (!strcmp (s, PIVOT_RC_OTHER))
+        {
+          *format = *settings_get_format ();
+          *honor_small = true;
+        }
+      else if (!strcmp (s, PIVOT_RC_COUNT) && !overridden_count_format)
+        {
+          *format = table->weight_format;
+          *honor_small = false;
+        }
+      else
+        {
+          const struct result_class *rc = pivot_result_class_find (s);
+          if (rc)
+            {
+              *format = rc->format;
+              *honor_small = false;
+            }
+          else
+            {
+              printf ("unknown class %s\n", s);
+            }
+        }
     }
 }
 
@@ -853,6 +874,8 @@ pivot_table_create__ (struct pivot_value *title, const char *subtype)
   table->subtype = subtype ? pivot_value_new_text (subtype) : NULL;
   table->command_c = output_get_command_name ();
   table->look = pivot_table_look_ref (pivot_table_look_get_default ());
+  table->settings = fmt_settings_copy (settings_get_fmt_settings ());
+  table->small = settings_get_small ();
 
   hmap_init (&table->cells);
 
@@ -890,12 +913,6 @@ pivot_table_ref (const struct pivot_table *table_)
   return table;
 }
 
-static char *
-xstrdup_if_nonnull (const char *s)
-{
-  return s ? xstrdup (s) : NULL;
-}
-
 static struct pivot_table_sizing
 clone_sizing (const struct pivot_table_sizing *s)
 {
@@ -967,7 +984,10 @@ clone_category (struct pivot_category *old,
 
   if (pivot_category_is_leaf (old))
     {
+      assert (new->data_index < new_dimension->n_leaves);
       new->dimension->data_leaves[new->data_index] = new;
+
+      assert (new->presentation_index < new_dimension->n_leaves);
       new->dimension->presentation_leaves[new->presentation_index] = new;
     }
 
@@ -1047,16 +1067,8 @@ pivot_table_unshare (struct pivot_table *old)
       [TABLE_VERT] = clone_sizing (&old->sizing[TABLE_VERT]),
     },
 
-    .epoch = old->epoch,
-    .decimal = old->decimal,
+    .settings = fmt_settings_copy (&old->settings),
     .grouping = old->grouping,
-    .ccs = {
-      [0] = xstrdup_if_nonnull (old->ccs[0]),
-      [1] = xstrdup_if_nonnull (old->ccs[1]),
-      [2] = xstrdup_if_nonnull (old->ccs[2]),
-      [3] = xstrdup_if_nonnull (old->ccs[3]),
-      [4] = xstrdup_if_nonnull (old->ccs[4]),
-    },
     .small = old->small,
 
     .command_local = xstrdup_if_nonnull (old->command_local),
@@ -1134,8 +1146,7 @@ pivot_table_unref (struct pivot_table *table)
   for (int i = 0; i < TABLE_N_AXES; i++)
     pivot_table_sizing_uninit (&table->sizing[i]);
 
-  for (int i = 0; i < sizeof table->ccs / sizeof *table->ccs; i++)
-    free (table->ccs[i]);
+  fmt_settings_uninit (&table->settings);
 
   free (table->command_local);
   free (table->command_c);
@@ -1250,7 +1261,6 @@ pivot_table_move_dimension (struct pivot_table *table,
       return;
     }
 
-
   /* Update the current layer, if necessary.  If we're moving within the layer
      axis, preserve the current layer. */
   if (dim->axis_type == PIVOT_AXIS_LAYER)
@@ -1422,11 +1432,13 @@ pivot_table_put (struct pivot_table *table, const size_t *dindexes, size_t n,
               if (c->format.w)
                 {
                   value->numeric.format = c->format;
+                  value->numeric.honor_small = c->honor_small;
                   goto done;
                 }
             }
         }
       value->numeric.format = *settings_get_format ();
+      value->numeric.honor_small = true;
 
     done:;
     }
@@ -1489,15 +1501,30 @@ pivot_table_create_footnote (struct pivot_table *table,
                                         NULL, content);
 }
 
-static struct pivot_value *
-pivot_make_default_footnote_marker (int idx, bool show_numeric_markers)
-{
-  char text[INT_BUFSIZE_BOUND (size_t)];
-  if (show_numeric_markers)
-    snprintf (text, sizeof text, "%d", idx + 1);
+void
+pivot_footnote_format_marker (const struct pivot_footnote *f,
+                              const struct pivot_table *pt,
+                              struct string *s)
+{
+  if (f->marker)
+    pivot_value_format_body (f->marker, pt, s);
+  else if (pt->look->show_numeric_markers)
+    ds_put_format (s, "%zu", f->idx + 1);
   else
-    str_format_26adic (idx + 1, false, text, sizeof text);
-  return pivot_value_new_user_text (text, -1);
+    {
+      char text[INT_BUFSIZE_BOUND (size_t)];
+      str_format_26adic (f->idx + 1, false, text, sizeof text);
+      ds_put_cstr (s, text);
+    }
+}
+
+char *
+pivot_footnote_marker_string (const struct pivot_footnote *f,
+                              const struct pivot_table *pt)
+{
+  struct string s = DS_EMPTY_INITIALIZER;
+  pivot_footnote_format_marker (f, pt, &s);
+  return ds_steal_cstr (&s);
 }
 
 /* Creates or modifies a footnote in TABLE with 0-based number IDX (and creates
@@ -1517,12 +1544,10 @@ pivot_table_create_footnote__ (struct pivot_table *table, size_t idx,
       while (idx >= table->n_footnotes)
         {
           struct pivot_footnote *f = xmalloc (sizeof *f);
-          f->idx = table->n_footnotes;
-          f->marker = pivot_make_default_footnote_marker (
-            f->idx, table->look->show_numeric_markers);
-          f->content = NULL;
-          f->show = true;
-
+          *f = (struct pivot_footnote) {
+            .idx = table->n_footnotes,
+            .show = true,
+          };
           table->footnotes[table->n_footnotes++] = f;
         }
     }
@@ -1567,8 +1592,8 @@ pivot_table_convert_indexes_ptod (const struct pivot_table *table,
       for (size_t j = 0; j < axis->n_dimensions; j++)
         {
           const struct pivot_dimension *d = axis->dimensions[j];
-          dindexes[d->top_index]
-            = d->presentation_leaves[pindexes[i][j]]->data_index;
+          size_t pindex = pindexes[i][j];
+          dindexes[d->top_index] = d->presentation_leaves[pindex]->data_index;
         }
     }
 }
@@ -1782,22 +1807,23 @@ indent (int indentation)
 }
 
 static void
-pivot_value_dump (const struct pivot_value *value)
+pivot_value_dump (const struct pivot_value *value,
+                  const struct pivot_table *pt)
 {
-  char *s = pivot_value_to_string_defaults (value);
+  char *s = pivot_value_to_string (value, pt);
   fputs (s, stdout);
   free (s);
 }
 
 static void
 pivot_table_dump_value (const struct pivot_value *value, const char *name,
-                      int indentation)
+                        const struct pivot_table *pt, int indentation)
 {
   if (value)
     {
       indent (indentation);
       printf ("%s: ", name);
-      pivot_value_dump (value);
+      pivot_value_dump (value, pt);
       putchar ('\n');
     }
 }
@@ -1813,11 +1839,12 @@ pivot_table_dump_string (const char *string, const char *name, int indentation)
 }
 
 static void
-pivot_category_dump (const struct pivot_category *c, int indentation)
+pivot_category_dump (const struct pivot_category *c,
+                     const struct pivot_table *pt, int indentation)
 {
   indent (indentation);
   printf ("%s \"", pivot_category_is_leaf (c) ? "leaf" : "group");
-  pivot_value_dump (c->name);
+  pivot_value_dump (c->name, pt);
   printf ("\" ");
 
   if (pivot_category_is_leaf (c))
@@ -1828,18 +1855,19 @@ pivot_category_dump (const struct pivot_category *c, int indentation)
       printf ("\n");
 
       for (size_t i = 0; i < c->n_subs; i++)
-        pivot_category_dump (c->subs[i], indentation + 1);
+        pivot_category_dump (c->subs[i], pt, indentation + 1);
     }
 }
 
 void
-pivot_dimension_dump (const struct pivot_dimension *d, int indentation)
+pivot_dimension_dump (const struct pivot_dimension *d,
+                      const struct pivot_table *pt, int indentation)
 {
   indent (indentation);
   printf ("%s dimension %zu (where 0=innermost), label_depth=%d:\n",
           pivot_axis_type_to_string (d->axis_type), d->level, d->label_depth);
 
-  pivot_category_dump (d->root, indentation + 1);
+  pivot_category_dump (d->root, pt, indentation + 1);
 }
 
 static void
@@ -1964,12 +1992,8 @@ pivot_table_dump (const struct pivot_table *table, int indentation)
 
   pivot_table_assign_label_depth (CONST_CAST (struct pivot_table *, table));
 
-  int old_decimal = settings_get_decimal_char (FMT_COMMA);
-  if (table->decimal == '.' || table->decimal == ',')
-    settings_set_decimal_char (table->decimal);
-
-  pivot_table_dump_value (table->title, "title", indentation);
-  pivot_table_dump_value (table->subtype, "subtype", indentation);
+  pivot_table_dump_value (table->title, "title", table, indentation);
+  pivot_table_dump_value (table->subtype, "subtype", table, indentation);
   pivot_table_dump_string (table->command_c, "command", indentation);
   pivot_table_dump_string (table->dataset, "dataset", indentation);
   pivot_table_dump_string (table->datafile, "datafile", indentation);
@@ -2004,7 +2028,7 @@ pivot_table_dump (const struct pivot_table *table, int indentation)
                              indentation + 1);
 
   for (size_t i = 0; i < table->n_dimensions; i++)
-    pivot_dimension_dump (table->dimensions[i], indentation);
+    pivot_dimension_dump (table->dimensions[i], table, indentation);
 
   /* Presentation and data indexes. */
   size_t *dindexes = XCALLOC (table->n_dimensions, size_t);
@@ -2042,7 +2066,7 @@ pivot_table_dump (const struct pivot_table *table, int indentation)
           const struct pivot_dimension *d = layer_axis->dimensions[i];
 
           fputs (i == 0 ? " " : ", ", stdout);
-          pivot_value_dump (d->root->name);
+          pivot_value_dump (d->root->name, table);
           fputs (" =", stdout);
 
           struct pivot_value **names = xnmalloc (d->n_leaves, sizeof *names);
@@ -2059,7 +2083,7 @@ pivot_table_dump (const struct pivot_table *table, int indentation)
           for (size_t i = n_names; i-- > 0;)
             {
               putchar (' ');
-              pivot_value_dump (names[i]);
+              pivot_value_dump (names[i], table);
             }
           free (names);
         }
@@ -2123,7 +2147,7 @@ pivot_table_dump (const struct pivot_table *table, int indentation)
               const struct pivot_value *value = pivot_table_get (
                 table, dindexes);
               if (value)
-                pivot_value_dump (value);
+                pivot_value_dump (value, table);
             }
           printf ("\n");
 
@@ -2135,7 +2159,7 @@ pivot_table_dump (const struct pivot_table *table, int indentation)
       free_headings (&table->axes[PIVOT_AXIS_ROW], row_headings);
     }
 
-  pivot_table_dump_value (table->caption, "caption", indentation);
+  pivot_table_dump_value (table->caption, "caption", table, indentation);
 
   for (size_t i = 0; i < table->n_footnotes; i++)
     {
@@ -2143,16 +2167,15 @@ pivot_table_dump (const struct pivot_table *table, int indentation)
       indent (indentation);
       putchar ('[');
       if (f->marker)
-        pivot_value_dump (f->marker);
+        pivot_value_dump (f->marker, table);
       else
         printf ("%zu", f->idx);
       putchar (']');
-      pivot_value_dump (f->content);
+      pivot_value_dump (f->content, table);
       putchar ('\n');
     }
 
   free (dindexes);
-  settings_set_decimal_char (old_decimal);
 }
 \f
 static const char *
@@ -2274,6 +2297,33 @@ interpret_show (enum settings_value_show global_show,
           : global_show);
 }
 
+/* Appends to OUT the actual text content from the given Pango MARKUP. */
+static void
+get_text_from_markup (const char *markup, struct string *out)
+{
+  xmlParserCtxt *parser = xmlCreatePushParserCtxt (NULL, NULL, NULL, 0, NULL);
+  if (!parser)
+    {
+      ds_put_cstr (out, markup);
+      return;
+    }
+
+  xmlParseChunk (parser, "<xml>", strlen ("<xml>"), false);
+  xmlParseChunk (parser, markup, strlen (markup), false);
+  xmlParseChunk (parser, "</xml>", strlen ("</xml>"), true);
+
+  if (parser->wellFormed)
+    {
+      xmlChar *s = xmlNodeGetContent (xmlDocGetRootElement (parser->myDoc));
+      ds_put_cstr (out, CHAR_CAST (char *, s));
+      xmlFree (s);
+    }
+  else
+    ds_put_cstr (out, markup);
+  xmlFreeDoc (parser->myDoc);
+  xmlFreeParserCtxt (parser);
+}
+
 /* Appends a text representation of the body of VALUE to OUT.  Settings on
    PT control whether variable and value labels are included.
 
@@ -2298,8 +2348,17 @@ pivot_value_format_body (const struct pivot_value *value,
                              value->numeric.value_label != NULL);
       if (show & SETTINGS_VALUE_SHOW_VALUE)
         {
+          const struct fmt_spec *f = &value->numeric.format;
+          const struct fmt_spec *format
+            = (f->type == FMT_F
+               && value->numeric.honor_small
+               && value->numeric.x != 0
+               && fabs (value->numeric.x) < pt->small
+               ? &(struct fmt_spec) { .type = FMT_E, .w = 40, .d = f->d }
+               : f);
+
           char *s = data_out (&(union value) { .f = value->numeric.x },
-                              "UTF-8", &value->numeric.format);
+                              "UTF-8", format, &pt->settings);
           ds_put_cstr (out, s + strspn (s, " "));
           free (s);
         }
@@ -2352,7 +2411,10 @@ pivot_value_format_body (const struct pivot_value *value,
       break;
 
     case PIVOT_VALUE_TEXT:
-      ds_put_cstr (out, value->text.local);
+      if (value->font_style && value->font_style->markup)
+        get_text_from_markup (value->text.local, out);
+      else
+        ds_put_cstr (out, value->text.local);
       break;
 
     case PIVOT_VALUE_TEMPLATE:
@@ -2367,13 +2429,16 @@ pivot_value_format_body (const struct pivot_value *value,
 /* Appends a text representation of VALUE to OUT.  Settings on
    PT control whether variable and value labels are included.
 
-   Subscripts and footnotes are included. */
-void
+   Subscripts and footnotes are included.
+
+   Returns true if OUT is a number (or a number plus a value label), false
+   otherwise.  */
+bool
 pivot_value_format (const struct pivot_value *value,
                     const struct pivot_table *pt,
                     struct string *out)
 {
-  pivot_value_format_body (value, pt, out);
+  bool numeric = pivot_value_format_body (value, pt, out);
 
   if (value->n_subscripts)
     {
@@ -2387,10 +2452,12 @@ pivot_value_format (const struct pivot_value *value,
 
       size_t idx = value->footnote_indexes[i];
       const struct pivot_footnote *f = pt->footnotes[idx];
-      pivot_value_format (f->marker, pt, out);
+      pivot_footnote_format_marker (f, pt, out);
 
       ds_put_byte (out, ']');
     }
+
+  return numeric;
 }
 
 /* Returns a text representation of VALUE.  The caller must free the string,
@@ -2410,6 +2477,7 @@ pivot_value_to_string_defaults (const struct pivot_value *value)
   static const struct pivot_table pt = {
     .show_values = SETTINGS_VALUE_SHOW_DEFAULT,
     .show_variables = SETTINGS_VALUE_SHOW_DEFAULT,
+    .settings = FMT_SETTINGS_INIT,
   };
   return pivot_value_to_string (value, &pt);
 }
@@ -2427,7 +2495,7 @@ pivot_value_clone (const struct pivot_value *old)
       font_style_copy (NULL, new->font_style, old->font_style);
     }
   if (old->cell_style)
-    new->font_style = xmemdup (old->font_style, sizeof *new->font_style);
+    new->cell_style = xmemdup (old->cell_style, sizeof *new->cell_style);
   if (old->n_subscripts)
     {
       new->subscripts = xnmalloc (old->n_subscripts, sizeof *new->subscripts);
@@ -2459,10 +2527,10 @@ pivot_value_clone (const struct pivot_value *old)
     case PIVOT_VALUE_TEXT:
       new->text.local = xstrdup (old->text.local);
       new->text.c = (old->text.c == old->text.local ? new->text.local
-                     : xstrdup (old->text.c));
+                     : xstrdup_if_nonnull (old->text.c));
       new->text.id = (old->text.id == old->text.local ? new->text.local
                       : old->text.id == old->text.c ? new->text.c
-                      : xstrdup (old->text.id));
+                      : xstrdup_if_nonnull (old->text.id));
       break;
 
     case PIVOT_VALUE_TEMPLATE:
@@ -2818,6 +2886,29 @@ pivot_value_add_footnote (struct pivot_value *v,
   v->footnote_indexes = xrealloc (
     v->footnote_indexes, (v->n_footnotes + 1) * sizeof *v->footnote_indexes);
   v->footnote_indexes[v->n_footnotes++] = footnote->idx;
+  pivot_value_sort_footnotes (v);
+}
+
+static int
+compare_footnote_indexes (const void *a_, const void *b_)
+{
+  const size_t *ap = a_;
+  const size_t *bp = b_;
+  size_t a = *ap;
+  size_t b = *bp;
+  return a < b ? -1 : a > b;
+}
+
+/* Sorts the footnote references in V in the standard ascending order.
+
+   This is only necessary if code adds (plural) footnotes to a pivot_value by
+   itself, because pivot_value_add_footnote() does it automatically. */
+void
+pivot_value_sort_footnotes (struct pivot_value *v)
+{
+  if (v->n_footnotes > 1)
+    qsort (v->footnote_indexes, v->n_footnotes, sizeof *v->footnote_indexes,
+           compare_footnote_indexes);
 }
 
 /* If VALUE is a numeric value, and RC is a result class such as
@@ -2827,10 +2918,7 @@ pivot_value_set_rc (const struct pivot_table *table, struct pivot_value *value,
                     const char *rc)
 {
   if (value->type == PIVOT_VALUE_NUMERIC)
-    {
-      const struct fmt_spec *f = pivot_table_get_format (table, rc);
-      if (f)
-        value->numeric.format = *f;
-    }
+    pivot_table_use_rc (table, rc,
+                        &value->numeric.format, &value->numeric.honor_small);
 }