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