summaryrefslogtreecommitdiff
path: root/grc/gui
diff options
context:
space:
mode:
Diffstat (limited to 'grc/gui')
-rw-r--r--grc/gui/Application.py71
-rw-r--r--grc/gui/BlockTreeWindow.py4
-rw-r--r--grc/gui/Dialogs.py10
-rw-r--r--grc/gui/MainWindow.py2
-rw-r--r--grc/gui/ParamWidgets.py28
-rw-r--r--grc/gui/Platform.py14
-rw-r--r--grc/gui/PropsDialog.py44
-rw-r--r--grc/gui/VariableEditor.py22
-rw-r--r--grc/gui/canvas/block.py54
-rw-r--r--grc/gui/canvas/connection.py9
-rw-r--r--grc/gui/canvas/flowgraph.py24
-rw-r--r--grc/gui/canvas/param.py20
-rw-r--r--grc/gui/canvas/port.py22
13 files changed, 168 insertions, 156 deletions
diff --git a/grc/gui/Application.py b/grc/gui/Application.py
index c1456c3a8d..b4df4d172e 100644
--- a/grc/gui/Application.py
+++ b/grc/gui/Application.py
@@ -20,18 +20,19 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
from __future__ import absolute_import, print_function
+import logging
import os
import subprocess
-import logging
from gi.repository import Gtk, Gio, GLib, GObject
-from . import Dialogs, Actions, Executor, FileDialogs, Utils, Bars
+from . import Constants, Dialogs, Actions, Executor, FileDialogs, Utils, Bars
+
from .MainWindow import MainWindow
-from .ParserErrorsDialog import ParserErrorsDialog
+# from .ParserErrorsDialog import ParserErrorsDialog
from .PropsDialog import PropsDialog
-from ..core import ParseXML, Messages
+from ..core import Messages
log = logging.getLogger(__name__)
@@ -212,9 +213,9 @@ class Application(Gtk.Application):
main.update_panel_visibility(main.CONSOLE, Actions.TOGGLE_CONSOLE_WINDOW.get_active())
main.update_panel_visibility(main.VARIABLES, Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR.get_active())
- if ParseXML.xml_failures:
- Messages.send_xml_errors_if_any(ParseXML.xml_failures)
- Actions.XML_PARSER_ERRORS_DISPLAY.set_enabled(True)
+ #if ParseXML.xml_failures:
+ # Messages.send_xml_errors_if_any(ParseXML.xml_failures)
+ # Actions.XML_PARSER_ERRORS_DISPLAY.set_enabled(True)
# Force an update on the current page to match loaded preferences.
# In the future, change the __init__ order to load preferences first
@@ -284,11 +285,11 @@ class Application(Gtk.Application):
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():
+ if param.get_value() == variable.name:
params.append(param.get_value())
for flow_param in flow_graph.get_parameters():
# If a block parameter exists that is a parameter, create a parameter for it
- if param.get_value() == flow_param.get_id():
+ if param.get_value() == flow_param.name:
params.append(param.get_value())
@@ -302,15 +303,15 @@ class Application(Gtk.Application):
for connection in block.connections:
# Get id of connected blocks
- source_id = connection.source_block.get_id()
- sink_id = connection.sink_block.get_id()
+ source_id = connection.source_block.name
+ sink_id = connection.sink_block.name
# If connected block is not in the list of selected blocks create a pad for it
if flow_graph.get_block(source_id) not in flow_graph.selected_blocks():
- pads.append({'key': connection.sink_port.key, 'coord': connection.source_port.coordinate, 'block_id' : block.get_id(), 'direction': 'source'})
+ pads.append({'key': connection.sink_port.key, 'coord': connection.source_port.coordinate, 'block_id' : block.name, 'direction': 'source'})
if flow_graph.get_block(sink_id) not in flow_graph.selected_blocks():
- pads.append({'key': connection.source_port.key, 'coord': connection.sink_port.coordinate, 'block_id' : block.get_id(), 'direction': 'sink'})
+ pads.append({'key': connection.source_port.key, 'coord': connection.sink_port.coordinate, 'block_id' : block.name, 'direction': 'sink'})
# Copy the selected blocks and paste them into a new page
@@ -324,10 +325,10 @@ class Application(Gtk.Application):
# Set flow graph to heir block type
top_block = flow_graph.get_block("top_block")
- top_block.get_param('generate_options').set_value('hb')
+ top_block.params['generate_options'].set_value('hb')
# this needs to be a unique name
- top_block.get_param('id').set_value('new_heir')
+ top_block.params['id'].set_value('new_heir')
# Remove the default samp_rate variable block that is created
remove_me = flow_graph.get_block("samp_rate")
@@ -339,7 +340,7 @@ class Application(Gtk.Application):
for param in params:
param_id = flow_graph.add_new_block('parameter',(x_pos,10))
param_block = flow_graph.get_block(param_id)
- param_block.get_param('id').set_value(param)
+ param_block.params['id'].set_value(param)
x_pos = x_pos + 100
for pad in pads:
@@ -357,10 +358,10 @@ class Application(Gtk.Application):
source = source_block.get_source(pad['key'])
# Ensure the port types match
- while pad_sink.get_type() != source.get_type():
+ while pad_sink.dtype != source.dtype:
# Special case for some blocks that have non-standard type names, e.g. uhd
- if pad_sink.get_type() == 'complex' and source.get_type() == 'fc32':
+ if pad_sink.dtype == 'complex' and source.dtype == 'fc32':
break;
pad_block.type_controller_modify(1)
@@ -378,9 +379,9 @@ class Application(Gtk.Application):
sink = sink_block.get_sink(pad['key'])
# Ensure the port types match
- while sink.get_type() != pad_source.get_type():
+ while sink.dtype != pad_source.dtype:
# Special case for some blocks that have non-standard type names, e.g. uhd
- if pad_source.get_type() == 'complex' and sink.get_type() == 'fc32':
+ if pad_source.dtype == 'complex' and sink.dtype == 'fc32':
break;
pad_block.type_controller_modify(1)
@@ -567,7 +568,8 @@ class Application(Gtk.Application):
# View Parser Errors
##################################################
elif action == Actions.XML_PARSER_ERRORS_DISPLAY:
- ParserErrorsDialog(ParseXML.xml_failures).run()
+ # ParserErrorsDialog(ParseXML.xml_failures).run()
+ pass
##################################################
# Undo/Redo
##################################################
@@ -616,7 +618,7 @@ class Application(Gtk.Application):
#otherwise try to save
else:
try:
- ParseXML.to_file(flow_graph.export_data(), page.file_path)
+ self.platform.save_flow_graph(page.file_path, flow_graph)
flow_graph.grc_file_path = page.file_path
page.saved = True
except IOError:
@@ -639,14 +641,14 @@ class Application(Gtk.Application):
else:
dup_file_path = page.file_path
dup_file_name = '.'.join(dup_file_path.split('.')[:-1]) + "_copy" # Assuming .grc extension at the end of file_path
- dup_file_path_temp = dup_file_name+'.grc'
+ dup_file_path_temp = dup_file_name + Constants.FILE_EXTENSION
count = 1
while os.path.exists(dup_file_path_temp):
- dup_file_path_temp = dup_file_name+'('+str(count)+').grc'
+ dup_file_path_temp = '{}({}){}'.format(dup_file_name, count, Constants.FILE_EXTENSION)
count += 1
dup_file_path_user = FileDialogs.SaveFlowGraph(main, dup_file_path_temp).run()
if dup_file_path_user is not None:
- ParseXML.to_file(flow_graph.export_data(), dup_file_path_user)
+ self.platform.save_flow_graph(dup_file_path_user, flow_graph)
Messages.send('Saved Copy to: "' + dup_file_path_user + '"\n')
except IOError:
Messages.send_fail_save("Can not create a copy of the flowgraph\n")
@@ -707,11 +709,13 @@ class Application(Gtk.Application):
elif action == Actions.PAGE_CHANGE: # pass and run the global actions
pass
elif action == Actions.RELOAD_BLOCKS:
- self.platform.build_block_library()
+ self.platform.build_library()
main.btwin.repopulate()
- Actions.XML_PARSER_ERRORS_DISPLAY.set_enabled(bool(
- ParseXML.xml_failures))
- Messages.send_xml_errors_if_any(ParseXML.xml_failures)
+
+ #todo: implement parser error dialog for YAML
+ #Actions.XML_PARSER_ERRORS_DISPLAY.set_enabled(bool(ParseXML.xml_failures))
+ #Messages.send_xml_errors_if_any(ParseXML.xml_failures)
+
# Force a redraw of the graph, by getting the current state and re-importing it
main.update_pages()
@@ -721,8 +725,9 @@ class Application(Gtk.Application):
main.btwin.search_entry.grab_focus()
elif action == Actions.OPEN_HIER:
for b in flow_graph.selected_blocks():
- if b._grc_source:
- main.new_page(b._grc_source, show=True)
+ grc_source = b.extra_data.get('grc_source', '')
+ if grc_source:
+ main.new_page(b.grc_source, show=True)
elif action == Actions.BUSSIFY_SOURCES:
for b in flow_graph.selected_blocks():
b.bussify('source')
@@ -781,8 +786,8 @@ class Application(Gtk.Application):
Actions.BLOCK_CREATE_HIER.set_enabled(bool(selected_blocks))
Actions.OPEN_HIER.set_enabled(bool(selected_blocks))
- Actions.BUSSIFY_SOURCES.set_enabled(bool(selected_blocks))
- Actions.BUSSIFY_SINKS.set_enabled(bool(selected_blocks))
+ #Actions.BUSSIFY_SOURCES.set_enabled(bool(selected_blocks))
+ #Actions.BUSSIFY_SINKS.set_enabled(bool(selected_blocks))
Actions.RELOAD_BLOCKS.enable()
Actions.FIND_BLOCKS.enable()
diff --git a/grc/gui/BlockTreeWindow.py b/grc/gui/BlockTreeWindow.py
index 8504200459..3b9b8642f9 100644
--- a/grc/gui/BlockTreeWindow.py
+++ b/grc/gui/BlockTreeWindow.py
@@ -172,7 +172,7 @@ class BlockTreeWindow(Gtk.VBox):
# add block
iter_ = treestore.insert_before(categories[category], None)
treestore.set_value(iter_, KEY_INDEX, block.key)
- treestore.set_value(iter_, NAME_INDEX, block.name)
+ treestore.set_value(iter_, NAME_INDEX, block.label)
treestore.set_value(iter_, DOC_INDEX, _format_doc(block.documentation))
def update_docs(self):
@@ -225,7 +225,7 @@ class BlockTreeWindow(Gtk.VBox):
self.expand_module_in_tree()
else:
matching_blocks = [b for b in list(self.platform.blocks.values())
- if key in b.key.lower() or key in b.name.lower()]
+ if key in b.key.lower() or key in b.label.lower()]
self.treestore_search.clear()
self._categories_search = {tuple(): None}
diff --git a/grc/gui/Dialogs.py b/grc/gui/Dialogs.py
index 51213a6154..45c9095313 100644
--- a/grc/gui/Dialogs.py
+++ b/grc/gui/Dialogs.py
@@ -241,15 +241,15 @@ class ErrorsDialog(Gtk.Dialog):
self.store.clear()
for element, message in flowgraph.iter_error_messages():
if element.is_block:
- src, aspect = element.get_id(), ''
+ src, aspect = element.name, ''
elif element.is_connection:
- src = element.source_block.get_id()
- aspect = "Connection to '{}'".format(element.sink_block.get_id())
+ src = element.source_block.name
+ aspect = "Connection to '{}'".format(element.sink_block.name)
elif element.is_port:
- src = element.parent_block.get_id()
+ src = element.parent_block.name
aspect = "{} '{}'".format('Sink' if element.is_sink else 'Source', element.name)
elif element.is_param:
- src = element.parent_block.get_id()
+ src = element.parent_block.name
aspect = "Param '{}'".format(element.name)
else:
src = aspect = ''
diff --git a/grc/gui/MainWindow.py b/grc/gui/MainWindow.py
index f913d63966..01502b38f9 100644
--- a/grc/gui/MainWindow.py
+++ b/grc/gui/MainWindow.py
@@ -249,7 +249,7 @@ class MainWindow(Gtk.ApplicationWindow):
return
try: #try to load from file
if file_path: Messages.send_start_load(file_path)
- flow_graph = self._platform.get_new_flow_graph()
+ flow_graph = self._platform.make_flow_graph()
flow_graph.grc_file_path = file_path
#print flow_graph
page = Page(
diff --git a/grc/gui/ParamWidgets.py b/grc/gui/ParamWidgets.py
index 71cb1b7a7d..18d1da736b 100644
--- a/grc/gui/ParamWidgets.py
+++ b/grc/gui/ParamWidgets.py
@@ -88,11 +88,11 @@ class InputParam(Gtk.HBox):
Set the markup, color, tooltip, show/hide.
"""
self.label.set_markup(self.param.format_label_markup(self._have_pending_changes))
- self.set_color('dtype_' + self.param.get_type())
+ self.set_color('dtype_' + self.param.dtype)
self.set_tooltip_text(self.param.format_tooltip_text())
- if self.param.get_hide() == 'all':
+ if self.param.hide == 'all':
self.hide()
else:
self.show_all()
@@ -214,19 +214,17 @@ class EnumParam(InputParam):
def __init__(self, *args, **kwargs):
InputParam.__init__(self, *args, **kwargs)
self._input = Gtk.ComboBoxText()
- for option_name in self.param.options_names:
+ for option_name in self.param.options.values():
self._input.append_text(option_name)
- value = self.param.get_value()
- active_index = self.param.options.index(value)
- self._input.set_active(active_index)
-
+ self.param_values = list(self.param.options)
+ self._input.set_active(self.param_values.index(self.param.get_value()))
self._input.connect('changed', self._editing_callback)
self._input.connect('changed', self._apply_change)
self.pack_start(self._input, False, False, 0)
def get_text(self):
- return self.param.options[self._input.get_active()]
+ return self.param_values[self._input.get_active()]
def set_tooltip_text(self, text):
self._input.set_tooltip_text(text)
@@ -238,13 +236,13 @@ class EnumEntryParam(InputParam):
def __init__(self, *args, **kwargs):
InputParam.__init__(self, *args, **kwargs)
self._input = Gtk.ComboBoxText.new_with_entry()
- for option_name in self.param.options_names:
+ for option_name in self.param.options.values():
self._input.append_text(option_name)
+ self.param_values = list(self.param.options)
value = self.param.get_value()
try:
- active_index = self.param.options.index(value)
- self._input.set_active(active_index)
+ self._input.set_active(self.param_values.index(value))
except ValueError:
self._input.set_active(-1)
self._input.get_child().set_text(value)
@@ -263,7 +261,7 @@ class EnumEntryParam(InputParam):
if self.has_custom_value:
return self._input.get_child().get_text()
else:
- return self.param.options[self._input.get_active()]
+ return self.param_values[self._input.get_active()]
def set_tooltip_text(self, text):
if self.has_custom_value: # custom entry
@@ -304,16 +302,16 @@ class FileParam(EntryParam):
dirname = os.getcwd() # fix bad paths
#build the dialog
- if self.param.get_type() == 'file_open':
+ if self.param.dtype == 'file_open':
file_dialog = Gtk.FileChooserDialog('Open a Data File...', None,
Gtk.FileChooserAction.OPEN, ('gtk-cancel',Gtk.ResponseType.CANCEL,'gtk-open',Gtk.ResponseType.OK))
- elif self.param.get_type() == 'file_save':
+ elif self.param.dtype == 'file_save':
file_dialog = Gtk.FileChooserDialog('Save a Data File...', None,
Gtk.FileChooserAction.SAVE, ('gtk-cancel',Gtk.ResponseType.CANCEL, 'gtk-save',Gtk.ResponseType.OK))
file_dialog.set_do_overwrite_confirmation(True)
file_dialog.set_current_name(basename) #show the current filename
else:
- raise ValueError("Can't open file chooser dialog for type " + repr(self.param.get_type()))
+ raise ValueError("Can't open file chooser dialog for type " + repr(self.param.dtype))
file_dialog.set_current_folder(dirname) #current directory
file_dialog.set_select_multiple(False)
file_dialog.set_local_only(True)
diff --git a/grc/gui/Platform.py b/grc/gui/Platform.py
index aeade75d78..2a38bc619e 100644
--- a/grc/gui/Platform.py
+++ b/grc/gui/Platform.py
@@ -24,7 +24,8 @@ import os
from .Config import Config
from . import canvas
-from ..core.Platform import Platform as CorePlatform
+from ..core.platform import Platform as CorePlatform
+from ..core.utils.backports import ChainMap
class Platform(CorePlatform):
@@ -61,8 +62,15 @@ class Platform(CorePlatform):
Config = Config
FlowGraph = canvas.FlowGraph
Connection = canvas.Connection
- block_classes = {key: canvas.Block.make_cls_with_base(cls)
- for key, cls in CorePlatform.block_classes.items()}
+
+ def new_block_class(self, block_id, **data):
+ cls = CorePlatform.new_block_class(self, block_id, **data)
+ return canvas.Block.make_cls_with_base(cls)
+
+ block_classes_build_in = {key: canvas.Block.make_cls_with_base(cls)
+ for key, cls in CorePlatform.block_classes_build_in.items()}
+ block_classes = ChainMap({}, block_classes_build_in)
+
port_classes = {key: canvas.Port.make_cls_with_base(cls)
for key, cls in CorePlatform.port_classes.items()}
param_classes = {key: canvas.Param.make_cls_with_base(cls)
diff --git a/grc/gui/PropsDialog.py b/grc/gui/PropsDialog.py
index 5f39770e78..9ce9bf2701 100644
--- a/grc/gui/PropsDialog.py
+++ b/grc/gui/PropsDialog.py
@@ -40,7 +40,7 @@ class PropsDialog(Gtk.Dialog):
Gtk.Dialog.__init__(
self,
- title='Properties: ' + block.name,
+ title='Properties: ' + block.label,
transient_for=parent,
modal=True,
destroy_with_parent=True,
@@ -70,7 +70,7 @@ class PropsDialog(Gtk.Dialog):
# Params boxes for block parameters
self._params_boxes = []
- self._build_param_tab_boxes(block.params)
+ self._build_param_tab_boxes()
# Docs for the block
self._docs_text_display = doc_view = SimpleTextDisplay()
@@ -109,26 +109,26 @@ 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 _build_param_tab_boxes(self):
+ categories = (p.category for p in self._block.params.values())
- def unique_tab_labels():
+ def unique_categories():
seen = {Constants.DEFAULT_PARAM_TAB}
yield Constants.DEFAULT_PARAM_TAB
- for tab_label in tab_labels:
- if tab_label in seen:
+ for cat in categories:
+ if cat in seen:
continue
- yield tab_label
- seen.add(tab_label)
+ yield cat
+ seen.add(cat)
- for tab in unique_tab_labels():
+ for category in unique_categories():
label = Gtk.Label()
vbox = Gtk.VBox()
scroll_box = Gtk.ScrolledWindow()
scroll_box.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
scroll_box.add(vbox)
self.notebook.append_page(scroll_box, label)
- self._params_boxes.append((tab, label, vbox))
+ self._params_boxes.append((category, label, vbox))
def _params_changed(self):
"""
@@ -143,7 +143,7 @@ class PropsDialog(Gtk.Dialog):
"""
old_hash = self._hash
new_hash = self._hash = hash(tuple(
- (hash(param), param.name, param.get_type(), param.get_hide() == 'all',)
+ (hash(param), param.name, param.dtype, param.hide == 'all',)
for param in self._block.params.values()
))
return new_hash != old_hash
@@ -171,7 +171,7 @@ class PropsDialog(Gtk.Dialog):
"""
if force or self._params_changed():
# hide params box before changing
- for tab, label, vbox in self._params_boxes:
+ for category, label, vbox in self._params_boxes:
vbox.hide()
# empty the params box
for child in vbox.get_children():
@@ -181,7 +181,7 @@ class PropsDialog(Gtk.Dialog):
box_all_valid = True
for param in self._block.params.values():
# todo: why do we even rebuild instead of really hiding params?
- if param.get_tab_label() != tab or param.get_hide() == 'all':
+ if param.category != category or param.hide == 'all':
continue
box_all_valid = box_all_valid and param.is_valid()
@@ -190,7 +190,7 @@ class PropsDialog(Gtk.Dialog):
vbox.pack_start(input_widget, input_widget.expand, True, 1)
label.set_markup('<span foreground="{color}">{name}</span>'.format(
- color='black' if box_all_valid else 'red', name=Utils.encode(tab)
+ color='black' if box_all_valid else 'red', name=Utils.encode(category)
))
vbox.show() # show params box with new params
@@ -225,7 +225,7 @@ class PropsDialog(Gtk.Dialog):
buf.insert(pos, '\n')
# if given the current parameters an exact match can be made
- block_constructor = self._block.get_make().rsplit('.', 2)[-1]
+ block_constructor = self._block.templates.render('make').rsplit('.', 2)[-1]
block_class = block_constructor.partition('(')[0].strip()
if block_class in docstrings:
docstrings = {block_class: docstrings[block_class]}
@@ -246,9 +246,9 @@ class PropsDialog(Gtk.Dialog):
key = block.key
if key == 'epy_block':
- src = block.get_param('_source_code').get_value()
+ src = block.params['_source_code'].get_value()
elif key == 'epy_module':
- src = block.get_param('source_code').get_value()
+ src = block.params['source_code'].get_value()
else:
src = ''
@@ -259,12 +259,12 @@ class PropsDialog(Gtk.Dialog):
buf.insert(buf.get_end_iter(), text)
buf.delete(buf.get_start_iter(), buf.get_end_iter())
- insert('# Imports\n', '\n'.join(block.get_imports()))
+ insert('# Imports\n', block.templates.render('imports').strip('\n'))
if block.is_variable:
- insert('\n\n# Variables\n', block.get_var_make())
- insert('\n\n# Blocks\n', block.get_make())
+ insert('\n\n# Variables\n', block.templates.render('var_make'))
+ insert('\n\n# Blocks\n', block.templates.render('make'))
if src:
- insert('\n\n# External Code ({}.py)\n'.format(block.get_id()), src)
+ insert('\n\n# External Code ({}.py)\n'.format(block.name), src)
def _handle_key_press(self, widget, event):
close_dialog = (
diff --git a/grc/gui/VariableEditor.py b/grc/gui/VariableEditor.py
index e310676420..c179c8bc84 100644
--- a/grc/gui/VariableEditor.py
+++ b/grc/gui/VariableEditor.py
@@ -174,13 +174,13 @@ class VariableEditor(Gtk.VBox):
# Block specific values
if block:
if block.key == 'import':
- value = block.get_param('import').get_value()
+ value = block.params['import'].get_value()
elif block.key != "variable":
value = "<Open Properties>"
sp('editable', False)
sp('foreground', '#0D47A1')
else:
- value = block.get_param('value').get_value()
+ value = block.params['value'].get_value()
# Check if there are errors in the blocks.
# Show the block error as a tooltip
@@ -192,7 +192,7 @@ class VariableEditor(Gtk.VBox):
else:
# Evaluate and show the value (if it is a variable)
if block.key == "variable":
- evaluated = str(block.get_param('value').evaluate())
+ evaluated = str(block.params['value'].evaluate())
self.set_tooltip_text(evaluated)
# Always set the text value.
sp('text', value)
@@ -227,21 +227,21 @@ class VariableEditor(Gtk.VBox):
imports = self.treestore.append(None, [None, 'Imports'])
variables = self.treestore.append(None, [None, 'Variables'])
for block in self._imports:
- self.treestore.append(imports, [block, block.get_param('id').get_value()])
- for block in sorted(self._variables, key=lambda v: v.get_id()):
- self.treestore.append(variables, [block, block.get_param('id').get_value()])
+ self.treestore.append(imports, [block, block.params['id'].get_value()])
+ for block in sorted(self._variables, key=lambda v: v.name):
+ self.treestore.append(variables, [block, block.params['id'].get_value()])
def _handle_name_edited_cb(self, cell, path, new_text):
block = self.treestore[path][BLOCK_INDEX]
- block.get_param('id').set_value(new_text)
+ block.params['id'].set_value(new_text)
Actions.VARIABLE_EDITOR_UPDATE()
def _handle_value_edited_cb(self, cell, path, new_text):
block = self.treestore[path][BLOCK_INDEX]
if block.is_import:
- block.get_param('import').set_value(new_text)
+ block.params['import'].set_value(new_text)
else:
- block.get_param('value').set_value(new_text)
+ block.params['value'].set_value(new_text)
Actions.VARIABLE_EDITOR_UPDATE()
def handle_action(self, item, key, event=None):
@@ -258,12 +258,12 @@ class VariableEditor(Gtk.VBox):
#Actions.BLOCK_PARAM_MODIFY()
pass
elif key == self.DELETE_BLOCK:
- self.emit('remove_block', self._block.get_id())
+ self.emit('remove_block', self._block.name)
elif key == self.DELETE_CONFIRM:
if self._confirm_delete:
# Create a context menu to confirm the delete operation
confirmation_menu = Gtk.Menu()
- block_id = self._block.get_param('id').get_value().replace("_", "__")
+ block_id = self._block.params['id'].get_value().replace("_", "__")
confirm = Gtk.MenuItem(label="Delete {}".format(block_id))
confirm.connect('activate', self.handle_action, self.DELETE_BLOCK)
confirmation_menu.add(confirm)
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):