Started porting to Vala
authorEnrico Zini <enrico@enricozini.org>
Tue, 14 Jul 2009 14:28:05 +0000 (15:28 +0100)
committerEnrico Zini <enrico@enricozini.org>
Tue, 14 Jul 2009 14:28:05 +0000 (15:28 +0100)
vala/Makefile [new file with mode: 0644]
vala/registry.vala [new file with mode: 0644]
vala/zavai.vala [new file with mode: 0644]

diff --git a/vala/Makefile b/vala/Makefile
new file mode 100644 (file)
index 0000000..326e644
--- /dev/null
@@ -0,0 +1,16 @@
+SOURCES=registry.vala zavai.vala
+VFLAGS=--pkg gee-1.0
+LDFLAGS=$(shell pkg-config --libs gee-1.0 glib-2.0)
+
+all: zavai
+
+zavai: $(SOURCES)
+       valac -o zavai $(VFLAGS) $^
+
+#zavai: $(SOURCES:.vala=.vala.o)
+#      echo $<
+#      gcc $(LDFLAGS) -o zavai $*
+#
+#%.vala.o: %.vala
+#      valac $(VFLAGS) -c $<
+
diff --git a/vala/registry.vala b/vala/registry.vala
new file mode 100644 (file)
index 0000000..c3f337a
--- /dev/null
@@ -0,0 +1,271 @@
+/* 
+ * 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 abstract class 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 virtual void shutdown()
+       {
+       }
+}
+
+public abstract class Service : Resource {
+       protected bool is_started = false;
+
+       public signal void started();
+       public signal void stopped();
+
+       public override void shutdown()
+       {
+               if (is_started)
+                       stop();
+       }
+
+       /// Activate the service
+       public virtual void start()
+       {
+               is_started = true;
+               started();
+       }
+
+       /// Deactivate the service
+       public virtual void stop()
+       {
+               is_started = false;
+               stopped();
+       }
+}
+
+// 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 : Resource
+{
+       HashMap<string, Resource> members;
+
+       construct {
+               members = new HashMap<string, Resource>();
+       }
+
+       public override void shutdown()
+       {
+               foreach (Resource r in members.get_values())
+                       r.shutdown();
+       }
+
+       public void register(string name, Resource obj)
+       {
+               members[name] = obj;
+       }
+
+       public Object? geto(string name)
+       {
+               if (name in members)
+                       return members[name];
+               else
+                       return null;
+       }
+
+       public Service? gets(string name)
+       {
+               if (name in members)
+                       return (Service)members[name];
+               else
+                       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()
+// 
+}
+
diff --git a/vala/zavai.vala b/vala/zavai.vala
new file mode 100644 (file)
index 0000000..4361704
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * 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) {
+       // 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.Registry registry = new 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();
+
+       return 0;
+}