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