[Zope3-checkins] CVS: Zope3/src/zope/app/registration/browser - __init__.py:1.1 changeregistrations.pt:1.1 configure.zcml:1.1 editregistration.pt:1.1 registered.pt:1.1 registration.pt:1.1

Stephan Richter srichter at cosmos.phy.tufts.edu
Sat Mar 13 13:01:19 EST 2004


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

Added Files:
	__init__.py changeregistrations.pt configure.zcml 
	editregistration.pt registered.pt registration.pt 
Log Message:


Moved registration code to zope.app.registration. Created module aliases, so
that old ZODBs work.


=== Added File Zope3/src/zope/app/registration/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.
#
##############################################################################
"""Gewneral registry-related views

$Id: __init__.py,v 1.1 2004/03/13 18:01:17 srichter Exp $
"""
from zope.app.browser.container.adding import Adding
from zope.app.browser.form.widget import RadioWidget, BrowserWidget
from zope.app.i18n import ZopeMessageIDFactory as _
from zope.app.browser.interfaces.form import IBrowserWidget
from zope.app.interfaces.form import IInputWidget
from zope.app.container.interfaces import INameChooser

from zope.app.registration.interfaces import IRegistration
from zope.app.registration.interfaces import IRegistered
from zope.app.registration.interfaces import UnregisteredStatus
from zope.app.registration.interfaces import RegisteredStatus
from zope.app.registration.interfaces import ActiveStatus
from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile
from zope.app.traversing import getName, traverse
from zope.component import getView, getServiceManager
from zope.proxy import removeAllProxies
from zope.app.publisher.browser import BrowserView
from zope.interface import implements


class RegistrationView(BrowserView):

    def __init__(self, context, request):
        super(RegistrationView, self).__init__(context, request)
        useconfig = IRegistered(self.context)
        self.registrations = useconfig.registrations()

    def update(self):
        """Make changes based on the form submission."""
        if len(self.registrations) > 1:
            self.request.response.redirect("registrations.html")
            return
        if "deactivate" in self.request:
            self.registrations[0].status = RegisteredStatus
        elif "activate" in self.request:
            if not self.registrations:
                # create a registration:
                self.request.response.redirect("addRegistration.html")
                return
            self.registrations[0].status = ActiveStatus

    def active(self):
        return self.registrations[0].status == ActiveStatus

    def registered(self):
        return bool(self.registrations)

    def registration(self):
        """Return the first registration.

        If there are no registrations, raises an error.
        """
        return self.registrations[0]


class Registered:

    def __init__(self, context, request):
        self.context = context
        self.request = request

    def uses(self):
        component = self.context
        useconfig = IRegistered(component)
        result = []
        for path in useconfig.usages():
            config = traverse(component, path)
            description = config.usageSummary()
            url = getView(config, 'absolute_url', self.request)
            result.append({'path': path,
                           'url': url(),
                           'status': config.status,
                           'description': description,
                           })
        return result


class ChangeRegistrations(BrowserView):

    _prefix = 'registrations'
    name = _prefix + ".active"
    message = ''
    configBase = ''

    def setPrefix(self, prefix):
        self._prefix = prefix
        self.name = prefix + ".active"

    def applyUpdates(self):
        message = ''
        if 'submit_update' in self.request.form:
            id = self.request.form.get(self.name)
            if id == "disable":
                active = self.context.active()
                if active is not None:
                    self.context.activate(None)
                    message = _("Disabled")
            else:
                for info in self.context.info():
                    if info['id'] == id and not info['active']:
                        self.context.activate(info['registration'])
                        message = _("Updated")
                        break

        return message

    def update(self):

        message = self.applyUpdates()

        self.configBase = str(getView(getServiceManager(self.context),
                                      'absolute_url', self.request)
                              )

        registrations = self.context.info(True)

        # This is OK because registrations is just a list of dicts
        registrations = removeAllProxies(registrations)

        inactive = 1
        have_none = False
        for info in registrations:
            if info['active']:
                inactive = None
            else:
                info['active'] = None

            reg = info['registration']
            if reg is not None:
                info['summary'] = reg.implementationSummary()
            else:
                info['summary'] = ""
                info['id'] = 'disable'
                have_none = True

        if not have_none:
            # Add a dummy registration since the stack removes trailing None.
            registrations.append({"active": False,
                                  "id": "disable",
                                  "summary": ""})

        self.inactive = inactive
        self.registrations = registrations

        self.message = message


class RegistrationStatusWidget(RadioWidget):

    def _getDefault(self):
        return UnregisteredStatus

    def __call__(self):
        rendered_items = self.renderItems(self._showData())
        return "  ".join(rendered_items)


class ComponentPathWidget(BrowserWidget):
    """Widget for displaying component paths

    The widget doesn't actually allow editing. Rather it gets the
    value by inspecting its field's context. If the context is an
    IComponentRegistration, then it just gets its value from the
    component using the field's name. Otherwise, it uses the path to
    the context.
    """

    implements(IBrowserWidget, IInputWidget)

    def __call__(self):
        """See zope.app.browser.interfaces.form.IBrowserWidget"""
        # Render as a link to the component
        field = self.context
        context = field.context
        if IRegistration.providedBy(context):
            # It's a registration object. Just get the corresponding attr
            path = getattr(context, field.__name__)
            # The path may be relative; then interpret relative to ../..
            if not path.startswith("/"):
                context = traverse(context, "../..")
            component = traverse(context, path)
        else:
            # It must be a component that is about to be configured.
            component = context
            # Always use a relative path (just the component name)
            path = getName(context)

        url = getView(component, 'absolute_url', self.request)

        return ('<a href="%s/@@SelectedManagementView.html">%s</a>'
                % (url, path))

    def hidden(self):
        """See zope.app.browser.interfaces.form.IBrowserWidget"""
        return ''

    def hasInput(self):
        """See zope.app.interfaces.form.IWidget"""
        return 1

    def getInputValue(self):
        """See zope.app.interfaces.form.IWidget"""
        field = self.context
        context = field.context
        if IRegistration.providedBy(context):
            # It's a registration object. Just get the corresponding attr
            path = getattr(context, field.getName())
        else:
            # It must be a component that is about to be configured.
            # Always return a relative path (just the component name)
            path = getName(context)

        return path


class AddComponentRegistration(BrowserView):
    """View for adding component registrations

    This class is used to define registration add forms.  It provides
    the ``add`` and ``nextURL`` methods needed when creating add forms
    for non-IAdding objects.  We need this here because registration
    add forms are views of the component being configured.
    """

    def add(self, registration):
        """Add a registration

        We are going to add the registration to the local
        registration manager. We don't want to hard code the name of
        this, so we'll simply scan the containing folder and add the
        registration to the first registration manager we find.

        """

        component = self.context

        # Get the registration manager for this folder
        folder = component.__parent__
        rm = folder.getRegistrationManager()

        name = INameChooser(rm).chooseName('', registration)
        rm[name] = registration
        return registration

    def nextURL(self):
        return "@@SelectedManagementView.html"


class RegistrationAdding(Adding):
    """Adding subclass for adding registrations."""

    menu_id = "add_registration"

    def nextURL(self):
        return str(getView(self.context, "absolute_url", self.request))


class EditRegistration(BrowserView):
    """A view on a registration manager, used by registrations.pt."""

    def __init__(self, context, request):
        self.request = request
        self.context = context

    def update(self):
        """Perform actions depending on user input."""

        if 'keys' in self.request:
            k = self.request['keys']
        else:
            k = []

        msg = 'You must select at least one item to use this action'

        if 'remove_submit' in self.request:
            if not k: return msg
            self.remove_objects(k)
        elif 'top_submit' in self.request:
            if not k: return msg
            self.context.moveTop(k)
        elif 'bottom_submit' in self.request:
            if not k: return msg
            self.context.moveBottom(k)
        elif 'up_submit' in self.request:
            if not k: return msg
            self.context.moveUp(k)
        elif 'down_submit' in self.request:
            if not k: return msg
            self.context.moveDown(k)
        elif 'refresh_submit' in self.request:
            pass # Nothing to do

        return ''

    def remove_objects(self, key_list):
        """Remove the directives from the container."""
        container = self.context
        for name in key_list:
            del container[name]

    def configInfo(self):
        """Render View for each directives."""
        result = []
        for name, configobj in self.context.items():
            url = str(getView(configobj, 'absolute_url', self.request))
            active = configobj.status == ActiveStatus
            summary1 = getattr(configobj, "usageSummary", None)
            summary2 = getattr(configobj, "implementationSummary", None)
            item = {'name': name, 'url': url, 'active': active}
            if summary1:
                item['line1'] = summary1()
            if summary2:
                item['line2'] = summary2()
            result.append(item)
        return result


=== Added File Zope3/src/zope/app/registration/browser/changeregistrations.pt ===
<table width="100%" i18n:domain="zope">
  <tr tal:define="message view/message" tal:condition="message">
     <td></td>
     <td colspan="2"><em tal:content="message">xxxx</em></td>
  </tr>
  <tr tal:repeat="registration view/registrations">
     <td><input type="radio" name="Roles" value="0"
             tal:attributes="
             name view/name;
             value registration/id;
             checked registration/active;
             "
             />
     </td>
     <td tal:condition="python: registration['id'] != 'disable'"><a href="."
            tal:attributes="href string:${view/configBase}/${registration/id}"
            tal:content="registration/id"
         >foo/bar</a></td>
     <td tal:condition="python: registration['id'] == 'disable'"
         i18n:translate="">
         Disabled</td>
     <td tal:content="structure registration/summary">
         Registration summary
     </td>
  </tr>
</table>


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

  <zope:view
      for="zope.app.registration.interfaces.IRegistrationStatus"
      type="zope.publisher.interfaces.browser.IBrowserRequest"
      provides="zope.app.interfaces.form.IInputWidget"
      factory=".RegistrationStatusWidget"
      permission="zope.ManageServices"
      />

  <page
      for="zope.app.registration.interfaces.IRegistrationStack"
      name="ChangeRegistrations"
      template="changeregistrations.pt"
      class=".ChangeRegistrations"
      allowed_interface=
                   "zope.app.browser.interfaces.form.IFormCollaborationView"
      permission="zope.ManageServices" />

  <zope:view
      for="zope.app.registration.interfaces.IComponentPath"
      type="zope.publisher.interfaces.browser.IBrowserRequest"
      provides="zope.app.interfaces.form.IInputWidget"
      factory=".ComponentPathWidget"
      permission="zope.Public"
      />

  <zope:view
      for="zope.app.registration.interfaces.IComponentPath"
      type="zope.publisher.interfaces.browser.IBrowserRequest"
      provides="zope.app.interfaces.form.IDisplayWidget"
      factory=".ComponentPathWidget"
      permission="zope.Public"
      />

<!-- RegistrationManager -->

  <page
     name="index.html" 
     for="zope.app.registration.interfaces.IRegistrationManager"
     menu="zmi_views" title="Registration"
     permission="zope.ManageServices"
     class=".EditRegistration"
     template="editregistration.pt" />

<!-- For now, we'll allow CMs to be added, but we won't include them
     in the add_component menu. -->
  <view
       for="zope.app.registration.interfaces.IRegistrationManager"
       name="+"
       menu="zmi_actions" title="Add"
       permission="zope.ManageServices"
       class=".RegistrationAdding">
    <page name="index.html"  attribute="index"  />
    <page name="action.html" attribute="action" />
  </view>

<!-- Error views -->

  <page
      for="
      zope.app.registration.interfaces.INoRegistrationManagerError"
      name="index.html"
      permission="zope.Public"
      template="../../browser/exception/user.pt"
      class="zope.app.browser.exception.user.UserErrorView" />

  <page
      for="zope.app.registration.interfaces.INoLocalServiceError"
      name="index.html"
      permission="zope.Public"
      template="../../browser/exception/user.pt"
      class="zope.app.browser.exception.user.UserErrorView" />


<!-- Generic page for objects that keep track of their registrations -->

  <page
      for="zope.app.registration.interfaces.IRegisterable"
      name="registrations.html"
      template="registered.pt"
      class=".Registered"
      permission="zope.ManageServices"
      usage="objectview"
      />

  <page
      for="zope.app.registration.interfaces.IRegisterable"
      name="registration.html"
      template="registration.pt"
      class=".RegistrationView"
      permission="zope.ManageServices"
      menu="zmi_views" title="Registration"
      />


</zope:configure>


=== Added File Zope3/src/zope/app/registration/browser/editregistration.pt ===
<html metal:use-macro="views/standard_macros/page">
<head>
  <title metal:fill-slot="title" i18n:translate="">
    View Registration Manager
  </title>
</head>
<body>
<div metal:fill-slot="body">

  <h2 i18n:translate="">Registration Manager</h2>

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

    <p tal:condition="message" tal:content="message" />

    <table>
      <thead>
        <tr>
          <th></th>
          <th align="left" i18n:translate="">Summary</th>
        </tr>
      </thead>
      <tbody>
        <tr tal:repeat="config view/configInfo">
          <td valign="top">
            <input type="checkbox" name='keys:list' value='1'
                   tal:attributes="value config/name" />
          </td>
          <td>
            <a href="." tal:attributes="href config/name">
              <span tal:content="config/line1|default">
                Config item <span tal:content="config/name" />
              </span>
            </a>
            <span tal:condition="not:config/active"
                i18n:translate="">(disabled)</span>
            <br />
            <span tal:content="config/line2|default">
              (No implementation summary)
            </span>
          </td>
        </tr>
      </tbody>
    </table>

    <div class="row">
      <input type="submit" name='refresh_submit' value="Refresh" 
             i18n:attributes="value refresh-button" />
      <input type="submit" name='UPDATE_SUBMIT' value="Submit" 
             i18n:attributes="value submit-button" />
      <input type="submit" name='remove_submit' value="Remove" 
             i18n:attributes="value remove-button" />
      &nbsp;&nbsp;
      <input type="submit" name='top_submit' value="Top"
             i18n:attributes="value top-button" />
      <input type="submit" name='up_submit' value="Up"
             i18n:attributes="value up-button" />
      <input type="submit" name='down_submit' value="Down"
             i18n:attributes="value down-button" />
      <input type="submit" name='bottom_submit' value="Bottom"
             i18n:attributes="value bottom-button" />
    </div>
  </form>

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


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

  <p i18n:translate="">Registrations for this object:</p>

  <ul>
    <li tal:repeat="use view/uses">

      <a href="http://."
         tal:attributes="href use/url"
         tal:content="use/description">Description</a>
      (<span tal:replace="use/status">Active</span>)

    </li>
  </ul>

  <p><a href="addRegistration.html" i18n:translate="">
    Add a registration for this object
  </a></p>

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


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

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

  <div tal:condition="view/registered">
    <div tal:define="registration view/registration">
      <p i18n:translate="">This object is registered as:</p>

      <div class="registrationSummary">
        <div tal:content="registration/usageSummary"
             class="usageSummary" />
        <div tal:content="registration/implementationSummary"
             class="implementationSummary" />
        <div class="modificationLink">
          <a tal:attributes="href registration/@@absolute_url"
             i18n:translate="">(modify)</a>
        </div>
      </div>

      <tal:block condition="view/active">
        <p i18n:translate="">This object is currently active.</p>
        <input type="submit" value="Deactivate" name="deactivate" />
      </tal:block>
      <tal:block condition="not:view/active">
        <p i18n:translate="">This object is currently inactive.</p>
        <input type="submit" value="Activate" name="activate" />
      </tal:block>
    </div>

    <hr />
    <a href="registrations.html" i18n:translate="">
      Advanced Options
    </a>

  </div>

  <div tal:condition="not:view/registered">
    <p i18n:translate="">This object is not currently active.</p>

    <p i18n:translate="">
      This object won't actually be used unless it is registered to
      perform a specific function and is activated.
    </p>

    <input type="submit" value="Register" name="activate" />
  </div>

</form>

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




More information about the Zope3-Checkins mailing list