Fixed some memory leaks
[pspp] / src / data / ods-reader.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2011, 2012, 2013 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 #include "libpspp/assertion.h"
22
23 #include "data/data-in.h"
24
25 #include "gl/c-strtod.h"
26 #include "gl/minmax.h"
27
28 #include "gettext.h"
29 #define _(msgid) gettext (msgid)
30 #define N_(msgid) (msgid)
31
32 #include "ods-reader.h"
33 #include "spreadsheet-reader.h"
34
35 #if !ODF_READ_SUPPORT
36
37 struct casereader *
38 ods_open_reader (const struct spreadsheet_read_options *opts, 
39                  struct dictionary **dict)
40 {
41   msg (ME, _("Support for %s files was not compiled into this installation of PSPP"), "OpenDocument");
42
43   return NULL;
44 }
45
46 #else
47
48 #include "libpspp/zip-reader.h"
49
50
51 #include <assert.h>
52 #include <stdbool.h>
53 #include <errno.h>
54 #include <libxml/xmlreader.h>
55 #include <zlib.h>
56
57 #include "data/format.h"
58 #include "data/case.h"
59 #include "data/casereader-provider.h"
60 #include "data/dictionary.h"
61 #include "data/identifier.h"
62 #include "data/value.h"
63 #include "data/variable.h"
64 #include "libpspp/i18n.h"
65 #include "libpspp/str.h"
66
67 #include "gl/xalloc.h"
68
69 static void ods_file_casereader_destroy (struct casereader *, void *);
70
71 static struct ccase *ods_file_casereader_read (struct casereader *, void *);
72
73 static const struct casereader_class ods_file_casereader_class =
74   {
75     ods_file_casereader_read,
76     ods_file_casereader_destroy,
77     NULL,
78     NULL,
79   };
80
81 struct sheet_detail
82 {
83   /* The name of the sheet (utf8 encoding) */
84   char *name;
85
86   int start_col;
87   int stop_col;
88   int start_row;
89   int stop_row;
90 };
91
92
93 enum reader_state
94   {
95     STATE_INIT = 0,        /* Initial state */
96     STATE_SPREADSHEET,     /* Found the start of the spreadsheet doc */
97     STATE_TABLE,           /* Found the sheet that we actually want */
98     STATE_ROW,             /* Found the start of the cell array */
99     STATE_CELL,            /* Found a cell */
100     STATE_CELL_CONTENT     /* Found a the text within a cell */
101   };
102
103 struct ods_reader
104 {
105   struct spreadsheet spreadsheet;
106   struct zip_reader *zreader;
107   xmlTextReaderPtr xtr;
108
109   enum reader_state state;
110   int row;
111   int col;
112   int node_type;
113   int current_sheet;
114   xmlChar *current_sheet_name;
115
116   const xmlChar *target_sheet_name;
117   int target_sheet_index;
118
119
120   int start_row;
121   int start_col;
122   int stop_row;
123   int stop_col;
124
125   int col_span;
126
127   struct sheet_detail *sheets;
128   int n_allocated_sheets;
129
130   struct caseproto *proto;
131   struct dictionary *dict;
132   struct ccase *first_case;
133   bool used_first_case;
134   bool read_names;
135
136   struct string ods_errs;
137 };
138
139
140 static bool
141 reading_target_sheet (const struct ods_reader *r)
142 {
143   if (r->target_sheet_name != NULL)
144     {
145       if ( 0 == xmlStrcmp (r->target_sheet_name, r->current_sheet_name))
146         return true;
147     }
148   
149   if (r->target_sheet_index == r->current_sheet + 1)
150     return true;
151
152   return false;
153 }
154
155
156 static void process_node (struct ods_reader *r);
157
158
159 const char *
160 ods_get_sheet_name (struct spreadsheet *s, int n)
161 {
162   struct ods_reader *or = (struct ods_reader *) s;
163   
164   assert (n < s->n_sheets);
165
166   while ( 
167           (or->n_allocated_sheets <= n)
168           || or->state != STATE_SPREADSHEET
169           )
170     {
171       int ret = xmlTextReaderRead (or->xtr);
172       if ( ret != 1)
173         break;
174
175       process_node (or);
176     }
177
178   return or->sheets[n].name;
179 }
180
181 char *
182 ods_get_sheet_range (struct spreadsheet *s, int n)
183 {
184   struct ods_reader *or = (struct ods_reader *) s;
185   
186   assert (n < s->n_sheets);
187
188   while ( 
189           (or->n_allocated_sheets <= n)
190           || (or->sheets[n].stop_row == -1) 
191           || or->state != STATE_SPREADSHEET
192           )
193     {
194       int ret = xmlTextReaderRead (or->xtr);
195       if ( ret != 1)
196         break;
197
198       process_node (or);
199     }
200
201   return create_cell_ref (
202                           or->sheets[n].start_col,
203                           or->sheets[n].start_row,
204                           or->sheets[n].stop_col,
205                           or->sheets[n].stop_row);
206 }
207
208
209 static void
210 ods_file_casereader_destroy (struct casereader *reader UNUSED, void *r_)
211 {
212   int i;
213   struct ods_reader *r = r_;
214   if ( r == NULL)
215     return ;
216
217   if (r->xtr)
218     xmlFreeTextReader (r->xtr);
219   r->xtr = NULL;
220
221   if ( ! ds_is_empty (&r->ods_errs))
222     msg (ME, "%s", ds_cstr (&r->ods_errs));
223
224   ds_destroy (&r->ods_errs);
225
226   if ( ! r->used_first_case )
227     case_unref (r->first_case);
228
229   caseproto_unref (r->proto);
230
231   xmlFree (r->current_sheet_name);
232
233   for (i = 0; i < r->n_allocated_sheets; ++i)
234   {
235     xmlFree (r->sheets[i].name);
236   }
237
238   free (r->sheets);
239
240   free (r);
241 }
242
243 static void
244 process_node (struct ods_reader *r)
245 {
246   xmlChar *name = xmlTextReaderName (r->xtr);
247   if (name == NULL)
248     name = xmlStrdup (_xml ("--"));
249
250
251   r->node_type = xmlTextReaderNodeType (r->xtr);
252
253   switch (r->state)
254     {
255     case STATE_INIT:
256       if (0 == xmlStrcasecmp (name, _xml("office:spreadsheet")) &&
257           XML_READER_TYPE_ELEMENT  == r->node_type)
258         {
259           r->state = STATE_SPREADSHEET;
260           r->current_sheet = -1;
261           r->current_sheet_name = NULL;
262         }
263       break;
264     case STATE_SPREADSHEET:
265       if (0 == xmlStrcasecmp (name, _xml("table:table"))
266           && 
267           (XML_READER_TYPE_ELEMENT == r->node_type))
268         {
269           xmlFree (r->current_sheet_name);
270           r->current_sheet_name = xmlTextReaderGetAttribute (r->xtr, _xml ("table:name"));
271
272           ++r->current_sheet;
273
274           if (r->current_sheet >= r->n_allocated_sheets)
275             {
276               assert (r->current_sheet == r->n_allocated_sheets);
277               r->sheets = xrealloc (r->sheets, sizeof (*r->sheets) * ++r->n_allocated_sheets);
278               r->sheets[r->n_allocated_sheets - 1].start_col = -1;
279               r->sheets[r->n_allocated_sheets - 1].stop_col = -1;
280               r->sheets[r->n_allocated_sheets - 1].start_row = -1;
281               r->sheets[r->n_allocated_sheets - 1].stop_row = -1;
282               r->sheets[r->n_allocated_sheets - 1].name = CHAR_CAST (char *, xmlStrdup (r->current_sheet_name));
283             }
284
285           r->col = 0;
286           r->row = 0;
287
288           r->state = STATE_TABLE;
289         }
290       else if (0 == xmlStrcasecmp (name, _xml("office:spreadsheet")) &&
291                XML_READER_TYPE_ELEMENT  == r->node_type)
292         {
293           r->state = STATE_INIT;
294         }
295       break;
296     case STATE_TABLE:
297       if (0 == xmlStrcasecmp (name, _xml("table:table-row")) && 
298           (XML_READER_TYPE_ELEMENT  == r->node_type))
299         {
300           xmlChar *value =
301             xmlTextReaderGetAttribute (r->xtr,
302                                        _xml ("table:number-rows-repeated"));
303           
304           int row_span = value ? _xmlchar_to_int (value) : 1;
305
306           r->row += row_span;
307           r->col = 0;
308           
309           if (! xmlTextReaderIsEmptyElement (r->xtr))
310             r->state = STATE_ROW;
311
312           xmlFree (value);
313         }
314       else if (0 == xmlStrcasecmp (name, _xml("table:table")) && 
315                (XML_READER_TYPE_END_ELEMENT  == r->node_type))
316         {
317           r->state = STATE_SPREADSHEET;
318         }
319       break;
320     case STATE_ROW:
321       if ( (0 == xmlStrcasecmp (name, _xml ("table:table-cell")))
322            && 
323            (XML_READER_TYPE_ELEMENT  == r->node_type))
324         {
325           xmlChar *value =
326             xmlTextReaderGetAttribute (r->xtr,
327                                        _xml ("table:number-columns-repeated"));
328           
329           r->col_span = value ? _xmlchar_to_int (value) : 1;
330           r->col += r->col_span;
331
332           if (! xmlTextReaderIsEmptyElement (r->xtr))
333             r->state = STATE_CELL;
334
335           xmlFree (value);
336         }
337       else if ( (0 == xmlStrcasecmp (name, _xml ("table:table-row")))
338                 &&
339                 (XML_READER_TYPE_END_ELEMENT  == r->node_type))
340         {
341           r->state = STATE_TABLE;
342         }
343       break;
344     case STATE_CELL:
345       if ( (0 == xmlStrcasecmp (name, _xml("text:p")))
346             &&
347            ( XML_READER_TYPE_ELEMENT  == r->node_type))
348         {
349           if (! xmlTextReaderIsEmptyElement (r->xtr))
350             r->state = STATE_CELL_CONTENT;
351         }
352       else if
353         ( (0 == xmlStrcasecmp (name, _xml("table:table-cell")))
354           &&
355           (XML_READER_TYPE_END_ELEMENT  == r->node_type)
356           )
357         {
358           r->state = STATE_ROW;
359         }
360       break;
361     case STATE_CELL_CONTENT:
362       assert (r->current_sheet >= 0);
363       assert (r->current_sheet < r->n_allocated_sheets);
364
365       if (r->sheets[r->current_sheet].start_row == -1)
366         r->sheets[r->current_sheet].start_row = r->row - 1;
367
368       if ( 
369           (r->sheets[r->current_sheet].start_col == -1)
370           ||
371           (r->sheets[r->current_sheet].start_col >= r->col - 1)
372            )
373         r->sheets[r->current_sheet].start_col = r->col - 1;
374
375       r->sheets[r->current_sheet].stop_row = r->row - 1;
376
377       if ( r->sheets[r->current_sheet].stop_col <  r->col - 1)
378         r->sheets[r->current_sheet].stop_col = r->col - 1;
379
380       if (XML_READER_TYPE_END_ELEMENT  == r->node_type)
381         r->state = STATE_CELL;
382       break;
383     default:
384       NOT_REACHED ();
385       break;
386     };
387
388   xmlFree (name);
389 }
390
391 /* 
392    A struct containing the parameters of a cell's value 
393    parsed from the xml
394 */
395 struct xml_value
396 {
397   xmlChar *type;
398   xmlChar *value;
399   xmlChar *text;
400 };
401
402 struct var_spec
403 {
404   char *name;
405   struct xml_value firstval;
406 };
407
408
409 /* Determine the width that a xmv should probably have */
410 static int
411 xmv_to_width (const struct xml_value *xmv, int fallback)
412 {
413   int width = SPREADSHEET_DEFAULT_WIDTH;
414
415   /* Non-strings always have zero width */
416   if (xmv->type != NULL && 0 != xmlStrcmp (xmv->type, _xml("string")))
417     return 0;
418
419   if ( fallback != -1)
420     return fallback;
421
422   if ( xmv->value )
423     width = ROUND_UP (xmlStrlen (xmv->value),
424                       SPREADSHEET_DEFAULT_WIDTH);
425   else if ( xmv->text)
426     width = ROUND_UP (xmlStrlen (xmv->text),
427                       SPREADSHEET_DEFAULT_WIDTH);
428
429   return width;
430 }
431
432 /*
433    Sets the VAR of case C, to the value corresponding to the xml data
434  */
435 static void
436 convert_xml_to_value (struct ccase *c, const struct variable *var,
437                       const struct xml_value *xmv)
438 {
439   union value *v = case_data_rw (c, var);
440
441   if (xmv->value == NULL && xmv->text == NULL)
442     value_set_missing (v, var_get_width (var));
443   else if ( var_is_alpha (var))
444     /* Use the text field, because it seems that there is no
445        value field for strings */
446     value_copy_str_rpad (v, var_get_width (var), xmv->text, ' ');
447   else
448     {
449       const struct fmt_spec *fmt = var_get_write_format (var);
450       enum fmt_category fc  = fmt_get_category (fmt->type);
451
452       assert ( fc != FMT_CAT_STRING);
453
454       if ( 0 == xmlStrcmp (xmv->type, _xml("float")))
455         {
456           v->f = c_strtod (CHAR_CAST (const char *, xmv->value), NULL);
457         }
458       else
459         {
460           const char *text = xmv->value ?
461             CHAR_CAST (const char *, xmv->value) : CHAR_CAST (const char *, xmv->text);
462
463
464           free (data_in (ss_cstr (text), "UTF-8",
465                          fmt->type,
466                          v,
467                          var_get_width (var),
468                          "UTF-8"));
469         }
470     }
471 }
472
473
474 /* Try to find out how many sheets there are in the "workbook" */
475 static int
476 get_sheet_count (struct zip_reader *zreader)
477 {
478   xmlTextReaderPtr mxtr;
479   struct zip_member *meta = NULL;
480   meta = zip_member_open (zreader, "meta.xml");
481
482   if ( meta == NULL)
483     return -1;
484
485   mxtr = xmlReaderForIO ((xmlInputReadCallback) zip_member_read,
486                          (xmlInputCloseCallback) zip_member_finish,
487                          meta,   NULL, NULL, 0);
488
489   while (1 == xmlTextReaderRead (mxtr))
490     {
491       xmlChar *name = xmlTextReaderName (mxtr);
492       if ( 0 == xmlStrcmp (name, _xml("meta:document-statistic")))
493         {
494           xmlChar *attr = xmlTextReaderGetAttribute (mxtr, _xml ("meta:table-count"));
495
496           if ( attr != NULL)
497             {
498               int s = _xmlchar_to_int (attr);
499               xmlFreeTextReader (mxtr);
500               xmlFree (name);
501               xmlFree (attr);      
502               return s;
503             }
504           xmlFree (attr);      
505         }
506       xmlFree (name);      
507     }
508
509   xmlFreeTextReader (mxtr);
510   return -1;
511 }
512
513 static void
514 ods_error_handler (void *ctx, const char *mesg,
515                         UNUSED xmlParserSeverities sev, xmlTextReaderLocatorPtr loc)
516 {
517   struct ods_reader *r = ctx;
518        
519   msg (MW, _("There was a problem whilst reading the %s file `%s' (near line %d): `%s'"),
520        "ODF",
521        r->spreadsheet.file_name,
522        xmlTextReaderLocatorLineNumber (loc),
523        mesg);
524 }
525
526
527 static bool
528 init_reader (struct ods_reader *r, bool report_errors)
529 {
530   struct zip_member *content = zip_member_open (r->zreader, "content.xml");
531   xmlTextReaderPtr xtr;
532
533   if ( content == NULL)
534     return false;
535
536   zip_member_ref (content);
537
538   if (r->xtr)
539     xmlFreeTextReader (r->xtr);
540
541   xtr = xmlReaderForIO ((xmlInputReadCallback) zip_member_read,
542                         (xmlInputCloseCallback) zip_member_finish,
543                         content,   NULL, NULL,
544                         report_errors ? 0 : (XML_PARSE_NOERROR | XML_PARSE_NOWARNING) );
545
546   if ( xtr == NULL)
547     return false;
548
549   r->xtr = xtr;
550   r->spreadsheet.type = SPREADSHEET_ODS;
551   r->row = 0;
552   r->col = 0;
553   r->current_sheet = 0;
554   r->state = STATE_INIT;
555
556   if (report_errors) 
557     xmlTextReaderSetErrorHandler (xtr, ods_error_handler, r);
558
559   return true;
560 }
561
562
563 struct spreadsheet *
564 ods_probe (const char *filename, bool report_errors)
565 {
566   struct ods_reader *r;
567   struct string errs = DS_EMPTY_INITIALIZER;
568   int sheet_count;
569   struct zip_reader *zr = zip_reader_create (filename, &errs);
570
571   if (zr == NULL)
572     {
573       if (report_errors)
574         {
575           msg (ME, _("Cannot open %s as a OpenDocument file: %s"),
576                filename, ds_cstr (&errs));
577         }
578       return NULL;
579     }
580
581   sheet_count = get_sheet_count (zr);
582
583   r = xzalloc (sizeof *r);
584   r->zreader = zr;
585
586   if (! init_reader (r, report_errors))
587     {
588       goto error;
589     }
590
591   r->spreadsheet.n_sheets = sheet_count;
592   r->n_allocated_sheets = 0;
593   r->sheets = NULL;
594
595   ds_destroy (&errs);
596
597   r->spreadsheet.file_name = filename;
598   return &r->spreadsheet;
599
600  error:
601   zip_reader_destroy (r->zreader);
602   ds_destroy (&errs);
603   free (r);
604   return NULL;
605 }
606
607 struct casereader *
608 ods_make_reader (struct spreadsheet *spreadsheet, 
609                  const struct spreadsheet_read_options *opts)
610 {
611   intf ret = 0;
612   xmlChar *type = NULL;
613   unsigned long int vstart = 0;
614   casenumber n_cases = CASENUMBER_MAX;
615   int i;
616   struct var_spec *var_spec = NULL;
617   int n_var_specs = 0;
618
619   struct ods_reader *r = (struct ods_reader *) spreadsheet;
620   xmlChar *val_string = NULL;
621
622   assert (r);
623   r->read_names = opts->read_names;
624   ds_init_empty (&r->ods_errs);
625
626
627   if ( !init_reader (r, true))
628     goto error;
629
630   if ( opts->cell_range )
631     {
632       if ( ! convert_cell_ref (opts->cell_range,
633                                &r->start_col, &r->start_row,
634                                &r->stop_col, &r->stop_row))
635         {
636           msg (SE, _("Invalid cell range `%s'"),
637                opts->cell_range);
638           goto error;
639         }
640     }
641   else
642     {
643       r->start_col = 0;
644       r->start_row = 0;
645       r->stop_col = -1;
646       r->stop_row = -1;
647     }
648
649   r->state = STATE_INIT;
650   r->target_sheet_name = BAD_CAST opts->sheet_name;
651   r->target_sheet_index = opts->sheet_index;
652   r->row = r->col = 0;
653
654
655 #if 0
656   printf ("%s:%d %d,%d %d,%d\n", __FILE__, __LINE__, 
657           r->start_col,
658           r->start_row,
659           r->stop_col,
660           r->stop_row);
661 #endif
662
663
664   /* Advance to the start of the cells for the target sheet */
665   while ( ! reading_target_sheet (r)  
666           || r->state != STATE_ROW || r->row <= r->start_row )
667     {
668       if (1 != (ret = xmlTextReaderRead (r->xtr)))
669            break;
670
671       process_node (r);
672     }
673
674   if (ret < 1)
675     {
676       msg (MW, _("Selected sheet or range of spreadsheet `%s' is empty."),
677            spreadsheet->file_name);
678       goto error;
679     }
680
681   if ( opts->read_names)
682     {
683       while (1 == (ret = xmlTextReaderRead (r->xtr)))
684         {
685           int idx;
686
687           process_node (r);
688
689           /* If the row is finished then stop for now */
690           if (r->state == STATE_TABLE && r->row > r->start_row)
691             break;
692
693           idx = r->col - r->start_col -1 ;
694
695           if ( idx < 0)
696             continue;
697
698           if (r->stop_col != -1 && idx > r->stop_col - r->start_col)
699             continue;
700
701           if (r->state == STATE_CELL_CONTENT 
702               &&
703               XML_READER_TYPE_TEXT  == r->node_type)
704             {
705               xmlChar *value = xmlTextReaderValue (r->xtr);
706
707               if ( idx >= n_var_specs)
708                 {
709                   var_spec = xrealloc (var_spec, sizeof (*var_spec) * (idx + 1));
710
711                   /* xrealloc (unlike realloc) doesn't initialise its memory to 0 */
712                   memset (var_spec + n_var_specs,
713                           0, 
714                           (idx - n_var_specs + 1) * sizeof (*var_spec));
715                   n_var_specs = idx + 1;
716                 }
717               var_spec[idx].firstval.text = 0;
718               var_spec[idx].firstval.value = 0;
719               var_spec[idx].firstval.type = 0;
720
721               var_spec [idx].name = strdup (CHAR_CAST (const char *, value));
722
723               xmlFree (value);
724             }
725         }
726     }
727
728   /* Read in the first row of data */
729   while (1 == xmlTextReaderRead (r->xtr))
730     {
731       int idx;
732       process_node (r);
733
734       if ( ! reading_target_sheet (r) )
735         break;
736
737       /* If the row is finished then stop for now */
738       if (r->state == STATE_TABLE &&
739           r->row > r->start_row + (opts->read_names ? 1 : 0))
740         break;
741
742       idx = r->col - r->start_col - 1;
743       if (idx < 0)
744         continue;
745
746       if (r->stop_col != -1 && idx > r->stop_col - r->start_col)
747         continue;
748
749       if ( r->state == STATE_CELL &&
750            XML_READER_TYPE_ELEMENT  == r->node_type)
751         {
752           type = xmlTextReaderGetAttribute (r->xtr, _xml ("office:value-type"));
753           val_string = xmlTextReaderGetAttribute (r->xtr, _xml ("office:value"));
754         }
755
756       if ( r->state == STATE_CELL_CONTENT &&
757            XML_READER_TYPE_TEXT  == r->node_type)
758         {
759 #if 0
760           printf ("%s:%d Idx %d n_var_specs %d\n", __FILE__, __LINE__,
761                   idx, n_var_specs);
762
763           printf ("%s:%d Idx %d r_col %d\n", __FILE__, __LINE__,
764                   idx, r->col);
765 #endif
766
767           if (idx >= n_var_specs)
768             {
769               var_spec = xrealloc (var_spec, sizeof (*var_spec) * (idx + 1));
770               memset (var_spec + n_var_specs,
771                       0, 
772                       (idx - n_var_specs + 1) * sizeof (*var_spec));
773
774               var_spec [idx].name = NULL;
775               n_var_specs = idx + 1;
776             }
777
778           var_spec [idx].firstval.type = type;
779           var_spec [idx].firstval.text = xmlTextReaderValue (r->xtr);
780           var_spec [idx].firstval.value = val_string;
781
782           val_string = NULL;
783           type = NULL;
784         }
785     }
786
787
788   /* Create the dictionary and populate it */
789   r->spreadsheet.dict = r->dict = dict_create (
790     CHAR_CAST (const char *, xmlTextReaderConstEncoding (r->xtr)));
791
792   for (i = 0; i < n_var_specs ; ++i )
793     {
794       struct fmt_spec fmt;
795       struct variable *var = NULL;
796       char *name = dict_make_unique_var_name (r->dict, var_spec[i].name, &vstart);
797       int width  = xmv_to_width (&var_spec[i].firstval, opts->asw);
798       dict_create_var (r->dict, name, width);
799       free (name);
800
801       var = dict_get_var (r->dict, i);
802
803       if ( 0 == xmlStrcmp (var_spec[i].firstval.type, _xml("date")))
804         {
805           fmt.type = FMT_DATE;
806           fmt.d = 0;
807           fmt.w = 20;
808         }
809       else
810         fmt = fmt_default_for_width (width);
811
812       var_set_both_formats (var, &fmt);
813     }
814
815   /* Create the first case, and cache it */
816   r->used_first_case = false;
817
818   if ( n_var_specs ==  0 )
819     {
820       msg (MW, _("Selected sheet or range of spreadsheet `%s' is empty."),
821            spreadsheet->file_name);
822       goto error;
823     }
824
825   r->proto = caseproto_ref (dict_get_proto (r->dict));
826   r->first_case = case_create (r->proto);
827   case_set_missing (r->first_case);
828
829   for (i = 0 ; i < n_var_specs; ++i)
830     {
831       const struct variable *var = dict_get_var (r->dict, i);
832
833       convert_xml_to_value (r->first_case, var,  &var_spec[i].firstval);
834     }
835
836   /* Read in the first row of data */
837   while (1 == xmlTextReaderRead (r->xtr))
838     {
839       process_node (r);
840
841       if (r->state == STATE_ROW)
842         break;
843     }
844
845   // zip_reader_destroy (zreader);
846
847   for ( i = 0 ; i < n_var_specs ; ++i )
848     {
849       free (var_spec[i].firstval.type);
850       free (var_spec[i].firstval.value);
851       free (var_spec[i].firstval.text);
852       free (var_spec[i].name);
853     }
854
855   free (var_spec);
856
857
858   return casereader_create_sequential
859     (NULL,
860      r->proto,
861      n_cases,
862      &ods_file_casereader_class, r);
863
864  error:
865   
866   //zip_reader_destroy (zreader);
867
868   for ( i = 0 ; i < n_var_specs ; ++i )
869     {
870       free (var_spec[i].firstval.type);
871       free (var_spec[i].firstval.value);
872       free (var_spec[i].firstval.text);
873       free (var_spec[i].name);
874     }
875
876   free (var_spec);
877
878   dict_destroy (r->spreadsheet.dict);
879   r->spreadsheet.dict = NULL;
880   ods_file_casereader_destroy (NULL, r);
881
882
883   return NULL;
884 }
885
886
887 /* Reads and returns one case from READER's file.  Returns a null
888    pointer on failure. */
889 static struct ccase *
890 ods_file_casereader_read (struct casereader *reader UNUSED, void *r_)
891 {
892   struct ccase *c = NULL;
893   xmlChar *val_string = NULL;
894   xmlChar *type = NULL;
895   struct ods_reader *r = r_;
896
897   if (!r->used_first_case)
898     {
899       r->used_first_case = true;
900       return r->first_case;
901     }
902
903
904   /* Advance to the start of a row. (If there is one) */
905   while (r->state != STATE_ROW 
906          && 1 == xmlTextReaderRead (r->xtr)
907          )
908     {
909       process_node (r);
910     }
911
912
913   if ( ! reading_target_sheet (r)  
914        ||  r->state < STATE_TABLE
915        ||  (r->stop_row != -1 && r->row > r->stop_row + 1)
916        )
917     {
918       return NULL;
919     }
920
921   c = case_create (r->proto);
922   case_set_missing (c);
923   
924   while (1 == xmlTextReaderRead (r->xtr))
925     {
926       process_node (r);
927
928       if ( r->stop_row != -1 && r->row > r->stop_row + 1)
929         break;
930
931       if (r->state == STATE_CELL &&
932            r->node_type == XML_READER_TYPE_ELEMENT)
933         {
934           type = xmlTextReaderGetAttribute (r->xtr, _xml ("office:value-type"));
935           val_string = xmlTextReaderGetAttribute (r->xtr, _xml ("office:value"));
936         }
937
938       if (r->state == STATE_CELL_CONTENT && 
939            r->node_type == XML_READER_TYPE_TEXT)
940         {
941           int col;
942           struct xml_value *xmv = xzalloc (sizeof *xmv);
943           xmv->text = xmlTextReaderValue (r->xtr);
944           xmv->value = val_string;       
945           xmv->type = type;
946           val_string = NULL;
947
948           for (col = 0; col < r->col_span; ++col)
949             {
950               const struct variable *var;
951               const int idx = r->col - col - r->start_col - 1;
952               if (idx < 0)
953                 continue;
954               if (r->stop_col != -1 && idx > r->stop_col - r->start_col )
955                 break;
956
957               var = dict_get_var (r->dict, idx);
958               convert_xml_to_value (c, var, xmv);
959             }
960
961           xmlFree (xmv->text);
962           xmlFree (xmv->value);
963           xmlFree (xmv->type);
964           free (xmv);
965         }
966       if ( r->state <= STATE_TABLE)
967         break;
968     }
969
970   return c;
971 }
972 #endif