*.pyc
*.swp
+*.o
+/src/*.c
+Makefile.in
+/Makefile
+/src/Makefile
+/src/*.stamp
+/aclocal.m4
+/autom4te.cache/
+/compile
+/config.guess
+/config.h
+/config.h.in
+/config.log
+/config.status
+/config.sub
+/configure
+/depcomp
+/install-sh
+/libtool
+/ltmain.sh
+/m4/
+/missing
+/src/zavai
+/stamp-h1
--- /dev/null
+ACLOCAL_AMFLAGS=-I m4
+
+SUBDIRS = src
+
+#pkgconfigdir = $(libdir)/pkgconfig
+#pkgconfig_DATA = gee-1.0.pc
+
+#EXTRA_DIST += \
+# MAINTAINERS \
+# gee-1.0.pc.in \
+# $(NULL)
+
--- /dev/null
+AC_INIT([zavai], [0.1], [enrico@enricozini.org], [zavai])
+AC_CONFIG_SRCDIR([Makefile.am])
+AC_CONFIG_HEADERS(config.h)
+AM_INIT_AUTOMAKE(foreign)
+
+# Checks for programs.
+AC_PROG_CC
+AM_PROG_CC_C_O
+AC_DISABLE_STATIC
+AC_PROG_LIBTOOL
+
+AC_CONFIG_MACRO_DIR([m4])
+
+AC_PATH_PROG(VALAC, valac, valac)
+AC_SUBST(VALAC)
+
+AC_SUBST(CFLAGS)
+AC_SUBST(CPPFLAGS)
+AC_SUBST(LDFLAGS)
+
+GLIB_REQUIRED=2.10.0
+PKG_CHECK_MODULES(GLIB, glib-2.0 >= $GLIB_REQUIRED gobject-2.0 >= $GLIB_REQUIRED)
+AC_SUBST(GLIB_CFLAGS)
+AC_SUBST(GLIB_LIBS)
+
+PKG_CHECK_MODULES(DBUS, dbus-glib-1 >= 0.80)
+AC_SUBST(DBUS_CFLAGS)
+AC_SUBST(DBUS_LIBS)
+
+PKG_CHECK_MODULES(GEE, gee-1.0 >= 0.1)
+AC_SUBST(GEE_CFLAGS)
+AC_SUBST(GEE_LIBS)
+
+PKG_CHECK_MODULES(GTK, gtk+-2.0 >= 2.16.0)
+AC_SUBST(GTK_CFLAGS)
+AC_SUBST(GTK_LIBS)
+
+AC_CONFIG_FILES([Makefile
+ src/Makefile])
+
+AC_OUTPUT
--- /dev/null
+#!/usr/bin/python
+
+# zavai - simple interface to the OpenMoko (or to the FSO stack)
+#
+# Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+import sys
+import signal
+import optparse
+import gtk
+import dbus
+import dbus.mainloop.glib
+import zavai
+
+VERSION=zavai.VERSION
+
+class Parser(optparse.OptionParser):
+ def __init__(self, *args, **kwargs):
+ # Yes, in 2009 optparse from the *standard library* still uses old
+ # style classes
+ optparse.OptionParser.__init__(self, *args, **kwargs)
+
+ def error(self, msg):
+ sys.stderr.write("%s: error: %s\n\n" % (self.get_prog_name(), msg))
+ self.print_help(sys.stderr)
+ sys.exit(2)
+
+parser = Parser(usage="usage: %prog [options]",
+ version="%prog "+ VERSION,
+ description="Simple interactive interface for the OpenMoko")
+parser.add_option("-v", "--verbose", action="store_true", help="verbose mode")
+
+(opts, args) = parser.parse_args()
+
+if not opts.verbose:
+ zavai.set_quiet()
+
+# Read configuration
+zavai.info("Loading configuration")
+conf = zavai.Config()
+
+# Set up dbus
+dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
+dbus_system_bus = dbus.SystemBus()
+
+# Set up zavai
+registry = zavai.Registry()
+
+# Register main factories
+registry.register(dbus_system_bus, "dbus.system_bus")
+registry.register(conf, "conf")
+registry.register_factory(zavai.Zavai, "app")
+registry.register_factory(zavai.GPS, "gps")
+registry.register_factory(zavai.GPX, "gpx")
+registry.register_factory(zavai.Audio, "audio")
+
+# Load plugins
+zavai.info("Loading plugins")
+for p in zavai.load_plugins(nick="zavai"):
+ try:
+ p.init(conf = conf, registry = registry)
+ except Exception, e:
+ print >>sys.stderr, "Exception caught loading plugin %s: skipping plugin" % p
+ print >>sys.stderr, "Exception details:"
+ import traceback
+ details = traceback.format_exc()
+ print >>sys.stderr, "\t"+details.rstrip().replace("\n", "\n\t")
+
+# Shutdown the main loop on SIGINT
+def on_kill(signum, frame):
+ gtk.main_quit()
+signal.signal(signal.SIGINT, on_kill)
+signal.signal(signal.SIGTERM, on_kill)
+
+zavai.info("Starting")
+app = registry.resource("app")
+app.connect("destroy", gtk.main_quit)
+app.run()
+
+zavai.info("Shutting down")
+registry.shutdown()
+
+sys.exit(0)
--- /dev/null
+VFLAGS=-g --pkg gee-1.0 --pkg dbus-glib-1 --pkg gtk+-2.0
+
+#zavai: $(SOURCES)
+# valac -o zavai $(VFLAGS) $^
+#
+#C: $(SOURCES)
+# valac -C $(VFLAGS) $^
+#
+##zavai: $(SOURCES:.vala=.vala.o)
+## echo $<
+## gcc $(LDFLAGS) -o zavai $*
+##
+##%.vala.o: %.vala
+## valac $(VFLAGS) -c $<
+
+AM_CPPFLAGS = \
+ -I$(top_srcdir) \
+ $(GLIB_CFLAGS) \
+ $(DBUS_CFLAGS) \
+ $(GEE_CFLAGS) \
+ $(GTK_CFLAGS)
+
+BUILT_SOURCES = zavai.vala.stamp
+
+bin_PROGRAMS = zavai
+
+zavai_VALASOURCES = \
+ log.vala \
+ config.vala \
+ registry.vala \
+ gps.vala \
+ app.vala \
+ app_gps.vala \
+ app_debug.vala \
+ zavai.vala
+
+zavai_SOURCES = \
+ zavai.vala.stamp \
+ $(zavai_VALASOURCES:.vala=.c) \
+ $(zavai_VALASOURCES:.vala=.h)
+
+zavai.vapi zavai.vala.stamp: $(zavai_VALASOURCES)
+ $(VALAC) -C --basedir $(top_srcdir) $(VFLAGS) $^
+ touch $@
+
+zavai_LDADD = \
+ $(GLIB_LIBS) \
+ $(DBUS_LIBS) \
+ $(GEE_LIBS) \
+ $(GTK_LIBS)
+
+#vapidir = $(datadir)/vala/vapi
+
+#dist_vapi_DATA = \
+# gee-1.0.vapi \
+# $(NULL)
+
+#EXTRA_DIST += $(libgee_la_VALASOURCES) gee-1.0.vapi gee.vala.stamp
--- /dev/null
+/*
+ * app - zavai main window
+ *
+ * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+using GLib;
+
+namespace zavai {
+
+public class Zavai : Gtk.Window, zavai.Resource
+{
+ zavai.Applet current;
+ string current_name;
+
+ public Zavai()
+ {
+ title = "Zavai";
+ current = null;
+ current_name = null;
+ destroy += Gtk.main_quit;
+ }
+
+ public void show_applet(string name)
+ {
+ zavai.Applet applet = zavai.registry.geta(name);
+
+ // Remove the current applet
+ if (current != null)
+ {
+ current.stop();
+ remove(current);
+ current = null;
+ current_name = null;
+ }
+
+ // Add the new applet
+ current = applet;
+ current_name = name;
+ add(current);
+ current.start();
+ current.show_all();
+ }
+
+ public void push_applet(string name)
+ {
+stderr.printf("push applet %s -> %s\n", current_name, name);
+ zavai.Applet applet = zavai.registry.geta(name);
+
+ // Remove the current applet
+ if (current != null)
+ {
+stderr.printf("push applet remove %s\n", current_name);
+ applet.back_link = current_name;
+ current.stop();
+ remove(current);
+ current = null;
+ current_name = null;
+ }
+
+stderr.printf("push applet add %s\n", name);
+ // Add the new applet
+ current = applet;
+ current_name = name;
+ add(current);
+ current.start();
+ current.show_all();
+ }
+
+ public void shutdown()
+ {
+ }
+
+ public void run()
+ {
+ set_size_request(300, 500);
+ //fullscreen();
+ show_all();
+ }
+}
+/*
+class Zavai(gtk.Window, zavai.Resource):
+ def __init__(self, registry, name):
+ super(Zavai, self).__init__()
+ self.registry = registry
+ self.current = None
+ self.activate_resource("menu.main")
+
+ def activate_resource(self, name):
+ widget = self.registry.resource(name)
+ if widget is None:
+ widget = self.registry.resource("menu.main")
+ if isinstance(widget, gtk.Action):
+ widget.activate()
+ else:
+ self.show_widget(name, widget)
+*/
+
+public abstract class Applet : Gtk.VBox, Resource
+{
+ // 'label' property: label to show in window title or button names
+ protected string _label;
+ public string label {
+ get { return this._label; }
+ set {
+ if (_label != value)
+ {
+ _label = value;
+ label_changed();
+ }
+ }
+ }
+ public signal void label_changed();
+
+ // 'back_link' property: link to use to "go back". If null, do not show
+ // a way to go back.
+ protected AppletLink _back_link = null;
+ public string back_link {
+ get { return _back_link.target; }
+ set {
+stderr.printf("Set back link of %s to %s\n", _label, value);
+ if (value == null && _back_link != null)
+ {
+ _back_link.target = value;
+ remove(_back_link);
+ } else if (value != null) {
+ if (_back_link.target == null)
+ {
+ _back_link.target = value;
+ pack_end(_back_link, false, false, 0);
+ _back_link.show();
+ } else
+ _back_link.target = value;
+ }
+ }
+ }
+
+ public Applet()
+ {
+ this.homogeneous = false;
+ this.spacing = 0;
+ _back_link = new AppletStraightLink();
+ }
+/*
+ name = gobject.property(type=str)
+ label = gobject.property(type=str)
+
+ def __init__(self, registry, name, label = None):
+ super(Applet, self).__init__()
+
+ self.zavai_registry = registry
+
+ self.props.name = name
+ if label is None:
+ self.props.label = zavai.default_label(name)
+ else:
+ self.props.label = label
+
+ self.back_link = zavai.LinkButton(registry, zavai.get_parent(name), _("Back"))
+ self.pack_end(self.back_link, False, False)
+
+ def add(self, widget):
+ self.pack_start(widget, True, True)
+*/
+
+ public void shutdown()
+ {
+ stop();
+ }
+
+ public virtual void start() {}
+ public virtual void stop() {}
+}
+
+public class Menu : Applet
+{
+ public Menu(string label)
+ {
+ _label = label;
+ }
+
+ public void add_applet(string target)
+ {
+stderr.printf("menu.add_applet.packpre me %s them %s\n", _label, target);
+ pack_start(new AppletPushLink(target), false, false, 0);
+stderr.printf("menu.add_applet.packpost me %s them %s\n", _label, target);
+ }
+
+ public void add_service_toggle(string service_name, string label_start, string label_stop)
+ {
+ pack_start(new ServiceRequestLink(service_name, label_start, label_stop), false, false, 0);
+ }
+
+ public void add_widget(Gtk.Widget w)
+ {
+ pack_start(w, false, false, 0);
+ }
+}
+
+public class BigButton : Gtk.Button
+{
+ public BigButton()
+ {
+ set_size_request(0, zavai.config.min_button_height);
+ }
+}
+
+public abstract class AppletLink : BigButton
+{
+ protected string _target;
+ public string target {
+ get { return _target; }
+ set
+ {
+ if (_target != null)
+ {
+ Applet a = zavai.registry.geta(_target);
+ a.label_changed -= on_label_changed;
+ }
+ bool was_shown = _target != null;
+ _target = value;
+ if (_target != null)
+ {
+ Applet a = zavai.registry.geta(_target);
+ set_label(a.label);
+ a.label_changed += on_label_changed;
+ if (!was_shown) show();
+ } else {
+ if (was_shown) hide();
+ }
+ }
+ }
+
+ private void on_label_changed(Applet a)
+ {
+ set_label(a.label);
+ }
+
+ private abstract void on_clicked(Gtk.Button src);
+
+ public AppletLink(string? name = null)
+ {
+ _target = null;
+ target = name;
+
+ clicked += on_clicked;
+ }
+}
+
+public class AppletStraightLink : AppletLink
+{
+ private override void on_clicked(Gtk.Button src)
+ {
+stderr.printf("straight link: %s\n", _target);
+ if (_target != null)
+ zavai.app.show_applet(_target);
+ }
+
+ public AppletStraightLink(string? name = null)
+ {
+ base(name);
+ }
+}
+
+public class AppletPushLink : AppletLink
+{
+ private override void on_clicked(Gtk.Button src)
+ {
+stderr.printf("push link: %s\n", _target);
+ if (_target != null)
+ zavai.app.push_applet(_target);
+ }
+
+ public AppletPushLink(string? name = null)
+ {
+ base(name);
+ }
+}
+
+public class ServiceRequestLink : Gtk.ToggleButton
+{
+ protected string service_name;
+ protected string label_start;
+ protected string label_stop;
+
+ private void on_toggled(Gtk.Button src)
+ {
+ Service s = zavai.registry.gets(service_name);
+ if (get_active())
+ s.request("servicerequestlink");
+ else
+ s.release("servicerequestlink");
+ set_label(get_active() ? label_stop : label_start);
+ }
+
+ public ServiceRequestLink(string service_name, string label_start, string label_stop)
+ {
+ this.service_name = service_name;
+ this.label_start = label_start;
+ this.label_stop = label_stop;
+ set_size_request(0, zavai.config.min_button_height);
+ toggled += on_toggled;
+
+ set_label(get_active() ? label_stop : label_start);
+ }
+}
+
+zavai.Zavai app;
+
+}
--- /dev/null
+/*
+ * app_debug - zavai debug menus
+ *
+ * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+namespace zavai {
+namespace ui {
+namespace debug {
+
+public class Useless : Applet
+{
+ public Useless()
+ {
+ _label = "Useless";
+ pack_start(new Gtk.Label("This has no use"), false, false, 0);
+ }
+}
+
+public class UselessService : Service
+{
+ public UselessService()
+ {
+ name = "app.debug.useless_service";
+ }
+}
+
+public class Quitter : Applet
+{
+ public Quitter()
+ {
+ _label = "Quit";
+ }
+
+ public override void start()
+ {
+ Gtk.main_quit();
+ }
+}
+
+/*
+class Quitter(gtk.Action):
+ def __init__(self, **kw):
+ super(Quitter, self).__init__("menu.main.debug.quit", _("Quit"), None, None)
+
+ self.connect("activate", gtk.main_quit)
+*/
+
+void init()
+{
+ //label_on = "Stop useless service";
+ //label_off = "Start useless service";
+ // Apps
+ var useless = new Useless();
+ var quitter = new Quitter();
+ var useless_service = new UselessService();
+ zavai.registry.register_applet("app.debug.useless", useless);
+ zavai.registry.register_service(useless_service);
+ zavai.registry.register_applet("app.debug.quit", quitter);
+
+ // Menus
+ var menu_debug = new zavai.Menu("Debug");
+ menu_debug.add_applet("app.debug.useless");
+ menu_debug.add_service_toggle("app.debug.useless_service", "Start useless service", "Stop useless service");
+ menu_debug.add_applet("app.debug.quit");
+
+ zavai.registry.register_menu("menu.debug", menu_debug);
+ zavai.registry.getmenu("menu.main").add_applet("menu.debug");
+}
+
+
+}
+}
+}
--- /dev/null
+/*
+ * gpx_trace - zavai GPX trace functions
+ *
+ * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+namespace zavai {
+namespace ui {
+namespace gps {
+
+/*
+class GPSOn(gtk.ToggleAction):
+ states = [_("GPS always on"), _("GPS on when needed")]
+
+ def __init__(self, registry, **kw):
+ self.state = 0
+ super(GPSOn, self).__init__("menu.main.gps.alwayson", self.states[self.state], None, None)
+
+ self.registry = registry
+ self.set_active(False)
+
+ self.connect("toggled", self.on_toggle)
+
+ def on_toggle(self, *args):
+ self.state = (self.state + 1) % len(self.states)
+ self.set_property("label", self.states[self.state])
+ if self.get_active():
+ self.start()
+ else:
+ self.stop()
+
+ def start(self):
+ self.registry.resource("gps").connect("gps", self)
+
+ def stop(self):
+ self.registry.resource("gps").disconnect("gps", self)
+
+class GPXTracer(gtk.ToggleAction):
+ states = [_("Start GPX trace"), _("Stop GPX trace")]
+
+ def __init__(self, registry, **kw):
+ self.state = 0
+ super(GPXTracer, self).__init__("menu.main.gps.gpx", self.states[self.state], None, None)
+
+ self.registry = registry
+ self.set_active(False)
+
+ self.connect("toggled", self.on_toggle)
+
+ def on_toggle(self, *args):
+ self.state = (self.state + 1) % len(self.states)
+ self.set_property("label", self.states[self.state])
+ if self.get_active():
+ self.start()
+ else:
+ self.stop()
+
+ def start(self):
+ zavai.info("GPX trace started")
+ self.registry.resource("gpx").connect("gpx", self)
+
+ def stop(self):
+ zavai.info("GPX trace ended")
+ self.registry.resource("gpx").disconnect("gpx", self)
+*/
+
+public class Waypoint : BigButton
+{
+ public Waypoint()
+ {
+ set_label("Take waypoint");
+ zavai.gps.gpx.tracking_changed += on_gpx_tracking_changed;
+ clicked += on_clicked;
+ set_sensitive(zavai.gps.gpx.tracking);
+ }
+
+ protected void on_gpx_tracking_changed(zavai.gps.GPX gpx, bool new_state)
+ {
+stderr.printf("Toggled %d\n", (int)new_state);
+ set_sensitive(new_state);
+ }
+
+ protected void on_clicked()
+ {
+stderr.printf("Activate\n");
+ zavai.gps.gpx.waypoint();
+ }
+}
+
+/*
+class GPXAudioTracer(gtk.ToggleAction):
+ states = [_("Start GPX and audio trace"), _("Stop GPX and audio trace")]
+
+ def __init__(self, registry, **kw):
+ self.state = 0
+ super(GPXAudioTracer, self).__init__("menu.main.gps.gpxaudio", self.states[self.state], None, None)
+
+ self.registry = registry
+ self.recorder = zavai.Recorder(registry)
+ self.set_active(False)
+
+ self.connect("toggled", self.on_toggle)
+
+ def shutdown(self):
+ self.recorder.stop()
+ super(GPXAudioTracer, self).shutdown()
+
+ def on_toggle(self, *args):
+ self.state = (self.state + 1) % len(self.states)
+ self.set_property("label", self.states[self.state])
+ if self.get_active():
+ self.start()
+ else:
+ self.stop()
+
+ def start(self):
+ zavai.info("GPX trace started")
+ gpx = self.registry.resource("gpx")
+ gpx.connect("gpx", self)
+ gpx.add_activity_monitor(self.on_gpx_activity_changed)
+
+ def stop(self):
+ zavai.info("GPX trace ended")
+ gpx = self.registry.resource("gpx")
+ gpx.disconnect("gpx", self)
+ self.recorder.stop()
+ gpx.del_activity_monitor(self.on_gpx_activity_changed)
+
+ def on_gpx_activity_changed(self, gpx, state):
+ if state:
+ self.recorder.start(gpx.basename + ".wav")
+ else:
+ self.recorder.stop()
+*/
+
+public class GPSRequestLink : Gtk.ToggleButton
+{
+ protected string service_name;
+ protected string label_start;
+ protected string label_stop;
+ protected Gtk.StatusIcon status_icon;
+ protected int fix_status = 0;
+
+ public GPSRequestLink()
+ {
+ service_name = "gps";
+ label_start = "Keep GPS on";
+ label_stop = "Stop keeping GPS on";
+ set_size_request(0, zavai.config.min_button_height);
+ toggled += on_toggled;
+
+ set_label(get_active() ? label_stop : label_start);
+
+ //tooltip = "GPS status";
+ try {
+ fix_status = zavai.gps.gps.device.GetFixStatus();
+ } catch (Error e) {
+ fix_status = 0;
+ }
+ zavai.gps.gps.device.FixStatusChanged += on_fix_status_changed;
+
+ // GPS status icon
+ status_icon = new Gtk.StatusIcon();
+ status_icon.set_visible(true);
+ status_icon.activate += on_status_activate;
+ update_icon();
+ }
+
+ protected void update_icon()
+ {
+ string name;
+ if (fix_status == 2 || fix_status == 3)
+ name = zavai.config.icondir + "/" + (get_active() ? "gps_fix_on.png" : "gps_fix_off.png");
+ else
+ name = zavai.config.icondir + "/" + (get_active() ? "gps_nofix_on.png" : "gps_nofix_off.png");
+stderr.printf("load icon from %s\n", name);
+ status_icon.set_from_file(name);
+ }
+
+ private void on_fix_status_changed(dynamic DBus.Object pos, int fix_status)
+ {
+ this.fix_status = fix_status;
+ update_icon();
+ }
+
+ private void on_toggled(Gtk.Button src)
+ {
+ Service s = zavai.registry.gets(service_name);
+ if (get_active())
+ s.request("servicerequestlink");
+ else
+ s.release("servicerequestlink");
+ set_label(get_active() ? label_stop : label_start);
+ update_icon();
+ }
+
+ private void on_status_activate()
+ {
+ set_active(!get_active());
+ }
+}
+
+public void init()
+{
+ /*
+ registry.register(GPXAudioTracer(registry))
+ registry.register(GPXWaypoint(registry))
+
+ // Apps
+ var useless = new Useless();
+ zavai.registry.register_applet("app.debug.useless", useless);
+ */
+ var menu_waypoint = new Waypoint();
+ var menu_gpsrequest = new GPSRequestLink();
+ //label_on = "Stop GPX trace";
+ //label_off = "Start GPX trace";
+ //label_on = "Stop GPS monitor";
+ //label_off = "Start GPS monitor";
+ //label_on = "Stop GPS position tracking";
+ //label_off = "Start GPS position tracking";
+ //label_on = "Stop keeping GPS on";
+ //label_off = "Keep GPS on";
+
+ // Menus
+ var menu_gps = new zavai.Menu("GPS");
+ //menu_gps.add_applet("app.debug.useless");
+ menu_gps.add_service_toggle("gps.gpx", "Start GPX trace", "Stop GPX trace");
+ menu_gps.add_widget(menu_waypoint);
+ menu_gps.add_widget(menu_gpsrequest);
+
+ zavai.registry.register_menu("menu.gps", menu_gps);
+ zavai.registry.getmenu("menu.main").add_applet("menu.gps");
+}
+
+}
+}
+}
--- /dev/null
+/*
+ * config - zavai configuration
+ *
+ * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+namespace zavai {
+
+public class Config
+{
+ public string version { get; set; }
+ public string homedir { get; set; }
+ public string icondir { get; set; }
+ public int min_button_height { get; set; }
+
+ public Config()
+ {
+ // Set defaults
+ version = "0.1";
+ homedir = "/root/.zavai";
+ icondir = ".";
+ min_button_height = 80;
+ }
+
+/*
+ def _get_homedir(self):
+ res = self.get("global", "home")
+ if res is None:
+ res = os.path.expanduser("~/.zavai")
+ if not os.path.isdir(res):
+ zavai.info("Creating directory", res)
+ os.makedirs(res)
+ return res
+*/
+}
+
+/*
+import os
+import ConfigParser, StringIO
+
+def read_config(rootDir = None, defaults = None, nick="octofuss"):
+ """
+ Read octofuss configuration, returning a ConfigParser object
+ """
+ if rootDir == None:
+ rootDir = os.environ.get(nick.upper() + "_CONFDIR", "/etc/" + nick)
+ files = []
+ def trytouse(path):
+ if os.path.exists(path):
+ files.append(path)
+
+ # Start with the main config file
+ trytouse(os.path.join(rootDir, nick + ".conf"))
+
+ # Add snippets found in rc.d style directory
+ subdir = os.path.join(rootDir, nick + ".conf.d")
+ if os.path.isdir(subdir):
+ for file in sorted(os.listdir(subdir)):
+ if file.startswith('#'): continue
+ if file.startswith('.'): continue
+ if file.endswith('~'): continue
+ if file.endswith('.bak'): continue
+ trytouse(os.path.join(subdir, file))
+
+ config = ConfigParser.ConfigParser()
+ if defaults != None:
+ infile = StringIO.StringIO(defaults)
+ config.readfp(infile, "defaults")
+ config.read(files)
+ return config
+import os.path
+import zavai
+
+class Config:
+ def __init__(self):
+ self.conf = zavai.read_config(nick="zavai")
+
+ def get(self, section, name, default=None):
+ if self.conf.has_section(section):
+ if self.conf.has_option(section, name):
+ return self.conf.get(section, name)
+ return None
+
+ homedir = property(_get_homedir)
+*/
+
+Config config = null;
+
+}
--- /dev/null
+/*
+ * gps - gps resource for zavai
+ *
+ * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+using GLib;
+
+namespace zavai {
+namespace gps {
+
+// For a list of dbus services, look in /etc/dbus-1/system.d/
+public class GPS: zavai.Service
+{
+ public dynamic DBus.Object usage;
+ public dynamic DBus.Object device;
+
+ public GPS()
+ {
+ name = "gps";
+
+ // see mdbus -s org.freesmartphone.ousaged /org/freesmartphone/Usage
+ usage = zavai.registry.sbus.get_object(
+ "org.freesmartphone.ousaged",
+ "/org/freesmartphone/Usage",
+ "org.freesmartphone.Usage");
+
+ device = zavai.registry.sbus.get_object(
+ "org.freesmartphone.ogpsd",
+ "/org/freedesktop/Gypsy",
+ "org.freedesktop.Gypsy.Device");
+
+// # see mdbus -s org.freesmartphone.ogpsd /org/freedesktop/Gypsy
+// gps = self.bus.get_object('org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
+// self.gps = dbus.Interface(gps, "org.freedesktop.Gypsy.Device")
+// self.gps_time = dbus.Interface(gps, "org.freedesktop.Gypsy.Time")
+// self.gps_position = dbus.Interface(gps, 'org.freedesktop.Gypsy.Position')
+// self.gps_ubx = dbus.Interface(gps, 'org.freesmartphone.GPS.UBX')
+ usage.ResourceChanged += on_resourcechanged;
+ }
+
+ public void on_resourcechanged(dynamic DBus.Object pos, string name, bool state, HashTable<string, Value?> attributes)
+ {
+ zavai.log.info("RESOURCE CHANGED " + name);
+ }
+
+ /// Request GPS resource
+ public override void start()
+ {
+ if (started) return;
+ try {
+ usage.RequestResource("GPS");
+ zavai.log.info("Acquired GPS");
+ base.start();
+ } catch (GLib.Error e) {
+ zavai.log.error(e.message);
+ }
+ base.start();
+ }
+
+ // Release usage of GPS
+ public override void stop()
+ {
+ if (!started) return;
+ try {
+ usage.ReleaseResource("GPS");
+ zavai.log.info("Released GPS");
+ base.stop();
+ } catch (GLib.Error e) {
+ zavai.log.error(e.message);
+ }
+ base.stop();
+ }
+}
+
+public class Monitor : zavai.Service
+{
+ static const int NAV_STATUS=0;
+ static const int NAV_SVINFO=1;
+ static const int NAV_MAX=2;
+
+ dynamic DBus.Object ubx;
+ dynamic DBus.Object time;
+ /*
+ string[] filters = { "NAV-STATUS", "NAV_SVINFO" };
+
+ int debug_busy;
+ int debug_want;
+ int debug_have;
+ int debug_error;
+ */
+
+
+ public Monitor()
+ {
+ name = "gps.monitor";
+
+ ubx = zavai.registry.sbus.get_object(
+ "org.freesmartphone.ogpsd",
+ "/org/freedesktop/Gypsy",
+ "org.freesmartphone.GPS.UBX");
+ time = zavai.registry.sbus.get_object(
+ "org.freesmartphone.ogpsd",
+ "/org/freedesktop/Gypsy",
+ "org.freedesktop.Gypsy.Time");
+
+ zavai.log.info("SETSIG1");
+ time.TimeChanged += timechanged;
+ zavai.log.info("SETSIG2");
+
+ zavai.log.info("DEBUG1");
+ ubx.DebugPacket += on_ubxdebug_packet;
+ zavai.log.info("DEBUG2");
+
+/*
+ // This piece of machinery is taken from Zhone
+ debug_busy = -1;
+ debug_want = (1 << NAV_STATUS) | (1 << NAV_SVINFO);
+ debug_have = 0;
+ debug_error = 0;
+*/
+ }
+
+ protected void timechanged(dynamic DBus.Object pos, int t)
+ {
+ zavai.log.info("TIMECHANGED");
+ }
+
+/*
+ protected void debug_update() throws GLib.Error
+ {
+ zavai.log.debug("UPDATE");
+ if (debug_busy != -1)
+ return;
+ zavai.log.debug("UPD1");
+ int pending = debug_want & (~debug_have) & (~debug_error);
+ if (pending == 0)
+ return;
+ zavai.log.debug("UPD2");
+ for (int i = 0; i < NAV_MAX; ++i)
+ if ((pending & (1<<i)) != 0)
+ {
+ debug_busy = i;
+ break;
+ }
+ zavai.log.debug("UPD3 " + filters[debug_busy]);
+
+ ubx.SetDebugFilter(
+ filters[debug_busy],
+ true,
+ on_debug_reply
+// on_debug_error
+ );
+ zavai.log.debug("UPD4");
+ }
+
+ protected void debug_request() throws GLib.Error
+ {
+ debug_have = 0;
+ debug_update();
+ }
+
+ protected void on_debug_reply() throws GLib.Error
+ {
+ debug_have |= (1<<debug_busy);
+ debug_busy = -1;
+ debug_update();
+ }
+
+ protected void on_debug_error(string e) throws GLib.Error
+ {
+ string name = debug_busy == -1 ? "none" : filters[debug_busy];
+ zavai.log.error("error while requesting debug packet " + name + ": " + e);
+ debug_error |= (1<<debug_busy);
+ debug_busy = -1;
+ debug_update();
+ }
+*/
+
+ /*
+ protected void on_satellites_changed(satellites)
+ {
+// zavai.info("gps monitor: satellites changed")
+// self.debug_request()
+ }
+ */
+
+ protected void on_ubxdebug_packet(dynamic DBus.Object ubx, string clid, int length,
+ HashTable<string, Value?>[] data)
+ {
+ zavai.log.info("gps monitor: UBX debug packet");
+ message("ZAZA %s %d", clid, length);
+ message("ZAZA %u %lu", data.length, sizeof(HashTable<string, Value?>));
+ message("ZAZA %p %p", (void*)data.length, this);
+ message("ZAZA %p", data[0]);
+ message("ZAZA %p", data[1]);
+ message("ZAZA %p", data[2]);
+ /*
+ message("ZAZA %u", data[0].size());
+ foreach (string k in data[0].get_keys())
+ message("ZAZA %s", k);
+ */
+ PtrArray< HashTable<string, Value?> >* prova = (PtrArray< HashTable<string, Value?> >)data;
+ message("ZAZA %u", prova->len);
+ /*
+ foreach (string k in prova[0].get_keys())
+ message("ZAZA %s", k);
+ */
+ /*
+ for (int i = 0; data[i] != null; ++i)
+ {
+ zavai.log.info("ZAZA");
+ }
+ */
+ //message("Size: %d", data.size());
+// self.notify("satellites", clid, length, data)
+ }
+
+ protected override void start()
+ {
+ if (started) return;
+
+ zavai.log.info("Starting GPS Monitor");
+ gps.request("gps.monitor");
+// # TODO: find out how come sometimes these events are not sent
+// self.gps.bus.add_signal_receiver(
+// self.on_satellites_changed, 'SatellitesChanged', 'org.freedesktop.Gypsy.Satellite',
+// 'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
+ //ubx.DebugPacket += prova;
+ //try {
+ //ubx.SetDebugFilter("NAV-STATUS", true);
+ //ubx.SetDebugFilter("NAV-SVINFO", true);
+ //debug_request();
+ base.start();
+ //} catch (GLib.Error e) {
+ //zavai.log.error(e.message);
+ //}
+ }
+
+ protected override void stop()
+ {
+ if (!started) return;
+ zavai.log.info("Stopping GPS Monitor");
+// self.gps.bus.remove_signal_receiver(
+// self.on_satellites_changed, 'SatellitesChanged', 'org.freedesktop.Gypsy.Satellite',
+// 'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
+ try {
+ ubx.SetDebugFilter("NAV-STATUS", false);
+ ubx.SetDebugFilter("NAV-SVINFO", false);
+ } catch (GLib.Error e) {
+ zavai.log.error(e.message);
+ }
+ ubx.DebugPacket -= on_ubxdebug_packet;
+ //ubx.DebugPacket -= prova;
+ gps.release("gps.monitor");
+ base.stop();
+ }
+}
+
+
+public class Position : zavai.Service
+{
+ dynamic DBus.Object position;
+
+ public signal void position_changed(int fields, int tstamp, double lat, double lon, double alt);
+
+ public Position()
+ {
+ name = "gps.position";
+ position = zavai.registry.sbus.get_object(
+ "org.freesmartphone.ogpsd",
+ "/org/freedesktop/Gypsy",
+ "org.freedesktop.Gypsy.Position");
+ }
+
+ public void on_position_changed(dynamic DBus.Object pos, int fields, int tstamp, double lat, double lon, double alt)
+ {
+ zavai.log.info("gps position: position changed");
+ position_changed(fields, tstamp, lat, lon, alt);
+ }
+
+ public override void start()
+ {
+ if (started) return;
+ zavai.log.info("Starting GPS position tracking");
+ gps.request("gps.position");
+ position.PositionChanged += on_position_changed;
+ base.start();
+ }
+
+ public override void stop()
+ {
+ if (!started) return;
+ zavai.log.info("Stopping GPS position tracking");
+ position.PositionChanged -= on_position_changed;
+ gps.release("gps.position");
+ base.stop();
+ }
+}
+
+// # def wait_for_fix(self, callback):
+// # status = self.gps.GetFixStatus()
+// # if status in [2, 3]:
+// # zavai.info("We already have a fix, good.")
+// # callback()
+// # return True
+// # else:
+// # zavai.info("Waiting for a fix...")
+// # self.waiting_for_fix = callback
+// # self.bus.add_signal_receiver(
+// # self.on_fix_status_changed, 'FixStatusChanged', 'org.freedesktop.Gypsy.Device',
+// # 'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
+// # return False
+// #
+// # def on_fix_status_changed(self, status):
+// # if status not in [2, 3]: return
+// #
+// # zavai.info("Got GPS fix")
+// # self.bus.remove_signal_receiver(
+// # self.on_fix_status_changed, 'FixStatusChanged', 'org.freedesktop.Gypsy.Device',
+// # 'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
+// #
+// # if self.waiting_for_fix:
+// # self.waiting_for_fix()
+// # self.waiting_for_fix = None
+// #
+//
+// # def start_recording(self):
+// # if self.gps_monitor:
+// # self.gps_monitor.stop()
+// # self.gps_monitor = None
+// #
+// # if not self.audio:
+// # return
+// #
+// # # Sync system time
+// # gpstime = self.gps.gps_time.GetTime()
+// # subprocess.call(["date", "-s", "@%d" % gpstime])
+// # subprocess.call(["hwclock", "--systohc"])
+// #
+// # # Compute basename for output files
+// # self.basename = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(gpstime))
+// # self.basename = os.path.join(AUDIODIR, self.basename)
+// #
+// # # Start recording the GPX track
+// # self.gpx = GPX(self.basename)
+// # self.gps.track_position(self.on_position_changed)
+// #
+// # # Start recording in background forking arecord
+// # self.audio.set_basename(self.basename)
+// # self.audio.start_recording()
+// #
+
+// Write GPX track and waypoint files
+public class GPX : Service
+{
+ public bool tracking {
+ get { return trk != null; }
+ set {}
+ }
+ public signal void tracking_changed(bool tracking);
+
+ FileStream trk = null;
+ FileStream wpt = null;
+ int wpt_seq = 1;
+ bool last_valid = false;
+ int last_fields;
+ time_t last_tstamp;
+ double last_lat;
+ double last_lon;
+ double last_alt;
+
+ public GPX()
+ {
+ name = "gps.gpx";
+ }
+
+ public override void start()
+ {
+ if (!started)
+ {
+ log.info("Starting GPX trace subsystem");
+ position.request("gps.gpx");
+ position.position_changed += on_position_changed;
+ base.start();
+ }
+ }
+
+ public override void stop()
+ {
+ if (started)
+ {
+ log.info("Stopping GPX trace subsystem");
+ position.release("gps.gpx");
+ position.position_changed -= on_position_changed;
+ stop_track();
+ base.stop();
+ }
+ }
+
+ public void on_position_changed(Position pos, int fields, int tstamp, double lat, double lon, double alt)
+ {
+ last_fields = fields;
+ last_tstamp = tstamp;
+ last_lat = lat;
+ last_lon = lon;
+ last_alt = alt;
+ last_valid = true;
+ trackpoint();
+ }
+
+ public void start_track(time_t tstamp = 0, string? basename = null)
+ {
+ string fname;
+ if (basename != null)
+ fname = basename;
+ else
+ {
+ time_t now = tstamp == 0 ? time_t() : tstamp;
+
+ // Compute basename for output files
+ var t = Time.local(now);
+ char[] res = new char[25];
+ t.strftime(res, "%Y-%m-%d-%H-%M-%S");
+ fname = zavai.config.homedir + "/" + (string)res;
+ }
+
+ trk = FileStream.open(fname + "-trk.gpx", "wt");
+ trk.puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
+ trk.puts(" <gpx");
+ trk.puts(" version=\"1.0\"");
+ trk.printf(" creator=\"zavai %s\"\n", zavai.config.version);
+ trk.puts(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
+ trk.puts(" xmlns=\"http://www.topografix.com/GPX/1/0\"");
+ trk.puts(" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">");
+ trk.puts(" <trk>");
+ trk.puts(" <trkseg>");
+
+ wpt = FileStream.open(fname + "-wpt.gpx", "wt");
+ wpt.puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
+ wpt.puts(" <gpx");
+ wpt.puts(" version=\"1.0\"");
+ wpt.printf(" creator=\"zavai %s\"", zavai.config.version);
+ wpt.puts(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
+ wpt.puts(" xmlns=\"http://www.topografix.com/GPX/1/0\"");
+ wpt.puts(" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">");
+
+ wpt_seq = 1;
+ tracking_changed(true);
+ }
+
+ public void stop_track()
+ {
+ if (trk != null)
+ {
+ trk.puts("</trkseg></trk></gpx>");
+ trk.flush();
+ trk = null;
+ }
+ if (wpt != null)
+ {
+ wpt.puts("</gpx>");
+ wpt.flush();
+ wpt = null;
+ }
+ last_valid = false;
+ tracking_changed(false);
+ }
+
+ // Mark a track point
+ public void trackpoint()
+ {
+ if (!last_valid) return;
+ if (trk == null)
+ start_track(last_tstamp);
+
+ trk.printf("<trkpt lat=\"%f\" lon=\"%f\">\n", last_lat, last_lon);
+ var t = Time.local(last_tstamp);
+ char[] ts = new char[25];
+ t.strftime(ts, "%Y-%m-%dT%H:%M:%SZ");
+ trk.printf(" <time>%s</time>\n", (string)ts);
+ trk.printf(" <ele>%f</ele>\n", last_alt);
+ // if course is not None: print >>self.trk, " <course>%f</course>" % course
+ // if speed is not None: print >>self.trk, " <speed>%f</speed>" % speed
+ // if fix is not None: print >>self.trk, " <fix>%f</fix>" % fix
+ // if hdop is not None: print >>self.trk, " <hdop>%f</hdop>" % hdop
+ trk.puts("</trkpt>");
+ }
+
+ // Mark a waypoint
+ public void waypoint(string? name = null)
+ {
+ if (!last_valid) return;
+ if (wpt == null)
+ start_track(last_tstamp);
+
+ string wptname;
+ if (name == null)
+ {
+ wptname = "wpt_%d".printf(wpt_seq);
+ wpt_seq += 1;
+ } else {
+ wptname = name;
+ }
+
+ wpt.printf("<wpt lat=\"%f\" lon=\"%f\">\n", last_lat, last_lon);
+ wpt.printf(" <name>%s</name>\n", wptname);
+ var t = Time.local(last_tstamp);
+ char[] ts = new char[25];
+ t.strftime(ts, "%Y-%m-%dT%H:%M:%SZ");
+ wpt.printf(" <time>%s</time>\n", (string)ts);
+ wpt.printf(" <ele>%f</ele>\n", last_alt);
+ wpt.puts("</wpt>");
+ }
+}
+
+// # def record(self):
+// # self.audio = Audio(self.make_waypoint)
+// # self.gps = GPS()
+// # # Get a fix and start recording
+// # if not self.gps.wait_for_fix(self.start_recording):
+// # self.gps_monitor = GPSMonitor(self.gps)
+// # self.gps_monitor.start()
+// #
+// # def monitor(self):
+// # self.audio = None
+// # self.gps = GPS()
+// # self.gps_monitor = GPSMonitor(self.gps)
+// # self.gps_monitor.start()
+// #
+// #
+// # def make_waypoint(self):
+// # if self.gpx is None:
+// # return
+// # if self.last_pos is None:
+// # self.last_pos = self.gps.gps_position.GetPosition()
+// # (fields, tstamp, lat, lon, alt) = self.last_pos
+// # self.gpx.waypoint(tstamp, lat, lon, alt)
+// # zavai.info("Making waypoint at %s: %f, %f, %f" % (
+// # time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(tstamp)), lat, lon, alt))
+
+public zavai.gps.GPS gps = null;
+public zavai.gps.Monitor monitor = null;
+public zavai.gps.Position position = null;
+public zavai.gps.GPX gpx = null;
+
+public void init()
+{
+ gps = new GPS();
+ monitor = new Monitor();
+ position = new Position();
+ gpx = new GPX();
+
+ zavai.registry.register_service(gps);
+ zavai.registry.register_service(position);
+ zavai.registry.register_service(monitor);
+ zavai.registry.register_service(gpx);
+}
+
+}
+}
--- /dev/null
+/*
+ * log - logging functions
+ *
+ * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+namespace zavai {
+namespace log {
+
+public void error(string s)
+{
+ stderr.printf("%s\n", s);
+}
+public void warning(string s)
+{
+ stderr.printf("%s\n", s);
+}
+public void info(string s)
+{
+ stderr.printf("%s\n", s);
+}
+public void debug(string s)
+{
+ stderr.printf("%s\n", s);
+}
+
+}
+}
--- /dev/null
+/*
+ * registry - zavai resource registry
+ *
+ * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+using GLib;
+using Gee;
+
+namespace zavai {
+
+public interface Resource : Object {
+ /**
+ * Shut down this resource.
+ *
+ * Normally one does nothing here, but it is important to give resources a
+ * chance to do cleanup when the program quits.
+ *
+ * This can be used for tasks like closing the tags on a GPX track,
+ * releasing a FSO resource, restoring mixer settings and so on.
+ */
+ public abstract void shutdown();
+}
+
+public abstract class Service : Object, Resource {
+ public string name { get; construct; }
+
+ bool _started;
+ public bool started {
+ get { return _started; }
+ set { _started = value; }
+ default = false;
+ }
+
+ public signal void toggled(bool new_state);
+
+ protected HashMap<string, int> requests;
+
+ construct {
+ requests = new HashMap<string, int>(str_hash, str_equal);
+ }
+
+ public void shutdown()
+ {
+ stop();
+ }
+
+ /// Activate the service
+ protected virtual void start()
+ {
+ if (!started)
+ {
+stderr.printf("SERVICE %s started\n", name);
+ started = true;
+ toggled(started);
+ }
+ }
+
+ /// Deactivate the service
+ protected virtual void stop()
+ {
+ if (started)
+ {
+stderr.printf("SERVICE %s stopped\n", name);
+ started = false;
+ toggled(started);
+ }
+ }
+
+ /**
+ Request a resource using the given ID.
+ *
+ * If it is the first time the resource is requested, start it and
+ * return true. Else, take note of the request and return false.
+ *
+ * If a resource is requested multiple times with the same ID, it will
+ * need to be released multiple times with that ID.
+ */
+ public bool request(string id)
+ {
+ bool res = (requests.size == 0);
+ if (id in requests)
+ requests[id] = requests[id] + 1;
+ else
+ requests.set(id, 1);
+ if (res) start();
+ return res;
+ }
+
+ /**
+ * Release a resource using the given ID.
+ *
+ * If after the call nothing is requesting the resource, stop it and
+ * return true. Else, take note of the release and return false.
+ *
+ * If a resource is requested multiple times with the same ID, it will
+ * need to be released multiple times with that ID.
+ */
+ public bool release(string id)
+ {
+ if (id in requests)
+ {
+ if (requests[id] > 1)
+ requests[id] = requests[id] - 1;
+ else
+ requests.remove(id);
+ } else {
+ return false;
+ }
+ if (requests.size > 0)
+ return false;
+ stop();
+ return true;
+ }
+}
+
+// class Service(Resource):
+// "Service that is activated only when someone is listening"
+// def __init__(self, types = []):
+// """
+// Initialise a service that can emit signals for the given event types
+// """
+// super(Service, self).__init__()
+// self.callbacks = dict()
+// for t in types:
+// self.callbacks[t] = set()
+// self.started = False
+//
+// def notify(self, type, *args, **kw):
+// "Call all callbacks with the given parameters"
+// for cb in self.callbacks[type]:
+// cb(*args, **kw)
+//
+// def has_callbacks(self):
+// for i in self.callbacks.values():
+// if i: return True
+// return False
+//
+// def connect(self, type, callback):
+// "Connect a callback to this resource, activating it if needed"
+// do_start = not self.has_callbacks()
+// self.callbacks[type].add(callback)
+// if do_start:
+// self.start()
+// self.started = True
+//
+// def disconnect(self, type, callback):
+// "Disconnect a callback to this resource, activating it if needed"
+// if not self.has_callbacks(): return
+// self.callbacks[type].discard(callback)
+// if not self.has_callbacks():
+// self.stop()
+// self.started = False
+
+
+// import zavai
+// import gtk
+//
+// def get_parent(s):
+// "Get the parent name for s"
+// pos = s.rfind(".")
+// if pos == -1: return None
+// res = s[:pos]
+// if res == "menu": return None
+// return res
+//
+// def default_label(s):
+// "Compute a default label given the last element of a path"
+// pos = s.rfind(".")
+// if pos == -1: return s.capitalize()
+// return s[pos+1:].capitalize()
+
+public class Registry : Object, Resource
+{
+ HashMap<string, Resource> memb_resources;
+ HashMap<string, Service> memb_services;
+ HashMap<string, Applet> memb_applets;
+ HashMap<string, Menu> memb_menus;
+ protected ArrayList<Resource> registration_order;
+ public DBus.Connection sbus;
+
+ public Registry()
+ {
+ memb_resources = new HashMap<string, Resource>(str_hash, str_equal);
+ memb_services = new HashMap<string, Service>(str_hash, str_equal);
+ memb_applets = new HashMap<string, Applet>(str_hash, str_equal);
+ memb_menus = new HashMap<string, Menu>(str_hash, str_equal);
+ registration_order = new ArrayList<Resource>();
+ sbus = DBus.Bus.get(DBus.BusType.SYSTEM);
+ }
+
+ public void shutdown()
+ {
+ // Shutdown in reverse registration order
+ for (int i = registration_order.size - 1; i >= 0; --i)
+ registration_order[i].shutdown();
+ }
+
+ public void register_resource(string name, Resource obj)
+ {
+ memb_resources[name] = obj;
+ registration_order.add(obj);
+ }
+
+ public void register_service(Service obj)
+ {
+ memb_services[obj.name] = obj;
+ registration_order.add(obj);
+ }
+
+ public void register_applet(string name, Applet obj)
+ {
+ memb_applets[name] = obj;
+ registration_order.add(obj);
+ }
+
+ public void register_menu(string name, Menu obj)
+ {
+ memb_applets[name] = obj;
+ memb_menus[name] = obj;
+ registration_order.add(obj);
+ }
+
+ public Resource? getr(string name)
+ {
+ if (name in memb_resources)
+ return memb_resources[name];
+ else
+ {
+ log.error("getr: no resource found: " + name);
+ return null;
+ }
+ }
+
+ public Service? gets(string name)
+ {
+ if (name in memb_services)
+ return memb_services[name];
+ else
+ {
+ log.error("gets: no service found: " + name);
+ return null;
+ }
+ }
+
+ public Applet? geta(string name)
+ {
+ if (name in memb_applets)
+ return memb_applets[name];
+ else
+ {
+ log.error("geta: no applet found: " + name);
+ return null;
+ }
+ }
+
+ public Menu? getmenu(string name)
+ {
+ if (name in memb_menus)
+ return memb_menus[name];
+ else
+ {
+ log.error("getmenu: no menu found: " + name);
+ return null;
+ }
+ }
+}
+
+// class Registry(object):
+// """Collection of resources.
+//
+// Various factories can be registered by name on the registry. Then when an
+// object is requested for the first time, it is created using the factory.
+// When it is requested again, the existing object is reused.
+// """
+//
+// def __init__(self):
+// self.factories = dict()
+// self.objects = dict()
+// self.labels = dict()
+//
+// def register(self, obj, name=None):
+// """Register an object at the given path.
+//
+// Name the path to this object, like "menu.gps.monitor".
+// """
+// if name is None:
+// name = obj.props.name
+//
+// if name in self.objects:
+// return KeyError("%s is already registered", name)
+// zavai.info("Registering", name)
+// self.objects[name] = obj
+//
+// if name.startswith("menu."):
+// self.add_to_menu(name)
+//
+// def register_factory(self, fac, name, label = None):
+// """Register an object factory at the given path.
+//
+// Name the path to this object, like "menu.gps.monitor".
+// """
+// if name in self.factories:
+// return KeyError("Factory %s is already registered", name)
+// zavai.info("Registering factory", name)
+// self.factories[name] = fac
+// if label is not None: self.labels[name] = label
+//
+// def add_to_menu(self, name):
+// "Add the applet with the given name to the menu structure"
+// parent = get_parent(name)
+// if parent is not None:
+// zavai.info("Add to menu", name, parent)
+// menu = self.menu(parent)
+//
+// obj = self.resource(name)
+// if isinstance(obj, gtk.ToggleAction):
+// menu.add_child(zavai.ToggleButton(self, name, action=obj))
+// elif isinstance(obj, gtk.Action):
+// menu.add_child(zavai.LinkButton(self, name, action=obj))
+// else:
+// menu.add_child(zavai.LinkButton(self, name, self.label(name)))
+//
+// def label(self, name):
+// "Return the label for the object with the given name"
+// res = self.labels.get(name)
+// if res is not None:
+// return res
+// try:
+// obj = self.resource(name)
+// return obj.props.label
+// except:
+// return default_label(name)
+//
+// def resource(self, name):
+// """Get a resource from the registry.
+//
+// If no resource exists at `name` but there is a factory, instantiate the
+// object using the factory.
+//
+// If not even a factory exists at `name`, returns None.
+// """
+// res = self.objects.get(name, None)
+// if res is None:
+// fac = self.factories.get(name, None)
+// if fac is not None:
+// res = self.objects[name] = fac(self, name)
+// return res
+//
+// def menu(self, name):
+// """Get a menu resource, automatically creating it if it is missing.
+//
+// Menus are created automatically linked to a parent menu, according to
+// the hierarchy in `name`.
+// """
+// res = self.resource(name)
+// if res is None:
+// # Check if it is a toplevel menu
+// if name.startswith("menu."):
+// parent = get_parent(name[5:])
+// if parent is not None:
+// parent = "menu." + parent
+// else:
+// parent = get_parent(name)
+//
+// res = zavai.Menu(self, name, parent)
+// self.register(res, name)
+// return res
+//
+// def shutdown(self):
+// """Shut down all objects in this Registry.
+//
+// After shutting down, all objects cannot be used anymore"""
+// for o in self.objects.itervalues():
+// if isinstance(o, Resource):
+// o.shutdown()
+// self.objects.clear()
+//
+
+zavai.Registry registry;
+
+}
+
+++ /dev/null
-#!/usr/bin/python
-
-# zavai - simple interface to the OpenMoko (or to the FSO stack)
-#
-# Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-import sys
-import signal
-import optparse
-import gtk
-import dbus
-import dbus.mainloop.glib
-import zavai
-
-VERSION=zavai.VERSION
-
-class Parser(optparse.OptionParser):
- def __init__(self, *args, **kwargs):
- # Yes, in 2009 optparse from the *standard library* still uses old
- # style classes
- optparse.OptionParser.__init__(self, *args, **kwargs)
-
- def error(self, msg):
- sys.stderr.write("%s: error: %s\n\n" % (self.get_prog_name(), msg))
- self.print_help(sys.stderr)
- sys.exit(2)
-
-parser = Parser(usage="usage: %prog [options]",
- version="%prog "+ VERSION,
- description="Simple interactive interface for the OpenMoko")
-parser.add_option("-v", "--verbose", action="store_true", help="verbose mode")
-
-(opts, args) = parser.parse_args()
-
-if not opts.verbose:
- zavai.set_quiet()
-
-# Read configuration
-zavai.info("Loading configuration")
-conf = zavai.Config()
-
-# Set up dbus
-dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
-dbus_system_bus = dbus.SystemBus()
-
-# Set up zavai
-registry = zavai.Registry()
-
-# Register main factories
-registry.register(dbus_system_bus, "dbus.system_bus")
-registry.register(conf, "conf")
-registry.register_factory(zavai.Zavai, "app")
-registry.register_factory(zavai.GPS, "gps")
-registry.register_factory(zavai.GPX, "gpx")
-registry.register_factory(zavai.Audio, "audio")
-
-# Load plugins
-zavai.info("Loading plugins")
-for p in zavai.load_plugins(nick="zavai"):
- try:
- p.init(conf = conf, registry = registry)
- except Exception, e:
- print >>sys.stderr, "Exception caught loading plugin %s: skipping plugin" % p
- print >>sys.stderr, "Exception details:"
- import traceback
- details = traceback.format_exc()
- print >>sys.stderr, "\t"+details.rstrip().replace("\n", "\n\t")
-
-# Shutdown the main loop on SIGINT
-def on_kill(signum, frame):
- gtk.main_quit()
-signal.signal(signal.SIGINT, on_kill)
-signal.signal(signal.SIGTERM, on_kill)
-
-zavai.info("Starting")
-app = registry.resource("app")
-app.connect("destroy", gtk.main_quit)
-app.run()
-
-zavai.info("Shutting down")
-registry.shutdown()
-
-sys.exit(0)
--- /dev/null
+/*
+ * zavai - simple interface to the OpenMoko (or to the FSO stack)
+ *
+ * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+using GLib;
+
+//string VERSION = "0.1";
+
+static int main (string[] args) {
+ Gtk.init (ref args);
+
+ // parser = Parser(usage="usage: %prog [options]",
+ // version="%prog "+ VERSION,
+ // description="Simple interactive interface for the OpenMoko")
+ // parser.add_option("-v", "--verbose", action="store_true", help="verbose mode")
+ //
+ // (opts, args) = parser.parse_args()
+ //
+ // if not opts.verbose:
+ // zavai.set_quiet()
+ //
+ // # Read configuration
+ // zavai.info("Loading configuration")
+ // conf = zavai.Config()
+ //
+ // # Set up dbus
+ // dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
+ // dbus_system_bus = dbus.SystemBus()
+
+ // Set up zavai
+ zavai.config = new zavai.Config();
+ zavai.registry = new zavai.Registry();
+ zavai.app = new zavai.Zavai();
+
+ zavai.registry.register_resource("zavai", zavai.app);
+
+ zavai.gps.init();
+
+ zavai.registry.register_menu("menu.main", new zavai.Menu("Main menu"));
+
+ // TODO: register the rest of menus here
+ zavai.ui.gps.init();
+ zavai.ui.debug.init();
+
+ zavai.app.show_applet("menu.main");
+
+ // # Register main factories
+ // registry.register(conf, "conf")
+ // registry.register_factory(zavai.GPX, "gpx")
+ // registry.register_factory(zavai.Audio, "audio")
+
+ // # Load plugins
+ // zavai.info("Loading plugins")
+ // for p in zavai.load_plugins(nick="zavai"):
+ // try:
+ // p.init(conf = conf, registry = registry)
+ // except Exception, e:
+ // print >>sys.stderr, "Exception caught loading plugin %s: skipping plugin" % p
+ // print >>sys.stderr, "Exception details:"
+ // import traceback
+ // details = traceback.format_exc()
+ // print >>sys.stderr, "\t"+details.rstrip().replace("\n", "\n\t")
+
+ // # Shutdown the main loop on SIGINT
+ // def on_kill(signum, frame):
+ // gtk.main_quit()
+ // signal.signal(signal.SIGINT, on_kill)
+ // signal.signal(signal.SIGTERM, on_kill)
+
+ // zavai.info("Starting")
+ // app = registry.resource("app")
+ // app.connect("destroy", gtk.main_quit)
+ // app.run()
+
+ zavai.app.run();
+ Gtk.main();
+ //registry.loop.run();
+
+ // zavai.info("Shutting down")
+ zavai.registry.shutdown();
+
+ return 0;
+}
+++ /dev/null
-SOURCES=log.vala config.vala registry.vala gps.vala app.vala app_gps.vala app_debug.vala zavai.vala
-VFLAGS=-g --pkg gee-1.0 --pkg dbus-glib-1 --pkg gtk+-2.0
-LDFLAGS=$(shell pkg-config --libs gee-1.0 glib-2.0 gtk+-2.0)
-
-all: zavai
-
-zavai: $(SOURCES)
- valac -o zavai $(VFLAGS) $^
-
-C: $(SOURCES)
- valac -C $(VFLAGS) $^
-
-#zavai: $(SOURCES:.vala=.vala.o)
-# echo $<
-# gcc $(LDFLAGS) -o zavai $*
-#
-#%.vala.o: %.vala
-# valac $(VFLAGS) -c $<
-
+++ /dev/null
-/*
- * app - zavai main window
- *
- * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-using GLib;
-
-namespace zavai {
-
-public class Zavai : Gtk.Window, zavai.Resource
-{
- zavai.Applet current;
- string current_name;
-
- public Zavai()
- {
- title = "Zavai";
- current = null;
- current_name = null;
- destroy += Gtk.main_quit;
- }
-
- public void show_applet(string name)
- {
- zavai.Applet applet = zavai.registry.geta(name);
-
- // Remove the current applet
- if (current != null)
- {
- current.stop();
- remove(current);
- current = null;
- current_name = null;
- }
-
- // Add the new applet
- current = applet;
- current_name = name;
- add(current);
- current.start();
- current.show_all();
- }
-
- public void push_applet(string name)
- {
-stderr.printf("push applet %s -> %s\n", current_name, name);
- zavai.Applet applet = zavai.registry.geta(name);
-
- // Remove the current applet
- if (current != null)
- {
-stderr.printf("push applet remove %s\n", current_name);
- applet.back_link = current_name;
- current.stop();
- remove(current);
- current = null;
- current_name = null;
- }
-
-stderr.printf("push applet add %s\n", name);
- // Add the new applet
- current = applet;
- current_name = name;
- add(current);
- current.start();
- current.show_all();
- }
-
- public void shutdown()
- {
- }
-
- public void run()
- {
- set_size_request(300, 500);
- //fullscreen();
- show_all();
- }
-}
-/*
-class Zavai(gtk.Window, zavai.Resource):
- def __init__(self, registry, name):
- super(Zavai, self).__init__()
- self.registry = registry
- self.current = None
- self.activate_resource("menu.main")
-
- def activate_resource(self, name):
- widget = self.registry.resource(name)
- if widget is None:
- widget = self.registry.resource("menu.main")
- if isinstance(widget, gtk.Action):
- widget.activate()
- else:
- self.show_widget(name, widget)
-*/
-
-public abstract class Applet : Gtk.VBox, Resource
-{
- // 'label' property: label to show in window title or button names
- protected string _label;
- public string label {
- get { return this._label; }
- set {
- if (_label != value)
- {
- _label = value;
- label_changed();
- }
- }
- }
- public signal void label_changed();
-
- // 'back_link' property: link to use to "go back". If null, do not show
- // a way to go back.
- protected AppletLink _back_link = null;
- public string back_link {
- get { return _back_link.target; }
- set {
-stderr.printf("Set back link of %s to %s\n", _label, value);
- if (value == null && _back_link != null)
- {
- _back_link.target = value;
- remove(_back_link);
- } else if (value != null) {
- if (_back_link.target == null)
- {
- _back_link.target = value;
- pack_end(_back_link, false, false, 0);
- _back_link.show();
- } else
- _back_link.target = value;
- }
- }
- }
-
- public Applet()
- {
- this.homogeneous = false;
- this.spacing = 0;
- _back_link = new AppletStraightLink();
- }
-/*
- name = gobject.property(type=str)
- label = gobject.property(type=str)
-
- def __init__(self, registry, name, label = None):
- super(Applet, self).__init__()
-
- self.zavai_registry = registry
-
- self.props.name = name
- if label is None:
- self.props.label = zavai.default_label(name)
- else:
- self.props.label = label
-
- self.back_link = zavai.LinkButton(registry, zavai.get_parent(name), _("Back"))
- self.pack_end(self.back_link, False, False)
-
- def add(self, widget):
- self.pack_start(widget, True, True)
-*/
-
- public void shutdown()
- {
- stop();
- }
-
- public virtual void start() {}
- public virtual void stop() {}
-}
-
-public class Menu : Applet
-{
- public Menu(string label)
- {
- _label = label;
- }
-
- public void add_applet(string target)
- {
-stderr.printf("menu.add_applet.packpre me %s them %s\n", _label, target);
- pack_start(new AppletPushLink(target), false, false, 0);
-stderr.printf("menu.add_applet.packpost me %s them %s\n", _label, target);
- }
-
- public void add_service_toggle(string service_name, string label_start, string label_stop)
- {
- pack_start(new ServiceRequestLink(service_name, label_start, label_stop), false, false, 0);
- }
-
- public void add_widget(Gtk.Widget w)
- {
- pack_start(w, false, false, 0);
- }
-}
-
-public class BigButton : Gtk.Button
-{
- public BigButton()
- {
- set_size_request(0, zavai.config.min_button_height);
- }
-}
-
-public abstract class AppletLink : BigButton
-{
- protected string _target;
- public string target {
- get { return _target; }
- set
- {
- if (_target != null)
- {
- Applet a = zavai.registry.geta(_target);
- a.label_changed -= on_label_changed;
- }
- bool was_shown = _target != null;
- _target = value;
- if (_target != null)
- {
- Applet a = zavai.registry.geta(_target);
- set_label(a.label);
- a.label_changed += on_label_changed;
- if (!was_shown) show();
- } else {
- if (was_shown) hide();
- }
- }
- }
-
- private void on_label_changed(Applet a)
- {
- set_label(a.label);
- }
-
- private abstract void on_clicked(Gtk.Button src);
-
- public AppletLink(string? name = null)
- {
- _target = null;
- target = name;
-
- clicked += on_clicked;
- }
-}
-
-public class AppletStraightLink : AppletLink
-{
- private override void on_clicked(Gtk.Button src)
- {
-stderr.printf("straight link: %s\n", _target);
- if (_target != null)
- zavai.app.show_applet(_target);
- }
-
- public AppletStraightLink(string? name = null)
- {
- base(name);
- }
-}
-
-public class AppletPushLink : AppletLink
-{
- private override void on_clicked(Gtk.Button src)
- {
-stderr.printf("push link: %s\n", _target);
- if (_target != null)
- zavai.app.push_applet(_target);
- }
-
- public AppletPushLink(string? name = null)
- {
- base(name);
- }
-}
-
-public class ServiceRequestLink : Gtk.ToggleButton
-{
- protected string service_name;
- protected string label_start;
- protected string label_stop;
-
- private void on_toggled(Gtk.Button src)
- {
- Service s = zavai.registry.gets(service_name);
- if (get_active())
- s.request("servicerequestlink");
- else
- s.release("servicerequestlink");
- set_label(get_active() ? label_stop : label_start);
- }
-
- public ServiceRequestLink(string service_name, string label_start, string label_stop)
- {
- this.service_name = service_name;
- this.label_start = label_start;
- this.label_stop = label_stop;
- set_size_request(0, zavai.config.min_button_height);
- toggled += on_toggled;
-
- set_label(get_active() ? label_stop : label_start);
- }
-}
-
-zavai.Zavai app;
-
-}
+++ /dev/null
-/*
- * app_debug - zavai debug menus
- *
- * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-namespace zavai {
-namespace ui {
-namespace debug {
-
-public class Useless : Applet
-{
- public Useless()
- {
- _label = "Useless";
- pack_start(new Gtk.Label("This has no use"), false, false, 0);
- }
-}
-
-public class UselessService : Service
-{
- public UselessService()
- {
- name = "app.debug.useless_service";
- }
-}
-
-public class Quitter : Applet
-{
- public Quitter()
- {
- _label = "Quit";
- }
-
- public override void start()
- {
- Gtk.main_quit();
- }
-}
-
-/*
-class Quitter(gtk.Action):
- def __init__(self, **kw):
- super(Quitter, self).__init__("menu.main.debug.quit", _("Quit"), None, None)
-
- self.connect("activate", gtk.main_quit)
-*/
-
-void init()
-{
- //label_on = "Stop useless service";
- //label_off = "Start useless service";
- // Apps
- var useless = new Useless();
- var quitter = new Quitter();
- var useless_service = new UselessService();
- zavai.registry.register_applet("app.debug.useless", useless);
- zavai.registry.register_service(useless_service);
- zavai.registry.register_applet("app.debug.quit", quitter);
-
- // Menus
- var menu_debug = new zavai.Menu("Debug");
- menu_debug.add_applet("app.debug.useless");
- menu_debug.add_service_toggle("app.debug.useless_service", "Start useless service", "Stop useless service");
- menu_debug.add_applet("app.debug.quit");
-
- zavai.registry.register_menu("menu.debug", menu_debug);
- zavai.registry.getmenu("menu.main").add_applet("menu.debug");
-}
-
-
-}
-}
-}
+++ /dev/null
-/*
- * gpx_trace - zavai GPX trace functions
- *
- * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-namespace zavai {
-namespace ui {
-namespace gps {
-
-/*
-class GPSOn(gtk.ToggleAction):
- states = [_("GPS always on"), _("GPS on when needed")]
-
- def __init__(self, registry, **kw):
- self.state = 0
- super(GPSOn, self).__init__("menu.main.gps.alwayson", self.states[self.state], None, None)
-
- self.registry = registry
- self.set_active(False)
-
- self.connect("toggled", self.on_toggle)
-
- def on_toggle(self, *args):
- self.state = (self.state + 1) % len(self.states)
- self.set_property("label", self.states[self.state])
- if self.get_active():
- self.start()
- else:
- self.stop()
-
- def start(self):
- self.registry.resource("gps").connect("gps", self)
-
- def stop(self):
- self.registry.resource("gps").disconnect("gps", self)
-
-class GPXTracer(gtk.ToggleAction):
- states = [_("Start GPX trace"), _("Stop GPX trace")]
-
- def __init__(self, registry, **kw):
- self.state = 0
- super(GPXTracer, self).__init__("menu.main.gps.gpx", self.states[self.state], None, None)
-
- self.registry = registry
- self.set_active(False)
-
- self.connect("toggled", self.on_toggle)
-
- def on_toggle(self, *args):
- self.state = (self.state + 1) % len(self.states)
- self.set_property("label", self.states[self.state])
- if self.get_active():
- self.start()
- else:
- self.stop()
-
- def start(self):
- zavai.info("GPX trace started")
- self.registry.resource("gpx").connect("gpx", self)
-
- def stop(self):
- zavai.info("GPX trace ended")
- self.registry.resource("gpx").disconnect("gpx", self)
-*/
-
-public class Waypoint : BigButton
-{
- public Waypoint()
- {
- set_label("Take waypoint");
- zavai.gps.gpx.tracking_changed += on_gpx_tracking_changed;
- clicked += on_clicked;
- set_sensitive(zavai.gps.gpx.tracking);
- }
-
- protected void on_gpx_tracking_changed(zavai.gps.GPX gpx, bool new_state)
- {
-stderr.printf("Toggled %d\n", (int)new_state);
- set_sensitive(new_state);
- }
-
- protected void on_clicked()
- {
-stderr.printf("Activate\n");
- zavai.gps.gpx.waypoint();
- }
-}
-
-/*
-class GPXAudioTracer(gtk.ToggleAction):
- states = [_("Start GPX and audio trace"), _("Stop GPX and audio trace")]
-
- def __init__(self, registry, **kw):
- self.state = 0
- super(GPXAudioTracer, self).__init__("menu.main.gps.gpxaudio", self.states[self.state], None, None)
-
- self.registry = registry
- self.recorder = zavai.Recorder(registry)
- self.set_active(False)
-
- self.connect("toggled", self.on_toggle)
-
- def shutdown(self):
- self.recorder.stop()
- super(GPXAudioTracer, self).shutdown()
-
- def on_toggle(self, *args):
- self.state = (self.state + 1) % len(self.states)
- self.set_property("label", self.states[self.state])
- if self.get_active():
- self.start()
- else:
- self.stop()
-
- def start(self):
- zavai.info("GPX trace started")
- gpx = self.registry.resource("gpx")
- gpx.connect("gpx", self)
- gpx.add_activity_monitor(self.on_gpx_activity_changed)
-
- def stop(self):
- zavai.info("GPX trace ended")
- gpx = self.registry.resource("gpx")
- gpx.disconnect("gpx", self)
- self.recorder.stop()
- gpx.del_activity_monitor(self.on_gpx_activity_changed)
-
- def on_gpx_activity_changed(self, gpx, state):
- if state:
- self.recorder.start(gpx.basename + ".wav")
- else:
- self.recorder.stop()
-*/
-
-public class GPSRequestLink : Gtk.ToggleButton
-{
- protected string service_name;
- protected string label_start;
- protected string label_stop;
- protected Gtk.StatusIcon status_icon;
- protected int fix_status = 0;
-
- public GPSRequestLink()
- {
- service_name = "gps";
- label_start = "Keep GPS on";
- label_stop = "Stop keeping GPS on";
- set_size_request(0, zavai.config.min_button_height);
- toggled += on_toggled;
-
- set_label(get_active() ? label_stop : label_start);
-
- //tooltip = "GPS status";
- try {
- fix_status = zavai.gps.gps.device.GetFixStatus();
- } catch (Error e) {
- fix_status = 0;
- }
- zavai.gps.gps.device.FixStatusChanged += on_fix_status_changed;
-
- // GPS status icon
- status_icon = new Gtk.StatusIcon();
- status_icon.set_visible(true);
- status_icon.activate += on_status_activate;
- update_icon();
- }
-
- protected void update_icon()
- {
- string name;
- if (fix_status == 2 || fix_status == 3)
- name = zavai.config.icondir + "/" + (get_active() ? "gps_fix_on.png" : "gps_fix_off.png");
- else
- name = zavai.config.icondir + "/" + (get_active() ? "gps_nofix_on.png" : "gps_nofix_off.png");
-stderr.printf("load icon from %s\n", name);
- status_icon.set_from_file(name);
- }
-
- private void on_fix_status_changed(dynamic DBus.Object pos, int fix_status)
- {
- this.fix_status = fix_status;
- update_icon();
- }
-
- private void on_toggled(Gtk.Button src)
- {
- Service s = zavai.registry.gets(service_name);
- if (get_active())
- s.request("servicerequestlink");
- else
- s.release("servicerequestlink");
- set_label(get_active() ? label_stop : label_start);
- update_icon();
- }
-
- private void on_status_activate()
- {
- set_active(!get_active());
- }
-}
-
-public void init()
-{
- /*
- registry.register(GPXAudioTracer(registry))
- registry.register(GPXWaypoint(registry))
-
- // Apps
- var useless = new Useless();
- zavai.registry.register_applet("app.debug.useless", useless);
- */
- var menu_waypoint = new Waypoint();
- var menu_gpsrequest = new GPSRequestLink();
- //label_on = "Stop GPX trace";
- //label_off = "Start GPX trace";
- //label_on = "Stop GPS monitor";
- //label_off = "Start GPS monitor";
- //label_on = "Stop GPS position tracking";
- //label_off = "Start GPS position tracking";
- //label_on = "Stop keeping GPS on";
- //label_off = "Keep GPS on";
-
- // Menus
- var menu_gps = new zavai.Menu("GPS");
- //menu_gps.add_applet("app.debug.useless");
- menu_gps.add_service_toggle("gps.gpx", "Start GPX trace", "Stop GPX trace");
- menu_gps.add_widget(menu_waypoint);
- menu_gps.add_widget(menu_gpsrequest);
-
- zavai.registry.register_menu("menu.gps", menu_gps);
- zavai.registry.getmenu("menu.main").add_applet("menu.gps");
-}
-
-}
-}
-}
+++ /dev/null
-/*
- * config - zavai configuration
- *
- * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-namespace zavai {
-
-public class Config
-{
- public string version { get; set; }
- public string homedir { get; set; }
- public string icondir { get; set; }
- public int min_button_height { get; set; }
-
- public Config()
- {
- // Set defaults
- version = "0.1";
- homedir = "/root/.zavai";
- icondir = ".";
- min_button_height = 80;
- }
-
-/*
- def _get_homedir(self):
- res = self.get("global", "home")
- if res is None:
- res = os.path.expanduser("~/.zavai")
- if not os.path.isdir(res):
- zavai.info("Creating directory", res)
- os.makedirs(res)
- return res
-*/
-}
-
-/*
-import os
-import ConfigParser, StringIO
-
-def read_config(rootDir = None, defaults = None, nick="octofuss"):
- """
- Read octofuss configuration, returning a ConfigParser object
- """
- if rootDir == None:
- rootDir = os.environ.get(nick.upper() + "_CONFDIR", "/etc/" + nick)
- files = []
- def trytouse(path):
- if os.path.exists(path):
- files.append(path)
-
- # Start with the main config file
- trytouse(os.path.join(rootDir, nick + ".conf"))
-
- # Add snippets found in rc.d style directory
- subdir = os.path.join(rootDir, nick + ".conf.d")
- if os.path.isdir(subdir):
- for file in sorted(os.listdir(subdir)):
- if file.startswith('#'): continue
- if file.startswith('.'): continue
- if file.endswith('~'): continue
- if file.endswith('.bak'): continue
- trytouse(os.path.join(subdir, file))
-
- config = ConfigParser.ConfigParser()
- if defaults != None:
- infile = StringIO.StringIO(defaults)
- config.readfp(infile, "defaults")
- config.read(files)
- return config
-import os.path
-import zavai
-
-class Config:
- def __init__(self):
- self.conf = zavai.read_config(nick="zavai")
-
- def get(self, section, name, default=None):
- if self.conf.has_section(section):
- if self.conf.has_option(section, name):
- return self.conf.get(section, name)
- return None
-
- homedir = property(_get_homedir)
-*/
-
-Config config = null;
-
-}
+++ /dev/null
-/*
- * gps - gps resource for zavai
- *
- * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-using GLib;
-
-namespace zavai {
-namespace gps {
-
-// For a list of dbus services, look in /etc/dbus-1/system.d/
-public class GPS: zavai.Service
-{
- public dynamic DBus.Object usage;
- public dynamic DBus.Object device;
-
- public GPS()
- {
- name = "gps";
-
- // see mdbus -s org.freesmartphone.ousaged /org/freesmartphone/Usage
- usage = zavai.registry.sbus.get_object(
- "org.freesmartphone.ousaged",
- "/org/freesmartphone/Usage",
- "org.freesmartphone.Usage");
-
- device = zavai.registry.sbus.get_object(
- "org.freesmartphone.ogpsd",
- "/org/freedesktop/Gypsy",
- "org.freedesktop.Gypsy.Device");
-
-// # see mdbus -s org.freesmartphone.ogpsd /org/freedesktop/Gypsy
-// gps = self.bus.get_object('org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
-// self.gps = dbus.Interface(gps, "org.freedesktop.Gypsy.Device")
-// self.gps_time = dbus.Interface(gps, "org.freedesktop.Gypsy.Time")
-// self.gps_position = dbus.Interface(gps, 'org.freedesktop.Gypsy.Position')
-// self.gps_ubx = dbus.Interface(gps, 'org.freesmartphone.GPS.UBX')
- usage.ResourceChanged += on_resourcechanged;
- }
-
- public void on_resourcechanged(dynamic DBus.Object pos, string name, bool state, HashTable<string, Value?> attributes)
- {
- zavai.log.info("RESOURCE CHANGED " + name);
- }
-
- /// Request GPS resource
- public override void start()
- {
- if (started) return;
- try {
- usage.RequestResource("GPS");
- zavai.log.info("Acquired GPS");
- base.start();
- } catch (GLib.Error e) {
- zavai.log.error(e.message);
- }
- base.start();
- }
-
- // Release usage of GPS
- public override void stop()
- {
- if (!started) return;
- try {
- usage.ReleaseResource("GPS");
- zavai.log.info("Released GPS");
- base.stop();
- } catch (GLib.Error e) {
- zavai.log.error(e.message);
- }
- base.stop();
- }
-}
-
-public class Monitor : zavai.Service
-{
- static const int NAV_STATUS=0;
- static const int NAV_SVINFO=1;
- static const int NAV_MAX=2;
-
- dynamic DBus.Object ubx;
- dynamic DBus.Object time;
- /*
- string[] filters = { "NAV-STATUS", "NAV_SVINFO" };
-
- int debug_busy;
- int debug_want;
- int debug_have;
- int debug_error;
- */
-
-
- public Monitor()
- {
- name = "gps.monitor";
-
- ubx = zavai.registry.sbus.get_object(
- "org.freesmartphone.ogpsd",
- "/org/freedesktop/Gypsy",
- "org.freesmartphone.GPS.UBX");
- time = zavai.registry.sbus.get_object(
- "org.freesmartphone.ogpsd",
- "/org/freedesktop/Gypsy",
- "org.freedesktop.Gypsy.Time");
-
- zavai.log.info("SETSIG1");
- time.TimeChanged += timechanged;
- zavai.log.info("SETSIG2");
-
- zavai.log.info("DEBUG1");
- ubx.DebugPacket += on_ubxdebug_packet;
- zavai.log.info("DEBUG2");
-
-/*
- // This piece of machinery is taken from Zhone
- debug_busy = -1;
- debug_want = (1 << NAV_STATUS) | (1 << NAV_SVINFO);
- debug_have = 0;
- debug_error = 0;
-*/
- }
-
- protected void timechanged(dynamic DBus.Object pos, int t)
- {
- zavai.log.info("TIMECHANGED");
- }
-
-/*
- protected void debug_update() throws GLib.Error
- {
- zavai.log.debug("UPDATE");
- if (debug_busy != -1)
- return;
- zavai.log.debug("UPD1");
- int pending = debug_want & (~debug_have) & (~debug_error);
- if (pending == 0)
- return;
- zavai.log.debug("UPD2");
- for (int i = 0; i < NAV_MAX; ++i)
- if ((pending & (1<<i)) != 0)
- {
- debug_busy = i;
- break;
- }
- zavai.log.debug("UPD3 " + filters[debug_busy]);
-
- ubx.SetDebugFilter(
- filters[debug_busy],
- true,
- on_debug_reply
-// on_debug_error
- );
- zavai.log.debug("UPD4");
- }
-
- protected void debug_request() throws GLib.Error
- {
- debug_have = 0;
- debug_update();
- }
-
- protected void on_debug_reply() throws GLib.Error
- {
- debug_have |= (1<<debug_busy);
- debug_busy = -1;
- debug_update();
- }
-
- protected void on_debug_error(string e) throws GLib.Error
- {
- string name = debug_busy == -1 ? "none" : filters[debug_busy];
- zavai.log.error("error while requesting debug packet " + name + ": " + e);
- debug_error |= (1<<debug_busy);
- debug_busy = -1;
- debug_update();
- }
-*/
-
- /*
- protected void on_satellites_changed(satellites)
- {
-// zavai.info("gps monitor: satellites changed")
-// self.debug_request()
- }
- */
-
- protected void on_ubxdebug_packet(dynamic DBus.Object ubx, string clid, int length,
- HashTable<string, Value?>[] data)
- {
- zavai.log.info("gps monitor: UBX debug packet");
- message("ZAZA %s %d", clid, length);
- message("ZAZA %u %lu", data.length, sizeof(HashTable<string, Value?>));
- message("ZAZA %p %p", (void*)data.length, this);
- message("ZAZA %p", data[0]);
- message("ZAZA %p", data[1]);
- message("ZAZA %p", data[2]);
- /*
- message("ZAZA %u", data[0].size());
- foreach (string k in data[0].get_keys())
- message("ZAZA %s", k);
- */
- PtrArray< HashTable<string, Value?> >* prova = (PtrArray< HashTable<string, Value?> >)data;
- message("ZAZA %u", prova->len);
- /*
- foreach (string k in prova[0].get_keys())
- message("ZAZA %s", k);
- */
- /*
- for (int i = 0; data[i] != null; ++i)
- {
- zavai.log.info("ZAZA");
- }
- */
- //message("Size: %d", data.size());
-// self.notify("satellites", clid, length, data)
- }
-
- protected override void start()
- {
- if (started) return;
-
- zavai.log.info("Starting GPS Monitor");
- gps.request("gps.monitor");
-// # TODO: find out how come sometimes these events are not sent
-// self.gps.bus.add_signal_receiver(
-// self.on_satellites_changed, 'SatellitesChanged', 'org.freedesktop.Gypsy.Satellite',
-// 'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
- //ubx.DebugPacket += prova;
- //try {
- //ubx.SetDebugFilter("NAV-STATUS", true);
- //ubx.SetDebugFilter("NAV-SVINFO", true);
- //debug_request();
- base.start();
- //} catch (GLib.Error e) {
- //zavai.log.error(e.message);
- //}
- }
-
- protected override void stop()
- {
- if (!started) return;
- zavai.log.info("Stopping GPS Monitor");
-// self.gps.bus.remove_signal_receiver(
-// self.on_satellites_changed, 'SatellitesChanged', 'org.freedesktop.Gypsy.Satellite',
-// 'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
- try {
- ubx.SetDebugFilter("NAV-STATUS", false);
- ubx.SetDebugFilter("NAV-SVINFO", false);
- } catch (GLib.Error e) {
- zavai.log.error(e.message);
- }
- ubx.DebugPacket -= on_ubxdebug_packet;
- //ubx.DebugPacket -= prova;
- gps.release("gps.monitor");
- base.stop();
- }
-}
-
-
-public class Position : zavai.Service
-{
- dynamic DBus.Object position;
-
- public signal void position_changed(int fields, int tstamp, double lat, double lon, double alt);
-
- public Position()
- {
- name = "gps.position";
- position = zavai.registry.sbus.get_object(
- "org.freesmartphone.ogpsd",
- "/org/freedesktop/Gypsy",
- "org.freedesktop.Gypsy.Position");
- }
-
- public void on_position_changed(dynamic DBus.Object pos, int fields, int tstamp, double lat, double lon, double alt)
- {
- zavai.log.info("gps position: position changed");
- position_changed(fields, tstamp, lat, lon, alt);
- }
-
- public override void start()
- {
- if (started) return;
- zavai.log.info("Starting GPS position tracking");
- gps.request("gps.position");
- position.PositionChanged += on_position_changed;
- base.start();
- }
-
- public override void stop()
- {
- if (!started) return;
- zavai.log.info("Stopping GPS position tracking");
- position.PositionChanged -= on_position_changed;
- gps.release("gps.position");
- base.stop();
- }
-}
-
-// # def wait_for_fix(self, callback):
-// # status = self.gps.GetFixStatus()
-// # if status in [2, 3]:
-// # zavai.info("We already have a fix, good.")
-// # callback()
-// # return True
-// # else:
-// # zavai.info("Waiting for a fix...")
-// # self.waiting_for_fix = callback
-// # self.bus.add_signal_receiver(
-// # self.on_fix_status_changed, 'FixStatusChanged', 'org.freedesktop.Gypsy.Device',
-// # 'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
-// # return False
-// #
-// # def on_fix_status_changed(self, status):
-// # if status not in [2, 3]: return
-// #
-// # zavai.info("Got GPS fix")
-// # self.bus.remove_signal_receiver(
-// # self.on_fix_status_changed, 'FixStatusChanged', 'org.freedesktop.Gypsy.Device',
-// # 'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
-// #
-// # if self.waiting_for_fix:
-// # self.waiting_for_fix()
-// # self.waiting_for_fix = None
-// #
-//
-// # def start_recording(self):
-// # if self.gps_monitor:
-// # self.gps_monitor.stop()
-// # self.gps_monitor = None
-// #
-// # if not self.audio:
-// # return
-// #
-// # # Sync system time
-// # gpstime = self.gps.gps_time.GetTime()
-// # subprocess.call(["date", "-s", "@%d" % gpstime])
-// # subprocess.call(["hwclock", "--systohc"])
-// #
-// # # Compute basename for output files
-// # self.basename = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(gpstime))
-// # self.basename = os.path.join(AUDIODIR, self.basename)
-// #
-// # # Start recording the GPX track
-// # self.gpx = GPX(self.basename)
-// # self.gps.track_position(self.on_position_changed)
-// #
-// # # Start recording in background forking arecord
-// # self.audio.set_basename(self.basename)
-// # self.audio.start_recording()
-// #
-
-// Write GPX track and waypoint files
-public class GPX : Service
-{
- public bool tracking {
- get { return trk != null; }
- set {}
- }
- public signal void tracking_changed(bool tracking);
-
- FileStream trk = null;
- FileStream wpt = null;
- int wpt_seq = 1;
- bool last_valid = false;
- int last_fields;
- time_t last_tstamp;
- double last_lat;
- double last_lon;
- double last_alt;
-
- public GPX()
- {
- name = "gps.gpx";
- }
-
- public override void start()
- {
- if (!started)
- {
- log.info("Starting GPX trace subsystem");
- position.request("gps.gpx");
- position.position_changed += on_position_changed;
- base.start();
- }
- }
-
- public override void stop()
- {
- if (started)
- {
- log.info("Stopping GPX trace subsystem");
- position.release("gps.gpx");
- position.position_changed -= on_position_changed;
- stop_track();
- base.stop();
- }
- }
-
- public void on_position_changed(Position pos, int fields, int tstamp, double lat, double lon, double alt)
- {
- last_fields = fields;
- last_tstamp = tstamp;
- last_lat = lat;
- last_lon = lon;
- last_alt = alt;
- last_valid = true;
- trackpoint();
- }
-
- public void start_track(time_t tstamp = 0, string? basename = null)
- {
- string fname;
- if (basename != null)
- fname = basename;
- else
- {
- time_t now = tstamp == 0 ? time_t() : tstamp;
-
- // Compute basename for output files
- var t = Time.local(now);
- char[] res = new char[25];
- t.strftime(res, "%Y-%m-%d-%H-%M-%S");
- fname = zavai.config.homedir + "/" + (string)res;
- }
-
- trk = FileStream.open(fname + "-trk.gpx", "wt");
- trk.puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
- trk.puts(" <gpx");
- trk.puts(" version=\"1.0\"");
- trk.printf(" creator=\"zavai %s\"\n", zavai.config.version);
- trk.puts(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
- trk.puts(" xmlns=\"http://www.topografix.com/GPX/1/0\"");
- trk.puts(" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">");
- trk.puts(" <trk>");
- trk.puts(" <trkseg>");
-
- wpt = FileStream.open(fname + "-wpt.gpx", "wt");
- wpt.puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
- wpt.puts(" <gpx");
- wpt.puts(" version=\"1.0\"");
- wpt.printf(" creator=\"zavai %s\"", zavai.config.version);
- wpt.puts(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
- wpt.puts(" xmlns=\"http://www.topografix.com/GPX/1/0\"");
- wpt.puts(" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">");
-
- wpt_seq = 1;
- tracking_changed(true);
- }
-
- public void stop_track()
- {
- if (trk != null)
- {
- trk.puts("</trkseg></trk></gpx>");
- trk.flush();
- trk = null;
- }
- if (wpt != null)
- {
- wpt.puts("</gpx>");
- wpt.flush();
- wpt = null;
- }
- last_valid = false;
- tracking_changed(false);
- }
-
- // Mark a track point
- public void trackpoint()
- {
- if (!last_valid) return;
- if (trk == null)
- start_track(last_tstamp);
-
- trk.printf("<trkpt lat=\"%f\" lon=\"%f\">\n", last_lat, last_lon);
- var t = Time.local(last_tstamp);
- char[] ts = new char[25];
- t.strftime(ts, "%Y-%m-%dT%H:%M:%SZ");
- trk.printf(" <time>%s</time>\n", (string)ts);
- trk.printf(" <ele>%f</ele>\n", last_alt);
- // if course is not None: print >>self.trk, " <course>%f</course>" % course
- // if speed is not None: print >>self.trk, " <speed>%f</speed>" % speed
- // if fix is not None: print >>self.trk, " <fix>%f</fix>" % fix
- // if hdop is not None: print >>self.trk, " <hdop>%f</hdop>" % hdop
- trk.puts("</trkpt>");
- }
-
- // Mark a waypoint
- public void waypoint(string? name = null)
- {
- if (!last_valid) return;
- if (wpt == null)
- start_track(last_tstamp);
-
- string wptname;
- if (name == null)
- {
- wptname = "wpt_%d".printf(wpt_seq);
- wpt_seq += 1;
- } else {
- wptname = name;
- }
-
- wpt.printf("<wpt lat=\"%f\" lon=\"%f\">\n", last_lat, last_lon);
- wpt.printf(" <name>%s</name>\n", wptname);
- var t = Time.local(last_tstamp);
- char[] ts = new char[25];
- t.strftime(ts, "%Y-%m-%dT%H:%M:%SZ");
- wpt.printf(" <time>%s</time>\n", (string)ts);
- wpt.printf(" <ele>%f</ele>\n", last_alt);
- wpt.puts("</wpt>");
- }
-}
-
-// # def record(self):
-// # self.audio = Audio(self.make_waypoint)
-// # self.gps = GPS()
-// # # Get a fix and start recording
-// # if not self.gps.wait_for_fix(self.start_recording):
-// # self.gps_monitor = GPSMonitor(self.gps)
-// # self.gps_monitor.start()
-// #
-// # def monitor(self):
-// # self.audio = None
-// # self.gps = GPS()
-// # self.gps_monitor = GPSMonitor(self.gps)
-// # self.gps_monitor.start()
-// #
-// #
-// # def make_waypoint(self):
-// # if self.gpx is None:
-// # return
-// # if self.last_pos is None:
-// # self.last_pos = self.gps.gps_position.GetPosition()
-// # (fields, tstamp, lat, lon, alt) = self.last_pos
-// # self.gpx.waypoint(tstamp, lat, lon, alt)
-// # zavai.info("Making waypoint at %s: %f, %f, %f" % (
-// # time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(tstamp)), lat, lon, alt))
-
-public zavai.gps.GPS gps = null;
-public zavai.gps.Monitor monitor = null;
-public zavai.gps.Position position = null;
-public zavai.gps.GPX gpx = null;
-
-public void init()
-{
- gps = new GPS();
- monitor = new Monitor();
- position = new Position();
- gpx = new GPX();
-
- zavai.registry.register_service(gps);
- zavai.registry.register_service(position);
- zavai.registry.register_service(monitor);
- zavai.registry.register_service(gpx);
-}
-
-}
-}
+++ /dev/null
-/*
- * log - logging functions
- *
- * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-namespace zavai {
-namespace log {
-
-public void error(string s)
-{
- stderr.printf("%s\n", s);
-}
-public void warning(string s)
-{
- stderr.printf("%s\n", s);
-}
-public void info(string s)
-{
- stderr.printf("%s\n", s);
-}
-public void debug(string s)
-{
- stderr.printf("%s\n", s);
-}
-
-}
-}
+++ /dev/null
-/*
- * registry - zavai resource registry
- *
- * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-using GLib;
-using Gee;
-
-namespace zavai {
-
-public interface Resource : Object {
- /**
- * Shut down this resource.
- *
- * Normally one does nothing here, but it is important to give resources a
- * chance to do cleanup when the program quits.
- *
- * This can be used for tasks like closing the tags on a GPX track,
- * releasing a FSO resource, restoring mixer settings and so on.
- */
- public abstract void shutdown();
-}
-
-public abstract class Service : Object, Resource {
- public string name { get; construct; }
-
- bool _started;
- public bool started {
- get { return _started; }
- set { _started = value; }
- default = false;
- }
-
- public signal void toggled(bool new_state);
-
- protected HashMap<string, int> requests;
-
- construct {
- requests = new HashMap<string, int>(str_hash, str_equal);
- }
-
- public void shutdown()
- {
- stop();
- }
-
- /// Activate the service
- protected virtual void start()
- {
- if (!started)
- {
-stderr.printf("SERVICE %s started\n", name);
- started = true;
- toggled(started);
- }
- }
-
- /// Deactivate the service
- protected virtual void stop()
- {
- if (started)
- {
-stderr.printf("SERVICE %s stopped\n", name);
- started = false;
- toggled(started);
- }
- }
-
- /**
- Request a resource using the given ID.
- *
- * If it is the first time the resource is requested, start it and
- * return true. Else, take note of the request and return false.
- *
- * If a resource is requested multiple times with the same ID, it will
- * need to be released multiple times with that ID.
- */
- public bool request(string id)
- {
- bool res = (requests.size == 0);
- if (id in requests)
- requests[id] = requests[id] + 1;
- else
- requests.set(id, 1);
- if (res) start();
- return res;
- }
-
- /**
- * Release a resource using the given ID.
- *
- * If after the call nothing is requesting the resource, stop it and
- * return true. Else, take note of the release and return false.
- *
- * If a resource is requested multiple times with the same ID, it will
- * need to be released multiple times with that ID.
- */
- public bool release(string id)
- {
- if (id in requests)
- {
- if (requests[id] > 1)
- requests[id] = requests[id] - 1;
- else
- requests.remove(id);
- } else {
- return false;
- }
- if (requests.size > 0)
- return false;
- stop();
- return true;
- }
-}
-
-// class Service(Resource):
-// "Service that is activated only when someone is listening"
-// def __init__(self, types = []):
-// """
-// Initialise a service that can emit signals for the given event types
-// """
-// super(Service, self).__init__()
-// self.callbacks = dict()
-// for t in types:
-// self.callbacks[t] = set()
-// self.started = False
-//
-// def notify(self, type, *args, **kw):
-// "Call all callbacks with the given parameters"
-// for cb in self.callbacks[type]:
-// cb(*args, **kw)
-//
-// def has_callbacks(self):
-// for i in self.callbacks.values():
-// if i: return True
-// return False
-//
-// def connect(self, type, callback):
-// "Connect a callback to this resource, activating it if needed"
-// do_start = not self.has_callbacks()
-// self.callbacks[type].add(callback)
-// if do_start:
-// self.start()
-// self.started = True
-//
-// def disconnect(self, type, callback):
-// "Disconnect a callback to this resource, activating it if needed"
-// if not self.has_callbacks(): return
-// self.callbacks[type].discard(callback)
-// if not self.has_callbacks():
-// self.stop()
-// self.started = False
-
-
-// import zavai
-// import gtk
-//
-// def get_parent(s):
-// "Get the parent name for s"
-// pos = s.rfind(".")
-// if pos == -1: return None
-// res = s[:pos]
-// if res == "menu": return None
-// return res
-//
-// def default_label(s):
-// "Compute a default label given the last element of a path"
-// pos = s.rfind(".")
-// if pos == -1: return s.capitalize()
-// return s[pos+1:].capitalize()
-
-public class Registry : Object, Resource
-{
- HashMap<string, Resource> memb_resources;
- HashMap<string, Service> memb_services;
- HashMap<string, Applet> memb_applets;
- HashMap<string, Menu> memb_menus;
- protected ArrayList<Resource> registration_order;
- public DBus.Connection sbus;
-
- public Registry()
- {
- memb_resources = new HashMap<string, Resource>(str_hash, str_equal);
- memb_services = new HashMap<string, Service>(str_hash, str_equal);
- memb_applets = new HashMap<string, Applet>(str_hash, str_equal);
- memb_menus = new HashMap<string, Menu>(str_hash, str_equal);
- registration_order = new ArrayList<Resource>();
- sbus = DBus.Bus.get(DBus.BusType.SYSTEM);
- }
-
- public void shutdown()
- {
- // Shutdown in reverse registration order
- for (int i = registration_order.size - 1; i >= 0; --i)
- registration_order[i].shutdown();
- }
-
- public void register_resource(string name, Resource obj)
- {
- memb_resources[name] = obj;
- registration_order.add(obj);
- }
-
- public void register_service(Service obj)
- {
- memb_services[obj.name] = obj;
- registration_order.add(obj);
- }
-
- public void register_applet(string name, Applet obj)
- {
- memb_applets[name] = obj;
- registration_order.add(obj);
- }
-
- public void register_menu(string name, Menu obj)
- {
- memb_applets[name] = obj;
- memb_menus[name] = obj;
- registration_order.add(obj);
- }
-
- public Resource? getr(string name)
- {
- if (name in memb_resources)
- return memb_resources[name];
- else
- {
- log.error("getr: no resource found: " + name);
- return null;
- }
- }
-
- public Service? gets(string name)
- {
- if (name in memb_services)
- return memb_services[name];
- else
- {
- log.error("gets: no service found: " + name);
- return null;
- }
- }
-
- public Applet? geta(string name)
- {
- if (name in memb_applets)
- return memb_applets[name];
- else
- {
- log.error("geta: no applet found: " + name);
- return null;
- }
- }
-
- public Menu? getmenu(string name)
- {
- if (name in memb_menus)
- return memb_menus[name];
- else
- {
- log.error("getmenu: no menu found: " + name);
- return null;
- }
- }
-}
-
-// class Registry(object):
-// """Collection of resources.
-//
-// Various factories can be registered by name on the registry. Then when an
-// object is requested for the first time, it is created using the factory.
-// When it is requested again, the existing object is reused.
-// """
-//
-// def __init__(self):
-// self.factories = dict()
-// self.objects = dict()
-// self.labels = dict()
-//
-// def register(self, obj, name=None):
-// """Register an object at the given path.
-//
-// Name the path to this object, like "menu.gps.monitor".
-// """
-// if name is None:
-// name = obj.props.name
-//
-// if name in self.objects:
-// return KeyError("%s is already registered", name)
-// zavai.info("Registering", name)
-// self.objects[name] = obj
-//
-// if name.startswith("menu."):
-// self.add_to_menu(name)
-//
-// def register_factory(self, fac, name, label = None):
-// """Register an object factory at the given path.
-//
-// Name the path to this object, like "menu.gps.monitor".
-// """
-// if name in self.factories:
-// return KeyError("Factory %s is already registered", name)
-// zavai.info("Registering factory", name)
-// self.factories[name] = fac
-// if label is not None: self.labels[name] = label
-//
-// def add_to_menu(self, name):
-// "Add the applet with the given name to the menu structure"
-// parent = get_parent(name)
-// if parent is not None:
-// zavai.info("Add to menu", name, parent)
-// menu = self.menu(parent)
-//
-// obj = self.resource(name)
-// if isinstance(obj, gtk.ToggleAction):
-// menu.add_child(zavai.ToggleButton(self, name, action=obj))
-// elif isinstance(obj, gtk.Action):
-// menu.add_child(zavai.LinkButton(self, name, action=obj))
-// else:
-// menu.add_child(zavai.LinkButton(self, name, self.label(name)))
-//
-// def label(self, name):
-// "Return the label for the object with the given name"
-// res = self.labels.get(name)
-// if res is not None:
-// return res
-// try:
-// obj = self.resource(name)
-// return obj.props.label
-// except:
-// return default_label(name)
-//
-// def resource(self, name):
-// """Get a resource from the registry.
-//
-// If no resource exists at `name` but there is a factory, instantiate the
-// object using the factory.
-//
-// If not even a factory exists at `name`, returns None.
-// """
-// res = self.objects.get(name, None)
-// if res is None:
-// fac = self.factories.get(name, None)
-// if fac is not None:
-// res = self.objects[name] = fac(self, name)
-// return res
-//
-// def menu(self, name):
-// """Get a menu resource, automatically creating it if it is missing.
-//
-// Menus are created automatically linked to a parent menu, according to
-// the hierarchy in `name`.
-// """
-// res = self.resource(name)
-// if res is None:
-// # Check if it is a toplevel menu
-// if name.startswith("menu."):
-// parent = get_parent(name[5:])
-// if parent is not None:
-// parent = "menu." + parent
-// else:
-// parent = get_parent(name)
-//
-// res = zavai.Menu(self, name, parent)
-// self.register(res, name)
-// return res
-//
-// def shutdown(self):
-// """Shut down all objects in this Registry.
-//
-// After shutting down, all objects cannot be used anymore"""
-// for o in self.objects.itervalues():
-// if isinstance(o, Resource):
-// o.shutdown()
-// self.objects.clear()
-//
-
-zavai.Registry registry;
-
-}
-
+++ /dev/null
-/*
- * zavai - simple interface to the OpenMoko (or to the FSO stack)
- *
- * Copyright (C) 2009 Enrico Zini <enrico@enricozini.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-using GLib;
-
-//string VERSION = "0.1";
-
-static int main (string[] args) {
- Gtk.init (ref args);
-
- // parser = Parser(usage="usage: %prog [options]",
- // version="%prog "+ VERSION,
- // description="Simple interactive interface for the OpenMoko")
- // parser.add_option("-v", "--verbose", action="store_true", help="verbose mode")
- //
- // (opts, args) = parser.parse_args()
- //
- // if not opts.verbose:
- // zavai.set_quiet()
- //
- // # Read configuration
- // zavai.info("Loading configuration")
- // conf = zavai.Config()
- //
- // # Set up dbus
- // dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
- // dbus_system_bus = dbus.SystemBus()
-
- // Set up zavai
- zavai.config = new zavai.Config();
- zavai.registry = new zavai.Registry();
- zavai.app = new zavai.Zavai();
-
- zavai.registry.register_resource("zavai", zavai.app);
-
- zavai.gps.init();
-
- zavai.registry.register_menu("menu.main", new zavai.Menu("Main menu"));
-
- // TODO: register the rest of menus here
- zavai.ui.gps.init();
- zavai.ui.debug.init();
-
- zavai.app.show_applet("menu.main");
-
- // # Register main factories
- // registry.register(conf, "conf")
- // registry.register_factory(zavai.GPX, "gpx")
- // registry.register_factory(zavai.Audio, "audio")
-
- // # Load plugins
- // zavai.info("Loading plugins")
- // for p in zavai.load_plugins(nick="zavai"):
- // try:
- // p.init(conf = conf, registry = registry)
- // except Exception, e:
- // print >>sys.stderr, "Exception caught loading plugin %s: skipping plugin" % p
- // print >>sys.stderr, "Exception details:"
- // import traceback
- // details = traceback.format_exc()
- // print >>sys.stderr, "\t"+details.rstrip().replace("\n", "\n\t")
-
- // # Shutdown the main loop on SIGINT
- // def on_kill(signum, frame):
- // gtk.main_quit()
- // signal.signal(signal.SIGINT, on_kill)
- // signal.signal(signal.SIGTERM, on_kill)
-
- // zavai.info("Starting")
- // app = registry.resource("app")
- // app.connect("destroy", gtk.main_quit)
- // app.run()
-
- zavai.app.run();
- Gtk.main();
- //registry.loop.run();
-
- // zavai.info("Shutting down")
- zavai.registry.shutdown();
-
- return 0;
-}