work
[pspp] / src / output / csv.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009, 2010, 2012, 2013, 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 <errno.h>
20 #include <stdlib.h>
21
22 #include "data/file-name.h"
23 #include "data/file-handle-def.h"
24 #include "libpspp/assertion.h"
25 #include "libpspp/compiler.h"
26 #include "libpspp/message.h"
27 #include "libpspp/str.h"
28 #include "libpspp/string-map.h"
29 #include "output/text-item.h"
30 #include "output/driver-provider.h"
31 #include "output/options.h"
32 #include "output/message-item.h"
33 #include "output/page-eject-item.h"
34 #include "output/pivot-output.h"
35 #include "output/pivot-table.h"
36 #include "output/table-item.h"
37 #include "output/table-provider.h"
38
39 #include "gl/minmax.h"
40 #include "gl/xalloc.h"
41 #include "gl/xvasprintf.h"
42
43 #include "gettext.h"
44 #define _(msgid) gettext (msgid)
45
46 /* Comma-separated value output driver. */
47 struct csv_driver
48   {
49     struct output_driver driver;
50
51     char *separator;            /* Field separator (usually comma or tab). */
52     int quote;                  /* Quote character (usually ' or ") or 0. */
53     char *quote_set;            /* Characters that force quoting. */
54     bool titles;                /* Print table titles? */
55     bool captions;              /* Print table captions? */
56
57     struct file_handle *handle;
58     FILE *file;                 /* Output file. */
59     int n_items;                /* Number of items output so far. */
60   };
61
62 static const struct output_driver_class csv_driver_class;
63
64 static struct csv_driver *
65 csv_driver_cast (struct output_driver *driver)
66 {
67   assert (driver->class == &csv_driver_class);
68   return UP_CAST (driver, struct csv_driver, driver);
69 }
70
71 static struct driver_option *
72 opt (struct output_driver *d, struct string_map *options, const char *key,
73      const char *default_value)
74 {
75   return driver_option_get (d, options, key, default_value);
76 }
77
78 static struct output_driver *
79 csv_create (struct file_handle *fh, enum settings_output_devices device_type,
80             struct string_map *o)
81 {
82   struct output_driver *d;
83   struct csv_driver *csv;
84   char *quote;
85
86   csv = xzalloc (sizeof *csv);
87   d = &csv->driver;
88   output_driver_init (&csv->driver, &csv_driver_class, fh_get_file_name (fh), device_type);
89
90   csv->separator = parse_string (opt (d, o, "separator", ","));
91   quote = parse_string (opt (d, o, "quote", "\""));
92   csv->quote = quote[0];
93   free (quote);
94   csv->quote_set = xasprintf ("\n\r\t%s%c", csv->separator, csv->quote);
95   csv->titles = parse_boolean (opt (d, o, "titles", "true"));
96   csv->captions = parse_boolean (opt (d, o, "captions", "true"));
97   csv->handle = fh;
98   csv->file = fn_open (fh, "w");
99   csv->n_items = 0;
100
101   if (csv->file == NULL)
102     {
103       msg_error (errno, _("error opening output file `%s'"), fh_get_file_name (fh));
104       output_driver_destroy (d);
105       return NULL;
106     }
107
108   return d;
109 }
110
111 static void
112 csv_destroy (struct output_driver *driver)
113 {
114   struct csv_driver *csv = csv_driver_cast (driver);
115
116   if (csv->file != NULL)
117     fn_close (csv->handle, csv->file);
118
119   free (csv->separator);
120   free (csv->quote_set);
121   fh_unref (csv->handle);
122   free (csv);
123 }
124
125 static void
126 csv_flush (struct output_driver *driver)
127 {
128   struct csv_driver *csv = csv_driver_cast (driver);
129   if (csv->file != NULL)
130     fflush (csv->file);
131 }
132
133 static void
134 csv_output_field__ (struct csv_driver *csv, struct substring field)
135 {
136   ss_ltrim (&field, ss_cstr (" "));
137
138   if (csv->quote && ss_cspan (field, ss_cstr (csv->quote_set)) < field.length)
139     {
140       putc (csv->quote, csv->file);
141       for (size_t i = 0; i < field.length; i++)
142         {
143           if (field.string[i] == csv->quote)
144             putc (csv->quote, csv->file);
145           putc (field.string[i], csv->file);
146         }
147       putc (csv->quote, csv->file);
148     }
149   else
150     fwrite (field.string, field.length, 1, csv->file);
151 }
152
153 static void
154 csv_output_field (struct csv_driver *csv, const char *field)
155 {
156   csv_output_field__ (csv, ss_cstr (field));
157 }
158
159 static void
160 csv_put_separator (struct csv_driver *csv)
161 {
162   if (csv->n_items++ > 0)
163     putc ('\n', csv->file);
164 }
165
166 static void
167 csv_output_lines (struct csv_driver *csv, const char *text_)
168 {
169   struct substring text = ss_cstr (text_);
170   struct substring line;
171   size_t save_idx = 0;
172   while (ss_separate (text, ss_cstr ("\n"), &save_idx, &line))
173     {
174       csv_output_field__ (csv, line);
175       putc ('\n', csv->file);
176     }
177 }
178
179 static void
180 csv_output_table_cell (struct csv_driver *csv, const struct table_cell *cell,
181                        const char *leader)
182 {
183   if (!cell)
184     return;
185
186   if (!(cell->options & TAB_MARKUP) && !cell->n_footnotes
187       && !cell->n_subscripts && !leader)
188     csv_output_field (csv, cell->text);
189   else
190     {
191       struct string s = DS_EMPTY_INITIALIZER;
192
193       if (leader)
194         ds_put_format (&s, "%s: ", leader);
195
196       if (cell->options & TAB_MARKUP)
197         {
198           char *t = output_get_text_from_markup (cell->text);
199           ds_put_cstr (&s, t);
200           free (t);
201         }
202       else
203         ds_put_cstr (&s, cell->text);
204
205       if (cell->n_subscripts)
206         for (size_t i = 0; i < cell->n_subscripts; i++)
207           ds_put_format (&s, "%c%s",
208                          i ? ',' : '_', cell->subscripts[i]);
209       for (size_t i = 0; i < cell->n_footnotes; i++)
210         {
211           ds_put_byte (&s, '[');
212           pivot_value_format (cell->footnotes[i]->marker,
213                               SETTINGS_VALUE_SHOW_DEFAULT,
214                               SETTINGS_VALUE_SHOW_DEFAULT, &s);
215           ds_put_byte (&s, ']');
216         }
217       csv_output_field (csv, ds_cstr (&s));
218       ds_destroy (&s);
219     }
220 }
221
222 static void
223 csv_output_table__ (struct csv_driver *csv, const struct table *t,
224                     const char *leader)
225 {
226   if (!t)
227     return;
228
229   for (int y = 0; y < t->n[TABLE_VERT]; y++)
230     {
231       for (int x = 0; x < t->n[TABLE_HORZ]; x++)
232         {
233           struct table_cell cell;
234
235           table_get_cell (t, x, y, &cell);
236
237           if (x > 0)
238             fputs (csv->separator, csv->file);
239
240           if (x != cell.d[TABLE_HORZ][0] || y != cell.d[TABLE_VERT][0])
241             csv_output_field (csv, "");
242           else
243             csv_output_table_cell (csv, &cell, !x ? leader : NULL);
244         }
245       putc ('\n', csv->file);
246     }
247 }
248
249 static void
250 csv_output_table_layer (struct csv_driver *csv, const struct pivot_table *pt,
251                         const size_t *layer_indexes)
252 {
253   struct table *title, *layers, *body, *caption, *footnotes;
254   pivot_output (pt, layer_indexes, true, &title, &layers, &body,
255                 &caption, &footnotes, NULL, NULL);
256
257   csv_put_separator (csv);
258   csv_output_table__ (csv, title, "Table");
259   csv_output_table__ (csv, layers, "Layer");
260   csv_output_table__ (csv, body, NULL);
261   csv_output_table__ (csv, caption, "Caption");
262   csv_output_table__ (csv, footnotes, "Footnote");
263
264   table_unref (title);
265   table_unref (layers);
266   table_unref (body);
267   table_unref (caption);
268   table_unref (footnotes);
269 }
270
271 static void
272 csv_submit (struct output_driver *driver,
273             const struct output_item *output_item)
274 {
275   struct csv_driver *csv = csv_driver_cast (driver);
276
277   if (is_table_item (output_item))
278     {
279       const struct pivot_table *pt = to_table_item (output_item)->pt;
280
281       size_t *layer_indexes;
282       PIVOT_OUTPUT_FOR_EACH_LAYER (layer_indexes, pt, true)
283         csv_output_table_layer (csv, pt, layer_indexes);
284     }
285   else if (is_text_item (output_item))
286     {
287       const struct text_item *text_item = to_text_item (output_item);
288       enum text_item_type type = text_item_get_type (text_item);
289       const char *text = text_item_get_text (text_item);
290
291       if (type == TEXT_ITEM_SYNTAX || type == TEXT_ITEM_PAGE_TITLE)
292         return;
293
294       csv_put_separator (csv);
295
296       if (text_item->style.markup)
297         {
298           char *plain_text = output_get_text_from_markup (text);
299           csv_output_lines (csv, plain_text);
300           free (plain_text);
301         }
302       else
303         csv_output_lines (csv, text);
304     }
305   else if (is_page_eject_item (output_item))
306     {
307       csv_put_separator (csv);
308       csv_output_lines (csv, "");
309     }
310   else if (is_message_item (output_item))
311     {
312       const struct message_item *message_item = to_message_item (output_item);
313       char *s = msg_to_string (message_item_get_msg (message_item));
314       csv_put_separator (csv);
315       csv_output_field (csv, s);
316       free (s);
317       putc ('\n', csv->file);
318     }
319 }
320
321 struct output_driver_factory csv_driver_factory = { "csv", "-", csv_create };
322
323 static const struct output_driver_class csv_driver_class =
324   {
325     "csv",
326     csv_destroy,
327     csv_submit,
328     csv_flush,
329   };