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