Commit 5428380b authored by eric pellegrini's avatar eric pellegrini

Relocated the DataController and updated the dependencies

parent 6065ccb0
......@@ -28,7 +28,6 @@
This package contains all the externals dependencies of MDANSE. It contains:
#. magnitude: a package for handling units
#. pubsub: a package that implements the publisher subscriber mechanism
#. pyparsing: a package for creating and executing simple grammar
#. svgfig: a package for handling SVG file format
......
Copyright (c) since 2006, Oliver Schoenborn
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
For PyPubSub v3.3.0
^^^^^^^^^^^^^^^^^^^^^
* cleanup low-level API: exception classes, moved some out of pub module that did not
belong there (clutter), move couple modules,
* completed the reference documentation
* support installation via pip
* follow some guidelines in some PEPs such as PEP 396 and PEP 8
* support Python 2.6, 2.7, and 3.2 to 3.4a4 but drop support for Python <= 2.5
For PyPubSub v3.2.0
^^^^^^^^^^^^^^^^^^^
This is a minor release for small improvements made (see docs/CHANGELOG.txt)
based on feedback from user community. In particular an XML reader for
topic specification contributed by Josh English. Also cleaned up the
documentation, updated the examples folder (available in source distribution
as well as `online`_).
.. _online: https://sourceforge.net/p/pubsub/code/HEAD/tree/
Only 3 changes to API (function names):
* renamed pub.getDefaultRootAllTopics to pub.getDefaultTopicTreeRoot
* removed pub.importTopicTree: use pub.addTopicDefnProvider(source, format)
* renamed pub.exportTopicTree to pub.exportTopicTreeSpec
Oliver Schoenborn
September 2013
PyPubSub 3.1.2
^^^^^^^^^^^^^^^^
This is a minor release for small improvements made (see docs/CHANGELOG.txt)
based on feedback from user community. Also extended the documentation. See
pubsub.sourceforge.net for installation and usage. See the examples folder for
some useful examples.
Oliver Schoenborn
Nov 2011
PyPubSub 3.1.1b1
^^^^^^^^^^^^^^^^^^
Docs updated.
Oliver Schoenborn
May 2010
For PyPubSub v3.1.0b1
^^^^^^^^^^^^^^^^^^^^^^
Major cleanup of the API since 3.0 and better support
for the legacy wxPython code. Defining a topic tree
via a text file has been improved drastically, making it
simpler to document topic messages and payload data
required or optional. More examples have been added,
and the messaging protocols clarified.
The included docs are not yet updated, that's what I'm
working on now and will lead to the 3.1.1b1 release.
I'm also working on an add-on module that would allow
two applications to communicate over the network using
pubsub-type messaging (with topics, etc). The design
is almost complete.
Oliver Schoenborn
Jan 2010
\ No newline at end of file
"""
Pubsub package initialization.
:copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved.
:license: BSD, see LICENSE_BSD_Simple.txt for details.
"""
_PREVIOUS_RELEASE_DATE = "2013-09-15"
_PREVIOUS_RELEASE_VER = "3.2.1b"
__version__ = "3.3.0"
__all__ = [
'pub',
'utils',
'setupkwargs',
'setuparg1',
'__version__'
]
"""
Core package of pubsub, holding the publisher, listener, and topic
object modules. Functions defined here are used internally by
pubsub so that the right modules can be found later, based on the
selected messaging protocol.
Indeed some of the API depends on the messaging
protocol used. For instance sendMessage(), defined in publisher.py,
has a different signature (and hence implementation) for the kwargs
protocol than for the arg1 protocol.
The most convenient way to
support this is to put the parts of the package that differ based
on protocol in separate folder, and add one of those folders to
the package's __path__ variable (defined automatically by the Python
interpreter when __init__.py is executed). For instance, code
specific to the kwargs protocol goes in the kwargs folder, and code
specific to the arg1 protocol in the arg1 folder. Then when doing
"from pubsub.core import listener", the correct listener.py will be
found for the specified protocol. The default protocol is kwargs.
Only one protocol can be used in an application. The default protocol,
if none is chosen by user, is kwargs, as selected by the call to
_prependModulePath() at end of this file.
:copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved.
:license: BSD, see LICENSE_BSD_Simple.txt for details.
"""
def _prependModulePath(extra):
"""Insert extra at beginning of package's path list. Should only be
called once, at package load time, to set the folder used for
implementation specific to the default message protocol."""
corepath = __path__
initpyLoc = corepath[-1]
import os
corepath.insert(0, os.path.join(initpyLoc, extra))
# add appropriate subdir for protocol-specific implementation
from .. import policies
_prependModulePath(policies.msgDataProtocol)
from .publisher import Publisher
from .callables import (
AUTO_TOPIC,
)
from .listener import (
Listener,
getID as getListenerID,
ListenerMismatchError,
IListenerExcHandler,
)
from .topicobj import (
Topic,
SenderMissingReqdMsgDataError,
SenderUnknownMsgDataError,
MessageDataSpecError,
TopicDefnError,
ExcHandlerError,
)
from .topicmgr import (
TopicManager,
TopicDefnError,
TopicNameError,
ALL_TOPICS,
)
from .topicdefnprovider import (
ITopicDefnProvider,
TopicDefnProvider,
ITopicDefnDeserializer,
UnrecognizedSourceFormatError,
exportTopicTreeSpec,
TOPIC_TREE_FROM_MODULE,
TOPIC_TREE_FROM_STRING,
TOPIC_TREE_FROM_CLASS,
)
from .topictreetraverser import (
TopicTreeTraverser,
)
from .notificationmgr import (
INotificationHandler,
)
\ No newline at end of file
"""
This is not really a package init file, it is only here to simplify the
packaging and installation of pubsub.core's protocol-specific subfolders
by setuptools. The python modules in this folder are automatically made
part of pubsub.core via pubsub.core's __path__. Hence, this should not
be imported directly, it is part of pubsub.core when the messaging
protocol is "arg1" (and not usable otherwise).
:copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved.
:license: BSD, see LICENSE_BSD_Simple.txt for details.
"""
msg = 'Should not import this directly, used by pubsub.core if applicable'
raise RuntimeError(msg)
\ No newline at end of file
"""
:copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved.
:license: BSD, see LICENSE_BSD_Simple.txt for details.
"""
from .listenerbase import (ListenerBase, ValidatorBase)
from .callables import ListenerMismatchError
from .. import policies
class Message:
"""
A simple container object for the two components of a topic messages
in the pubsub legacy API: the
topic and the user data. An instance of Message is given to your
listener when called by sendMessage(topic). The data is accessed
via the 'data' attribute, and can be type of object.
"""
def __init__(self, topicNameTuple, data):
self.topic = topicNameTuple
self.data = data
def __str__(self):
return '[Topic: '+repr(self.topic)+', Data: '+repr(self.data)+']'
class Listener(ListenerBase):
"""
Wraps a callable so it can be stored by weak reference and introspected
to verify that it adheres to a topic's MDS.
A Listener instance has the same hash value as the callable that it wraps.
A callable will be given data when a message is sent to it. In the arg1
protocol only one object can be sent via sendMessage, it is put in a
Message object in its "data" field, the listener receives the Message
object.
"""
def __call__(self, actualTopic, data):
"""Call the listener with data. Note that it raises RuntimeError
if listener is dead. Should always return True (False would require
the callable_ be dead but self hasn't yet been notified of it...)."""
kwargs = {}
if self._autoTopicArgName is not None:
kwargs[self._autoTopicArgName] = actualTopic
cb = self._callable()
if cb is None:
self._calledWhenDead()
msg = Message(actualTopic.getNameTuple(), data)
cb(msg, **kwargs)
return True
class ListenerValidator(ValidatorBase):
"""
Accept one arg or *args; accept any **kwarg,
and require that the Listener have at least all the kwargs (can
have extra) of Topic.
"""
def _validateArgs(self, listener, paramsInfo):
# accept **kwargs
# accept *args
# accept any keyword args
if (paramsInfo.getAllArgs() == ()) and paramsInfo.acceptsAllUnnamedArgs:
return
if paramsInfo.getAllArgs() == ():
msg = 'Must have at least one parameter (any name, with or without default value, or *arg)'
raise ListenerMismatchError(msg, listener, [])
assert paramsInfo.getAllArgs()
#assert not paramsInfo.acceptsAllUnnamedArgs
# verify at most one required arg
numReqdArgs = paramsInfo.numRequired
if numReqdArgs > 1:
allReqd = paramsInfo.getRequiredArgs()
msg = 'only one of %s can be a required agument' % (allReqd,)
raise ListenerMismatchError(msg, listener, allReqd)
# if no required args but listener has *args, then we
# don't care about anything else:
if numReqdArgs == 0 and paramsInfo.acceptsAllUnnamedArgs:
return
# if no policy set, any name ok; otherwise validate name:
needArgName = policies.msgDataArgName
firstArgName = paramsInfo.allParams[0]
if (needArgName is not None) and firstArgName != needArgName:
msg = 'listener arg name must be "%s" (is "%s")' % (needArgName, firstArgName)
effTopicArgs = [needArgName]
raise ListenerMismatchError(msg, listener, effTopicArgs)
"""
Mixin for publishing messages to a topic's listeners. This will be
mixed into topicobj.Topic so that a user can use a Topic object to
send a message to the topic's listeners via a publish() method.
:copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved.
:license: BSD, see LICENSE_BSD_Simple.txt for details.
"""
from .publisherbase import PublisherBase
class Publisher(PublisherBase):
"""
Publisher that allows old-style Message.data messages to be sent
to listeners. Listeners take one arg (required, unless there is an
*arg), but can have kwargs (since they have default values).
"""
def sendMessage(self, topicName, data=None):
"""Send message of type topicName to all subscribed listeners,
with message data. If topicName is a subtopic, listeners
of topics more general will also get the message.
Note that any listener that lets a raised exception escape will
interrupt the send operation, unless an exception handler was
specified via pub.setListenerExcHandler().
"""
topicMgr = self.getTopicMgr()
topicObj = topicMgr.getOrCreateTopic(topicName)
# don't care if topic not final: topicObj.getListeners()
# will return nothing if not final but notification will still work
topicObj.publish(data)
def getMsgProtocol(self):
return 'arg1'
"""
Mixin for publishing messages to a topic's listeners. This will be
mixed into topicobj.Topic so that a user can use a Topic object to
send a message to the topic's listeners via a publish() method.
Note that it is important that the PublisherMixin NOT modify any
state data during message sending, because in principle it could
happen that a listener causes another message of same topic to be
sent (presumably, the listener has a way of preventing infinite
loop).
:copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved.
:license: BSD, see LICENSE_BSD_Simple.txt for details.
"""
class PublisherMixin:
def __init__(self):
pass
def publish(self, data=None):
self._publish(data)
############## IMPLEMENTATION ###############
def _mix_prePublish(self, data, topicObj=None, iterState=None):
"""Called just before the __sendMessage, to perform any argument
checking, set iterState, etc"""
return None
def _mix_callListener(self, listener, data, iterState):
"""Send the data to given listener."""
listener(self, data)
"""
:copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved.
:license: BSD, see LICENSE_BSD_Simple.txt for details.
"""
import weakref
from .topicutils import WeakNone
class SenderMissingReqdMsgDataError(RuntimeError):
"""
Ignore: Not used for this message protocol.
"""
pass
class SenderUnknownMsgDataError(RuntimeError):
"""
Ignore: Not used for this message protocol.
"""
pass
class ArgsInfo:
"""
Encode the Message Data Specification (MDS) for a given
topic. In the arg1 protocol of pubsub, this MDS is the same for all
topics, so this is quite a simple class, required only because
the part of pubsub that uses ArgsInfos supports several API
versions using one common API. So the only difference between
an ArgsInfo and an ArgSpecGiven is that ArgsInfo refers to
parent topic's ArgsInfo; other data members are the same.
Note that the MDS is always complete because it is known:
it consists of one required argument named 'data' and no
optional arguments.
"""
SPEC_MISSING = 10 # no args given
SPEC_COMPLETE = 12 # all args, but not confirmed via user spec
def __init__(self, topicNameTuple, specGiven, parentArgsInfo):
self.__argsDocs = specGiven.argsDocs or {'data':'message data'}
self.argsSpecType = self.SPEC_COMPLETE
self.allOptional = () # list of topic message optional argument names
self.allRequired = ('data',) # list of topic message required argument names
self.parentAI = WeakNone()
if parentArgsInfo is not None:
self.parentAI = weakref.ref(parentArgsInfo)
def isComplete(self):
return True
def getArgs(self):
return self.allOptional + self.allRequired
def numArgs(self):
return len(self.allOptional) + len(self.allRequired)
def getArgsDocs(self):
return self.__argsDocs.copy()
"""
The root topic of all topics is different based on messaging protocol.
:copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved.
:license: BSD, see LICENSE_BSD_Simple.txt for details.
"""
from .. import policies
def getRootTopicSpec():
"""If using "arg1" messaging protocol, then root topic has one arg;
if policies.msgDataArgName is something, then use it as arg name."""
argName = policies.msgDataArgName or 'data'
argsDocs = {argName : 'data for message sent'}
reqdArgs = (argName,)
return argsDocs, reqdArgs
"""
Low level functions and classes related to callables.
The AUTO_TOPIC
is the "marker" to use in callables to indicate that when a message
is sent to those callables, the topic object for that message should be
added to the data sent via the call arguments. See the docs in
CallArgsInfo regarding its autoTopicArgName data member.
:copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved.
:license: BSD, see LICENSE_BSD_Simple.txt for details.
"""
from inspect import getargspec, ismethod, isfunction
from .. import py2and3
AUTO_TOPIC = '## your listener wants topic name ## (string unlikely to be used by caller)'
def getModule(obj):
"""Get the module in which an object was defined. Returns '__main__'
if no module defined (which usually indicates either a builtin, or
a definition within main script). """
if hasattr(obj, '__module__'):
module = obj.__module__
else:
module = '__main__'
return module
def getID(callable_):
"""Get name and module name for a callable, ie function, bound
method or callable instance, by inspecting the callable. E.g.
getID(Foo.bar) returns ('Foo.bar', 'a.b') if Foo.bar was
defined in module a.b. """
sc = callable_
if ismethod(sc):
module = getModule(sc.__self__)
id = '%s.%s' % (sc.__self__.__class__.__name__, sc.__func__.__name__)
elif isfunction(sc):
module = getModule(sc)
id = sc.__name__
else: # must be a functor (instance of a class that has __call__ method)
module = getModule(sc)
id = sc.__class__.__name__
return id, module
def getRawFunction(callable_):
"""Given a callable, return (offset, func) where func is the
function corresponding to callable, and offset is 0 or 1 to
indicate whether the function's first argument is 'self' (1)
or not (0). Raises ValueError if callable_ is not of a
recognized type (function, method or has __call__ method)."""
firstArg = 0
if isfunction(callable_):
#print 'Function', getID(callable_)
func = callable_
elif ismethod(callable_):
#print 'Method', getID(callable_)
func = callable_
if func.__self__ is not None:
# Method is bound, don't care about the self arg
firstArg = 1
elif hasattr(callable_, '__call__'):
#print 'Functor', getID(callable_)
func = callable_.__call__
firstArg = 1 # don't care about the self arg
else:
msg = 'type "%s" not supported' % type(callable_).__name__
raise ValueError(msg)
return func, firstArg
class ListenerMismatchError(ValueError):
"""
Raised when an attempt is made to subscribe a listener to
a topic, but listener does not satisfy the topic's message data
specification (MDS). This specification is inferred from the first
listener subscribed to a topic, or from an imported topic tree
specification (see pub.addTopicDefnProvider()).
"""
def __init__(self, msg, listener, *args):
idStr, module = getID(listener)
msg = 'Listener "%s" (from module "%s") inadequate: %s' % (idStr, module, msg)
ValueError.__init__(self, msg)
self.msg = msg
self.args = args
self.module = module
self.idStr = idStr
def __str__(self):
return self.msg
class CallArgsInfo:
"""
Represent the "signature" or protocol of a listener in the context of
topics.
"""
def __init__(self, func, firstArgIdx): #args, firstArgIdx, defaultVals, acceptsAllKwargs=False):
"""Inputs:
- Args and defaultVals are the complete set of arguments and
default values as obtained form inspect.getargspec();
- The firstArgIdx points to the first item in
args that is of use, so it is typically 0 if listener is a function,
and 1 if listener is a method.
- The acceptsAllKwargs should be true
if the listener has **kwargs in its protocol.
After construction,
- self.allParams will contain the subset of 'args' without first
firstArgIdx items,
- self.numRequired will indicate number of required arguments
(ie self.allParams[:self.numRequired] are the required args names);
- self.acceptsAllKwargs = acceptsAllKwargs
- self.autoTopicArgName will be the name of argument
in which to put the topic object for which pubsub message is
sent, or None. This is identified by the argument that has a
default value of AUTO_TOPIC.
For instance, listener(self, arg1, arg2=AUTO_TOPIC, arg3=None) will
have self.allParams = (arg1, arg2, arg3), self.numRequired=1, and
self.autoTopicArgName = 'arg2', whereas
listener(self, arg1, arg3=None) will have
self.allParams = (arg1, arg3), self.numRequired=1, and
self.autoTopicArgName = None."""
#args, firstArgIdx, defaultVals, acceptsAllKwargs
(allParams, varParamName, varOptParamName, defaultVals) = getargspec(func)
if defaultVals is None:
defaultVals = []
else:
defaultVals = list(defaultVals)
self.acceptsAllKwargs = (varOptParamName is not None)
self.acceptsAllUnnamedArgs = (varParamName is not None)
self.allParams = allParams
del self.allParams[0:firstArgIdx] # does nothing if firstArgIdx == 0
self.numRequired = len(self.allParams) - len(defaultVals)
assert self.numRequired >= 0
# if listener wants topic, remove that arg from args/defaultVals
self.autoTopicArgName = None
if defaultVals:
self.__setupAutoTopic(defaultVals)
def getAllArgs(self):
return tuple( self.allParams )
def getOptionalArgs(self):
return tuple( self.allParams[self.numRequired:] )
def getRequiredArgs(self):
"""Return a tuple of names indicating which call arguments
are required to be present when pub.sendMessage(...) is called. """
return tuple( self.allParams[:self.numRequired] )
def __setupAutoTopic(self, defaults):