]> git.tdb.fi Git - ext/subsurface.git/blob - parse-xml.c
Save and parse notes and locations
[ext/subsurface.git] / parse-xml.c
1 #include <stdio.h>
2 #include <ctype.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <errno.h>
6 #include <time.h>
7 #include <libxml/parser.h>
8 #include <libxml/tree.h>
9
10 #include "dive.h"
11
12 int verbose;
13
14 struct dive_table dive_table;
15
16 /*
17  * Add a dive into the dive_table array
18  */
19 static void record_dive(struct dive *dive)
20 {
21         int nr = dive_table.nr, allocated = dive_table.allocated;
22         struct dive **dives = dive_table.dives;
23
24         if (nr >= allocated) {
25                 allocated = (nr + 32) * 3 / 2;
26                 dives = realloc(dives, allocated * sizeof(struct dive *));
27                 if (!dives)
28                         exit(1);
29                 dive_table.dives = dives;
30                 dive_table.allocated = allocated;
31         }
32         dives[nr] = dive;
33         dive_table.nr = nr+1;
34 }
35
36 static void start_match(const char *type, const char *name, char *buffer)
37 {
38         if (verbose > 2)
39                 printf("Matching %s '%s' (%s)\n",
40                         type, name, buffer);
41 }
42
43 static void nonmatch(const char *type, const char *name, char *buffer)
44 {
45         if (verbose > 1)
46                 printf("Unable to match %s '%s' (%s)\n",
47                         type, name, buffer);
48         free(buffer);
49 }
50
51 typedef void (*matchfn_t)(char *buffer, void *);
52
53 static int match(const char *pattern, int plen,
54                  const char *name, int nlen,
55                  matchfn_t fn, char *buf, void *data)
56 {
57         if (plen > nlen)
58                 return 0;
59         if (memcmp(pattern, name + nlen - plen, plen))
60                 return 0;
61         fn(buf, data);
62         return 1;
63 }
64
65 /*
66  * Dive info as it is being built up..
67  */
68 static int alloc_samples;
69 static struct dive *dive;
70 static struct sample *sample;
71 static struct tm tm;
72 static int suunto;
73 static int event_index, gasmix_index;
74
75 static time_t utc_mktime(struct tm *tm)
76 {
77         static const int mdays[] = {
78             0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
79         };
80         int year = tm->tm_year;
81         int month = tm->tm_mon;
82         int day = tm->tm_mday;
83
84         /* First normalize relative to 1900 */
85         if (year < 70)
86                 year += 100;
87         else if (year > 1900)
88                 year -= 1900;
89
90         /* Normalized to Jan 1, 1970: unix time */
91         year -= 70;
92
93         if (year < 0 || year > 129) /* algo only works for 1970-2099 */
94                 return -1;
95         if (month < 0 || month > 11) /* array bounds */
96                 return -1;
97         if (month < 2 || (year + 2) % 4)
98                 day--;
99         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
100                 return -1;
101         return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
102                 tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
103 }
104
105 static void divedate(char *buffer, void *_when)
106 {
107         int d,m,y;
108         time_t *when = _when;
109         int success = 0;
110
111         success = tm.tm_sec | tm.tm_min | tm.tm_hour;
112         if (sscanf(buffer, "%d.%d.%d", &d, &m, &y) == 3) {
113                 tm.tm_year = y;
114                 tm.tm_mon = m-1;
115                 tm.tm_mday = d;
116         } else if (sscanf(buffer, "%d-%d-%d", &y, &m, &d) == 3) {
117                 tm.tm_year = y;
118                 tm.tm_mon = m-1;
119                 tm.tm_mday = d;
120         } else {
121                 fprintf(stderr, "Unable to parse date '%s'\n", buffer);
122                 success = 0;
123         }
124
125         if (success)
126                 *when = utc_mktime(&tm);
127
128         free(buffer);
129 }
130
131 static void divetime(char *buffer, void *_when)
132 {
133         int h,m,s = 0;
134         time_t *when = _when;
135
136         if (sscanf(buffer, "%d:%d:%d", &h, &m, &s) >= 2) {
137                 tm.tm_hour = h;
138                 tm.tm_min = m;
139                 tm.tm_sec = s;
140                 if (tm.tm_year)
141                         *when = utc_mktime(&tm);
142         }
143         free(buffer);
144 }
145
146 /* Libdivecomputer: "2011-03-20 10:22:38" */
147 static void divedatetime(char *buffer, void *_when)
148 {
149         int y,m,d;
150         int hr,min,sec;
151         time_t *when = _when;
152
153         if (sscanf(buffer, "%d-%d-%d %d:%d:%d",
154                 &y, &m, &d, &hr, &min, &sec) == 6) {
155                 tm.tm_year = y;
156                 tm.tm_mon = m-1;
157                 tm.tm_mday = d;
158                 tm.tm_hour = hr;
159                 tm.tm_min = min;
160                 tm.tm_sec = sec;
161                 *when = utc_mktime(&tm);
162         }
163         free(buffer);
164 }
165
166 union int_or_float {
167         long i;
168         double fp;
169 };
170
171 enum number_type {
172         NEITHER,
173         INTEGER,
174         FLOAT
175 };
176
177 static enum number_type integer_or_float(char *buffer, union int_or_float *res)
178 {
179         char *end;
180         long val;
181         double fp;
182
183         /* Integer or floating point? */
184         val = strtol(buffer, &end, 10);
185         if (val < 0 || end == buffer)
186                 return NEITHER;
187
188         /* Looks like it might be floating point? */
189         if (*end == '.') {
190                 errno = 0;
191                 fp = strtod(buffer, &end);
192                 if (!errno) {
193                         res->fp = fp;
194                         return FLOAT;
195                 }
196         }
197
198         res->i = val;
199         return INTEGER;
200 }
201
202 static void pressure(char *buffer, void *_press)
203 {
204         pressure_t *pressure = _press;
205         union int_or_float val;
206
207         switch (integer_or_float(buffer, &val)) {
208         case FLOAT:
209                 /* Maybe it's in Bar? */
210                 if (val.fp < 500.0) {
211                         pressure->mbar = val.fp * 1000 + 0.5;
212                         break;
213                 }
214                 printf("Unknown fractional pressure reading %s\n", buffer);
215                 break;
216
217         case INTEGER:
218                 /*
219                  * Random integer? Maybe in PSI? Or millibar already?
220                  *
221                  * We assume that 5 bar is a ridiculous tank pressure,
222                  * so if it's smaller than 5000, it's in PSI..
223                  */
224                 if (val.i < 5000) {
225                         pressure->mbar = val.i * 68.95;
226                         break;
227                 }
228                 pressure->mbar = val.i;
229                 break;
230         default:
231                 printf("Strange pressure reading %s\n", buffer);
232         }
233         free(buffer);
234 }
235
236 static void depth(char *buffer, void *_depth)
237 {
238         depth_t *depth = _depth;
239         union int_or_float val;
240
241         switch (integer_or_float(buffer, &val)) {
242         /* All values are probably in meters */
243         case INTEGER:
244                 val.fp = val.i;
245                 /* fallthrough */
246         case FLOAT:
247                 depth->mm = val.fp * 1000 + 0.5;
248                 break;
249         default:
250                 printf("Strange depth reading %s\n", buffer);
251         }
252         free(buffer);
253 }
254
255 static void temperature(char *buffer, void *_temperature)
256 {
257         temperature_t *temperature = _temperature;
258         union int_or_float val;
259
260         switch (integer_or_float(buffer, &val)) {
261         /* C or F? Who knows? Let's default to Celsius */
262         case INTEGER:
263                 val.fp = val.i;
264                 /* Fallthrough */
265         case FLOAT:
266                 /* Ignore zero. It means "none" */
267                 if (!val.fp)
268                         break;
269                 /* Celsius */
270                 if (val.fp < 50.0) {
271                         temperature->mkelvin = (val.fp + 273.15) * 1000 + 0.5;
272                         break;
273                 }
274                 /* Fahrenheit */
275                 if (val.fp < 212.0) {
276                         temperature->mkelvin = (val.fp + 459.67) * 5000/9;
277                         break;
278                 }
279                 /* Kelvin or already millikelvin */
280                 if (val.fp < 1000.0)
281                         val.fp *= 1000;
282                 temperature->mkelvin = val.fp;
283                 break;
284         default:
285                 printf("Strange temperature reading %s\n", buffer);
286         }
287         free(buffer);
288 }
289
290 static void sampletime(char *buffer, void *_time)
291 {
292         int i;
293         int min, sec;
294         duration_t *time = _time;
295
296         i = sscanf(buffer, "%d:%d", &min, &sec);
297         switch (i) {
298         case 1:
299                 sec = min;
300                 min = 0;
301         /* fallthrough */
302         case 2:
303                 time->seconds = sec + min*60;
304                 break;
305         default:
306                 printf("Strange sample time reading %s\n", buffer);
307         }
308         free(buffer);
309 }
310
311 static void duration(char *buffer, void *_time)
312 {
313         sampletime(buffer, _time);
314 }
315
316 static void percent(char *buffer, void *_fraction)
317 {
318         fraction_t *fraction = _fraction;
319         union int_or_float val;
320
321         switch (integer_or_float(buffer, &val)) {
322         /* C or F? Who knows? Let's default to Celsius */
323         case INTEGER:
324                 val.fp = val.i;
325                 /* Fallthrough */
326         case FLOAT:
327                 if (val.fp <= 100.0)
328                         fraction->permille = val.fp * 10 + 0.5;
329                 break;
330
331         default:
332                 printf("Strange percentage reading %s\n", buffer);
333                 break;
334         }
335         free(buffer);
336 }
337
338 static void gasmix(char *buffer, void *_fraction)
339 {
340         /* libdivecomputer does negative percentages. */
341         if (*buffer == '-')
342                 return;
343         if (gasmix_index < MAX_MIXES)
344                 percent(buffer, _fraction);
345 }
346
347 static void gasmix_nitrogen(char *buffer, void *_gasmix)
348 {
349         /* Ignore n2 percentages. There's no value in them. */
350 }
351
352 static void utf8_string(char *buffer, void *_res)
353 {
354         *(char **)_res = buffer;
355 }
356
357 #define MATCH(pattern, fn, dest) \
358         match(pattern, strlen(pattern), name, len, fn, buf, dest)
359
360 /* We're in samples - try to convert the random xml value to something useful */
361 static void try_to_fill_sample(struct sample *sample, const char *name, char *buf)
362 {
363         int len = strlen(name);
364
365         start_match("sample", name, buf);
366         if (MATCH(".sample.pressure", pressure, &sample->tankpressure))
367                 return;
368         if (MATCH(".sample.cylpress", pressure, &sample->tankpressure))
369                 return;
370         if (MATCH(".sample.depth", depth, &sample->depth))
371                 return;
372         if (MATCH(".sample.temp", temperature, &sample->temperature))
373                 return;
374         if (MATCH(".sample.temperature", temperature, &sample->temperature))
375                 return;
376         if (MATCH(".sample.sampletime", sampletime, &sample->time))
377                 return;
378         if (MATCH(".sample.time", sampletime, &sample->time))
379                 return;
380
381         nonmatch("sample", name, buf);
382 }
383
384 /*
385  * Crazy suunto xml. Look at how those o2/he things match up.
386  */
387 static int suunto_dive_match(struct dive *dive, const char *name, int len, char *buf)
388 {
389         return  MATCH(".o2pct", percent, &dive->gasmix[0].o2) ||
390                 MATCH(".hepct_0", percent, &dive->gasmix[0].he) ||
391                 MATCH(".o2pct_2", percent, &dive->gasmix[1].o2) ||
392                 MATCH(".hepct_1", percent, &dive->gasmix[1].he) ||
393                 MATCH(".o2pct_3", percent, &dive->gasmix[2].o2) ||
394                 MATCH(".hepct_2", percent, &dive->gasmix[2].he) ||
395                 MATCH(".o2pct_4", percent, &dive->gasmix[3].o2) ||
396                 MATCH(".hepct_3", percent, &dive->gasmix[3].he);
397 }
398
399 /* We're in the top-level dive xml. Try to convert whatever value to a dive value */
400 static void try_to_fill_dive(struct dive *dive, const char *name, char *buf)
401 {
402         int len = strlen(name);
403
404         start_match("dive", name, buf);
405         if (MATCH(".date", divedate, &dive->when))
406                 return;
407         if (MATCH(".time", divetime, &dive->when))
408                 return;
409         if (MATCH(".datetime", divedatetime, &dive->when))
410                 return;
411         if (MATCH(".maxdepth", depth, &dive->maxdepth))
412                 return;
413         if (MATCH(".meandepth", depth, &dive->meandepth))
414                 return;
415         if (MATCH(".duration", duration, &dive->duration))
416                 return;
417         if (MATCH(".divetime", duration, &dive->duration))
418                 return;
419         if (MATCH(".divetimesec", duration, &dive->duration))
420                 return;
421         if (MATCH(".surfacetime", duration, &dive->surfacetime))
422                 return;
423         if (MATCH(".airtemp", temperature, &dive->airtemp))
424                 return;
425         if (MATCH(".watertemp", temperature, &dive->watertemp))
426                 return;
427         if (MATCH(".cylinderstartpressure", pressure, &dive->beginning_pressure))
428                 return;
429         if (MATCH(".cylinderendpressure", pressure, &dive->end_pressure))
430                 return;
431         if (MATCH(".location", utf8_string, &dive->location))
432                 return;
433         if (MATCH(".notes", utf8_string, &dive->notes))
434                 return;
435
436         if (MATCH(".o2", gasmix, &dive->gasmix[gasmix_index].o2))
437                 return;
438         if (MATCH(".n2", gasmix_nitrogen, &dive->gasmix[gasmix_index]))
439                 return;
440         if (MATCH(".he", gasmix, &dive->gasmix[gasmix_index].he))
441                 return;
442
443         /* Suunto XML files are some crazy sh*t. */
444         if (suunto && suunto_dive_match(dive, name, len, buf))
445                 return;
446
447         nonmatch("dive", name, buf);
448 }
449
450 static unsigned int dive_size(int samples)
451 {
452         return sizeof(struct dive) + samples*sizeof(struct sample);
453 }
454
455 /*
456  * File boundaries are dive boundaries. But sometimes there are
457  * multiple dives per file, so there can be other events too that
458  * trigger a "new dive" marker and you may get some nesting due
459  * to that. Just ignore nesting levels.
460  */
461 static void dive_start(void)
462 {
463         unsigned int size;
464
465         if (dive)
466                 return;
467
468         alloc_samples = 5;
469         size = dive_size(alloc_samples);
470         dive = malloc(size);
471         if (!dive)
472                 exit(1);
473         memset(dive, 0, size);
474         memset(&tm, 0, sizeof(tm));
475 }
476
477 static char *generate_name(struct dive *dive)
478 {
479         int len;
480         struct tm *tm;
481         char buffer[256], *p;
482
483         tm = gmtime(&dive->when);
484
485         len = snprintf(buffer, sizeof(buffer),
486                 "%04d-%02d-%02d "
487                 "%02d:%02d:%02d "
488                 "(%d ft, %d min)",
489                 tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
490                 tm->tm_hour, tm->tm_min, tm->tm_sec,
491                 to_feet(dive->maxdepth), dive->duration.seconds / 60);
492         p = malloc(len+1);
493         if (!p)
494                 exit(1);
495         memcpy(p, buffer, len+1);
496         return p;
497 }
498
499 static void sanitize_gasmix(struct dive *dive)
500 {
501         int i;
502
503         for (i = 0; i < MAX_MIXES; i++) {
504                 gasmix_t *mix = dive->gasmix+i;
505                 unsigned int o2, he;
506
507                 o2 = mix->o2.permille;
508                 he = mix->he.permille;
509
510                 /* Regular air: leave empty */
511                 if (!he) {
512                         if (!o2)
513                                 continue;
514                         /* 20.9% or 21% O2 is just air */
515                         if (o2 >= 209 && o2 <= 210) {
516                                 mix->o2.permille = 0;
517                                 continue;
518                         }
519                 }
520
521                 /* Sane mix? */
522                 if (o2 <= 1000 && he <= 1000 && o2+he <= 1000)
523                         continue;
524                 fprintf(stderr, "Odd gasmix: %d O2 %d He\n", o2, he);
525                 memset(mix, 0, sizeof(*mix));
526         }
527 }
528
529 static void dive_end(void)
530 {
531         if (!dive)
532                 return;
533         if (!dive->name)
534                 dive->name = generate_name(dive);
535         sanitize_gasmix(dive);
536         record_dive(dive);
537         dive = NULL;
538         gasmix_index = 0;
539 }
540
541 static void suunto_start(void)
542 {
543         suunto++;
544 }
545
546 static void suunto_end(void)
547 {
548         suunto--;
549 }
550
551 static void event_start(void)
552 {
553 }
554
555 static void event_end(void)
556 {
557         event_index++;
558 }
559
560 static void gasmix_start(void)
561 {
562 }
563
564 static void gasmix_end(void)
565 {
566         gasmix_index++;
567 }
568
569 static void sample_start(void)
570 {
571         int nr;
572
573         if (!dive)
574                 return;
575         nr = dive->samples;
576         if (nr >= alloc_samples) {
577                 unsigned int size;
578
579                 alloc_samples = (alloc_samples * 3)/2 + 10;
580                 size = dive_size(alloc_samples);
581                 dive = realloc(dive, size);
582                 if (!dive)
583                         return;
584         }
585         sample = dive->sample + nr;
586         memset(sample, 0, sizeof(*sample));
587         event_index = 0;
588 }
589
590 static void sample_end(void)
591 {
592         if (!dive)
593                 return;
594
595         if (sample->time.seconds > dive->duration.seconds) {
596                 if (sample->depth.mm)
597                         dive->duration = sample->time;
598         }
599
600         if (sample->depth.mm > dive->maxdepth.mm)
601                 dive->maxdepth.mm = sample->depth.mm;
602
603         sample = NULL;
604         dive->samples++;
605 }
606
607 static void entry(const char *name, int size, const char *raw)
608 {
609         char *buf = malloc(size+1);
610
611         if (!buf)
612                 return;
613         memcpy(buf, raw, size);
614         buf[size] = 0;
615         if (sample) {
616                 try_to_fill_sample(sample, name, buf);
617                 return;
618         }
619         if (dive) {
620                 try_to_fill_dive(dive, name, buf);
621                 return;
622         }
623 }
624
625 static const char *nodename(xmlNode *node, char *buf, int len)
626 {
627         if (!node || !node->name)
628                 return "root";
629
630         buf += len;
631         *--buf = 0;
632         len--;
633
634         for(;;) {
635                 const char *name = node->name;
636                 int i = strlen(name);
637                 while (--i >= 0) {
638                         unsigned char c = name[i];
639                         *--buf = tolower(c);
640                         if (!--len)
641                                 return buf;
642                 }
643                 node = node->parent;
644                 if (!node || !node->name)
645                         return buf;
646                 *--buf = '.';
647                 if (!--len)
648                         return buf;
649         }
650 }
651
652 #define MAXNAME 64
653
654 static void visit_one_node(xmlNode *node)
655 {
656         int len;
657         const unsigned char *content;
658         char buffer[MAXNAME];
659         const char *name;
660
661         content = node->content;
662         if (!content)
663                 return;
664
665         /* Trim whitespace at beginning */
666         while (isspace(*content))
667                 content++;
668
669         /* Trim whitespace at end */
670         len = strlen(content);
671         while (len && isspace(content[len-1]))
672                 len--;
673
674         if (!len)
675                 return;
676
677         /* Don't print out the node name if it is "text" */
678         if (!strcmp(node->name, "text"))
679                 node = node->parent;
680
681         name = nodename(node, buffer, sizeof(buffer));
682
683         entry(name, len, content);
684 }
685
686 static void traverse(xmlNode *root);
687
688 static void traverse_properties(xmlNode *node)
689 {
690         xmlAttr *p;
691
692         for (p = node->properties; p; p = p->next)
693                 traverse(p->children);
694 }
695
696 static void visit(xmlNode *n)
697 {
698         visit_one_node(n);
699         traverse_properties(n);
700         traverse(n->children);
701 }
702
703 /*
704  * I'm sure this could be done as some fancy DTD rules.
705  * It's just not worth the headache.
706  */
707 static struct nesting {
708         const char *name;
709         void (*start)(void), (*end)(void);
710 } nesting[] = {
711         { "dive", dive_start, dive_end },
712         { "SUUNTO", suunto_start, suunto_end },
713         { "sample", sample_start, sample_end },
714         { "SAMPLE", sample_start, sample_end },
715         { "event", event_start, event_end },
716         { "gasmix", gasmix_start, gasmix_end },
717         { NULL, }
718 };
719
720 static void traverse(xmlNode *root)
721 {
722         xmlNode *n;
723
724         for (n = root; n; n = n->next) {
725                 struct nesting *rule = nesting;
726
727                 do {
728                         if (!strcmp(rule->name, n->name))
729                                 break;
730                         rule++;
731                 } while (rule->name);
732
733                 if (rule->start)
734                         rule->start();
735                 visit(n);
736                 if (rule->end)
737                         rule->end();
738         }
739 }
740
741 void parse_xml_file(const char *filename)
742 {
743         xmlDoc *doc;
744
745         doc = xmlReadFile(filename, NULL, 0);
746         if (!doc) {
747                 fprintf(stderr, "Failed to parse '%s'.\n", filename);
748                 return;
749         }
750
751         dive_start();
752         traverse(xmlDocGetRootElement(doc));
753         dive_end();
754         xmlFreeDoc(doc);
755         xmlCleanupParser();
756 }
757
758 void parse_xml_init(void)
759 {
760         LIBXML_TEST_VERSION
761 }