From 7f7fa2f91467fdb2b11312be8562e7b51fdeb199 Mon Sep 17 00:00:00 2001
From: Sebastian Koslowski <sebastian.koslowski@gmail.com>
Date: Tue, 3 May 2016 17:13:08 +0200
Subject: grc: added yaml/mako support

Includes basic converter from XML/Cheetah to YAML/Mako based block format.
---
 grc/gui/canvas/block.py      | 54 +++++++++++++++++++++++---------------------
 grc/gui/canvas/connection.py |  9 ++++----
 grc/gui/canvas/flowgraph.py  | 24 +++++++++-----------
 grc/gui/canvas/param.py      | 20 ++++++++--------
 grc/gui/canvas/port.py       | 22 ++++++++++--------
 5 files changed, 65 insertions(+), 64 deletions(-)

(limited to 'grc/gui/canvas')

diff --git a/grc/gui/canvas/block.py b/grc/gui/canvas/block.py
index d336bc139a..33edf988c2 100644
--- a/grc/gui/canvas/block.py
+++ b/grc/gui/canvas/block.py
@@ -32,7 +32,7 @@ from ..Constants import (
     PORT_BORDER_SEPARATION, BLOCK_FONT, PARAM_FONT
 )
 from ...core import utils
-from ...core.Block import Block as CoreBlock
+from ...core.blocks import Block as CoreBlock
 
 
 class Block(CoreBlock, Drawable):
@@ -45,7 +45,7 @@ class Block(CoreBlock, Drawable):
         """
         super(self.__class__, self).__init__(parent, **n)
 
-        self.states.update(_coordinate=(0, 0), _rotation=0)
+        self.states.update(coordinate=(0, 0), rotation=0)
         self.width = self.height = 0
         Drawable.__init__(self)  # needs the states and initial sizes
 
@@ -68,7 +68,7 @@ class Block(CoreBlock, Drawable):
         Returns:
             the coordinate tuple (x, y) or (0, 0) if failure
         """
-        return Utils.scale(self.states['_coordinate'])
+        return Utils.scale(self.states['coordinate'])
 
     @coordinate.setter
     def coordinate(self, coor):
@@ -85,7 +85,7 @@ class Block(CoreBlock, Drawable):
                 Utils.align_to_grid(coor[0] + offset_x) - offset_x,
                 Utils.align_to_grid(coor[1] + offset_y) - offset_y
             )
-        self.states['_coordinate'] = coor
+        self.states['coordinate'] = coor
 
     @property
     def rotation(self):
@@ -95,7 +95,7 @@ class Block(CoreBlock, Drawable):
         Returns:
             the rotation in degrees or 0 if failure
         """
-        return self.states['_rotation']
+        return self.states['rotation']
 
     @rotation.setter
     def rotation(self, rot):
@@ -105,7 +105,7 @@ class Block(CoreBlock, Drawable):
         Args:
             rot: the rotation in degrees
         """
-        self.states['_rotation'] = rot
+        self.states['rotation'] = rot
 
     def _update_colors(self):
         self._bg_color = (
@@ -128,7 +128,8 @@ class Block(CoreBlock, Drawable):
             self._area = (0, 0, self.height, self.width)
         self.bounds_from_area(self._area)
 
-        bussified = self.current_bus_structure['source'], self.current_bus_structure['sink']
+        # bussified = self.current_bus_structure['source'], self.current_bus_structure['sink']
+        bussified = False, False
         for ports, has_busses in zip((self.active_sources, self.active_sinks), bussified):
             if not ports:
                 continue
@@ -160,9 +161,9 @@ class Block(CoreBlock, Drawable):
             PangoCairo.update_layout(cr, params_layout)
 
         title_layout.set_markup(
-            '<span {foreground} font_desc="{font}"><b>{name}</b></span>'.format(
+            '<span {foreground} font_desc="{font}"><b>{label}</b></span>'.format(
                 foreground='foreground="red"' if not self.is_valid() else '', font=BLOCK_FONT,
-                name=Utils.encode(self.name)
+                label=Utils.encode(self.label)
             )
         )
         title_width, title_height = title_layout.get_size()
@@ -170,7 +171,7 @@ class Block(CoreBlock, Drawable):
         # update the params layout
         if not self.is_dummy_block:
             markups = [param.format_block_surface_markup()
-                       for param in self.params.values() if param.get_hide() not in ('all', 'part')]
+                       for param in self.params.values() if param.hide not in ('all', 'part')]
         else:
             markups = ['<span font_desc="{font}"><b>key: </b>{key}</span>'.format(font=PARAM_FONT, key=self.key)]
 
@@ -200,15 +201,15 @@ class Block(CoreBlock, Drawable):
                      get_min_height_for_ports(self.active_sinks),
                      get_min_height_for_ports(self.active_sources))
 
-        def get_min_height_for_bus_ports(ports):
-            return 2 * PORT_BORDER_SEPARATION + sum(
-                port.height + PORT_SPACING for port in ports if port.get_type() == 'bus'
-            ) - PORT_SPACING
-
-        if self.current_bus_structure['sink']:
-            height = max(height, get_min_height_for_bus_ports(self.active_sinks))
-        if self.current_bus_structure['source']:
-            height = max(height, get_min_height_for_bus_ports(self.active_sources))
+        # def get_min_height_for_bus_ports(ports):
+        #     return 2 * PORT_BORDER_SEPARATION + sum(
+        #         port.height + PORT_SPACING for port in ports if port.dtype == 'bus'
+        #     ) - PORT_SPACING
+        #
+        # if self.current_bus_structure['sink']:
+        #     height = max(height, get_min_height_for_bus_ports(self.active_sinks))
+        # if self.current_bus_structure['source']:
+        #     height = max(height, get_min_height_for_bus_ports(self.active_sources))
 
         self.width, self.height = width, height = Utils.align_to_grid((width, height))
 
@@ -237,7 +238,7 @@ class Block(CoreBlock, Drawable):
 
         # Show the flow graph complexity on the top block if enabled
         if Actions.TOGGLE_SHOW_FLOWGRAPH_COMPLEXITY.get_active() and self.key == "options":
-            complexity = utils.calculate_flowgraph_complexity(self.parent)
+            complexity = utils.flow_graph_complexity.calculate(self.parent)
             markups.append(
                 '<span foreground="#444" size="medium" font_desc="{font}">'
                 '<b>Complexity: {num}bal</b></span>'.format(num=Utils.num_to_str(complexity), font=BLOCK_FONT)
@@ -344,7 +345,8 @@ class Block(CoreBlock, Drawable):
         Returns:
             true for change
         """
-        type_templates = ' '.join(p._type for p in self.get_children())
+        type_templates = ' '.join(p._type for p in self.params.values())
+        type_templates += ' '.join(p.get_raw('dtype') for p in (self.sinks + self.sources))
         type_param = None
         for key, param in six.iteritems(self.params):
             if not param.is_enum():
@@ -361,10 +363,10 @@ class Block(CoreBlock, Drawable):
 
         # Try to increment the enum by direction
         try:
-            keys = list(type_param.options)
-            old_index = keys.index(type_param.get_value())
-            new_index = (old_index + direction + len(keys)) % len(keys)
-            type_param.set_value(keys[new_index])
+            values = list(type_param.options)
+            old_index = values.index(type_param.get_value())
+            new_index = (old_index + direction + len(values)) % len(values)
+            type_param.set_value(values[new_index])
             return True
         except:
             return False
@@ -381,7 +383,7 @@ class Block(CoreBlock, Drawable):
         """
         changed = False
         # Concat the nports string from the private nports settings of all ports
-        nports_str = ' '.join(port._nports for port in self.get_ports())
+        nports_str = ' '.join(str(port.get_raw('multiplicity')) for port in self.ports())
         # Modify all params whose keys appear in the nports string
         for key, param in six.iteritems(self.params):
             if param.is_enum() or param.key not in nports_str:
diff --git a/grc/gui/canvas/connection.py b/grc/gui/canvas/connection.py
index ff790503ef..56dab45570 100644
--- a/grc/gui/canvas/connection.py
+++ b/grc/gui/canvas/connection.py
@@ -32,7 +32,7 @@ from ..Constants import (
     LINE_SELECT_SENSITIVITY,
 )
 from ...core.Connection import Connection as CoreConnection
-from ...core.Element import nop_write
+from ...core.utils.descriptors import nop_write
 
 
 class Connection(CoreConnection, Drawable):
@@ -93,10 +93,9 @@ class Connection(CoreConnection, Drawable):
         ]
         self._current_coordinates = None  # triggers _make_path()
 
-        def get_domain_color(domain_name):
-            domain = self.parent_platform.domains.get(domain_name, {})
-            color_spec = domain.get('color')
-            return colors.get_color(color_spec) if color_spec else colors.DEFAULT_DOMAIN_COLOR
+        def get_domain_color(domain_id):
+            domain = self.parent_platform.domains.get(domain_id, None)
+            return colors.get_color(domain.color) if domain else colors.DEFAULT_DOMAIN_COLOR
 
         if source.domain == GR_MESSAGE_DOMAIN:
             self._line_width_factor = 1.0
diff --git a/grc/gui/canvas/flowgraph.py b/grc/gui/canvas/flowgraph.py
index 14326fd3f6..394b12cfba 100644
--- a/grc/gui/canvas/flowgraph.py
+++ b/grc/gui/canvas/flowgraph.py
@@ -81,7 +81,7 @@ class FlowGraph(CoreFlowgraph, Drawable):
         Returns:
             a unique id
         """
-        block_ids = set(b.get_id() for b in self.blocks)
+        block_ids = set(b.name for b in self.blocks)
         for index in count():
             block_id = '{}_{}'.format(base_id, index)
             if block_id not in block_ids:
@@ -89,7 +89,7 @@ class FlowGraph(CoreFlowgraph, Drawable):
         return block_id
 
     def install_external_editor(self, param):
-        target = (param.parent_block.get_id(), param.key)
+        target = (param.parent_block.name, param.key)
 
         if target in self._external_updaters:
             editor = self._external_updaters[target]
@@ -118,7 +118,7 @@ class FlowGraph(CoreFlowgraph, Drawable):
     def handle_external_editor_change(self, new_value, target):
         try:
             block_id, param_key = target
-            self.get_block(block_id).get_param(param_key).set_value(new_value)
+            self.get_block(block_id).params[param_key].set_value(new_value)
 
         except (IndexError, ValueError):  # block no longer exists
             self._external_updaters[target].stop()
@@ -146,7 +146,7 @@ class FlowGraph(CoreFlowgraph, Drawable):
         # get the new block
         block = self.new_block(key)
         block.coordinate = coor
-        block.get_param('id').set_value(id)
+        block.params['id'].set_value(id)
         Actions.ELEMENT_CREATE()
         return id
 
@@ -262,18 +262,18 @@ class FlowGraph(CoreFlowgraph, Drawable):
                 except (KeyError, SyntaxError, ValueError):
                     pass
             if block_key == 'epy_block':
-                block.get_param('_io_cache').set_value(param_data.pop('_io_cache'))
-                block.get_param('_source_code').set_value(param_data.pop('_source_code'))
+                block.params['_io_cache'].set_value(param_data.pop('_io_cache'))
+                block.params['_source_code'].set_value(param_data.pop('_source_code'))
                 block.rewrite()  # this creates the other params
             for param_key, param_value in six.iteritems(param_data):
                 #setup id parameter
                 if param_key == 'id':
                     old_id2block[param_value] = block
                     #if the block id is not unique, get a new block id
-                    if param_value in (blk.get_id() for blk in self.blocks):
+                    if param_value in (blk.name for blk in self.blocks):
                         param_value = self._get_unique_id(param_value)
                 #set value to key
-                block.get_param(param_key).set_value(param_value)
+                block.params[param_key].set_value(param_value)
             #move block to offset coordinate
             block.move((x_off, y_off))
         #update before creating connections
@@ -282,11 +282,9 @@ class FlowGraph(CoreFlowgraph, Drawable):
         for connection_n in connections_n:
             source = old_id2block[connection_n.get('source_block_id')].get_source(connection_n.get('source_key'))
             sink = old_id2block[connection_n.get('sink_block_id')].get_sink(connection_n.get('sink_key'))
-            self.connect(source, sink)
-        #set all pasted elements selected
-        for block in selected:
-            selected = selected.union(set(block.get_connections()))
-        self.selected_elements = set(selected)
+            connection = self.connect(source, sink)
+            selected.add(connection)
+        self.selected_elements = selected
 
     ###########################################################################
     # Modify Selected
diff --git a/grc/gui/canvas/param.py b/grc/gui/canvas/param.py
index b027b7653a..e2c335d9cf 100644
--- a/grc/gui/canvas/param.py
+++ b/grc/gui/canvas/param.py
@@ -39,20 +39,20 @@ class Param(CoreParam):
         Returns:
             gtk input class
         """
-        type_ = self.get_type()
-        if type_ in ('file_open', 'file_save'):
+        dtype = self.dtype
+        if dtype in ('file_open', 'file_save'):
             input_widget_cls = ParamWidgets.FileParam
 
-        elif self.is_enum():
+        elif dtype == 'enum':
             input_widget_cls = ParamWidgets.EnumParam
 
         elif self.options:
             input_widget_cls = ParamWidgets.EnumEntryParam
 
-        elif type_ == '_multiline':
+        elif dtype == '_multiline':
             input_widget_cls = ParamWidgets.MultiLineEntryParam
 
-        elif type_ == '_multiline_python_external':
+        elif dtype == '_multiline_python_external':
             input_widget_cls = ParamWidgets.PythonEditorParam
 
         else:
@@ -64,8 +64,8 @@ class Param(CoreParam):
         block = self.parent
         # fixme: using non-public attribute here
         has_callback = \
-            hasattr(block, 'get_callbacks') and \
-            any(self.key in callback for callback in block._callbacks)
+            hasattr(block, 'templates') and \
+            any(self.key in callback for callback in block.templates.get('callbacks', ''))
 
         return '<span {underline} {foreground} font_desc="Sans 9">{label}</span>'.format(
             underline='underline="low"' if has_callback else '',
@@ -76,7 +76,7 @@ class Param(CoreParam):
 
     def format_tooltip_text(self):
         errors = self.get_error_messages()
-        tooltip_lines = ['Key: ' + self.key, 'Type: ' + self.get_type()]
+        tooltip_lines = ['Key: ' + self.key, 'Type: ' + self.dtype]
         if self.is_valid():
             value = str(self.get_evaluated())
             if len(value) > 100:
@@ -117,7 +117,7 @@ class Param(CoreParam):
         if not self.is_valid():
             return _truncate(value)
         if value in self.options:
-            return self.options_names[self.options.index(value)]
+            return self.options[value]  # its name
 
         ##################################################
         # Split up formatting by type
@@ -125,7 +125,7 @@ class Param(CoreParam):
         # Default center truncate
         truncate = 0
         e = self.get_evaluated()
-        t = self.get_type()
+        t = self.dtype
         if isinstance(e, bool):
             return str(e)
         elif isinstance(e, Constants.COMPLEX_TYPES):
diff --git a/grc/gui/canvas/port.py b/grc/gui/canvas/port.py
index b74e4adfcc..2ea35f3dd3 100644
--- a/grc/gui/canvas/port.py
+++ b/grc/gui/canvas/port.py
@@ -26,8 +26,9 @@ from gi.repository import Gtk, PangoCairo, Pango
 from . import colors
 from .drawable import Drawable
 from .. import Actions, Utils, Constants
-from ...core.Element import nop_write
-from ...core.Port import Port as CorePort
+
+from ...core.utils.descriptors import nop_write
+from ...core.ports import Port as CorePort
 
 
 class Port(CorePort, Drawable):
@@ -75,12 +76,13 @@ class Port(CorePort, Drawable):
         if not self.parent_block.enabled:
             self._font_color[-1] = 0.4
             color = colors.BLOCK_DISABLED_COLOR
+        elif self.domain == Constants.GR_MESSAGE_DOMAIN:
+            color = colors.PORT_TYPE_TO_COLOR.get('message')
         else:
             self._font_color[-1] = 1.0
-            color = colors.PORT_TYPE_TO_COLOR.get(self.get_type()) or colors.PORT_TYPE_TO_COLOR.get('')
-            vlen = self.get_vlen()
-            if vlen > 1:
-                dark = (0, 0, 30 / 255.0, 50 / 255.0, 70 / 255.0)[min(4, vlen)]
+            color = colors.PORT_TYPE_TO_COLOR.get(self.dtype) or colors.PORT_TYPE_TO_COLOR.get('')
+            if self.vlen > 1:
+                dark = (0, 0, 30 / 255.0, 50 / 255.0, 70 / 255.0)[min(4, self.vlen)]
                 color = tuple(max(c - dark, 0) for c in color)
         self._bg_color = color
         self._border_color = tuple(max(c - 0.3, 0) for c in color)
@@ -108,7 +110,7 @@ class Port(CorePort, Drawable):
         if cr:
             PangoCairo.update_layout(cr, self.label_layout)
 
-        if self.domain in (Constants.GR_MESSAGE_DOMAIN, Constants.DEFAULT_DOMAIN):
+        if self.domain in (Constants.GR_MESSAGE_DOMAIN, Constants.GR_STREAM_DOMAIN):
             self._line_width_factor = 1.0
         else:
             self._line_width_factor = 2.0
@@ -124,9 +126,9 @@ class Port(CorePort, Drawable):
         self.width = 2 * Constants.PORT_LABEL_PADDING + label_width / Pango.SCALE
         self.height = 2 * Constants.PORT_LABEL_PADDING + label_height / Pango.SCALE
         self._label_layout_offsets = [0, Constants.PORT_LABEL_PADDING]
-        if self.get_type() == 'bus':
-            self.height += Constants.PORT_EXTRA_BUS_HEIGHT
-            self._label_layout_offsets[1] += Constants.PORT_EXTRA_BUS_HEIGHT / 2
+        # if self.dtype == 'bus':
+        #     self.height += Constants.PORT_EXTRA_BUS_HEIGHT
+        #     self._label_layout_offsets[1] += Constants.PORT_EXTRA_BUS_HEIGHT / 2
         self.height += self.height % 2  # uneven height
 
     def draw(self, cr):
-- 
cgit v1.2.3