File size: 1,889 Bytes
3ea44ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from traceback import print_exc as debug

class Mode(object):
    def __init__(self):
        self.base = dict()

    def drive(self, event, *args):
        """ Spreads an event """
        try:
            item = self.base[event]
        except KeyError:
            pass
        else:
            for handle, data in item[:]:
                try:
        # We call the handle associated to event.
        # if it returns an iterator we just chain it.
                    seq = handle(self, *(args + data))
        # In case of not having an iterator we go on 
        # processing.
                    if not seq:
                        continue
        # It chains the iterator.
                    point = next(seq)
                    point(self, seq)
        # It stops processing handles linked to event.
                except Stop:
                    break
        # It stops all the sequence of events.
                except Kill, Root:
                    raise
                except StopIteration:
                    pass
        # It prints the exception. 
                except Exception:
                    debug()

    def link(self, event, handle, *args):
        """ Used to link a handle to an event """

        item = self.base.setdefault(event, list())
        item.append((handle, args))

    def unlink(self, event, handle, *args):
        """ Use args to unmap the handle """

        # It shouldnt have printed exceptions if the event 
        # doesnt exist since a call to spin.destroy()
        # would clear all the events and some handles
        # would try to unlinke themselves from the spin
        # it wouldnt be like a real problem.
        try:
            self.base[event].remove((handle, args))
        except KeyError:
            pass



class Stop(Exception):
    pass

class Root(Exception):
    pass

class Kill(Exception):
    pass