another distcheck fix
[debian/gnuradio] / grc / src / grc / converter.py
1 """
2 Copyright 2008 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 ##@package grc.converter
20 #convert old flow graph file format to new format
21
22 from grc.Constants import FLOW_GRAPH_DTD
23 from grc import ParseXML, Utils
24 from grc.Utils import odict
25 from lxml import etree
26 import difflib
27 import os
28
29 def _make_param(key, value):
30         """!
31         Make a paramater dict from the key/value pair.
32         @param key the key
33         @param value the value
34         @return a dictionary object
35         """
36         param = odict()
37         param['key'] = key
38         param['value'] = value
39         return param
40
41 def _get_blocks(blocks, tag):
42         """!
43         Get a list of blocks with the tag.
44         @param blocks the old block list
45         @param tag the tag name
46         @retun a list of matching blocks
47         """
48         return filter(lambda b: b['tag'] == tag, blocks)
49
50 def _get_params(block):
51         """!
52         Get a list of params.
53         @param block the old block
54         @retun a list of params
55         """
56         params = Utils.exists_or_else(block, 'params', {}) or {}
57         params = Utils.listify(params, 'param')
58         return params
59
60 def _convert_id(id):
61         """!
62         Convert an old id to a new safe id.
63         Replace spaces with underscores.
64         Lower case the odl id.
65         @return the reformatted id
66         """
67         return id.lower().replace(' ', '_')
68
69 def convert(file_path, platform):
70         """!
71         Convert the flow graph to the new format.
72         Make a backup of the old file.
73         Save a reformated flow graph to the file path.
74         If this is a new format flow graph, do nothing.
75         @param file_path the path to the saved flow graph
76         @param platform the grc gnuradio platform
77         """
78         try: #return if file passes validation
79                 ParseXML.validate_dtd(file_path, FLOW_GRAPH_DTD)
80                 try:
81                         changed = False
82                         #convert instances of gui_coordinate and gui_rotation
83                         xml = etree.parse(file_path)
84                         for find, replace in (
85                                 ('gui_coordinate', '_coordinate'),
86                                 ('gui_rotation', '_rotation'),
87                         ):
88                                 keys = xml.xpath('/flow_graph/block/param[key="%s"]/key'%find)
89                                 for key in keys:
90                                         key.text = replace
91                                         changed = True
92                         if not changed: return
93                         #backup after successful conversion
94                         os.rename(file_path, file_path+'.bak')
95                         #save new flow graph to file path
96                         xml.write(file_path, xml_declaration=True, pretty_print=True)
97                 except Exception, e: print e
98                 return
99         except: pass #convert
100         ############################################################
101         # extract window size, variables, blocks, and connections
102         ############################################################
103         old_n = ParseXML.from_file(file_path)['flow_graph']
104         try: window_width = min(3*int(old_n['window_width'])/2, 2048)
105         except: window_width = 2048
106         try: window_height = min(3*int(old_n['window_height'])/2, 2048)
107         except: window_height = 2048
108         window_size = '%d, %d'%(window_width, window_height)
109         variables = Utils.exists_or_else(old_n, 'vars', {}) or {}
110         variables = Utils.listify(variables, 'var')
111         blocks = Utils.exists_or_else(old_n, 'signal_blocks', {}) or {}
112         blocks = Utils.listify(blocks, 'signal_block')
113         connections = Utils.exists_or_else(old_n, 'connections', {}) or {}
114         connections = Utils.listify(connections, 'connection')
115         #initialize new nested data
116         new_n = odict()
117         new_n['block'] = list()
118         new_n['connection'] = list()
119         ############################################################
120         # conversion - options block
121         ############################################################
122         #get name
123         about_blocks = _get_blocks(blocks, 'About')
124         if about_blocks: title = _get_params(about_blocks[0])[0]
125         else: title = 'Untitled'
126         #get author
127         if about_blocks: author = _get_params(about_blocks[0])[1]
128         else: author = ''
129         #get desc
130         note_blocks = _get_blocks(blocks, 'Note')
131         if note_blocks: desc = _get_params(note_blocks[0])[0]
132         else: desc = ''
133         #create options block
134         options_block = odict()
135         options_block['key'] = 'options'
136         options_block['param'] = [
137                 _make_param('id', 'top_block'),
138                 _make_param('title', title),
139                 _make_param('author', author),
140                 _make_param('description', desc),
141                 _make_param('window_size', window_size),
142                 _make_param('_coordinate', '(10, 10)'),
143         ]
144         #append options block
145         new_n['block'].append(options_block)
146         ############################################################
147         # conversion - variables
148         ############################################################
149         x = 100 
150         for variable in variables:
151                 key = variable['key']
152                 value = variable['value']
153                 minimum = Utils.exists_or_else(variable, 'min', '')
154                 maximum = Utils.exists_or_else(variable, 'max', '')
155                 step = Utils.exists_or_else(variable, 'step', '')
156                 x = x + 150
157                 coor = '(%d, %d)'%(x, 10)
158                 var_block = odict()
159                 if minimum and maximum: #slider varible
160                         #determine num steps
161                         try: num_steps = str(int((float(maximum) - float(minimum))/float(step)))
162                         except: num_steps = '100'
163                         var_block['key'] = 'variable_slider'
164                         var_block['param'] = [
165                                 _make_param('id', key),
166                                 _make_param('value', value),
167                                 _make_param('min', minimum),
168                                 _make_param('max', maximum),
169                                 _make_param('num_steps', num_steps),
170                                 _make_param('_coordinate', coor),
171                         ]
172                 else: #regular variable
173                         var_block['key'] = 'variable'
174                         var_block['param'] = [
175                                 _make_param('id', key),
176                                 _make_param('value', value),
177                                 _make_param('_coordinate', coor),
178                         ]
179                 #append variable block
180                 new_n['block'].append(var_block)
181         ############################################################
182         # conversion - blocks
183         ############################################################
184         #create name to key map for all blocks in platform
185         name_to_key = dict((b.get_name(), b.get_key()) for b in platform.get_blocks())
186         for block in blocks:
187                 #extract info
188                 tag = block['tag']
189                 #ignore list
190                 if tag in ('Note', 'About'): continue
191                 id = _convert_id(block['id'])
192                 coor = '(%s, %s + 100)'%(
193                         Utils.exists_or_else(block, 'x_coordinate', '0'),
194                         Utils.exists_or_else(block, 'y_coordinate', '0'),
195                 )
196                 rot = Utils.exists_or_else(block, 'rotation', '0')
197                 params = _get_params(block)
198                 #new block
199                 new_block = odict()
200                 matches = difflib.get_close_matches(tag, name_to_key.keys(), 1)
201                 if not matches: continue
202                 #match found
203                 key = name_to_key[matches[0]]
204                 new_block['key'] = key
205                 new_block['param'] = [
206                         _make_param('id', id),
207                         _make_param('_coordinate', coor),
208                         _make_param('_rotation', rot),
209                 ]
210                 #handle specific blocks
211                 if key == 'wxgui_fftsink2':
212                         params = params[0:3] + ['0'] + params[3:4] + ['8'] + params[4:]
213                 #append params
214                 for i, param in enumerate(params):
215                         platform_block = platform.get_block(key)
216                         try: platform_param = platform_block.get_params()[i+2]
217                         except IndexError: break
218                         if platform_param.is_enum():
219                                 try: param_value = platform_param.get_option_keys()[int(param)]
220                                 except: param_value = platform_param.get_option_keys()[0]
221                         else:
222                                 param_value = param.replace('$', '').replace('^', '**')
223                         new_block['param'].append(_make_param(platform_param.get_key(), param_value))
224                 #append block
225                 new_n['block'].append(new_block)
226         ############################################################
227         # conversion - connections
228         ############################################################
229         for connection in connections:
230                 #extract info
231                 input_signal_block_id = connection['input_signal_block_id']
232                 input_socket_index = connection['input_socket_index']
233                 output_signal_block_id = connection['output_signal_block_id']
234                 output_socket_index = connection['output_socket_index']
235                 #new connection
236                 new_conn = odict()
237                 new_conn['source_block_id'] = _convert_id(output_signal_block_id)
238                 new_conn['sink_block_id'] = _convert_id(input_signal_block_id)
239                 new_conn['source_key'] = output_socket_index
240                 new_conn['sink_key'] = input_socket_index
241                 #append connection
242                 new_n['connection'].append(new_conn)
243         ############################################################
244         # backup and replace
245         ############################################################
246         #backup after successful conversion
247         os.rename(file_path, file_path+'.bak')
248         #save new flow graph to file path
249         ParseXML.to_file({'flow_graph': new_n}, file_path)
250