def get_title_from_context(context): title = None if IAlchemistContent.providedBy(context): if IDCDescriptiveProperties.providedBy(context): title = context.title else: props = IDCDescriptiveProperties(context, None) if props is not None: title = props.title else: title = context.short_name elif IAlchemistContainer.providedBy(context): domain_model = context._class try: descriptor = queryModelDescriptor(domain_model) except: descriptor = None name = "" if descriptor: name = getattr(descriptor, 'container_name', None) if name is None: name = getattr(descriptor, 'display_name', None) if not name: name = getattr(context, '__name__', None) title = name elif ILocation.providedBy(context) and \ IDCDescriptiveProperties.providedBy(context): title = context.title return title
def update(self): """ Update the viewlet manager for rendering. This method is part of the protocol of a content provider, called before :meth:`render`. This implementation will use it to: 1. Find the total set of available viewlets by querying for viewlet adapters. 2. Filter the total set down to the active set by using :meth:`filter`. 3. Sort the active set using :meth:`sort`. 4. Provide viewlets that implement :class:`~zope.location.interfaces.ILocation` with a name. 5. Set :attr:`viewlets` to the found set of active viewlets. 6. Fire :class:`.BeforeUpdateEvent` for each active viewlet before calling ``update()`` on it. .. seealso:: :class:`zope.contentprovider.interfaces.IContentProvider` """ self.__updated = True # Find all content providers for the region viewlets = zope.component.getAdapters( (self.context, self.request, self.__parent__, self), interfaces.IViewlet) viewlets = self.filter(viewlets) viewlets = self.sort(viewlets) # Just use the viewlets from now on self.viewlets = [] for name, viewlet in viewlets: if ILocation.providedBy(viewlet): viewlet.__name__ = name self.viewlets.append(viewlet) self._updateViewlets()
def _get_title_from_context(context): title = None if IAlchemistContent.providedBy(context): if IDCDescriptiveProperties.providedBy(context): title = context.title else: props = IDCDescriptiveProperties(context, None) if props is not None: title = props.title else: ''' !+ AttributeError: 'GroupAddress' object has no attribute 'short_name': File "/home/undesa/bungeni/cap_installs/bungeni_install/bungeni/releases/20100305100101/src/bungeni.main/bungeni/ui/viewlets/navigation.py", line 59, in _get_title_from_context #title = context.short_name So, we temporarily default the above to the context.__class__.__name__: ''' title = getattr(context, "short_name", context.__class__.__name__) elif IAlchemistContainer.providedBy(context): domain_model = context._class try: descriptor = queryModelDescriptor(domain_model) except: descriptor = None name = "" if descriptor: name = getattr(descriptor, 'container_name', None) if name is None: name = getattr(descriptor, 'display_name', None) if not name: name = getattr(context, '__name__', None) title = name elif ILocation.providedBy(context) and \ IDCDescriptiveProperties.providedBy(context): title = context.title return title
def render_content_provider(econtext, name): name = name.strip() context = econtext.get("context") request = econtext.get("request") view = econtext.get("view") cp = zope.component.queryMultiAdapter((context, request, view), IContentProvider, name=name) # provide a useful error message, if the provider was not found. # Be sure to provide the objects in addition to the name so # debugging ZCML registrations is possible if cp is None: raise ContentProviderLookupError(name, (context, request, view)) # add the __name__ attribute if it implements ILocation if ILocation.providedBy(cp): cp.__name__ = name # Insert the data gotten from the context addTALNamespaceData(cp, econtext) # Stage 1: Do the state update. zope.event.notify(BeforeUpdateEvent(cp, request)) cp.update() # Stage 2: Render the HTML content. return cp.render()
def test_factory_location(self): # Given an object that is a location, # it is not proxied @interface.implementer(ILocation) class LocatedTarget(Target): __name__ = None __parent__ = None getAnnotation = factory(LocatedTarget) context = Context() target = getAnnotation(context) key = 'zope.annotation.tests.test_factory.LocatedTarget' self.assertEqual([key], list(context)) # Second, a target object is stored at that location. self.assertEqual(type(context[key]), LocatedTarget) # Third, the returned object is an ILocation, rooted at the # parent and having the given name. self.assertTrue(ILocation.providedBy(target)) self.assertIs(target.__parent__, context) self.assertEqual(target.__name__, key) # And it's not a proxy. self.assertEqual(type(target), LocatedTarget) self.assertTrue(ITarget.providedBy(target)) self.assertIs(target, context[key])
def update(self): """See zope.contentprovider.interfaces.IContentProvider""" #--=mpj17=-- Stolen from zope.viewlet.manager self.__updated = True # Find all content providers for the region viewlets = getAdapters( (self.context, self.request, self.__parent__, self), interfaces.IViewlet) viewlets = self.filter_out_no_shows(viewlets) # --=mpj17=-- This is the main change to the standard viewlet # manager: the viewlets are sorted according to the # "weight" attribute viewlets.sort(key=lambda v: int(v[1].weight)) self.viewlets = [] for name, viewlet in viewlets: if ILocation.providedBy(viewlet): viewlet.__name__ = name self.viewlets.append(viewlet) # --=mpj17=-- Don't call _updateViewlets, because it does # not exist in Zope 2.10 if zope213: notify(BeforeUpdateEvent(viewlet, self.request)) viewlet.update()
def render_content_provider(econtext, name): name = name.strip() context = econtext.get('context') request = econtext.get('request') view = econtext.get('view') cp = queryMultiAdapter((context, request, view), IContentProvider, name=name) # provide a useful error message, if the provider was not found. if cp is None: raise ContentProviderLookupError(name) # add the __name__ attribute if it implements ILocation if ILocation.providedBy(cp): cp.__name__ = name # Insert the data gotten from the context addTALNamespaceData(cp, econtext) # BBB: This is where we're different: if getattr(cp, '__of__', None) is not None: cp = cp.__of__(context) # Stage 1: Do the state update. if BeforeUpdateEvent is not None: notify(BeforeUpdateEvent(cp, request)) cp.update() # Stage 2: Render the HTML content. return cp.render()
def render_content_provider(econtext, name): name = name.strip() context = econtext.get('context') request = econtext.get('request') view = econtext.get('view') cp = zope.component.queryMultiAdapter( (context, request, view), IContentProvider, name=name) # provide a useful error message, if the provider was not found. if cp is None: raise ContentProviderLookupError(name) # add the __name__ attribute if it implements ILocation if ILocation.providedBy(cp): cp.__name__ = name # Insert the data gotten from the context addTALNamespaceData(cp, econtext) # Stage 1: Do the state update. if BeforeUpdateEvent is not None: zope.event.notify(BeforeUpdateEvent(cp, request)) cp.update() # Stage 2: Render the HTML content. return cp.render()
def render_content_provider(econtext, name): name = name.strip() context = econtext.get("context") request = econtext.get("request") view = econtext.get("view") cp = zope.component.queryMultiAdapter( (context, request, view), IContentProvider, name=name ) # provide a useful error message, if the provider was not found. # Be sure to provide the objects in addition to the name so # debugging ZCML registrations is possible if cp is None: raise ContentProviderLookupError(name, (context, request, view)) # add the __name__ attribute if it implements ILocation if ILocation.providedBy(cp): cp.__name__ = name # Insert the data gotten from the context addTALNamespaceData(cp, econtext) # Stage 1: Do the state update. zope.event.notify(BeforeUpdateEvent(cp, request)) cp.update() # Stage 2: Render the HTML content. return cp.render()
def test_factory_no_location(self): getAnnotation = factory(Target) context = Context() target = getAnnotation(context) # Several things have happened now. # First, we have an annotation, derived from # our class name key = 'zope.annotation.tests.test_factory.Target' self.assertEqual([key], list(context)) # Second, a target object is stored at that location. self.assertEqual(type(context[key]), Target) # Third, the returned object is an ILocation, rooted at the # parent and having the given name. self.assertTrue(ILocation.providedBy(target)) self.assertIs(target.__parent__, context) self.assertEqual(target.__name__, key) # But it's a proxy. self.assertNotEqual(type(target), Target) self.assertTrue(ITarget.providedBy(target))
def containedEvent(object, container, name=None): """Establish the containment of the object in the container. """ if not IContained.providedBy(object): if ILocation.providedBy(object): zope.interface.alsoProvides(object, IContained) else: object = ContainedProxy(object) oldparent = object.__parent__ oldname = object.__name__ if oldparent is container and oldname == name: # No events return object, None object.__parent__ = container object.__name__ = name if oldparent is None or oldname is None: event = ObjectAddedEvent(object, container, name) else: event = ObjectMovedEvent(object, oldparent, oldname, container, name) return object, event
def contained(obj, parent=None, name=None): """An implementation of zope.app.container.contained.contained that doesn't generate events, for internal use. copied from SQLOS / z3c.zalchemy """ if (parent is None): raise TypeError('Must provide a parent') if not IContained.providedBy(obj): if ILocation.providedBy(obj): interface.directlyProvides(obj, IContained, interface.directlyProvidedBy(obj)) else: obj = ContainedProxy(obj) oldparent = obj.__parent__ oldname = obj.__name__ if (oldparent is None) or not (oldparent is parent or sameProxiedObjects(oldparent, parent)): obj.__parent__ = parent if oldname != name and name is not None: obj.__name__ = name return obj
def __call__(self, econtext): name = super(ProviderExpression, self).__call__(econtext) view = econtext.vars['view'] context = view.context request = view.request # Try to look up the provider. provider = zope.component.queryMultiAdapter( (context, request, view), interfaces.IContentProvider, name) # Provide a useful error message, if the provider was not found. if provider is None: raise interfaces.ContentProviderLookupError(name) # add the __name__ attribute if it implements ILocation if ILocation.providedBy(provider): provider.__name__ = name # Insert the data gotten from the context addTALNamespaceData(provider, econtext) # Stage 1: Do the state update. zope.event.notify(interfaces.BeforeUpdateEvent(provider, request)) provider.update() # Stage 2: Render the HTML content. return provider.render()
def __init__(self, context): perms = [] # first get object permissionsmap supp = IObjectPermissionsMaps(context, None) if supp is not None: perms.extend(supp.get()) for name, permissions in getAdapters((context,), IPermissionsMap): # then get adapted permissionsmap perms.append(permissions) self.perms = perms # collect parents permissionsmaps parent_perms = [] if hasattr(context, '__parent__'): parent_context = context.__parent__ else: parent_context = None while ILocation.providedBy(parent_context) and parent_context is not None: for name, permissions in getAdapters((parent_context,), IPermissionsMap): if permissions not in parent_perms: parent_perms.append(permissions) parent_context = parent_context.__parent__ self.parent_perms = parent_perms #tuple(reversed(parent_perms)) # Permissions are propagated in 'child -> parent' direction
def _setUpWidgets(self): adapted = self.schema(self.context) if adapted is not self.context: if not ILocation.providedBy(adapted): adapted = LocationProxy(adapted) adapted.__parent__ = self.context self.adapted = adapted setUpEditWidgets(self, self.schema, source=self.adapted, names=self.fieldNames)
def __setitem__(self, name, value): if ILocation.providedBy(value): super(HighlightData, self).__setitem__(name, value) if hasattr(self, name): delattr(self, name) else: setattr(self, name, value)
def __init__(self, authplugin, pau): # locate them if ILocation.providedBy(authplugin): self.__parent__ = authplugin.__parent__ self.__name__ = authplugin.__name__ else: self.__parent__ = pau self.__name__ = "" self.authplugin = authplugin self.pau = pau
def update(self): self.path = self._get_path(self.context) # if the view is a location, append this to the breadcrumbs if ILocation.providedBy(self.__parent__) and \ IDCDescriptiveProperties.providedBy(self.__parent__): self.path.append({ "name": self.__parent__.title, "url": None, }) self.chamber = get_chamber_for_context(self.context)
def update(self): self.path = self._get_path(self.context) # if the view is a location, append this to the breadcrumbs if ILocation.providedBy(self.__parent__) and IDCDescriptiveProperties.providedBy(self.__parent__): self.path.append({"name": self.__parent__.title, "url": None}) try: self.user_name = self.request.principal.login except: pass
def __init__(self, authplugin, pau): if (ILocation.providedBy(authplugin) and authplugin.__parent__ is not None): # Checking explicitly for the parent, because providing ILocation # basically means that the object *could* be located. It doesn't # say the object must be located. self.__parent__ = authplugin.__parent__ self.__name__ = authplugin.__name__ else: self.__parent__ = pau self.__name__ = "" self.authplugin = authplugin self.pau = pau self.schema = authplugin.schema
def update(self): self.path = self._get_path(self.context) # if the view is a location, append this to the breadcrumbs if ILocation.providedBy(self.__parent__) and \ IDCDescriptiveProperties.providedBy(self.__parent__): self.path.append({ 'name': self.__parent__.title, 'url': None, }) try: self.user_name = self.request.principal.login except: pass
def publishTraverse(self, request, name): # this is the primary condition; traverse to ``name`` by # looking up methods on this class try: method = getattr(self.context, "get_%s" % name) except AttributeError: # fall back to default traversal (view lookup) def method(): return super(SchedulingContextTraverser, self ).publishTraverse(request, name) obj = method() assert ILocation.providedBy(obj), obj log.debug("SchedulingContextTraverser.publishTraverse: " \ "self=%s context=%s name=%s obj=%s" % (self, self.context, name, obj)) return ProxyFactory(LocationProxy( removeSecurityProxy(obj), container=self.context, name=name))
def show_overlay(self): """Check whether the calendar overlay portlet needs to be rendered. >>> from zope.app.testing import setup >>> setup.placelessSetUp() >>> setup.setUpAnnotations() >>> from schooltool.testing import setup as sbsetup >>> sbsetup.setUpCalendaring() The portlet is only shown when an authenticated user is looking at his/her calendar. Anonymous user: >>> from zope.publisher.browser import TestRequest >>> from schooltool.person.person import Person >>> request = TestRequest() >>> person = Person() >>> context = ISchoolToolCalendar(person) >>> view = CalendarOverlayView(context, request, None, None) >>> view.show_overlay() False Person that we're looking at >>> from schooltool.app.security import Principal >>> request.setPrincipal(Principal('id', 'title', person)) >>> view.show_overlay() True A different person: >>> request.setPrincipal(Principal('id', 'title', Person())) >>> view.show_overlay() False Cleanup: >>> setup.placelessTearDown() """ if not ILocation.providedBy(self.context): return False logged_in = removeSecurityProxy(IPerson(self.request.principal, None)) calendar_owner = removeSecurityProxy(self.context.__parent__) return logged_in is calendar_owner
def update(self): """See zope.contentprovider.interfaces.IContentProvider""" self.__updated = True # Find all content providers for the region viewlets = zope.component.getAdapters( (self.context, self.request, self.__parent__, self), interfaces.IViewlet) viewlets = self.filter(viewlets) viewlets = self.sort(viewlets) # Just use the viewlets from now on self.viewlets = [] for name, viewlet in viewlets: if ILocation.providedBy(viewlet): viewlet.__name__ = name self.viewlets.append(viewlet) self._updateViewlets()
def update(self): """See zope.contentprovider.interfaces.IContentProvider""" self.__updated = True # Find all content providers for the region viewlets = zope.component.getAdapters( (self.context, self.request, self.__parent__, self), interfaces.IViewlet) viewlets = self.filter(viewlets) viewlets = self.sort(viewlets) # Just use the viewlets from now on self.viewlets=[] for name, viewlet in viewlets: if ILocation.providedBy(viewlet): viewlet.__name__ = name self.viewlets.append(viewlet) self._updateViewlets()
def update(self): """See :py:class:`zope.contentprovider.interfaces.IContentProvider`""" registry = self.request.registry registry.notify(BeforeUpdateEvent(self, self.request)) # check permission if self.permission and not self.request.has_permission( self.permission, context=self.context): return # get the viewlets from now on self.viewlets = [] append = self.viewlets.append for name, viewlet in self._get_viewlets(): if ILocation.providedBy(viewlet): viewlet.__name__ = name append(viewlet) # and update them... self._update_viewlets() self.__updated = True
def publishTraverse(self, request, name): # this is the primary condition; traverse to ``name`` by # looking up methods on this class try: method = getattr(self.context, "get_%s" % name) except AttributeError: # fall back to default traversal (view lookup) def method(): return super(SchedulingContextTraverser, self).publishTraverse(request, name) obj = method() assert ILocation.providedBy(obj), obj log.debug("SchedulingContextTraverser.publishTraverse: " \ "self=%s context=%s name=%s obj=%s" % (self, self.context, name, obj)) return ProxyFactory( LocationProxy(removeSecurityProxy(obj), container=self.context, name=name))
def cascade_modifications(obj): """Cascade modify events on an object to the direct parent. !+NAMING(mr, nov-2012) why cascade (implies down?!) instead of bubble (up, usually)? Plus, we are not cascading *modifications* anyway, we are just notifying of such... ! !+EVENT_CONSUMER_ISSUE(mr, nov-2012) why fire new events off the ancestor if the descendent has presumably already fired off its own modified event? If anything it should be a new specialized type of event, with a pointer to the original trigger object (descendent that was modified), so that the consumer can know it is a "derived" event and maybe act accordingly... as it is, all modified event handlers registerd will execute, e.g. auditing of the change if the ancestor is auditable, but the change had already been audited on the originator modified descendent object. """ if not ILocation.providedBy(obj): return if IAlchemistContainer.providedBy(obj.__parent__): if IAlchemistContent.providedBy(obj.__parent__.__parent__): notify(ObjectModifiedEvent(obj.__parent__.__parent__)) elif IAlchemistContent.providedBy(obj.__parent__): notify(ObjectModifiedEvent(obj.__parent__))
def workspace_resolver(context, request, name): """Get the workspace domain object identified by name. Raise zope.publisher.interfaces.NotFound if no container found. This is a callback for the "/workspace" Section (the context here), to resolve which domain object is the workspace container. """ if name.startswith("obj-"): obj_id = int(name[4:]) for workspace in IAnnotations(request)["layer_data"].workspaces: if obj_id == workspace.group_id: log.debug("[workspace_resolver] name=%s workspace=%s context=%s" % ( name, workspace, context)) assert interfaces.IWorkspaceContainer.providedBy(workspace) assert ILocation.providedBy(workspace) # update location for workspace workspace.__parent__ = context workspace.__name__ = name return workspace raise NotFound(context, name, request)
def workspace_resolver(context, request, name): """Get the workspace domain object identified by name. Raise zope.publisher.interfaces.NotFound if no container found. This is a callback for the "/workspace" Section (the context here), to resolve which domain object is the workspace container. """ if name.startswith("obj-"): obj_id = int(name[4:]) for workspace in IAnnotations(request)["layer_data"].workspaces: if obj_id==workspace.group_id: log.debug("[workspace_resolver] name=%s workspace=%s context=%s" % ( name, workspace, context)) assert interfaces.IWorkspaceContainer.providedBy(workspace) assert ILocation.providedBy(workspace) # update location for workspace workspace.__parent__ = context workspace.__name__ = name return workspace raise NotFound(context, name, request)
def login(self): data, errors = self.extractData() if errors: return FAILURE principal = self.request.principal if IUnauthenticatedPrincipal.providedBy(principal): self.status = _(u"Login failed") return FAILURE self.flash(_('You are now logged in as ${name}', mapping={"name": principal.id})) notify(UserLoginEvent(principal)) camefrom = self.request.get('camefrom', None) if not camefrom: if ILocation.providedBy(principal): camefrom = absoluteURL(principal, self.request) else: camefrom = absoluteURL(self.context, self.request) self.redirect(camefrom) return SUCCESS
def login(self): data, errors = self.extractData() if errors: return FAILURE principal = self.request.principal if IUnauthenticatedPrincipal.providedBy(principal): self.status = _("Login failed") return FAILURE self.flash( _("You are now logged in as ${name}", mapping={"name": principal.id})) grok.notify(UserLoggedInEvent(principal)) camefrom = self.request.get("camefrom", None) if not camefrom: if ILocation.providedBy(principal): camefrom = absoluteURL(principal, self.request) else: camefrom = absoluteURL(self.context, self.request) self.redirect(camefrom) return SUCCESS
def expand(self, chain, include_siblings=True): if len(chain) == 0: return () context = chain.pop() items = [] if IApplication.providedBy(context): items.extend(self.expand(chain)) elif IAlchemistContent.providedBy(context): _url = url.absoluteURL(context, self.request) if IDCDescriptiveProperties.providedBy(context): title = context.title else: props = IDCDescriptiveProperties(context, None) if props is not None: title = props.title else: title = context.short_name selected = len(chain) == 0 if chain: nodes = self.expand(chain) else: kls = context.__class__ containers = [(key, getattr(context, key)) for key, value in kls.__dict__.items() if isinstance(value, ManagedContainerDescriptor)] nodes = [] self.expand_containers(nodes, containers, _url, chain, None) items.append({ 'title': title, 'url': _url, 'current': True, 'selected': selected, 'kind': 'content', 'nodes': nodes, }) elif IAlchemistContainer.providedBy(context): # loop through all managed containers of the parent # object, and include the present container as the # 'current' node. parent = context.__parent__ assert parent is not None _url = url.absoluteURL(parent, self.request) # append managed containers as child nodes kls = type(proxy.removeSecurityProxy(parent)) if include_siblings is True: if IApplication.providedBy(parent): containers = [ (name, parent[name]) for name in location.model_to_container_name_mapping.values() if name in parent ] elif IReadContainer.providedBy(parent): containers = list(parent.items()) else: containers = [ (key, getattr(parent, key)) for key, value in kls.__dict__.items() if isinstance(value, ManagedContainerDescriptor) ] else: containers = [(context.__name__, context)] self.expand_containers(items, containers, _url, chain, context) elif ILocation.providedBy(context): _url = url.absoluteURL(context, self.request) #props = IDCDescriptiveProperties.providedBy(context) and \ # context or IDCDescriptiveProperties(context) if IDCDescriptiveProperties.providedBy(context): props = IDCDescriptiveProperties(context) else: props = context props = proxy.removeSecurityProxy(props) selected = len(chain) == 0 if selected and IReadContainer.providedBy(context): nodes = [] try: self.expand_containers(nodes, context.items(), _url, chain, context) except: pass else: nodes = self.expand(chain) i_id = getattr(props, 'id', 'N/A') items.append({ 'title': getattr(props, 'title', i_id), 'url': _url, 'current': True, 'selected': selected, 'kind': 'location', 'nodes': nodes, }) elif IReadContainer.providedBy(context): items.extend(self.expand(chain)) return items
try: descriptor = utils.get_descriptor(domain_model) except KeyError, e: log.warn("TYPE_INFO: no descriptor for model %s " "[container=%s] [error=%s]" % ( domain_model, context, e)) descriptor = None name = "" if descriptor: name = getattr(descriptor, "container_name", None) if name is None: name = getattr(descriptor, "display_name", None) if not name: name = getattr(context, "__name__", None) title = name elif (ILocation.providedBy(context) and IDCDescriptiveProperties.providedBy(context)): title = IDCDescriptiveProperties(context).title return title #!+DevProgammingGuide(mr, oct-2012) always return localized template data class SecondaryNavigationViewlet(browser.BungeniViewlet): render = ViewPageTemplateFile("templates/secondary-navigation.pt") def update(self): #request = self.request context = self.context chain = _get_context_chain(context) length = len(chain) self.items = []
def containedEvent(object, container, name=None): # pylint:disable=redefined-builtin """Establish the containment of the object in the container The object and necessary event are returned. The object may be a `ContainedProxy` around the original object. The event is an added event, a moved event, or None. If the object implements `IContained`, simply set its ``__parent__`` and ``__name__`` attributes: >>> container = {} >>> item = Contained() >>> x, event = containedEvent(item, container, u'foo') >>> x is item True >>> item.__parent__ is container True >>> item.__name__ u'foo' We have an added event: >>> event.__class__.__name__ 'ObjectAddedEvent' >>> event.object is item True >>> event.newParent is container True >>> event.newName u'foo' >>> event.oldParent >>> event.oldName Now if we call contained again: >>> x2, event = containedEvent(item, container, u'foo') >>> x2 is item True >>> item.__parent__ is container True >>> item.__name__ u'foo' We don't get a new added event: >>> event If the object already had a parent but the parent or name was different, we get a moved event: >>> x, event = containedEvent(item, container, u'foo2') >>> event.__class__.__name__ 'ObjectMovedEvent' >>> event.object is item True >>> event.newParent is container True >>> event.newName u'foo2' >>> event.oldParent is container True >>> event.oldName u'foo' If the *object* implements `ILocation`, but not `IContained`, set its ``__parent__`` and ``__name__`` attributes *and* declare that it implements `IContained`: >>> from zope.location import Location >>> item = Location() >>> IContained.providedBy(item) False >>> x, event = containedEvent(item, container, 'foo') >>> x is item True >>> item.__parent__ is container True >>> item.__name__ 'foo' >>> IContained.providedBy(item) True If the *object* doesn't even implement `ILocation`, put a `ContainedProxy` around it: >>> item = [] >>> x, event = containedEvent(item, container, 'foo') >>> x is item False >>> x.__parent__ is container True >>> x.__name__ 'foo' Make sure we don't lose existing directly provided interfaces. >>> from zope.interface import Interface, directlyProvides >>> class IOther(Interface): ... pass >>> from zope.location import Location >>> item = Location() >>> directlyProvides(item, IOther) >>> IOther.providedBy(item) True >>> x, event = containedEvent(item, container, 'foo') >>> IOther.providedBy(item) True """ if not IContained.providedBy(object): if ILocation.providedBy(object): zope.interface.alsoProvides(object, IContained) else: object = ContainedProxy(object) oldparent = object.__parent__ oldname = object.__name__ if oldparent is container and oldname == name: # No events return object, None object.__parent__ = container object.__name__ = name if oldparent is None or oldname is None: event = ObjectAddedEvent(object, container, name) else: event = ObjectMovedEvent(object, oldparent, oldname, container, name) return object, event
def expand(self, chain, include_siblings=True): if len(chain) == 0: return () context = chain.pop() items = [] if IApplication.providedBy(context): items.extend(self.expand(chain)) elif IAlchemistContent.providedBy(context): _url = url.absoluteURL(context, self.request) selected = len(chain) == 0 if chain: nodes = self.expand(chain) else: containers = utils.get_managed_containers(context) nodes = [] self.expand_containers(nodes, containers, _url, chain, None) items.append({ "id": self.get_nav_entry_id(_url), "label": IDCDescriptiveProperties(context).title, "url": _url, "current": True, "selected": selected, "kind": "content", "nodes": nodes, }) elif IAlchemistContainer.providedBy(context): # loop through all managed containers of the parent # object, and include the present container as the # "current" node. parent = context.__parent__ assert parent is not None _url = url.absoluteURL(parent, self.request) # append managed containers as child nodes if include_siblings is True: if IApplication.providedBy(parent): containers = [ (name, parent[name]) for name in location.model_to_container_name_mapping.values() if name in parent ] elif IReadContainer.providedBy(parent): containers = list(parent.items()) else: containers = utils.get_managed_containers(parent) else: containers = [(context.__name__, context)] self.expand_containers(items, containers, _url, chain, context) elif ILocation.providedBy(context): # e.g. bungeni.core.content.Section, DisplayForm _url = url.absoluteURL(context, self.request) selected = len(chain) == 0 if selected and IReadContainer.providedBy(context): nodes = [] try: self.expand_containers( nodes, context.items(), _url, chain, context) except: pass else: nodes = self.expand(chain) _title = getattr(context, "title", None) or \ getattr(context, "page_title", "!+BungeniBrowserView.title") items.append({ "id": self.get_nav_entry_id(_url), # !+BungeniBrowserView.title "label": _title, #IDCDescriptiveProperties(context).title, "url": _url, "current": True, "selected": selected, "kind": "location", "nodes": nodes, }) elif IReadContainer.providedBy(context): #!+NavigationTreeViewlet-EXPAND-IReadContainer(mr, oct-2012) does this ever execute?! raise Exception("!+NavigationTreeViewlet-EXPAND-IReadContainer [%s]" % context) items.extend(self.expand(chain)) return items
def setProp(self, name, value): setattr(self, name, value) if ILocation.providedBy(value): locate(value, self, name) self.children.append(value)
def containedEvent(object, container, name=None): """Establish the containment of the object in the container The object and necessary event are returned. The object may be a `ContainedProxy` around the original object. The event is an added event, a moved event, or None. If the object implements `IContained`, simply set its `__parent__` and `__name__` attributes: >>> container = {} >>> item = Contained() >>> x, event = containedEvent(item, container, u'foo') >>> x is item True >>> item.__parent__ is container True >>> item.__name__ u'foo' We have an added event: >>> event.__class__.__name__ 'ObjectAddedEvent' >>> event.object is item True >>> event.newParent is container True >>> event.newName u'foo' >>> event.oldParent >>> event.oldName Now if we call contained again: >>> x2, event = containedEvent(item, container, u'foo') >>> x2 is item True >>> item.__parent__ is container True >>> item.__name__ u'foo' We don't get a new added event: >>> event If the object already had a parent but the parent or name was different, we get a moved event: >>> x, event = containedEvent(item, container, u'foo2') >>> event.__class__.__name__ 'ObjectMovedEvent' >>> event.object is item True >>> event.newParent is container True >>> event.newName u'foo2' >>> event.oldParent is container True >>> event.oldName u'foo' If the `object` implements `ILocation`, but not `IContained`, set its `__parent__` and `__name__` attributes *and* declare that it implements `IContained`: >>> from zope.location import Location >>> item = Location() >>> IContained.providedBy(item) False >>> x, event = containedEvent(item, container, 'foo') >>> x is item True >>> item.__parent__ is container True >>> item.__name__ 'foo' >>> IContained.providedBy(item) True If the `object` doesn't even implement `ILocation`, put a `ContainedProxy` around it: >>> item = [] >>> x, event = containedEvent(item, container, 'foo') >>> x is item False >>> x.__parent__ is container True >>> x.__name__ 'foo' Make sure we don't lose existing directly provided interfaces. >>> from zope.interface import Interface, directlyProvides >>> class IOther(Interface): ... pass >>> from zope.location import Location >>> item = Location() >>> directlyProvides(item, IOther) >>> IOther.providedBy(item) True >>> x, event = containedEvent(item, container, 'foo') >>> IOther.providedBy(item) True """ if not IContained.providedBy(object): if ILocation.providedBy(object): zope.interface.alsoProvides(object, IContained) else: object = ContainedProxy(object) oldparent = object.__parent__ oldname = object.__name__ if oldparent is container and oldname == name: # No events return object, None object.__parent__ = container object.__name__ = name if oldparent is None or oldname is None: event = ObjectAddedEvent(object, container, name) else: event = ObjectMovedEvent(object, oldparent, oldname, container, name) return object, event
def absolute_url(self): context = self.context if not ILocation.providedBy(context): context = self.form.context return absoluteURL(context, self.request)
def expand(self, chain, include_siblings=True): if len(chain) == 0: return () context = chain.pop() items = [] if IApplication.providedBy(context): items.extend(self.expand(chain)) elif IAlchemistContent.providedBy(context): _url = url.absoluteURL(context, self.request) if IDCDescriptiveProperties.providedBy(context): title = context.title else: props = IDCDescriptiveProperties(context, None) if props is not None: title = props.title else: title = context.short_name selected = len(chain) == 0 if chain: nodes = self.expand(chain) else: kls = context.__class__ containers = [ (key, getattr(context, key)) for key, value in kls.__dict__.items() if isinstance(value, ManagedContainerDescriptor)] nodes = [] self.expand_containers(nodes, containers, _url, chain, None) items.append( {'title': title, 'url': _url, 'current': True, 'selected': selected, 'kind': 'content', 'nodes': nodes, }) elif IAlchemistContainer.providedBy(context): # loop through all managed containers of the parent # object, and include the present container as the # 'current' node. parent = context.__parent__ assert parent is not None _url = url.absoluteURL(parent, self.request) # append managed containers as child nodes kls = type(proxy.removeSecurityProxy(parent)) if include_siblings is True: if IApplication.providedBy(parent): containers = [ (name, parent[name]) for name in location.model_to_container_name_mapping.values() if name in parent ] elif IReadContainer.providedBy(parent): containers = list(parent.items()) else: containers = [ (key, getattr(parent, key)) for key, value in kls.__dict__.items() if isinstance(value, ManagedContainerDescriptor)] else: containers = [(context.__name__, context)] self.expand_containers(items, containers, _url, chain, context) elif ILocation.providedBy(context): _url = url.absoluteURL(context, self.request) #props = IDCDescriptiveProperties.providedBy(context) and \ # context or IDCDescriptiveProperties(context) if IDCDescriptiveProperties.providedBy(context): props = IDCDescriptiveProperties(context) else: props = context props = proxy.removeSecurityProxy(props) selected = len(chain) == 0 if selected and IReadContainer.providedBy(context): nodes = [] try: self.expand_containers( nodes, context.items(), _url, chain, context) except: pass else: nodes = self.expand(chain) i_id = getattr(props, 'id','N/A') items.append( {'title': getattr(props, 'title', i_id), 'url': _url, 'current': True, 'selected': selected, 'kind': 'location', 'nodes': nodes, }) elif IReadContainer.providedBy(context): items.extend(self.expand(chain)) return items
def setProperties(self, name, value): setattr(self, name, value) for term in value: if ILocation.providedBy(term): locate(term, self, 'term') self.children.extend(value)
def render_content_provider(econtext, name): # pylint: disable=too-many-locals,too-many-statements """TALES provider: content provider This TALES expression is used to render a registered "content provider", which is an adapter providing IContentProvider interface; adapter lookup is based on current context, request and view. The requested provider can be called with our without arguments, like in ${structure:provider:my_provider} or ${structure:provider:my_provider(arg1, arg2)}. In the second form, arguments will be passed to the "update" method; arguments can be static (like strings or integers), or can be variables defined into current template context; other Python expressions including computations or functions calls are actually not supported, but dotted syntax is supported to access inner attributes of variables. Provider arguments can be passed by position but can also be passed by name, using classic syntax as in ${structure:provider:my_provider(arg1, arg3=var3)} """ def get_provider(name): # we first look into request annotations to check if a provider implementation has # already been provided during traversal; if not, a simple adapter lookup is done provider = get_request_data(request, 'provider:{}:factory'.format(name)) # if using request annotations, provider can be given as a "direct" factory or as a # dict; if a dict is provided, it's keys are interfaces or classes that the current # context class have to provide or inherit from, and it's matching values are the # provider factories. # if provider is given as a dict, it should be ordered using an OrderedDict so thet # more specific interfaces are provided first! if isinstance(provider, dict): for intf, factory in provider.items(): if (is_interface(intf) and intf.providedBy(context)) or \ (inspect.isclass(intf) and isinstance(context, intf)): provider = factory break else: provider = None # if provider is a callable, we call it! if callable(provider): provider = provider(context, request, view) if provider is None: provider = registry.queryMultiAdapter((context, request, view), IContentProvider, name=name) if provider is not None: econtext['provider'] = provider return provider def get_value(arg): """Extract argument value from context Extension expression language is quite simple. Values can be given as positioned strings, integers or named arguments of the same types. """ arg = arg.strip() if arg.startswith('"') or arg.startswith("'"): # may be a quoted string... return arg[1:-1] if '=' in arg: key, value = arg.split('=', 1) value = get_value(value) return {key.strip(): value} try: arg = int(arg) # check integer value except ValueError: args = arg.split('.') result = econtext.get(args.pop(0)) for arg in args: # pylint: disable=redefined-argument-from-local result = getattr(result, arg) return result else: return arg def get_context_arg(arg): """Extract a value if present in kwargs, otherwise look into context""" if arg in kwargs: return kwargs.pop(arg) return econtext.get(arg) name = name.strip() args, kwargs = [], {} func_match = FUNCTION_EXPRESSION.match(name) if func_match: name, arguments = func_match.groups() for arg in map(get_value, ARGUMENTS_EXPRESSION.findall(arguments)): if isinstance(arg, dict): kwargs.update(arg) else: args.append(arg) else: match = CONTENT_PROVIDER_NAME.match(name) if match: name = match.groups()[0] else: raise ContentProviderLookupError(name) context = get_context_arg('context') request = get_context_arg('request') view = get_context_arg('view') registry = request.registry provider = get_provider(name) # raise an exception if the provider was not found. if provider is None: raise ContentProviderLookupError(name) # add the __name__ attribute if it implements ILocation if ILocation.providedBy(provider): provider.__name__ = name # Insert the data gotten from the context addTALNamespaceData(provider, econtext) # Stage 1: Do the state update registry.notify(BeforeUpdateEvent(provider, request)) provider.update(*args, **kwargs) # Stage 2: Render the HTML content return provider.render()
def expand(self, chain, include_siblings=True): if len(chain) == 0: return () context = chain.pop() items = [] if IApplication.providedBy(context): items.extend(self.expand(chain)) elif IAlchemistContent.providedBy(context): _url = url.absoluteURL(context, self.request) selected = len(chain) == 0 if chain: nodes = self.expand(chain) else: containers = utils.get_managed_containers(context) nodes = [] self.expand_containers(nodes, containers, _url, chain, None) items.append({ "id": self.get_nav_entry_id(_url), "label": IDCDescriptiveProperties(context).title, "url": _url, "current": True, "selected": selected, "kind": "content", "nodes": nodes, }) elif IAlchemistContainer.providedBy(context): # loop through all managed containers of the parent # object, and include the present container as the # "current" node. parent = context.__parent__ assert parent is not None _url = url.absoluteURL(parent, self.request) # append managed containers as child nodes if include_siblings is True: if IApplication.providedBy(parent): containers = [ (name, parent[name]) for name in location.model_to_container_name_mapping.values() if name in parent ] elif IReadContainer.providedBy(parent): containers = list(parent.items()) else: containers = utils.get_managed_containers(parent) else: containers = [(context.__name__, context)] self.expand_containers(items, containers, _url, chain, context) elif ILocation.providedBy(context): # e.g. bungeni.core.content.Section, DisplayForm _url = url.absoluteURL(context, self.request) selected = len(chain) == 0 if selected and IReadContainer.providedBy(context): nodes = [] try: self.expand_containers(nodes, context.items(), _url, chain, context) except: pass else: nodes = self.expand(chain) _title = getattr(context, "title", None) or \ getattr(context, "page_title", "!+BungeniBrowserView.title") items.append({ "id": self.get_nav_entry_id(_url), # !+BungeniBrowserView.title "label": _title, #IDCDescriptiveProperties(context).title, "url": _url, "current": True, "selected": selected, "kind": "location", "nodes": nodes, }) elif IReadContainer.providedBy(context): #!+NavigationTreeViewlet-EXPAND-IReadContainer(mr, oct-2012) does this ever execute?! raise Exception( "!+NavigationTreeViewlet-EXPAND-IReadContainer [%s]" % context) items.extend(self.expand(chain)) return items
elif IAlchemistContainer.providedBy(context): domain_model = context._class try: descriptor = utils.get_descriptor(domain_model) except KeyError, e: log.warn("TYPE_INFO: no descriptor for model %s " "[container=%s] [error=%s]" % (domain_model, context, e)) descriptor = None name = "" if descriptor: name = getattr(descriptor, "container_name", None) if name is None: name = getattr(descriptor, "display_name", None) if not name: name = getattr(context, "__name__", None) title = name elif ILocation.providedBy(context) and IDCDescriptiveProperties.providedBy(context): title = IDCDescriptiveProperties(context).title return title #!+DevProgammingGuide(mr, oct-2012) always return localized template data class SecondaryNavigationViewlet(browser.BungeniViewlet): render = ViewPageTemplateFile("templates/secondary-navigation.pt") def update(self): # request = self.request context = self.context chain = _get_context_chain(context) length = len(chain) self.items = []
domain_model = context._class try: descriptor = utils.get_descriptor(domain_model) except KeyError, e: log.warn("TYPE_INFO: no descriptor for model %s " "[container=%s] [error=%s]" % (domain_model, context, e)) descriptor = None name = "" if descriptor: name = getattr(descriptor, "container_name", None) if name is None: name = getattr(descriptor, "display_name", None) if not name: name = getattr(context, "__name__", None) title = name elif (ILocation.providedBy(context) and IDCDescriptiveProperties.providedBy(context)): title = IDCDescriptiveProperties(context).title return title #!+DevProgammingGuide(mr, oct-2012) always return localized template data class SecondaryNavigationViewlet(browser.BungeniViewlet): render = ViewPageTemplateFile("templates/secondary-navigation.pt") def update(self): #request = self.request context = self.context chain = _get_context_chain(context) length = len(chain)