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