avoid loops
[debian/gnuradio] / grc / python / Port.py
1 """
2 Copyright 2008, 2009 Free Software Foundation, Inc.
3 This file is part of GNU Radio
4
5 GNU Radio Companion is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
9
10 GNU Radio Companion is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18 """
19
20 from .. base.Port import Port as _Port
21 import Constants
22
23 def _get_source_from_virtual_sink_port(vsp):
24         """
25         Resolve the source port that is connected to the given virtual sink port.
26         Use the get source from virtual source to recursively resolve subsequent ports. 
27         """
28         try: return _get_source_from_virtual_source_port(
29                 vsp.get_enabled_connections()[0].get_source())
30         except: raise Exception, 'Could not resolve source for virtual sink port %s'%vsp
31
32 def _get_source_from_virtual_source_port(vsp, traversed=[]):
33         """
34         Recursively resolve source ports over the virtual connections.
35         Keep track of traversed sources to avoid recursive loops.
36         """
37         if not vsp.is_virtual_source(): return vsp
38         if vsp in traversed: raise Exception, 'Loop found when resolving virtual source %s'%vsp
39         try: return _get_source_from_virtual_source_port(
40                 _get_source_from_virtual_sink_port(
41                         filter(
42                                 lambda vs: vs.get_param('stream_id').get_value() == vsp.get_parent().get_param('stream_id').get_value(),
43                                 filter(
44                                         lambda b: b.get_key() == 'virtual_sink',
45                                         vsp.get_parent().get_parent().get_enabled_blocks(),
46                                 ),
47                         )[0].get_sink(vsp.get_key())
48                 ), traversed + [vsp],
49         )
50         except: raise Exception, 'Could not resolve source for virtual source port %s'%vsp
51
52 class Port(_Port):
53
54         ##possible port types
55         TYPES = ['complex', 'float', 'int', 'short', 'byte', 'msg']
56
57         def __init__(self, block, n, dir):
58                 """
59                 Make a new port from nested data.
60                 @param block the parent element
61                 @param n the nested odict
62                 @param dir the direction
63                 """
64                 self._n = n
65                 if n['type'] == 'msg': n['key'] = 'msg'
66                 if dir == 'source' and not n.find('key'):
67                         n['key'] = str(block._source_count)
68                         block._source_count += 1
69                 if dir == 'sink' and not n.find('key'):
70                         n['key'] = str(block._sink_count)
71                         block._sink_count += 1
72                 #build the port
73                 _Port.__init__(
74                         self,
75                         block=block,
76                         n=n,
77                         dir=dir,
78                 )
79                 self._nports = n.find('nports') or ''
80                 self._vlen = n.find('vlen') or ''
81                 self._optional = bool(n.find('optional'))
82
83         def validate(self):
84                 _Port.validate(self)
85                 try: assert self.get_enabled_connections() or self.get_optional()
86                 except AssertionError: self.add_error_message('Port is not connected.')
87                 try: assert self.is_source() or len(self.get_enabled_connections()) <= 1
88                 except AssertionError: self.add_error_message('Port has too many connections.')
89                 #message port logic
90                 if self.get_type() == 'msg':
91                         try: assert not self.get_nports()
92                         except AssertionError: self.add_error_message('A port of type "msg" cannot have "nports" set.')
93                         try: assert self.get_vlen() == 1
94                         except AssertionError: self.add_error_message('A port of type "msg" must have a "vlen" of 1.')
95
96         def rewrite(self):
97                 """
98                 Handle the port cloning for virtual blocks.
99                 """
100                 _Port.rewrite(self)
101                 if self.is_virtual_sink() or self.is_virtual_source():
102                         try: #clone type and vlen
103                                 source = self.resolve_virtual_source()
104                                 self._type = str(source.get_type())
105                                 self._vlen = str(source.get_vlen())
106                         except: #reset type and vlen
107                                 self._type = ''
108                                 self._vlen = ''
109
110         def is_virtual_sink(self): return self.get_parent().get_key() == 'virtual_sink'
111         def is_virtual_source(self): return self.get_parent().get_key() == 'virtual_source'
112         def resolve_virtual_source(self):
113                 if self.is_virtual_sink(): return _get_source_from_virtual_sink_port(self)
114                 if self.is_virtual_source(): return _get_source_from_virtual_source_port(self)
115
116         def get_vlen(self):
117                 """
118                 Get the vector length.
119                 If the evaluation of vlen cannot be cast to an integer, return 1.
120                 @return the vector length or 1
121                 """
122                 vlen = self.get_parent().resolve_dependencies(self._vlen)
123                 try: return int(self.get_parent().get_parent().evaluate(vlen))
124                 except: return 1
125
126         def get_nports(self):
127                 """
128                 Get the number of ports.
129                 If already blank, return a blank
130                 If the evaluation of nports cannot be cast to an integer, return 1.
131                 @return the number of ports or 1
132                 """
133                 nports = self.get_parent().resolve_dependencies(self._nports)
134                 #return blank if nports is blank
135                 if not nports: return ''
136                 try:
137                         nports = int(self.get_parent().get_parent().evaluate(nports))
138                         assert 0 < nports
139                         return nports
140                 except: return 1
141
142         def get_optional(self): return bool(self._optional)
143
144         def get_color(self):
145                 """
146                 Get the color that represents this port's type.
147                 Codes differ for ports where the vec length is 1 or greater than 1.
148                 @return a hex color code.
149                 """
150                 try:
151                         if self.get_vlen() == 1:
152                                 return {#vlen is 1
153                                         'complex': Constants.COMPLEX_COLOR_SPEC,
154                                         'float': Constants.FLOAT_COLOR_SPEC,
155                                         'int': Constants.INT_COLOR_SPEC,
156                                         'short': Constants.SHORT_COLOR_SPEC,
157                                         'byte': Constants.BYTE_COLOR_SPEC,
158                                         'msg': Constants.MSG_COLOR_SPEC,
159                                 }[self.get_type()]
160                         return {#vlen is non 1
161                                 'complex': Constants.COMPLEX_VECTOR_COLOR_SPEC,
162                                 'float': Constants.FLOAT_VECTOR_COLOR_SPEC,
163                                 'int': Constants.INT_VECTOR_COLOR_SPEC,
164                                 'short': Constants.SHORT_VECTOR_COLOR_SPEC,
165                                 'byte': Constants.BYTE_VECTOR_COLOR_SPEC,
166                         }[self.get_type()]
167                 except: return _Port.get_color(self)
168
169         def copy(self, new_key=None):
170                 n = self._n.copy()
171                 if new_key: n['key'] = new_key
172                 return self.__class__(self.get_parent(), n, self._dir)