121827aa614033015a4891581d0838e1bb097e22
[nepi.git] / src / nepi / design / box.py
1 from neco.util import guid
2
3 guid_gen = guid.GuidGenerator()
4
5 class Attributes(object):
6     def __init__(self):
7         super(Attributes, self).__init__()
8         self._attributes = dict()
9
10     def __getattr__(self, name):
11         try:
12             return self._attributes[name]
13         except:
14             return super(Attributes, self).__getattribute__(name)
15
16     def __setattr__(self, name, value):
17         try:
18             if value == None:
19                 old = self._attributes[name]
20                 del self._attributes[name]
21                 return old
22
23             self._attributes[name] = value
24             return value
25         except:
26             return super(Attributes, self).__setattr__(name, value)
27
28 class Connections(object):
29     def __init__(self):
30         super(Connections, self).__init__()
31         self._connections = set()
32
33     def __getattr__(self, guid_or_label):
34         try:
35             for b in self._connections:
36                 if guid_or_label in [b.guid, b.label]:
37                     return b
38         except:
39             return super(Connections, self).__getattribute__(guid_or_label)
40
41 class Box(object):
42     def __init__(self, label = None, guid = None):
43         super(Box, self).__init__()
44         self._guid = guid_gen.next(guid)
45         self._a = Attributes()
46         self._c = Connections()
47         self._tags = set()
48         self.label = label or self._guid
49
50         # Graphical information to draw box
51         self.x = 0
52         self.y = 0
53         self.width = 4
54         self.height = 4
55
56     @property
57     def tags(self):
58         return self._tags
59
60     @property
61     def attributes(self):
62         return self._a._attributes.keys()
63
64     @property
65     def a(self):
66         return self._a
67
68     @property
69     def c(self):
70         return self._c
71
72     @property
73     def guid(self):
74         return self._guid
75
76     @property
77     def connections(self):
78         return set(self._c._connections)
79
80     def tadd(self, name):
81         self._tags.add(name)
82
83     def tdel(self, name):
84         self._tags.remove(name)
85
86     def thas(self, name):
87         return name in self._tags
88
89     def connect(self, box, cascade = True):
90         self._c._connections.add(box)
91         if cascade:
92             box.connect(self, cascade = False)
93
94     def disconnect(self, box, cascade = True):
95         self._c._connections.remove(box)
96         if cascade:
97             box.disconnect(self, cascade = False)
98
99     def is_connected(self, box):
100         return box in self.connections
101