File: signals.py

package info (click to toggle)
frescobaldi 1.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 4,240 kB
  • ctags: 2,434
  • sloc: python: 15,614; lisp: 28; sh: 25; makefile: 2
file content (178 lines) | stat: -rw-r--r-- 5,986 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008, 2009, 2010 by Wilbert Berendsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
# See http://www.gnu.org/licenses/ for more information.

"""
A simple signal/slot implementation.
"""

import inspect, weakref


class SignalInstance(object):
    """
    A simple implementation of the Signal/Slot pattern.
    
    To use, simply create a Signal instance. The instance may be a member
    of a class, a global, or a local; it makes no difference what scope
    it resides within. Connect slots to the signal using the "connect()"
    method. The slot may be a member of a class or a simple function.
    
    If the slot is a member of a class, Signal will automatically detect
    when the method's class instance has been deleted and remove it
    from its list of connected slots.
    
    Emit the signal (to call all connected slots) by simply invoking it.
    The order in which the slots are called is undetermined.
    """
    def __init__(self):
        self.functions = set()
        self.objects = weakref.WeakKeyDictionary()

    def __call__(self, *args, **kwargs):
        """ call all connected slots """
        # make copies because the sets might change...
        for func in set(self.functions):
            # if possible determine the number of arguments the function 
            # expects, and discard the superfluous arguments.
            try:
                func.func_code.co_argcount
            except AttributeError:
                func(*args, **kwargs)
            else:
                func(*args[:func.func_code.co_argcount], **kwargs)
        for obj, methods in self.objects.items():
            for func in set(methods):
                try:
                    func.func_code.co_argcount
                except AttributeError:
                    func(obj, *args, **kwargs)
                else:
                    func(obj, *args[:func.func_code.co_argcount-1], **kwargs)
            
    def connect(self, func):
        if inspect.ismethod(func):
            self.objects.setdefault(func.im_self, set()).add(func.im_func)
        else:
            self.functions.add(func)

    def disconnect(self, func):
        if inspect.ismethod(func):
            s = self.objects.get(func.im_self)
            if s is not None:
                s.discard(func.im_func)
        else:
            self.functions.discard(func)

    def clear(self):
        self.functions.clear()
        self.objects.clear()

    def disconnectObject(self, obj):
        """ Remove all connections that are methods of given object obj """
        try:
            del self.objects[obj]
        except KeyError:
            pass


class SignalInstanceFireOnce(SignalInstance):
    """
    Clears all connections after being invoked.
    """
    def __call__(self, *args, **kwargs):
        SignalInstance.__call__(self, *args, **kwargs)
        self.clear()


class SignalProxyInstance(object):
    """
    A Signal that dispatches method calls to connected objects.
    
    Call methods on this proxy object and the same method will be called
    on all connected objects with the same arguments.
    
    Attributes other than methods are not supported.
    Methods can't be named 'connect' or 'disconnect'.
    Return values are discarded.
    A SignalProxy keeps weak references to connected objects.
    """
    def __init__(self):
        self._objects = weakref.WeakKeyDictionary()
    
    def connect(self, obj):
        self._objects[obj] = True
        
    def disconnect(self, obj):
        try:
            del self._objects[obj]
        except KeyError:
            pass

    def __getattr__(self, attr):
        def func(*args, **kwargs):
            for obj in self._objects:
                getattr(obj, attr)(*args, **kwargs)
        func.func_name = attr
        setattr(self, attr, func)
        return func


class SignalBase(object):
    """Abstract base class for class level Signal and SignalProxy classes."""
    def __init__(self, doc=None):
        self.__doc__ = doc
        self.instances = weakref.WeakKeyDictionary()
        
    def __get__(self, instance, owner):
        if instance is None:
            return self
        try:
            return self.instances[instance]
        except KeyError:
            ret = self.instances[instance] = self.signalType()
            return ret


class Signal(SignalBase):
    """A class level Signal/Slot mechanism.
    
    Use an instance of Signal() as a class attribute, and it will automatically
    work on instances as soon as the attribute is accessed via the instance.
    
    If you create the Signal with fireOnce=True, all connections to the
    signal of the object instance will be cleared after being invoked.
    
    See SignalInstance and SignalInstanceFireOnce.
    """
    def __init__(self, doc=None, fireOnce=False):
        super(Signal, self).__init__(doc)
        self.signalType = SignalInstanceFireOnce if fireOnce else SignalInstance


class SignalProxy(SignalBase):
    """A class level Signal proxy.
    
    Add as a class attribute to a class and access it via an instance.
    A SignalProxyInstance instance will then be returned.
    
    See SignalProxyInstance.
    """
    signalType = SignalProxyInstance