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