Merge 'master' into 'psppsheet'.
[pspp] / src / data / gnumeric-reader.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2007, 2009, 2010, 2011, 2012 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 "libpspp/message.h"
20 #include "libpspp/misc.h"
21
22 #include "gl/minmax.h"
23 #include "gl/c-strtod.h"
24
25 #include "gettext.h"
26 #define _(msgid) gettext (msgid)
27 #define N_(msgid) (msgid)
28
29 #include "spreadsheet-reader.h"
30
31 #if !GNM_SUPPORT
32
33 struct casereader *
34 gnumeric_open_reader (struct spreadsheet_read_info *gri, struct dictionary **dict)
35 {
36   msg (ME, _("Support for %s files was not compiled into this installation of PSPP"), "Gnumeric");
37
38   return NULL;
39 }
40
41 #else
42
43 #include "data/gnumeric-reader.h"
44
45 #include <assert.h>
46 #include <stdbool.h>
47 #include <errno.h>
48 #include <libxml/xmlreader.h>
49 #include <zlib.h>
50
51 #include "data/case.h"
52 #include "data/casereader-provider.h"
53 #include "data/dictionary.h"
54 #include "data/identifier.h"
55 #include "data/value.h"
56 #include "data/variable.h"
57 #include "libpspp/i18n.h"
58 #include "libpspp/str.h"
59
60 #include "gl/xalloc.h"
61
62 static void gnm_file_casereader_destroy (struct casereader *, void *);
63
64 static struct ccase *gnm_file_casereader_read (struct casereader *, void *);
65
66 static const struct casereader_class gnm_file_casereader_class =
67   {
68     gnm_file_casereader_read,
69     gnm_file_casereader_destroy,
70     NULL,
71     NULL,
72   };
73
74 enum reader_state
75   {
76     STATE_INIT = 0,        /* Initial state */
77     STATE_SHEET_START,     /* Found the start of a sheet */
78     STATE_SHEET_NAME,      /* Found the sheet name */
79     STATE_MAXROW,
80     STATE_SHEET_FOUND,     /* Found the sheet that we actually want */
81     STATE_CELLS_START,     /* Found the start of the cell array */
82     STATE_CELL             /* Found a cell */
83   };
84
85
86 struct gnumeric_reader
87 {
88   xmlTextReaderPtr xtr;
89
90   enum reader_state state;
91   int row;
92   int col;
93   int node_type;
94   int sheet_index;
95
96
97   const xmlChar *target_sheet;
98   int target_sheet_index;
99
100   int start_row;
101   int start_col;
102   int stop_row;
103   int stop_col;
104
105   struct caseproto *proto;
106   struct dictionary *dict;
107   struct ccase *first_case;
108   bool used_first_case;
109 };
110
111 static void process_node (struct gnumeric_reader *r);
112
113
114 static void
115 gnm_file_casereader_destroy (struct casereader *reader UNUSED, void *r_)
116 {
117   struct gnumeric_reader *r = r_;
118   if ( r == NULL)
119         return ;
120
121   if ( r->xtr)
122     xmlFreeTextReader (r->xtr);
123
124   if ( ! r->used_first_case )
125     case_unref (r->first_case);
126
127   caseproto_unref (r->proto);
128
129   free (r);
130 }
131
132 static void
133 process_node (struct gnumeric_reader *r)
134 {
135   xmlChar *name = xmlTextReaderName (r->xtr);
136   if (name == NULL)
137     name = xmlStrdup (_xml ("--"));
138
139
140   r->node_type = xmlTextReaderNodeType (r->xtr);
141
142   switch ( r->state)
143     {
144     case STATE_INIT:
145       if (0 == xmlStrcasecmp (name, _xml("gnm:Sheet")) &&
146           XML_READER_TYPE_ELEMENT  == r->node_type)
147         {
148           ++r->sheet_index;
149           r->state = STATE_SHEET_START;
150         }
151       break;
152     case STATE_SHEET_START:
153       if (0 == xmlStrcasecmp (name, _xml("gnm:Name"))  &&
154           XML_READER_TYPE_ELEMENT  == r->node_type)
155         {
156           r->state = STATE_SHEET_NAME;
157         }
158       break;
159     case STATE_SHEET_NAME:
160       if (0 == xmlStrcasecmp (name, _xml("gnm:Name"))  &&
161           XML_READER_TYPE_END_ELEMENT  == r->node_type)
162         {
163           r->state = STATE_INIT;
164         }
165       else if (XML_READER_TYPE_TEXT == r->node_type)
166         {
167           if ( r->target_sheet != NULL)
168             {
169               xmlChar *value = xmlTextReaderValue (r->xtr);
170               if ( 0 == xmlStrcmp (value, r->target_sheet))
171                 r->state = STATE_SHEET_FOUND;
172               free (value);
173             }
174           else if (r->target_sheet_index == r->sheet_index)
175             {
176               r->state = STATE_SHEET_FOUND;
177             }
178         }
179       break;
180     case STATE_SHEET_FOUND:
181       if (0 == xmlStrcasecmp (name, _xml("gnm:Cells"))  &&
182           XML_READER_TYPE_ELEMENT  == r->node_type)
183         {
184           if (! xmlTextReaderIsEmptyElement (r->xtr))
185             r->state = STATE_CELLS_START;
186         }
187       else if (0 == xmlStrcasecmp (name, _xml("gnm:MaxRow"))  &&
188           XML_READER_TYPE_ELEMENT  == r->node_type)
189         {
190           r->state = STATE_MAXROW;
191         }
192       else if (0 == xmlStrcasecmp (name, _xml("gnm:Sheet"))  &&
193           XML_READER_TYPE_END_ELEMENT  == r->node_type)
194         {
195           r->state = STATE_INIT;
196         }
197       break;
198     case STATE_MAXROW:
199       if (0 == xmlStrcasecmp (name, _xml("gnm:MaxRow"))  &&
200           XML_READER_TYPE_END_ELEMENT  == r->node_type)
201         {
202           r->state = STATE_SHEET_FOUND;
203         }
204     case STATE_CELLS_START:
205       if (0 == xmlStrcasecmp (name, _xml ("gnm:Cell"))  &&
206           XML_READER_TYPE_ELEMENT  == r->node_type)
207         {
208           xmlChar *attr = NULL;
209           r->state = STATE_CELL;
210
211           attr = xmlTextReaderGetAttribute (r->xtr, _xml ("Col"));
212           r->col =  _xmlchar_to_int (attr);
213           free (attr);
214
215           attr = xmlTextReaderGetAttribute (r->xtr, _xml ("Row"));
216           r->row = _xmlchar_to_int (attr);
217           free (attr);
218         }
219       else if (0 == xmlStrcasecmp (name, _xml("gnm:Cells"))  &&
220                XML_READER_TYPE_END_ELEMENT  == r->node_type)
221         r->state = STATE_SHEET_NAME;
222
223       break;
224     case STATE_CELL:
225       if (0 == xmlStrcasecmp (name, _xml("gnm:Cell"))  &&
226                               XML_READER_TYPE_END_ELEMENT  == r->node_type)
227         {
228           r->state = STATE_CELLS_START;
229         }
230       break;
231     default:
232       break;
233     };
234
235   xmlFree (name);
236 }
237
238
239 /*
240    Sets the VAR of case C, to the value corresponding to the xml string XV
241  */
242 static void
243 convert_xml_string_to_value (struct ccase *c, const struct variable *var,
244                              const xmlChar *xv)
245 {
246   union value *v = case_data_rw (c, var);
247
248   if (xv == NULL)
249     value_set_missing (v, var_get_width (var));
250   else if ( var_is_alpha (var))
251     value_copy_str_rpad (v, var_get_width (var), xv, ' ');
252   else
253     {
254       const char *text = CHAR_CAST (const char *, xv);
255       char *endptr;
256
257       errno = 0;
258       v->f = c_strtod (text, &endptr);
259       if ( errno != 0 || endptr == text)
260         v->f = SYSMIS;
261     }
262 }
263
264 struct var_spec
265 {
266   char *name;
267   int width;
268   xmlChar *first_value;
269 };
270
271 struct casereader *
272 gnumeric_open_reader (struct spreadsheet_read_info *gri, struct dictionary **dict)
273 {
274   unsigned long int vstart = 0;
275   int ret;
276   casenumber n_cases = CASENUMBER_MAX;
277   int i;
278   struct var_spec *var_spec = NULL;
279   int n_var_specs = 0;
280
281   struct gnumeric_reader *r = NULL;
282
283   gzFile gz = gzopen (gri->file_name, "r");
284
285   if ( NULL == gz)
286     {
287       msg (ME, _("Error opening `%s' for reading as a Gnumeric file: %s."),
288            gri->file_name, strerror (errno));
289
290       goto error;
291     }
292
293   r = xzalloc (sizeof *r);
294
295   r->xtr = xmlReaderForIO ((xmlInputReadCallback) gzread,
296                            (xmlInputCloseCallback) gzclose, gz,
297                            NULL, NULL, 0);
298
299   if ( r->xtr == NULL )
300     goto error;
301
302   if ( gri->cell_range )
303     {
304       if ( ! convert_cell_ref (gri->cell_range,
305                                &r->start_col, &r->start_row,
306                                &r->stop_col, &r->stop_row))
307         {
308           msg (SE, _("Invalid cell range `%s'"),
309                gri->cell_range);
310           goto error;
311         }
312     }
313   else
314     {
315       r->start_col = 0;
316       r->start_row = 0;
317       r->stop_col = -1;
318       r->stop_row = -1;
319     }
320
321   r->state = STATE_INIT;
322   r->target_sheet = BAD_CAST gri->sheet_name;
323   r->target_sheet_index = gri->sheet_index;
324   r->row = r->col = -1;
325   r->sheet_index = 0;
326
327   /* Advance to the start of the cells for the target sheet */
328   while ( (r->state != STATE_CELL || r->row < r->start_row )
329           && 1 == (ret = xmlTextReaderRead (r->xtr)))
330     {
331       xmlChar *value ;
332       process_node (r);
333       value = xmlTextReaderValue (r->xtr);
334
335       if ( r->state == STATE_MAXROW  && r->node_type == XML_READER_TYPE_TEXT)
336         {
337           n_cases = 1 + _xmlchar_to_int (value) ;
338         }
339       free (value);
340     }
341
342
343   /* If a range has been given, then  use that to calculate the number
344      of cases */
345   if ( gri->cell_range)
346     {
347       n_cases = MIN (n_cases, r->stop_row - r->start_row + 1);
348     }
349
350   if ( gri->read_names )
351     {
352       r->start_row++;
353       n_cases --;
354     }
355
356   /* Read in the first row of cells,
357      including the headers if read_names was set */
358   while (
359          (( r->state == STATE_CELLS_START && r->row <= r->start_row) || r->state == STATE_CELL )
360          && (ret = xmlTextReaderRead (r->xtr))
361          )
362     {
363       int idx;
364       process_node (r);
365
366       if ( r->row > r->start_row ) break;
367
368       if ( r->col < r->start_col ||
369            (r->stop_col != -1 && r->col > r->stop_col))
370         continue;
371
372       idx = r->col - r->start_col;
373
374       if ( idx  >= n_var_specs )
375         {
376           n_var_specs =  idx + 1 ;
377           var_spec = xrealloc (var_spec, sizeof (*var_spec) * n_var_specs);
378           var_spec [idx].name = NULL;
379           var_spec [idx].width = -1;
380           var_spec [idx].first_value = NULL;
381         }
382
383       if ( r->node_type == XML_READER_TYPE_TEXT )
384         {
385           xmlChar *value = xmlTextReaderValue (r->xtr);
386           const char *text  = CHAR_CAST (const char *, value);
387
388           if ( r->row < r->start_row)
389             {
390               if ( gri->read_names )
391                 {
392                   var_spec [idx].name = xstrdup (text);
393                 }
394             }
395           else
396             {
397               var_spec [idx].first_value = xmlStrdup (value);
398
399               if (-1 ==  var_spec [idx].width )
400                 var_spec [idx].width = (gri->asw == -1) ?
401                   ROUND_UP (strlen(text), SPREADSHEET_DEFAULT_WIDTH) : gri->asw;
402             }
403
404           free (value);
405         }
406       else if ( r->node_type == XML_READER_TYPE_ELEMENT
407                 && r->state == STATE_CELL)
408         {
409           if ( r->row == r->start_row )
410             {
411               xmlChar *attr =
412                 xmlTextReaderGetAttribute (r->xtr, _xml ("ValueType"));
413
414               if ( NULL == attr || 60 !=  _xmlchar_to_int (attr))
415                 var_spec [idx].width = 0;
416
417               free (attr);
418             }
419         }
420     }
421
422   {
423     const xmlChar *enc = xmlTextReaderConstEncoding (r->xtr);
424     if ( enc == NULL)
425       goto error;
426     /* Create the dictionary and populate it */
427     *dict = r->dict = dict_create (CHAR_CAST (const char *, enc));
428   }
429
430   for (i = 0 ; i < n_var_specs ; ++i )
431     {
432       char *name;
433
434       /* Probably no data exists for this variable, so allocate a
435          default width */
436       if ( var_spec[i].width == -1 )
437         var_spec[i].width = SPREADSHEET_DEFAULT_WIDTH;
438
439       name = dict_make_unique_var_name (r->dict, var_spec[i].name, &vstart);
440       dict_create_var (r->dict, name, var_spec[i].width);
441       free (name);
442     }
443
444   /* Create the first case, and cache it */
445   r->used_first_case = false;
446
447   if ( n_var_specs ==  0 )
448     {
449       msg (MW, _("Selected sheet or range of spreadsheet `%s' is empty."),
450            gri->file_name);
451       goto error;
452     }
453
454   r->proto = caseproto_ref (dict_get_proto (r->dict));
455   r->first_case = case_create (r->proto);
456   case_set_missing (r->first_case);
457
458   for ( i = 0 ; i < n_var_specs ; ++i )
459     {
460       const struct variable *var = dict_get_var (r->dict, i);
461
462       convert_xml_string_to_value (r->first_case, var,
463                                    var_spec[i].first_value);
464     }
465
466   for ( i = 0 ; i < n_var_specs ; ++i )
467     {
468       free (var_spec[i].first_value);
469       free (var_spec[i].name);
470     }
471
472   free (var_spec);
473
474   return casereader_create_sequential
475     (NULL,
476      r->proto,
477      n_cases,
478      &gnm_file_casereader_class, r);
479
480
481  error:
482   for ( i = 0 ; i < n_var_specs ; ++i )
483     {
484       free (var_spec[i].first_value);
485       free (var_spec[i].name);
486     }
487
488   free (var_spec);
489   dict_destroy (*dict);
490
491   gnm_file_casereader_destroy (NULL, r);
492
493   return NULL;
494 };
495
496
497 /* Reads and returns one case from READER's file.  Returns a null
498    pointer on failure. */
499 static struct ccase *
500 gnm_file_casereader_read (struct casereader *reader UNUSED, void *r_)
501 {
502   struct ccase *c;
503   int ret = 0;
504
505   struct gnumeric_reader *r = r_;
506   int current_row = r->row;
507
508   if ( !r->used_first_case )
509     {
510       r->used_first_case = true;
511       return r->first_case;
512     }
513
514   c = case_create (r->proto);
515   case_set_missing (c);
516
517   while ((r->state == STATE_CELL || r->state == STATE_CELLS_START )
518          && r->row == current_row && (ret = xmlTextReaderRead (r->xtr)))
519     {
520       process_node (r);
521
522       if ( r->col < r->start_col || (r->stop_col != -1 &&
523                                      r->col > r->stop_col))
524         continue;
525
526       if ( r->col - r->start_col >= caseproto_get_n_widths (r->proto))
527         continue;
528
529       if ( r->stop_row != -1 && r->row > r->stop_row)
530         break;
531
532       if ( r->node_type == XML_READER_TYPE_TEXT )
533         {
534           xmlChar *value = xmlTextReaderValue (r->xtr);
535
536           const int idx = r->col - r->start_col;
537
538           const struct variable *var = dict_get_var (r->dict, idx);
539
540           convert_xml_string_to_value (c, var, value);
541
542           free (value);
543         }
544
545     }
546
547   if (ret == 1)
548     return c;
549   else
550     {
551       case_unref (c);
552       return NULL;
553     }
554 }
555
556
557 #endif /* GNM_SUPPORT */