commit-gnuradio
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Commit-gnuradio] [gnuradio] 23/101: grc-refactor: make block.params a d


From: git
Subject: [Commit-gnuradio] [gnuradio] 23/101: grc-refactor: make block.params a dict
Date: Thu, 16 Mar 2017 14:58:00 +0000 (UTC)

This is an automated email from the git hooks/post-receive script.

jcorgan pushed a commit to branch python3
in repository gnuradio.

commit 025c19f6a22ab3ed035cbc63787c4dcdba395faf
Author: Sebastian Koslowski <address@hidden>
Date:   Sat Jun 18 21:00:28 2016 -0700

    grc-refactor: make block.params a dict
---
 grc/core/Block.py                  | 73 +++++++++++++-------------------------
 grc/core/FlowGraph.py              |  8 ++---
 grc/core/Param.py                  | 12 +++----
 grc/core/generator/flow_graph.tmpl | 20 +++++------
 grc/gui/ActionHandler.py           |  2 +-
 grc/gui/Block.py                   |  5 +--
 grc/gui/PropsDialog.py             | 40 ++++++++++++++-------
 7 files changed, 75 insertions(+), 85 deletions(-)

diff --git a/grc/core/Block.py b/grc/core/Block.py
index f08aff8..c6d743e 100644
--- a/grc/core/Block.py
+++ b/grc/core/Block.py
@@ -22,6 +22,7 @@ from __future__ import absolute_import
 import collections
 import itertools
 
+import six
 from six.moves import map, range
 
 from Cheetah.Template import Template
@@ -90,8 +91,7 @@ class Block(Element):
         sinks_n = n.get('sink', [])
 
         # Get list of param tabs
-        self._param_tab_labels = n.get('param_tab_order', {}).get('tab') or 
[DEFAULT_PARAM_TAB]
-        self.params = []
+        self.params = collections.OrderedDict()
         self._init_params(
             params_n=params_n,
             has_sinks=len(sinks_n),
@@ -110,8 +110,7 @@ class Block(Element):
     def _add_param(self, key, name, value='', type='raw', **kwargs):
         n = {'key': key, 'name': name, 'value': value, 'type': type}
         n.update(kwargs)
-        param = self.parent_platform.Param(block=self, n=n)
-        self.params.append(param)
+        self.params[key] = self.parent_platform.Param(block=self, n=n)
 
     def _init_params(self, params_n, has_sources, has_sinks):
         self._add_param(key='id', name='ID', type='id')
@@ -144,14 +143,12 @@ class Block(Element):
             self._add_param(key='maxoutbuf', name='Max Output Buffer', 
type='int',
                             hide='part', value='0', tab=ADVANCED_PARAM_TAB)
 
-        param_keys = set(param.key for param in self.params)
         for param_n in params_n:
             param = self.parent_platform.Param(block=self, n=param_n)
             key = param.key
-            if key in param_keys:
+            if key in self.params:
                 raise Exception('Key "{}" already exists in 
params'.format(key))
-            param_keys.add(key)
-            self.params.append(param)
+            self.params[key] = param
 
         self._add_param(key='comment', name='Comment', type='_multiline', 
hide='part',
                         value='', tab=ADVANCED_PARAM_TAB)
@@ -215,7 +212,7 @@ class Block(Element):
         self._validate_generate_mode_compat()
         self._validate_var_value()
         if self._epy_reload_error:
-            
self.get_param('_source_code').add_error_message(str(self._epy_reload_error))
+            
self.params['_source_code'].add_error_message(str(self._epy_reload_error))
 
     def rewrite(self):
         """
@@ -308,8 +305,8 @@ class Block(Element):
     def rewrite_epy_block(self):
         flowgraph = self.parent_flowgraph
         platform = self.parent_block
-        param_blk = self.get_param('_io_cache')
-        param_src = self.get_param('_source_code')
+        param_blk = self.params['_io_cache']
+        param_src = self.params['_source_code']
 
         src = param_src.get_value()
         src_hash = hash((self.get_id(), src))
@@ -346,7 +343,7 @@ class Block(Element):
         for param in list(self.params):
             if hasattr(param, '__epy_param__'):
                 params[param.key] = param
-                self.params.remove(param)
+                del self.params[param.key]
 
         for key, value in blk_io.params:
             try:
@@ -357,7 +354,7 @@ class Block(Element):
                 n = dict(name=name, key=key, type='raw', value=value)
                 param = platform.Param(block=self, n=n)
                 setattr(param, '__epy_param__', True)
-            self.params.append(param)
+            self.params[key] = param
 
         def update_ports(label, ports, port_specs, direction):
             ports_to_remove = list(ports)
@@ -413,7 +410,7 @@ class Block(Element):
             DISABLED - 2
         """
         try:
-            return int(self.get_param('_enabled').get_value())
+            return int(self.params['_enabled'].get_value())
         except ValueError:
             return self.ENABLED
 
@@ -429,7 +426,7 @@ class Block(Element):
         """
         if value not in [self.ENABLED, self.BYPASSED, self.DISABLED]:
             value = self.ENABLED
-        self.get_param('_enabled').set_value(str(value))
+        self.params['_enabled'].set_value(str(value))
 
     # Enable/Disable Aliases
     def get_enabled(self):
@@ -491,7 +488,7 @@ class Block(Element):
         return 'Block - {} - {}({})'.format(self.get_id(), self.name, self.key)
 
     def get_id(self):
-        return self.get_param('id').get_value()
+        return self.params['id'].get_value()
 
     def get_ports(self):
         return self.sources + self.sinks
@@ -500,13 +497,13 @@ class Block(Element):
         return self.filter_bus_port(self.sources) + 
self.filter_bus_port(self.sinks)
 
     def get_children(self):
-        return self.get_ports() + self.params
+        return self.get_ports() + self.params.values()
 
     def get_children_gui(self):
-        return self.get_ports_gui() + self.params
+        return self.get_ports_gui() + self.params.values()
 
     def get_comment(self):
-        return self.get_param('comment').get_value()
+        return self.params['comment'].get_value()
 
     @property
     def is_throtteling(self):
@@ -519,21 +516,9 @@ class Block(Element):
     ##############################################
     # Access Params
     ##############################################
-    def get_param_tab_labels(self):
-        return self._param_tab_labels
-
-    def get_param_keys(self):
-        return [p.key for p in self.params]
 
     def get_param(self, key):
-        return _get_elem(self.params, key)
-
-    def has_param(self, key):
-        try:
-            _get_elem(self.params, key)
-            return True
-        except:
-            return False
+        return self.params[key]
 
     ##############################################
     # Access Sinks
@@ -541,9 +526,6 @@ class Block(Element):
     def get_sink(self, key):
         return _get_elem(self.sinks, key)
 
-    def get_sinks(self):
-        return self.sinks
-
     def get_sinks_gui(self):
         return self.filter_bus_port(self.sinks)
 
@@ -553,9 +535,6 @@ class Block(Element):
     def get_source(self, key):
         return _get_elem(self.sources, key)
 
-    def get_sources(self):
-        return self.sources
-
     def get_sources_gui(self):
         return self.filter_bus_port(self.sources)
 
@@ -580,7 +559,7 @@ class Block(Element):
         if '$' not in tmpl:
             return tmpl
         # TODO: cache that
-        n = {param.key: param.template_arg for param in self.params}
+        n = {key: param.template_arg for key, param in 
six.iteritems(self.params)}
         try:
             return str(Template(tmpl, n))
         except Exception as err:
@@ -601,7 +580,7 @@ class Block(Element):
         """
         changed = False
         type_param = None
-        for param in [p for p in self.params if p.is_enum()]:
+        for key, param in six.iteritems(self.params):
             children = self.get_children()
             # Priority to the type controller
             if param.key in ' '.join([p._type for p in children]): type_param 
= param
@@ -634,14 +613,13 @@ class Block(Element):
         # Concat the nports string from the private nports settings of all 
ports
         nports_str = ' '.join([port._nports for port in self.get_ports()])
         # Modify all params whose keys appear in the nports string
-        for param in self.params:
+        for key, param in six.iteritems(self.params):
             if param.is_enum() or param.key not in nports_str:
                 continue
             # Try to increment the port controller by direction
             try:
-                value = param.get_evaluated()
-                value = value + direction
-                if 0 < value:
+                value = param.get_evaluated() + direction
+                if value > 0:
                     param.set_value(value)
                     changed = True
             except:
@@ -660,7 +638,7 @@ class Block(Element):
         """
         n = collections.OrderedDict()
         n['key'] = self.key
-        n['param'] = [p.export_data() for p in sorted(self.params, key=str)]
+        n['param'] = [param.export_data() for _, param in 
sorted(six.iteritems(self.params))]
         if 'bus' in [a.get_type() for a in self.sinks]:
             n['bus_sink'] = str(1)
         if 'bus' in [a.get_type() for a in self.sources]:
@@ -680,10 +658,9 @@ class Block(Element):
             n: the nested data odict
         """
         params_n = n.get('param', [])
-        params = dict((param.key, param) for param in self.params)
 
         def get_hash():
-            return hash(tuple(map(hash, self.params)))
+            return hash(tuple(map(hash, self.params.values())))
 
         my_hash = 0
         while get_hash() != my_hash:
@@ -691,7 +668,7 @@ class Block(Element):
                 key = param_n['key']
                 value = param_n['value']
                 try:
-                    params[key].set_value(value)
+                    self.params[key].set_value(value)
                 except KeyError:
                     continue
             # Store hash and call rewrite
diff --git a/grc/core/FlowGraph.py b/grc/core/FlowGraph.py
index d520564..53c4b78 100644
--- a/grc/core/FlowGraph.py
+++ b/grc/core/FlowGraph.py
@@ -116,7 +116,7 @@ class FlowGraph(Element):
         bussink = [b for b in self.get_enabled_blocks() if 
_bussink_searcher.search(b.key)]
 
         for i in bussink:
-            for j in i.params:
+            for j in i.params.values():
                 if j.get_name() == 'On/Off' and j.get_value() == 'on':
                     return True
         return False
@@ -125,7 +125,7 @@ class FlowGraph(Element):
         bussrc = [b for b in self.get_enabled_blocks() if 
_bussrc_searcher.search(b.key)]
 
         for i in bussrc:
-            for j in i.params:
+            for j in i.params.values():
                 if j.get_name() == 'On/Off' and j.get_value() == 'on':
                     return True
         return False
@@ -560,10 +560,10 @@ def _initialize_dummy_block(block, block_n):
     block.is_valid = lambda: False
     block.get_enabled = lambda: False
     for param_n in block_n.get('param', []):
-        if param_n['key'] not in block.get_param_keys():
+        if param_n['key'] not in block.params:
             new_param_n = {'key': param_n['key'], 'name': param_n['key'], 
'type': 'string'}
             param = block.parent_platform.Param(block=block, n=new_param_n)
-            block.param.append(param)
+            block.params.append(param)
 
 
 def _dummy_block_add_port(block, key, dir):
diff --git a/grc/core/Param.py b/grc/core/Param.py
index 907562d..c35d593 100644
--- a/grc/core/Param.py
+++ b/grc/core/Param.py
@@ -145,8 +145,8 @@ class Param(Element):
         """
         # If the base key is a valid param key, copy its data and overlay this 
params data
         base_key = n.get('base_key')
-        if base_key and base_key in block.get_param_keys():
-            n_expanded = block.get_param(base_key)._n.copy()
+        if base_key and base_key in block.params:
+            n_expanded = block.params[base_key]._n.copy()
             n_expanded.update(n)
             n = n_expanded
         # Save odict in case this param will be base for another
@@ -157,9 +157,7 @@ class Param(Element):
         value = n.get('value', '')
         self._type = n.get('type', 'raw')
         self._hide = n.get('hide', '')
-        self._tab_label = n.get('tab', block.get_param_tab_labels()[0])
-        if self._tab_label not in block.get_param_tab_labels():
-            block.get_param_tab_labels().append(self._tab_label)
+        self.tab_label = n.get('tab', Constants.DEFAULT_PARAM_TAB)
         # Build the param
         Element.__init__(self, parent=block)
         # Create the Option objects from the n data
@@ -624,7 +622,7 @@ class Param(Element):
         """
         params = []
         for block in self.parent_flowgraph.get_enabled_blocks():
-            params.extend(p for p in block.params if p.get_type() == type)
+            params.extend(p for p in block.params.values() if p.get_type() == 
type)
         return params
 
     def is_enum(self):
@@ -650,7 +648,7 @@ class Param(Element):
         return self.parent.resolve_dependencies(self._type)
 
     def get_tab_label(self):
-        return self._tab_label
+        return self.tab_label
 
     def get_name(self):
         return self.parent.resolve_dependencies(self._name).strip()
diff --git a/grc/core/generator/flow_graph.tmpl 
b/grc/core/generator/flow_graph.tmpl
index 98f7b43..4e6a918 100644
--- a/grc/core/generator/flow_graph.tmpl
+++ b/grc/core/generator/flow_graph.tmpl
@@ -221,17 +221,17 @@ gr.io_signaturev($(len($io_sigs)), $(len($io_sigs)), 
[$(', '.join($size_strs))])
         $indent($blk.get_make())
     #else
         self.$blk.get_id() = $indent($blk.get_make())
-        #if $blk.has_param('alias') and $blk.get_param('alias').get_evaluated()
-        
(self.$blk.get_id()).set_block_alias("$blk.get_param('alias').get_evaluated()")
+        #if 'alias' in $blk.params and $blk.params['alias'].get_evaluated()
+        
(self.$blk.get_id()).set_block_alias("$blk.params['alias'].get_evaluated()")
         #end if
-        #if $blk.has_param('affinity') and 
$blk.get_param('affinity').get_evaluated()
-        
(self.$blk.get_id()).set_processor_affinity($blk.get_param('affinity').get_evaluated())
+        #if 'affinity' in $blk.params and 
$blk.params['affinity'].get_evaluated()
+        
(self.$blk.get_id()).set_processor_affinity($blk.params['affinity'].get_evaluated())
         #end if
-        #if (len($blk.sources)>0) and $blk.has_param('minoutbuf') and 
(int($blk.get_param('minoutbuf').get_evaluated()) > 0)
-        
(self.$blk.get_id()).set_min_output_buffer($blk.get_param('minoutbuf').get_evaluated())
+        #if len($blk.sources) > 0 and 'minoutbuf' in $blk.params and 
int($blk.params['minoutbuf'].get_evaluated()) > 0
+        
(self.$blk.get_id()).set_min_output_buffer($blk.params['minoutbuf'].get_evaluated())
         #end if
-        #if (len($blk.sources)>0) and $blk.has_param('maxoutbuf') and 
(int($blk.get_param('maxoutbuf').get_evaluated()) > 0)
-        
(self.$blk.get_id()).set_max_output_buffer($blk.get_param('maxoutbuf').get_evaluated())
+        #if len($blk.sources) > 0 and 'maxoutbuf' in $blk.params and 
int($blk.params['maxoutbuf'].get_evaluated()) > 0
+        
(self.$blk.get_id()).set_max_output_buffer($blk.params['maxoutbuf'].get_evaluated())
         #end if
     #end if
 #end for
@@ -404,8 +404,8 @@ def main(top_block_cls=$(class_name), options=None):
         tb.wait()
     qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting)
         #for $m in $monitors
-    if $m.has_param('en'):
-        if $m.get_param('en').get_value():
+    if 'en' in $m.params:
+        if $m.params['en'].get_value():
             (tb.$m.get_id()).start()
     else:
         sys.stderr.write("Monitor '{0}' does not have an enable ('en') 
parameter.".format("tb.$m.get_id()"))
diff --git a/grc/gui/ActionHandler.py b/grc/gui/ActionHandler.py
index fdda105..732c48f 100644
--- a/grc/gui/ActionHandler.py
+++ b/grc/gui/ActionHandler.py
@@ -219,7 +219,7 @@ class ActionHandler:
                         for block in flow_graph.get_selected_blocks():
 
                             # Check for string variables within the blocks
-                            for param in block.params:
+                            for param in block.params.values():
                                 for variable in flow_graph.get_variables():
                                     # If a block parameter exists that is a 
variable, create a parameter for it
                                     if param.get_value() == variable.get_id():
diff --git a/grc/gui/Block.py b/grc/gui/Block.py
index f3a7a35..d3659dd 100644
--- a/grc/gui/Block.py
+++ b/grc/gui/Block.py
@@ -65,7 +65,7 @@ class Block(Element, _Block):
             the coordinate tuple (x, y) or (0, 0) if failure
         """
         try:
-            coor = self.get_param('_coordinate').get_value()  # should 
evaluate to tuple
+            coor = self.params['_coordinate'].get_value()  # should evaluate 
to tuple
             coor = tuple(int(x) for x in coor[1:-1].split(','))
         except:
             coor = 0, 0
@@ -137,7 +137,8 @@ class Block(Element, _Block):
                 font=PARAM_FONT, key=self.key
             )]
         else:
-            markups = [param.format_block_surface_markup() for param in 
self.params if param.get_hide() not in ('all', 'part')]
+            markups = [param.format_block_surface_markup()
+                       for param in self.params.values() if param.get_hide() 
not in ('all', 'part')]
         if markups:
             layout = Gtk.DrawingArea().create_pango_layout('')
             layout.set_spacing(LABEL_SEPARATION*Pango.SCALE)
diff --git a/grc/gui/PropsDialog.py b/grc/gui/PropsDialog.py
index 7b71add..da79c0e 100644
--- a/grc/gui/PropsDialog.py
+++ b/grc/gui/PropsDialog.py
@@ -59,22 +59,15 @@ class PropsDialog(Gtk.Dialog):
         self.vbox.pack_start(vpaned, True, True, 0)
 
         # Notebook to hold param boxes
-        notebook = Gtk.Notebook()
+        notebook = self.notebook = Gtk.Notebook()
         notebook.set_show_border(False)
         notebook.set_scrollable(True)  # scroll arrows for page tabs
         notebook.set_tab_pos(Gtk.PositionType.TOP)
         vpaned.pack1(notebook, True)
 
         # Params boxes for block parameters
-        self._params_boxes = list()
-        for tab in block.get_param_tab_labels():
-            label = Gtk.Label()
-            vbox = Gtk.VBox()
-            scroll_box = Gtk.ScrolledWindow()
-            scroll_box.set_policy(Gtk.PolicyType.AUTOMATIC, 
Gtk.PolicyType.AUTOMATIC)
-            scroll_box.add_with_viewport(vbox)
-            notebook.append_page(scroll_box, label)
-            self._params_boxes.append((tab, label, vbox))
+        self._params_boxes = []
+        self._build_param_tab_boxes(block.params)
 
         # Docs for the block
         self._docs_text_display = doc_view = SimpleTextDisplay()
@@ -113,6 +106,27 @@ class PropsDialog(Gtk.Dialog):
         self.connect('response', self._handle_response)
         self.show_all()  # show all (performs initial gui update)
 
+    def _build_param_tab_boxes(self, params):
+        tab_labels = (p.tab_label for p in self._block.params.values())
+
+        def unique_tab_labels():
+            seen = {Constants.DEFAULT_PARAM_TAB}
+            yield Constants.DEFAULT_PARAM_TAB
+            for tab_label in tab_labels:
+                if tab_label in seen:
+                    continue
+                yield tab_label
+                seen.add(tab_label)
+
+        for tab in unique_tab_labels():
+            label = Gtk.Label()
+            vbox = Gtk.VBox()
+            scroll_box = Gtk.ScrolledWindow()
+            scroll_box.set_policy(Gtk.PolicyType.AUTOMATIC, 
Gtk.PolicyType.AUTOMATIC)
+            scroll_box.add_with_viewport(vbox)
+            self.notebook.append_page(scroll_box, label)
+            self._params_boxes.append((tab, label, vbox))
+
     def _params_changed(self):
         """
         Have the params in this dialog changed?
@@ -127,7 +141,7 @@ class PropsDialog(Gtk.Dialog):
         old_hash = self._hash
         new_hash = self._hash = hash(tuple(
             (hash(param), param.get_name(), param.get_type(), param.get_hide() 
== 'all',)
-            for param in self._block.params
+            for param in self._block.params.values()
         ))
         return new_hash != old_hash
 
@@ -162,9 +176,9 @@ class PropsDialog(Gtk.Dialog):
                     # child.destroy()   # disabled because it throws errors...
                 # repopulate the params box
                 box_all_valid = True
-                for param in (p for p in self._block.params if 
p.get_tab_label() == tab):
+                for param in self._block.params.values():
                     # fixme: why do we even rebuild instead of really hiding 
params?
-                    if param.get_hide() == 'all':
+                    if param.get_tab_label() != tab or param.get_hide() == 
'all':
                         continue
                     box_all_valid = box_all_valid and param.is_valid()
 



reply via email to

[Prev in Thread] Current Thread [Next in Thread]