pivot-table: Implement hiding footnotes.
[pspp] / src / output / spv / spv-writer.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2019 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 "output/spv/spv-writer.h"
20
21 #include <inttypes.h>
22 #include <libxml/xmlwriter.h>
23 #include <math.h>
24 #include <stdlib.h>
25 #include <time.h>
26
27 #include "libpspp/array.h"
28 #include "libpspp/assertion.h"
29 #include "libpspp/cast.h"
30 #include "libpspp/float-format.h"
31 #include "libpspp/integer-format.h"
32 #include "libpspp/temp-file.h"
33 #include "libpspp/version.h"
34 #include "libpspp/zip-writer.h"
35 #include "output/page-setup-item.h"
36 #include "output/pivot-table.h"
37 #include "output/text-item.h"
38
39 #include "gl/xalloc.h"
40 #include "gl/xvasprintf.h"
41
42 #include "gettext.h"
43 #define _(msgid) gettext (msgid)
44 #define N_(msgid) (msgid)
45
46 struct spv_writer
47   {
48     struct zip_writer *zw;
49
50     FILE *heading;
51     int heading_depth;
52     xmlTextWriter *xml;
53
54     int n_tables;
55
56     int n_headings;
57     struct page_setup *page_setup;
58     bool need_page_break;
59   };
60
61 char * WARN_UNUSED_RESULT
62 spv_writer_open (const char *filename, struct spv_writer **writerp)
63 {
64   *writerp = NULL;
65
66   struct zip_writer *zw = zip_writer_create (filename);
67   if (!zw)
68     return xasprintf (_("%s: create failed"), filename);
69
70   struct spv_writer *w = xmalloc (sizeof *w);
71   *w = (struct spv_writer) { .zw = zw };
72   *writerp = w;
73   return NULL;
74 }
75
76 char * WARN_UNUSED_RESULT
77 spv_writer_close (struct spv_writer *w)
78 {
79   if (!w)
80     return NULL;
81
82   zip_writer_add_string (w->zw, "META-INF/MANIFEST.MF", "allowPivoting=true");
83
84   while (w->heading_depth)
85     spv_writer_close_heading (w);
86
87   char *error = NULL;
88   if (!zip_writer_close (w->zw))
89     error = xstrdup (_("I/O error writing SPV file"));
90
91   page_setup_destroy (w->page_setup);
92   free (w);
93   return error;
94 }
95
96 void
97 spv_writer_set_page_setup (struct spv_writer *w,
98                            const struct page_setup *page_setup)
99 {
100   page_setup_destroy (w->page_setup);
101   w->page_setup = page_setup_clone (page_setup);
102 }
103
104 static void
105 write_attr (struct spv_writer *w, const char *name, const char *value)
106 {
107   xmlTextWriterWriteAttribute (w->xml,
108                                CHAR_CAST (xmlChar *, name),
109                                CHAR_CAST (xmlChar *, value));
110 }
111
112 static void PRINTF_FORMAT (3, 4)
113 write_attr_format (struct spv_writer *w, const char *name,
114                    const char *format, ...)
115 {
116   va_list args;
117   va_start (args, format);
118   char *value = xvasprintf (format, args);
119   va_end (args);
120
121   write_attr (w, name, value);
122   free (value);
123 }
124
125 static void
126 start_elem (struct spv_writer *w, const char *name)
127 {
128   xmlTextWriterStartElement (w->xml, CHAR_CAST (xmlChar *, name));
129 }
130
131 static void
132 end_elem (struct spv_writer *w)
133 {
134   xmlTextWriterEndElement (w->xml);
135 }
136
137 static void
138 write_text (struct spv_writer *w, const char *text)
139 {
140   xmlTextWriterWriteString (w->xml, CHAR_CAST (xmlChar *, text));
141 }
142
143 static void
144 write_page_heading (struct spv_writer *w, const struct page_heading *h,
145                     const char *name)
146 {
147   start_elem (w, name);
148   if (h->n)
149     {
150       start_elem (w, "pageParagraph");
151       for (size_t i = 0; i < h->n; i++)
152         {
153           start_elem (w, "text");
154           write_attr (w, "type", "title");
155           write_text (w, h->paragraphs[i].markup); /* XXX */
156           end_elem (w);
157         }
158       end_elem (w);
159     }
160   end_elem (w);
161 }
162
163 static void
164 write_page_setup (struct spv_writer *w, const struct page_setup *ps)
165 {
166   start_elem (w, "pageSetup");
167   write_attr_format (w, "initial-page-number", "%d", ps->initial_page_number);
168   write_attr (w, "chart-size",
169               (ps->chart_size == PAGE_CHART_AS_IS ? "as-is"
170                : ps->chart_size == PAGE_CHART_FULL_HEIGHT ? "full-height"
171                : ps->chart_size == PAGE_CHART_HALF_HEIGHT ? "half-height"
172                : "quarter-height"));
173   write_attr_format (w, "margin-left", "%.2fin", ps->margins[TABLE_HORZ][0]);
174   write_attr_format (w, "margin-right", "%.2fin", ps->margins[TABLE_HORZ][1]);
175   write_attr_format (w, "margin-top", "%.2fin", ps->margins[TABLE_VERT][0]);
176   write_attr_format (w, "margin-bottom", "%.2fin", ps->margins[TABLE_VERT][1]);
177   write_attr_format (w, "paper-height", "%.2fin", ps->paper[TABLE_VERT]);
178   write_attr_format (w, "paper-width", "%.2fin", ps->paper[TABLE_HORZ]);
179   write_attr (w, "reference-orientation",
180               ps->orientation == PAGE_PORTRAIT ? "portrait" : "landscape");
181   write_attr_format (w, "space-after", "%.1fpt", ps->object_spacing * 72.0);
182   write_page_heading (w, &ps->headings[0], "pageHeader");
183   write_page_heading (w, &ps->headings[1], "pageFooter");
184   end_elem (w);
185 }
186
187 static bool
188 spv_writer_open_file (struct spv_writer *w)
189 {
190   w->heading = create_temp_file ();
191   if (!w->heading)
192     return false;
193
194   w->xml = xmlNewTextWriter (xmlOutputBufferCreateFile (w->heading, NULL));
195   xmlTextWriterStartDocument (w->xml, NULL, "UTF-8", NULL);
196   start_elem (w, "heading");
197
198   time_t t = time (NULL);
199   struct tm *tm = gmtime (&t);
200   char *tm_s = asctime (tm);
201   write_attr (w, "creation-date-time", tm_s);
202
203   write_attr (w, "creator", version);
204
205   write_attr (w, "creator-version", "21");
206
207   write_attr (w, "xmlns", "http://xml.spss.com/spss/viewer/viewer-tree");
208   write_attr (w, "xmlns:vps", "http://xml.spss.com/spss/viewer/viewer-pagesetup");
209   write_attr (w, "xmlns:vtx", "http://xml.spss.com/spss/viewer/viewer-text");
210   write_attr (w, "xmlns:vtb", "http://xml.spss.com/spss/viewer/viewer-table");
211
212   start_elem (w, "label");
213   write_text (w, _("Output"));
214   end_elem (w);
215
216   if (w->page_setup)
217     {
218       write_page_setup (w, w->page_setup);
219
220       page_setup_destroy (w->page_setup);
221       w->page_setup = NULL;
222     }
223
224   return true;
225 }
226
227 void
228 spv_writer_open_heading (struct spv_writer *w, const char *command_id,
229                          const char *label)
230 {
231   if (!w->heading)
232     {
233       if (!spv_writer_open_file (w))
234         return;
235     }
236
237   w->heading_depth++;
238   start_elem (w, "heading");
239   write_attr (w, "commandName", command_id);
240   /* XXX locale */
241   /* XXX olang */
242
243   start_elem (w, "label");
244   write_text (w, label);
245   end_elem (w);
246 }
247
248 static void
249 spv_writer_close_file (struct spv_writer *w, const char *infix)
250 {
251   if (!w->heading)
252     return;
253
254   end_elem (w);
255   xmlTextWriterEndDocument (w->xml);
256   xmlFreeTextWriter (w->xml);
257
258   char *member_name = xasprintf ("outputViewer%010d%s.xml",
259                                  w->n_headings++, infix);
260   zip_writer_add (w->zw, w->heading, member_name);
261   free (member_name);
262
263   w->heading = NULL;
264 }
265
266 void
267 spv_writer_close_heading (struct spv_writer *w)
268 {
269   const char *infix = "";
270   if (w->heading_depth)
271     {
272       infix = "_heading";
273       end_elem (w);
274       w->heading_depth--;
275     }
276
277   if (!w->heading_depth)
278     spv_writer_close_file (w, infix);
279 }
280
281 static void
282 start_container (struct spv_writer *w)
283 {
284   start_elem (w, "container");
285   write_attr (w, "visibility", "visible");
286   if (w->need_page_break)
287     {
288       write_attr (w, "page-break-before", "always");
289       w->need_page_break = false;
290     }
291 }
292
293 void
294 spv_writer_put_text (struct spv_writer *w, const struct text_item *text,
295                      const char *command_id)
296 {
297   bool initial_depth = w->heading_depth;
298   if (!initial_depth)
299     spv_writer_open_file (w);
300
301   start_container (w);
302
303   start_elem (w, "label");
304   write_text (w, (text->type == TEXT_ITEM_TITLE ? "Title"
305                   : text->type == TEXT_ITEM_PAGE_TITLE ? "Page Title"
306                   : "Log"));
307   end_elem (w);
308
309   start_elem (w, "vtx:text");
310   write_attr (w, "type", (text->type == TEXT_ITEM_TITLE ? "title"
311                           : text->type == TEXT_ITEM_PAGE_TITLE ? "page-title"
312                           : "log"));
313   if (command_id)
314     write_attr (w, "commandName", command_id);
315
316   start_elem (w, "html");
317   write_text (w, text->text);   /* XXX */
318   end_elem (w); /* html */
319   end_elem (w); /* vtx:text */
320   end_elem (w); /* container */
321
322   if (!initial_depth)
323     spv_writer_close_file (w, "");
324 }
325
326 static cairo_status_t
327 write_to_zip (void *zw_, const unsigned char *data, unsigned int length)
328 {
329   struct zip_writer *zw = zw_;
330
331   zip_writer_add_write (zw, data, length);
332   return CAIRO_STATUS_SUCCESS;
333 }
334
335 void
336 spv_writer_put_image (struct spv_writer *w, cairo_surface_t *image)
337 {
338   bool initial_depth = w->heading_depth;
339   if (!initial_depth)
340     spv_writer_open_file (w);
341
342   char *uri = xasprintf ("%010d_Imagegeneric.png", ++w->n_tables);
343
344   start_container (w);
345
346   start_elem (w, "label");
347   write_text (w, "Image");
348   end_elem (w);
349
350   start_elem (w, "object");
351   write_attr (w, "type", "unknown");
352   write_attr (w, "uri", uri);
353   end_elem (w); /* object */
354   end_elem (w); /* container */
355
356   if (!initial_depth)
357     spv_writer_close_file (w, "");
358
359   zip_writer_add_start (w->zw, uri);
360   cairo_surface_write_to_png_stream (image, write_to_zip, w->zw);
361   zip_writer_add_finish (w->zw);
362
363   free (uri);
364 }
365
366 void
367 spv_writer_eject_page (struct spv_writer *w)
368 {
369   w->need_page_break = true;
370 }
371 \f
372 #define H TABLE_HORZ
373 #define V TABLE_VERT
374
375 struct buf
376   {
377     uint8_t *data;
378     size_t len;
379     size_t allocated;
380   };
381
382 static uint8_t *
383 put_uninit (struct buf *b, size_t n)
384 {
385   while (b->allocated - b->len < n)
386     b->data = x2nrealloc (b->data, &b->allocated, sizeof b->data);
387   uint8_t *p = &b->data[b->len];
388   b->len += n;
389   return p;
390 }
391
392 static void
393 put_byte (struct buf *b, uint8_t byte)
394 {
395   *put_uninit (b, 1) = byte;
396 }
397
398 static void
399 put_bool (struct buf *b, bool boolean)
400 {
401   put_byte (b, boolean);
402 }
403
404 static void
405 put_bytes (struct buf *b, const char *bytes, size_t n)
406 {
407   memcpy (put_uninit (b, n), bytes, n);
408 }
409
410 static void
411 put_u16 (struct buf *b, uint16_t x)
412 {
413   put_uint16 (native_to_le16 (x), put_uninit (b, sizeof x));
414 }
415
416 static void
417 put_u32 (struct buf *b, uint32_t x)
418 {
419   put_uint32 (native_to_le32 (x), put_uninit (b, sizeof x));
420 }
421
422 static void
423 put_u64 (struct buf *b, uint64_t x)
424 {
425   put_uint64 (native_to_le64 (x), put_uninit (b, sizeof x));
426 }
427
428 static void
429 put_be32 (struct buf *b, uint32_t x)
430 {
431   put_uint32 (native_to_be32 (x), put_uninit (b, sizeof x));
432 }
433
434 static void
435 put_double (struct buf *b, double x)
436 {
437   float_convert (FLOAT_NATIVE_DOUBLE, &x,
438                  FLOAT_IEEE_DOUBLE_LE, put_uninit (b, 8));
439 }
440
441 static void
442 put_float (struct buf *b, float x)
443 {
444   float_convert (FLOAT_NATIVE_FLOAT, &x,
445                  FLOAT_IEEE_SINGLE_LE, put_uninit (b, 4));
446 }
447
448 static void
449 put_string (struct buf *b, const char *s_)
450 {
451   const char *s = s_ ? s_ : "";
452   size_t len = strlen (s);
453   put_u32 (b, len);
454   memcpy (put_uninit (b, len), s, len);
455 }
456
457 static void
458 put_bestring (struct buf *b, const char *s_)
459 {
460   const char *s = s_ ? s_ : "";
461   size_t len = strlen (s);
462   put_be32 (b, len);
463   memcpy (put_uninit (b, len), s, len);
464 }
465
466 static size_t
467 start_count (struct buf *b)
468 {
469   put_u32 (b, 0);
470   return b->len;
471 }
472
473 static void
474 end_count_u32 (struct buf *b, size_t start)
475 {
476   put_uint32 (native_to_le32 (b->len - start), &b->data[start - 4]);
477 }
478
479 static void
480 end_count_be32 (struct buf *b, size_t start)
481 {
482   put_uint32 (native_to_be32 (b->len - start), &b->data[start - 4]);
483 }
484
485 static void
486 put_color (struct buf *buf, const struct cell_color *color)
487 {
488   char *s = xasprintf ("#%02"PRIx8"%02"PRIx8"%02"PRIx8,
489                        color->r, color->g, color->b);
490   put_string (buf, s);
491   free (s);
492 }
493
494 static void
495 put_font_style (struct buf *buf, const struct font_style *font_style)
496 {
497   put_bool (buf, font_style->bold);
498   put_bool (buf, font_style->italic);
499   put_bool (buf, font_style->underline);
500   put_bool (buf, 1);
501   put_color (buf, &font_style->fg[0]);
502   put_color (buf, &font_style->bg[0]);
503   put_string (buf, font_style->typeface ? font_style->typeface : "SansSerif");
504   put_byte (buf, ceil (font_style->size * 1.33));
505 }
506
507 static void
508 put_halign (struct buf *buf, enum table_halign halign,
509             uint32_t mixed, uint32_t decimal)
510 {
511   put_u32 (buf, (halign == TABLE_HALIGN_RIGHT ? 4
512                  : halign == TABLE_HALIGN_LEFT ? 2
513                  : halign == TABLE_HALIGN_CENTER ? 0
514                  : halign == TABLE_HALIGN_MIXED ? mixed
515                  : decimal));
516 }
517
518 static void
519 put_valign (struct buf *buf, enum table_valign valign)
520 {
521   put_u32 (buf, (valign == TABLE_VALIGN_TOP ? 1
522                  : valign == TABLE_VALIGN_CENTER ? 0
523                  : 3));
524 }
525
526 static void
527 put_cell_style (struct buf *buf, const struct cell_style *cell_style)
528 {
529   put_halign (buf, cell_style->halign, 0xffffffad, 6);
530   put_valign (buf, cell_style->valign);
531   put_double (buf, cell_style->decimal_offset);
532   put_u16 (buf, cell_style->margin[H][0]);
533   put_u16 (buf, cell_style->margin[H][1]);
534   put_u16 (buf, cell_style->margin[V][0]);
535   put_u16 (buf, cell_style->margin[V][1]);
536 }
537
538 static void UNUSED
539 put_style_pair (struct buf *buf, const struct font_style *font_style,
540                 const struct cell_style *cell_style)
541 {
542   if (font_style)
543     {
544       put_byte (buf, 0x31);
545       put_font_style (buf, font_style);
546     }
547   else
548     put_byte (buf, 0x58);
549
550   if (cell_style)
551     {
552       put_byte (buf, 0x31);
553       put_cell_style (buf, cell_style);
554     }
555   else
556     put_byte (buf, 0x58);
557 }
558
559 static void
560 put_value_mod (struct buf *buf, const struct pivot_value *value,
561                const char *template)
562 {
563   if (value->n_footnotes || value->n_subscripts
564       || template || value->font_style || value->cell_style)
565     {
566       put_byte (buf, 0x31);
567
568       /* Footnotes. */
569       put_u32 (buf, value->n_footnotes);
570       for (size_t i = 0; i < value->n_footnotes; i++)
571         put_u16 (buf, value->footnote_indexes[i]);
572
573       /* Subscripts. */
574       put_u32 (buf, value->n_subscripts);
575       for (size_t i = 0; i < value->n_subscripts; i++)
576         put_string (buf, value->subscripts[i]);
577
578       /* Template and style. */
579       uint32_t v3_start = start_count (buf);
580       uint32_t template_string_start = start_count (buf);
581       if (template)
582         {
583           uint32_t inner_start = start_count (buf);
584           end_count_u32 (buf, inner_start);
585
586           put_byte (buf, 0x31);
587           put_string (buf, template);
588         }
589       end_count_u32 (buf, template_string_start);
590       put_style_pair (buf, value->font_style, value->cell_style);
591       end_count_u32 (buf, v3_start);
592     }
593   else
594     put_byte (buf, 0x58);
595 }
596
597 static void
598 put_format (struct buf *buf, const struct fmt_spec *f, bool honor_small)
599 {
600   int type = f->type == FMT_F && honor_small ? 40 : fmt_to_io (f->type);
601   put_u32 (buf, (type << 16) | (f->w << 8) | f->d);
602 }
603
604 static int
605 show_values_to_spvlb (enum settings_value_show show)
606 {
607   return (show == SETTINGS_VALUE_SHOW_DEFAULT ? 0
608           : show == SETTINGS_VALUE_SHOW_VALUE ? 1
609           : show == SETTINGS_VALUE_SHOW_LABEL ? 2
610           : 3);
611 }
612
613 static void
614 put_show_values (struct buf *buf, enum settings_value_show show)
615 {
616   put_byte (buf, show_values_to_spvlb (show));
617 }
618
619 static void
620 put_value (struct buf *buf, const struct pivot_value *value)
621 {
622   switch (value->type)
623     {
624     case PIVOT_VALUE_NUMERIC:
625       if (value->numeric.var_name || value->numeric.value_label)
626         {
627           put_byte (buf, 2);
628           put_value_mod (buf, value, NULL);
629           put_format (buf, &value->numeric.format, value->numeric.honor_small);
630           put_double (buf, value->numeric.x);
631           put_string (buf, value->numeric.var_name);
632           put_string (buf, value->numeric.value_label);
633           put_show_values (buf, value->numeric.show);
634         }
635       else
636         {
637           put_byte (buf, 1);
638           put_value_mod (buf, value, NULL);
639           put_format (buf, &value->numeric.format, value->numeric.honor_small);
640           put_double (buf, value->numeric.x);
641         }
642       break;
643
644     case PIVOT_VALUE_STRING:
645       put_byte (buf, 4);
646       put_value_mod (buf, value, NULL);
647       size_t len = strlen (value->string.s);
648       if (value->string.hex)
649         put_format (buf, &(struct fmt_spec) { FMT_AHEX, len * 2, 0 }, false);
650       else
651         put_format (buf, &(struct fmt_spec) { FMT_A, len, 0 }, false);
652       put_string (buf, value->string.value_label);
653       put_string (buf, value->string.var_name);
654       put_show_values (buf, value->string.show);
655       put_string (buf, value->string.s);
656       break;
657
658     case PIVOT_VALUE_VARIABLE:
659       put_byte (buf, 5);
660       put_value_mod (buf, value, NULL);
661       put_string (buf, value->variable.var_name);
662       put_string (buf, value->variable.var_label);
663       put_show_values (buf, value->variable.show);
664       break;
665
666     case PIVOT_VALUE_TEXT:
667       put_byte (buf, 3);
668       put_string (buf, value->text.local);
669       put_value_mod (buf, value, NULL);
670       put_string (buf, value->text.id);
671       put_string (buf, value->text.c);
672       put_byte (buf, 1);        /* XXX user-provided */
673       break;
674
675     case PIVOT_VALUE_TEMPLATE:
676       put_byte (buf, 0);
677       put_value_mod (buf, value, value->template.id);
678       put_string (buf, value->template.local);
679       put_u32 (buf, value->template.n_args);
680       for (size_t i = 0; i < value->template.n_args; i++)
681         {
682           const struct pivot_argument *arg = &value->template.args[i];
683           assert (arg->n >= 1);
684           if (arg->n > 1)
685             {
686               put_u32 (buf, arg->n);
687               put_u32 (buf, 0);
688               for (size_t j = 0; j < arg->n; j++)
689                 {
690                   if (j > 0)
691                     put_bytes (buf, "\0\0\0\0", 4);
692                   put_value (buf, arg->values[j]);
693                 }
694             }
695           else
696             {
697               put_u32 (buf, 0);
698               put_value (buf, arg->values[0]);
699             }
700         }
701       break;
702
703     default:
704       NOT_REACHED ();
705     }
706 }
707
708 static void
709 put_optional_value (struct buf *buf, const struct pivot_value *value)
710 {
711   if (value)
712     {
713       put_byte (buf, 0x31);
714       put_value (buf, value);
715     }
716   else
717     put_byte (buf, 0x58);
718 }
719
720 static void
721 put_category (struct buf *buf, const struct pivot_category *c)
722 {
723   put_value (buf, c->name);
724   if (pivot_category_is_leaf (c))
725     {
726       put_bytes (buf, "\0\0\0", 3);
727       put_u32 (buf, 2);
728       put_u32 (buf, c->data_index);
729       put_u32 (buf, 0);
730     }
731   else
732     {
733       put_bytes (buf, "\0\0\1", 3);
734       put_u32 (buf, 0);         /* x23 */
735       put_u32 (buf, -1);
736       put_u32 (buf, c->n_subs);
737       for (size_t i = 0; i < c->n_subs; i++)
738         put_category (buf, c->subs[i]);
739     }
740 }
741
742 static void
743 put_y0 (struct buf *buf, const struct pivot_table *table)
744 {
745   put_u32 (buf, table->settings.epoch);
746   put_byte (buf, table->settings.decimal);
747   put_byte (buf, ',');
748 }
749
750 static void
751 put_custom_currency (struct buf *buf, const struct pivot_table *table)
752 {
753   put_u32 (buf, 5);
754   for (int i = 0; i < 5; i++)
755     {
756       enum fmt_type types[5] = { FMT_CCA, FMT_CCB, FMT_CCC, FMT_CCD, FMT_CCE };
757       char *cc = fmt_number_style_to_string (fmt_settings_get_style (
758                                                &table->settings, types[i]));
759       put_string (buf, cc);
760       free (cc);
761     }
762 }
763
764 static void
765 put_x1 (struct buf *buf, const struct pivot_table *table)
766 {
767   put_byte (buf, 0);            /* x14 */
768   put_byte (buf, table->show_title ? 1 : 10);
769   put_byte (buf, 0);            /* x16 */
770   put_byte (buf, 0);            /* lang */
771   put_show_values (buf, table->show_variables);
772   put_show_values (buf, table->show_values);
773   put_u32 (buf, -1);            /* x18 */
774   put_u32 (buf, -1);            /* x19 */
775   for (int i = 0; i < 17; i++)
776     put_byte (buf, 0);
777   put_bool (buf, false);        /* x20 */
778   put_byte (buf, table->show_caption);
779 }
780
781 static void
782 put_x2 (struct buf *buf)
783 {
784   put_u32 (buf, 0);             /* n-row-heights */
785   put_u32 (buf, 0);             /* n-style-map */
786   put_u32 (buf, 0);             /* n-styles */
787   put_u32 (buf, 0);
788 }
789
790 static void
791 put_y1 (struct buf *buf, const struct pivot_table *table)
792 {
793   put_string (buf, table->command_c);
794   put_string (buf, table->command_local);
795   put_string (buf, table->language);
796   put_string (buf, "UTF-8");    /* XXX */
797   put_string (buf, table->locale);
798   put_bytes (buf, "\0\0\1\1", 4);
799   put_y0 (buf, table);
800 }
801
802 static void
803 put_y2 (struct buf *buf, const struct pivot_table *table)
804 {
805   put_custom_currency (buf, table);
806   put_byte (buf, '.');
807   put_bool (buf, 0);
808 }
809
810 static void
811 put_x3 (struct buf *buf, const struct pivot_table *table)
812 {
813   put_byte (buf, 1);
814   put_byte (buf, 0);
815   put_byte (buf, 4);            /* x21 */
816   put_byte (buf, 0);
817   put_byte (buf, 0);
818   put_byte (buf, 0);
819   put_y1 (buf, table);
820   put_double (buf, table->small);
821   put_byte (buf, 1);
822   put_string (buf, table->dataset);
823   put_string (buf, table->datafile);
824   put_u32 (buf, 0);
825   put_u32 (buf, table->date);
826   put_u32 (buf, 0);
827   put_y2 (buf, table);
828 }
829
830 static void
831 put_light_table (struct buf *buf, uint64_t table_id,
832                  const struct pivot_table *table)
833 {
834   /* Header. */
835   put_bytes (buf, "\1\0", 2);
836   put_u32 (buf, 3);
837   put_bool (buf, true);
838   put_bool (buf, false);
839   put_bool (buf, table->rotate_inner_column_labels);
840   put_bool (buf, table->rotate_outer_row_labels);
841   put_bool (buf, true);
842   put_u32 (buf, 0x15);
843   put_u32 (buf, table->look->width_ranges[H][0]);
844   put_u32 (buf, table->look->width_ranges[H][1]);
845   put_u32 (buf, table->look->width_ranges[V][0]);
846   put_u32 (buf, table->look->width_ranges[V][1]);
847   put_u64 (buf, table_id);
848
849   /* Titles. */
850   put_value (buf, table->title);
851   put_value (buf, table->subtype);
852   put_optional_value (buf, table->title);
853   put_optional_value (buf, table->corner_text);
854   put_optional_value (buf, table->caption);
855
856   /* Footnotes. */
857   put_u32 (buf, table->n_footnotes);
858   for (size_t i = 0; i < table->n_footnotes; i++)
859     {
860       const struct pivot_footnote *f = table->footnotes[i];
861       put_value (buf, f->content);
862       put_optional_value (buf, f->marker);
863       put_u32 (buf, f->show ? 1 : -1);
864     }
865
866   /* Areas. */
867   for (size_t i = 0; i < PIVOT_N_AREAS; i++)
868     {
869       const struct table_area_style *a = &table->look->areas[i];
870       put_byte (buf, i + 1);
871       put_byte (buf, 0x31);
872       put_string (buf, (a->font_style.typeface
873                         ? a->font_style.typeface
874                         : "SansSerif"));
875       put_float (buf, ceil (a->font_style.size * 1.33));
876       put_u32 (buf, ((a->font_style.bold ? 1 : 0)
877                      | (a->font_style.italic ? 2 : 0)));
878       put_bool (buf, a->font_style.underline);
879       put_halign (buf, a->cell_style.halign, 64173, 61453);
880       put_valign (buf, a->cell_style.valign);
881
882       put_color (buf, &a->font_style.fg[0]);
883       put_color (buf, &a->font_style.bg[0]);
884
885       bool alt
886         = (!cell_color_equal (&a->font_style.fg[0], &a->font_style.fg[1])
887            || !cell_color_equal (&a->font_style.bg[0], &a->font_style.bg[1]));
888       put_bool (buf, alt);
889       if (alt)
890         {
891           put_color (buf, &a->font_style.fg[1]);
892           put_color (buf, &a->font_style.bg[1]);
893         }
894       else
895         {
896           put_string (buf, "");
897           put_string (buf, "");
898         }
899
900       put_u32 (buf, a->cell_style.margin[H][0]);
901       put_u32 (buf, a->cell_style.margin[H][1]);
902       put_u32 (buf, a->cell_style.margin[V][0]);
903       put_u32 (buf, a->cell_style.margin[V][1]);
904     }
905
906   /* Borders. */
907   uint32_t borders_start = start_count (buf);
908   put_be32 (buf, 1);
909   put_be32 (buf, PIVOT_N_BORDERS);
910   for (size_t i = 0; i < PIVOT_N_BORDERS; i++)
911     {
912       const struct table_border_style *b = &table->look->borders[i];
913       put_be32 (buf, i);
914       put_be32 (buf, (b->stroke == TABLE_STROKE_NONE ? 0
915                       : b->stroke == TABLE_STROKE_SOLID ? 1
916                       : b->stroke == TABLE_STROKE_DASHED ? 2
917                       : b->stroke == TABLE_STROKE_THICK ? 3
918                       : b->stroke == TABLE_STROKE_THIN ? 4
919                       : 5));
920       put_be32 (buf, ((b->color.alpha << 24)
921                       | (b->color.r << 16)
922                       | (b->color.g << 8)
923                       | b->color.b));
924     }
925   put_bool (buf, table->show_grid_lines);
926   put_bytes (buf, "\0\0\0", 3);
927   end_count_u32 (buf, borders_start);
928
929   /* Print Settings. */
930   uint32_t ps_start = start_count (buf);
931   put_be32 (buf, 1);
932   put_bool (buf, table->look->print_all_layers);
933   put_bool (buf, table->look->paginate_layers);
934   put_bool (buf, table->look->shrink_to_fit[H]);
935   put_bool (buf, table->look->shrink_to_fit[V]);
936   put_bool (buf, table->look->top_continuation);
937   put_bool (buf, table->look->bottom_continuation);
938   put_be32 (buf, table->look->n_orphan_lines);
939   put_bestring (buf, table->look->continuation);
940   end_count_u32 (buf, ps_start);
941
942   /* Table Settings. */
943   uint32_t ts_start = start_count (buf);
944   put_be32 (buf, 1);
945   put_be32 (buf, 4);
946   put_be32 (buf, 0);            /* XXX current_layer */
947   put_bool (buf, table->look->omit_empty);
948   put_bool (buf, table->look->row_labels_in_corner);
949   put_bool (buf, !table->look->show_numeric_markers);
950   put_bool (buf, table->look->footnote_marker_superscripts);
951   put_byte (buf, 0);
952   uint32_t keep_start = start_count (buf);
953   put_be32 (buf, 0);            /* n-row-breaks */
954   put_be32 (buf, 0);            /* n-column-breaks */
955   put_be32 (buf, 0);            /* n-row-keeps */
956   put_be32 (buf, 0);            /* n-column-keeps */
957   put_be32 (buf, 0);            /* n-row-point-keeps */
958   put_be32 (buf, 0);            /* n-column-point-keeps */
959   end_count_be32 (buf, keep_start);
960   put_bestring (buf, table->notes);
961   put_bestring (buf, table->look->name);
962   for (size_t i = 0; i < 82; i++)
963     put_byte (buf, 0);
964   end_count_u32 (buf, ts_start);
965
966   /* Formats. */
967   put_u32 (buf, 0);             /* n-widths */
968   put_string (buf, "en_US.ISO_8859-1:1987"); /* XXX */
969   put_u32 (buf, 0);                /* XXX current-layer */
970   put_bool (buf, 0);
971   put_bool (buf, 0);
972   put_bool (buf, 1);
973   put_y0 (buf, table);
974   put_custom_currency (buf, table);
975   uint32_t formats_start = start_count (buf);
976   uint32_t x1_start = start_count (buf);
977   put_x1 (buf, table);
978   uint32_t x2_start = start_count (buf);
979   put_x2 (buf);
980   end_count_u32 (buf, x2_start);
981   end_count_u32 (buf, x1_start);
982   uint32_t x3_start = start_count (buf);
983   put_x3 (buf, table);
984   end_count_u32 (buf, x3_start);
985   end_count_u32 (buf, formats_start);
986
987   /* Dimensions. */
988   put_u32 (buf, table->n_dimensions);
989   int *x2 = xnmalloc (table->n_dimensions, sizeof *x2);
990   for (size_t i = 0; i < table->axes[PIVOT_AXIS_LAYER].n_dimensions; i++)
991     x2[i] = 2;
992   for (size_t i = 0; i < table->axes[PIVOT_AXIS_ROW].n_dimensions; i++)
993     x2[i + table->axes[PIVOT_AXIS_LAYER].n_dimensions] = 0;
994   for (size_t i = 0; i < table->axes[PIVOT_AXIS_COLUMN].n_dimensions; i++)
995     x2[i
996        + table->axes[PIVOT_AXIS_LAYER].n_dimensions
997        + table->axes[PIVOT_AXIS_ROW].n_dimensions] = 1;
998   for (size_t i = 0; i < table->n_dimensions; i++)
999     {
1000       const struct pivot_dimension *d = table->dimensions[i];
1001       put_value (buf, d->root->name);
1002       put_byte (buf, 0);        /* x1 */
1003       put_byte (buf, x2[i]);
1004       put_u32 (buf, 2);         /* x3 */
1005       put_bool (buf, !d->root->show_label);
1006       put_bool (buf, d->hide_all_labels);
1007       put_bool (buf, 1);
1008       put_u32 (buf, i);
1009
1010       put_u32 (buf, d->root->n_subs);
1011       for (size_t j = 0; j < d->root->n_subs; j++)
1012         put_category (buf, d->root->subs[j]);
1013     }
1014   free (x2);
1015
1016   /* Axes. */
1017   put_u32 (buf, table->axes[PIVOT_AXIS_LAYER].n_dimensions);
1018   put_u32 (buf, table->axes[PIVOT_AXIS_ROW].n_dimensions);
1019   put_u32 (buf, table->axes[PIVOT_AXIS_COLUMN].n_dimensions);
1020   for (size_t i = 0; i < table->axes[PIVOT_AXIS_LAYER].n_dimensions; i++)
1021     put_u32 (buf, table->axes[PIVOT_AXIS_LAYER].dimensions[i]->top_index);
1022   for (size_t i = 0; i < table->axes[PIVOT_AXIS_ROW].n_dimensions; i++)
1023     put_u32 (buf, table->axes[PIVOT_AXIS_ROW].dimensions[i]->top_index);
1024   for (size_t i = 0; i < table->axes[PIVOT_AXIS_COLUMN].n_dimensions; i++)
1025     put_u32 (buf, table->axes[PIVOT_AXIS_COLUMN].dimensions[i]->top_index);
1026
1027   /* Cells. */
1028   put_u32 (buf, hmap_count (&table->cells));
1029   const struct pivot_cell *cell;
1030   HMAP_FOR_EACH (cell, struct pivot_cell, hmap_node, &table->cells)
1031     {
1032       uint64_t index = 0;
1033       for (size_t j = 0; j < table->n_dimensions; j++)
1034         index = (table->dimensions[j]->n_leaves * index) + cell->idx[j];
1035       put_u64 (buf, index);
1036
1037       put_value (buf, cell->value);
1038     }
1039 }
1040
1041 void
1042 spv_writer_put_table (struct spv_writer *w, const struct pivot_table *table)
1043 {
1044   struct pivot_table *table_rw = CONST_CAST (struct pivot_table *, table);
1045   if (!table_rw->subtype)
1046     table_rw->subtype = pivot_value_new_user_text ("unknown", -1);
1047
1048   int table_id = ++w->n_tables;
1049
1050   bool initial_depth = w->heading_depth;
1051   if (!initial_depth)
1052     spv_writer_open_file (w);
1053
1054   start_container (w);
1055
1056   char *title = pivot_value_to_string (table->title, table);
1057   char *subtype = pivot_value_to_string (table->subtype, table);
1058   
1059   start_elem (w, "label");
1060   write_text (w, title);
1061   end_elem (w);
1062
1063   start_elem (w, "vtb:table");
1064   write_attr (w, "commandName", table->command_c);
1065   write_attr (w, "type", "table"); /* XXX */
1066   write_attr (w, "subType", subtype);
1067   write_attr_format (w, "tableId", "%d", table_id);
1068
1069   free (subtype);
1070   free (title);
1071
1072   start_elem (w, "vtb:tableStructure");
1073   start_elem (w, "vtb:dataPath");
1074   char *data_path = xasprintf ("%010d_lightTableData.bin", table_id);
1075   write_text (w, data_path);
1076   end_elem (w); /* vtb:dataPath */
1077   end_elem (w); /* vtb:tableStructure */
1078   end_elem (w); /* vtb:table */
1079   end_elem (w); /* container */
1080
1081   if (!initial_depth)
1082     spv_writer_close_file (w, "");
1083
1084   struct buf buf = { NULL, 0, 0 };
1085   put_light_table (&buf, table_id, table);
1086   zip_writer_add_memory (w->zw, data_path, buf.data, buf.len);
1087   free (buf.data);
1088
1089   free (data_path);
1090 }