[Zope3-checkins] CVS: Zope3/src/zope/app/utility/browser - __init__.py:1.1 configure.zcml:1.1 configureutility.pt:1.1 utilities.pt:1.1

Stephan Richter srichter at cosmos.phy.tufts.edu
Thu Mar 11 17:05:04 EST 2004


Update of /cvs-repository/Zope3/src/zope/app/utility/browser
In directory cvs.zope.org:/tmp/cvs-serv4201/utility/browser

Added Files:
	__init__.py configure.zcml configureutility.pt utilities.pt 
Log Message:
Moved local utility service implementation to zope.app.utility till Jim 
will provide the new one.

Note: I forgot this module in an earlier checkin today.


=== Added File Zope3/src/zope/app/utility/browser/__init__.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Use-Registration view for utilities.

$Id: __init__.py,v 1.1 2004/03/11 22:05:02 srichter Exp $
"""
from zope.app.browser.component.interfacewidget import InterfaceWidget
from zope.app.browser.services.registration import AddComponentRegistration
from zope.app.form.widget import CustomWidgetFactory
from zope.app.interfaces.services.registration import ActiveStatus
from zope.app.interfaces.services.registration import RegisteredStatus
from zope.app.interfaces.services.registration import UnregisteredStatus
from zope.app import zapi
from zope.interface import providedBy
from zope.proxy import removeAllProxies
from zope.app.introspector import interfaceToName

class UtilityInterfaceWidget(InterfaceWidget):
    """Custom widget to select an interface from the component's interfaces.
    """

    def __call__(self):
        field = self.context
        component = field.context
        result = ['\n<select name="%s">' % self.name]
        for interface in providedBy(component).flattened():
            result.append('  <option value="%s.%s">%s</option>' %
                          (interface.__module__, interface.getName(),
                           interface.getName()))
        result.append('</select>')
        return '\n'.join(result)


class AddRegistration(AddComponentRegistration):
    """View for adding a utility registration.

    We could just use AddComponentRegistration, except that we need a
    custom interface widget.

    This is a view on a local utility, configured by an <addform>
    directive.
    """
    interface_widget = CustomWidgetFactory(UtilityInterfaceWidget)

    def add(self, registration):
        reg = super(AddRegistration, self).add(registration)
        reg.status = ActiveStatus
        return reg


class Utilities(object):

    # self.context is the local utility service

    def update(self):
        """Possibly delete one or more utilities.

        In that case, issue a message.
        """
        selected = self.request.get("selected")
        doActivate = self.request.get("Activate")
        doDeactivate = self.request.get("Deactivate")
        doDelete = self.request.get("Delete")
        if not selected:
            if doActivate or doDeactivate or doDelete:
                return _("Please select at least one checkbox")
            return None
        folder = zapi.getParent(self.context)
        todo = []
        for key in selected:
            name, ifacename = key.split(":", 1)
            iface = folder.resolve(ifacename)
            todo.append((key, name, iface))
        if doActivate:
            return self._activate(todo)
        if doDeactivate:
            return self._deactivate(todo)
        if doDelete:
            return self._delete(todo)

    def _activate(self, todo):
        done = []
        for key, name, iface in todo:
            registry = self.context.queryRegistrations(name, iface)
            obj = registry.active()
            if obj is None:
                # Activate the first registered registration
                obj = registry.info()[0]['registration']
                obj.status = ActiveStatus
                done.append(obj.usageSummary())
        if done:
            s = _("Activated: ${activated_utilities}")
            s.mapping = {'activated_utilities': ", ".join(done)}
            return s
        else:
            return _("All of the checked utilities were already active")

    def _deactivate(self, todo):
        done = []
        for key, name, iface in todo:
            registry = self.context.queryRegistrations(name, iface)
            obj = registry.active()
            if obj is not None:
                obj.status = RegisteredStatus
                done.append(obj.usageSummary())
        if done:
            s = _("Deactivated: ${deactivated_utilities}")
            s.mapping = {'deactivated_utilities': ", ".join(done)}
            return s
        else:
            return _("None of the checked utilities were active")

    def _delete(self, todo):
        errors = []
        for key, name, iface in todo:
            registry = self.context.queryRegistrations(name, iface)
            assert registry
            obj = registry.active()
            if obj is not None:
                errors.append(obj.usageSummary())
                continue
        if errors:
            s = _("Can't delete active utility/utilites: ${utility_names}; "
                  "use the Deactivate button to deactivate")
            s.mapping = {'utility_names': ", ".join(errors)}
            return s

        # 1) Delete the registrations
        services = {}
        done = []
        for key, name, iface in todo:
            registry = self.context.queryRegistrations(name, iface)
            assert registry
            assert registry.active() is None # Phase error
            first = True
            for info in registry.info():
                conf = info['registration']
                obj = conf.getComponent()
                if first:
                    done.append(conf.usageSummary())
                    first = False
                path = zapi.getPath(obj)
                services[path] = obj
                conf.status = UnregisteredStatus
                parent = zapi.getParent(conf)
                name = zapi.getName(conf)
                del parent[name]

        # 2) Delete the service objects
        for path, obj in services.items():
            parent = zapi.getParent(obj)
            name = zapi.getName(obj)
            del parent[name]
            
        s = _("Deleted: ${utility_names}")
        s.mapping = {'utility_names': ", ".join(todo)}
        return s

    def getConfigs(self):
        L = []
        for iface, name, cr in self.context.getRegisteredMatching():
            active = obj = cr.active()
            if obj is None:
                obj = cr.info()[0]['registration'] # Pick a representative
            ifname = interfaceToName(self.context, iface)
            d = {"interface": ifname,
                 "name": name,
                 "url": "",
                 "summary": obj.usageSummary(),
                 "configurl": ("@@configureutility.html?interface=%s&name=%s"
                               % (ifname, name)),
                 }
            if active is not None:
                d["url"] = str(zapi.getView(active.getComponent(),
                                            "absolute_url",
                                            self.request))
            L.append((ifname, name, d))
        L.sort()
        return [d for ifname, name, d in L]


class ConfigureUtility:
    def update(self):
        folder = zapi.getParent(self.context)
        iface = folder.resolve(self.request['interface'])
        name = self.request['name']
        iface = removeAllProxies(iface)
        regstack = self.context.queryRegistrations(name, iface)
        form = zapi.getView(regstack, "ChangeRegistrations", self.request)
        form.update()
        return form


=== Added File Zope3/src/zope/app/utility/browser/configure.zcml ===
<zope:configure 
   xmlns:zope="http://namespaces.zope.org/zope"
   xmlns="http://namespaces.zope.org/browser">

<!-- Browser directives for the utility service -->

  <!-- "Add service" menu entry to add a utility service.
       The action attribute matches a factory name defined in
       zope/app/services/utility.zcml. -->
  <addMenuItem
      description=
        "A Local Utility Service allows you to register Utilities in this site"
      title="Utility Service"
      class="zope.app.utility.LocalUtilityService"
      permission="zope.ManageServices" />

  <!-- ZMI tab named "Utilites" for the utility service -->
  <page
      for="zope.app.utility.interfaces.ILocalUtilityService"
      menu="zmi_views" title="Utilities"
      name="utilities.html"
      template="utilities.pt"
      class=".Utilities"
      permission="zope.ManageServices" />

<!-- Browser directives for individual utility objects -->

  <!-- Registration page for utility objects.  You get here by
       clicking on the (configure) link for a particular utility
       in the "Utilities" tab of the utility service.  It shows
       a menu of different registrations, at most one of which
       is active.  You can activate a different registration, or
       click on an individual registration to edit it.
       (Note that this page doesn't really apply to a single utility,
       it applies to a single "utility registration".  That is a
       combination of a name and a provided interface, where the name
       may be empty.) -->
  <page
      for="zope.app.utility.interfaces.ILocalUtilityService"
      name="configureutility.html"
      template="configureutility.pt"
      class=".ConfigureUtility"
      permission="zope.ManageServices" />

  <!-- When creating a new utility object, you are taken to this
       form to configure it.  The form lets you choose a name,
       an interface, a permission, and a registration status
       (Unregistered, Registered or Active). -->
  <addform
      label="New Utility Registration"
      for="zope.app.utility.interfaces.ILocalUtility"
      name="addRegistration.html"
      schema="zope.app.utility.interfaces.IUtilityRegistration"
      class=".AddRegistration"
      permission="zope.ManageServices"
      content_factory="zope.app.utility.UtilityRegistration"
      arguments="name interface componentPath"
      fields="name interface componentPath permission"
      usage="addingdialog"/>

  <!-- When editing the registration of an existing utility object,
       you are taken to this form.  It is similar to the above add
       form, but doesn't let you change the name, interface or path.
       (Thus leaving only permission and registration status.) -->
  <editform
      menu="zmi_views" title="Edit"
      label="Edit Utility Registration"
      name="index.html"
      schema="zope.app.utility.interfaces.IUtilityRegistration"
      permission="zope.ManageServices"
      fields="name interface componentPath permission status" />

 <menuItems
    menu="zmi_actions"
    for="zope.app.utility.interfaces.ILocalUtilityService">

    <menuItem
        title="Add utility"
        action="../AddUtility"
        permission="zope.ManageServices" />

 </menuItems>


</zope:configure>


=== Added File Zope3/src/zope/app/utility/browser/configureutility.pt ===
<html metal:use-macro="context/@@standard_macros/page">
<body>
<div metal:fill-slot="body">

  <h2 i18n:translate="" tal:condition="request/name">
    Utility registrations for interface
    <span tal:replace="request/interface" i18n:name="interface"/>
    with name
    <span tal:replace="request/name" i18n:name="utility_name" />
  </h2>

  <h2 i18n:translate="" tal:condition="not:request/name">
    Utility registrations for interface
    <span tal:replace="request/interface" i18n:name="interface"/>
  </h2>

  <form action="." method="post"
        tal:attributes="action request/URL"
        tal:define="form view/update">

    <input type="hidden" name="interface"
           tal:attributes="value request/interface" />

    <input type="hidden" name="name"
           tal:attributes="value request/name" />

    <div tal:replace="structure form" />

    <input type="submit" name="submit_update" value="Update"
           i18n:attributes="value update-button" />

  </form>

</div>
</body>
</html>


=== Added File Zope3/src/zope/app/utility/browser/utilities.pt ===
<html metal:use-macro="context/@@standard_macros/page">
<body>
<div metal:fill-slot="body"
     tal:define="message view/update; configs view/getConfigs">

  <h2 i18n:translate="">Utilities registered in this utility service</h2>

  <div class="message" tal:condition="message">
    <span tal:replace="message">view/update message here</span>
    <br /><br />
    <i><a href="" i18n:translate="">(click to clear message)</a></i>
  </div>

  <p tal:condition="not:configs">None</p>

  <form method="POST" action="utilities.html" tal:condition="configs">

    <table>
      <tr tal:repeat="config configs">
        <td><input type="checkbox" name="selected:list"
                   tal:attributes=
                   "value string:${config/name}:${config/interface}" />
        </td>
        <td>
          <a href="."
             tal:condition="config/url"
             tal:attributes=
                 "href string:${config/url}/@@SelectedManagementView.html"
             tal:content="config/summary" />
          <span tal:condition="not:config/url"
                tal:replace="config/summary" />
        </td>
        <td>
          (<a href="."
             tal:attributes="href config/configurl"
             i18n:translate=""
             >change registration</a>)
        </td>
      </tr>
    </table>

    <input type="submit" name="Activate" value="Activate" 
           i18n:attributes="value activate-button"/>
    <input type="submit" name="Deactivate" value="Deactivate"
           i18n:attributes="value deactivate-button"/>
    &nbsp;
    <input type="submit" name="Delete" value="Delete"
           i18n:attributes="value delete-button"/>
    &nbsp;
    <input type="submit" name="Refresh" value="Refresh"
           i18n:attributes="value refresh-button"/>

  </form>

</div>
</body>
</html>




More information about the Zope3-Checkins mailing list