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