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