Add support for reading and writing SPV files.
[pspp] / src / output / driver.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009, 2010, 2011, 2012, 2014 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/driver.h"
20 #include "output/driver-provider.h"
21
22 #include <ctype.h>
23 #include <errno.h>
24 #include <libxml/parser.h>
25 #include <libxml/tree.h>
26 #include <limits.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <time.h>
30
31 #include "data/file-handle-def.h"
32 #include "data/settings.h"
33 #include "libpspp/array.h"
34 #include "libpspp/assertion.h"
35 #include "libpspp/message.h"
36 #include "libpspp/llx.h"
37 #include "libpspp/string-map.h"
38 #include "libpspp/string-set.h"
39 #include "libpspp/str.h"
40 #include "output/group-item.h"
41 #include "output/message-item.h"
42 #include "output/output-item.h"
43 #include "output/text-item.h"
44
45 #include "gl/error.h"
46 #include "gl/xalloc.h"
47 #include "gl/xmemdup0.h"
48
49 #include "gettext.h"
50 #define _(msgid) gettext (msgid)
51
52 struct output_engine
53   {
54     struct llx_list drivers;       /* Contains "struct output_driver"s. */
55     struct string deferred_text;   /* Output text being accumulated. */
56     enum text_item_type deferred_type; /* Type of text being accumulated. */
57     char *command_name;            /* Name of command being processed. */
58     char *title, *subtitle;        /* Components of page title. */
59
60     /* Output grouping stack.
61
62        TEXT_ITEM_GROUP_OPEN pushes a group on the stack and
63        TEXT_ITEM_GROUP_CLOSE pops one off. */
64     char **groups;               /* Command names of nested sections. */
65     size_t n_groups;
66     size_t allocated_groups;
67
68     struct string_map heading_vars;
69   };
70
71 static const struct output_driver_factory *factories[];
72
73 /* A stack of output engines.. */
74 static struct output_engine *engine_stack;
75 static size_t n_stack, allocated_stack;
76
77 static struct output_engine *
78 engine_stack_top (void)
79 {
80   assert (n_stack > 0);
81   return &engine_stack[n_stack - 1];
82 }
83
84 static void
85 put_strftime (const char *key, const char *format,
86               const struct tm *tm, struct string_map *vars)
87 {
88   if (!string_map_find (vars, key))
89     {
90       char value[128];
91       strftime (value, sizeof value, format, tm);
92       string_map_insert (vars, key, value);
93     }
94 }
95
96 void
97 output_engine_push (void)
98 {
99   struct output_engine *e;
100
101   if (n_stack >= allocated_stack)
102     engine_stack = x2nrealloc (engine_stack, &allocated_stack,
103                                sizeof *engine_stack);
104
105   e = &engine_stack[n_stack++];
106   memset (e, 0, sizeof *e);
107   llx_init (&e->drivers);
108   ds_init_empty (&e->deferred_text);
109
110   string_map_init (&e->heading_vars);
111
112   time_t t = time (NULL);
113   const struct tm *tm = localtime (&t);
114   put_strftime ("Date", "%x", tm, &e->heading_vars);
115   put_strftime ("Time", "%X", tm, &e->heading_vars);
116 }
117
118 void
119 output_engine_pop (void)
120 {
121   struct output_engine *e;
122
123   assert (n_stack > 0);
124   e = &engine_stack[--n_stack];
125   while (!llx_is_empty (&e->drivers))
126     {
127       struct output_driver *d = llx_pop_head (&e->drivers, &llx_malloc_mgr);
128       output_driver_destroy (d);
129     }
130   ds_destroy (&e->deferred_text);
131   free (e->command_name);
132   free (e->title);
133   free (e->subtitle);
134   for (size_t i = 0; i < e->n_groups; i++)
135     free (e->groups[i]);
136   free (e->groups);
137   string_map_destroy (&e->heading_vars);
138 }
139
140 void
141 output_get_supported_formats (struct string_set *formats)
142 {
143   const struct output_driver_factory **fp;
144
145   for (fp = factories; *fp != NULL; fp++)
146     string_set_insert (formats, (*fp)->extension);
147 }
148
149 static void
150 output_submit__ (struct output_engine *e, struct output_item *item)
151 {
152   struct llx *llx, *next;
153
154   for (llx = llx_head (&e->drivers); llx != llx_null (&e->drivers); llx = next)
155     {
156       struct output_driver *d = llx_data (llx);
157       enum settings_output_type type;
158
159       next = llx_next (llx);
160
161       if (is_message_item (item))
162         {
163           const struct msg *m = message_item_get_msg (to_message_item (item));
164           if (m->severity == MSG_S_NOTE)
165             type = SETTINGS_OUTPUT_NOTE;
166           else
167             type = SETTINGS_OUTPUT_ERROR;
168         }
169       else if (is_text_item (item)
170                && text_item_get_type (to_text_item (item)) == TEXT_ITEM_SYNTAX)
171         type = SETTINGS_OUTPUT_SYNTAX;
172       else
173         type = SETTINGS_OUTPUT_RESULT;
174
175       if (settings_get_output_routing (type) & d->device_type)
176         d->class->submit (d, item);
177     }
178
179   output_item_unref (item);
180 }
181
182 static void
183 flush_deferred_text (struct output_engine *e)
184 {
185   if (!ds_is_empty (&e->deferred_text))
186     {
187       char *text = ds_steal_cstr (&e->deferred_text);
188       output_submit__ (e, text_item_super (text_item_create_nocopy (
189                                              e->deferred_type, text)));
190     }
191 }
192
193 static bool
194 defer_text (struct output_engine *e, struct output_item *item)
195 {
196   if (!is_text_item (item))
197     return false;
198
199   struct text_item *text_item = to_text_item (item);
200   if (text_item->markup)        /* XXX */
201     return false;
202
203   enum text_item_type type = text_item_get_type (text_item);
204   if (type != TEXT_ITEM_SYNTAX && type != TEXT_ITEM_LOG)
205     return false;
206
207   if (!ds_is_empty (&e->deferred_text) && e->deferred_type != type)
208     flush_deferred_text (e);
209
210   e->deferred_type = type;
211
212   if (!ds_is_empty (&e->deferred_text))
213     ds_put_byte (&e->deferred_text, '\n');
214
215   const char *text = text_item_get_text (text_item);
216   ds_put_cstr (&e->deferred_text, text);
217   output_item_unref (item);
218
219   return true;
220 }
221
222 /* Submits ITEM to the configured output drivers, and transfers ownership to
223    the output subsystem. */
224 void
225 output_submit (struct output_item *item)
226 {
227   struct output_engine *e = engine_stack_top ();
228
229   if (item == NULL)
230     return;
231
232   if (defer_text (e, item))
233     return;
234   flush_deferred_text (e);
235
236   if (is_group_open_item (item))
237     {
238       const struct group_open_item *group_open_item
239         = to_group_open_item (item);
240       if (e->n_groups >= e->allocated_groups)
241         e->groups = x2nrealloc (e->groups, &e->allocated_groups,
242                                 sizeof *e->groups);
243       e->groups[e->n_groups] = (group_open_item->command_name
244                                 ? xstrdup (group_open_item->command_name)
245                                 : NULL);
246       e->n_groups++;
247     }
248   else if (is_group_close_item (item))
249     {
250       assert (e->n_groups > 0);
251
252       size_t idx = --e->n_groups;
253       free (e->groups[idx]);
254       if (idx >= 1 && idx <= 4)
255         {
256           char *key = xasprintf ("Head%zu", idx);
257           free (string_map_find_and_delete (&e->heading_vars, key));
258           free (key);
259         }
260     }
261   else if (is_text_item (item))
262     {
263       const struct text_item *text_item = to_text_item (item);
264       enum text_item_type type = text_item_get_type (text_item);
265       const char *text = text_item_get_text (text_item);
266       if (type == TEXT_ITEM_TITLE
267           && e->n_groups >= 1 && e->n_groups <= 4)
268         {
269           char *key = xasprintf ("Head%zu", e->n_groups);
270           string_map_replace (&e->heading_vars, key, text);
271           free (key);
272         }
273       else if (type == TEXT_ITEM_PAGE_TITLE)
274         string_map_replace (&e->heading_vars, "PageTitle", text);
275     }
276
277   output_submit__ (e, item);
278 }
279
280 const char *
281 output_get_command_name (void)
282 {
283   if (n_stack)
284     {
285       struct output_engine *e = engine_stack_top ();
286       for (size_t i = e->n_groups; i-- > 0; )
287         if (e->groups[i])
288           return e->groups[i];
289     }
290
291   return NULL;
292 }
293
294 /* Flushes output to screen devices, so that the user can see
295    output that doesn't fill up an entire page. */
296 void
297 output_flush (void)
298 {
299   struct output_engine *e = engine_stack_top ();
300   struct llx *llx;
301
302   flush_deferred_text (e);
303   for (llx = llx_head (&e->drivers); llx != llx_null (&e->drivers);
304        llx = llx_next (llx))
305     {
306       struct output_driver *d = llx_data (llx);
307       if (d->device_type & SETTINGS_DEVICE_TERMINAL && d->class->flush != NULL)
308         d->class->flush (d);
309     }
310 }
311
312 static void
313 output_set_title__ (struct output_engine *e, char **dst, const char *src)
314 {
315   free (*dst);
316   *dst = src ? xstrdup (src) : NULL;
317
318   char *page_title
319     = (e->title && e->subtitle ? xasprintf ("%s\n%s", e->title, e->subtitle)
320        : e->title ? xstrdup (e->title)
321        : e->subtitle ? xstrdup (e->subtitle)
322        : xzalloc (1));
323   text_item_submit (text_item_create_nocopy (TEXT_ITEM_PAGE_TITLE,
324                                              page_title));
325 }
326
327 void
328 output_set_title (const char *title)
329 {
330   struct output_engine *e = engine_stack_top ();
331
332   output_set_title__ (e, &e->title, title);
333 }
334
335 void
336 output_set_subtitle (const char *subtitle)
337 {
338   struct output_engine *e = engine_stack_top ();
339
340   output_set_title__ (e, &e->subtitle, subtitle);
341 }
342
343 void
344 output_set_filename (const char *filename)
345 {
346   struct output_engine *e = engine_stack_top ();
347
348   string_map_replace (&e->heading_vars, "Filename", filename);
349 }
350
351 size_t
352 output_get_group_level (void)
353 {
354   struct output_engine *e = engine_stack_top ();
355
356   return e->n_groups;
357 }
358 \f
359 void
360 output_driver_init (struct output_driver *driver,
361                     const struct output_driver_class *class,
362                     const char *name, enum settings_output_devices type)
363 {
364   driver->class = class;
365   driver->name = xstrdup (name);
366   driver->device_type = type;
367 }
368
369 void
370 output_driver_destroy (struct output_driver *driver)
371 {
372   if (driver != NULL)
373     {
374       char *name = driver->name;
375       if (output_driver_is_registered (driver))
376         output_driver_unregister (driver);
377       if (driver->class->destroy)
378         driver->class->destroy (driver);
379       free (name);
380     }
381 }
382
383 const char *
384 output_driver_get_name (const struct output_driver *driver)
385 {
386   return driver->name;
387 }
388 \f
389 static struct output_engine *
390 output_driver_get_engine (const struct output_driver *driver)
391 {
392   struct output_engine *e;
393
394   for (e = engine_stack; e < &engine_stack[n_stack]; e++)
395     if (llx_find (llx_head (&e->drivers), llx_null (&e->drivers), driver))
396       return e;
397
398   return NULL;
399 }
400
401 void
402 output_driver_register (struct output_driver *driver)
403 {
404   struct output_engine *e = engine_stack_top ();
405
406   assert (!output_driver_is_registered (driver));
407   llx_push_tail (&e->drivers, driver, &llx_malloc_mgr);
408 }
409
410 void
411 output_driver_unregister (struct output_driver *driver)
412 {
413   struct output_engine *e = output_driver_get_engine (driver);
414
415   assert (e != NULL);
416   llx_remove (llx_find (llx_head (&e->drivers), llx_null (&e->drivers), driver),
417               &llx_malloc_mgr);
418 }
419
420 bool
421 output_driver_is_registered (const struct output_driver *driver)
422 {
423   return output_driver_get_engine (driver) != NULL;
424 }
425 \f
426 extern const struct output_driver_factory txt_driver_factory;
427 extern const struct output_driver_factory list_driver_factory;
428 extern const struct output_driver_factory html_driver_factory;
429 extern const struct output_driver_factory csv_driver_factory;
430 extern const struct output_driver_factory odt_driver_factory;
431 extern const struct output_driver_factory spv_driver_factory;
432 #ifdef HAVE_CAIRO
433 extern const struct output_driver_factory pdf_driver_factory;
434 extern const struct output_driver_factory ps_driver_factory;
435 extern const struct output_driver_factory svg_driver_factory;
436 #endif
437
438 static const struct output_driver_factory *factories[] =
439   {
440     &txt_driver_factory,
441     &list_driver_factory,
442     &html_driver_factory,
443     &csv_driver_factory,
444     &odt_driver_factory,
445     &spv_driver_factory,
446 #ifdef HAVE_CAIRO
447     &pdf_driver_factory,
448     &ps_driver_factory,
449     &svg_driver_factory,
450 #endif
451     NULL
452   };
453
454 static const struct output_driver_factory *
455 find_factory (const char *format)
456 {
457   const struct output_driver_factory **fp;
458
459   for (fp = factories; *fp != NULL; fp++)
460     {
461       const struct output_driver_factory *f = *fp;
462
463       if (!strcmp (f->extension, format))
464         return f;
465     }
466   return &txt_driver_factory;
467 }
468
469 static enum settings_output_devices
470 default_device_type (const char *file_name)
471 {
472   return (!strcmp (file_name, "-")
473           ? SETTINGS_DEVICE_TERMINAL
474           : SETTINGS_DEVICE_LISTING);
475 }
476
477 struct output_driver *
478 output_driver_create (struct string_map *options)
479 {
480   enum settings_output_devices device_type;
481   const struct output_driver_factory *f;
482   struct output_driver *driver;
483   char *device_string;
484   char *file_name;
485   char *format;
486
487   format = string_map_find_and_delete (options, "format");
488   file_name = string_map_find_and_delete (options, "output-file");
489
490   if (format == NULL)
491     {
492       if (file_name != NULL)
493         {
494           const char *extension = strrchr (file_name, '.');
495           format = xstrdup (extension != NULL ? extension + 1 : "");
496         }
497       else
498         format = xstrdup ("txt");
499     }
500   f = find_factory (format);
501
502   if (file_name == NULL)
503     file_name = xstrdup (f->default_file_name);
504
505   /* XXX should use parse_enum(). */
506   device_string = string_map_find_and_delete (options, "device");
507   if (device_string == NULL || device_string[0] == '\0')
508     device_type = default_device_type (file_name);
509   else if (!strcmp (device_string, "terminal"))
510     device_type = SETTINGS_DEVICE_TERMINAL;
511   else if (!strcmp (device_string, "listing"))
512     device_type = SETTINGS_DEVICE_LISTING;
513   else
514     {
515       msg (MW, _("%s is not a valid device type (the choices are `%s' and `%s')"),
516                      device_string, "terminal", "listing");
517       device_type = default_device_type (file_name);
518     }
519
520   struct file_handle *fh = fh_create_file (NULL, file_name, NULL, fh_default_properties ());
521
522   driver = f->create (fh, device_type, options);
523   if (driver != NULL)
524     {
525       const struct string_map_node *node;
526       const char *key;
527
528       STRING_MAP_FOR_EACH_KEY (key, node, options)
529         msg (MW, _("%s: unknown option `%s'"), file_name, key);
530     }
531   string_map_clear (options);
532
533   free (file_name);
534   free (format);
535   free (device_string);
536
537   return driver;
538 }
539
540 void
541 output_driver_parse_option (const char *option, struct string_map *options)
542 {
543   const char *equals = strchr (option, '=');
544   if (equals == NULL)
545     {
546       error (0, 0, _("%s: output option missing `='"), option);
547       return;
548     }
549
550   char *key = xmemdup0 (option, equals - option);
551   if (string_map_contains (options, key))
552     {
553       error (0, 0, _("%s: output option specified more than once"), key);
554       free (key);
555       return;
556     }
557
558   char *value = xmemdup0 (equals + 1, strlen (equals + 1));
559   string_map_insert_nocopy (options, key, value);
560 }
561 \f
562 /* Extracts the actual text content from the given Pango MARKUP and returns it
563    as as a malloc()'d string. */
564 char *
565 output_get_text_from_markup (const char *markup)
566 {
567   xmlParserCtxt *parser = xmlCreatePushParserCtxt (NULL, NULL, NULL, 0, NULL);
568   if (!parser)
569     return xstrdup (markup);
570
571   xmlParseChunk (parser, "<xml>", strlen ("<xml>"), false);
572   xmlParseChunk (parser, markup, strlen (markup), false);
573   xmlParseChunk (parser, "</xml>", strlen ("</xml>"), true);
574
575   char *content
576     = (parser->wellFormed
577        ? CHAR_CAST (char *,
578                     xmlNodeGetContent (xmlDocGetRootElement (parser->myDoc)))
579        : xstrdup (markup));
580   xmlFreeDoc (parser->myDoc);
581   xmlFreeParserCtxt (parser);
582
583   return content;
584 }
585
586 char *
587 output_driver_substitute_heading_vars (const char *src, int page_number)
588 {
589   struct output_engine *e = engine_stack_top ();
590   struct string dst = DS_EMPTY_INITIALIZER;
591   ds_extend (&dst, strlen (src));
592   for (const char *p = src; *p; )
593     {
594       if (!strncmp (p, "&amp;[", 6))
595         {
596           if (page_number != INT_MIN)
597             {
598               const char *start = p + 6;
599               const char *end = strchr (start, ']');
600               if (end)
601                 {
602                   const char *value = string_map_find__ (&e->heading_vars,
603                                                          start, end - start);
604                   if (value)
605                     ds_put_cstr (&dst, value);
606                   else if (ss_equals (ss_buffer (start, end - start),
607                                       ss_cstr ("Page")))
608                     ds_put_format (&dst, "%d", page_number);
609                   p = end + 1;
610                   continue;
611                 }
612             }
613           ds_put_cstr (&dst, "&amp;");
614           p += 5;
615         }
616       else
617         ds_put_byte (&dst, *p++);
618     }
619   return ds_steal_cstr (&dst);
620 }