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