more work toward making table_item just a pivot_Table
[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 xmemdup (pt->current_layer, MAX (size, 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, struct footnote **footnotes,
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       for (size_t i = 0; i < value->n_footnotes; i++)
159         {
160           struct footnote *f = footnotes[value->footnotes[i]->idx];
161           if (f)
162             table_add_footnote (t, x1, y1, f);
163         }
164
165       if (value->n_subscripts)
166         table_add_subscripts (t, x1, y1,
167                               value->subscripts, value->n_subscripts);
168     }
169 }
170
171 static int
172 get_table_rule (const struct table_border_style *styles,
173                 enum pivot_border style_idx)
174 {
175   return styles[style_idx].stroke | (style_idx << TAB_RULE_STYLE_SHIFT);
176 }
177
178 static void
179 draw_line (struct table *t, const struct table_border_style *styles,
180            enum pivot_border style_idx,
181            enum table_axis axis, int a, int b0, int b1)
182 {
183   int rule = get_table_rule (styles, style_idx);
184   if (axis == H)
185     table_hline (t, rule, b0, b1, a);
186   else
187     table_vline (t, rule, a, b0, b1);
188 }
189
190 static void
191 compose_headings (struct table *t,
192                   const struct pivot_axis *a_axis, enum table_axis a,
193                   const struct pivot_axis *b_axis,
194                   const struct table_border_style *borders,
195                   enum pivot_border dim_col_horz,
196                   enum pivot_border dim_col_vert,
197                   enum pivot_border cat_col_horz,
198                   enum pivot_border cat_col_vert,
199                   const size_t *column_enumeration, size_t n_columns,
200                   const struct table_area_style *label_style,
201                   int label_style_idx,
202                   const struct table_area_style *corner_style,
203                   struct footnote **footnotes,
204                   enum settings_value_show show_values,
205                   enum settings_value_show show_variables,
206                   bool rotate_inner_labels, bool rotate_outer_labels)
207 {
208   enum table_axis b = !a;
209   int b_size = a_axis->label_depth;
210   int a_ofs = b_axis->label_depth;
211
212   if (!a_axis->n_dimensions || !n_columns || !b_size)
213     return;
214
215   int bottom_row = b_size - 1;
216   const int stride = MAX (1, a_axis->n_dimensions);
217   for (int dim_index = 0; dim_index < a_axis->n_dimensions; dim_index++)
218     {
219       const struct pivot_dimension *d = a_axis->dimensions[dim_index];
220       if (d->hide_all_labels)
221         continue;
222
223       for (int row_ofs = 0; row_ofs < d->label_depth; row_ofs++)
224         {
225           for (size_t x1 = 0; x1 < n_columns;)
226             {
227               const struct pivot_category *c = find_category (
228                 d, dim_index, column_enumeration + x1 * stride, row_ofs);
229               if (!c)
230                 {
231                   x1++;
232                   continue;
233                 }
234
235               size_t x2;
236               for (x2 = x1 + 1; x2 < n_columns; x2++)
237                 {
238                   const struct pivot_category *c2 = find_category (
239                     d, dim_index, column_enumeration + x2 * stride, row_ofs);
240                   if (c != c2)
241                     break;
242                 }
243
244               int y1 = bottom_row - row_ofs - c->extra_depth;
245               int y2 = bottom_row - row_ofs + 1;
246               bool is_outer_row = y1 == 0;
247               bool is_inner_row = y2 == b_size;
248               if (pivot_category_is_leaf (c) || c->show_label)
249                 {
250                   int bb[TABLE_N_AXES][2];
251                   bb[a][0] = x1 + a_ofs;
252                   bb[a][1] = x2 + a_ofs - 1;
253                   bb[b][0] = y1;
254                   bb[b][1] = y2 - 1;
255                   bool rotate = ((rotate_inner_labels && is_inner_row)
256                                  || (rotate_outer_labels && is_outer_row));
257                   fill_cell (t, bb[H][0], bb[V][0], bb[H][1], bb[V][1],
258                              label_style, label_style_idx, c->name, footnotes,
259                              show_values, show_variables, rotate);
260
261                   if (pivot_category_is_leaf (c) && x2 + 1 <= n_columns)
262                     {
263                       enum pivot_border style
264                         = (y1 == 0 && a_axis->label_depth > d->label_depth
265                            ? dim_col_vert
266                            : cat_col_vert);
267                       draw_line (t, borders, style, b, x2 + a_ofs, y1,
268                                  t->n[b] - 1);
269                     }
270                   if (pivot_category_is_leaf (c) && x1 > 0)
271                     {
272                       enum pivot_border style
273                         = (y1 == 0 && a_axis->label_depth > d->label_depth
274                            ? dim_col_vert
275                            : cat_col_vert);
276                       draw_line (t, borders, style, b, x1 + a_ofs, y1,
277                                  t->n[b] - 1);
278                     }
279                 }
280               if (c->parent && c->parent->show_label)
281                 draw_line (t, borders, cat_col_horz, a, y1,
282                            x1 + a_ofs, x2 + a_ofs - 1);
283
284               x1 = x2;
285             }
286         }
287
288       if (d->root->show_label_in_corner && a_ofs > 0)
289         {
290           int bb[TABLE_N_AXES][2];
291           bb[a][0] = 0;
292           bb[a][1] = a_ofs - 1;
293           bb[b][0] = bottom_row - d->label_depth + 1;
294           bb[b][1] = bottom_row;
295           fill_cell (t, bb[H][0], bb[V][0], bb[H][1], bb[V][1],
296                      corner_style, PIVOT_AREA_CORNER, d->root->name, footnotes,
297                      show_values, show_variables, false);
298         }
299
300       if (dim_index > 1)
301         draw_line (t, borders, dim_col_horz, a, bottom_row + 1, a_ofs,
302                    t->n[a] - 1);
303
304       bottom_row -= d->label_depth;
305     }
306 }
307
308 static struct table *
309 create_aux_table (const struct pivot_table *pt, int nc, int nr,
310                   int style_idx)
311 {
312   struct table *table = table_create (nr, nc, 0, 0, 0, 0);
313   table->styles[style_idx] = table_area_style_override (
314       t->container, &pt->look->areas[style_idx], NULL, NULL, false);
315   return table;
316 }
317
318
319 static struct footnote **
320 add_footnotes (struct footnote **refs, size_t n_refs,
321                struct footnote **footnotes, size_t *allocated, size_t *n)
322 {
323   for (size_t i = 0; i < n_refs; i++)
324     {
325       struct footnote *f = refs[i];
326       if (f->idx >= *allocated)
327         {
328           size_t new_allocated = (f->idx + 1) * 2;
329           footnotes = xrealloc (footnotes, new_allocated * sizeof *footnotes);
330           while (*allocated < new_allocated)
331             footnotes[(*allocated)++] = NULL;
332         }
333       footnotes[f->idx] = f;
334       if (f->idx >= *n)
335         *n = f->idx + 1;
336     }
337   return footnotes;
338 }
339
340 size_t
341 table_collect_footnotes (const struct table *
342                          struct footnote ***footnotesp)
343 {
344   struct footnote **footnotes = NULL;
345   size_t allocated = 0;
346   size_t n = 0;
347
348   struct table *t = item->table;
349   for (int y = 0; y < t->n[V]; y++)
350     {
351       struct table_cell cell;
352       for (int x = 0; x < t->n[H]; x = cell.d[TABLE_HORZ][1])
353         {
354           table_get_cell (t, x, y, &cell);
355
356           if (x == cell.d[TABLE_HORZ][0] && y == cell.d[TABLE_VERT][0])
357             footnotes = add_footnotes (cell.footnotes, cell.n_footnotes,
358                                        footnotes, &allocated, &n);
359         }
360     }
361
362   const struct table_cell *title = table_item_get_title (item);
363   if (title)
364     footnotes = add_footnotes (title->footnotes, title->n_footnotes,
365                                footnotes, &allocated, &n);
366
367   const struct table_item_layers *layers = table_item_get_layers (item);
368   if (layers)
369     {
370       for (size_t i = 0; i < layers->n_layers; i++)
371         footnotes = add_footnotes (layers->layers[i].footnotes,
372                                    layers->layers[i].n_footnotes,
373                                    footnotes, &allocated, &n);
374     }
375
376   const struct table_cell *caption = table_item_get_caption (item);
377   if (caption)
378     footnotes = add_footnotes (caption->footnotes, caption->n_footnotes,
379                                footnotes, &allocated, &n);
380
381   size_t n_nonnull = 0;
382   for (size_t i = 0; i < n; i++)
383     if (footnotes[i])
384       footnotes[n_nonnull++] = footnotes[i];
385
386   *footnotesp = footnotes;
387   return n_nonnull;
388 }
389
390 void
391 pivot_output (const struct pivot_table *pt,
392               const size_t *layer_indexes,
393               struct table **titlep,
394               struct table **layersp,
395               struct table **bodyp,
396               struct table **captionp,
397               struct table **footnotesp,
398               struct footnote ***fp, size_t *nfp)
399 {
400   const size_t *pindexes[PIVOT_N_AXES]
401     = { [PIVOT_AXIS_LAYER] = layer_indexes };
402
403   size_t data[TABLE_N_AXES];
404   size_t *column_enumeration = pivot_table_enumerate_axis (
405     pt, PIVOT_AXIS_COLUMN, layer_indexes, pt->look->omit_empty, &data[H]);
406   size_t *row_enumeration = pivot_table_enumerate_axis (
407     pt, PIVOT_AXIS_ROW, layer_indexes, pt->look->omit_empty, &data[V]);
408
409   int stub[TABLE_N_AXES] = {
410     [H] = pt->axes[PIVOT_AXIS_ROW].label_depth,
411     [V] = pt->axes[PIVOT_AXIS_COLUMN].label_depth,
412   };
413   struct table *body = table_create (data[H] + stub[H],
414                                      data[V] + stub[V],
415                                      stub[H], 0, stub[V], 0);
416   for (size_t i = 0; i < PIVOT_N_AREAS; i++)
417     body->styles[i] = table_area_style_override (
418       body->container, &pt->look->areas[i], NULL, NULL, false);
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   struct footnote **footnotes = XCALLOC (pt->n_footnotes,  struct footnote *);
429   for (size_t i = 0; i < pt->n_footnotes; i++)
430     {
431       const struct pivot_footnote *pf = pt->footnotes[i];
432
433       if (!pf->show)
434         continue;
435
436       char *content = pivot_value_to_string (pf->content, pt->show_values,
437                                              pt->show_variables);
438       char *marker = pivot_value_to_string (pf->marker, pt->show_values,
439                                             pt->show_variables);
440       footnotes[i] = table_create_footnote (
441         body, i, content, marker,
442         table_area_style_override (body->container,
443                                    &pt->look->areas[PIVOT_AREA_FOOTER],
444                                    pf->content->cell_style,
445                                    pf->content->font_style,
446                                    false));
447       free (marker);
448       free (content);
449     }
450
451   compose_headings (body,
452                     &pt->axes[PIVOT_AXIS_COLUMN], H, &pt->axes[PIVOT_AXIS_ROW],
453                     pt->look->borders,
454                     PIVOT_BORDER_DIM_COL_HORZ,
455                     PIVOT_BORDER_DIM_COL_VERT,
456                     PIVOT_BORDER_CAT_COL_HORZ,
457                     PIVOT_BORDER_CAT_COL_VERT,
458                     column_enumeration, data[H],
459                     &pt->look->areas[PIVOT_AREA_COLUMN_LABELS],
460                     PIVOT_AREA_COLUMN_LABELS,
461                     &pt->look->areas[PIVOT_AREA_CORNER], footnotes,
462                     pt->show_values, pt->show_variables,
463                     pt->rotate_outer_row_labels, false);
464
465   compose_headings (body,
466                     &pt->axes[PIVOT_AXIS_ROW], V, &pt->axes[PIVOT_AXIS_COLUMN],
467                     pt->look->borders,
468                     PIVOT_BORDER_DIM_ROW_VERT,
469                     PIVOT_BORDER_DIM_ROW_HORZ,
470                     PIVOT_BORDER_CAT_ROW_VERT,
471                     PIVOT_BORDER_CAT_ROW_HORZ,
472                     row_enumeration, data[V],
473                     &pt->look->areas[PIVOT_AREA_ROW_LABELS],
474                     PIVOT_AREA_ROW_LABELS,
475                     &pt->look->areas[PIVOT_AREA_CORNER], footnotes,
476                     pt->show_values, pt->show_variables,
477                     false, pt->rotate_inner_column_labels);
478
479   size_t *dindexes = XCALLOC (pt->n_dimensions, size_t);
480   size_t y = 0;
481   PIVOT_ENUMERATION_FOR_EACH (pindexes[PIVOT_AXIS_ROW], row_enumeration,
482                               &pt->axes[PIVOT_AXIS_ROW])
483     {
484       size_t x = 0;
485       PIVOT_ENUMERATION_FOR_EACH (pindexes[PIVOT_AXIS_COLUMN],
486                                   column_enumeration,
487                                   &pt->axes[PIVOT_AXIS_COLUMN])
488         {
489           pivot_table_convert_indexes_ptod (pt, pindexes, dindexes);
490           const struct pivot_value *value = pivot_table_get (pt, dindexes);
491           fill_cell (body,
492                      x + stub[H], y + stub[V],
493                      x + stub[H], y + stub[V],
494                      &pt->look->areas[PIVOT_AREA_DATA], PIVOT_AREA_DATA,
495                      value, footnotes,
496                      pt->show_values, pt->show_variables, false);
497
498           x++;
499         }
500
501       y++;
502     }
503   free (dindexes);
504
505   if ((pt->corner_text || !pt->look->row_labels_in_corner)
506       && stub[H] && stub[V])
507     fill_cell (body, 0, 0, stub[H] - 1, stub[V] - 1,
508                &pt->look->areas[PIVOT_AREA_CORNER], PIVOT_AREA_CORNER,
509                pt->corner_text, footnotes,
510                pt->show_values, pt->show_variables, false);
511
512   if (body->n[H] && body->n[V])
513     {
514       table_hline (
515         body, get_table_rule (pt->look->borders, PIVOT_BORDER_INNER_TOP),
516         0, body->n[H] - 1, 0);
517       table_hline (
518         body, get_table_rule (pt->look->borders, PIVOT_BORDER_INNER_BOTTOM),
519         0, body->n[H] - 1, body->n[V]);
520       table_vline (
521         body, get_table_rule (pt->look->borders, PIVOT_BORDER_INNER_LEFT),
522         0, 0, body->n[V] - 1);
523       table_vline (
524         body, get_table_rule (pt->look->borders, PIVOT_BORDER_INNER_RIGHT),
525         body->n[H], 0, body->n[V] - 1);
526
527       if (stub[V])
528         table_hline (
529           body, get_table_rule (pt->look->borders, PIVOT_BORDER_DATA_TOP),
530           0, body->n[H] - 1, stub[V]);
531       if (stub[H])
532         table_vline (
533           body, get_table_rule (pt->look->borders, PIVOT_BORDER_DATA_LEFT),
534           stub[H], 0, body->n[V] - 1);
535
536     }
537   free (column_enumeration);
538   free (row_enumeration);
539
540   /* Title. */
541   struct table *title;
542   if (pt->title && titlep)
543     {
544       title = create_aux_table (pt, 1, 1, PIVOT_AREA_TITLE);
545       fill_cell (title, 0, 0, 1, 1,
546                  &pt->look->areas[PIVOT_AREA_TITLE], PIVOT_AREA_TITLE,
547                  pt->title, footnotes,
548                  pt->show_values, pt->show_variables, false);
549     }
550   else
551     title = NULL;
552
553   /* Layers. */
554   const struct pivot_axis *layer_axis = &pt->axes[PIVOT_AXIS_LAYER];
555   int n_layers = 0;
556   if (layersp)
557     for (size_t i = 0; i < layer_axis->n_dimensions; i++)
558       {
559         const struct pivot_dimension *d = layer_axis->dimensions[i];
560         if (d->n_leaves)
561           n_layers++;
562       }
563
564   struct table *layers;
565   if (n_layers > 0)
566     {
567       layers = create_aux_table (pt, 1, n_layers, PIVOT_AREA_LAYERS);
568       size_t y = 0;
569       for (size_t i = 0; i < layer_axis->n_dimensions; i++)
570         {
571           const struct pivot_dimension *d = layer_axis->dimensions[i];
572           if (!d->n_leaves)
573             continue;
574
575           /* XXX This puts in the layer values, but not the variable names. */
576           const struct pivot_value *name
577             = d->data_leaves[layer_indexes[i]]->name;
578           fill_cell (layers, 0, y, 1, y + 1,
579                      &pt->look->areas[PIVOT_AREA_LAYERS], PIVOT_AREA_LAYERS,
580                      name, footnotes,
581                      pt->show_values, pt->show_variables, false);
582           y++;
583         }
584     }
585   else
586     layers = NULL;
587
588   /* Caption. */
589   struct table *caption;
590   if (pt->caption && captionp)
591     {
592       caption = create_aux_table (pt, 1, 1, PIVOT_AREA_CAPTION);
593       fill_cell (caption, 0, 0, 1, 1,
594                  &pt->look->areas[PIVOT_AREA_CAPTION], PIVOT_AREA_CAPTION,
595                  pt->caption, footnotes,
596                  pt->show_values, pt->show_variables, false);
597     }
598   else
599     caption = NULL;
600
601   free (footnotes);
602
603   *bodyp = body;
604 }
605
606 void
607 pivot_table_submit (struct pivot_table *pt)
608 {
609   table_item_submit (table_item_create (pt));
610 }