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