08db3a0781f375fb9022c739eeeb23bba8aa7091
[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-table.h"
22
23 #include "data/settings.h"
24 #include "libpspp/assertion.h"
25 #include "libpspp/pool.h"
26 #include "output/tab.h"
27 #include "output/table.h"
28 #include "output/table-item.h"
29 #include "output/text-item.h"
30 #include "output/table-provider.h"
31
32 #include "gl/minmax.h"
33 #include "gl/xalloc.h"
34
35 #define H TABLE_HORZ
36 #define V TABLE_VERT
37
38 static const struct pivot_category *
39 find_category (const struct pivot_dimension *d, int dim_index,
40                const size_t *indexes, int row_ofs)
41 {
42   size_t index = indexes[dim_index];
43   assert (index < d->n_leaves);
44   for (const struct pivot_category *c = d->presentation_leaves[index];
45        c; c = c->parent)
46     {
47       if (!row_ofs)
48         return c;
49
50       row_ofs -= 1 + c->extra_depth;
51       if (row_ofs < 0)
52         return NULL;
53     }
54   return NULL;
55 }
56
57 static struct area_style *
58 area_style_override (struct pool *pool,
59                      const struct area_style *in,
60                      const struct cell_style *cell_,
61                      const struct font_style *font_)
62 {
63   const struct cell_style *cell = cell_ ? cell_ : &in->cell_style;
64   const struct font_style *font = font_ ? font_ : &in->font_style;
65
66   struct area_style *out = (pool
67                             ? pool_alloc (pool, sizeof *out)
68                             : xmalloc (sizeof *out));
69   *out = (struct area_style) {
70     .cell_style.halign = cell->halign,
71     .cell_style.valign = cell->valign,
72     .cell_style.decimal_offset = cell->decimal_offset,
73     .cell_style.margin[H][0] = cell->margin[H][0],
74     .cell_style.margin[H][1] = cell->margin[H][1],
75     .cell_style.margin[V][0] = cell->margin[V][0],
76     .cell_style.margin[V][1] = cell->margin[V][1],
77     .font_style.fg[0] = font->fg[0],
78     .font_style.fg[1] = font->fg[1],
79     .font_style.bg[0] = font->bg[0],
80     .font_style.bg[1] = font->bg[1],
81     .font_style.typeface = (font->typeface
82                             ? pool_strdup (pool, font->typeface)
83                             : NULL),
84     .font_style.size = font->size,
85     .font_style.bold = font->bold,
86     .font_style.italic = font->italic,
87     .font_style.underline = font->underline,
88     .font_style.markup = font->markup,
89   };
90   return out;
91 }
92
93 static void
94 fill_cell (struct tab_table *t, int x1, int y1, int x2, int y2,
95            const struct area_style *style, int style_idx,
96            const struct pivot_value *value, struct footnote **footnotes,
97            enum settings_value_show show_values,
98            enum settings_value_show show_variables,
99            bool rotate_label)
100 {
101
102   struct string s = DS_EMPTY_INITIALIZER;
103   int opts = style_idx << TAB_STYLE_SHIFT;
104   if (value)
105     {
106       bool numeric = pivot_value_format_body (value, show_values,
107                                               show_variables, &s);
108       if (numeric)
109         opts |= TAB_NUMERIC;
110       if (value->font_style && value->font_style->markup)
111         opts |= TAB_MARKUP;
112       if (rotate_label)
113         opts |= TAB_ROTATE;
114     }
115   tab_joint_text (t, x1, y1, x2, y2, opts, ds_cstr (&s));
116   ds_destroy (&s);
117
118   if (value)
119     {
120       if (value->cell_style || value->font_style)
121         tab_add_style (t, x1, y1,
122                        area_style_override (t->container, style,
123                                             value->cell_style,
124                                             value->font_style));
125
126       for (size_t i = 0; i < value->n_footnotes; i++)
127         tab_add_footnote (t, x1, y1, footnotes[value->footnotes[i]->idx]);
128     }
129 }
130
131 static struct table_item_text *
132 pivot_value_to_table_item_text (const struct pivot_value *value,
133                                 const struct area_style *area,
134                                 struct footnote **footnotes,
135                                 enum settings_value_show show_values,
136                                 enum settings_value_show show_variables)
137 {
138   if (!value)
139     return NULL;
140
141   struct string s = DS_EMPTY_INITIALIZER;
142   pivot_value_format_body (value, show_values, show_variables, &s);
143
144   struct table_item_text *text = xmalloc (sizeof *text);
145   *text = (struct table_item_text) {
146     .content = ds_steal_cstr (&s),
147     .footnotes = xnmalloc (value->n_footnotes, sizeof *text->footnotes),
148     .n_footnotes = value->n_footnotes,
149     .style = area_style_override (
150       NULL, area, value->cell_style, value->font_style),
151   };
152
153   for (size_t i = 0; i < value->n_footnotes; i++)
154     text->footnotes[i] = footnotes[value->footnotes[i]->idx];
155
156   return text;
157 }
158
159 static int
160 get_table_rule (const struct table_border_style *styles,
161                 enum pivot_border style_idx)
162 {
163   return styles[style_idx].stroke | (style_idx << TAB_RULE_STYLE_SHIFT);
164 }
165
166 static void
167 draw_line (struct tab_table *t, const struct table_border_style *styles,
168            enum pivot_border style_idx,
169            enum table_axis axis, int a, int b0, int b1)
170 {
171   int rule = get_table_rule (styles, style_idx);
172   if (axis == H)
173     tab_hline (t, rule, b0, b1, a);
174   else
175     tab_vline (t, rule, a, b0, b1);
176 }
177
178 static void
179 compose_headings (struct tab_table *t,
180                   const struct pivot_axis *a_axis, enum table_axis a,
181                   const struct pivot_axis *b_axis,
182                   const struct table_border_style *borders,
183                   enum pivot_border dim_col_horz,
184                   enum pivot_border dim_col_vert,
185                   enum pivot_border cat_col_horz,
186                   enum pivot_border cat_col_vert,
187                   const size_t *column_enumeration, size_t n_columns,
188                   const struct area_style *label_style, int label_style_idx,
189                   const struct area_style *corner_style,
190                   struct footnote **footnotes,
191                   enum settings_value_show show_values,
192                   enum settings_value_show show_variables,
193                   bool rotate_inner_labels, bool rotate_outer_labels)
194 {
195   enum table_axis b = !a;
196   int b_size = a_axis->label_depth;
197   int a_ofs = b_axis->label_depth;
198
199   if (!a_axis->n_dimensions || !n_columns || !b_size)
200     return;
201
202   int bottom_row = b_size - 1;
203   const int stride = MAX (1, a_axis->n_dimensions);
204   for (int dim_index = 0; dim_index < a_axis->n_dimensions; dim_index++)
205     {
206       const struct pivot_dimension *d = a_axis->dimensions[dim_index];
207       if (d->hide_all_labels)
208         continue;
209
210       for (int row_ofs = 0; row_ofs < d->label_depth; row_ofs++)
211         {
212           for (size_t x1 = 0; x1 < n_columns; )
213             {
214               const struct pivot_category *c = find_category (
215                 d, dim_index, column_enumeration + x1 * stride, row_ofs);
216               if (!c)
217                 {
218                   x1++;
219                   continue;
220                 }
221
222               size_t x2;
223               for (x2 = x1 + 1; x2 < n_columns; x2++)
224                 {
225                   const struct pivot_category *c2 = find_category (
226                     d, dim_index, column_enumeration + x2 * stride, row_ofs);
227                   if (c != c2)
228                     break;
229                 }
230
231               int y1 = bottom_row - row_ofs - c->extra_depth;
232               int y2 = bottom_row - row_ofs + 1;
233               bool is_outer_row = y1 == 0;
234               bool is_inner_row = y2 == b_size;
235               if (pivot_category_is_leaf (c) || c->show_label)
236                 {
237                   int bb[TABLE_N_AXES][2];
238                   bb[a][0] = x1 + a_ofs;
239                   bb[a][1] = x2 + a_ofs - 1;
240                   bb[b][0] = y1;
241                   bb[b][1] = y2 - 1;
242                   bool rotate = ((rotate_inner_labels && is_inner_row)
243                                  || (rotate_outer_labels && is_outer_row));
244                   fill_cell (t, bb[H][0], bb[V][0], bb[H][1], bb[V][1],
245                              label_style, label_style_idx, c->name, footnotes,
246                              show_values, show_variables, rotate);
247
248                   if (pivot_category_is_leaf (c) && x2 + 1 <= n_columns)
249                     {
250                       enum pivot_border style
251                         = (y1 == 0 && a_axis->label_depth > d->label_depth
252                            ? dim_col_vert
253                            : cat_col_vert);
254                       draw_line (t, borders, style, b, x2 + a_ofs, y1,
255                                  t->table.n[b] - 1);
256                     }
257                   if (pivot_category_is_leaf (c) && x1 > 0)
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, x1 + a_ofs, y1,
264                                  t->table.n[b] - 1);
265                     }
266                 }
267               if (c->parent && c->parent->show_label)
268                 draw_line (t, borders, cat_col_horz, a, y1,
269                            x1 + a_ofs, x2 + a_ofs - 1);
270
271               x1 = x2;
272             }
273         }
274
275       if (d->root->show_label_in_corner && a_ofs > 0)
276         {
277           int bb[TABLE_N_AXES][2];
278           bb[a][0] = a_ofs - 1;
279           bb[a][1] = a_ofs - 1;
280           bb[b][0] = bottom_row - d->label_depth + 1;
281           bb[b][1] = bottom_row;
282           fill_cell (t, bb[H][0], bb[V][0], bb[H][1], bb[V][1],
283                      corner_style, PIVOT_AREA_CORNER, d->root->name, footnotes,
284                      show_values, show_variables, false);
285         }
286
287       if (dim_index > 1)
288         draw_line (t, borders, dim_col_horz, a, bottom_row + 1, a_ofs,
289                    t->table.n[a] - 1);
290
291       bottom_row -= d->label_depth;
292     }
293 }
294
295 static void
296 pivot_table_submit_layer (const struct pivot_table *pt,
297                           const size_t *layer_indexes)
298 {
299   const size_t *pindexes[PIVOT_N_AXES]
300     = { [PIVOT_AXIS_LAYER] = layer_indexes };
301
302   struct string layer_label = DS_EMPTY_INITIALIZER;
303   const struct pivot_axis *layer_axis = &pt->axes[PIVOT_AXIS_LAYER];
304   for (size_t i = 0; i < layer_axis->n_dimensions; i++)
305     {
306       const struct pivot_dimension *d = layer_axis->dimensions[i];
307       if (d->n_leaves)
308         {
309           if (!ds_is_empty (&layer_label))
310             ds_put_byte (&layer_label, '\n');
311           pivot_value_format (d->root->name, pt->show_values,
312                               pt->show_variables, &layer_label);
313           ds_put_cstr (&layer_label, ": ");
314           pivot_value_format (d->data_leaves[layer_indexes[i]]->name,
315                               pt->show_values, pt->show_variables,
316                               &layer_label);
317         }
318     }
319
320   size_t body[TABLE_N_AXES];
321   size_t *column_enumeration = pivot_table_enumerate_axis (
322     pt, PIVOT_AXIS_COLUMN, layer_indexes, pt->omit_empty, &body[H]);
323   size_t *row_enumeration = pivot_table_enumerate_axis (
324     pt, PIVOT_AXIS_ROW, layer_indexes, pt->omit_empty, &body[V]);
325
326   int stub[TABLE_N_AXES] = {
327     [H] = pt->axes[PIVOT_AXIS_ROW].label_depth,
328     [V] = pt->axes[PIVOT_AXIS_COLUMN].label_depth,
329   };
330   struct tab_table *table = tab_create (body[H] + stub[H],
331                                         body[V] + stub[V]);
332   tab_headers (table, stub[H], 0, stub[V], 0);
333
334   for (size_t i = 0; i < PIVOT_N_AREAS; i++)
335     table->styles[i] = area_style_override (table->container, &pt->areas[i],
336                                             NULL, NULL);
337
338   for (size_t i = 0; i < PIVOT_N_BORDERS; i++)
339     {
340       const struct table_border_style *in = &pt->borders[i];
341       table->rule_colors[i] = pool_alloc (table->container,
342                                           sizeof *table->rule_colors[i]);
343       struct cell_color *out = table->rule_colors[i];
344       out->alpha = in->color.alpha;
345       out->r = in->color.r;
346       out->g = in->color.g;
347       out->b = in->color.b;
348     }
349
350   struct footnote **footnotes = xcalloc (pt->n_footnotes, sizeof *footnotes);
351   for (size_t i = 0; i < pt->n_footnotes; i++)
352     {
353       char *content = pivot_value_to_string (
354         pt->footnotes[i]->content, pt->show_values, pt->show_variables);
355       char *marker = pivot_value_to_string (
356         pt->footnotes[i]->marker, pt->show_values, pt->show_variables);
357       footnotes[i] = tab_create_footnote (
358         table, i, content, marker,
359         area_style_override (table->container, &pt->areas[PIVOT_AREA_FOOTER],
360                              pt->footnotes[i]->content->cell_style,
361                              pt->footnotes[i]->content->font_style));
362       free (marker);
363       free (content);
364     }
365
366   compose_headings (table,
367                     &pt->axes[PIVOT_AXIS_COLUMN], H, &pt->axes[PIVOT_AXIS_ROW],
368                     pt->borders,
369                     PIVOT_BORDER_DIM_COL_HORZ,
370                     PIVOT_BORDER_DIM_COL_VERT,
371                     PIVOT_BORDER_CAT_COL_HORZ,
372                     PIVOT_BORDER_CAT_COL_VERT,
373                     column_enumeration, body[H],
374                     &pt->areas[PIVOT_AREA_COLUMN_LABELS],
375                     PIVOT_AREA_COLUMN_LABELS,
376                     &pt->areas[PIVOT_AREA_CORNER], footnotes,
377                     pt->show_values, pt->show_variables,
378                     pt->rotate_inner_column_labels, false);
379
380   compose_headings (table,
381                     &pt->axes[PIVOT_AXIS_ROW], V, &pt->axes[PIVOT_AXIS_COLUMN],
382                     pt->borders,
383                     PIVOT_BORDER_DIM_ROW_VERT,
384                     PIVOT_BORDER_DIM_ROW_HORZ,
385                     PIVOT_BORDER_CAT_ROW_VERT,
386                     PIVOT_BORDER_CAT_ROW_HORZ,
387                     row_enumeration, body[V],
388                     &pt->areas[PIVOT_AREA_ROW_LABELS],
389                     PIVOT_AREA_ROW_LABELS,
390                     &pt->areas[PIVOT_AREA_CORNER], footnotes,
391                     pt->show_values, pt->show_variables,
392                     false, pt->rotate_outer_row_labels);
393
394   size_t *dindexes = xcalloc (pt->n_dimensions, sizeof *dindexes);
395   size_t y = 0;
396   PIVOT_ENUMERATION_FOR_EACH (pindexes[PIVOT_AXIS_ROW], row_enumeration,
397                               &pt->axes[PIVOT_AXIS_ROW])
398     {
399       size_t x = 0;
400       PIVOT_ENUMERATION_FOR_EACH (pindexes[PIVOT_AXIS_COLUMN],
401                                   column_enumeration,
402                                   &pt->axes[PIVOT_AXIS_COLUMN])
403         {
404           pivot_table_convert_indexes_ptod (pt, pindexes, dindexes);
405           const struct pivot_value *value = pivot_table_get (pt, dindexes);
406           fill_cell (table,
407                      x + stub[H], y + stub[V],
408                      x + stub[H], y + stub[V],
409                      &pt->areas[PIVOT_AREA_DATA], PIVOT_AREA_DATA,
410                      value, footnotes,
411                      pt->show_values, pt->show_variables, false);
412
413           x++;
414         }
415
416       y++;
417     }
418   free (dindexes);
419
420   if (pt->corner_text && stub[H] && stub[V])
421     fill_cell (table, 0, 0, stub[H] - 1, stub[V] - 1,
422                &pt->areas[PIVOT_AREA_CORNER], PIVOT_AREA_CORNER,
423                pt->corner_text, footnotes,
424                pt->show_values, pt->show_variables, false);
425
426   if (tab_nc (table) && tab_nr (table))
427     {
428       tab_hline (
429         table, get_table_rule (pt->borders, PIVOT_BORDER_INNER_TOP),
430         0, tab_nc (table) - 1, 0);
431       tab_hline (
432         table, get_table_rule (pt->borders, PIVOT_BORDER_INNER_BOTTOM),
433         0, tab_nc (table) - 1, tab_nr (table));
434       tab_vline (
435         table, get_table_rule (pt->borders, PIVOT_BORDER_INNER_LEFT),
436         0, 0, tab_nr (table) - 1);
437       tab_vline (
438         table, get_table_rule (pt->borders, PIVOT_BORDER_INNER_RIGHT),
439         tab_nc (table), 0, tab_nr (table) - 1);
440
441       if (stub[V])
442         tab_hline (
443           table, get_table_rule (pt->borders, PIVOT_BORDER_DATA_TOP),
444           0, tab_nc (table) - 1, stub[V]);
445       if (stub[H])
446         tab_vline (
447           table, get_table_rule (pt->borders, PIVOT_BORDER_DATA_LEFT),
448           stub[H], 0, tab_nr (table) - 1);
449
450     }
451   free (column_enumeration);
452   free (row_enumeration);
453
454   struct table_item *ti = table_item_create (&table->table, NULL, NULL);
455
456   if (pt->title)
457     {
458       struct table_item_text *title = pivot_value_to_table_item_text (
459         pt->title, &pt->areas[PIVOT_AREA_TITLE], footnotes,
460         pt->show_values, pt->show_variables);
461       table_item_set_title (ti, title);
462       table_item_text_destroy (title);
463     }
464
465   if (!ds_is_empty (&layer_label))
466     {
467       struct table_item_text *layers = table_item_text_create (
468         ds_cstr (&layer_label));
469       layers->style = area_style_override (NULL, &pt->areas[PIVOT_AREA_LAYERS],
470                                            NULL, NULL);
471       table_item_set_layers (ti, layers);
472       table_item_text_destroy (layers);
473
474       ds_destroy (&layer_label);
475     }
476
477   if (pt->caption)
478     {
479       struct table_item_text *caption = pivot_value_to_table_item_text (
480         pt->caption, &pt->areas[PIVOT_AREA_CAPTION], footnotes,
481         pt->show_values, pt->show_variables);
482       table_item_set_caption (ti, caption);
483       table_item_text_destroy (caption);
484     }
485
486   free (footnotes);
487   table_item_submit (ti);
488 }
489
490 void
491 pivot_table_flatten (const struct pivot_table *pt)
492 {
493   int old_decimal = settings_get_decimal_char (FMT_COMMA);
494   if (pt->decimal == '.' || pt->decimal == ',')
495     settings_set_decimal_char (pt->decimal);
496
497   pivot_table_submit_layer (pt, pt->current_layer);
498
499   settings_set_decimal_char (old_decimal);
500 }