added rewrite methods to element to separate from validation logic
[debian/gnuradio] / grc / python / Block.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.Block import Block as _Block
21 import extract_docs
22 import extract_category
23
24 class Block(_Block):
25
26         ##for make source to keep track of indexes
27         _source_count = 0
28         ##for make sink to keep track of indexes
29         _sink_count = 0
30
31         def __init__(self, flow_graph, n):
32                 """
33                 Make a new block from nested data.
34                 @param flow graph the parent element
35                 @param n the nested odict
36                 @return block a new block
37                 """
38                 #grab the data
39                 self._doc = n.find('doc') or ''
40                 self._imports = map(lambda i: i.strip(), n.findall('import'))
41                 self._make = n.find('make')
42                 self._var_make = n.find('var_make')
43                 self._checks = n.findall('check')
44                 self._callbacks = n.findall('callback')
45                 #build the block
46                 _Block.__init__(
47                         self,
48                         flow_graph=flow_graph,
49                         n=n,
50                 )
51
52         def validate(self):
53                 """
54                 Validate this block.
55                 Call the base class validate.
56                 Evaluate the checks: each check must evaluate to True.
57                 """
58                 _Block.validate(self)
59                 #evaluate the checks
60                 for check in self._checks:
61                         check_res = self.resolve_dependencies(check)
62                         try:
63                                 check_eval = self.get_parent().evaluate(check_res)
64                                 try: assert check_eval
65                                 except AssertionError: self.add_error_message('Check "%s" failed.'%check)
66                         except: self.add_error_message('Check "%s" did not evaluate.'%check)
67
68         def rewrite(self):
69                 """
70                 Add and remove ports to adjust for the nports.
71                 """
72                 _Block.rewrite(self)
73                 #adjust nports
74                 for get_ports, get_port in (
75                         (self.get_sources, self.get_source),
76                         (self.get_sinks, self.get_sink),
77                 ):
78                         #how many streaming (non-message) ports?
79                         num_ports = len(filter(lambda p: p.get_type() != 'msg', get_ports()))
80                         #do nothing for 0 ports
81                         if not num_ports: continue
82                         #get the nports setting
83                         port0 = get_port(str(0))
84                         nports = port0.get_nports()
85                         #do nothing for no nports
86                         if not nports: continue
87                         #do nothing if nports is already num ports
88                         if nports == num_ports: continue
89                         #remove excess ports and connections
90                         if nports < num_ports:
91                                 #remove the connections
92                                 for key in map(str, range(nports, num_ports)):
93                                         port = get_port(key)
94                                         for connection in port.get_connections():
95                                                 self.get_parent().remove_element(connection)
96                                 #remove the ports
97                                 for key in map(str, range(nports, num_ports)):
98                                         get_ports().remove(get_port(key))
99                                 continue
100                         #add more ports
101                         if nports > num_ports:
102                                 for key in map(str, range(num_ports, nports)):
103                                         prev_port = get_port(str(int(key)-1))
104                                         get_ports().insert(
105                                                 get_ports().index(prev_port)+1,
106                                                 prev_port.copy(new_key=key),
107                                         )
108                                 continue
109
110         def port_controller_modify(self, direction):
111                 """
112                 Change the port controller.
113                 @param direction +1 or -1
114                 @return true for change
115                 """
116                 changed = False
117                 #concat the nports string from the private nports settings of both port0
118                 nports_str = \
119                         (self.get_sinks() and self.get_sinks()[0]._nports or '') + \
120                         (self.get_sources() and self.get_sources()[0]._nports or '')
121                 #modify all params whose keys appear in the nports string
122                 for param in self.get_params():
123                         if param.is_enum() or param.get_key() not in nports_str: continue
124                         #try to increment the port controller by direction
125                         try:
126                                 value = param.get_evaluated()
127                                 value = value + direction
128                                 assert 0 < value
129                                 param.set_value(value)
130                                 changed = True
131                         except: pass
132                 return changed
133
134         def get_doc(self):
135                 doc = self._doc.strip('\n').replace('\\\n', '')
136                 #merge custom doc with doxygen docs
137                 return '\n'.join([doc, extract_docs.extract(self.get_key())]).strip('\n')
138
139         def get_category(self):
140                 category = extract_category.extract(self.get_key())
141                 #if category: return category
142                 return _Block.get_category(self)
143
144         def get_imports(self):
145                 """
146                 Resolve all import statements.
147                 Split each import statement at newlines.
148                 Combine all import statments into a list.
149                 Filter empty imports.
150                 @return a list of import statements
151                 """
152                 return filter(lambda i: i, sum(map(lambda i: self.resolve_dependencies(i).split('\n'), self._imports), []))
153
154         def get_make(self): return self.resolve_dependencies(self._make)
155         def get_var_make(self): return self.resolve_dependencies(self._var_make)
156
157         def get_callbacks(self):
158                 """
159                 Get a list of function callbacks for this block.
160                 @return a list of strings
161                 """
162                 def make_callback(callback):
163                         callback = self.resolve_dependencies(callback)
164                         if 'self.' in callback: return callback
165                         return 'self.%s.%s'%(self.get_id(), callback)
166                 return map(make_callback, self._callbacks)