work
[pspp] / src / output / pivot-output.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2018 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <stdlib.h>
20
21 #include "output/pivot-output.h"
22
23 #include "data/settings.h"
24 #include "libpspp/assertion.h"
25 #include "libpspp/pool.h"
26 #include "output/page-eject-item.h"
27 #include "output/pivot-table.h"
28 #include "output/table-item.h"
29 #include "output/table-provider.h"
30 #include "output/table.h"
31 #include "output/text-item.h"
32
33 #include "gl/minmax.h"
34 #include "gl/xalloc.h"
35
36 #define H TABLE_HORZ
37 #define V TABLE_VERT
38
39 size_t *
40 pivot_output_next_layer (const struct pivot_table *pt, size_t *indexes,
41                          bool print)
42 {
43   const struct pivot_axis *layer_axis = &pt->axes[PIVOT_AXIS_LAYER];
44   if (print && pt->look->print_all_layers)
45     return pivot_axis_iterator_next (indexes, layer_axis);
46   else if (!indexes)
47     {
48       size_t size = layer_axis->n_dimensions * sizeof *pt->current_layer;
49       return size ? xmemdup (pt->current_layer, size) : xmalloc (1);
50     }
51   else
52     {
53       free (indexes);
54       return NULL;
55     }
56 }
57
58 static const struct pivot_category *
59 find_category (const struct pivot_dimension *d, int dim_index,
60                const size_t *indexes, int row_ofs)
61 {
62   size_t index = indexes[dim_index];
63   assert (index < d->n_leaves);
64   for (const struct pivot_category *c = d->presentation_leaves[index];
65        c; c = c->parent)
66     {
67       if (!row_ofs)
68         return c;
69
70       row_ofs -= 1 + c->extra_depth;
71       if (row_ofs < 0)
72         return NULL;
73     }
74   return NULL;
75 }
76
77 static struct table_area_style *
78 table_area_style_override (struct pool *pool,
79                            const struct table_area_style *in,
80                            const struct cell_style *cell_,
81                            const struct font_style *font_,
82                            bool rotate_label)
83 {
84   const struct cell_style *cell = cell_ ? cell_ : &in->cell_style;
85   const struct font_style *font = font_ ? font_ : &in->font_style;
86
87   struct table_area_style *out = (pool
88                             ? pool_alloc (pool, sizeof *out)
89                             : xmalloc (sizeof *out));
90   *out = (struct table_area_style) {
91     .cell_style.halign = rotate_label ? TABLE_HALIGN_CENTER : cell->halign,
92     .cell_style.valign = rotate_label ? TABLE_VALIGN_CENTER : cell->valign,
93     .cell_style.decimal_offset = cell->decimal_offset,
94     .cell_style.margin[H][0] = cell->margin[H][0],
95     .cell_style.margin[H][1] = cell->margin[H][1],
96     .cell_style.margin[V][0] = cell->margin[V][0],
97     .cell_style.margin[V][1] = cell->margin[V][1],
98     .font_style.fg[0] = font->fg[0],
99     .font_style.fg[1] = font->fg[1],
100     .font_style.bg[0] = font->bg[0],
101     .font_style.bg[1] = font->bg[1],
102     .font_style.typeface = (font->typeface
103                             ? pool_strdup (pool, font->typeface)
104                             : NULL),
105     .font_style.size = font->size,
106     .font_style.bold = font->bold,
107     .font_style.italic = font->italic,
108     .font_style.underline = font->underline,
109     .font_style.markup = font->markup,
110   };
111   return out;
112 }
113
114 static int
115 format_cell (const struct pivot_value *value, int style_idx,
116              enum settings_value_show show_values,
117              enum settings_value_show show_variables,
118              bool rotate_label, struct string *s)
119 {
120   int options = style_idx << TAB_STYLE_SHIFT;
121   if (value)
122     {
123       bool numeric = pivot_value_format_body (value, show_values,
124                                               show_variables, s);
125       if (numeric)
126         options |= TAB_NUMERIC;
127       if (value->font_style && value->font_style->markup)
128         options |= TAB_MARKUP;
129       if (rotate_label)
130         options |= TAB_ROTATE;
131     }
132   return options;
133 }
134
135 static void
136 fill_cell (struct table *t, int x1, int y1, int x2, int y2,
137            const struct table_area_style *style, int style_idx,
138            const struct pivot_value *value,
139            enum settings_value_show show_values,
140            enum settings_value_show show_variables,
141            bool rotate_label)
142 {
143   struct string s = DS_EMPTY_INITIALIZER;
144   int options = format_cell (value, style_idx,
145                              show_values, show_variables, rotate_label, &s);
146   table_joint_text (t, x1, y1, x2, y2, options, ds_cstr (&s));
147   ds_destroy (&s);
148
149   if (value)
150     {
151       if (value->cell_style || value->font_style || rotate_label)
152         table_add_style (t, x1, y1,
153                          table_area_style_override (t->container, style,
154                                                     value->cell_style,
155                                                     value->font_style,
156                                                     rotate_label));
157
158       table_add_footnotes (t, x1, y1,
159                            (struct pivot_footnote **) value->footnotes,
160                            value->n_footnotes);
161
162       if (value->n_subscripts)
163         table_add_subscripts (t, x1, y1,
164                               value->subscripts, value->n_subscripts);
165     }
166 }
167
168 static int
169 get_table_rule (const struct table_border_style *styles,
170                 enum pivot_border style_idx)
171 {
172   return styles[style_idx].stroke | (style_idx << TAB_RULE_STYLE_SHIFT);
173 }
174
175 static void
176 draw_line (struct table *t, const struct table_border_style *styles,
177            enum pivot_border style_idx,
178            enum table_axis axis, int a, int b0, int b1)
179 {
180   int rule = get_table_rule (styles, style_idx);
181   if (axis == H)
182     table_hline (t, rule, b0, b1, a);
183   else
184     table_vline (t, rule, a, b0, b1);
185 }
186
187 static void
188 compose_headings (struct table *t,
189                   const struct pivot_axis *a_axis, enum table_axis a,
190                   const struct pivot_axis *b_axis,
191                   const struct table_border_style *borders,
192                   enum pivot_border dim_col_horz,
193                   enum pivot_border dim_col_vert,
194                   enum pivot_border cat_col_horz,
195                   enum pivot_border cat_col_vert,
196                   const size_t *column_enumeration, size_t n_columns,
197                   const struct table_area_style *label_style,
198                   int label_style_idx,
199                   const struct table_area_style *corner_style,
200                   enum settings_value_show show_values,
201                   enum settings_value_show show_variables,
202                   bool rotate_inner_labels, bool rotate_outer_labels)
203 {
204   enum table_axis b = !a;
205   int b_size = a_axis->label_depth;
206   int a_ofs = b_axis->label_depth;
207
208   if (!a_axis->n_dimensions || !n_columns || !b_size)
209     return;
210
211   int bottom_row = b_size - 1;
212   const int stride = MAX (1, a_axis->n_dimensions);
213   for (int dim_index = 0; dim_index < a_axis->n_dimensions; dim_index++)
214     {
215       const struct pivot_dimension *d = a_axis->dimensions[dim_index];
216       if (d->hide_all_labels)
217         continue;
218
219       for (int row_ofs = 0; row_ofs < d->label_depth; row_ofs++)
220         {
221           for (size_t x1 = 0; x1 < n_columns;)
222             {
223               const struct pivot_category *c = find_category (
224                 d, dim_index, column_enumeration + x1 * stride, row_ofs);
225               if (!c)
226                 {
227                   x1++;
228                   continue;
229                 }
230
231               size_t x2;
232               for (x2 = x1 + 1; x2 < n_columns; x2++)
233                 {
234                   const struct pivot_category *c2 = find_category (
235                     d, dim_index, column_enumeration + x2 * stride, row_ofs);
236                   if (c != c2)
237                     break;
238                 }
239
240               int y1 = bottom_row - row_ofs - c->extra_depth;
241               int y2 = bottom_row - row_ofs + 1;
242               bool is_outer_row = y1 == 0;
243               bool is_inner_row = y2 == b_size;
244               if (pivot_category_is_leaf (c) || c->show_label)
245                 {
246                   int bb[TABLE_N_AXES][2];
247                   bb[a][0] = x1 + a_ofs;
248                   bb[a][1] = x2 + a_ofs - 1;
249                   bb[b][0] = y1;
250                   bb[b][1] = y2 - 1;
251                   bool rotate = ((rotate_inner_labels && is_inner_row)
252                                  || (rotate_outer_labels && is_outer_row));
253                   fill_cell (t, bb[H][0], bb[V][0], bb[H][1], bb[V][1],
254                              label_style, label_style_idx, c->name,
255                              show_values, show_variables, rotate);
256
257                   if (pivot_category_is_leaf (c) && x2 + 1 <= n_columns)
258                     {
259                       enum pivot_border style
260                         = (y1 == 0 && a_axis->label_depth > d->label_depth
261                            ? dim_col_vert
262                            : cat_col_vert);
263                       draw_line (t, borders, style, b, x2 + a_ofs, y1,
264                                  t->n[b] - 1);
265                     }
266                   if (pivot_category_is_leaf (c) && x1 > 0)
267                     {
268                       enum pivot_border style
269                         = (y1 == 0 && a_axis->label_depth > d->label_depth
270                            ? dim_col_vert
271                            : cat_col_vert);
272                       draw_line (t, borders, style, b, x1 + a_ofs, y1,
273                                  t->n[b] - 1);
274                     }
275                 }
276               if (c->parent && c->parent->show_label)
277                 draw_line (t, borders, cat_col_horz, a, y1,
278                            x1 + a_ofs, x2 + a_ofs - 1);
279
280               x1 = x2;
281             }
282         }
283
284       if (d->root->show_label_in_corner && a_ofs > 0)
285         {
286           int bb[TABLE_N_AXES][2];
287           bb[a][0] = 0;
288           bb[a][1] = a_ofs - 1;
289           bb[b][0] = bottom_row - d->label_depth + 1;
290           bb[b][1] = bottom_row;
291           fill_cell (t, bb[H][0], bb[V][0], bb[H][1], bb[V][1],
292                      corner_style, PIVOT_AREA_CORNER, d->root->name,
293                      show_values, show_variables, false);
294         }
295
296       if (dim_index > 1)
297         draw_line (t, borders, dim_col_horz, a, bottom_row + 1, a_ofs,
298                    t->n[a] - 1);
299
300       bottom_row -= d->label_depth;
301     }
302 }
303
304 static struct table *
305 create_aux_table (const struct pivot_table *pt, int nc, int nr,
306                   int style_idx)
307 {
308   struct table *table = table_create (nr, nc, 0, 0, 0, 0);
309   table->styles[style_idx] = table_area_style_override (
310       table->container, &pt->look->areas[style_idx], NULL, NULL, false);
311   return table;
312 }
313
314
315 static void
316 add_references (const struct pivot_table *pt, const struct table *table,
317                 bool *refs, size_t *n_refs)
318 {
319   if (!table)
320     return;
321
322   for (int y = 0; y < table->n[V]; y++)
323     for (int x = 0; x < table->n[H]; )
324       {
325         struct table_cell cell;
326         table_get_cell (table, x, y, &cell);
327
328         if (x == cell.d[H][0] && y == cell.d[V][0])
329           {
330             for (size_t i = 0; i < cell.n_footnotes; i++)
331               {
332                 const struct pivot_footnote *f = cell.footnotes[i];
333                 assert (f->idx < pt->n_footnotes);
334                 assert (f == pt->footnotes[f->idx]);
335
336                 if (!refs[f->idx])
337                   {
338                     refs[f->idx] = true;
339                     (*n_refs)++;
340                   }
341               }
342           }
343
344         x = cell.d[TABLE_HORZ][1];
345       }
346 }
347
348 static struct pivot_footnote **
349 collect_footnotes (const struct pivot_table *pt,
350                    const struct table *title,
351                    const struct table *layers,
352                    const struct table *body,
353                    const struct table *caption,
354                    size_t *n_footnotesp)
355 {
356   if (!pt->n_footnotes)
357     {
358       *n_footnotesp = 0;
359       return NULL;
360     }
361
362   bool *refs = xzalloc (pt->n_footnotes);
363   size_t n_refs = 0;
364   add_references (pt, title, refs, &n_refs);
365   add_references (pt, layers, refs, &n_refs);
366   add_references (pt, body, refs, &n_refs);
367   add_references (pt, caption, refs, &n_refs);
368
369   struct pivot_footnote **footnotes = xnmalloc (n_refs, sizeof *footnotes);
370   size_t n_footnotes = 0;
371   for (size_t i = 0; i < pt->n_footnotes; i++)
372     if (refs[i])
373       footnotes[n_footnotes++] = pt->footnotes[i];
374   assert (n_footnotes == n_refs);
375
376   free (refs);
377
378   *n_footnotesp = n_footnotes;
379   return footnotes;
380 }
381
382 void
383 pivot_output (const struct pivot_table *pt,
384               const size_t *layer_indexes,
385               bool printing UNUSED,
386               struct table **titlep,
387               struct table **layersp,
388               struct table **bodyp,
389               struct table **captionp,
390               struct table **footnotesp,
391               struct pivot_footnote ***fp, size_t *nfp)
392 {
393   const size_t *pindexes[PIVOT_N_AXES]
394     = { [PIVOT_AXIS_LAYER] = layer_indexes };
395
396   size_t data[TABLE_N_AXES];
397   size_t *column_enumeration = pivot_table_enumerate_axis (
398     pt, PIVOT_AXIS_COLUMN, layer_indexes, pt->look->omit_empty, &data[H]);
399   size_t *row_enumeration = pivot_table_enumerate_axis (
400     pt, PIVOT_AXIS_ROW, layer_indexes, pt->look->omit_empty, &data[V]);
401
402   int stub[TABLE_N_AXES] = {
403     [H] = pt->axes[PIVOT_AXIS_ROW].label_depth,
404     [V] = pt->axes[PIVOT_AXIS_COLUMN].label_depth,
405   };
406   struct table *body = table_create (data[H] + stub[H],
407                                      data[V] + stub[V],
408                                      stub[H], 0, stub[V], 0);
409   for (size_t i = 0; i < PIVOT_N_AREAS; i++)
410     body->styles[i] = table_area_style_override (
411       body->container, &pt->look->areas[i], NULL, NULL, false);
412
413   struct table_border_style borders[PIVOT_N_BORDERS];
414   memcpy (borders, pt->look->borders, sizeof borders);
415   if (!printing && pt->show_grid_lines)
416     for (int b = 0; b < PIVOT_N_BORDERS; b++)
417       if (borders[b].stroke == TABLE_STROKE_NONE)
418         borders[b].stroke = TABLE_STROKE_DASHED;
419
420   for (size_t i = 0; i < PIVOT_N_BORDERS; i++)
421     {
422       const struct table_border_style *in = &pt->look->borders[i];
423       body->rule_colors[i] = pool_alloc (body->container,
424                                          sizeof *body->rule_colors[i]);
425       *body->rule_colors[i] = in->color;
426     }
427
428   compose_headings (body,
429                     &pt->axes[PIVOT_AXIS_COLUMN], H, &pt->axes[PIVOT_AXIS_ROW],
430                     borders,
431                     PIVOT_BORDER_DIM_COL_HORZ,
432                     PIVOT_BORDER_DIM_COL_VERT,
433                     PIVOT_BORDER_CAT_COL_HORZ,
434                     PIVOT_BORDER_CAT_COL_VERT,
435                     column_enumeration, data[H],
436                     &pt->look->areas[PIVOT_AREA_COLUMN_LABELS],
437                     PIVOT_AREA_COLUMN_LABELS,
438                     &pt->look->areas[PIVOT_AREA_CORNER],
439                     pt->show_values, pt->show_variables,
440                     pt->rotate_outer_row_labels, false);
441
442   compose_headings (body,
443                     &pt->axes[PIVOT_AXIS_ROW], V, &pt->axes[PIVOT_AXIS_COLUMN],
444                     borders,
445                     PIVOT_BORDER_DIM_ROW_VERT,
446                     PIVOT_BORDER_DIM_ROW_HORZ,
447                     PIVOT_BORDER_CAT_ROW_VERT,
448                     PIVOT_BORDER_CAT_ROW_HORZ,
449                     row_enumeration, data[V],
450                     &pt->look->areas[PIVOT_AREA_ROW_LABELS],
451                     PIVOT_AREA_ROW_LABELS,
452                     &pt->look->areas[PIVOT_AREA_CORNER],
453                     pt->show_values, pt->show_variables,
454                     false, pt->rotate_inner_column_labels);
455
456   size_t *dindexes = XCALLOC (pt->n_dimensions, size_t);
457   size_t y = 0;
458   PIVOT_ENUMERATION_FOR_EACH (pindexes[PIVOT_AXIS_ROW], row_enumeration,
459                               &pt->axes[PIVOT_AXIS_ROW])
460     {
461       size_t x = 0;
462       PIVOT_ENUMERATION_FOR_EACH (pindexes[PIVOT_AXIS_COLUMN],
463                                   column_enumeration,
464                                   &pt->axes[PIVOT_AXIS_COLUMN])
465         {
466           pivot_table_convert_indexes_ptod (pt, pindexes, dindexes);
467           const struct pivot_value *value = pivot_table_get (pt, dindexes);
468           fill_cell (body,
469                      x + stub[H], y + stub[V],
470                      x + stub[H], y + stub[V],
471                      &pt->look->areas[PIVOT_AREA_DATA], PIVOT_AREA_DATA,
472                      value, pt->show_values, pt->show_variables, false);
473
474           x++;
475         }
476
477       y++;
478     }
479   free (dindexes);
480
481   if ((pt->corner_text || !pt->look->row_labels_in_corner)
482       && stub[H] && stub[V])
483     fill_cell (body, 0, 0, stub[H] - 1, stub[V] - 1,
484                &pt->look->areas[PIVOT_AREA_CORNER], PIVOT_AREA_CORNER,
485                pt->corner_text, pt->show_values, pt->show_variables, false);
486
487   if (body->n[H] && body->n[V])
488     {
489       table_hline (
490         body, get_table_rule (borders, PIVOT_BORDER_INNER_TOP),
491         0, body->n[H] - 1, 0);
492       table_hline (
493         body, get_table_rule (borders, PIVOT_BORDER_INNER_BOTTOM),
494         0, body->n[H] - 1, body->n[V]);
495       table_vline (
496         body, get_table_rule (borders, PIVOT_BORDER_INNER_LEFT),
497         0, 0, body->n[V] - 1);
498       table_vline (
499         body, get_table_rule (borders, PIVOT_BORDER_INNER_RIGHT),
500         body->n[H], 0, body->n[V] - 1);
501
502       if (stub[V])
503         table_hline (
504           body, get_table_rule (borders, PIVOT_BORDER_DATA_TOP),
505           0, body->n[H] - 1, stub[V]);
506       if (stub[H])
507         table_vline (
508           body, get_table_rule (borders, PIVOT_BORDER_DATA_LEFT),
509           stub[H], 0, body->n[V] - 1);
510
511     }
512   free (column_enumeration);
513   free (row_enumeration);
514
515   /* Title. */
516   struct table *title;
517   if (pt->title && pt->show_title && titlep)
518     {
519       title = create_aux_table (pt, 1, 1, PIVOT_AREA_TITLE);
520       fill_cell (title, 0, 0, 0, 0,
521                  &pt->look->areas[PIVOT_AREA_TITLE], PIVOT_AREA_TITLE,
522                  pt->title, pt->show_values, pt->show_variables, false);
523     }
524   else
525     title = NULL;
526
527   /* Layers. */
528   const struct pivot_axis *layer_axis = &pt->axes[PIVOT_AXIS_LAYER];
529   int n_layers = 0;
530   if (layersp)
531     for (size_t i = 0; i < layer_axis->n_dimensions; i++)
532       {
533         const struct pivot_dimension *d = layer_axis->dimensions[i];
534         if (d->n_leaves)
535           n_layers++;
536       }
537
538   struct table *layers;
539   if (n_layers > 0)
540     {
541       layers = create_aux_table (pt, 1, n_layers, PIVOT_AREA_LAYERS);
542       size_t y = 0;
543       for (size_t i = 0; i < layer_axis->n_dimensions; i++)
544         {
545           const struct pivot_dimension *d = layer_axis->dimensions[i];
546           if (!d->n_leaves)
547             continue;
548
549           /* XXX This puts in the layer values, but not the variable names. */
550           const struct pivot_value *name
551             = d->data_leaves[layer_indexes[i]]->name;
552           fill_cell (layers, 0, y, 0, y,
553                      &pt->look->areas[PIVOT_AREA_LAYERS], PIVOT_AREA_LAYERS,
554                      name, pt->show_values, pt->show_variables, false);
555           y++;
556         }
557     }
558   else
559     layers = NULL;
560
561   /* Caption. */
562   struct table *caption;
563   if (pt->caption && pt->show_caption && captionp)
564     {
565       caption = create_aux_table (pt, 1, 1, PIVOT_AREA_CAPTION);
566       fill_cell (caption, 0, 0, 0, 0,
567                  &pt->look->areas[PIVOT_AREA_CAPTION], PIVOT_AREA_CAPTION,
568                  pt->caption, pt->show_values, pt->show_variables, false);
569     }
570   else
571     caption = NULL;
572
573   /* Footnotes. */
574   size_t nf;
575   struct pivot_footnote **f = collect_footnotes (pt, title, layers, body,
576                                                  caption, &nf);
577   struct table *footnotes;
578   if (nf && footnotesp)
579     {
580       footnotes = create_aux_table (pt, 1, nf, PIVOT_AREA_FOOTER);
581
582       for (size_t i = 0; i < nf; i++)
583         {
584           struct string s = DS_EMPTY_INITIALIZER;
585           pivot_value_format (f[i]->marker, pt->show_values,
586                               pt->show_variables, &s);
587           ds_put_cstr (&s, ". ");
588           pivot_value_format (f[i]->content, pt->show_values,
589                               pt->show_variables, &s);
590
591           struct pivot_value *value = pivot_value_new_user_text_nocopy (
592             ds_steal_cstr (&s));
593
594           fill_cell (footnotes, 0, i, 0, i,
595                      &pt->look->areas[PIVOT_AREA_FOOTER], PIVOT_AREA_FOOTER,
596                      value, pt->show_values, pt->show_variables, false);
597         }
598     }
599   else
600     footnotes = NULL;
601
602   *titlep = title;
603   if (layersp)
604     *layersp = layers;
605   *bodyp = body;
606   if (captionp)
607     *captionp = caption;
608   if (footnotesp)
609     *footnotesp = footnotes;
610   if (fp)
611     {
612       *fp = f;
613       *nfp = nf;
614     }
615   else
616     free (f);
617 }
618
619 void
620 pivot_table_submit (struct pivot_table *pt)
621 {
622   table_item_submit (table_item_create (pt));
623 }