sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
def setup_forward_or_backward_execution(self):
""" Sets up the execution of the concurrency states dependent on if the state is executed forward of backward.
:return:
"""
if self.backward_execution:
# pop the return item of this concurrency state to get the correct scoped data
last_history_item = self.execution_history.pop_last_item()
assert isinstance(last_history_item, ReturnItem)
self.scoped_data = last_history_item.scoped_data
# get the concurrency item for the children execution historys
concurrency_history_item = self.execution_history.get_last_history_item()
assert isinstance(concurrency_history_item, ConcurrencyItem)
else: # forward_execution
self.execution_history.push_call_history_item(self, CallType.CONTAINER, self, self.input_data)
concurrency_history_item = self.execution_history.push_concurrency_history_item(self, len(self.states))
return concurrency_history_item | Sets up the execution of the concurrency states dependent on if the state is executed forward of backward.
:return: | entailment |
def start_child_states(self, concurrency_history_item, do_not_start_state=None):
""" Utility function to start all child states of the concurrency state.
:param concurrency_history_item: each concurrent child branch gets an execution history stack of this
concurrency history item
:param do_not_start_state: optionally the id of a state can be passed, that must not be started (e.g. in the
case of the barrier concurrency state the decider state)
:return:
"""
self.state_execution_status = StateExecutionStatus.EXECUTE_CHILDREN
# actually the queue is not needed in the barrier concurrency case
# to avoid code duplication both concurrency states have the same start child function
concurrency_queue = queue.Queue(maxsize=0) # infinite Queue size
for index, state in enumerate(self.states.values()):
if state is not do_not_start_state:
state.input_data = self.get_inputs_for_state(state)
state.output_data = self.create_output_dictionary_for_state(state)
state.concurrency_queue = concurrency_queue
state.concurrency_queue_id = index
state.generate_run_id()
if not self.backward_execution:
# care for the history items; this item is only for execution visualization
concurrency_history_item.execution_histories[index].push_call_history_item(
state, CallType.EXECUTE, self, state.input_data)
else: # backward execution
last_history_item = concurrency_history_item.execution_histories[index].pop_last_item()
assert isinstance(last_history_item, ReturnItem)
state.start(concurrency_history_item.execution_histories[index], self.backward_execution, False)
return concurrency_queue | Utility function to start all child states of the concurrency state.
:param concurrency_history_item: each concurrent child branch gets an execution history stack of this
concurrency history item
:param do_not_start_state: optionally the id of a state can be passed, that must not be started (e.g. in the
case of the barrier concurrency state the decider state)
:return: | entailment |
def join_state(self, state, history_index, concurrency_history_item):
""" a utility function to join a state
:param state: the state to join
:param history_index: the index of the execution history stack in the concurrency history item
for the given state
:param concurrency_history_item: the concurrency history item that stores the execution history stacks of all
children
:return:
"""
state.join()
if state.backward_execution:
self.backward_execution = True
state.state_execution_status = StateExecutionStatus.INACTIVE
# care for the history items
if not self.backward_execution:
state.concurrency_queue = None
# add the data of all child states to the scoped data and the scoped variables
state.execution_history.push_return_history_item(state, CallType.EXECUTE, self, state.output_data)
else:
last_history_item = concurrency_history_item.execution_histories[history_index].pop_last_item()
assert isinstance(last_history_item, CallItem) | a utility function to join a state
:param state: the state to join
:param history_index: the index of the execution history stack in the concurrency history item
for the given state
:param concurrency_history_item: the concurrency history item that stores the execution history stacks of all
children
:return: | entailment |
def finalize_backward_execution(self):
""" Utility function to finalize the backward execution of the concurrency state.
:return:
"""
# backward_execution needs to be True to signal the parent container state the backward execution
self.backward_execution = True
# pop the ConcurrencyItem as we are leaving the barrier concurrency state
last_history_item = self.execution_history.pop_last_item()
assert isinstance(last_history_item, ConcurrencyItem)
last_history_item = self.execution_history.pop_last_item()
assert isinstance(last_history_item, CallItem)
# this copy is convenience and not required here
self.scoped_data = last_history_item.scoped_data
self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE
return self.finalize() | Utility function to finalize the backward execution of the concurrency state.
:return: | entailment |
def finalize_concurrency_state(self, outcome):
""" Utility function to finalize the forward execution of the concurrency state.
:param outcome:
:return:
"""
final_outcome = outcome
self.write_output_data()
self.check_output_data_type()
self.execution_history.push_return_history_item(self, CallType.CONTAINER, self, self.output_data)
self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE
singleton.state_machine_execution_engine._modify_run_to_states(self)
if self.preempted:
final_outcome = Outcome(-2, "preempted")
return self.finalize(final_outcome) | Utility function to finalize the forward execution of the concurrency state.
:param outcome:
:return: | entailment |
def _head_length(self, port):
"""Distance from the center of the port to the perpendicular waypoint"""
if not port:
return 0.
parent_state_v = self.get_parent_state_v()
if parent_state_v is port.parent: # port of connection's parent state
return port.port_size[1]
return max(port.port_size[1] * 1.5, self._calc_line_width() / 1.3) | Distance from the center of the port to the perpendicular waypoint | entailment |
def register_view(self, view):
"""Called when the View was registered"""
super(DataPortListController, self).register_view(view)
view['name_col'].add_attribute(view['name_text'], 'text', self.NAME_STORAGE_ID)
view['data_type_col'].add_attribute(view['data_type_text'], 'text', self.DATA_TYPE_NAME_STORAGE_ID)
if not isinstance(self.model.state, LibraryState) and self.model.state.get_next_upper_library_root_state() is None:
view['name_text'].set_property("editable", True)
view['data_type_text'].set_property("editable", True)
# in the linkage overview the the default value is not shown
if isinstance(view, InputPortsListView) or isinstance(view, OutputPortsListView):
view['default_value_col'].add_attribute(view['default_value_text'], 'text', self.DEFAULT_VALUE_STORAGE_ID)
self._apply_value_on_edited_and_focus_out(view['default_value_text'], self._apply_new_data_port_default_value)
view['default_value_col'].set_cell_data_func(view['default_value_text'],
self._default_value_cell_data_func)
if isinstance(self.model.state, LibraryState):
view['default_value_col'].set_title("Used value")
if self.model.state.get_next_upper_library_root_state() is None: # never enabled means it is disabled
view['default_value_text'].set_property("editable", True)
self._apply_value_on_edited_and_focus_out(view['name_text'], self._apply_new_data_port_name)
self._apply_value_on_edited_and_focus_out(view['data_type_text'], self._apply_new_data_port_type)
if isinstance(self.model.state, LibraryState):
view['use_runtime_value_toggle'] = Gtk.CellRendererToggle()
view['use_runtime_value_col'] = Gtk.TreeViewColumn("Use Runtime Value")
view['use_runtime_value_col'].set_property("sizing", Gtk.TreeViewColumnSizing.AUTOSIZE)
view.get_top_widget().append_column(view['use_runtime_value_col'])
view['use_runtime_value_col'].pack_start(view['use_runtime_value_toggle'], True)
view['use_runtime_value_col'].add_attribute(view['use_runtime_value_toggle'], 'active',
self.USE_RUNTIME_VALUE_STORAGE_ID)
if self.model.state.get_next_upper_library_root_state() is None:
view['use_runtime_value_toggle'].set_property("activatable", True)
view['use_runtime_value_toggle'].connect("toggled", self.on_use_runtime_value_toggled)
self._reload_data_port_list_store() | Called when the View was registered | entailment |
def on_use_runtime_value_toggled(self, widget, path):
"""Try to set the use runtime value flag to the newly entered one
"""
try:
data_port_id = self.list_store[path][self.ID_STORAGE_ID]
self.toggle_runtime_value_usage(data_port_id)
except TypeError as e:
logger.exception("Error while trying to change the use_runtime_value flag") | Try to set the use runtime value flag to the newly entered one | entailment |
def _default_value_cell_data_func(self, tree_view_column, cell, model, iter, data=None):
"""Function set renderer properties for every single cell independently
The function controls the editable and color scheme for every cell in the default value column according
the use_runtime_value flag and whether the state is a library state.
:param tree_view_column: the Gtk.TreeViewColumn to be rendered
:param cell: the current CellRenderer
:param model: the Gtk.ListStore or TreeStore that is the model for TreeView
:param iter: an iterator over the rows of the TreeStore/Gtk.ListStore Model
:param data: optional data to be passed: see http://dumbmatter.com/2012/02/some-notes-on-porting-from-pygtk-to-pygobject/
"""
if isinstance(self.model.state, LibraryState):
use_runtime_value = model.get_value(iter, self.USE_RUNTIME_VALUE_STORAGE_ID)
if use_runtime_value:
cell.set_property("editable", True)
cell.set_property('text', model.get_value(iter, self.RUNTIME_VALUE_STORAGE_ID))
cell.set_property('foreground', "white")
else:
cell.set_property("editable", False)
cell.set_property('text', model.get_value(iter, self.DEFAULT_VALUE_STORAGE_ID))
cell.set_property('foreground', "dark grey")
return | Function set renderer properties for every single cell independently
The function controls the editable and color scheme for every cell in the default value column according
the use_runtime_value flag and whether the state is a library state.
:param tree_view_column: the Gtk.TreeViewColumn to be rendered
:param cell: the current CellRenderer
:param model: the Gtk.ListStore or TreeStore that is the model for TreeView
:param iter: an iterator over the rows of the TreeStore/Gtk.ListStore Model
:param data: optional data to be passed: see http://dumbmatter.com/2012/02/some-notes-on-porting-from-pygtk-to-pygobject/ | entailment |
def _reload_data_port_list_store(self):
"""Reloads the input data port list store from the data port models"""
tmp = self._get_new_list_store()
for data_port_m in self.data_port_model_list:
data_port_id = data_port_m.data_port.data_port_id
data_type = data_port_m.data_port.data_type
# get name of type (e.g. ndarray)
data_type_name = data_type.__name__
# get module of type, e.g. numpy
data_type_module = data_type.__module__
# if the type is not a builtin type, also show the module
if data_type_module not in ['__builtin__', 'builtins']:
data_type_name = data_type_module + '.' + data_type_name
if data_port_m.data_port.default_value is None:
default_value = "None"
else:
default_value = data_port_m.data_port.default_value
if not isinstance(self.model.state, LibraryState):
tmp.append([data_port_m.data_port.name, data_type_name, str(default_value), data_port_id,
None, None, data_port_m])
else:
use_runtime_value, runtime_value = self.get_data_port_runtime_configuration(data_port_id)
tmp.append([data_port_m.data_port.name,
data_type_name,
str(default_value),
data_port_id,
bool(use_runtime_value),
str(runtime_value),
data_port_m,
])
tms = Gtk.TreeModelSort(model=tmp)
tms.set_sort_column_id(0, Gtk.SortType.ASCENDING)
tms.set_sort_func(0, compare_variables)
tms.sort_column_changed()
tmp = tms
self.list_store.clear()
for elem in tmp:
self.list_store.append(elem[:]) | Reloads the input data port list store from the data port models | entailment |
def _apply_new_data_port_name(self, path, new_name):
"""Applies the new name of the data port defined by path
:param str path: The path identifying the edited data port
:param str new_name: New name
"""
try:
data_port_id = self.list_store[path][self.ID_STORAGE_ID]
if self.state_data_port_dict[data_port_id].name != new_name:
self.state_data_port_dict[data_port_id].name = new_name
except (TypeError, ValueError) as e:
logger.exception("Error while trying to change data port name") | Applies the new name of the data port defined by path
:param str path: The path identifying the edited data port
:param str new_name: New name | entailment |
def _apply_new_data_port_type(self, path, new_data_type_str):
"""Applies the new data type of the data port defined by path
:param str path: The path identifying the edited data port
:param str new_data_type_str: New data type as str
"""
try:
data_port_id = self.list_store[path][self.ID_STORAGE_ID]
if self.state_data_port_dict[data_port_id].data_type.__name__ != new_data_type_str:
self.state_data_port_dict[data_port_id].change_data_type(new_data_type_str)
except ValueError as e:
logger.exception("Error while changing data type") | Applies the new data type of the data port defined by path
:param str path: The path identifying the edited data port
:param str new_data_type_str: New data type as str | entailment |
def _apply_new_data_port_default_value(self, path, new_default_value_str):
"""Applies the new default value of the data port defined by path
:param str path: The path identifying the edited variable
:param str new_default_value_str: New default value as string
"""
try:
data_port_id = self.list_store[path][self.ID_STORAGE_ID]
if isinstance(self.model.state, LibraryState):
# this always has to be true, as the runtime value column can only be edited
# if the use_runtime_value flag is True
if self.list_store[path][self.USE_RUNTIME_VALUE_STORAGE_ID]:
self.set_data_port_runtime_value(data_port_id, new_default_value_str)
else:
if str(self.state_data_port_dict[data_port_id].default_value) != new_default_value_str:
self.state_data_port_dict[data_port_id].default_value = new_default_value_str
except (TypeError, AttributeError) as e:
logger.exception("Error while changing default value") | Applies the new default value of the data port defined by path
:param str path: The path identifying the edited variable
:param str new_default_value_str: New default value as string | entailment |
def _data_ports_changed(self, model):
"""Reload list store and reminds selection when the model was changed"""
if not isinstance(model, AbstractStateModel):
return
# store port selection
path_list = None
if self.view is not None:
model, path_list = self.tree_view.get_selection().get_selected_rows()
selected_data_port_ids = [self.list_store[path[0]][self.ID_STORAGE_ID] for path in path_list] if path_list else []
self._reload_data_port_list_store()
# recover port selection
if selected_data_port_ids:
[self.select_entry(selected_data_port_id, False) for selected_data_port_id in selected_data_port_ids] | Reload list store and reminds selection when the model was changed | entailment |
def runtime_values_changed(self, model, prop_name, info):
"""Handle cases for the library runtime values"""
if ("_input_runtime_value" in info.method_name or
info.method_name in ['use_runtime_value_input_data_ports',
'input_data_port_runtime_values']) and \
self.model is model:
self._data_ports_changed(model) | Handle cases for the library runtime values | entailment |
def add_new_data_port(self):
"""Add a new port with default values and select it"""
try:
new_data_port_ids = gui_helper_state_machine.add_data_port_to_selected_states('OUTPUT', int, [self.model])
if new_data_port_ids:
self.select_entry(new_data_port_ids[self.model.state])
except ValueError:
pass | Add a new port with default values and select it | entailment |
def add_callback_for_action(self, action, callback):
"""Adds a callback function to an action
The method checks whether both action and callback are valid. If so, the callback is added to the list of
functions called when the action is triggered.
:param str action: An action like 'add', 'copy', 'info'
:param callback: A callback function, which is called when action is triggered. It retrieves the event as
parameter
:return: True is the parameters are valid and the callback is registered, False else
:rtype: bool
"""
if hasattr(callback, '__call__'): # Is the callback really a function?
if action not in self.__action_to_callbacks:
self.__action_to_callbacks[action] = []
self.__action_to_callbacks[action].append(callback)
controller = None
try:
controller = callback.__self__
except AttributeError:
try:
# Needed when callback was wrapped using functools.partial
controller = callback.func.__self__
except AttributeError:
pass
if controller:
if controller not in self.__controller_action_callbacks:
self.__controller_action_callbacks[controller] = {}
if action not in self.__controller_action_callbacks[controller]:
self.__controller_action_callbacks[controller][action] = []
self.__controller_action_callbacks[controller][action].append(callback)
return True | Adds a callback function to an action
The method checks whether both action and callback are valid. If so, the callback is added to the list of
functions called when the action is triggered.
:param str action: An action like 'add', 'copy', 'info'
:param callback: A callback function, which is called when action is triggered. It retrieves the event as
parameter
:return: True is the parameters are valid and the callback is registered, False else
:rtype: bool | entailment |
def remove_callback_for_action(self, action, callback):
""" Remove a callback for a specific action
This is mainly for cleanup purposes or a plugin that replaces a GUI widget.
:param str action: the cation of which the callback is going to be remove
:param callback: the callback to be removed
"""
if action in self.__action_to_callbacks:
if callback in self.__action_to_callbacks[action]:
self.__action_to_callbacks[action].remove(callback) | Remove a callback for a specific action
This is mainly for cleanup purposes or a plugin that replaces a GUI widget.
:param str action: the cation of which the callback is going to be remove
:param callback: the callback to be removed | entailment |
def trigger_action(self, action, key_value, modifier_mask):
"""Calls the appropriate callback function(s) for the given action
:param str action: The name of the action that was triggered
:param key_value: The key value of the shortcut that caused the trigger
:param modifier_mask: The modifier mask of the shortcut that caused the trigger
:return: Whether a callback was triggered
:rtype: bool
"""
res = False
if action in self.__action_to_callbacks:
for callback_function in self.__action_to_callbacks[action]:
try:
ret = callback_function(key_value, modifier_mask)
# If at least one controller returns True, the whole result becomes True
res |= (False if ret is None else ret)
except Exception as e:
logger.exception('Exception while calling callback methods for action "{0}": {1}'.format(action, e))
return res | Calls the appropriate callback function(s) for the given action
:param str action: The name of the action that was triggered
:param key_value: The key value of the shortcut that caused the trigger
:param modifier_mask: The modifier mask of the shortcut that caused the trigger
:return: Whether a callback was triggered
:rtype: bool | entailment |
def check_info_on_no_update_flags(self, info):
"""Stop updates while multi-actions"""
# TODO that could need a second clean up
# avoid updates because of state destruction
if 'before' in info and info['method_name'] == "remove_state":
if info.instance is self.model.state:
self.no_update_state_destruction = True
else:
# if the state it self is removed lock the widget to never run updates and relieve all models
removed_state_id = info.args[1] if len(info.args) > 1 else info.kwargs['state_id']
if removed_state_id == self.model.state.state_id or \
not self.model.state.is_root_state and removed_state_id == self.model.parent.state.state_id:
self.no_update_self_or_parent_state_destruction = True
self.relieve_all_models()
elif 'after' in info and info['method_name'] == "remove_state":
if info.instance.state_id == self.model.state.state_id:
self.no_update_state_destruction = False
# reduce NotificationOverview generations by the fact that after could cause False and before could cause True
if not self.no_update_state_destruction and not self.no_update_self_or_parent_state_destruction and \
(not self.no_update and 'before' in info or 'after' in info and self.no_update):
return
overview = NotificationOverview(info, False, self.__class__.__name__)
# The method causing the change raised an exception, thus nothing was changed and updates are allowed
if 'after' in info and isinstance(overview['result'][-1], Exception):
self.no_update = False
self.no_update_state_destruction = False
# self.no_update_self_or_parent_state_destruction = False
return
if overview['method_name'][-1] in ['group_states', 'ungroup_state', "change_state_type",
"change_root_state_type"]:
instance_is_self = self.model.state is overview['instance'][-1]
instance_is_parent = self.model.parent and self.model.parent.state is overview['instance'][-1]
instance_is_parent_parent = self.model.parent and self.model.parent.parent and self.model.parent.parent.state is overview['instance'][-1]
# print("no update flag: ", True if 'before' in info and (instance_is_self or instance_is_parent or instance_is_parent_parent) else False)
if instance_is_self or instance_is_parent or instance_is_parent_parent:
self.no_update = True if 'before' in info else False
if overview['prop_name'][-1] == 'state' and overview['method_name'][-1] in ["change_state_type"] and \
self.model.get_state_machine_m() is not None:
changed_model = self.model.get_state_machine_m().get_state_model_by_path(overview['args'][-1][1].get_path())
if changed_model not in self._model_observed:
self.observe_model(changed_model) | Stop updates while multi-actions | entailment |
def before_notification_state_machine_observation_control(self, model, prop_name, info):
"""Check for multi-actions and set respective no update flags. """
if is_execution_status_update_notification_from_state_machine_model(prop_name, info):
return
# do not update while multi-actions
self.check_info_on_no_update_flags(info) | Check for multi-actions and set respective no update flags. | entailment |
def store_value(self, name, value, parameters=None):
"""Stores the value of a certain variable
The value of a variable with name 'name' is stored together with the parameters that were used for the
calculation.
:param str name: The name of the variable
:param value: The value to be cached
:param dict parameters: The parameters on which the value depends
"""
if not isinstance(parameters, dict):
raise TypeError("parameters must be a dict")
hash = self._parameter_hash(parameters)
if name not in self._cache:
self._cache[name] = {}
self._cache[name][hash.hexdigest()] = value | Stores the value of a certain variable
The value of a variable with name 'name' is stored together with the parameters that were used for the
calculation.
:param str name: The name of the variable
:param value: The value to be cached
:param dict parameters: The parameters on which the value depends | entailment |
def get_value(self, name, parameters=None):
"""Return the value of a cached variable if applicable
The value of the variable 'name' is returned, if no parameters are passed or if all parameters are identical
to the ones stored for the variable.
:param str name: Name of teh variable
:param dict parameters: Current parameters or None if parameters do not matter
:return: The cached value of the variable or None if the parameters differ
"""
if not isinstance(parameters, dict):
raise TypeError("parameters must a dict")
if name not in self._cache:
return None
hash = self._parameter_hash(parameters)
hashdigest = hash.hexdigest()
return self._cache[name].get(hashdigest, None) | Return the value of a cached variable if applicable
The value of the variable 'name' is returned, if no parameters are passed or if all parameters are identical
to the ones stored for the variable.
:param str name: Name of teh variable
:param dict parameters: Current parameters or None if parameters do not matter
:return: The cached value of the variable or None if the parameters differ | entailment |
def _normalize_number_values(self, parameters):
"""Assures equal precision for all number values"""
for key, value in parameters.items():
if isinstance(value, (int, float)):
parameters[key] = str(Decimal(value).normalize(self._context)) | Assures equal precision for all number values | entailment |
def register_view(self, view):
"""Register callbacks for button press events and selection changed"""
super(AbstractTreeViewController, self).register_view(view)
self.signal_handlers.append((self._tree_selection,
self._tree_selection.connect('changed', self.selection_changed)))
# self.handler_ids.append((self.tree_view,
# self.tree_view.connect('key-press-event', self.tree_view_keypress_callback)))
self.tree_view.connect('key-release-event', self.on_key_release_event)
self.tree_view.connect('button-release-event', self.tree_view_keypress_callback)
# key press is needed for tab motion but needs to be registered already here TODO why?
self.tree_view.connect('key-press-event', self.tree_view_keypress_callback)
self._tree_selection.set_mode(Gtk.SelectionMode.MULTIPLE)
self.update_selection_sm_prior() | Register callbacks for button press events and selection changed | entailment |
def get_view_selection(self):
"""Get actual tree selection object and all respective models of selected rows"""
if not self.MODEL_STORAGE_ID:
return None, None
# avoid selection requests on empty tree views -> case warnings in gtk3
if len(self.store) == 0:
paths = []
else:
model, paths = self._tree_selection.get_selected_rows()
# get all related models for selection from respective tree store field
selected_model_list = []
for path in paths:
model = self.store[path][self.MODEL_STORAGE_ID]
selected_model_list.append(model)
return self._tree_selection, selected_model_list | Get actual tree selection object and all respective models of selected rows | entailment |
def get_selections(self):
"""Get current model selection status in state machine selection (filtered according the purpose of the widget)
and tree selection of the widget"""
sm_selection, sm_filtered_selected_model_set = self.get_state_machine_selection()
tree_selection, selected_model_list = self.get_view_selection()
return tree_selection, selected_model_list, sm_selection, sm_filtered_selected_model_set | Get current model selection status in state machine selection (filtered according the purpose of the widget)
and tree selection of the widget | entailment |
def state_machine_selection_changed(self, state_machine_m, signal_name, signal_msg):
"""Notify tree view about state machine selection"""
if self.CORE_ELEMENT_CLASS in signal_msg.arg.affected_core_element_classes:
self.update_selection_sm_prior() | Notify tree view about state machine selection | entailment |
def add_action_callback(self, *event):
"""Callback method for add action"""
if react_to_event(self.view, self.tree_view, event) and self.active_entry_widget is None:
self.on_add(None)
return True | Callback method for add action | entailment |
def remove_action_callback(self, *event):
"""Callback method for remove action
The method checks whether a shortcut ('Delete') is in the gui config model which shadow the delete functionality
of maybe active a entry widget. If a entry widget is active the remove callback return with None.
"""
if react_to_event(self.view, self.tree_view, event) and \
not (self.active_entry_widget and not is_event_of_key_string(event, 'Delete')):
self.on_remove(None)
return True | Callback method for remove action
The method checks whether a shortcut ('Delete') is in the gui config model which shadow the delete functionality
of maybe active a entry widget. If a entry widget is active the remove callback return with None. | entailment |
def copy_action_callback(self, *event):
"""Callback method for copy action"""
if react_to_event(self.view, self.tree_view, event) and self.active_entry_widget is None:
sm_selection, sm_selected_model_list = self.get_state_machine_selection()
# only list specific elements are copied by widget
if sm_selection is not None:
sm_selection.set(sm_selected_model_list)
global_clipboard.copy(sm_selection)
return True | Callback method for copy action | entailment |
def cut_action_callback(self, *event):
"""Callback method for copy action"""
if react_to_event(self.view, self.tree_view, event) and self.active_entry_widget is None:
sm_selection, sm_selected_model_list = self.get_state_machine_selection()
# only list specific elements are cut by widget
if sm_selection is not None:
sm_selection.set(sm_selected_model_list)
global_clipboard.cut(sm_selection)
return True | Callback method for copy action | entailment |
def _apply_value_on_edited_and_focus_out(self, renderer, apply_method):
"""Sets up the renderer to apply changed when loosing focus
The default behaviour for the focus out event dismisses the changes in the renderer. Therefore we setup
handlers for that event, applying the changes.
:param Gtk.CellRendererText renderer: The cell renderer who's changes are to be applied on focus out events
:param apply_method: The callback method applying the newly entered value
"""
assert isinstance(renderer, Gtk.CellRenderer)
def remove_all_handler(renderer):
"""Remove all handler for given renderer and its editable
:param renderer: Renderer of the respective column which is edit by a entry widget, at the moment
"""
def remove_handler(widget, data_name):
"""Remove handler from given widget
:param Gtk.Widget widget: Widget from which a handler is to be removed
:param data_name: Name of the data of the widget in which the handler id is stored
"""
handler_id = getattr(widget, data_name)
if widget.handler_is_connected(handler_id):
widget.disconnect(handler_id)
editable = getattr(renderer, "editable")
remove_handler(editable, "focus_out_handler_id")
remove_handler(editable, "cursor_move_handler_id")
remove_handler(editable, "insert_at_cursor_handler_id")
remove_handler(editable, "entry_widget_expose_event_handler_id")
remove_handler(renderer, "editing_cancelled_handler_id")
def on_focus_out(entry, event):
"""Applies the changes to the entry
:param Gtk.Entry entry: The entry that was focused out
:param Gtk.Event event: Event object with information about the event
"""
renderer.remove_all_handler(renderer)
if renderer.ctrl.get_path() is None:
return
# Originally we had to use idle_add to prevent core dumps:
# https://mail.gnome.org/archives/gtk-perl-list/2005-September/msg00143.html
# Gtk TODO: use idle_add if there are problems
apply_method(renderer.ctrl.get_path(), entry.get_text())
def on_cursor_move_in_entry_widget(entry, step, count, extend_selection):
"""Trigger scroll bar adjustments according active entry widgets cursor change
"""
self.tree_view_keypress_callback(entry, None)
def on_editing_started(renderer, editable, path):
"""Connects the a handler for the focus-out-event of the current editable
:param Gtk.CellRendererText renderer: The cell renderer who's editing was started
:param Gtk.CellEditable editable: interface for editing the current TreeView cell
:param str path: the path identifying the edited cell
"""
# secure scrollbar adjustments on active cell
ctrl = renderer.ctrl
[path, focus_column] = ctrl.tree_view.get_cursor()
if path:
ctrl.tree_view.scroll_to_cell(path, ctrl.widget_columns[ctrl.widget_columns.index(focus_column)],
use_align=False)
editing_cancelled_handler_id = renderer.connect('editing-canceled', on_editing_canceled)
focus_out_handler_id = editable.connect('focus-out-event', on_focus_out)
cursor_move_handler_id = editable.connect('move-cursor', on_cursor_move_in_entry_widget)
insert_at_cursor_handler_id = editable.connect("insert-at-cursor", on_cursor_move_in_entry_widget)
entry_widget_expose_event_handler_id = editable.connect("draw", self.on_entry_widget_draw_event)
# Store reference to editable and signal handler ids for later access when removing the handlers
# see https://gitlab.gnome.org/GNOME/accerciser/commit/036689e70304a9e98ce31238dfad2432ad4c78ea
# originally with renderer.set_data()
# renderer.set_data("editable", editable)
setattr(renderer, "editable", editable)
setattr(renderer, "editing_cancelled_handler_id", editing_cancelled_handler_id)
# editable
setattr(editable, "focus_out_handler_id", focus_out_handler_id)
setattr(editable, "cursor_move_handler_id", cursor_move_handler_id)
setattr(editable, "insert_at_cursor_handler_id", insert_at_cursor_handler_id)
setattr(editable, "entry_widget_expose_event_handler_id", entry_widget_expose_event_handler_id)
ctrl.active_entry_widget = editable
def on_edited(renderer, path, new_value_str):
"""Calls the apply method with the new value
:param Gtk.CellRendererText renderer: The cell renderer that was edited
:param str path: The path string of the renderer
:param str new_value_str: The new value as string
"""
renderer.remove_all_handler(renderer)
apply_method(path, new_value_str)
renderer.ctrl.active_entry_widget = None
def on_editing_canceled(renderer):
"""Disconnects the focus-out-event handler of cancelled editable
:param Gtk.CellRendererText renderer: The cell renderer who's editing was cancelled
"""
remove_all_handler(renderer)
renderer.ctrl.active_entry_widget = None
renderer.remove_all_handler = remove_all_handler
renderer.ctrl = self
# renderer.connect('editing-started', on_editing_started)
# renderer.connect('edited', on_edited)
self.__attached_renderers.append(renderer)
self.connect_signal(renderer, 'editing-started', on_editing_started)
self.connect_signal(renderer, 'edited', on_edited) | Sets up the renderer to apply changed when loosing focus
The default behaviour for the focus out event dismisses the changes in the renderer. Therefore we setup
handlers for that event, applying the changes.
:param Gtk.CellRendererText renderer: The cell renderer who's changes are to be applied on focus out events
:param apply_method: The callback method applying the newly entered value | entailment |
def tree_view_keypress_callback(self, widget, event):
"""General method to adapt widget view and controller behavior according the key press/release and
button release events
Here the scrollbar motion to follow key cursor motions in editable is already in.
:param Gtk.TreeView widget: The tree view the controller use
:param Gdk.Event event: The key press event
:return:
"""
current_row_path, current_focused_column = self.tree_view.get_cursor()
# print(current_row_path, current_focused_column)
if isinstance(widget, Gtk.TreeView) and not self.active_entry_widget: # avoid jumps for active entry widget
pass
# cursor motion/selection changes (e.g. also by button release event)
# if current_row_path is not None and len(current_row_path) == 1 and isinstance(current_row_path[0], int):
# self.tree_view.scroll_to_cell(current_row_path[0], current_focused_column, use_align=True)
# # else:
# # self._logger.debug("A ListViewController aspects a current_row_path of dimension 1 with integer but"
# # " it is {0} and column is {1}".format(current_row_path, current_focused_column))
elif isinstance(widget, Gtk.Entry) and self.view.scrollbar_widget is not None:
# calculate the position of the scrollbar to be always centered with the entry widget cursor
# TODO check how to get sufficient the scroll-offset in the entry widget -> some times zero when not
# TODO the scrollbar is one step behind cursor -> so jump from pos1 to end works not perfect
entry_widget_scroll_offset, entry_widget_cursor_position, entry_widget_text_length = \
widget.get_properties(*["scroll-offset", "cursor-position", "text-length"])
cell_rect_of_entry_widget = widget.get_allocation()
horizontal_scroll_bar = self.view.scrollbar_widget.get_hscrollbar()
# entry_widget_text_length must be greater than zero otherwise DevisionByZero Exception
if horizontal_scroll_bar is not None and float(entry_widget_text_length) > 0:
adjustment = horizontal_scroll_bar.get_adjustment()
layout_pixel_width = widget.get_layout().get_pixel_size()[0]
# print("rel_pos pices", cell_rect_of_entry_widget.x,)
# int(layout_pixel_width*float(entry_widget_cursor_position)/float(entry_widget_text_length))
rel_pos = cell_rect_of_entry_widget.x - entry_widget_scroll_offset + \
int(layout_pixel_width*float(entry_widget_cursor_position)/float(entry_widget_text_length))
# optimize rel_pos for better user support
bounds = widget.get_selection_bounds()
if bounds and bounds[1] - bounds[0] == len(widget.get_text()):
# if text is fully selected stay in front as far as possible
rel_pos = cell_rect_of_entry_widget.x
if self._horizontal_scrollbar_stay_in_front_if_possible():
return True
else:
# try to stay long at the beginning of the columns if the columns fully fit in
rel_space = adjustment.get_page_size() - cell_rect_of_entry_widget.x
if cell_rect_of_entry_widget.x + widget.get_layout().get_pixel_size()[0] < \
adjustment.get_page_size():
rel_pos = 0.
elif rel_space and rel_pos <= rel_space:
# accelerate the showing of the first columns
rel_pos = rel_pos + rel_pos*3.*(rel_pos - rel_space)/adjustment.get_page_size()
rel_pos = 0. if rel_pos <= 0 else rel_pos
else:
# and jump to the end of the scroller space if close to the upper limit
rel_pos = adjustment.get_upper() if rel_pos + 2*entry_widget_scroll_offset > adjustment.get_upper() else rel_pos
self._put_horizontal_scrollbar_onto_rel_pos(rel_pos) | General method to adapt widget view and controller behavior according the key press/release and
button release events
Here the scrollbar motion to follow key cursor motions in editable is already in.
:param Gtk.TreeView widget: The tree view the controller use
:param Gdk.Event event: The key press event
:return: | entailment |
def register_view(self, view):
"""Register callbacks for button press events and selection changed"""
super(ListViewController, self).register_view(view)
self.tree_view.connect('button_press_event', self.mouse_click) | Register callbacks for button press events and selection changed | entailment |
def on_remove(self, widget, data=None):
"""Removes respective selected core elements and select the next one"""
path_list = None
if self.view is not None:
model, path_list = self.tree_view.get_selection().get_selected_rows()
old_path = self.get_path()
models = [self.list_store[path][self.MODEL_STORAGE_ID] for path in path_list] if path_list else []
if models:
try:
self.remove_core_elements(models)
except AttributeError as e:
self._logger.warning("The respective core element of {1}.list_store couldn't be removed. -> {0}"
"".format(e, self.__class__.__name__))
if len(self.list_store) > 0:
self.tree_view.set_cursor(min(old_path[0], len(self.list_store) - 1))
return True
else:
self._logger.warning("Please select an element to be removed.") | Removes respective selected core elements and select the next one | entailment |
def get_state_machine_selection(self):
"""An abstract getter method for state machine selection
The method maybe has to be re-implemented by inherit classes and hands generally a filtered set of
selected elements.
:return: selection object it self, filtered set of selected elements
:rtype: rafcon.gui.selection.Selection, set
"""
sm_selection = self.model.get_state_machine_m().selection if self.model.get_state_machine_m() else None
return sm_selection, sm_selection.get_selected_elements_of_core_class(self.CORE_ELEMENT_CLASS) if sm_selection else set() | An abstract getter method for state machine selection
The method maybe has to be re-implemented by inherit classes and hands generally a filtered set of
selected elements.
:return: selection object it self, filtered set of selected elements
:rtype: rafcon.gui.selection.Selection, set | entailment |
def mouse_click(self, widget, event=None):
"""Implements shift- and control-key handling features for mouse button press events explicit
The method is implements a fully defined mouse pattern to use shift- and control-key for multi-selection in a
TreeView and a ListStore as model. It avoid problems caused by special renderer types like the text combo
renderer by stopping the callback handler to continue with notifications.
:param Gtk.Object widget: Object which is the source of the event
:param Gtk.Event event: Event generated by mouse click
:rtype: bool
"""
if event.type == Gdk.EventType.BUTTON_PRESS:
pthinfo = self.tree_view.get_path_at_pos(int(event.x), int(event.y))
if not bool(event.get_state() & Gdk.ModifierType.CONTROL_MASK) \
and not bool(event.get_state() & Gdk.ModifierType.SHIFT_MASK) and \
event.type == Gdk.EventType.BUTTON_PRESS and event.get_button()[1] == 3:
if pthinfo is not None:
model, paths = self._tree_selection.get_selected_rows()
# print(paths)
if pthinfo[0] not in paths:
# self._logger.info("force single selection for right click")
self.tree_view.set_cursor(pthinfo[0])
self._last_path_selection = pthinfo[0]
else:
# self._logger.info("single- or multi-selection for right click")
pass
self.on_right_click_menu()
return True
if (bool(event.get_state() & Gdk.ModifierType.CONTROL_MASK) or \
bool(event.get_state() & Gdk.ModifierType.SHIFT_MASK)) and \
event.type == Gdk.EventType.BUTTON_PRESS and event.get_button()[1] == 3:
return True
if not bool(event.get_state() & Gdk.ModifierType.SHIFT_MASK) and event.get_button()[1] == 1:
if pthinfo is not None:
# self._logger.info("last select row {}".format(pthinfo[0]))
self._last_path_selection = pthinfo[0]
# else:
# self._logger.info("deselect rows")
# self.tree_selection.unselect_all()
if bool(event.get_state() & Gdk.ModifierType.SHIFT_MASK) and event.get_button()[1] == 1:
# self._logger.info("SHIFT adjust selection range")
model, paths = self._tree_selection.get_selected_rows()
# print(model, paths, pthinfo[0])
if paths and pthinfo and pthinfo[0]:
if self._last_path_selection[0] <= pthinfo[0][0]:
new_row_ids_selected = list(range(self._last_path_selection[0], pthinfo[0][0]+1))
else:
new_row_ids_selected = list(range(self._last_path_selection[0], pthinfo[0][0]-1, -1))
# self._logger.info("range to select {0}, {1}".format(new_row_ids_selected, model))
self._tree_selection.unselect_all()
for path in new_row_ids_selected:
self._tree_selection.select_path(path)
return True
else:
# self._logger.info("nothing selected {}".format(model))
if pthinfo and pthinfo[0]:
self._last_path_selection = pthinfo[0]
if bool(event.get_state() & Gdk.ModifierType.CONTROL_MASK) and event.get_button()[1] == 1:
# self._logger.info("CONTROL adjust selection range")
model, paths = self._tree_selection.get_selected_rows()
# print(model, paths, pthinfo[0])
if paths and pthinfo and pthinfo[0]:
if pthinfo[0] in paths:
self._tree_selection.unselect_path(pthinfo[0])
else:
self._tree_selection.select_path(pthinfo[0])
return True
elif pthinfo and pthinfo[0]:
self._tree_selection.select_path(pthinfo[0])
return True
elif event.type == Gdk.EventType._2BUTTON_PRESS:
self._handle_double_click(event) | Implements shift- and control-key handling features for mouse button press events explicit
The method is implements a fully defined mouse pattern to use shift- and control-key for multi-selection in a
TreeView and a ListStore as model. It avoid problems caused by special renderer types like the text combo
renderer by stopping the callback handler to continue with notifications.
:param Gtk.Object widget: Object which is the source of the event
:param Gtk.Event event: Event generated by mouse click
:rtype: bool | entailment |
def _handle_double_click(self, event):
""" Double click with left mouse button focuses the element"""
if event.get_button()[1] == 1: # Left mouse button
path_info = self.tree_view.get_path_at_pos(int(event.x), int(event.y))
if path_info: # Valid entry was clicked on
path = path_info[0]
iter = self.list_store.get_iter(path)
model = self.list_store.get_value(iter, self.MODEL_STORAGE_ID)
selection = self.model.get_state_machine_m().selection
selection.focus = model | Double click with left mouse button focuses the element | entailment |
def update_selection_sm_prior(self):
"""State machine prior update of tree selection"""
if self._do_selection_update:
return
self._do_selection_update = True
tree_selection, selected_model_list, sm_selection, sm_selected_model_list = self.get_selections()
if tree_selection is not None:
for path, row in enumerate(self.list_store):
model = row[self.MODEL_STORAGE_ID]
if model not in sm_selected_model_list and model in selected_model_list:
tree_selection.unselect_path(Gtk.TreePath.new_from_indices([path]))
if model in sm_selected_model_list and model not in selected_model_list:
tree_selection.select_path(Gtk.TreePath.new_from_indices([path]))
self._do_selection_update = False | State machine prior update of tree selection | entailment |
def update_selection_self_prior(self):
"""Tree view prior update of state machine selection"""
if self._do_selection_update:
return
self._do_selection_update = True
tree_selection, selected_model_list, sm_selection, sm_selected_model_list = self.get_selections()
if isinstance(sm_selection, Selection):
sm_selection.handle_prepared_selection_of_core_class_elements(self.CORE_ELEMENT_CLASS, selected_model_list)
self._do_selection_update = False | Tree view prior update of state machine selection | entailment |
def select_entry(self, core_element_id, by_cursor=True):
"""Selects the row entry belonging to the given core_element_id by cursor or tree selection"""
for row_num, element_row in enumerate(self.list_store):
# Compare data port ids
if element_row[self.ID_STORAGE_ID] == core_element_id:
if by_cursor:
self.tree_view.set_cursor(row_num)
else:
self.tree_view.get_selection().select_path((row_num, ))
break | Selects the row entry belonging to the given core_element_id by cursor or tree selection | entailment |
def get_path_for_core_element(self, core_element_id):
"""Get path to the row representing core element described by handed core_element_id
:param core_element_id: Core element identifier used in the respective list store column
:rtype: tuple
:return: path
"""
for row_num, element_row in enumerate(self.list_store):
# Compare data port ids
if element_row[self.ID_STORAGE_ID] == core_element_id:
return row_num, | Get path to the row representing core element described by handed core_element_id
:param core_element_id: Core element identifier used in the respective list store column
:rtype: tuple
:return: path | entailment |
def tree_view_keypress_callback(self, widget, event):
"""Tab back and forward tab-key motion in list widget and the scrollbar motion to follow key cursor motions
The method introduce motion and edit functionality by using "tab"- or "shift-tab"-key for a Gtk.TreeView.
It is designed to work with a Gtk.TreeView which model is a Gtk.ListStore and only uses text cell renderer.
Additional, the TreeView is assumed to be used as a list not as a tree.
With the "tab"-key the cell on the right site of the actual focused cell is started to be edit. Changes in the
Gtk.Entry-Widget are confirmed by emitting a 'edited'-signal. If the row ends the edit process continues
with the first cell of the next row. With the "shift-tab"-key the inverse functionality of the "tab"-key is
provided.
The Controller over steps not editable cells.
:param Gtk.TreeView widget: The tree view the controller use
:param Gdk.Event event: The key press event
:return:
"""
# self._logger.info("key_value: " + str(event.keyval if event is not None else ''))
if event and "GDK_KEY_PRESS" == event.type.value_name \
and (event.keyval == Gdk.KEY_Tab or event.keyval == Gdk.KEY_ISO_Left_Tab):
[path, focus_column] = self.tree_view.get_cursor()
if not path:
return False
self.tree_view_keypress_callback.__func__.core_element_id = self.store[path][self.ID_STORAGE_ID]
# finish active edit process
if self.active_entry_widget is not None:
text = self.active_entry_widget.get_buffer().get_text()
if focus_column in self.widget_columns:
focus_column.get_cells()[0].emit('edited', path[0], text)
# row could be updated by other call_backs caused by emitting 'edited' signal but selection stays an editable neighbor
path = self.get_path_for_core_element(self.tree_view_keypress_callback.__func__.core_element_id)
if event.keyval == Gdk.KEY_Tab:
# logger.info("move right")
direction = +1
else:
# logger.info("move left")
direction = -1
# get next row_id for focus
if direction < 0 and focus_column is self.widget_columns[0] \
or direction > 0 and focus_column is self.widget_columns[-1]:
if direction < 0 < path[0] or direction > 0 and not path[0] + 1 > len(self.store):
next_row = path[0] + direction
else:
return False
else:
next_row = path[0]
# get next column_id for focus
focus_column_id = self.widget_columns.index(focus_column)
if focus_column_id is not None:
# search all columns for next editable cell renderer
next_focus_column_id = 0
for index in range(len(self.tree_view.get_model())):
test_id = focus_column_id + direction * index + direction
next_focus_column_id = test_id % len(self.widget_columns)
if test_id > len(self.widget_columns) - 1 or test_id < 0:
next_row = path[0] + direction
if next_row < 0 or next_row > len(self.tree_view.get_model()) - 1:
return False
if self.widget_columns[next_focus_column_id].get_cells()[0].get_property('editable'):
break
else:
return False
del self.tree_view_keypress_callback.__func__.core_element_id
# self._logger.info("self.tree_view.scroll_to_cell(next_row={0}, self.widget_columns[{1}] , use_align={2})"
# "".format(next_row, next_focus_column_id, False))
# self.tree_view.scroll_to_cell(next_row, self.widget_columns[next_focus_column_id], use_align=False)
self.tree_view.set_cursor_on_cell(Gtk.TreePath.new_from_indices([next_row]), self.widget_columns[
next_focus_column_id], focus_cell=None, start_editing=True)
return True
else:
super(ListViewController, self).tree_view_keypress_callback(widget, event) | Tab back and forward tab-key motion in list widget and the scrollbar motion to follow key cursor motions
The method introduce motion and edit functionality by using "tab"- or "shift-tab"-key for a Gtk.TreeView.
It is designed to work with a Gtk.TreeView which model is a Gtk.ListStore and only uses text cell renderer.
Additional, the TreeView is assumed to be used as a list not as a tree.
With the "tab"-key the cell on the right site of the actual focused cell is started to be edit. Changes in the
Gtk.Entry-Widget are confirmed by emitting a 'edited'-signal. If the row ends the edit process continues
with the first cell of the next row. With the "shift-tab"-key the inverse functionality of the "tab"-key is
provided.
The Controller over steps not editable cells.
:param Gtk.TreeView widget: The tree view the controller use
:param Gdk.Event event: The key press event
:return: | entailment |
def iter_tree_with_handed_function(self, function, *function_args):
"""Iterate tree view with condition check function"""
def iter_all_children(row_iter, function, function_args):
if isinstance(row_iter, Gtk.TreeIter):
function(row_iter, *function_args)
for n in reversed(range(self.tree_store.iter_n_children(row_iter))):
child_iter = self.tree_store.iter_nth_child(row_iter, n)
iter_all_children(child_iter, function, function_args)
else:
self._logger.warning("Iter has to be TreeIter -> handed argument is: {0}".format(row_iter))
# iter on root level of tree
next_iter = self.tree_store.get_iter_first()
while next_iter:
iter_all_children(next_iter, function, function_args)
next_iter = self.tree_store.iter_next(next_iter) | Iterate tree view with condition check function | entailment |
def update_selection_sm_prior_condition(self, state_row_iter, selected_model_list, sm_selected_model_list):
"""State machine prior update of tree selection for one tree model row"""
selected_path = self.tree_store.get_path(state_row_iter)
tree_model_row = self.tree_store[selected_path]
model = tree_model_row[self.MODEL_STORAGE_ID]
if model not in sm_selected_model_list and model in selected_model_list:
self._tree_selection.unselect_iter(state_row_iter)
elif model in sm_selected_model_list and model not in selected_model_list:
self.tree_view.expand_to_path(selected_path)
self._tree_selection.select_iter(state_row_iter) | State machine prior update of tree selection for one tree model row | entailment |
def update_selection_self_prior_condition(self, state_row_iter, sm_selected_model_set, selected_model_list):
"""Tree view prior update of one model in the state machine selection"""
selected_path = self.tree_store.get_path(state_row_iter)
tree_model_row = self.tree_store[selected_path]
model = tree_model_row[self.MODEL_STORAGE_ID]
if model in sm_selected_model_set and model not in selected_model_list:
sm_selected_model_set.remove(model)
elif model not in sm_selected_model_set and model in selected_model_list:
sm_selected_model_set.add(model) | Tree view prior update of one model in the state machine selection | entailment |
def update_selection_self_prior(self):
"""Tree view prior update of state machine selection"""
if self._do_selection_update:
return
self._do_selection_update = True
tree_selection, selected_model_list, sm_selection, sm_selected_model_set = self.get_selections()
if isinstance(sm_selection, Selection):
# current sm_selected_model_set will be updated and hand it back
self.iter_tree_with_handed_function(self.update_selection_self_prior_condition,
sm_selected_model_set, selected_model_list)
sm_selection.handle_prepared_selection_of_core_class_elements(self.CORE_ELEMENT_CLASS, sm_selected_model_set)
# TODO check if we can solve the difference that occurs e.g. while complex actions?, or same state paths!
# -> models in selection for core element not in the tree the function iter tree + condition tolerates this
if not set(selected_model_list) == sm_selected_model_set:
self._logger.verbose("Difference between tree view selection: \n{0} \nand state machine selection: "
"\n{1}".format(set(selected_model_list), sm_selected_model_set))
# TODO check why sometimes not consistent with sm selection. e.g while modification history test
if self.check_selection_consistency(sm_check=False):
self.update_selection_sm_prior()
self._do_selection_update = False | Tree view prior update of state machine selection | entailment |
def update_selection_sm_prior(self):
"""State machine prior update of tree selection"""
if self._do_selection_update:
return
self._do_selection_update = True
tree_selection, selected_model_list, sm_selection, sm_selected_model_list = self.get_selections()
if tree_selection is not None:
# self._logger.info("SM SELECTION IS: {2}\n{0}, \n{1}".format(selected_model_list, sm_selected_model_list,
# tree_selection.get_mode()))
self.iter_tree_with_handed_function(self.update_selection_sm_prior_condition,
selected_model_list, sm_selected_model_list)
self.check_selection_consistency()
self._do_selection_update = False | State machine prior update of tree selection | entailment |
def select_entry(self, core_element_id, by_cursor=True):
"""Selects the row entry belonging to the given core_element_id by cursor or tree selection"""
path = self.get_path_for_core_element(core_element_id)
if path:
if by_cursor:
self.tree_view.set_cursor(path)
else:
self.tree_view.get_selection().select_path(path)
else:
self._logger.warning("Path not valid: {0} (by_cursor {1})".format(str(core_element_id), str(by_cursor))) | Selects the row entry belonging to the given core_element_id by cursor or tree selection | entailment |
def tree_view_keypress_callback(self, widget, event):
"""Tab back and forward tab-key motion in list widget and the scrollbar motion to follow key cursor motions
The method introduce motion and edit functionality by using "tab"- or "shift-tab"-key for a Gtk.TreeView.
It is designed to work with a Gtk.TreeView which model is a Gtk.ListStore and only uses text cell renderer.
Additional, the TreeView is assumed to be used as a list not as a tree.
With the "tab"-key the cell on the right site of the actual focused cell is started to be edit. Changes in the
Gtk.Entry-Widget are confirmed by emitting a 'edited'-signal. If the row ends the edit process continues
with the first cell of the next row. With the "shift-tab"-key the inverse functionality of the "tab"-key is
provided.
The Controller over steps not editable cells.
:param Gtk.TreeView widget: The tree view the controller use
:param Gdk.Event event: The key press event
:return:
"""
# self._logger.info("key_value: " + str(event.keyval if event is not None else ''))
# TODO works for root level or other single level of tree view but not for switching in between levels
if event and "GDK_KEY_PRESS" == event.type.value_name \
and (event.keyval == Gdk.KEY_Tab or event.keyval == Gdk.KEY_ISO_Left_Tab):
[path, focus_column] = self.tree_view.get_cursor()
# print("cursor ", path, focus_column)
model, paths = self.tree_view.get_selection().get_selected_rows()
if paths:
path = paths[0]
# print("tree selection", path, focus_column, paths)
if not path:
return False
self.tree_view_keypress_callback.__func__.core_element_id = self.store[path][self.ID_STORAGE_ID]
# print("core id", self.store[path][self.ID_STORAGE_ID], path, type(path))
# finish active edit process
if self.active_entry_widget is not None:
text = self.active_entry_widget.get_buffer().get_text()
if focus_column in self.widget_columns:
# print("path", ':'.join([str(elem) for elem in path]))
focus_column.get_cells()[0].emit('edited', ':'.join([str(elem) for elem in path]), text)
# row could be updated by other call_backs caused by emitting 'edited' signal but selection stays an editable neighbor
core_element_id = ':'.join([str(key) for key in self.tree_view_keypress_callback.__func__.core_element_id])
if core_element_id in self._changed_id_to:
self.tree_view_keypress_callback.__func__.core_element_id = self._changed_id_to[core_element_id]
path = self.get_path_for_core_element(self.tree_view_keypress_callback.__func__.core_element_id)
if event.keyval == Gdk.KEY_Tab:
# logger.info("move right")
direction = +1
else:
# logger.info("move left")
direction = -1
if len(path) > 1:
n_elements_in_hierarchy = self.tree_store.iter_n_children(self.tree_store.get_iter(path[:-1]))
else:
n_elements_in_hierarchy = self.tree_store.iter_n_children(None) # root
if direction < 0 and focus_column is self.widget_columns[0] \
or direction > 0 and focus_column is self.widget_columns[-1]:
if direction < 0 < path[-1] or direction > 0 and not path[-1] + 1 > n_elements_in_hierarchy:
next_row = path[-1] + direction
else:
return False
else:
next_row = path[-1]
new_path = tuple(list(path[:-1]) + [next_row])
# print("new path", new_path, path[:-1])
# get next column_id for focus
focus_column_id = self.widget_columns.index(focus_column)
if focus_column_id is not None:
# search all columns for next editable cell renderer
next_focus_column_id = 0
for index in range(len(self.tree_view.get_model())):
test_id = focus_column_id + direction * index + direction
next_focus_column_id = test_id % len(self.widget_columns)
if test_id > len(self.widget_columns) - 1 or test_id < 0:
next_row = path[-1] + direction
if next_row < 0 or next_row > len(self.tree_store[path[:-1]] if len(path) > 1 else self.tree_store) - 1:
return False
if self.widget_columns[next_focus_column_id].get_cells()[0].get_property('editable'):
break
else:
return False
new_path = tuple(list(path[:-1]) + [next_row])
# print("nnew path", new_path)
del self.tree_view_keypress_callback.__func__.core_element_id
# self._logger.info("self.tree_view.scroll_to_cell(next_row={0}, self.widget_columns[{1}] , use_align={2})"
# "".format(next_row, next_focus_column_id, False))
# self.tree_view.scroll_to_cell(new_path, self.widget_columns[next_focus_column_id], use_align=False)
self.tree_view.set_cursor_on_cell(Gtk.TreePath.new_from_indices([new_path]), self.widget_columns[
next_focus_column_id], focus_cell=None, start_editing=True)
return True
else:
super(TreeViewController, self).tree_view_keypress_callback(widget, event) | Tab back and forward tab-key motion in list widget and the scrollbar motion to follow key cursor motions
The method introduce motion and edit functionality by using "tab"- or "shift-tab"-key for a Gtk.TreeView.
It is designed to work with a Gtk.TreeView which model is a Gtk.ListStore and only uses text cell renderer.
Additional, the TreeView is assumed to be used as a list not as a tree.
With the "tab"-key the cell on the right site of the actual focused cell is started to be edit. Changes in the
Gtk.Entry-Widget are confirmed by emitting a 'edited'-signal. If the row ends the edit process continues
with the first cell of the next row. With the "shift-tab"-key the inverse functionality of the "tab"-key is
provided.
The Controller over steps not editable cells.
:param Gtk.TreeView widget: The tree view the controller use
:param Gdk.Event event: The key press event
:return: | entailment |
def contains_geometric_info(var):
""" Check whether the passed variable is a tuple with two floats or integers """
return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var) | Check whether the passed variable is a tuple with two floats or integers | entailment |
def generate_default_state_meta_data(parent_state_m, canvas=None, num_child_state=None, gaphas_editor=True):
"""Generate default meta data for a child state according its parent state
The function could work with the handed num_child_state if all child state are not drawn, till now.
The method checks if the parents meta data is consistent in canvas state view and model if a canvas instance is
handed.
:param rafcon.gui.models.container_state.ContainerStateModel parent_state_m: Model of the state were the child
should be drawn into
:param rafcon.gui.mygaphas.canvas.MyCanvas canvas: canvas instance the state will be drawn into
:param int num_child_state: Number of child states already drawn in canvas parent state view
:return child relative pos (tuple) in parent and it size (tuple)
"""
parent_size = parent_state_m.get_meta_data_editor()['size']
if not contains_geometric_info(parent_size):
raise ValueError("Invalid state size: {}".format(parent_size))
# use handed number of child states and otherwise take number of child states from parent state model
num_child_state = len(parent_state_m.states) if num_child_state is None else num_child_state
# check if respective canvas is handed if meta data of parent canvas view is consistent with model
if canvas is not None:
parent_state_v = canvas.get_view_for_model(parent_state_m)
if not (parent_state_v.width, parent_state_v.height) == parent_size:
logger.warning("Size meta data of model {0} is different to gaphas {1}"
"".format((parent_state_v.width, parent_state_v.height), parent_size))
# Calculate default positions for the child states
# Make the inset from the top left corner
parent_state_width, parent_state_height = parent_size
new_state_side_size = min(parent_state_width * 0.2, parent_state_height * 0.2)
child_width = new_state_side_size
child_height = new_state_side_size
child_size = (child_width, child_height)
child_spacing = max(child_size) * 1.2
parent_margin = cal_margin(parent_size)
# print("parent size", parent_size, parent_margin)
max_cols = (parent_state_width - 2*parent_margin) // child_spacing
(row, col) = divmod(num_child_state, max_cols)
max_rows = (parent_state_height - 2*parent_margin - 0.5*child_spacing) // (1.5*child_spacing)
(overlapping, row) = divmod(row, max_rows)
overlapping_step = 0.5*parent_margin
max_overlaps_x = (parent_state_width - 2*parent_margin - child_width -
(parent_margin + (max_cols - 1) * child_spacing + child_spacing - child_width)) // overlapping_step
max_overlaps_y = (parent_state_height - 2*parent_margin - child_height -
child_spacing * (1.5 * (max_rows - 1) + 1)) // overlapping_step
# handle case of less space TODO check again not perfect, maybe that can be done more simple
max_overlaps_x = 0 if max_overlaps_x < 0 else max_overlaps_x
max_overlaps_y = 0 if max_overlaps_y < 0 else max_overlaps_y
max_overlaps = min(max_overlaps_x, max_overlaps_y) + 1
overlapping = divmod(overlapping, max_overlaps)[1]
child_rel_pos_x = parent_margin + col * child_spacing + child_spacing - child_width + overlapping*overlapping_step
child_rel_pos_y = child_spacing * (1.5 * row + 1.) + overlapping*overlapping_step
return (child_rel_pos_x, child_rel_pos_y), (new_state_side_size, new_state_side_size) | Generate default meta data for a child state according its parent state
The function could work with the handed num_child_state if all child state are not drawn, till now.
The method checks if the parents meta data is consistent in canvas state view and model if a canvas instance is
handed.
:param rafcon.gui.models.container_state.ContainerStateModel parent_state_m: Model of the state were the child
should be drawn into
:param rafcon.gui.mygaphas.canvas.MyCanvas canvas: canvas instance the state will be drawn into
:param int num_child_state: Number of child states already drawn in canvas parent state view
:return child relative pos (tuple) in parent and it size (tuple) | entailment |
def add_boundary_clearance(left, right, top, bottom, frame, clearance=0.1):
"""Increase boundary size
The function increase the space between top and bottom and between left and right parameters.
The increase performed on the biggest size/frame so max(size boundary, size frame)
:param float left: lower x-axis value
:param float right: upper x-axis value
:param float top: lower y-axis value
:param float bottom: upper y-axis value
:param dict frame: Dictionary with size and rel_pos tuples
:param float clearance: Percentage 0.01 = 1% of clearance
:return:
"""
# print("old boundary", left, right, top, bottom)
width = right - left
width = frame['size'][0] if width < frame['size'][0] else width
left -= 0.5 * clearance * width
left = 0 if left < 0 else left
right += 0.5 * clearance * width
height = bottom - top
height = frame['size'][1] if height < frame['size'][1] else height
top -= 0.5 * clearance * height
top = 0 if top < 0 else top
bottom += 0.5 * clearance * height
# print("new boundary", left, right, top, bottom)
return left, right, top, bottom | Increase boundary size
The function increase the space between top and bottom and between left and right parameters.
The increase performed on the biggest size/frame so max(size boundary, size frame)
:param float left: lower x-axis value
:param float right: upper x-axis value
:param float top: lower y-axis value
:param float bottom: upper y-axis value
:param dict frame: Dictionary with size and rel_pos tuples
:param float clearance: Percentage 0.01 = 1% of clearance
:return: | entailment |
def get_boundaries_of_elements_in_dict(models_dict, clearance=0.):
""" Get boundaries of all handed models
The function checks all model meta data positions to increase boundary starting with a state or scoped variables.
It is finally iterated over all states, data and logical port models and linkage if sufficient for respective
graphical editor. At the end a clearance is added to the boundary if needed e.g. to secure size for opengl.
:param models_dict: dict of all handed models
:return: tuple of left, right, top and bottom value
"""
# Determine initial outer coordinates
right = 0.
bottom = 0.
if 'states' in models_dict and models_dict['states']:
left = list(models_dict['states'].items())[0][1].get_meta_data_editor()['rel_pos'][0]
top = list(models_dict['states'].items())[0][1].get_meta_data_editor()['rel_pos'][1]
elif 'scoped_variables' in models_dict and models_dict['scoped_variables']:
left = list(models_dict['scoped_variables'].items())[0][1].get_meta_data_editor()['inner_rel_pos'][0]
top = list(models_dict['scoped_variables'].items())[0][1].get_meta_data_editor()['inner_rel_pos'][1]
else:
all_ports = list(models_dict['input_data_ports'].values()) + list(models_dict['output_data_ports'].values()) + \
list(models_dict['scoped_variables'].values()) + list(models_dict['outcomes'].values())
if len(set([port_m.core_element.parent for port_m in all_ports])) == 1:
logger.info("Only one parent {0} {1}".format(all_ports[0].core_element.parent, all_ports[0].parent.get_meta_data_editor()))
if all_ports:
left = all_ports[0].parent.get_meta_data_editor()['rel_pos'][0]
top = all_ports[0].parent.get_meta_data_editor()['rel_pos'][1]
else:
raise ValueError("Get boundary method does not aspects all list elements empty in dictionary. {0}"
"".format(models_dict))
def cal_max(max_x, max_y, rel_pos, size):
max_x = size[0] + rel_pos[0] if size[0] + rel_pos[0] > max_x else max_x
max_y = rel_pos[1] + size[1] if rel_pos[1] + size[1] > max_y else max_y
return max_x, max_y
def cal_min(min_x, min_y, rel_pos, size):
min_x = rel_pos[0] if rel_pos[0] < min_x else min_x
min_y = rel_pos[1] if rel_pos[1] < min_y else min_y
return min_x, min_y
# Finally take into account all relevant elements in models_dict
# -> states, scoped variables (maybe input- and output- data ports) and transitions and data flows are relevant
parts = ['states', 'transitions', 'data_flows']
for key in parts:
elems_dict = models_dict[key]
rel_positions = []
for model in elems_dict.values():
_size = (0., 0.)
if key == 'states':
rel_positions = [model.get_meta_data_editor()['rel_pos']]
_size = model.get_meta_data_editor()['size']
# print(key, rel_positions, _size)
elif key in ['scoped_variables', 'input_data_ports', 'output_data_ports']:
rel_positions = [model.get_meta_data_editor()['inner_rel_pos']]
# TODO check to take the ports size into account
# print(key, rel_positions, _size)
elif key in ['transitions', 'data_flows']:
if key is "data_flows":
# take into account the meta data positions of opengl if there is some (always in opengl format)
rel_positions = mirror_waypoints(deepcopy(model.get_meta_data_editor()))['waypoints']
else:
rel_positions = model.get_meta_data_editor()['waypoints']
# print(key, rel_positions, _size, model.meta)
for rel_position in rel_positions:
# check for empty fields and ignore them at this point
if not contains_geometric_info(rel_position):
continue
right, bottom = cal_max(right, bottom, rel_position, _size)
left, top = cal_min(left, top, rel_position, _size)
# print("new edges:", left, right, top, bottom, key)
# increase of boundary results into bigger estimated size and finally stronger reduction of original element sizes
left, right, top, bottom = add_boundary_clearance(left, right, top, bottom, {'size': (0., 0.)}, clearance)
return left, right, top, bottom | Get boundaries of all handed models
The function checks all model meta data positions to increase boundary starting with a state or scoped variables.
It is finally iterated over all states, data and logical port models and linkage if sufficient for respective
graphical editor. At the end a clearance is added to the boundary if needed e.g. to secure size for opengl.
:param models_dict: dict of all handed models
:return: tuple of left, right, top and bottom value | entailment |
def cal_frame_according_boundaries(left, right, top, bottom, parent_size, gaphas_editor=True, group=True):
""" Generate margin and relative position and size handed boundary parameter and parent size """
# print("parent_size ->", parent_size)
margin = cal_margin(parent_size)
# Add margin and ensure that the upper left corner is within the state
if group:
# frame of grouped state
rel_pos = max(left - margin, 0), max(top - margin, 0)
# Add margin and ensure that the lower right corner is within the state
size = (min(right - left + 2 * margin, parent_size[0] - rel_pos[0]),
min(bottom - top + 2 * margin, parent_size[1] - rel_pos[1]))
else:
# frame inside of state
# rel_pos = max(margin, 0), max(margin, 0)
rel_pos = left, top
size = right - left, bottom - top
return margin, rel_pos, size | Generate margin and relative position and size handed boundary parameter and parent size | entailment |
def offset_rel_pos_of_all_models_in_dict(models_dict, pos_offset, gaphas_editor=True):
""" Add position offset to all handed models in dict"""
# print("\n", "#"*30, "offset models", pos_offset, "#"*30)
# Update relative position of states within the container in order to maintain their absolute position
for child_state_m in models_dict['states'].values():
old_rel_pos = child_state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['rel_pos']
# print("old_rel_pos", old_rel_pos, child_state_m)
child_state_m.set_meta_data_editor('rel_pos', add_pos(old_rel_pos, pos_offset), from_gaphas=gaphas_editor)
# print("new_rel_pos", child_state_m.get_meta_data_editor(for_gaphas=gaphas_editor), child_state_m)
# Do the same for scoped variable
if not gaphas_editor:
for scoped_variable_m in models_dict['scoped_variables'].values():
old_rel_pos = scoped_variable_m.get_meta_data_editor(for_gaphas=gaphas_editor)['inner_rel_pos']
scoped_variable_m.set_meta_data_editor('inner_rel_pos', add_pos(old_rel_pos, pos_offset), gaphas_editor)
# Do the same for all connections (transitions and data flows)
connection_models = list(models_dict['transitions'].values()) + list(models_dict['data_flows'].values())
for connection_m in connection_models:
old_waypoints = connection_m.get_meta_data_editor(for_gaphas=gaphas_editor)['waypoints']
new_waypoints = []
for waypoint in old_waypoints:
from rafcon.gui.models.data_flow import DataFlowModel
if isinstance(connection_m, DataFlowModel) and gaphas_editor:
new_waypoints.append(add_pos(waypoint, (pos_offset[0], -pos_offset[1])))
else:
new_waypoints.append(add_pos(waypoint, pos_offset))
connection_m.set_meta_data_editor('waypoints', new_waypoints, from_gaphas=gaphas_editor) | Add position offset to all handed models in dict | entailment |
def scale_library_ports_meta_data(state_m, gaphas_editor=True):
"""Scale the ports of library model accordingly relative to state_copy meta size.
The function assumes that the meta data of ports of the state_copy of the library was copied to
respective elements in the library and that those was not adjusted before.
"""
if state_m.meta_data_was_scaled:
return
state_m.income.set_meta_data_editor('rel_pos', state_m.state_copy.income.get_meta_data_editor()['rel_pos'])
# print("scale_library_ports_meta_data ", state_m.get_meta_data_editor()['size'], \)
# state_m.state_copy.get_meta_data_editor()['size']
factor = divide_two_vectors(state_m.get_meta_data_editor()['size'],
state_m.state_copy.get_meta_data_editor()['size'])
# print("scale_library_ports_meta_data -> resize_state_port_meta", factor)
if contains_geometric_info(factor):
resize_state_port_meta(state_m, factor, True)
state_m.meta_data_was_scaled = True
else:
logger.info("Skip resize of library ports meta data {0}".format(state_m)) | Scale the ports of library model accordingly relative to state_copy meta size.
The function assumes that the meta data of ports of the state_copy of the library was copied to
respective elements in the library and that those was not adjusted before. | entailment |
def scale_library_content(library_state_m, gaphas_editor=True):
"""Scales the meta data of the content of a LibraryState
The contents of the `LibraryStateModel` `library_state_m` (i.e., the `state_copy` and all it children/state
elements) to fit the current size of the `LibraryStateModel`.
:param LibraryStateModel library_state_m: The library who's content is to be resized
:param bool gaphas_editor: Whether to use the meta data for the GraphicalEditor using gaphas (default: True)
"""
assert isinstance(library_state_m, LibraryStateModel)
# For library states with an ExecutionState as state_copy, scaling does not make sense
if not isinstance(library_state_m.state_copy, ContainerStateModel):
return
# use same size for state copy and put rel_pos to zero
library_meta = library_state_m.get_meta_data_editor(gaphas_editor)
state_copy_meta = library_state_m.state_copy.set_meta_data_editor('size', library_meta['size'], gaphas_editor)
library_state_m.state_copy.set_meta_data_editor('rel_pos', (0., 0.), from_gaphas=gaphas_editor)
# work around that gaphas draws in state_copy coordinates (which is not shown) -> reduce state copy size
if gaphas_editor:
library_state_margin = cal_margin(state_copy_meta['size'])
state_copy_size = subtract_pos(state_copy_meta['size'], (2*library_state_margin, 2*library_state_margin))
library_state_m.state_copy.set_meta_data_editor('size', state_copy_size, gaphas_editor)
# if meta data has empty fields put default data on state meta data
if model_has_empty_meta(library_state_m.state_copy) and \
not put_default_meta_data_on_state_m_recursively(library_state_m.state_copy, library_state_m,
only_child_states=True):
return
# prepare resize by collecting all state elements in the models_dict
# do resize in respect to state copy
# (opengl same size as library state and in case of gaphas reduced by library state margin)
models_dict = {'state': library_state_m.state_copy}
for state_element_key in library_state_m.state_copy.state.state_element_attrs:
state_element_list = getattr(library_state_m.state_copy, state_element_key)
# Some models are hold in a gtkmvc3.support.wrappers.ObsListWrapper, not a list
if hasattr(state_element_list, 'keys'):
state_element_list = state_element_list.values()
models_dict[state_element_key] = {elem.core_element.core_element_id: elem for elem in state_element_list}
# perform final resize
resize_factor = (1., 1.)
try:
if not models_dict['states'] and (not models_dict['scoped_variables'] or gaphas_editor):
logger.info("Skip scaling for empty root state {0}.".format(library_state_m.state))
else:
resize_factor = scale_meta_data_according_state(models_dict, fill_up=True)
except:
logger.exception("Scale library content of {0} cause a problem.".format(library_state_m.state))
finally:
resize_income_of_state_m(library_state_m.state_copy, resize_factor, gaphas_editor) | Scales the meta data of the content of a LibraryState
The contents of the `LibraryStateModel` `library_state_m` (i.e., the `state_copy` and all it children/state
elements) to fit the current size of the `LibraryStateModel`.
:param LibraryStateModel library_state_m: The library who's content is to be resized
:param bool gaphas_editor: Whether to use the meta data for the GraphicalEditor using gaphas (default: True) | entailment |
def _resize_port_models_list(port_models, rel_pos_key, factor, gaphas_editor=True):
""" Resize relative positions a list of (data or logical) port models """
for port_m in port_models:
old_rel_pos = port_m.get_meta_data_editor(for_gaphas=gaphas_editor)[rel_pos_key]
port_m.set_meta_data_editor(rel_pos_key, mult_two_vectors(factor, old_rel_pos), from_gaphas=gaphas_editor) | Resize relative positions a list of (data or logical) port models | entailment |
def _resize_connection_models_list(connection_models, factor, gaphas_editor=True):
""" Resize relative positions of way points of a list of connection/linkage models """
for connection_m in connection_models:
# print("old_waypoints", connection_m.get_meta_data_editor(for_gaphas=gaphas_editor), connection_m.core_element)
old_waypoints = connection_m.get_meta_data_editor(for_gaphas=gaphas_editor)['waypoints']
new_waypoints = []
for waypoint in old_waypoints:
new_waypoints.append(mult_two_vectors(factor, waypoint))
connection_m.set_meta_data_editor('waypoints', new_waypoints, from_gaphas=gaphas_editor) | Resize relative positions of way points of a list of connection/linkage models | entailment |
def resize_state_port_meta(state_m, factor, gaphas_editor=True):
""" Resize data and logical ports relative positions """
# print("scale ports", factor, state_m, gaphas_editor)
if not gaphas_editor and isinstance(state_m, ContainerStateModel):
port_models = state_m.input_data_ports[:] + state_m.output_data_ports[:] + state_m.scoped_variables[:]
else:
port_models = state_m.input_data_ports[:] + state_m.output_data_ports[:] + state_m.outcomes[:]
port_models += state_m.scoped_variables[:] if isinstance(state_m, ContainerStateModel) else []
_resize_port_models_list(port_models, 'rel_pos' if gaphas_editor else 'inner_rel_pos', factor, gaphas_editor)
resize_income_of_state_m(state_m, factor, gaphas_editor) | Resize data and logical ports relative positions | entailment |
def resize_state_meta(state_m, factor, gaphas_editor=True):
""" Resize state meta data recursive what includes also LibraryStateModels meta data and its internal state_copy
"""
# print("START RESIZE OF STATE", state_m.get_meta_data_editor(for_gaphas=gaphas_editor), state_m)
old_rel_pos = state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['rel_pos']
# print("old_rel_pos state", old_rel_pos, state_m.core_element)
state_m.set_meta_data_editor('rel_pos', mult_two_vectors(factor, old_rel_pos), from_gaphas=gaphas_editor)
# print("new_rel_pos state", state_m.get_meta_data_editor(for_gaphas=gaphas_editor), state_m.core_element)
# print("resize factor", factor, state_m, state_m.meta)
old_size = state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['size']
# print("old_size", old_size, type(old_size))
state_m.set_meta_data_editor('size', mult_two_vectors(factor, old_size), from_gaphas=gaphas_editor)
# print("new_size", state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['size'])
if gaphas_editor:
old_rel_pos = state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['name']['rel_pos']
state_m.set_meta_data_editor('name.rel_pos', mult_two_vectors(factor, old_rel_pos), from_gaphas=gaphas_editor)
old_size = state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['name']['size']
state_m.set_meta_data_editor('name.size', mult_two_vectors(factor, old_size), from_gaphas=gaphas_editor)
if isinstance(state_m, LibraryStateModel):
# print("LIBRARY", state_m)
if gaphas_editor and state_m.state_copy_initialized:
if state_m.meta_data_was_scaled:
resize_state_port_meta(state_m, factor, gaphas_editor)
else:
scale_library_ports_meta_data(state_m, gaphas_editor)
if state_m.state_copy_initialized:
resize_state_meta(state_m.state_copy, factor, gaphas_editor)
# print("END LIBRARY RESIZE")
else:
# print("resize_state_meta -> resize_state_port_meta")
resize_state_port_meta(state_m, factor, gaphas_editor)
if isinstance(state_m, ContainerStateModel):
_resize_connection_models_list(state_m.transitions[:] + state_m.data_flows[:], factor, gaphas_editor)
for child_state_m in state_m.states.values():
resize_state_meta(child_state_m, factor, gaphas_editor) | Resize state meta data recursive what includes also LibraryStateModels meta data and its internal state_copy | entailment |
def offset_rel_pos_of_models_meta_data_according_parent_state(models_dict):
""" Offset meta data of state elements according the area used indicated by the state meta data.
The offset_rel_pos_of_models_meta_data_according_parent_state offset the position of all handed old elements
in the dictionary.
:param models_dict: dict that hold lists of meta data with state attribute consistent keys
:return:
"""
old_parent_rel_pos = models_dict['state'].get_meta_data_editor()['rel_pos']
offset_rel_pos_of_all_models_in_dict(models_dict, pos_offset=old_parent_rel_pos)
return True | Offset meta data of state elements according the area used indicated by the state meta data.
The offset_rel_pos_of_models_meta_data_according_parent_state offset the position of all handed old elements
in the dictionary.
:param models_dict: dict that hold lists of meta data with state attribute consistent keys
:return: | entailment |
def scale_meta_data_according_states(models_dict):
""" Offset meta data of state elements according the area used indicated by the states and
maybe scoped variables (in case of OpenGL editor) meta data.
Method is used by group states to set the offset for the elements in the new container state.
The method needs some generalisation to create methods to easily scale meta data according new parents or views
(e.g. to show inner elements of s library state).
:param models_dict: dictionary that hold lists of meta data with state attribute consistent keys
:return:
"""
left, right, top, bottom = get_boundaries_of_elements_in_dict(models_dict=models_dict)
parent_size = models_dict['state'].parent.get_meta_data_editor()['size']
_, rel_pos, size = cal_frame_according_boundaries(left, right, top, bottom, parent_size)
# Set size and position of new container state
models_dict['state'].set_meta_data_editor('rel_pos', rel_pos)
models_dict['state'].set_meta_data_editor('size', size)
offset = mult_two_vectors((-1., -1.), rel_pos)
offset_rel_pos_of_all_models_in_dict(models_dict, offset)
return True | Offset meta data of state elements according the area used indicated by the states and
maybe scoped variables (in case of OpenGL editor) meta data.
Method is used by group states to set the offset for the elements in the new container state.
The method needs some generalisation to create methods to easily scale meta data according new parents or views
(e.g. to show inner elements of s library state).
:param models_dict: dictionary that hold lists of meta data with state attribute consistent keys
:return: | entailment |
def scale_meta_data_according_state(models_dict, rel_pos=None, as_template=False, fill_up=False):
# TODO Documentation needed....
""" Scale elements in dict to fit into dict state key element.
If elements are already small enough no resize is performed.
"""
# TODO check about positions of input-data- and output-data- or scoped variable-ports is needed
# TODO adjustments of data ports positions are not sufficient -> origin state size is maybe needed for that
# TODO consistency check on boundary and scale parameter for every if else case
if 'states' in models_dict or 'scoped_variables' in models_dict:
left, right, top, bottom = get_boundaries_of_elements_in_dict(models_dict=models_dict)
parent_size = models_dict['state'].get_meta_data_editor()['size']
margin, old_rel_pos, size = cal_frame_according_boundaries(left, right, top, bottom, parent_size, group=False)
automatic_mode = True if rel_pos is None else False
clearance = 0.2 if rel_pos is None else 0.
rel_pos = (margin, margin) if rel_pos is None else rel_pos
# rel_pos = (0., 0.) if fill_up else rel_pos
clearance_scale = 1 + clearance
assert parent_size[0] > rel_pos[0]
assert parent_size[1] > rel_pos[1]
# print("edges:", left, right, top, bottom)
# print("margin:", margin, "rel_pos:", rel_pos, "old_rel_pos", old_rel_pos, "size:", size)
parent_width, parent_height = parent_size
boundary_width, boundary_height = size
# print("parent width: {0}, parent_height: {1}".format(parent_width, parent_height))
# print("boundary width: {0}, boundary_height: {1}".format(boundary_width, boundary_height))
# no site scale
if parent_width - rel_pos[0] > boundary_width * clearance_scale and \
parent_height - rel_pos[1] > boundary_height * clearance_scale and not fill_up:
if automatic_mode:
resize_factor = 1.
boundary_width_in_parent = boundary_width*resize_factor
# print(boundary_width, resize_factor, boundary_width*resize_factor, boundary_height*resize_factor + margin*2, parent_height)
# print("left over width: ", parent_width - boundary_width_in_parent - rel_pos[0] - margin)
width_pos_offset_to_middle = (parent_width - boundary_width_in_parent - rel_pos[0] - margin)/2.
rel_pos = add_pos(rel_pos, (width_pos_offset_to_middle, 0.))
boundary_height_in_parent = boundary_height*resize_factor
# print("left over height: ", parent_height - boundary_height_in_parent - rel_pos[0] - margin)
height_pos_offset_to_middle = (parent_height - boundary_height_in_parent - rel_pos[1] - margin)/2.
rel_pos = add_pos(rel_pos, (0., height_pos_offset_to_middle))
offset = subtract_pos((0., 0.), subtract_pos(old_rel_pos, rel_pos))
offset_rel_pos_of_all_models_in_dict(models_dict, offset)
return 1, 1 # (1, 1), offset, rel_pos
# smallest site scale
else:
# increase of boundary or clearance results into bigger estimated size and finally stronger
# reduction of original element sizes
left, right, top, bottom = get_boundaries_of_elements_in_dict(models_dict=models_dict, clearance=clearance)
parent_size = models_dict['state'].get_meta_data_editor()['size']
margin, old_rel_pos, size = cal_frame_according_boundaries(left, right, top, bottom, parent_size, group=False)
rel_pos = (margin, margin) if rel_pos is None else rel_pos
assert parent_size[0] > rel_pos[0]
assert parent_size[1] > rel_pos[1]
# print("edges:", left, right, top, bottom)
# print("margin:", margin, "rel_pos:", rel_pos, "old_rel_pos", old_rel_pos, "size:", size)
parent_width, parent_height = parent_size
boundary_width, boundary_height = size
if (parent_height - rel_pos[1] - margin)/boundary_height < \
(parent_width - rel_pos[0] - margin)/boundary_width:
# print("#2"*20, 1, "#"*20, rel_pos)
resize_factor = (parent_height - rel_pos[1] - margin)/boundary_height
boundary_width_in_parent = boundary_width*resize_factor
# print(boundary_width, resize_factor, boundary_width*resize_factor)
# print("left over width: ", parent_width - boundary_width_in_parent - rel_pos[0] - margin)
width_pos_offset_to_middle = (parent_width - boundary_width_in_parent - rel_pos[0] - margin)/2.
rel_pos = add_pos(rel_pos, (width_pos_offset_to_middle, 0.))
# print(resize_factor, rel_pos)
else:
# print("#2"*20, 2, "#"*20, rel_pos)
resize_factor = (parent_width - rel_pos[0] - margin)/boundary_width
boundary_height_in_parent = boundary_height*resize_factor
# print(boundary_width, resize_factor, boundary_width*resize_factor)
# print("left over height: ", parent_height - boundary_height_in_parent - rel_pos[0] - margin)
height_pos_offset_to_middle = (parent_height - boundary_height_in_parent - rel_pos[1] - margin)/2.
rel_pos = add_pos(rel_pos, (0., height_pos_offset_to_middle))
# print(resize_factor, rel_pos)
frame = {'rel_pos': rel_pos, 'size': mult_two_vectors((resize_factor, resize_factor), size)}
# print(models_dict['state'].get_meta_data_editor()['rel_pos'], \)
# parent_size, models_dict['state'].parent.get_meta_data_editor()['size']
# print("frame", frame, resize_factor)
# # rel_pos = mult_two_vectors((1, -1), frame['rel_pos'])
offset = subtract_pos((0., 0.), old_rel_pos)
offset_rel_pos_of_all_models_in_dict(models_dict, offset)
resize_of_all_models_in_dict(models_dict, (resize_factor, resize_factor))
offset_rel_pos_of_all_models_in_dict(models_dict, frame['rel_pos'])
# scale_meta_data_according_frame(models_dict, frame)
return resize_factor, resize_factor # (resize_factor, resize_factor) , offset, frame['rel_pos']
else:
return 1, 1 | Scale elements in dict to fit into dict state key element.
If elements are already small enough no resize is performed. | entailment |
def get_closest_sibling_state(state_m, from_logical_port=None):
""" Calculate the closest sibling also from optional logical port of handed state model
:param StateModel state_m: Reference State model the closest sibling state should be find for
:param str from_logical_port: The logical port of handed state model to be used as reference.
:rtype: tuple
:return: distance, StateModel of closest state
"""
if not state_m.parent:
logger.warning("A state can not have a closest sibling state if it has not parent as {0}".format(state_m))
return
margin = cal_margin(state_m.parent.get_meta_data_editor()['size'])
pos = state_m.get_meta_data_editor()['rel_pos']
size = state_m.get_meta_data_editor()['size'] # otherwise measure from reference state itself
if from_logical_port in ["outcome", "income"]:
size = (margin, margin)
if from_logical_port == "outcome":
outcomes_m = [outcome_m for outcome_m in state_m.outcomes if outcome_m.outcome.outcome_id >= 0]
free_outcomes_m = [oc_m for oc_m in outcomes_m
if not state_m.state.parent.get_transition_for_outcome(state_m.state, oc_m.outcome)]
if free_outcomes_m:
outcome_m = free_outcomes_m[0]
else:
outcome_m = outcomes_m[0]
pos = add_pos(pos, outcome_m.get_meta_data_editor()['rel_pos'])
elif from_logical_port == "income":
pos = add_pos(pos, state_m.income.get_meta_data_editor()['rel_pos'])
min_distance = None
for sibling_state_m in state_m.parent.states.values():
if sibling_state_m is state_m:
continue
sibling_pos = sibling_state_m.get_meta_data_editor()['rel_pos']
sibling_size = sibling_state_m.get_meta_data_editor()['size']
distance = geometry.cal_dist_between_2_coord_frame_aligned_boxes(pos, size, sibling_pos, sibling_size)
if not min_distance or min_distance[0] > distance:
min_distance = (distance, sibling_state_m)
return min_distance | Calculate the closest sibling also from optional logical port of handed state model
:param StateModel state_m: Reference State model the closest sibling state should be find for
:param str from_logical_port: The logical port of handed state model to be used as reference.
:rtype: tuple
:return: distance, StateModel of closest state | entailment |
def get_action_arguments(self, target_state_m):
""" Collect argument attributes for action signal
Use non empty list dict to create arguments for action signal msg and logger messages. The action parent model
can be different then the target state model because logical and data port changes also may influence the
linkage, see action-module (undo/redo).
:param rafcon.gui.models.abstract_state.AbstractStateModel target_state_m: State model of target of action
:return: dict with lists of elements part of the action, action parent model
"""
non_empty_lists_dict = {key: elems for key, elems in self.model_copies.items() if elems}
port_attrs = ['input_data_ports', 'output_data_ports', 'scoped_variables', 'outcomes']
port_is_pasted = any([key in non_empty_lists_dict for key in port_attrs])
return non_empty_lists_dict, target_state_m.parent if target_state_m.parent and port_is_pasted else target_state_m | Collect argument attributes for action signal
Use non empty list dict to create arguments for action signal msg and logger messages. The action parent model
can be different then the target state model because logical and data port changes also may influence the
linkage, see action-module (undo/redo).
:param rafcon.gui.models.abstract_state.AbstractStateModel target_state_m: State model of target of action
:return: dict with lists of elements part of the action, action parent model | entailment |
def copy(self, selection, smart_selection_adaption=True):
""" Copy all selected items to the clipboard using smart selection adaptation by default
:param selection: the current selection
:param bool smart_selection_adaption: flag to enable smart selection adaptation mode
:return:
"""
assert isinstance(selection, Selection)
self.__create_core_and_model_object_copies(selection, smart_selection_adaption) | Copy all selected items to the clipboard using smart selection adaptation by default
:param selection: the current selection
:param bool smart_selection_adaption: flag to enable smart selection adaptation mode
:return: | entailment |
def cut(self, selection, smart_selection_adaption=False):
"""Cuts all selected items and copy them to the clipboard using smart selection adaptation by default
:param selection: the current selection
:param bool smart_selection_adaption: flag to enable smart selection adaptation mode
:return:
"""
assert isinstance(selection, Selection)
import rafcon.gui.helpers.state_machine as gui_helper_state_machine
if gui_helper_state_machine.is_selection_inside_of_library_state(selected_elements=selection.get_all()):
logger.warning("Cut is not performed because elements inside of a library state are selected.")
return
selection_dict_of_copied_models, parent_m = self.__create_core_and_model_object_copies(
selection, smart_selection_adaption)
non_empty_lists_dict, action_parent_m = self.get_action_arguments(parent_m if parent_m else None)
action_parent_m.action_signal.emit(ActionSignalMsg(action='cut', origin='clipboard',
action_parent_m=action_parent_m,
affected_models=[], after=False,
kwargs={'remove': non_empty_lists_dict}))
for models in selection_dict_of_copied_models.values():
gui_helper_state_machine.delete_core_elements_of_models(models, destroy=True,
recursive=True, force=False)
affected_models = [model for models in non_empty_lists_dict.values() for model in models]
action_parent_m.action_signal.emit(ActionSignalMsg(action='cut', origin='clipboard',
action_parent_m=action_parent_m,
affected_models=affected_models, after=True)) | Cuts all selected items and copy them to the clipboard using smart selection adaptation by default
:param selection: the current selection
:param bool smart_selection_adaption: flag to enable smart selection adaptation mode
:return: | entailment |
def paste(self, target_state_m, cursor_position=None, limited=None, convert=False):
"""Paste objects to target state
The method checks whether the target state is a execution state or a container state and inserts respective
elements and notifies the user if the parts can not be insert to the target state.
- for ExecutionStates outcomes, input- and output-data ports can be inserted
- for ContainerState additional states, scoped variables and data flows and/or transitions (if related) can be
inserted
Related data flows and transitions are determined by origin and target keys and respective objects which has to
be in the state machine selection, too. Thus, transitions or data flows without the related objects are not copied.
:param target_state_m: state in which the copied/cut elements should be insert
:param cursor_position: cursor position used to adapt meta data positioning of elements e.g states and
via points
:return:
"""
self.reset_clipboard_mapping_dicts()
if not isinstance(target_state_m, StateModel):
logger.warning("Paste is not performed because target state indication has to be a StateModel not {0}"
"".format(target_state_m.__class__.__name__))
return
if target_state_m.state.get_next_upper_library_root_state() is not None:
logger.warning("Paste is not performed because selected target state is inside of a library state.")
return
element_m_copy_lists = self.model_copies
self.prepare_new_copy() # threaded in future -> important that the copy is prepared here!!!
# use non empty list dict to create arguments for action signal msg and logger messages
dict_of_non_empty_lists_of_model_copies, action_parent_m = self.get_action_arguments(target_state_m)
action_parent_m.action_signal.emit(ActionSignalMsg(action='paste', origin='clipboard',
action_parent_m=action_parent_m,
affected_models=[], after=False,
kwargs={'insert': dict_of_non_empty_lists_of_model_copies,
'convert': convert,
'limited': limited}))
self.state_id_mapping_dict[self.copy_parent_state_id] = target_state_m.state.state_id
# prepare list of lists to copy for limited or converted paste of objects
target_state_element_attrs = target_state_m.state.state_element_attrs
if limited and all([state_element_attr in target_state_element_attrs for state_element_attr in limited]):
if len(limited) == 1 and limited[0] in ['input_data_ports', 'output_data_ports', 'scoped_variables'] and convert:
combined_list = element_m_copy_lists['input_data_ports'] + element_m_copy_lists['output_data_ports'] + \
element_m_copy_lists['scoped_variables']
for state_element_attr in ['input_data_ports', 'output_data_ports', 'scoped_variables']:
element_m_copy_lists[state_element_attr] = combined_list
state_element_attrs_to_insert = limited
else:
state_element_attrs_to_insert = target_state_element_attrs
# check list order and put transitions and data flows to the end
for state_element_attr in ['transitions', 'data_flows']:
if state_element_attr in state_element_attrs_to_insert:
state_element_attrs_to_insert.remove(state_element_attr)
state_element_attrs_to_insert.append(state_element_attr)
def insert_elements_from_model_copies_list(model_list, state_element_name):
""" Insert/add all core elements of model_list into the target_state_m
The function returns a list of pairs of models (new and original models) because the target_state_m for
some insert operations still generates a new model.
:param list model_list: list of models
:param str state_element_name: appendix string to "_insert_*" to get the attribute of respective methods in
clipboard-class.
:return: list of pairs of models (new and original models)
:rtype: list[tuple]
"""
new_and_copied_models = []
for orig_element_m_copy in model_list:
try:
# hold orig_element_m_copy related to newly generated model for debugging reasons
# (its doubt that ids are fully correct, meta data is considered to be alright now)
insert_function = getattr(self, '_insert_{0}'.format(state_element_name)) # e.g. self._insert_state
new_element_m = insert_function(target_state_m, orig_element_m_copy)
new_and_copied_models.append((new_element_m, orig_element_m_copy))
except (ValueError, AttributeError, TypeError) as e:
logger.warning("While inserting a {0} a failure was detected, exception: {1}."
"".format(state_element_name, e))
return new_and_copied_models
# insert all lists and their elements into target state
# insert_dict hold lists of pairs of models -> new (maybe generated by parent model) and original copy
insert_dict = dict()
for state_element_attr in state_element_attrs_to_insert:
state_element_name = state_element_attr[:-1] # e.g. "states" => "state", "outcomes" => "outcome"
insert_dict[state_element_attr] = \
insert_elements_from_model_copies_list(element_m_copy_lists[state_element_attr],
state_element_name)
# move meta data from original copied model to newly insert models and resize them to fit into target_state_m
models_dict = {'state': target_state_m}
for state_element_attr, state_elements in insert_dict.items():
models_dict[state_element_attr] = {}
for new_state_element_m, copied_state_element_m in state_elements:
new_core_element_id = new_state_element_m.core_element.core_element_id
models_dict[state_element_attr][new_core_element_id] = new_state_element_m
affected_models = []
for key, state_elements in insert_dict.items():
if key == 'state':
continue
for new_state_element_m, copied_state_element_m in state_elements:
affected_models.append(new_state_element_m)
# commented parts are here for later use to detect empty meta data fields and debug those
if all([all([not gui_helpers_meta_data.model_has_empty_meta(state_element_m) for state_element_m, _ in elems_list])
if isinstance(elems_list, list) else gui_helpers_meta_data.model_has_empty_meta(elems_list)
for elems_list in insert_dict.values()]) or \
len(dict_of_non_empty_lists_of_model_copies) == 1 and 'states' in dict_of_non_empty_lists_of_model_copies:
try:
gui_helpers_meta_data.scale_meta_data_according_state(models_dict)
except:
logger.exception("Scale of pasted content {0} cause a problems.".format(models_dict))
else:
# TODO this should become a warning in the future or the meta module has to handle the empty data fields
logger.info("Paste miss meta to scale. {0}".format(affected_models))
if not affected_models:
logger.warning("Paste with no effect. No elements pasted from {0}".format(dict_of_non_empty_lists_of_model_copies))
action_parent_m.action_signal.emit(ActionSignalMsg(action='paste', origin='clipboard',
action_parent_m=action_parent_m,
affected_models=affected_models, after=True))
return insert_dict | Paste objects to target state
The method checks whether the target state is a execution state or a container state and inserts respective
elements and notifies the user if the parts can not be insert to the target state.
- for ExecutionStates outcomes, input- and output-data ports can be inserted
- for ContainerState additional states, scoped variables and data flows and/or transitions (if related) can be
inserted
Related data flows and transitions are determined by origin and target keys and respective objects which has to
be in the state machine selection, too. Thus, transitions or data flows without the related objects are not copied.
:param target_state_m: state in which the copied/cut elements should be insert
:param cursor_position: cursor position used to adapt meta data positioning of elements e.g states and
via points
:return: | entailment |
def reset_clipboard(self):
""" Resets the clipboard, so that old elements do not pollute the new selection that is copied into the
clipboard.
:return:
"""
# reset selections
for state_element_attr in ContainerState.state_element_attrs:
self.model_copies[state_element_attr] = []
# reset parent state_id the copied elements are taken from
self.copy_parent_state_id = None
self.reset_clipboard_mapping_dicts() | Resets the clipboard, so that old elements do not pollute the new selection that is copied into the
clipboard.
:return: | entailment |
def do_selection_reduction_to_one_parent(selection):
""" Find and reduce selection to one parent state.
:param selection:
:return: state model which is parent of selection or None if root state
"""
all_models_selected = selection.get_all()
# check if all elements selected are on one hierarchy level -> TODO or in future are parts of sibling?!
# if not take the state with the most siblings as the copy root
parent_m_count_dict = {}
for model in all_models_selected:
parent_m_count_dict[model.parent] = parent_m_count_dict[model.parent] + 1 if model.parent in parent_m_count_dict else 1
parent_m = None
current_count_parent = 0
for possible_parent_m, count in parent_m_count_dict.items():
parent_m = possible_parent_m if current_count_parent < count else parent_m
# if root no parent exist and only on model can be selected
if len(selection.states) == 1 and selection.get_selected_state().state.is_root_state:
parent_m = None
# kick all selection except root_state
if len(all_models_selected) > 1:
selection.set(selection.get_selected_state())
if parent_m is not None:
# check and reduce selection
for model in all_models_selected:
if model.parent is not parent_m:
selection.remove(model)
return parent_m | Find and reduce selection to one parent state.
:param selection:
:return: state model which is parent of selection or None if root state | entailment |
def do_smart_selection_adaption(selection, parent_m):
""" Reduce and extend transition and data flow element selection if already enclosed by selection
The smart selection adaptation checks and ignores directly data flows and transitions which are selected
without selected related origin or targets elements. Additional the linkage (data flows and transitions)
if those origins and targets are covered by the selected elements is added to the selection.
Thereby the selection it self is manipulated to provide direct feedback to the user.
:param selection:
:param parent_m:
:return:
"""
def get_ports_related_to_data_flow(data_flow):
from_port = data_flow.parent.get_data_port(data_flow.from_state, data_flow.from_key)
to_port = data_flow.parent.get_data_port(data_flow.to_state, data_flow.to_key)
return from_port, to_port
def get_states_related_to_transition(transition):
if transition.from_state == transition.parent.state_id or transition.from_state is None:
from_state = transition.parent
else:
from_state = transition.parent.states[transition.from_state]
if transition.to_state == transition.parent.state_id:
to_state = transition.parent
else:
to_state = transition.parent.states[transition.to_state]
if transition.to_outcome in transition.parent.outcomes:
to_outcome = transition.parent.outcomes[transition.to_outcome]
else:
to_outcome = transition.to_outcome
return from_state, to_state, to_outcome
# reduce linkage selection by not fully by selection covered linkage
possible_states = [state_m.state for state_m in selection.states]
possible_outcomes = [outcome_m.outcome for outcome_m in selection.outcomes]
for data_flow_m in selection.data_flows:
from_port, to_port = get_ports_related_to_data_flow(data_flow_m.data_flow)
if from_port.parent not in possible_states or to_port not in possible_states:
selection.remove(data_flow_m)
for transition_m in selection.transitions:
from_state, to_state, to_oc = get_states_related_to_transition(transition_m.transition)
if from_state not in possible_states or (to_state not in possible_states and to_oc not in possible_outcomes):
selection.remove(transition_m)
# extend linkage selection by fully by selected element enclosed linkage
if parent_m and isinstance(parent_m.state, ContainerState):
state_ids = [state.state_id for state in possible_states]
port_ids = [sv_m.scoped_variable.data_port_id for sv_m in selection.scoped_variables] + \
[ip_m.data_port.data_port_id for ip_m in selection.input_data_ports] + \
[op_m.data_port.data_port_id for op_m in selection.output_data_ports]
ports = [sv_m.scoped_variable for sv_m in selection.scoped_variables] + \
[ip_m.data_port for ip_m in selection.input_data_ports] + \
[op_m.data_port for op_m in selection.output_data_ports]
related_transitions, related_data_flows = \
parent_m.state.related_linkage_states_and_scoped_variables(state_ids, port_ids)
# extend by selected states or a port and a state enclosed data flows
for data_flow in related_data_flows['enclosed']:
data_flow_m = parent_m.get_data_flow_m(data_flow.data_flow_id)
if data_flow_m not in selection.data_flows:
selection.add(data_flow_m)
# extend by selected ports enclosed data flows
for data_flow_id, data_flow in parent_m.state.data_flows.items():
from_port, to_port = get_ports_related_to_data_flow(data_flow)
if from_port in ports and to_port in ports:
selection.add(parent_m.get_data_flow_m(data_flow_id))
# extend by selected states enclosed transitions
for transition in related_transitions['enclosed']:
transition_m = parent_m.get_transition_m(transition.transition_id)
if transition_m not in selection.transitions:
selection.add(transition_m)
# extend by selected state and outcome enclosed transitions
for transition_id, transition in parent_m.state.transitions.items():
from_state, to_state, to_oc = get_states_related_to_transition(transition)
if from_state in possible_states and to_oc in possible_outcomes:
selection.add(parent_m.get_transition_m(transition_id)) | Reduce and extend transition and data flow element selection if already enclosed by selection
The smart selection adaptation checks and ignores directly data flows and transitions which are selected
without selected related origin or targets elements. Additional the linkage (data flows and transitions)
if those origins and targets are covered by the selected elements is added to the selection.
Thereby the selection it self is manipulated to provide direct feedback to the user.
:param selection:
:param parent_m:
:return: | entailment |
def __create_core_and_model_object_copies(self, selection, smart_selection_adaption):
"""Copy all elements of a selection.
The method copies all objects and modifies the selection before copying the elements if the smart flag is true.
The smart selection adaption is by default enabled. In any case the selection is reduced to have one parent
state that is used as the root of copy, except a root state it self is selected.
:param Selection selection: an arbitrary selection, whose elements should be copied
.param bool smart_selection_adaption: flag to enable smart selection adaptation mode
:return: dictionary of selected models copied, parent model of copy
"""
all_models_selected = selection.get_all()
if not all_models_selected:
logger.warning("Nothing to copy because state machine selection is empty.")
return
parent_m = self.do_selection_reduction_to_one_parent(selection)
self.copy_parent_state_id = parent_m.state.state_id if parent_m else None
if smart_selection_adaption:
self.do_smart_selection_adaption(selection, parent_m)
# store all lists of selection
selected_models_dict = {}
for state_element_attr in ContainerState.state_element_attrs:
selected_models_dict[state_element_attr] = list(getattr(selection, state_element_attr))
# delete old models
self.destroy_all_models_in_dict(self.model_copies)
# copy all selected elements
self.model_copies = deepcopy(selected_models_dict)
new_content_of_clipboard = ', '.join(["{0} {1}".format(len(elems), key if len(elems) > 1 else key[:-1])
for key, elems in self.model_copies.items() if elems])
logger.info("The new content is {0}".format(new_content_of_clipboard.replace('_', ' ')))
return selected_models_dict, parent_m | Copy all elements of a selection.
The method copies all objects and modifies the selection before copying the elements if the smart flag is true.
The smart selection adaption is by default enabled. In any case the selection is reduced to have one parent
state that is used as the root of copy, except a root state it self is selected.
:param Selection selection: an arbitrary selection, whose elements should be copied
.param bool smart_selection_adaption: flag to enable smart selection adaptation mode
:return: dictionary of selected models copied, parent model of copy | entailment |
def destroy_all_models_in_dict(target_dict):
""" Method runs the prepare destruction method of models
which are assumed in list or tuple as values within a dict
"""
if target_dict:
for model_list in target_dict.values():
if isinstance(model_list, (list, tuple)):
for model in model_list:
model.prepare_destruction()
if model._parent:
model._parent = None
else:
raise Exception("wrong data in clipboard") | Method runs the prepare destruction method of models
which are assumed in list or tuple as values within a dict | entailment |
def destroy(self):
""" Destroys the clipboard by relieving all model references.
"""
self.destroy_all_models_in_dict(self.model_copies)
self.model_copies = None
self.copy_parent_state_id = None
self.outcome_id_mapping_dict = None
self.port_id_mapping_dict = None
self.state_id_mapping_dict = None | Destroys the clipboard by relieving all model references. | entailment |
def extend_extents(extents, factor=1.1):
"""Extend a given bounding box
The bounding box (x1, y1, x2, y2) is centrally stretched by the given factor.
:param extents: The bound box extents
:param factor: The factor for stretching
:return: (x1, y1, x2, y2) of the extended bounding box
"""
width = extents[2] - extents[0]
height = extents[3] - extents[1]
add_width = (factor - 1) * width
add_height = (factor - 1) * height
x1 = extents[0] - add_width / 2
x2 = extents[2] + add_width / 2
y1 = extents[1] - add_height / 2
y2 = extents[3] + add_height / 2
return x1, y1, x2, y2 | Extend a given bounding box
The bounding box (x1, y1, x2, y2) is centrally stretched by the given factor.
:param extents: The bound box extents
:param factor: The factor for stretching
:return: (x1, y1, x2, y2) of the extended bounding box | entailment |
def calc_rel_pos_to_parent(canvas, item, handle):
"""This method calculates the relative position of the given item's handle to its parent
:param canvas: Canvas to find relative position in
:param item: Item to find relative position to parent
:param handle: Handle of item to find relative position to
:return: Relative position (x, y)
"""
from gaphas.item import NW
if isinstance(item, ConnectionView):
return item.canvas.get_matrix_i2i(item, item.parent).transform_point(*handle.pos)
parent = canvas.get_parent(item)
if parent:
return item.canvas.get_matrix_i2i(item, parent).transform_point(*handle.pos)
else:
return item.canvas.get_matrix_i2c(item).transform_point(*item.handles()[NW].pos) | This method calculates the relative position of the given item's handle to its parent
:param canvas: Canvas to find relative position in
:param item: Item to find relative position to parent
:param handle: Handle of item to find relative position to
:return: Relative position (x, y) | entailment |
def assert_exactly_one_true(bool_list):
"""This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise
"""
assert isinstance(bool_list, list)
counter = 0
for item in bool_list:
if item:
counter += 1
return counter == 1 | This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise | entailment |
def get_state_id_for_port(port):
"""This method returns the state ID of the state containing the given port
:param port: Port to check for containing state ID
:return: State ID of state containing port
"""
parent = port.parent
from rafcon.gui.mygaphas.items.state import StateView
if isinstance(parent, StateView):
return parent.model.state.state_id | This method returns the state ID of the state containing the given port
:param port: Port to check for containing state ID
:return: State ID of state containing port | entailment |
def get_port_for_handle(handle, state):
"""Looks for and returns the PortView to the given handle in the provided state
:param handle: Handle to look for port
:param state: State containing handle and port
:returns: PortView for handle
"""
from rafcon.gui.mygaphas.items.state import StateView
if isinstance(state, StateView):
if state.income.handle == handle:
return state.income
else:
for outcome in state.outcomes:
if outcome.handle == handle:
return outcome
for input in state.inputs:
if input.handle == handle:
return input
for output in state.outputs:
if output.handle == handle:
return output
for scoped in state.scoped_variables:
if scoped.handle == handle:
return scoped | Looks for and returns the PortView to the given handle in the provided state
:param handle: Handle to look for port
:param state: State containing handle and port
:returns: PortView for handle | entailment |
def create_new_connection(from_port, to_port):
"""Checks the type of connection and tries to create it
If bot port are logical port,s a transition is created. If both ports are data ports (including scoped variable),
then a data flow is added. An error log is created, when the types are not compatible.
:param from_port: The starting port of the connection
:param to_port: The end point of the connection
:return: True if a new connection was added
"""
from rafcon.gui.mygaphas.items.ports import ScopedVariablePortView, LogicPortView, DataPortView
if isinstance(from_port, LogicPortView) and isinstance(to_port, LogicPortView):
return add_transition_to_state(from_port, to_port)
elif isinstance(from_port, (DataPortView, ScopedVariablePortView)) and \
isinstance(to_port, (DataPortView, ScopedVariablePortView)):
return add_data_flow_to_state(from_port, to_port)
# Both ports are not None
elif from_port and to_port:
logger.error("Connection of non-compatible ports: {0} and {1}".format(type(from_port), type(to_port)))
return False | Checks the type of connection and tries to create it
If bot port are logical port,s a transition is created. If both ports are data ports (including scoped variable),
then a data flow is added. An error log is created, when the types are not compatible.
:param from_port: The starting port of the connection
:param to_port: The end point of the connection
:return: True if a new connection was added | entailment |
def add_data_flow_to_state(from_port, to_port):
"""Interface method between Gaphas and RAFCON core for adding data flows
The method checks the types of the given ports and their relation. From this the necessary parameters for the
add_dat_flow method of the RAFCON core are determined. Also the parent state is derived from the ports.
:param from_port: Port from which the data flow starts
:param to_port: Port to which the data flow goes to
:return: True if a data flow was added, False if an error occurred
"""
from rafcon.gui.mygaphas.items.ports import InputPortView, OutputPortView, ScopedVariablePortView
from rafcon.gui.models.container_state import ContainerStateModel
from_state_v = from_port.parent
to_state_v = to_port.parent
from_state_m = from_state_v.model
to_state_m = to_state_v.model
from_state_id = from_state_m.state.state_id
to_state_id = to_state_m.state.state_id
from_port_id = from_port.port_id
to_port_id = to_port.port_id
if not isinstance(from_port, (InputPortView, OutputPortView, ScopedVariablePortView)) or \
not isinstance(from_port, (InputPortView, OutputPortView, ScopedVariablePortView)):
logger.error("Data flows only exist between data ports (input, output, scope). Given: {0} and {1}".format(type(
from_port), type(to_port)))
return False
responsible_parent_m = None
# from parent to child
if isinstance(from_state_m, ContainerStateModel) and \
check_if_dict_contains_object_reference_in_values(to_state_m.state, from_state_m.state.states):
responsible_parent_m = from_state_m
# from child to parent
elif isinstance(to_state_m, ContainerStateModel) and \
check_if_dict_contains_object_reference_in_values(from_state_m.state, to_state_m.state.states):
responsible_parent_m = to_state_m
# from parent to parent
elif isinstance(from_state_m, ContainerStateModel) and from_state_m.state is to_state_m.state:
responsible_parent_m = from_state_m # == to_state_m
# from child to child
elif (not from_state_m.state.is_root_state) and (not to_state_m.state.is_root_state) \
and from_state_m.state is not to_state_m.state \
and from_state_m.parent.state.state_id and to_state_m.parent.state.state_id:
responsible_parent_m = from_state_m.parent
if not isinstance(responsible_parent_m, ContainerStateModel):
logger.error("Data flows only exist in container states (e.g. hierarchy states)")
return False
try:
responsible_parent_m.state.add_data_flow(from_state_id, from_port_id, to_state_id, to_port_id)
return True
except (ValueError, AttributeError, TypeError) as e:
logger.error("Data flow couldn't be added: {0}".format(e))
return False | Interface method between Gaphas and RAFCON core for adding data flows
The method checks the types of the given ports and their relation. From this the necessary parameters for the
add_dat_flow method of the RAFCON core are determined. Also the parent state is derived from the ports.
:param from_port: Port from which the data flow starts
:param to_port: Port to which the data flow goes to
:return: True if a data flow was added, False if an error occurred | entailment |
def add_transition_to_state(from_port, to_port):
"""Interface method between Gaphas and RAFCON core for adding transitions
The method checks the types of the given ports (IncomeView or OutcomeView) and from this determines the necessary
parameters for the add_transition method of the RAFCON core. Also the parent state is derived from the ports.
:param from_port: Port from which the transition starts
:param to_port: Port to which the transition goes to
:return: True if a transition was added, False if an error occurred
"""
from rafcon.gui.mygaphas.items.ports import IncomeView, OutcomeView
from_state_v = from_port.parent
to_state_v = to_port.parent
from_state_m = from_state_v.model
to_state_m = to_state_v.model
# Gather necessary information to create transition
from_state_id = from_state_m.state.state_id
to_state_id = to_state_m.state.state_id
responsible_parent_m = None
# Start transition
if isinstance(from_port, IncomeView):
from_state_id = None
from_outcome_id = None
responsible_parent_m = from_state_m
# Transition from parent income to child income
if isinstance(to_port, IncomeView):
to_outcome_id = None
# Transition from parent income to parent outcome
elif isinstance(to_port, OutcomeView):
to_outcome_id = to_port.outcome_id
elif isinstance(from_port, OutcomeView):
from_outcome_id = from_port.outcome_id
# Transition from child outcome to child income
if isinstance(to_port, IncomeView):
responsible_parent_m = from_state_m.parent
to_outcome_id = None
# Transition from child outcome to parent outcome
elif isinstance(to_port, OutcomeView):
responsible_parent_m = to_state_m
to_outcome_id = to_port.outcome_id
else:
raise ValueError("Invalid port type")
from rafcon.gui.models.container_state import ContainerStateModel
if not responsible_parent_m:
logger.error("Transitions only exist between incomes and outcomes. Given: {0} and {1}".format(type(
from_port), type(to_port)))
return False
elif not isinstance(responsible_parent_m, ContainerStateModel):
logger.error("Transitions only exist in container states (e.g. hierarchy states)")
return False
try:
t_id = responsible_parent_m.state.add_transition(from_state_id, from_outcome_id, to_state_id, to_outcome_id)
if from_state_id == to_state_id:
gui_helper_meta_data.insert_self_transition_meta_data(responsible_parent_m.states[from_state_id], t_id,
combined_action=True)
return True
except (ValueError, AttributeError, TypeError) as e:
logger.error("Transition couldn't be added: {0}".format(e))
return False | Interface method between Gaphas and RAFCON core for adding transitions
The method checks the types of the given ports (IncomeView or OutcomeView) and from this determines the necessary
parameters for the add_transition method of the RAFCON core. Also the parent state is derived from the ports.
:param from_port: Port from which the transition starts
:param to_port: Port to which the transition goes to
:return: True if a transition was added, False if an error occurred | entailment |
def get_relative_positions_of_waypoints(transition_v):
"""This method takes the waypoints of a connection and returns all relative positions of these waypoints.
:param canvas: Canvas to check relative position in
:param transition_v: Transition view to extract all relative waypoint positions
:return: List with all relative positions of the given transition
"""
handles_list = transition_v.handles()
rel_pos_list = []
for handle in handles_list:
if handle in transition_v.end_handles(include_waypoints=True):
continue
rel_pos = transition_v.canvas.get_matrix_i2i(transition_v, transition_v.parent).transform_point(*handle.pos)
rel_pos_list.append(rel_pos)
return rel_pos_list | This method takes the waypoints of a connection and returns all relative positions of these waypoints.
:param canvas: Canvas to check relative position in
:param transition_v: Transition view to extract all relative waypoint positions
:return: List with all relative positions of the given transition | entailment |
def update_meta_data_for_transition_waypoints(graphical_editor_view, transition_v, last_waypoint_list, publish=True):
"""This method updates the relative position meta data of the transitions waypoints if they changed
:param graphical_editor_view: Graphical Editor the change occurred in
:param transition_v: Transition that changed
:param last_waypoint_list: List of waypoints before change
:param bool publish: Whether to publish the changes using the meta signal
"""
from rafcon.gui.mygaphas.items.connection import TransitionView
assert isinstance(transition_v, TransitionView)
transition_m = transition_v.model
waypoint_list = get_relative_positions_of_waypoints(transition_v)
if waypoint_list != last_waypoint_list:
transition_m.set_meta_data_editor('waypoints', waypoint_list)
if publish:
graphical_editor_view.emit('meta_data_changed', transition_m, "waypoints", False) | This method updates the relative position meta data of the transitions waypoints if they changed
:param graphical_editor_view: Graphical Editor the change occurred in
:param transition_v: Transition that changed
:param last_waypoint_list: List of waypoints before change
:param bool publish: Whether to publish the changes using the meta signal | entailment |
def update_meta_data_for_port(graphical_editor_view, item, handle):
"""This method updates the meta data of the states ports if they changed.
:param graphical_editor_view: Graphical Editor the change occurred in
:param item: State the port was moved in
:param handle: Handle of moved port or None if all ports are to be updated
"""
from rafcon.gui.mygaphas.items.ports import IncomeView, OutcomeView, InputPortView, OutputPortView, \
ScopedVariablePortView
for port in item.get_all_ports():
if not handle or handle is port.handle:
rel_pos = (port.handle.pos.x.value, port.handle.pos.y.value)
if isinstance(port, (IncomeView, OutcomeView, InputPortView, OutputPortView, ScopedVariablePortView)):
port_m = port.model
cur_rel_pos = port_m.get_meta_data_editor()['rel_pos']
if rel_pos != cur_rel_pos:
port_m.set_meta_data_editor('rel_pos', rel_pos)
if handle:
graphical_editor_view.emit('meta_data_changed', port_m, "position", True)
else:
continue
if handle: # If we were supposed to update the meta data of a specific port, we can stop here
break | This method updates the meta data of the states ports if they changed.
:param graphical_editor_view: Graphical Editor the change occurred in
:param item: State the port was moved in
:param handle: Handle of moved port or None if all ports are to be updated | entailment |
def update_meta_data_for_name_view(graphical_editor_view, name_v, publish=True):
"""This method updates the meta data of a name view.
:param graphical_editor_view: Graphical Editor view the change occurred in
:param name_v: The name view which has been changed/moved
:param publish: Whether to publish the changes of the meta data
"""
from gaphas.item import NW
rel_pos = calc_rel_pos_to_parent(graphical_editor_view.editor.canvas, name_v, name_v.handles()[NW])
state_v = graphical_editor_view.editor.canvas.get_parent(name_v)
state_v.model.set_meta_data_editor('name.size', (name_v.width, name_v.height))
state_v.model.set_meta_data_editor('name.rel_pos', rel_pos)
if publish:
graphical_editor_view.emit('meta_data_changed', state_v.model, "name_size", False) | This method updates the meta data of a name view.
:param graphical_editor_view: Graphical Editor view the change occurred in
:param name_v: The name view which has been changed/moved
:param publish: Whether to publish the changes of the meta data | entailment |
def update_meta_data_for_state_view(graphical_editor_view, state_v, affects_children=False, publish=True):
"""This method updates the meta data of a state view
:param graphical_editor_view: Graphical Editor view the change occurred in
:param state_v: The state view which has been changed/moved
:param affects_children: Whether the children of the state view have been resized or not
:param publish: Whether to publish the changes of the meta data
"""
from gaphas.item import NW
# Update all port meta data to match with new position and size of parent
update_meta_data_for_port(graphical_editor_view, state_v, None)
if affects_children:
update_meta_data_for_name_view(graphical_editor_view, state_v.name_view, publish=False)
for transition_v in state_v.get_transitions():
update_meta_data_for_transition_waypoints(graphical_editor_view, transition_v, None, publish=False)
for child_state_v in state_v.child_state_views():
update_meta_data_for_state_view(graphical_editor_view, child_state_v, True, publish=False)
rel_pos = calc_rel_pos_to_parent(graphical_editor_view.editor.canvas, state_v, state_v.handles()[NW])
state_v.model.set_meta_data_editor('size', (state_v.width, state_v.height))
state_v.model.set_meta_data_editor('rel_pos', rel_pos)
if publish:
graphical_editor_view.emit('meta_data_changed', state_v.model, "size", affects_children) | This method updates the meta data of a state view
:param graphical_editor_view: Graphical Editor view the change occurred in
:param state_v: The state view which has been changed/moved
:param affects_children: Whether the children of the state view have been resized or not
:param publish: Whether to publish the changes of the meta data | entailment |
def remove(self):
"""Remove recursively all children and then the StateView itself
"""
self.canvas.get_first_view().unselect_item(self)
for child in self.canvas.get_children(self)[:]:
child.remove()
self.remove_income()
for outcome_v in self.outcomes[:]:
self.remove_outcome(outcome_v)
for input_port_v in self.inputs[:]:
self.remove_input_port(input_port_v)
for output_port_v in self.outputs[:]:
self.remove_output_port(output_port_v)
for scoped_variable_port_v in self.scoped_variables[:]:
self.remove_scoped_variable(scoped_variable_port_v)
self.remove_keep_rect_within_constraint_from_parent()
for constraint in self._constraints[:]:
self.canvas.solver.remove_constraint(constraint)
self._constraints.remove(constraint)
self.canvas.remove(self) | Remove recursively all children and then the StateView itself | entailment |
def set_enable_flag_keep_rect_within_constraints(self, enable):
""" Enable/disables the KeepRectangleWithinConstraint for child states """
for child_state_v in self.child_state_views():
self.keep_rect_constraints[child_state_v].enable = enable
child_state_v.keep_rect_constraints[child_state_v._name_view].enable = enable | Enable/disables the KeepRectangleWithinConstraint for child states | entailment |
def show_content(self, with_content=False):
"""Checks if the state is a library with the `show_content` flag set
:param with_content: If this parameter is `True`, the method return only True if the library represents a
ContainerState
:return: Whether the content of a library state is shown
"""
if isinstance(self.model, LibraryStateModel) and self.model.show_content():
return not with_content or isinstance(self.model.state_copy, ContainerStateModel)
return False | Checks if the state is a library with the `show_content` flag set
:param with_content: If this parameter is `True`, the method return only True if the library represents a
ContainerState
:return: Whether the content of a library state is shown | entailment |
def _calculate_port_pos_on_line(self, port_num, side_length, port_width=None):
"""Calculate the position of a port on a line
The position depends on the number of element. Elements are equally spaced. If the end of the line is
reached, ports are stacked.
:param int port_num: The number of the port of that type
:param float side_length: The length of the side the element is placed on
:param float port_width: The width of one port
:return: The position on the line for the given port
:rtype: float
"""
if port_width is None:
port_width = 2 * self.border_width
border_size = self.border_width
pos = 0.5 * border_size + port_num * port_width
outermost_pos = max(side_length / 2., side_length - 0.5 * border_size - port_width)
pos = min(pos, outermost_pos)
return pos | Calculate the position of a port on a line
The position depends on the number of element. Elements are equally spaced. If the end of the line is
reached, ports are stacked.
:param int port_num: The number of the port of that type
:param float side_length: The length of the side the element is placed on
:param float port_width: The width of one port
:return: The position on the line for the given port
:rtype: float | entailment |
def write_dict_to_yaml(dictionary, path, **kwargs):
"""
Writes a dictionary to a yaml file
:param dictionary: the dictionary to be written
:param path: the absolute path of the target yaml file
:param kwargs: optional additional parameters for dumper
"""
with open(path, 'w') as f:
yaml.dump(dictionary, f, indent=4, **kwargs) | Writes a dictionary to a yaml file
:param dictionary: the dictionary to be written
:param path: the absolute path of the target yaml file
:param kwargs: optional additional parameters for dumper | entailment |
def load_dict_from_yaml(path):
"""
Loads a dictionary from a yaml file
:param path: the absolute path of the target yaml file
:return:
"""
f = file(path, 'r')
dictionary = yaml.load(f)
f.close()
return dictionary | Loads a dictionary from a yaml file
:param path: the absolute path of the target yaml file
:return: | entailment |
def write_dict_to_json(dictionary, path, **kwargs):
"""
Write a dictionary to a json file.
:param path: The relative path to save the dictionary to
:param dictionary: The dictionary to get saved
:param kwargs: optional additional parameters for dumper
"""
result_string = json.dumps(dictionary, cls=JSONObjectEncoder,
indent=4, check_circular=False, sort_keys=True, **kwargs)
with open(path, 'w') as f:
# We cannot write directly to the file, as otherwise the 'encode' method wouldn't be called
f.write(result_string) | Write a dictionary to a json file.
:param path: The relative path to save the dictionary to
:param dictionary: The dictionary to get saved
:param kwargs: optional additional parameters for dumper | entailment |
def load_objects_from_json(path, as_dict=False):
"""Loads a dictionary from a json file.
:param path: The relative path of the json file.
:return: The dictionary specified in the json file
"""
f = open(path, 'r')
if as_dict:
result = json.load(f)
else:
result = json.load(f, cls=JSONObjectDecoder, substitute_modules=substitute_modules)
f.close()
return result | Loads a dictionary from a json file.
:param path: The relative path of the json file.
:return: The dictionary specified in the json file | entailment |
def solve_for(self, var=None):
"""Ensure that the children is within its parent
"""
if not self.enable:
return
margin = self.margin_method()
def parent_width():
return self.parent_se[0].value - self.parent_nw[0].value
def parent_height():
return self.parent_se[1].value - self.parent_nw[1].value
def child_width():
child_width = self.child_se[0].value - self.child_nw[0].value
if child_width > parent_width() - 2 * margin:
child_width = parent_width() - 2 * margin
return max(self.child.min_width, child_width)
def child_height():
child_height = self.child_se[1].value - self.child_nw[1].value
if child_height > parent_height() - 2 * margin:
child_height = parent_height() - 2 * margin
return max(self.child.min_height, child_height)
updated = False
# Left edge (west)
if self.parent_nw[0].value > self.child_nw[0].value - margin + EPSILON:
width = child_width()
_update(self.child_nw[0], self.parent_nw[0].value + margin)
_update(self.child_se[0], self.child_nw[0].value + width)
updated = True
# Right edge (east)
elif self.parent_se[0].value < self.child_se[0].value + margin - EPSILON:
width = child_width()
_update(self.child_se[0], self.parent_se[0].value - margin)
_update(self.child_nw[0], self.child_se[0].value - width)
updated = True
# Upper edge (north)
if self.parent_nw[1].value > self.child_nw[1].value - margin + EPSILON:
height = child_height()
_update(self.child_nw[1], self.parent_nw[1].value + margin)
_update(self.child_se[1], self.child_nw[1].value + height)
updated = True
# Lower edge (south)
elif self.parent_se[1].value < self.child_se[1].value + margin - EPSILON:
height = child_height()
_update(self.child_se[1], self.parent_se[1].value - margin)
_update(self.child_nw[1], self.child_se[1].value - height)
updated = True
from rafcon.gui.mygaphas.items.state import StateView
if updated and isinstance(self.child, StateView):
self.child.update_minimum_size_of_children() | Ensure that the children is within its parent | entailment |
def solve_for(self, var=None):
"""
Ensure that the children is within its parent
"""
margin = self.margin_method()
if self.parent_nw[0].value > self.child[0].value - margin:
_update(self.child[0], self.parent_nw[0].value + margin)
# Right edge (east)
if self.parent_se[0].value < self.child[0].value + margin:
_update(self.child[0], self.parent_se[0].value - margin)
# Upper edge (north)
if self.parent_nw[1].value > self.child[1].value - margin:
_update(self.child[1], self.parent_nw[1].value + margin)
# Lower edge (south)
if self.parent_se[1].value < self.child[1].value + margin:
_update(self.child[1], self.parent_se[1].value - margin) | Ensure that the children is within its parent | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.