[Zope3-checkins] CVS: Zope3/src/zope/component - __init__.py:1.1.2.1 adapter.py:1.1.2.1 contextdependent.py:1.1.2.1 exceptions.py:1.1.2.1 factory.py:1.1.2.1 interfaces.py:1.1.2.1 resource.py:1.1.2.1 service.py:1.1.2.1 skin.py:1.1.2.1 utility.py:1.1.2.1 view.py:1.1.2.1

Jim Fulton jim@zope.com
Mon, 23 Dec 2002 14:32:42 -0500


Update of /cvs-repository/Zope3/src/zope/component
In directory cvs.zope.org:/tmp/cvs-serv19908/zope/component

Added Files:
      Tag: NameGeddon-branch
	__init__.py adapter.py contextdependent.py exceptions.py 
	factory.py interfaces.py resource.py service.py skin.py 
	utility.py view.py 
Log Message:
Initial renaming before debugging

=== Added File Zope3/src/zope/component/__init__.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
# 
##############################################################################
"""

$Id: __init__.py,v 1.1.2.1 2002/12/23 19:32:40 jim Exp $
"""

from zope.component.interfaces import IComponentArchitecture
from zope.component.exceptions import ComponentLookupError
from zope.component.service import serviceManager

__implements__ = IComponentArchitecture

def getServiceManager(context): # hookable
    return getServiceManager_hook(context)

def queryServiceManager(context, default=None):
    try:
        return getServiceManager(context)
    except ComponentLookupError:
        return default

def getServiceManager_hook(context): # default hook
    return serviceManager

def getService(context, name):
    return getServiceManager(context).getService(name)

def queryService(context, name, default=None):
    sm = queryServiceManager(context)
    if sm is None:
        return default
    return sm.queryService(name, default)

def getServiceDefinitions(context): 
    return getServiceManager(context).getServiceDefinitions()

# Utility service

def getUtility(context, interface, name=''):
    return getService(context, 'Utilities').getUtility(interface, name)

def queryUtility(context, interface, default=None, name=''):
    return getService(context, 'Utilities').queryUtility(
        interface, default, name)

# Adapter service

def getAdapter(object, interface, name='', context=None):
    if context is None:
        context = object
    return getService(context, 'Adapters').getAdapter(
        object, interface, name)

def queryAdapter(object, interface, default=None, name='', context=None):
    if context is None:
        context = object
    try:
        adapters = getService(context, 'Adapters')
    except ComponentLookupError:
        # Oh blast, no adapter service. We're probably just running from a test
        return default
    
    return adapters.queryAdapter(
        object, interface, default, name)

# Factory service

def createObject(context, name, *args, **kwargs):
    return getService(context, 'Factories').createObject(name, *args, **kwargs)

def getFactory(context, name):
    return getService(context, 'Factories').getFactory(name)

def queryFactory(context, name, default=None):
    return getService(context, 'Factories').queryFactory(name, default)

def getFactoryInterfaces(context, name):
    return getService(context, 'Factories').getInterfaces(name)

# Skin service

def getSkin(wrapped_object, name, view_type):
    return getService(wrapped_object, 
                      'Skins').getSkin(wrapped_object, name, view_type)

# View service

def getView(wrapped_object, name, request):
    return getService(wrapped_object, 
                      'Views').getView(wrapped_object, name, request)

def queryView(wrapped_object, name, request, default=None):
    return getService(wrapped_object, 
                      'Views').queryView(wrapped_object, name,
                                         request, default)

def getDefaultViewName(wrapped_object, request):
    return getService(wrapped_object, 
                      'Views').getDefaultViewName(wrapped_object,
                                                  request)

def queryDefaultViewName(wrapped_object, request, default=None):
    return getService(wrapped_object,
                      'Views').queryDefaultViewName(wrapped_object,
                                                    request, default)

# Resource service

def getResource(wrapped_object, name, request):
    return getService(wrapped_object,
                      'Resources').getResource(
        wrapped_object, name, request)

def queryResource(wrapped_object, name, request, default=None):
    return getService(wrapped_object,
                      'Resources').queryResource(
        wrapped_object, name, request, default)


#def _clear():
#    from Service import _clear;     _clear()
#    from ViewService import _clear; _clear()
#    from ResourceService import _clear; _clear()
#    from SkinService import _clear; _clear()


=== Added File Zope3/src/zope/component/adapter.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
# 
##############################################################################
"""adapter service
"""

from zope.interface.adapter import AdapterRegistry
from zope.component.exceptions import ComponentLookupError
from zope.component.interfaces import IAdapterService

class IGlobalAdapterService(IAdapterService):

    def provideAdapter(forInterface, providedInterface, maker, name=''):
        """Provide an adapter

        An adapter provides an interface for objects that have another
        interface.

        Arguments:

        forInterface -- The interface the adapter provides an interface for.

        providedInterface -- The provided interface

        maker -- a callable object that gets an adapter component for
        a context component.
        """
    def getRegisteredMatching(for_interface=None, provide_interface=None,
                              name=None):
        """Return information about registered data

        A four-tuple is returned containing:

          - registered name,

          - registered for interface

          - registered provided interface, and

          - registered data
        """

class GlobalAdapterService:
    
    __implements__ = IGlobalAdapterService
    
    def __init__(self):
        self.__adapters = {}
    
    def provideAdapter(self, forInterface, providedInterface, maker, name=''):
        """see IGlobalAdapterService interface"""

        if not isinstance(maker, (list, tuple)):
            maker = [maker]
        else:
            maker = list(maker)

        if not maker == filter(callable, maker):
            raise TypeError("The registered component callable is not "
                            "callable")

        registry = self.__adapters.get(name)
        if registry is None:
            registry = AdapterRegistry()
            self.__adapters[name] = registry
        
        registry.register(forInterface, providedInterface, maker)

    def getAdapter(self, object, interface, name=''):
        """see IAdapterService interface"""
        result = self.queryAdapter(object, interface, None, name)
        if result is None:
            raise ComponentLookupError(object, interface)

        return result
    
    
    def queryAdapter(self, object, interface, default=None, name=''):
        """see IAdapterService interface"""
        if (not name) and interface.isImplementedBy(object):
            return object

        registry = self.__adapters.get(name)
        if registry is None:
            return default
        
        makers = registry.getForObject(object, interface)

        if makers is None:
            return default

        result = object
        for maker in makers:
            result = maker(result)

        return result

    def getRegisteredMatching(self,
                              for_interfaces=None,
                              provided_interfaces=None,
                              name = None,
                              ):

        if name is not None:
            registry = self.__adapters.get(name)
            if registry is None:
                return ()
            return [(name, for_, provided, data)
                    for (for_, provided, data)
                    in registry.getRegisteredMatching(for_interfaces,
                                                      provided_interfaces)
                    ]

        result = []
        for name in self.__adapters:
            r = self.getRegisteredMatching(
                for_interfaces, provided_interfaces, name)
            result.extend(r)

        return result

    _clear = __init__

# the global adapter service instance (see component.zcml )
adapterService = GlobalAdapterService()
provideAdapter = adapterService.provideAdapter



_clear = adapterService._clear

# Register our cleanup with Testing.CleanUp to make writing unit tests simpler.
from zope.testing.cleanup import addCleanUp
addCleanUp(_clear)
del addCleanUp


=== Added File Zope3/src/zope/component/contextdependent.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
# 
##############################################################################
"""

$Id: contextdependent.py,v 1.1.2.1 2002/12/23 19:32:40 jim Exp $
"""

from zope.component.interfaces import IContextDependent

class ContextDependent(object):
    """standard boilerplate for context dependent objects"""

    __implements__ = IContextDependent

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



=== Added File Zope3/src/zope/component/exceptions.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
# 
##############################################################################

from zope.exceptions import NotFoundError

class ComponentLookupError(NotFoundError):
    "A component could not be found"

class Invalid(Exception):
    """A component doesn't satisfy a promise
    """

class Misused(Exception):
    """A component is being used (registered) for the wrong interface
    """


=== Added File Zope3/src/zope/component/factory.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
# 
##############################################################################
"""factory service
"""


from zope.interface.verify import verifyObject
from zope.component.interfaces import IFactory
from zope.component.interfaces import IFactoryService
from zope.component.exceptions import ComponentLookupError

class IGlobalFactoryService(IFactoryService):

    def provideFactory(name, factory):
        """Provide a factory for the given name.
        """

class GlobalFactoryService:
    
    __implements__ = IGlobalFactoryService
    
    def __init__(self):
        self.__factories={}

    def provideFactory(self, name, factory):
        """See IGlobalFactoryService interface"""
        verifyObject(IFactory, factory)
        self.__factories[name] = factory

    def createObject(self, name, *args, **kwargs):
        """See IFactoryService interface"""
        try:
            return self.__factories[name](*args, **kwargs)
        except KeyError:
            raise ComponentLookupError(name)

    def getFactory(self, name):
        """See IFactoryService interface"""
        try:
            return self.__factories[name]
        except KeyError:
            raise ComponentLookupError(name)

    def queryFactory(self, name, default=None):
        """See IFactoryService interface"""
        return self.__factories.get(name, default)
    
    def getInterfaces(self, name):
        """See IFactoryService interface"""
        try: return self.__factories[name].getInterfaces()
        except KeyError:
            raise ComponentLookupError(name)

    _clear = __init__

# the global factory service instance (see component.zcml )
factoryService = GlobalFactoryService()
provideFactory = factoryService.provideFactory



_clear         = factoryService._clear

# Register our cleanup with Testing.CleanUp to make writing unit tests simpler.
from zope.testing.cleanup import addCleanUp
addCleanUp(_clear)
del addCleanUp


=== Added File Zope3/src/zope/component/interfaces.py === (475/575 lines abridged)
##############################################################################
#
# Copyright (c) 2001, 2002 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.
# 
##############################################################################
"""

$Id: interfaces.py,v 1.1.2.1 2002/12/23 19:32:40 jim Exp $
"""

from zope.interface import Interface

class IFactoryService(Interface):

    def createObject(name, *args, **kwargs):
        """Create a new object using the factory with the given name,
        passing all remaining arguments to the factory transparently.

        A Zope.ComponentArchitecture.ComponentLookupError will be
        raised if the factory component can't be found.
        """

    def getFactory(name):
        """Return a registered factory

        A Zope.ComponentArchitecture.ComponentLookupError will be
        raised if the factory component can't be found.
        """

    def queryFactory(name, default=None):
        """Return a registered factory
        """

    def getInterfaces(name):
        """returns the interface or interface tuple that
        object instances created by the named factory will implement."""
    


"""Interface for Factory objects."""



[-=- -=- -=- 475 lines omitted -=- -=- -=-]

$Id: interfaces.py,v 1.1.2.1 2002/12/23 19:32:40 jim Exp $
"""

from zope.interface import Interface

class IPresentationRequest(Interface):
    """An IPresentationRequest provides methods for getting view meta data.
    """

    def getPresentationType():
        """Get a view type

        The view type is expressed as an interface, as would be passed
        to IViewService.getView.
        """

    def getPresentationSkin():
        """Get the skin to be used for a request.

        The skin is a string as would be passed
        to IViewService.getView.
        """


"""

$Id: interfaces.py,v 1.1.2.1 2002/12/23 19:32:40 jim Exp $
"""

from zope.interface import Interface



class IView(IPresentation, IContextDependent):
    """Views provide a connection between an external actor and an object
    """

class IViewFactory(Interface):
    """Objects for creating views
    """

    def __call__(context, request):
        """Create an view (IView) object

        The context aregument is the object displayed by the view. The
        request argument is an object, such as a web request, that
        "stands in" for the user.
        """

    


=== Added File Zope3/src/zope/component/resource.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
# 
##############################################################################
"""

$Id: resource.py,v 1.1.2.1 2002/12/23 19:32:40 jim Exp $
"""

from zope.interface.implementor import ImplementorRegistry
from zope.component.exceptions import ComponentLookupError
from zope.component import getSkin
from zope.component.interfaces import IResourceService

class IGlobalResourceService(IResourceService):

    def provideResource(name, type, factory, layer='default'):
        """Provide a resource

        A resource is an inependent component that provides a view
        type.  It is like a view except that it acts by itself,
        typically to support views. Common resources include images,
        style sheets, etc.

        Arguments:

        name -- The resource name

        type -- The resource type, expressed as an interface

        factory -- an IResourceFactory that computes a resource.

        layer -- Optional skin layer. Layers are used to define skins.
        """

class GlobalResourceService:

    def __init__(self):
        self.__layers = {}

    __implements__ = IGlobalResourceService
        
    # Implementation methods for interface
    # Zope.ComponentArchitecture.IResourceService.

    def getResource(self, object, name, request):
        '''See interface IResourceService'''

        resource = self.queryResource(object, name, request)

        if resource is None:
            raise ComponentLookupError(object, name, type)

        return resource

    def queryResource(self, object, name, request, default=None):
        '''See interface IResourceService'''

        type = request.getPresentationType()
        skin = request.getPresentationSkin()

        for layername in getSkin(object, skin, type):
            layer = self.__layers.get(layername)
            if not layer: continue
            reg = layer.get(name, None)
            if reg is None: continue
            factory = reg.get(type)
            if factory is None:
                continue

            return factory(request)

        return default
        
        
    def provideResource(self, name, type, factory, layer='default'):
        '''See interface IGlobalResourceService'''

        resources = self.__layers.get(layer)
        if resources is None:
            resources = self.__layers[layer] = {}

        reg = resources.get(name, None)
        if reg is None:
            reg = resources[name] = ImplementorRegistry()

        reg.register(type, factory)

    _clear = __init__
    
resourceService = GlobalResourceService()
provideResource = resourceService.provideResource
_clear             = resourceService._clear


# Register our cleanup with Testing.CleanUp to make writing unit tests simpler.
from zope.testing.cleanup import addCleanUp
addCleanUp(_clear)
del addCleanUp


=== Added File Zope3/src/zope/component/service.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
# 
##############################################################################
"""

$Id: service.py,v 1.1.2.1 2002/12/23 19:32:40 jim Exp $
"""

from zope.exceptions import DuplicationError
from zope.component.interfaces import IServiceService
from zope.component.exceptions import ComponentLookupError


class IGlobalServiceManager(IServiceService):
    
    def defineService(name, interface):
        """Define a new service of the given name implementing the given
        interface.  If the name already exists, raises
        Zope.Exceptions.DuplicationError"""
    
    def provideService(name, component):
        """provide a service component to do the work of the named
        service.  If a service component has already been assigned to
        this name, raise Zope.Exceptions.DuplicationError; if the name
        has not been defined, raises
        Zope.ComponentArchitecture.GlobalServiceManager.UndefinedService;
        if the component does not implement the registered interface for
        the service name, raises
        Zope.ComponentArchitecture.GlobalServiceManager.InvalidService.
        """

class UndefinedService(Exception):
    """An attempt to register a service that has not been defined
    """

class InvalidService(Exception):
    """An attempt to register a service that doesn't implement
       the required interface
    """
    
class GlobalServiceManager:
    """service manager"""

    __implements__ = IGlobalServiceManager

    def __init__(self):
        self.__defs     = {}
        self.__services = {}
    
    def defineService(self, name, interface):
        """see IGlobalServiceManager interface"""

        if name in self.__defs:
            raise DuplicationError(name)

        self.__defs[name] = interface

    def getServiceDefinitions(self):
        """see IServiceService Interface"""
        return self.__defs.items()

    def provideService(self, name, component):
        """see IGlobalServiceManager interface, above"""

        if name in self.__services:
            raise DuplicationError(name)

        if name not in self.__defs:
            raise UndefinedService(name)

        if not self.__defs[name].isImplementedBy(component):
            raise InvalidService(name, component, self.__defs[name])

        self.__services[name] = component

    def getService(self, name):
        """see IServiceService interface"""
        service = self.queryService(name)
        if service is None:
            raise ComponentLookupError(name)

        return service

    def queryService(self, name, default=None):
        """see IServiceService interface"""

        return self.__services.get(name, default)

    _clear = __init__


serviceManager = GlobalServiceManager() # the global service manager instance
defineService = serviceManager.defineService


_clear         = serviceManager._clear

# Register our cleanup with Testing.CleanUp to make writing unit tests simpler.
from zope.testing.cleanup import addCleanUp
addCleanUp(_clear)
del addCleanUp


=== Added File Zope3/src/zope/component/skin.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
# 
##############################################################################
"""

$Id: skin.py,v 1.1.2.1 2002/12/23 19:32:40 jim Exp $
"""

from zope.interface.implementor import ImplementorRegistry
from zope.component.exceptions import ComponentLookupError
from zope.component.interfaces import ISkinService

class IGlobalSkinService(ISkinService):

    def defineSkin(name, view_type, layers):
        """Define a skin for a given view type as a sequence of layers

        There is a predefined skin, '', with a single layer, ''.
        """

_default = ('default',)

class GlobalSkinService:

    def __init__(self):
        self.__skins = {}

    __implements__ = IGlobalSkinService
        
    # Implementation methods for interface
    # Zope.ComponentArchitecture.ISkinService.

    def defineSkin(self, name, view_type, layers):
        '''See interface IGlobalSkinService'''
        
        reg = self.__skins.get(name, None)
        if reg is None:
            reg = self.__skins[name] = ImplementorRegistry()

        reg.register(view_type, layers)

    def getSkin(self, object, name, view_type):
        '''See interface ISkinService'''

        reg = self.__skins.get(name, None)
        if reg is not None:
            layers = reg.get(view_type)
            if layers is not None:
                return layers

        return _default

    _clear = __init__
    
skinService = GlobalSkinService()



_clear     = skinService._clear

# Register our cleanup with Testing.CleanUp to make writing unit tests simpler.
from zope.testing.cleanup import addCleanUp
addCleanUp(_clear)
del addCleanUp


=== Added File Zope3/src/zope/component/utility.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
# 
##############################################################################
"""utility service

$Id: utility.py,v 1.1.2.1 2002/12/23 19:32:40 jim Exp $
"""

from zope.interface.implementor import ImplementorRegistry
from zope.component.interfaces import IUtilityService
from zope.component.exceptions import ComponentLookupError

class IGlobalUtilityService(IUtilityService):

    def provideUtility(providedInterface, component, name=''):
        """Provide a utility

        A utility is a component that provides an interface.
        """

class GlobalUtilityService:
    
    __implements__=IGlobalUtilityService
    
    def __init__(self):
        self.__utilities = {}

    def provideUtility(self, providedInterface, component, name=''):
        """See IGlobalUtilityService interface"""

        if not providedInterface.isImplementedBy(component):
            raise Invalid("The registered component doesn't implement "
                          "the promised interface.")

        registry = self.__utilities.get(name)
        if registry is None:
            registry = ImplementorRegistry()
            self.__utilities[name] = registry
        
        registry.register(providedInterface, component)

    def getUtility(self, interface, name=''):
        """See IUtilityService interface"""
        c = self.queryUtility(interface, None, name)
        if c is None:
            raise ComponentLookupError(interface)
        return c

    def queryUtility(self, interface, default=None, name=''):
        """See IUtilityService interface"""

        registry = self.__utilities.get(name)
        if registry is None:
            return default

        c = registry.get(interface)
        if c is None:
            c = default

        return c
    
    _clear = __init__

# the global utility service instance (see component.zcml )
utilityService = GlobalUtilityService()




_clear         = utilityService._clear

# Register our cleanup with Testing.CleanUp to make writing unit tests simpler.
from zope.testing.cleanup import addCleanUp
addCleanUp(_clear)
del addCleanUp


=== Added File Zope3/src/zope/component/view.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
# 
##############################################################################
"""

$Id: view.py,v 1.1.2.1 2002/12/23 19:32:40 jim Exp $
"""

from zope.interface.adapter import AdapterRegistry
from zope.component.exceptions import ComponentLookupError
from zope.component import getSkin
from zope.component.interfaces import IViewService
from zope.exceptions import NotFoundError

class IGlobalViewService(IViewService):
    
    def setDefaultViewName(i_required, i_provided, name):
        '''Add name to our registry of default view names for
           the interfaces given.
        '''
        
    def provideView(forInterface, name, type, factory, layer='default'):
        """Register a view factory

        The factory is a sequence. The last object in the sequence
        must be an IViewFactory. The other objects in the sequence
        must be adapter factories.
        """

class GlobalViewService:

    __implements__ = IGlobalViewService

    def __init__(self):
        self.__layers = {}
        self.__default_view_names = AdapterRegistry()

    def setDefaultViewName(self, i_required, i_provided, name):
        self.__default_view_names.register(i_required,
                                           i_provided,
                                           name)

    def getView(self, object, name, request):
        '''See interface IViewService'''
        view = self.queryView(object, name, request)
        if view is None:
            raise ComponentLookupError(object, name, type)
        return view

    def queryView(self, object, name, request, default=None):
        '''See interface IViewService'''

        type = request.getPresentationType()
        skin = request.getPresentationSkin()

        for layername in getSkin(object, skin, type):
            layer = self.__layers.get(layername)
            if not layer:
                continue

            reg = layer.get(name, None)
            if reg is None:
                continue

            makers = reg.getForObject(object, type)
            if not makers:
                continue

            result = object
            for maker in makers[:-1]:
                result = maker(result)

            return makers[-1](result, request)

        return default
        
        
    def provideView(self, forInterface, name, type, maker, layer='default'):
        '''See interface IGlobalViewService'''

        views = self.__layers.get(layer)
        if views is None:
            views = self.__layers[layer] = {}

        reg = views.get(name, None)
        if reg is None:
            reg = views[name] = AdapterRegistry()

        if not isinstance(maker, (list, tuple)):
            maker = [maker]
        else:
            maker = list(maker)

        if not maker == filter(callable, maker):
            raise TypeError("The registered component callable is not "
                            "callable")

        reg.register(forInterface, type, maker)

    def getDefaultViewName(self, object, request):
        '''See interface IViewService'''

        name = self.queryDefaultViewName(object, request)

        if name is None:
            raise NotFoundError, \
                  'No default view name found for object %s' % object

        return name

    def queryDefaultViewName(self, object, request, default=None):
        '''See interface IViewService'''

        type = request.getPresentationType()
        name = self.__default_view_names.getForObject(object, type)

        if name is None:
            name = default

        return name

    def all(self):
        return self.__layers

    _clear = __init__
    
viewService = GlobalViewService()
provideView = viewService.provideView
setDefaultViewName = viewService.setDefaultViewName
_clear         = viewService._clear


# Register our cleanup with Testing.CleanUp to make writing unit tests simpler.
from zope.testing.cleanup import addCleanUp
addCleanUp(_clear)
del addCleanUp