ba2d54f9f5060f055a96be78ba517ef3d7913cb7
[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 #include "output/options.h"
22
23 #include <ctype.h>
24 #include <errno.h>
25 #include <limits.h>
26 #include <stdarg.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/output-item.h"
42
43 #include "gl/error.h"
44 #include "gl/xalloc.h"
45 #include "gl/xmemdup0.h"
46 #include "gl/xvasprintf.h"
47
48 #include "gettext.h"
49 #define _(msgid) gettext (msgid)
50
51 struct output_engine
52   {
53     struct ll ll;                  /* Node for this engine. */
54     struct llx_list drivers;       /* Contains "struct output_driver"s. */
55     struct output_item *deferred_text; /* Output text being accumulated. */
56     char *command_name;            /* Name of command being processed. */
57     char *title, *subtitle;        /* Components of page title. */
58
59     /* Output grouping stack. */
60     struct output_item **groups;
61     size_t n_groups;
62     size_t allocated_groups;
63
64     struct string_map heading_vars;
65   };
66
67 static struct ll_list engine_stack = LL_INITIALIZER (engine_stack);
68
69 static const struct output_driver_factory *factories[];
70
71 static struct output_engine *
72 engine_stack_top (void)
73 {
74   struct ll *head = ll_head (&engine_stack);
75   if (ll_is_empty (&engine_stack))
76     return NULL;
77   return ll_data (head, struct output_engine, ll);
78 }
79
80 static void
81 put_strftime (const char *key, const char *format,
82               const struct tm *tm, struct string_map *vars)
83 {
84   if (!string_map_find (vars, key))
85     {
86       char value[128];
87       strftime (value, sizeof value, format, tm);
88       string_map_insert (vars, key, value);
89     }
90 }
91
92 void
93 output_engine_push (void)
94 {
95   struct output_engine *e = XZALLOC (struct output_engine);
96
97   llx_init (&e->drivers);
98
99   string_map_init (&e->heading_vars);
100
101   time_t t = time (NULL);
102   const struct tm *tm = localtime (&t);
103   put_strftime ("Date", "%x", tm, &e->heading_vars);
104   put_strftime ("Time", "%X", tm, &e->heading_vars);
105
106   ll_push_head (&engine_stack, &e->ll);
107 }
108
109 void
110 output_engine_pop (void)
111 {
112   struct ll *head = ll_pop_head (&engine_stack);
113   struct output_engine *e = ll_data (head, struct output_engine, ll);
114
115   struct output_driver *d;
116   llx_for_each_preremove (d, &e->drivers, &llx_malloc_mgr)
117     output_driver_destroy (d);
118   output_item_unref (e->deferred_text);
119   free (e->command_name);
120   free (e->title);
121   free (e->subtitle);
122   if (e->n_groups)
123     output_item_unref (e->groups[0]);
124   free (e->groups);
125   string_map_destroy (&e->heading_vars);
126   free (e);
127 }
128
129 void
130 output_get_supported_formats (struct string_set *formats)
131 {
132   const struct output_driver_factory **fp;
133
134   for (fp = factories; *fp != NULL; fp++)
135     string_set_insert (formats, (*fp)->extension);
136 }
137
138 static bool
139 output_driver_should_show (const struct output_driver *d,
140                            const struct output_item *item)
141 {
142   enum settings_output_type type = SETTINGS_OUTPUT_RESULT;
143   switch (item->type)
144     {
145     case OUTPUT_ITEM_MESSAGE:
146       type = (item->message->severity == MSG_S_NOTE
147               ? SETTINGS_OUTPUT_NOTE
148               : SETTINGS_OUTPUT_ERROR);
149       break;
150
151     case OUTPUT_ITEM_TEXT:
152       if (item->text.subtype == TEXT_ITEM_SYNTAX)
153         type = SETTINGS_OUTPUT_SYNTAX;
154       break;
155
156     case OUTPUT_ITEM_CHART:
157     case OUTPUT_ITEM_GROUP:
158     case OUTPUT_ITEM_IMAGE:
159     case OUTPUT_ITEM_PAGE_BREAK:
160     case OUTPUT_ITEM_TABLE:
161       break;
162     }
163
164   return (settings_get_output_routing (type) & d->device_type) != 0;
165 }
166
167 /* Adds to OUT the subset of IN that driver D should show, considering routing
168    and visibility of each item, and flattening groups for drivers that don't
169    handle them internally. */
170 static void
171 make_driver_output_subset (const struct output_item *in,
172                            const struct output_driver *d,
173                            struct output_item *out)
174 {
175   if (in->type == OUTPUT_ITEM_GROUP)
176     {
177       /* If we should include the group itself, then clone IN inside OUT, and
178          add any children to the clone instead to OUT directly. */
179       if (output_driver_should_show (d, in) && d->class->handles_groups)
180         {
181           struct output_item *group = group_item_clone_empty (in);
182           group_item_add_child (out, group);
183           out = group;
184         }
185
186       for (size_t i = 0; i < in->group.n_children; i++)
187         make_driver_output_subset (in->group.children[i], d, out);
188     }
189   else
190     {
191       if (output_driver_should_show (d, in)
192           && (in->show || d->class->handles_show))
193         group_item_add_child (out, output_item_ref (in));
194     }
195 }
196
197 static void
198 output_submit__ (struct output_engine *e, struct output_item *item)
199 {
200   if (e->n_groups > 0)
201     {
202       group_item_add_child (e->groups[e->n_groups - 1], item);
203       return;
204     }
205
206   struct llx *llx, *next;
207   llx_for_each_safe (llx, next, &e->drivers)
208     {
209       struct output_driver *d = llx_data (llx);
210
211       struct output_item *root = root_item_create ();
212       make_driver_output_subset (item, d, root);
213       for (size_t i = 0; i < root->group.n_children; i++)
214         d->class->submit (d, root->group.children[i]);
215       output_item_unref (root);
216     }
217
218   output_item_unref (item);
219 }
220
221 static void
222 flush_deferred_text (struct output_engine *e)
223 {
224   struct output_item *deferred_text = e->deferred_text;
225   if (deferred_text)
226     {
227       e->deferred_text = NULL;
228       output_submit__ (e, deferred_text);
229     }
230 }
231
232 static bool
233 defer_text (struct output_engine *e, struct output_item *item)
234 {
235   if (item->type != OUTPUT_ITEM_TEXT)
236     return false;
237
238   if (!e->deferred_text)
239     e->deferred_text = output_item_unshare (item);
240   else if (text_item_append (e->deferred_text, item))
241     output_item_unref (item);
242   else
243     {
244       flush_deferred_text (e);
245       e->deferred_text = output_item_unshare (item);
246     }
247   return true;
248 }
249
250 /* Submits ITEM to the configured output drivers, and transfers ownership to
251    the output subsystem. */
252 void
253 output_submit (struct output_item *item)
254 {
255   struct output_engine *e = engine_stack_top ();
256
257   if (e == NULL)
258     return;
259
260   if (item == NULL)
261     return;
262
263   if (defer_text (e, item))
264     return;
265   flush_deferred_text (e);
266
267   /* XXX heading_vars */
268
269   output_submit__ (e, item);
270 }
271
272 /* Returns the name of the command currently being parsed, or NULL if no
273    command is being parsed. */
274 const char *
275 output_get_command_name (void)
276 {
277   struct output_engine *e = engine_stack_top ();
278   if (e == NULL)
279     return NULL;
280
281   for (size_t i = e->n_groups; i-- > 0;)
282     if (e->groups[i]->command_name)
283       return e->groups[i]->command_name;
284
285   return NULL;
286 }
287
288 char *
289 output_get_uppercase_command_name (void)
290 {
291   const char *command_name = output_get_command_name ();
292   return command_name ? utf8_to_upper (command_name) : NULL;
293 }
294
295 size_t
296 output_open_group (struct output_item *item)
297 {
298   struct output_engine *e = engine_stack_top ();
299   if (e == NULL)
300     return 0;
301
302   if (e->n_groups >= e->allocated_groups)
303     e->groups = x2nrealloc (e->groups, &e->allocated_groups,
304                             sizeof *e->groups);
305   e->groups[e->n_groups++] = item;
306   if (e->n_groups > 1)
307     group_item_add_child (e->groups[e->n_groups - 2], item);
308
309   return e->n_groups - 1;
310 }
311
312 void
313 output_close_groups (size_t nesting_level)
314 {
315   struct output_engine *e = engine_stack_top ();
316   if (e == NULL)
317     return;
318
319   while (e->n_groups > nesting_level)
320     {
321       flush_deferred_text (e);
322
323       struct output_item *group = e->groups[--e->n_groups];
324       if (e->n_groups == 0)
325         output_submit__ (e, group);
326     }
327 }
328
329 /* Flushes output to screen devices, so that the user can see
330    output that doesn't fill up an entire page. */
331 void
332 output_flush (void)
333 {
334   struct output_engine *e = engine_stack_top ();
335
336   flush_deferred_text (e);
337
338   struct llx *llx;
339   llx_for_each (llx, &e->drivers)
340     {
341       struct output_driver *d = llx_data (llx);
342       if (d->device_type & SETTINGS_DEVICE_TERMINAL && d->class->flush != NULL)
343         d->class->flush (d);
344     }
345 }
346
347 static void
348 output_set_title__ (struct output_engine *e, char **dst, const char *src)
349 {
350   free (*dst);
351   *dst = xstrdup_if_nonnull (src);
352
353   char *page_title
354     = (e->title && e->subtitle ? xasprintf ("%s\n%s", e->title, e->subtitle)
355        : e->title ? xstrdup (e->title)
356        : e->subtitle ? xstrdup (e->subtitle)
357        : xzalloc (1));
358   output_item_submit (text_item_create_nocopy (TEXT_ITEM_PAGE_TITLE,
359                                                page_title, NULL));
360 }
361
362 void PRINTF_FORMAT (1, 2)
363 output_log (const char *format, ...)
364 {
365   va_list args;
366   va_start (args, format);
367   char *s = xvasprintf (format, args);
368   va_end (args);
369
370   output_log_nocopy (s);
371 }
372
373 void
374 output_log_nocopy (char *s)
375 {
376   output_submit (text_item_create_nocopy (TEXT_ITEM_LOG, s, NULL));
377 }
378
379 const char *
380 output_get_title (void)
381 {
382   return engine_stack_top ()->title;
383 }
384
385 void
386 output_set_title (const char *title)
387 {
388   struct output_engine *e = engine_stack_top ();
389
390   output_set_title__ (e, &e->title, title);
391 }
392
393 const char *
394 output_get_subtitle (void)
395 {
396   return engine_stack_top ()->subtitle;
397 }
398
399 void
400 output_set_subtitle (const char *subtitle)
401 {
402   struct output_engine *e = engine_stack_top ();
403
404   output_set_title__ (e, &e->subtitle, subtitle);
405 }
406
407 void
408 output_set_filename (const char *filename)
409 {
410   struct output_engine *e = engine_stack_top ();
411
412   string_map_replace (&e->heading_vars, "Filename", filename);
413 }
414 \f
415 void
416 output_driver_destroy (struct output_driver *driver)
417 {
418   if (driver != NULL)
419     {
420       char *name = driver->name;
421       if (output_driver_is_registered (driver))
422         output_driver_unregister (driver);
423       if (driver->class->destroy)
424         driver->class->destroy (driver);
425       free (name);
426     }
427 }
428
429 const char *
430 output_driver_get_name (const struct output_driver *driver)
431 {
432   return driver->name;
433 }
434 \f
435 static struct output_engine *
436 output_driver_get_engine (const struct output_driver *driver)
437 {
438   struct output_engine *e;
439
440   ll_for_each (e, struct output_engine, ll, &engine_stack)
441     {
442       if (llx_find (llx_head (&e->drivers), llx_null (&e->drivers), driver))
443         return e;
444     }
445
446   return NULL;
447 }
448
449 void
450 output_driver_register (struct output_driver *driver)
451 {
452   struct output_engine *e = engine_stack_top ();
453
454   assert (!output_driver_is_registered (driver));
455   llx_push_tail (&e->drivers, driver, &llx_malloc_mgr);
456 }
457
458 void
459 output_driver_unregister (struct output_driver *driver)
460 {
461   struct output_engine *e = output_driver_get_engine (driver);
462
463   assert (e != NULL);
464   llx_remove (llx_find (llx_head (&e->drivers), llx_null (&e->drivers), driver),
465               &llx_malloc_mgr);
466 }
467
468 bool
469 output_driver_is_registered (const struct output_driver *driver)
470 {
471   return output_driver_get_engine (driver) != NULL;
472 }
473
474 void
475 output_set_page_setup (const struct page_setup *ps)
476 {
477   struct output_engine *e = engine_stack_top ();
478
479   struct llx *llx;
480   llx_for_each (llx, &e->drivers)
481     {
482       struct output_driver *d = llx_data (llx);
483       if (d->class->setup)
484         d->class->setup (d, ps);
485     }
486 }
487 \f
488 extern const struct output_driver_factory csv_driver_factory;
489 extern const struct output_driver_factory html_driver_factory;
490 extern const struct output_driver_factory list_driver_factory;
491 extern const struct output_driver_factory odt_driver_factory;
492 extern const struct output_driver_factory pdf_driver_factory;
493 extern const struct output_driver_factory png_driver_factory;
494 extern const struct output_driver_factory ps_driver_factory;
495 extern const struct output_driver_factory spv_driver_factory;
496 extern const struct output_driver_factory svg_driver_factory;
497 extern const struct output_driver_factory tex_driver_factory;
498 extern const struct output_driver_factory txt_driver_factory;
499
500 static const struct output_driver_factory *factories[] =
501   {
502     &txt_driver_factory,
503     &list_driver_factory,
504     &html_driver_factory,
505     &csv_driver_factory,
506     &odt_driver_factory,
507     &spv_driver_factory,
508     &pdf_driver_factory,
509     &ps_driver_factory,
510     &svg_driver_factory,
511     &png_driver_factory,
512     &tex_driver_factory,
513     NULL
514   };
515
516 static const struct output_driver_factory *
517 find_factory (const char *format)
518 {
519   const struct output_driver_factory **fp;
520
521   for (fp = factories; *fp != NULL; fp++)
522     {
523       const struct output_driver_factory *f = *fp;
524
525       if (!strcmp (f->extension, format))
526         return f;
527     }
528   return &txt_driver_factory;
529 }
530
531 static enum settings_output_devices
532 default_device_type (const char *file_name)
533 {
534   return (!strcmp (file_name, "-")
535           ? SETTINGS_DEVICE_TERMINAL
536           : SETTINGS_DEVICE_LISTING);
537 }
538
539 struct output_driver *
540 output_driver_create (struct string_map *options)
541 {
542   char *format = string_map_find_and_delete (options, "format");
543   char *file_name = string_map_find_and_delete (options, "output-file");
544   if (!format)
545     {
546       if (file_name)
547         {
548           const char *extension = strrchr (file_name, '.');
549           format = xstrdup (extension != NULL ? extension + 1 : "");
550         }
551       else
552         format = xstrdup ("txt");
553     }
554   const struct output_driver_factory *f = find_factory (format);
555
556   struct driver_options o = {
557     .driver_name = f->extension,
558     .map = STRING_MAP_INITIALIZER (o.map),
559     .garbage = STRING_ARRAY_INITIALIZER,
560   };
561   string_map_swap (&o.map, options);
562
563   if (file_name == NULL)
564     file_name = xstrdup (f->default_file_name);
565
566   /* XXX should use parse_enum(). */
567   enum settings_output_devices default_type = default_device_type (file_name);
568   const char *default_type_string = (default_type == SETTINGS_DEVICE_TERMINAL
569                                 ? "terminal" : "listing");
570   enum settings_output_devices device_type = parse_enum (
571     driver_option_get (&o, "device", default_type_string),
572     "terminal", SETTINGS_DEVICE_TERMINAL,
573     "listing", SETTINGS_DEVICE_LISTING,
574     NULL_SENTINEL);
575
576   struct file_handle *fh = fh_create_file (NULL, file_name, NULL,
577                                            fh_default_properties ());
578   struct output_driver *driver = f->create (fh, device_type, &o);
579   if (driver)
580     {
581       const struct string_map_node *node;
582       const char *key;
583
584       STRING_MAP_FOR_EACH_KEY (key, node, &o.map)
585         msg (MW, _("%s: unknown option `%s'"), file_name, key);
586     }
587
588   string_map_destroy (&o.map);
589   string_array_destroy (&o.garbage);
590
591   free (file_name);
592   free (format);
593
594   return driver;
595 }
596
597 void
598 output_driver_parse_option (const char *option, struct string_map *options)
599 {
600   const char *equals = strchr (option, '=');
601   if (equals == NULL)
602     {
603       error (0, 0, _("%s: output option missing `='"), option);
604       return;
605     }
606
607   char *key = xmemdup0 (option, equals - option);
608   if (string_map_contains (options, key))
609     {
610       error (0, 0, _("%s: output option specified more than once"), key);
611       free (key);
612       return;
613     }
614
615   char *value = xmemdup0 (equals + 1, strlen (equals + 1));
616   string_map_insert_nocopy (options, key, value);
617 }
618 \f
619 char *
620 output_driver_substitute_heading_vars (const char *src, int page_number)
621 {
622   struct output_engine *e = engine_stack_top ();
623   struct string dst = DS_EMPTY_INITIALIZER;
624   ds_extend (&dst, strlen (src));
625   for (const char *p = src; *p;)
626     {
627       if (!strncmp (p, "&amp;[", 6))
628         {
629           if (page_number != INT_MIN)
630             {
631               const char *start = p + 6;
632               const char *end = strchr (start, ']');
633               if (end)
634                 {
635                   const char *value = string_map_find__ (&e->heading_vars,
636                                                          start, end - start);
637                   if (value)
638                     ds_put_cstr (&dst, value);
639                   else if (ss_equals (ss_buffer (start, end - start),
640                                       ss_cstr ("Page")))
641                     ds_put_format (&dst, "%d", page_number);
642                   p = end + 1;
643                   continue;
644                 }
645             }
646           ds_put_cstr (&dst, "&amp;");
647           p += 5;
648         }
649       else
650         ds_put_byte (&dst, *p++);
651     }
652   return ds_steal_cstr (&dst);
653 }