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