Enumerate log entries using delegates and lambdas
[gregoa/zavai.git] / src / log.vala
index a3ef9a05b6fd69b9937bb7364f0aea6e7885a939..2f10dbc8b5766b69ffe60e728e0cc2870e86cced 100644 (file)
@@ -47,7 +47,7 @@ public class Waypoint : Object
     public void writeInside(FileStream outfd)
     {
         var t = Time.gm(ts);
-        outfd.printf("   <time>%s</time>", t.format("%Y-%m-%dT%H:%M:%SZ"));
+        outfd.printf("   <time>%s</time>\n", t.format("%Y-%m-%dT%H:%M:%S%z"));
     }
 }
 
@@ -58,14 +58,15 @@ public class LogEntry : Waypoint
 
     public LogEntry()
     {
-        Object();
+        base();
     }
 
     public void write(FileStream outfd)
     {
-        outfd.printf("   <wpt lat=\"%f\" lon=\"%f\">", lat, lon);
+        outfd.printf("   <wpt lat=\"%f\" lon=\"%f\">\n", lat, lon);
         writeInside(outfd);
-        outfd.puts("   </wpt>");
+        outfd.printf("   <name>%s</name>\n", Markup.escape_text(msg));
+        outfd.puts("   </wpt>\n");
     }
 }
 
@@ -73,29 +74,31 @@ public class TrackEntry : Waypoint
 {
     public TrackEntry()
     {
-        Object();
+        base();
     }
 
     public void write(FileStream outfd)
     {
-        outfd.printf("   <trkpt lat=\"%f\" lon=\"%f\">", lat, lon);
+        outfd.printf("   <trkpt lat=\"%f\" lon=\"%f\">\n", lat, lon);
         writeInside(outfd);
-        outfd.puts("   </trkpt>");
+        outfd.puts("   </trkpt>\n");
     }
 }
 
 
 public class Log : Object
 {
-    public uint id;
     public string tag;
+    public string title;
+    public bool acked;
     public List<LogEntry> entries;
     public List<TrackEntry> track;
 
-    public Log(uint id, string tag)
+    public Log(string tag, string title, bool acked=false)
     {
-        this.id = id;
         this.tag = tag;
+        this.title = title;
+        this.acked = acked;
         entries = null;
         track = null;
     }
@@ -107,150 +110,302 @@ public class Log : Object
         entries.append(entry);
     }
 
+    public void add_trackpoint()
+    {
+        track.append(new TrackEntry());
+    }
+
     public void save()
     {
         if (entries == null) return;
 
         // Directory where we save the log
-        string dir = config.homedir + "/log-" + tag;
+        string dir;
+        if (acked)
+            dir = config.homedir + "/archive";
+        else
+            dir = config.homedir + "/log";
+        DirUtils.create(dir, 0777);
 
         // First try with a plain name
         var t = Time.local(entries.data.ts);
-        string basename = t.format("%Y%m%d-%H%M%S");
+        string basename = dir + "/" + t.format("%Y%m%d-%H%M%S") + "-" + tag;
 
-        string name = basename + ".gpx";
+        string pathname = basename + ".gpx";
 
         // Find a pathname that does not exist already
-        string pathname = dir + "/" + name;
-        for (int i = 1; FileUtils.test(dir + "/" + name, FileTest.EXISTS); ++i)
-            name = "%s-%d.gpx".printf(basename, i);
+        for (int i = 1; FileUtils.test(pathname, FileTest.EXISTS); ++i)
+            pathname = "%s-%d.gpx".printf(basename, i);
 
         // Write out
         var outfd = FileStream.open(pathname, "w");
+        if (outfd == null)
+        {
+            zavai.log.error("opening " + pathname + ": " + strerror(errno));
+            return;
+        }
+
         write(outfd);
         outfd.flush();
     }
 
+    public void dump()
+    {
+        write(stderr);
+    }
+
     protected void writeTrack(FileStream outfd)
     {
-        outfd.puts("   <trk>");
-        outfd.puts("     <trkseg>");
+        outfd.puts("   <trk>\n");
+        outfd.puts("     <trkseg>\n");
         for (weak List<TrackEntry> i = track; i != null; i = i.next)
             i.data.write(outfd);
-        outfd.puts("     </trkseg>");
-        outfd.puts("   </trk>");
+        outfd.puts("     </trkseg>\n");
+        outfd.puts("   </trk>\n");
     }
 
     protected void writeEntries(FileStream outfd)
     {
-        outfd.puts("   <wpt>");
         for (weak List<LogEntry> i = entries; i != null; i = i.next)
             i.data.write(outfd);
-        outfd.puts("   </wpt>");
     }
 
     protected void write(FileStream outfd)
     {
-        outfd.puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
-        outfd.puts(" <gpx");
-        outfd.puts("     version=\"1.0\"");
+        outfd.puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+        outfd.puts("<gpx version=\"1.0\"\n");
         outfd.printf("     creator=\"zavai %s\"\n", zavai.config.version);
-        outfd.puts("     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
-        outfd.puts("     xmlns=\"http://www.topografix.com/GPX/1/0\"");
-        outfd.puts("     xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">");
+        outfd.puts("     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
+        outfd.puts("     xmlns=\"http://www.topografix.com/GPX/1/0\"\n");
+        outfd.puts("     xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">\n");
+        outfd.puts("  <metadata>\n");
+        outfd.printf("    <name>%s</name>\n", Markup.escape_text(title));
+        outfd.puts("  </metadata>\n");
         if (track != null) writeTrack(outfd);
         if (entries != null) writeEntries(outfd);
-        outfd.puts(" </gpx>");
+        outfd.puts(" </gpx>\n");
     }
 }
 
-public class Logger : Resource, Object
+enum LogParserState {
+    NONE,
+    METADATA,
+    TRACK,
+    WPT,
+}
+
+class LogParser: Object
 {
-    protected List<Log> logs;
-    protected uint seq;
+    const MarkupParser parser = { // It's a structure, not an object
+        start,// when an element opens
+        end,  // when an element closes
+        text, // when text is found
+        null, // when comments are found
+        null  // when errors occur
+    };
+
+    MarkupParseContext context = null;
+    public Log result = null;
+    LogParserState state = LogParserState.NONE;
+    string cur_text = "";
+    LogEntry cur_logentry = null;
+    TrackEntry cur_trackentry = null;
+
+    construct
+    {
+        context = new MarkupParseContext(
+            parser, // the structure with the callbacks
+            0,      // MarkupParseFlags
+            this,   // extra argument for the callbacks, methods in this case
+            destroy // when the parsing ends
+        );
+    }
 
-    public Logger()
+    void destroy()
     {
-        logs = null;
-        seq = 0;
+        cur_text = "";
+        cur_logentry = null;
+        cur_trackentry = null;
+    }
 
-        zavai.registry.register(this);
+    public bool parse(string content, ssize_t len = -1) throws MarkupError
+    {
+        string oldtz = Environment.get_variable("TZ");
+        Environment.set_variable("TZ", "UTC", true);
+        bool res = context.parse(content, len);
+        if (oldtz == null)
+            Environment.unset_variable("TZ");
+        else
+            Environment.set_variable("TZ", oldtz, true);
+        return res;
     }
 
-    protected uint gen_seq()
+    void parse_attrs(Waypoint w, string[] attr_names, string[] attr_values)
     {
-        // Increase avoiding 0 on rollover
-        while (true)
+        w.lat = 1000;
+        w.lon = 1000;
+        for (int i = 0; attr_names[i] != null; ++i)
         {
-            if (++seq == 0) ++seq;
-            bool found = false;
-            for (weak List<Log> i = logs; i != null; i = i.next)
+            if (attr_names[i] == "lat")
+                w.lat = attr_values[i].to_double();
+            else if (attr_names[i] == "lon")
+                w.lon = attr_values[i].to_double();
+        }
+    }
+
+    void start (MarkupParseContext context, string name,
+                string[] attr_names, string[] attr_values) throws MarkupError
+    {
+        if (name == "gpx")
+        {
+            state = LogParserState.NONE;
+            result = new Log("TODO:TAG", "TODO:TITLE");
+        } else if (name == "metadata") {
+            state = LogParserState.METADATA;
+        } else if (name == "wpt") {
+            cur_logentry = new LogEntry();
+            parse_attrs(cur_logentry, attr_names, attr_values);
+            result.entries.append(cur_logentry);
+            state = LogParserState.WPT;
+        } else if (name == "trkpt") {
+            cur_trackentry = new TrackEntry();
+            parse_attrs(cur_trackentry, attr_names, attr_values);
+            result.track.append(cur_trackentry);
+            state = LogParserState.TRACK;
+        }
+        cur_text = "";
+    }
+
+    void end (MarkupParseContext context, string name) throws MarkupError
+    {
+        if (name == "name")
+        {
+            switch (state)
             {
-                if (i.data.id == seq)
-                {
-                    found = true;
+                case LogParserState.METADATA:
+                    result.title = cur_text;
+                    break;
+                case LogParserState.WPT:
+                    cur_logentry.msg = cur_text;
                     break;
-                }
             }
-            if (!found) break;
         }
-        return seq;
+        else if (name == "time")
+        {
+            Time t = Time();
+            t.strptime(cur_text, "%Y-%m-%dT%H:%M:%S%z");
+            if (state == LogParserState.WPT)
+                cur_logentry.ts = t.mktime();
+            else if (state == LogParserState.TRACK)
+                cur_trackentry.ts = t.mktime();
+        }
+    }
+
+    void text (MarkupParseContext context,
+               string text, size_t text_len) throws MarkupError
+    {
+        cur_text += text;
+    }
+}
+
+public class Logger : Resource, Object
+{
+    protected List<Log> logs;
+
+    public Logger()
+    {
+        logs = null;
+        zavai.registry.register(this);
+    }
+
+    protected void start_trace()
+    {
+        gps.gps.pos_changed += on_pos_changed;
+    }
+
+    protected void end_trace()
+    {
+        gps.gps.pos_changed -= on_pos_changed;
     }
 
-    protected weak Log? find(uint id)
+    protected void on_pos_changed()
     {
         for (weak List<Log> i = logs; i != null; i = i.next)
-            if (i.data.id == id)
-                return i.data;
-        return null;
+            i.data.add_trackpoint();
     }
 
-    protected Log? pop(uint id)
+    protected void pop(Log log)
     {
         for (weak List<Log> i = logs; i != null; i = i.next)
-            if (i.data.id == id)
-            {
-                Log res = i.data;
+            if (i.data == log)
                 logs.delete_link(i);
-                return res;
-            }
-        return null;
     }
 
-    public uint start(string tag)
+    public Log start(string tag, string title)
     {
-        uint id = gen_seq();
-        logs.append(new Log(id, tag));
-        return id;
+        bool was_empty = (logs == null);
+        Log res = new Log(tag, title);
+        logs.append(res);
+        if (was_empty) start_trace();
+        return res;
     }
 
-    public void add(uint id, string msg)
+    public void end(Log log)
     {
-        Log log = find(id);
-        if (log == null) return;
-        log.add(msg);
+        pop(log);
+        log.save();
+        if (logs == null) end_trace();
     }
 
-    public void end(uint id)
+    public Log load(string fname)
     {
-        Log log = pop(id);
-        log.save();
+        string contents;
+        size_t length;
+        FileUtils.get_contents(fname, out contents, out length);
+        LogParser parser = new LogParser();
+        parser.parse(contents, (ssize_t)length);
+        return parser.result;
+    }
+
+    public delegate bool EntriesVisitor(string dir, string name);
+
+
+    protected void list_dir(string dir, EntriesVisitor visitor)
+    {
+        var d = File.new_for_path(dir);
+        var enumerator = d.enumerate_children(FILE_ATTRIBUTE_STANDARD_NAME, 0, null);
+        FileInfo file_info;
+        while ((file_info = enumerator.next_file(null)) != null)
+        {
+            if (!file_info.get_name().has_suffix(".gpx")) continue;
+            if (!visitor(dir, file_info.get_name()))
+                break;
+        }
+    }
+
+    public void list_entries(EntriesVisitor visitor, bool only_unacked=true)
+    {
+        if (!only_unacked)
+            list_dir(config.homedir + "/archive", visitor);
+        list_dir(config.homedir + "/log", visitor);
     }
 
     public void instant(string tag, string msg)
     {
-        var log = new Log(0, tag);
+        var log = new Log(tag, msg);
         log.add(msg);
         log.save();
     }
 
     public void shutdown()
     {
+        bool had_logs = (logs != null);
         while (logs != null)
         {
-            var log = pop(logs.data.id);
-            log.save();
+            logs.data.save();
+            logs.delete_link(logs);
         }
+        if (had_logs) end_trace();
     }
 }