import zavai 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() def resource(self, name): """Get a resource, instantiating it if it has not been done yet. First it tries to use the factory registered with `name` itself. If it fails, it tries to use the factory registered one level above (using the dot '.' as a separator). If no suitable factory has been found, returns None. """ res = self.objects.get(name, None) if res is None: fac = self.factories.get(name, None) if fac is None: root = name while True: pos = root.rfind(".") if pos == -1: break root = root[:pos] fac = self.factories.get(root, None) if fac is None: return None res = fac(self, name) if res is not None: self.objects[name] = res return res def menu(self, name): """Get a menu resource, instantiating it if it has not been done yet. All menu resources share the same factory, which builds zavai.Menu objects. """ return self.resource("menu." + name) def menu_link(self, name, label): """Return a MenuLink to the menu with the given name """ return zavai.MenuLink(self, name, label) def get_existing(self, name): """Get a menu resource, but only if it has been already instantiated. If the resource has not been instantiated yet, returns None. """ return self.objects.get(name, None) def register(self, name, factory): """Register a factory for this registry. Name is a name for this factory, like "menu.gps.monitor". Factory is a function that creates a Resource object. The function will be passed the Registry itself as the only parameter""" if name in self.factories: return KeyError("% is already registered as a factory", name) self.factories[name] = factory 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(): o.shutdown() self.objects.clear() class Resource(object): def __init__(self, registry, name, *args, **kw): """The default constructor does nothing, but is there to eat the parameters passed by Registry in case subclassers do not need a constructor""" pass def shutdown(self): """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. """ pass