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