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