acd98ef8414ef2a6ee1241451efd28d76f70e511
[debian/gnuradio] / grc / python / Generator.py
1 """
2 Copyright 2008, 2009, 2010 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 import os
21 import subprocess
22 import tempfile
23 from Cheetah.Template import Template
24 import expr_utils
25 from Constants import \
26         TOP_BLOCK_FILE_MODE, HIER_BLOCK_FILE_MODE, \
27         HIER_BLOCKS_LIB_DIR, PYEXEC, \
28         FLOW_GRAPH_TEMPLATE
29 import convert_hier
30 from .. gui import Messages
31
32 class Generator(object):
33
34         def __init__(self, flow_graph, file_path):
35                 """
36                 Initialize the generator object.
37                 Determine the file to generate.
38                 @param flow_graph the flow graph object
39                 @param file_path the path to write the file to
40                 """
41                 self._flow_graph = flow_graph
42                 self._generate_options = self._flow_graph.get_option('generate_options')
43                 if self._generate_options == 'hb':
44                         self._mode = HIER_BLOCK_FILE_MODE
45                         dirname = HIER_BLOCKS_LIB_DIR
46                 else:
47                         self._mode = TOP_BLOCK_FILE_MODE
48                         dirname = os.path.dirname(file_path)
49                         #handle the case where the directory is read-only
50                         #in this case, use the system's temp directory
51                         if not os.access(dirname, os.W_OK):
52                                 dirname = tempfile.gettempdir()
53                 filename = self._flow_graph.get_option('id') + '.py'
54                 self._file_path = os.path.join(dirname, filename)
55
56         def get_file_path(self): return self._file_path
57
58         def write(self):
59                 #do throttle warning
60                 all_keys = ' '.join(map(lambda b: b.get_key(), self._flow_graph.get_enabled_blocks()))
61                 if ('usrp' not in all_keys) and ('audio' not in all_keys) and ('throttle' not in all_keys) and self._generate_options != 'hb':
62                         Messages.send_warning('''\
63 This flow graph may not have flow control: no audio or usrp blocks found. \
64 Add a Misc->Throttle block to your flow graph to avoid CPU congestion.''')
65                 #generate
66                 open(self.get_file_path(), 'w').write(str(self))
67                 if self._generate_options == 'hb':
68                         #convert hier block to xml wrapper
69                         convert_hier.convert_hier(self._flow_graph, self.get_file_path())
70                 os.chmod(self.get_file_path(), self._mode)
71
72         def get_popen(self):
73                 """
74                 Execute this python flow graph.
75                 @return a popen object
76                 """
77                 #execute
78                 cmds = [PYEXEC, '-u', self.get_file_path()] #-u is unbuffered stdio
79                 if self._generate_options == 'no_gui':
80                         cmds = ['xterm', '-e'] + cmds
81                 p = subprocess.Popen(args=cmds, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, universal_newlines=True)
82                 return p
83
84         def __str__(self):
85                 """
86                 Convert the flow graph to python code.
87                 @return a string of python code
88                 """
89                 title = self._flow_graph.get_option('title') or self._flow_graph.get_option('id').replace('_', ' ').title()
90                 imports = self._flow_graph.get_imports()
91                 variables = self._flow_graph.get_variables()
92                 parameters = self._flow_graph.get_parameters()
93                 #list of variables with controls
94                 controls = filter(lambda v: v.get_make(), variables)
95                 #list of blocks not including variables and imports and parameters and disabled
96                 blocks = sorted(self._flow_graph.get_enabled_blocks(), lambda x, y: cmp(x.get_id(), y.get_id()))
97                 probes = filter(lambda b: b.get_key().startswith('probe_'), blocks) #ensure probes are last in the block list
98                 #get a list of notebooks and sort them according dependencies
99                 notebooks = expr_utils.sort_objects(
100                         filter(lambda b: b.get_key() == 'notebook', blocks),
101                         lambda n: n.get_id(), lambda n: n.get_param('notebook').get_value(),
102                 )
103                 #list of regular blocks (all blocks minus the special ones)
104                 blocks = filter(lambda b: b not in (imports + parameters + variables + probes + notebooks), blocks) + probes
105                 #list of connections where each endpoint is enabled
106                 connections = filter(lambda c: not c.is_msg(), self._flow_graph.get_enabled_connections())
107                 messages = filter(lambda c: c.is_msg(), self._flow_graph.get_enabled_connections())
108                 #list of variable names
109                 var_ids = [var.get_id() for var in parameters + variables]
110                 #prepend self.
111                 replace_dict = dict([(var_id, 'self.%s'%var_id) for var_id in var_ids])
112                 #list of callbacks
113                 callbacks = [
114                         expr_utils.expr_replace(cb, replace_dict)
115                         for cb in sum([block.get_callbacks() for block in self._flow_graph.get_enabled_blocks()], [])
116                 ]
117                 #map var id to callbacks
118                 var_id2cbs = dict(
119                         [(var_id, filter(lambda c: expr_utils.get_variable_dependencies(c, [var_id]), callbacks))
120                         for var_id in var_ids]
121                 )
122                 #load the namespace
123                 namespace = {
124                         'title': title,
125                         'imports': imports,
126                         'flow_graph': self._flow_graph,
127                         'variables': variables,
128                         'notebooks': notebooks,
129                         'controls': controls,
130                         'parameters': parameters,
131                         'blocks': blocks,
132                         'connections': connections,
133                         'messages': messages,
134                         'generate_options': self._generate_options,
135                         'var_id2cbs': var_id2cbs,
136                 }
137                 #build the template
138                 t = Template(open(FLOW_GRAPH_TEMPLATE, 'r').read(), namespace)
139                 return str(t)