Source

codeaide / codeaide / interface.py

Full commit
  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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# -*- coding: utf-8 -*-
import sys
import weakref
import inspect

DEBUG = False



class lazyproperty(object):


    def __init__(self, fget=None, fset=None, fdel=None, doc=''):
        for attr in ('fget', 'fset'):
            func = locals()[attr]
            if callable(func):
                setattr(self, attr, func.func_name)
        setattr(self, '__doc__', doc)


    def __get__(self, obj=None, type_=None):
        if not obj:
            return 'property'
        if self.fget:
            return getattr(obj, self.fget)()


    def __set__(self, obj, arg):
        if self.fset:
            return getattr(obj, self.fset)(arg)





class classproperty(object):

    def __init__(self, fget=None, fset=None, fdel=None, doc=None, name=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        self.__doc__ = doc
        self.name = name


    def __get__(self, obj, cls):
        fget = self.fget
        if issubclass(cls, Interface) and self.fget is None:
            cp = getattr(cls.find_implementation(), self.name)
            fget = cp.fget
        return fget(cls)


    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError, "can't set attribute"
        self.fset(obj, value)


    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError, "can't delete attribute"
        self.fdel(obj)





class Interface(type):

    __registered__ = {}


    class Error(Exception):
        pass
    class NotFoundError(Error):
        pass

    class __metaclass__(type):
        def __new__(cls, name, bases, attrs):
            if name != "Interface":
                attrs["__attributes__"] = [
                    attr_name for attr_name in attrs.keys() \
                    if not hasattr(Interface, attr_name) ]
            else:
                attrs["__attributes__"] = []
            for aname, avalue in attrs.items():
                if isinstance(avalue, classproperty):
                    avalue.name = aname

            attrs["__implementations__"] = []
            attrs["__objects__"] = []
            t = type.__new__(cls, name, bases, attrs)
            if name != "Interface":
                t.__registered__[name] = t
            return t


        def __getattr__(cls, name):
            impl = cls.find_implementation()
            return getattr(impl, name)


    def __new__(cls, *args, **kwargs):
        impl = cls.find_implementation()
        return cls.create(impl, *args, **kwargs)
    

    @classmethod
    def create(cls, impl, *args, **kwargs):
        class Destructor(object):
            def __init__(self):
                self.interfaces = []
            
            def __call__(self, obj):
                if DEBUG:
                    print "destruct", repr(obj), self.interfaces
                for iface in self.interfaces:
                    try:
                        iface.__objects__.remove(obj)
                    except: pass
        
        if DEBUG:
            print "%s.%s:%s.%s" % (
              cls.__module__, cls.__name__,
              impl.__module__, impl.__name__),
            l = []
            l.extend([repr(a) for a in args])
            l.extend(["%s=%r" % (k, v) for k, v in kwargs.items()])
            print "(%s)" % ",".join(l)

        obj = impl(*args, **kwargs)
        destruct = Destructor()
        ref = weakref.proxy(obj, destruct)
        for iface in impl.__interfaces__:
            iface.__objects__.append(ref)
            destruct.interfaces.append(iface)
            if DEBUG:
                print "adding", iface, "to", obj
        return obj
        

    
    @classmethod
    def attributes(cls):
        interfaces = [interface for interface in [cls]+cls.mro(cls) \
                      if issubclass(interface, Interface)]
        attribs = set()
        for interface in interfaces:
            for name in interface.__attributes__:
                if not callable(getattr(interface, name)):
                    attribs.add(name)
        return attribs


    @classmethod
    def callables(cls):
        interfaces = [interface for interface in [cls]+cls.mro(cls) \
                      if issubclass(interface, Interface)]
        attribs = set()
        for interface in interfaces:
            for name in interface.__attributes__:
                if callable(getattr(interface, name)):
                    attribs.add(name)
        return attribs

    
    @classproperty
    def objects(cls):
        return cls.__objects__

    
    @classproperty
    def instance(cls):
        return cls.__objects__[0]

    
    @classproperty
    def implementations(cls):
        l = []
        for i, impl in enumerate(cls.__implementations__):
            if isinstance(impl, tuple):
                name, context = impl
                impl = context[name]
                cls.__implementations__[i] = impl
            l.append(impl)
        return l

    
    @classmethod
    def create_implementations(cls, *args, **kwargs):
        l = []
        for impl in cls.implementations:
            l.append(cls.create(impl, *args, **kwargs))
        return l


    @classmethod
    def find_implementation(cls):
        try:
            return cls.implementations[-1]
        except IndexError, e:
            raise Interface.NotFoundError, "No implementation found"


    @classmethod
    def validate_interface(cls, impl, throw_exception=False):
        for attr in cls.attributes():
            try:
                getattr(impl, attr)
            except AttributeError:
                if throw_exception:
                    raise TypeError, "%s does not implement attribute %r of interface %s" % (impl, attr, cls)
                else:
                    return False
        for attr in cls.callables():
            try:
                method = getattr(impl, attr)
            except AttributeError:
                if throw_exception:
                    raise TypeError, "%s does not implement callable %r of interface %s" % (impl, attr, cls)
                else:
                    return False
        return True



def implements(*interfaces):
    frame = sys._getframe(1)
    class_name = frame.f_code.co_name
    context = sys._getframe(2).f_locals

    iface_classes = []
    for iface in interfaces:
        if isinstance(iface, basestring):
            iface = Interface.__registered__[iface]
        iface_classes.append(iface)
        iface.__implementations__.append((class_name, context))
    frame.f_locals.setdefault("__interfaces__", []).extend(iface_classes)


def register_interfaces(cls, *interfaces):
    iface_classes = []
    for iface in interfaces:
        if isinstance(iface, basestring):
            iface = Interface.__registered__[iface]
        iface_classes.append(iface)
        iface.__implementations__.append(cls)
    cls.__interfaces__ = getattr(cls, "__interfaces__", []) + iface_classes


    
    
def on_hook(hook_iface, *args, **kwargs):
    break_on_result = kwargs.pop("break_on_hook_result", True)
    for hook_class in hook_iface.implementations:
        hook = hook_class()
        result = hook.execute(*args, **kwargs)
        if result and break_on_result:
            return result

        
        


class _WeakMethod_FuncHost(object):

    def __init__(self, func):
        self.hostedFunction = func
    def func(self, *args, **kwargs):
        self.hostedFunction(*args, **kwargs)



class _WeakMethod(object):

    def __init__(self, f):
        self.f = f.im_func
        self.c = weakref.ref(f.im_self)


    def __call__(self, *args, **kwargs):
        obj = self.c()
        if obj == None : return
        self.f(obj, *args, **kwargs)

        
        
        
class Signal(object):

    block_all = False


    def __init__(self):
        self.slots = []
        # for keeping references to _WeakMethod_FuncHost objects.
        # If we didn't, then the weak references would die for
        # non-method slots that we've created.
        self.func_host = []
        self._blocked = False

    def set_blocked(self, flag):
        self._blocked = True

    def get_blocked(self):
        return self._blocked

    blocked = property(get_blocked, set_blocked)


    dispatcher = None

    
    def __call__(self, *args, **kwargs):
        cls = self.__class__
        if self._blocked or cls.block_all:
            return
        dispatcher = cls.dispatcher
        if dispatcher:
            dispatcher.sender = self
            call = dispatcher.send
        else:
            call = lambda func, *args, **kwargs: func(*args, **kwargs)
        for i, slot in enumerate(self.slots[:]):
            if slot is None:
                del self.slots[i]
            else:
                call(slot, *args, **kwargs)


    def connect(self, slot):
        self.disconnect(slot)
        if inspect.ismethod(slot):
            self.slots.append(_WeakMethod(slot))
        else:
            o = _WeakMethod_FuncHost(slot)
            self.slots.append(_WeakMethod(o.func))
            # we stick a copy in here just to keep the instance alive
            self.func_host.append(o)


    def __iadd__(self, slot):
        self.connect(slot)
        return self


    def disconnect(self, slot):
        try:
            for i, wm in enumerate(self.slots[:]):
                if inspect.ismethod(slot):
                    if wm.f == slot.im_func and wm.c() == slot.im_self:
                        del self.slots[i]
                        return
                else:
                    if wm.c().hostedFunction == slot:
                        del self.slots[i]
                        return
        except:
            pass


    def __isub__(self, slot):
        self.disconnect(slot)
        return self


    def disconnect_all(self):
        del self.slots
        del self.func_host
        self.slots = []
        self.func_host = []



class SignalMapper(object):


    def __init__(self, slot, *args, **kwargs):
        self.slot = slot
        self.args = args
        self.kwargs = kwargs


    def __call__(self, *args, **kwargs):
        args = self.args + args
        kwargs.update(self.kwargs)
        return self.slot(*args, **kwargs)




if __name__ == "__main__":
    class Greeting(Interface):
        def greet(self, name): pass

    class EastFrisian(object):
        implements(Greeting)
        def greet(self, name): return "moin " + name

    greeting = Greeting()
    print greeting
    print greeting.greet("world")