output-item: Collapse the inheritance hierarchy into a single struct.
[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 <stdlib.h>
26 #include <string.h>
27 #include <time.h>
28
29 #include "data/file-handle-def.h"
30 #include "data/settings.h"
31 #include "libpspp/array.h"
32 #include "libpspp/assertion.h"
33 #include "libpspp/i18n.h"
34 #include "libpspp/message.h"
35 #include "libpspp/llx.h"
36 #include "libpspp/string-map.h"
37 #include "libpspp/string-set.h"
38 #include "libpspp/str.h"
39 #include "output/output-item.h"
40
41 #include "gl/error.h"
42 #include "gl/xalloc.h"
43 #include "gl/xmemdup0.h"
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47
48 struct output_engine
49   {
50     struct ll ll;                  /* Node for this engine. */
51     struct llx_list drivers;       /* Contains "struct output_driver"s. */
52     struct output_item *deferred_text; /* Output text being accumulated. */
53     char *command_name;            /* Name of command being processed. */
54     char *title, *subtitle;        /* Components of page title. */
55
56     /* Output grouping stack.
57
58        TEXT_ITEM_GROUP_OPEN pushes a group on the stack and
59        TEXT_ITEM_GROUP_CLOSE pops one off. */
60     char **groups;               /* Command names of nested sections. */
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 (sizeof (*e));
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   while (!llx_is_empty (&e->drivers))
116     {
117       struct output_driver *d = llx_pop_head (&e->drivers, &llx_malloc_mgr);
118       output_driver_destroy (d);
119     }
120   output_item_unref (e->deferred_text);
121   free (e->command_name);
122   free (e->title);
123   free (e->subtitle);
124   for (size_t i = 0; i < e->n_groups; i++)
125     free (e->groups[i]);
126   free (e->groups);
127   string_map_destroy (&e->heading_vars);
128   free (e);
129 }
130
131 void
132 output_get_supported_formats (struct string_set *formats)
133 {
134   const struct output_driver_factory **fp;
135
136   for (fp = factories; *fp != NULL; fp++)
137     string_set_insert (formats, (*fp)->extension);
138 }
139
140 static void
141 output_submit__ (struct output_engine *e, struct output_item *item)
142 {
143   struct llx *llx, *next;
144
145   for (llx = llx_head (&e->drivers); llx != llx_null (&e->drivers); llx = next)
146     {
147       struct output_driver *d = llx_data (llx);
148
149       next = llx_next (llx);
150
151       enum settings_output_type type = SETTINGS_OUTPUT_RESULT;
152       switch (item->type)
153         {
154         case OUTPUT_ITEM_MESSAGE:
155           type = (item->message->severity == MSG_S_NOTE
156                   ? SETTINGS_OUTPUT_NOTE
157                   : SETTINGS_OUTPUT_ERROR);
158           break;
159
160         case OUTPUT_ITEM_TEXT:
161           if (item->text.subtype == TEXT_ITEM_SYNTAX)
162             type = SETTINGS_OUTPUT_SYNTAX;
163           break;
164
165         case OUTPUT_ITEM_CHART:
166         case OUTPUT_ITEM_GROUP_OPEN:
167         case OUTPUT_ITEM_GROUP_CLOSE:
168         case OUTPUT_ITEM_IMAGE:
169         case OUTPUT_ITEM_PAGE_BREAK:
170         case OUTPUT_ITEM_PAGE_SETUP:
171         case OUTPUT_ITEM_TABLE:
172           break;
173         }
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   struct output_item *deferred_text = e->deferred_text;
186   if (deferred_text)
187     {
188       e->deferred_text = NULL;
189       output_submit__ (e, deferred_text);
190     }
191 }
192
193 static bool
194 defer_text (struct output_engine *e, struct output_item *item)
195 {
196   if (item->type != OUTPUT_ITEM_TEXT)
197     return false;
198
199   if (!e->deferred_text)
200     e->deferred_text = output_item_unshare (item);
201   else if (text_item_append (e->deferred_text, item))
202     output_item_unref (item);
203   else
204     {
205       flush_deferred_text (e);
206       e->deferred_text = output_item_unshare (item);
207     }
208   return true;
209 }
210
211 /* Submits ITEM to the configured output drivers, and transfers ownership to
212    the output subsystem. */
213 void
214 output_submit (struct output_item *item)
215 {
216   struct output_engine *e = engine_stack_top ();
217
218   if (e == NULL)
219     return;
220
221   if (item == NULL)
222     return;
223
224   if (defer_text (e, item))
225     return;
226   flush_deferred_text (e);
227
228   switch (item->type)
229     {
230     case OUTPUT_ITEM_GROUP_OPEN:
231       if (e->n_groups >= e->allocated_groups)
232         e->groups = x2nrealloc (e->groups, &e->allocated_groups,
233                                 sizeof *e->groups);
234       e->groups[e->n_groups] = xstrdup_if_nonnull (item->command_name);
235       e->n_groups++;
236       break;
237
238     case OUTPUT_ITEM_GROUP_CLOSE:
239       assert (e->n_groups > 0);
240
241       size_t idx = --e->n_groups;
242       free (e->groups[idx]);
243
244       char *key = xasprintf ("Head%zu", idx);
245       free (string_map_find_and_delete (&e->heading_vars, key));
246       free (key);
247       break;
248
249     case OUTPUT_ITEM_TEXT:
250       {
251         enum text_item_subtype st = item->text.subtype;
252         char *key = (st == TEXT_ITEM_TITLE ? xasprintf ("Head%zu", e->n_groups)
253                      : st == TEXT_ITEM_PAGE_TITLE ? xstrdup ("PageTitle")
254                      : NULL);
255         if (key)
256           string_map_replace_nocopy (&e->heading_vars, key,
257                                      text_item_get_plain_text (item));
258       }
259       break;
260
261     case OUTPUT_ITEM_CHART:
262     case OUTPUT_ITEM_IMAGE:
263     case OUTPUT_ITEM_MESSAGE:
264     case OUTPUT_ITEM_PAGE_BREAK:
265     case OUTPUT_ITEM_PAGE_SETUP:
266     case OUTPUT_ITEM_TABLE:
267       break;
268     }
269
270   output_submit__ (e, item);
271 }
272
273 /* Returns the name of the command currently being parsed, or NULL if no
274    command is being parsed. */
275 const char *
276 output_get_command_name (void)
277 {
278   struct output_engine *e = engine_stack_top ();
279   if (e == NULL)
280     return NULL;
281
282   for (size_t i = e->n_groups; i-- > 0;)
283     if (e->groups[i])
284       return e->groups[i];
285
286   return NULL;
287 }
288
289 char *
290 output_get_uppercase_command_name (void)
291 {
292   const char *command_name = output_get_command_name ();
293   return command_name ? utf8_to_upper (command_name) : NULL;
294 }
295
296 /* Flushes output to screen devices, so that the user can see
297    output that doesn't fill up an entire page. */
298 void
299 output_flush (void)
300 {
301   struct output_engine *e = engine_stack_top ();
302   struct llx *llx;
303
304   flush_deferred_text (e);
305   for (llx = llx_head (&e->drivers); llx != llx_null (&e->drivers);
306        llx = llx_next (llx))
307     {
308       struct output_driver *d = llx_data (llx);
309       if (d->device_type & SETTINGS_DEVICE_TERMINAL && d->class->flush != NULL)
310         d->class->flush (d);
311     }
312 }
313
314 static void
315 output_set_title__ (struct output_engine *e, char **dst, const char *src)
316 {
317   free (*dst);
318   *dst = xstrdup_if_nonnull (src);
319
320   char *page_title
321     = (e->title && e->subtitle ? xasprintf ("%s\n%s", e->title, e->subtitle)
322        : e->title ? xstrdup (e->title)
323        : e->subtitle ? xstrdup (e->subtitle)
324        : xzalloc (1));
325   output_item_submit (text_item_create_nocopy (TEXT_ITEM_PAGE_TITLE,
326                                                page_title, NULL));
327 }
328
329 void
330 output_set_title (const char *title)
331 {
332   struct output_engine *e = engine_stack_top ();
333
334   output_set_title__ (e, &e->title, title);
335 }
336
337 void
338 output_set_subtitle (const char *subtitle)
339 {
340   struct output_engine *e = engine_stack_top ();
341
342   output_set_title__ (e, &e->subtitle, subtitle);
343 }
344
345 void
346 output_set_filename (const char *filename)
347 {
348   struct output_engine *e = engine_stack_top ();
349
350   string_map_replace (&e->heading_vars, "Filename", filename);
351 }
352
353 size_t
354 output_get_group_level (void)
355 {
356   struct output_engine *e = engine_stack_top ();
357
358   return e->n_groups;
359 }
360 \f
361 void
362 output_driver_init (struct output_driver *driver,
363                     const struct output_driver_class *class,
364                     const char *name, enum settings_output_devices type)
365 {
366   driver->class = class;
367   driver->name = xstrdup (name);
368   driver->device_type = type;
369 }
370
371 void
372 output_driver_destroy (struct output_driver *driver)
373 {
374   if (driver != NULL)
375     {
376       char *name = driver->name;
377       if (output_driver_is_registered (driver))
378         output_driver_unregister (driver);
379       if (driver->class->destroy)
380         driver->class->destroy (driver);
381       free (name);
382     }
383 }
384
385 const char *
386 output_driver_get_name (const struct output_driver *driver)
387 {
388   return driver->name;
389 }
390 \f
391 static struct output_engine *
392 output_driver_get_engine (const struct output_driver *driver)
393 {
394   struct output_engine *e;
395
396   ll_for_each (e, struct output_engine, ll, &engine_stack)
397     {
398       if (llx_find (llx_head (&e->drivers), llx_null (&e->drivers), driver))
399         return e;
400     }
401
402   return NULL;
403 }
404
405 void
406 output_driver_register (struct output_driver *driver)
407 {
408   struct output_engine *e = engine_stack_top ();
409
410   assert (!output_driver_is_registered (driver));
411   llx_push_tail (&e->drivers, driver, &llx_malloc_mgr);
412 }
413
414 void
415 output_driver_unregister (struct output_driver *driver)
416 {
417   struct output_engine *e = output_driver_get_engine (driver);
418
419   assert (e != NULL);
420   llx_remove (llx_find (llx_head (&e->drivers), llx_null (&e->drivers), driver),
421               &llx_malloc_mgr);
422 }
423
424 bool
425 output_driver_is_registered (const struct output_driver *driver)
426 {
427   return output_driver_get_engine (driver) != NULL;
428 }
429 \f
430 extern const struct output_driver_factory csv_driver_factory;
431 extern const struct output_driver_factory html_driver_factory;
432 extern const struct output_driver_factory list_driver_factory;
433 extern const struct output_driver_factory odt_driver_factory;
434 extern const struct output_driver_factory pdf_driver_factory;
435 extern const struct output_driver_factory png_driver_factory;
436 extern const struct output_driver_factory ps_driver_factory;
437 extern const struct output_driver_factory spv_driver_factory;
438 extern const struct output_driver_factory svg_driver_factory;
439 extern const struct output_driver_factory tex_driver_factory;
440 extern const struct output_driver_factory txt_driver_factory;
441
442 static const struct output_driver_factory *factories[] =
443   {
444     &txt_driver_factory,
445     &list_driver_factory,
446     &html_driver_factory,
447     &csv_driver_factory,
448     &odt_driver_factory,
449     &spv_driver_factory,
450     &pdf_driver_factory,
451     &ps_driver_factory,
452     &svg_driver_factory,
453     &png_driver_factory,
454     &tex_driver_factory,
455     NULL
456   };
457
458 static const struct output_driver_factory *
459 find_factory (const char *format)
460 {
461   const struct output_driver_factory **fp;
462
463   for (fp = factories; *fp != NULL; fp++)
464     {
465       const struct output_driver_factory *f = *fp;
466
467       if (!strcmp (f->extension, format))
468         return f;
469     }
470   return &txt_driver_factory;
471 }
472
473 static enum settings_output_devices
474 default_device_type (const char *file_name)
475 {
476   return (!strcmp (file_name, "-")
477           ? SETTINGS_DEVICE_TERMINAL
478           : SETTINGS_DEVICE_LISTING);
479 }
480
481 struct output_driver *
482 output_driver_create (struct string_map *options)
483 {
484   enum settings_output_devices device_type;
485   const struct output_driver_factory *f;
486   struct output_driver *driver;
487   char *device_string;
488   char *file_name;
489   char *format;
490
491   format = string_map_find_and_delete (options, "format");
492   file_name = string_map_find_and_delete (options, "output-file");
493
494   if (format == NULL)
495     {
496       if (file_name != NULL)
497         {
498           const char *extension = strrchr (file_name, '.');
499           format = xstrdup (extension != NULL ? extension + 1 : "");
500         }
501       else
502         format = xstrdup ("txt");
503     }
504   f = find_factory (format);
505
506   if (file_name == NULL)
507     file_name = xstrdup (f->default_file_name);
508
509   /* XXX should use parse_enum(). */
510   device_string = string_map_find_and_delete (options, "device");
511   if (device_string == NULL || device_string[0] == '\0')
512     device_type = default_device_type (file_name);
513   else if (!strcmp (device_string, "terminal"))
514     device_type = SETTINGS_DEVICE_TERMINAL;
515   else if (!strcmp (device_string, "listing"))
516     device_type = SETTINGS_DEVICE_LISTING;
517   else
518     {
519       msg (MW, _("%s is not a valid device type (the choices are `%s' and `%s')"),
520                      device_string, "terminal", "listing");
521       device_type = default_device_type (file_name);
522     }
523
524   struct file_handle *fh = fh_create_file (NULL, file_name, NULL, fh_default_properties ());
525
526   driver = f->create (fh, device_type, options);
527   if (driver != NULL)
528     {
529       const struct string_map_node *node;
530       const char *key;
531
532       STRING_MAP_FOR_EACH_KEY (key, node, options)
533         msg (MW, _("%s: unknown option `%s'"), file_name, key);
534     }
535   string_map_clear (options);
536
537   free (file_name);
538   free (format);
539   free (device_string);
540
541   return driver;
542 }
543
544 void
545 output_driver_parse_option (const char *option, struct string_map *options)
546 {
547   const char *equals = strchr (option, '=');
548   if (equals == NULL)
549     {
550       error (0, 0, _("%s: output option missing `='"), option);
551       return;
552     }
553
554   char *key = xmemdup0 (option, equals - option);
555   if (string_map_contains (options, key))
556     {
557       error (0, 0, _("%s: output option specified more than once"), key);
558       free (key);
559       return;
560     }
561
562   char *value = xmemdup0 (equals + 1, strlen (equals + 1));
563   string_map_insert_nocopy (options, key, value);
564 }
565 \f
566 char *
567 output_driver_substitute_heading_vars (const char *src, int page_number)
568 {
569   struct output_engine *e = engine_stack_top ();
570   struct string dst = DS_EMPTY_INITIALIZER;
571   ds_extend (&dst, strlen (src));
572   for (const char *p = src; *p;)
573     {
574       if (!strncmp (p, "&amp;[", 6))
575         {
576           if (page_number != INT_MIN)
577             {
578               const char *start = p + 6;
579               const char *end = strchr (start, ']');
580               if (end)
581                 {
582                   const char *value = string_map_find__ (&e->heading_vars,
583                                                          start, end - start);
584                   if (value)
585                     ds_put_cstr (&dst, value);
586                   else if (ss_equals (ss_buffer (start, end - start),
587                                       ss_cstr ("Page")))
588                     ds_put_format (&dst, "%d", page_number);
589                   p = end + 1;
590                   continue;
591                 }
592             }
593           ds_put_cstr (&dst, "&amp;");
594           p += 5;
595         }
596       else
597         ds_put_byte (&dst, *p++);
598     }
599   return ds_steal_cstr (&dst);
600 }