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