sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
def update_is_start(self):
"""Updates the `is_start` property of the state
A state is a start state, if it is the root state, it has no parent, the parent is a LibraryState or the state's
state_id is identical with the ContainerState.start_state_id of the ContainerState it is within.
"""
self.is_start = self.state.is_root_state or \
self.parent is None or \
isinstance(self.parent.state, LibraryState) or \
self.state.state_id == self.state.parent.start_state_id | Updates the `is_start` property of the state
A state is a start state, if it is the root state, it has no parent, the parent is a LibraryState or the state's
state_id is identical with the ContainerState.start_state_id of the ContainerState it is within. | entailment |
def prepare_destruction(self, recursive=True):
"""Prepares the model for destruction
Recursively un-registers all observers and removes references to child models
"""
if self.state is None:
logger.verbose("Multiple calls of prepare destruction for {0}".format(self))
self.destruction_signal.emit()
try:
self.unregister_observer(self)
except KeyError: # Might happen if the observer was already unregistered
logger.verbose("Observer already unregistered!")
pass
if recursive:
if self.income:
self.income.prepare_destruction()
for port in self.input_data_ports[:] + self.output_data_ports[:] + self.outcomes[:]:
port.prepare_destruction()
del self.input_data_ports[:]
del self.output_data_ports[:]
del self.outcomes[:]
self.state = None
self.input_data_ports = None
self.output_data_ports = None
self.income = None
self.outcomes = None
# History TODO: these are needed by the modification history
# self.action_signal = None
# self.meta_signal = None
# self.destruction_signal = None
self.observe = None
super(AbstractStateModel, self).prepare_destruction() | Prepares the model for destruction
Recursively un-registers all observers and removes references to child models | entailment |
def get_state_machine_m(self, two_factor_check=True):
""" Get respective state machine model
Get a reference of the state machine model the state model belongs to. As long as the root state model
has no direct reference to its state machine model the state machine manager model is checked respective model.
:rtype: rafcon.gui.models.state_machine.StateMachineModel
:return: respective state machine model
"""
from rafcon.gui.singleton import state_machine_manager_model
state_machine = self.state.get_state_machine()
if state_machine:
if state_machine.state_machine_id in state_machine_manager_model.state_machines:
sm_m = state_machine_manager_model.state_machines[state_machine.state_machine_id]
if not two_factor_check or sm_m.get_state_model_by_path(self.state.get_path()) is self:
return sm_m
else:
logger.debug("State model requesting its state machine model parent seems to be obsolete. "
"This is a hint to duplicated models and dirty coding")
return None | Get respective state machine model
Get a reference of the state machine model the state model belongs to. As long as the root state model
has no direct reference to its state machine model the state machine manager model is checked respective model.
:rtype: rafcon.gui.models.state_machine.StateMachineModel
:return: respective state machine model | entailment |
def get_input_data_port_m(self, data_port_id):
"""Returns the input data port model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the data port with the given id
"""
for data_port_m in self.input_data_ports:
if data_port_m.data_port.data_port_id == data_port_id:
return data_port_m
return None | Returns the input data port model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the data port with the given id | entailment |
def get_output_data_port_m(self, data_port_id):
"""Returns the output data port model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the data port with the given id
"""
for data_port_m in self.output_data_ports:
if data_port_m.data_port.data_port_id == data_port_id:
return data_port_m
return None | Returns the output data port model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the data port with the given id | entailment |
def get_data_port_m(self, data_port_id):
"""Searches and returns the model of a data port of a given state
The method searches a port with the given id in the data ports of the given state model. If the state model
is a container state, not only the input and output data ports are looked at, but also the scoped variables.
:param data_port_id: The data port id to be searched
:return: The model of the data port or None if it is not found
"""
from itertools import chain
data_ports_m = chain(self.input_data_ports, self.output_data_ports)
for data_port_m in data_ports_m:
if data_port_m.data_port.data_port_id == data_port_id:
return data_port_m
return None | Searches and returns the model of a data port of a given state
The method searches a port with the given id in the data ports of the given state model. If the state model
is a container state, not only the input and output data ports are looked at, but also the scoped variables.
:param data_port_id: The data port id to be searched
:return: The model of the data port or None if it is not found | entailment |
def get_outcome_m(self, outcome_id):
"""Returns the outcome model for the given outcome id
:param outcome_id: The outcome id to search for
:return: The model of the outcome with the given id
"""
for outcome_m in self.outcomes:
if outcome_m.outcome.outcome_id == outcome_id:
return outcome_m
return False | Returns the outcome model for the given outcome id
:param outcome_id: The outcome id to search for
:return: The model of the outcome with the given id | entailment |
def action_signal_triggered(self, model, prop_name, info):
"""This method notifies the parent state and child state models about complex actions
"""
msg = info.arg
# print("action_signal_triggered state: ", self.state.state_id, model, prop_name, info)
if msg.action.startswith('sm_notification_'):
return
# # affected child propagation from state
# if hasattr(self, 'states'):
# for m in info['arg'].affected_models:
# print(m, self.states)
# print([m is mm for mm in self.states.values()], [m in self for m in info['arg'].affected_models], \)
# [m in self.states.values() for m in info['arg'].affected_models]
if any([m in self for m in info['arg'].affected_models]):
if not msg.action.startswith('parent_notification_'):
new_msg = msg._replace(action='parent_notification_' + msg.action)
else:
new_msg = msg
for m in info['arg'].affected_models:
# print('???propagate it to', m, m.parent)
if isinstance(m, AbstractStateModel) and m in self:
# print('!!!propagate it from {0} to {1} {2}'.format(self.state.state_id, m.state.state_id, m))
m.action_signal.emit(new_msg)
if msg.action.startswith('parent_notification_'):
return
# recursive propagation of action signal TODO remove finally
if self.parent is not None:
# Notify parent about change of meta data
info.arg = msg
# print("DONE1", self.state.state_id, msg)
self.parent.action_signal_triggered(model, prop_name, info)
# print("FINISH DONE1", self.state.state_id, msg)
# state machine propagation of action signal (indirect) TODO remove finally
elif not msg.action.startswith('sm_notification_'): # Prevent recursive call
# If we are the root state, inform the state machine model by emitting our own meta signal.
# To make the signal distinguishable for a change of meta data to our state, the change property of
# the message is prepended with 'sm_notification_'
# print("DONE2", self.state.state_id, msg)
new_msg = msg._replace(action='sm_notification_' + msg.action)
self.action_signal.emit(new_msg)
# print("FINISH DONE2", self.state.state_id, msg)
else:
# print("DONE3 NOTHING")
pass | This method notifies the parent state and child state models about complex actions | entailment |
def meta_changed(self, model, prop_name, info):
"""This method notifies the parent state about changes made to the meta data
"""
msg = info.arg
# print("meta_changed state: ", model, prop_name, info)
if msg.notification is None:
# Meta data of this state was changed, add information about notification to the signal message
notification = Notification(model, prop_name, info)
msg = msg._replace(notification=notification)
# print("DONE0 ", msg)
if self.parent is not None:
# Notify parent about change of meta data
info.arg = msg
self.parent.meta_changed(model, prop_name, info)
# print("DONE1 ", msg)
elif not msg.change.startswith('sm_notification_'): # Prevent recursive call
# If we are the root state, inform the state machine model by emitting our own meta signal.
# To make the signal distinguishable for a change of meta data to our state, the change property of
# the message is prepended with 'sm_notification_'
msg = msg._replace(change='sm_notification_' + msg.change)
self.meta_signal.emit(msg)
# print("DONE2 ", msg)
else:
# print("DONE3 NOTHING")
pass | This method notifies the parent state about changes made to the meta data | entailment |
def load_meta_data(self, path=None):
"""Load meta data of state model from the file system
The meta data of the state model is loaded from the file system and stored in the meta property of the model.
Existing meta data is removed. Also the meta data of all state elements (data ports, outcomes,
etc) are loaded, as those stored in the same file as the meta data of the state.
This is either called on the __init__ of a new state model or if a state model for a container state is created,
which then calls load_meta_data for all its children.
:param str path: Optional file system path to the meta data file. If not given, the path will be derived from
the state's path on the filesystem
:return: if meta data file was loaded True otherwise False
:rtype: bool
"""
# TODO: for an Execution state this method is called for each hierarchy level again and again, still?? check it!
# print("1AbstractState_load_meta_data: ", path, not path)
if not path:
path = self.state.file_system_path
# print("2AbstractState_load_meta_data: ", path)
if path is None:
self.meta = Vividict({})
return False
path_meta_data = os.path.join(path, storage.FILE_NAME_META_DATA)
# TODO: Should be removed with next minor release
if not os.path.exists(path_meta_data):
logger.debug("Because meta data was not found in {0} use backup option {1}"
"".format(path_meta_data, os.path.join(path, storage.FILE_NAME_META_DATA_OLD)))
path_meta_data = os.path.join(path, storage.FILE_NAME_META_DATA_OLD)
# TODO use the following logger message to debug meta data load process and to avoid maybe repetitive loads
# if not os.path.exists(path_meta_data):
# logger.info("path not found {0}".format(path_meta_data))
try:
# print("try to load meta data from {0} for state {1}".format(path_meta_data, self.state))
tmp_meta = storage.load_data_file(path_meta_data)
except ValueError as e:
# if no element which is newly generated log a warning
# if os.path.exists(os.path.dirname(path)):
# logger.debug("Because '{1}' meta data of {0} was not loaded properly.".format(self, e))
if not path.startswith(constants.RAFCON_TEMP_PATH_STORAGE) and not os.path.exists(os.path.dirname(path)):
logger.debug("Because '{1}' meta data of {0} was not loaded properly.".format(self, e))
tmp_meta = {}
# JSON returns a dict, which must be converted to a Vividict
tmp_meta = Vividict(tmp_meta)
if tmp_meta:
self._parse_for_element_meta_data(tmp_meta)
# assign the meta data to the state
self.meta = tmp_meta
self.meta_signal.emit(MetaSignalMsg("load_meta_data", "all", True))
return True
else:
# print("nothing to parse", tmp_meta)
return False | Load meta data of state model from the file system
The meta data of the state model is loaded from the file system and stored in the meta property of the model.
Existing meta data is removed. Also the meta data of all state elements (data ports, outcomes,
etc) are loaded, as those stored in the same file as the meta data of the state.
This is either called on the __init__ of a new state model or if a state model for a container state is created,
which then calls load_meta_data for all its children.
:param str path: Optional file system path to the meta data file. If not given, the path will be derived from
the state's path on the filesystem
:return: if meta data file was loaded True otherwise False
:rtype: bool | entailment |
def store_meta_data(self, copy_path=None):
"""Save meta data of state model to the file system
This method generates a dictionary of the meta data of the state together with the meta data of all state
elements (data ports, outcomes, etc.) and stores it on the filesystem.
Secure that the store meta data method is called after storing the core data otherwise the last_stored_path is
maybe wrong or None.
The copy path is considered to be a state machine file system path but not the current one but e.g.
of a as copy saved state machine. The meta data will be stored in respective relative state folder in the state
machine hierarchy. This folder has to exist.
Dues the core elements of the state machine has to be stored first.
:param str copy_path: Optional copy path if meta data is not stored to the file system path of state machine
"""
if copy_path:
meta_file_path_json = os.path.join(copy_path, self.state.get_storage_path(), storage.FILE_NAME_META_DATA)
else:
if self.state.file_system_path is None:
logger.error("Meta data of {0} can be stored temporary arbitrary but by default first after the "
"respective state was stored and a file system path is set.".format(self))
return
meta_file_path_json = os.path.join(self.state.file_system_path, storage.FILE_NAME_META_DATA)
meta_data = deepcopy(self.meta)
self._generate_element_meta_data(meta_data)
storage_utils.write_dict_to_json(meta_data, meta_file_path_json) | Save meta data of state model to the file system
This method generates a dictionary of the meta data of the state together with the meta data of all state
elements (data ports, outcomes, etc.) and stores it on the filesystem.
Secure that the store meta data method is called after storing the core data otherwise the last_stored_path is
maybe wrong or None.
The copy path is considered to be a state machine file system path but not the current one but e.g.
of a as copy saved state machine. The meta data will be stored in respective relative state folder in the state
machine hierarchy. This folder has to exist.
Dues the core elements of the state machine has to be stored first.
:param str copy_path: Optional copy path if meta data is not stored to the file system path of state machine | entailment |
def copy_meta_data_from_state_m(self, source_state_m):
"""Dismiss current meta data and copy meta data from given state model
The meta data of the given state model is used as meta data for this state. Also the meta data of all state
elements (data ports, outcomes, etc.) is overwritten with the meta data of the elements of the given state.
:param source_state_m: State model to load the meta data from
"""
self.meta = deepcopy(source_state_m.meta)
for input_data_port_m in self.input_data_ports:
source_data_port_m = source_state_m.get_input_data_port_m(input_data_port_m.data_port.data_port_id)
input_data_port_m.meta = deepcopy(source_data_port_m.meta)
for output_data_port_m in self.output_data_ports:
source_data_port_m = source_state_m.get_output_data_port_m(output_data_port_m.data_port.data_port_id)
output_data_port_m.meta = deepcopy(source_data_port_m.meta)
for outcome_m in self.outcomes:
source_outcome_m = source_state_m.get_outcome_m(outcome_m.outcome.outcome_id)
outcome_m.meta = deepcopy(source_outcome_m.meta)
self.income.meta = deepcopy(source_state_m.income.meta)
self.meta_signal.emit(MetaSignalMsg("copy_state_m", "all", True)) | Dismiss current meta data and copy meta data from given state model
The meta data of the given state model is used as meta data for this state. Also the meta data of all state
elements (data ports, outcomes, etc.) is overwritten with the meta data of the elements of the given state.
:param source_state_m: State model to load the meta data from | entailment |
def _parse_for_element_meta_data(self, meta_data):
"""Load meta data for state elements
The meta data of the state meta data file also contains the meta data for state elements (data ports,
outcomes, etc). This method parses the loaded meta data for each state element model. The meta data of the
elements is removed from the passed dictionary.
:param meta_data: Dictionary of loaded meta data
"""
# print("_parse meta data", meta_data)
for data_port_m in self.input_data_ports:
self._copy_element_meta_data_from_meta_file_data(meta_data, data_port_m, "input_data_port",
data_port_m.data_port.data_port_id)
for data_port_m in self.output_data_ports:
self._copy_element_meta_data_from_meta_file_data(meta_data, data_port_m, "output_data_port",
data_port_m.data_port.data_port_id)
for outcome_m in self.outcomes:
self._copy_element_meta_data_from_meta_file_data(meta_data, outcome_m, "outcome",
outcome_m.outcome.outcome_id)
if "income" in meta_data:
if "gui" in meta_data and "editor_gaphas" in meta_data["gui"] and \
"income" in meta_data["gui"]["editor_gaphas"]: # chain necessary to prevent key generation
del meta_data["gui"]["editor_gaphas"]["income"]
elif "gui" in meta_data and "editor_gaphas" in meta_data["gui"] and \
"income" in meta_data["gui"]["editor_gaphas"]: # chain necessary to prevent key generation in meta data
meta_data["income"]["gui"]["editor_gaphas"] = meta_data["gui"]["editor_gaphas"]["income"]
del meta_data["gui"]["editor_gaphas"]["income"]
self._copy_element_meta_data_from_meta_file_data(meta_data, self.income, "income", "") | Load meta data for state elements
The meta data of the state meta data file also contains the meta data for state elements (data ports,
outcomes, etc). This method parses the loaded meta data for each state element model. The meta data of the
elements is removed from the passed dictionary.
:param meta_data: Dictionary of loaded meta data | entailment |
def _copy_element_meta_data_from_meta_file_data(meta_data, element_m, element_name, element_id):
"""Helper method to assign the meta of the given element
The method assigns the meta data of the elements from the given meta data dictionary. The copied meta data is
then removed from the dictionary.
:param meta_data: The loaded meta data
:param element_m: The element model that is supposed to retrieve the meta data
:param element_name: The name string of the element type in the dictionary
:param element_id: The id of the element
"""
meta_data_element_id = element_name + str(element_id)
meta_data_element = meta_data[meta_data_element_id]
# print(meta_data_element_id, element_m, meta_data_element)
element_m.meta = meta_data_element
del meta_data[meta_data_element_id] | Helper method to assign the meta of the given element
The method assigns the meta data of the elements from the given meta data dictionary. The copied meta data is
then removed from the dictionary.
:param meta_data: The loaded meta data
:param element_m: The element model that is supposed to retrieve the meta data
:param element_name: The name string of the element type in the dictionary
:param element_id: The id of the element | entailment |
def _generate_element_meta_data(self, meta_data):
"""Generate meta data for state elements and add it to the given dictionary
This method retrieves the meta data of the state elements (data ports, outcomes, etc) and adds it to the
given meta data dictionary.
:param meta_data: Dictionary of meta data
"""
for data_port_m in self.input_data_ports:
self._copy_element_meta_data_to_meta_file_data(meta_data, data_port_m, "input_data_port",
data_port_m.data_port.data_port_id)
for data_port_m in self.output_data_ports:
self._copy_element_meta_data_to_meta_file_data(meta_data, data_port_m, "output_data_port",
data_port_m.data_port.data_port_id)
for outcome_m in self.outcomes:
self._copy_element_meta_data_to_meta_file_data(meta_data, outcome_m, "outcome",
outcome_m.outcome.outcome_id)
self._copy_element_meta_data_to_meta_file_data(meta_data, self.income, "income", "") | Generate meta data for state elements and add it to the given dictionary
This method retrieves the meta data of the state elements (data ports, outcomes, etc) and adds it to the
given meta data dictionary.
:param meta_data: Dictionary of meta data | entailment |
def save_file_data(self, path):
""" Implements the abstract method of the ExternalEditor class.
"""
sm = self.model.state.get_state_machine()
if sm.marked_dirty and not self.saved_initial:
try:
# Save the file before opening it to update the applied changes. Use option create_full_path=True
# to assure that temporary state_machines' script files are saved to
# (their path doesnt exist when not saved)
filesystem.write_file(os.path.join(path, storage.SCRIPT_FILE),
self.view.get_text(), create_full_path=True)
except IOError as e:
# Only happens if the file doesnt exist yet and would be written to the temp folder.
# The method write_file doesnt create the path
logger.error('The operating system raised an error: {}'.format(e))
self.saved_initial = True | Implements the abstract method of the ExternalEditor class. | entailment |
def load_and_set_file_content(self, file_system_path):
""" Implements the abstract method of the ExternalEditor class.
"""
content = filesystem.read_file(file_system_path, storage.SCRIPT_FILE)
if content is not None:
self.set_script_text(content) | Implements the abstract method of the ExternalEditor class. | entailment |
def apply_clicked(self, button):
"""Triggered when the Apply button in the source editor is clicked.
"""
if isinstance(self.model.state, LibraryState):
logger.warning("It is not allowed to modify libraries.")
self.view.set_text("")
return
# Ugly workaround to give user at least some feedback about the parser
# Without the loop, this function would block the GTK main loop and the log message would appear after the
# function has finished
# TODO: run parser in separate thread
while Gtk.events_pending():
Gtk.main_iteration_do(False)
# get script
current_text = self.view.get_text()
# Directly apply script if linter was deactivated
if not self.view['pylint_check_button'].get_active():
self.set_script_text(current_text)
return
logger.debug("Parsing execute script...")
with open(self.tmp_file, "w") as text_file:
text_file.write(current_text)
# clear astroid module cache, see http://stackoverflow.com/questions/22241435/pylint-discard-cached-file-state
MANAGER.astroid_cache.clear()
lint_config_file = resource_filename(rafcon.__name__, "pylintrc")
args = ["--rcfile={}".format(lint_config_file)] # put your own here
with contextlib.closing(StringIO()) as dummy_buffer:
json_report = JSONReporter(dummy_buffer.getvalue())
try:
lint.Run([self.tmp_file] + args, reporter=json_report, exit=False)
except:
logger.exception("Could not run linter to check script")
os.remove(self.tmp_file)
if json_report.messages:
def on_message_dialog_response_signal(widget, response_id):
if response_id == 1:
self.set_script_text(current_text)
else:
logger.debug("The script was not saved")
widget.destroy()
message_string = "Are you sure that you want to save this file?\n\nThe following errors were found:"
line = None
for message in json_report.messages:
(error_string, line) = self.format_error_string(message)
message_string += "\n\n" + error_string
# focus line of error
if line:
tbuffer = self.view.get_buffer()
start_iter = tbuffer.get_start_iter()
start_iter.set_line(int(line)-1)
tbuffer.place_cursor(start_iter)
message_string += "\n\nThe line was focused in the source editor."
self.view.scroll_to_cursor_onscreen()
# select state to show source editor
sm_m = state_machine_manager_model.get_state_machine_model(self.model)
if sm_m.selection.get_selected_state() is not self.model:
sm_m.selection.set(self.model)
dialog = RAFCONButtonDialog(message_string, ["Save with errors", "Do not save"],
on_message_dialog_response_signal,
message_type=Gtk.MessageType.WARNING, parent=self.get_root_window())
result = dialog.run()
else:
self.set_script_text(current_text) | Triggered when the Apply button in the source editor is clicked. | entailment |
def split_text(text_to_split):
"""Split text
Splits the debug text into its different parts: 'Time', 'LogLevel + Module Name', 'Debug message'
:param text_to_split: Text to split
:return: List containing the content of text_to_split split up
"""
assert isinstance(text_to_split, string_types)
try:
time, rest = text_to_split.split(': ', 1)
source, message = rest.split(':', 1)
except ValueError:
time = source = ""
message = text_to_split
return time.strip(), source.strip(), message.strip() | Split text
Splits the debug text into its different parts: 'Time', 'LogLevel + Module Name', 'Debug message'
:param text_to_split: Text to split
:return: List containing the content of text_to_split split up | entailment |
def update_auto_scroll_mode(self):
""" Register or un-register signals for follow mode """
if self._enables['CONSOLE_FOLLOW_LOGGING']:
if self._auto_scroll_handler_id is None:
self._auto_scroll_handler_id = self.text_view.connect("size-allocate", self._auto_scroll)
else:
if self._auto_scroll_handler_id is not None:
self.text_view.disconnect(self._auto_scroll_handler_id)
self._auto_scroll_handler_id = None | Register or un-register signals for follow mode | entailment |
def _auto_scroll(self, *args):
""" Scroll to the end of the text view """
adj = self['scrollable'].get_vadjustment()
adj.set_value(adj.get_upper() - adj.get_page_size()) | Scroll to the end of the text view | entailment |
def get_line_number_next_to_cursor_with_string_within(self, s):
""" Find the closest occurrence of a string with respect to the cursor position in the text view """
line_number, _ = self.get_cursor_position()
text_buffer = self.text_view.get_buffer()
line_iter = text_buffer.get_iter_at_line(line_number)
# find closest before line with string within
before_line_number = None
while line_iter.backward_line():
if s in self.get_text_of_line(line_iter):
before_line_number = line_iter.get_line()
break
# find closest after line with string within
after_line_number = None
while line_iter.forward_line():
if s in self.get_text_of_line(line_iter):
after_line_number = line_iter.get_line()
break
# take closest one to current position
if after_line_number is not None and before_line_number is None:
return after_line_number, after_line_number - line_number
elif before_line_number is not None and after_line_number is None:
return before_line_number, line_number - before_line_number
elif after_line_number is not None and before_line_number is not None:
after_distance = after_line_number - line_number
before_distance = line_number - before_line_number
if after_distance < before_distance:
return after_line_number, after_distance
else:
return before_line_number, before_distance
else:
return None, None | Find the closest occurrence of a string with respect to the cursor position in the text view | entailment |
def set_variable(self, key, value, per_reference=False, access_key=None, data_type=None):
"""Sets a global variable
:param key: the key of the global variable to be set
:param value: the new value of the global variable
:param per_reference: a flag to decide if the variable should be stored per reference or per value
:param access_key: if the variable was explicitly locked with the rafcon.state lock_variable
:raises exceptions.RuntimeError: if a wrong access key is passed
"""
key = str(key) # Ensure that we have the same string type for all keys (under Python2 and 3!)
if self.variable_exist(key):
if data_type is None:
data_type = self.__global_variable_type_dictionary[key]
else:
if data_type is None:
data_type = type(None)
assert isinstance(data_type, type)
self.check_value_and_type(value, data_type)
with self.__global_lock:
unlock = True
if self.variable_exist(key):
if self.is_locked(key) and self.__access_keys[key] != access_key:
raise RuntimeError("Wrong access key for accessing global variable")
elif self.is_locked(key):
unlock = False
else:
access_key = self.lock_variable(key, block=True)
else:
self.__variable_locks[key] = Lock()
access_key = self.lock_variable(key, block=True)
# --- variable locked
if per_reference:
self.__global_variable_dictionary[key] = value
self.__global_variable_type_dictionary[key] = data_type
self.__variable_references[key] = True
else:
self.__global_variable_dictionary[key] = copy.deepcopy(value)
self.__global_variable_type_dictionary[key] = data_type
self.__variable_references[key] = False
# --- release variable
if unlock:
self.unlock_variable(key, access_key)
logger.debug("Global variable '{}' was set to value '{}' with type '{}'".format(key, value, data_type.__name__)) | Sets a global variable
:param key: the key of the global variable to be set
:param value: the new value of the global variable
:param per_reference: a flag to decide if the variable should be stored per reference or per value
:param access_key: if the variable was explicitly locked with the rafcon.state lock_variable
:raises exceptions.RuntimeError: if a wrong access key is passed | entailment |
def get_variable(self, key, per_reference=None, access_key=None, default=None):
"""Fetches the value of a global variable
:param key: the key of the global variable to be fetched
:param bool per_reference: a flag to decide if the variable should be stored per reference or per value
:param access_key: if the variable was explicitly locked with the rafcon.state lock_variable
:param default: a value to be returned if the key does not exist
:return: The value stored at in the global variable key
:raises exceptions.RuntimeError: if a wrong access key is passed or the variable cannot be accessed by reference
"""
key = str(key)
if self.variable_exist(key):
unlock = True
if self.is_locked(key):
if self.__access_keys[key] == access_key:
unlock = False
else:
if not access_key:
access_key = self.lock_variable(key, block=True)
else:
raise RuntimeError("Wrong access key for accessing global variable")
else:
access_key = self.lock_variable(key, block=True)
# --- variable locked
if self.variable_can_be_referenced(key):
if per_reference or per_reference is None:
return_value = self.__global_variable_dictionary[key]
else:
return_value = copy.deepcopy(self.__global_variable_dictionary[key])
else:
if per_reference:
self.unlock_variable(key, access_key)
raise RuntimeError("Variable cannot be accessed by reference")
else:
return_value = copy.deepcopy(self.__global_variable_dictionary[key])
# --- release variable
if unlock:
self.unlock_variable(key, access_key)
return return_value
else:
# logger.warning("Global variable '{0}' not existing, returning default value".format(key))
return default | Fetches the value of a global variable
:param key: the key of the global variable to be fetched
:param bool per_reference: a flag to decide if the variable should be stored per reference or per value
:param access_key: if the variable was explicitly locked with the rafcon.state lock_variable
:param default: a value to be returned if the key does not exist
:return: The value stored at in the global variable key
:raises exceptions.RuntimeError: if a wrong access key is passed or the variable cannot be accessed by reference | entailment |
def variable_can_be_referenced(self, key):
"""Checks whether the value of the variable can be returned by reference
:param str key: Name of the variable
:return: True if value of variable can be returned by reference, False else
"""
key = str(key)
return key in self.__variable_references and self.__variable_references[key] | Checks whether the value of the variable can be returned by reference
:param str key: Name of the variable
:return: True if value of variable can be returned by reference, False else | entailment |
def delete_variable(self, key):
"""Deletes a global variable
:param key: the key of the global variable to be deleted
:raises exceptions.AttributeError: if the global variable does not exist
"""
key = str(key)
if self.is_locked(key):
raise RuntimeError("Global variable is locked")
with self.__global_lock:
if key in self.__global_variable_dictionary:
access_key = self.lock_variable(key, block=True)
del self.__global_variable_dictionary[key]
self.unlock_variable(key, access_key)
del self.__variable_locks[key]
del self.__variable_references[key]
else:
raise AttributeError("Global variable %s does not exist!" % str(key))
logger.debug("Global variable %s was deleted!" % str(key)) | Deletes a global variable
:param key: the key of the global variable to be deleted
:raises exceptions.AttributeError: if the global variable does not exist | entailment |
def lock_variable(self, key, block=False):
"""Locks a global variable
:param key: the key of the global variable to be locked
:param block: a flag to specify if to wait for locking the variable in blocking mode
"""
key = str(key)
# watch out for releasing the __dictionary_lock properly
try:
if key in self.__variable_locks:
# acquire without arguments is blocking
lock_successful = self.__variable_locks[key].acquire(False)
if lock_successful or block:
if (not lock_successful) and block: # case: lock could not be acquired => wait for it as block=True
duration = 0.
loop_time = 0.1
while not self.__variable_locks[key].acquire(False):
time.sleep(loop_time)
duration += loop_time
if int(duration*10) % 20 == 0:
# while loops informs the user about long locked variables
logger.verbose("Variable '{2}' is locked and thread {0} waits already {1} seconds to "
"access it.".format(currentThread(), duration, key))
access_key = global_variable_id_generator()
self.__access_keys[key] = access_key
return access_key
else:
logger.warning("Global variable {} already locked".format(str(key)))
return False
else:
logger.error("Global variable key {} does not exist".format(str(key)))
return False
except Exception as e:
logger.error("Exception thrown: {}".format(str(e)))
return False | Locks a global variable
:param key: the key of the global variable to be locked
:param block: a flag to specify if to wait for locking the variable in blocking mode | entailment |
def unlock_variable(self, key, access_key, force=False):
"""Unlocks a global variable
:param key: the key of the global variable to be unlocked
:param access_key: the access key to be able to unlock the global variable
:param force: if the variable should be unlocked forcefully
:raises exceptions.AttributeError: if the global variable does not exist
:raises exceptions.RuntimeError: if the wrong access key is passed
"""
key = str(key)
if self.__access_keys[key] == access_key or force:
if key in self.__variable_locks:
if self.is_locked(key):
self.__variable_locks[key].release()
return True
else:
logger.error("Global variable {} is not locked, thus cannot unlock it".format(str(key)))
return False
else:
raise AttributeError("Global variable %s does not exist!" % str(key))
else:
raise RuntimeError("Wrong access key for accessing global variable") | Unlocks a global variable
:param key: the key of the global variable to be unlocked
:param access_key: the access key to be able to unlock the global variable
:param force: if the variable should be unlocked forcefully
:raises exceptions.AttributeError: if the global variable does not exist
:raises exceptions.RuntimeError: if the wrong access key is passed | entailment |
def set_locked_variable(self, key, access_key, value):
"""Set an already locked global variable
:param key: the key of the global variable to be set
:param access_key: the access key to the already locked global variable
:param value: the new value of the global variable
"""
return self.set_variable(key, value, per_reference=False, access_key=access_key) | Set an already locked global variable
:param key: the key of the global variable to be set
:param access_key: the access key to the already locked global variable
:param value: the new value of the global variable | entailment |
def get_locked_variable(self, key, access_key):
"""Returns the value of an global variable that is already locked
:param key: the key of the global variable
:param access_key: the access_key to the global variable that is already locked
"""
return self.get_variable(key, per_reference=False, access_key=access_key) | Returns the value of an global variable that is already locked
:param key: the key of the global variable
:param access_key: the access_key to the global variable that is already locked | entailment |
def is_locked(self, key):
"""Returns the status of the lock of a global variable
:param key: the unique key of the global variable
:return:
"""
key = str(key)
if key in self.__variable_locks:
return self.__variable_locks[key].locked()
return False | Returns the status of the lock of a global variable
:param key: the unique key of the global variable
:return: | entailment |
def get_all_keys_starting_with(self, start_key):
""" Returns all keys, which start with a certain pattern defined in :param start_key.
:param start_key: The start pattern to search all keys for.
:return:
"""
start_key = str(start_key)
output_list = []
if len(self.__global_variable_dictionary) == 0:
return output_list
for g_key in self.__global_variable_dictionary.keys():
# string comparison
if g_key and start_key in g_key:
output_list.append(g_key)
return output_list | Returns all keys, which start with a certain pattern defined in :param start_key.
:param start_key: The start pattern to search all keys for.
:return: | entailment |
def global_variable_dictionary(self):
"""Property for the _global_variable_dictionary field"""
dict_copy = {}
for key, value in self.__global_variable_dictionary.items():
if key in self.__variable_references and self.__variable_references[key]:
dict_copy[key] = value
else:
dict_copy[key] = copy.deepcopy(value)
return dict_copy | Property for the _global_variable_dictionary field | entailment |
def check_value_and_type(value, data_type):
"""Checks if a given value is of a specific type
:param value: the value to check
:param data_type: the type to be checked upon
:return:
"""
if value is not None and data_type is not type(None):
# if not isinstance(value, data_type):
if not type_inherits_of_type(data_type, type(value)):
raise TypeError(
"Value: '{0}' is not of data type: '{1}', value type: {2}".format(value, data_type, type(value))) | Checks if a given value is of a specific type
:param value: the value to check
:param data_type: the type to be checked upon
:return: | entailment |
def glue(self, pos):
"""Calculates the distance between the given position and the port
:param (float, float) pos: Distance to this position is calculated
:return: Distance to port
:rtype: float
"""
# Distance between border of rectangle and point
# Equation from http://stackoverflow.com/a/18157551/3568069
dx = max(self.point.x - self.width / 2. - pos[0], 0, pos[0] - (self.point.x + self.width / 2.))
dy = max(self.point.y - self.height / 2. - pos[1], 0, pos[1] - (self.point.y + self.height / 2.))
dist = sqrt(dx*dx + dy*dy)
return self.point, dist | Calculates the distance between the given position and the port
:param (float, float) pos: Distance to this position is calculated
:return: Distance to port
:rtype: float | entailment |
def format_time(time):
""" Formats the given time into HH:MM:SS """
h, r = divmod(time / 1000, 3600)
m, s = divmod(r, 60)
return "%02d:%02d:%02d" % (h, m, s) | Formats the given time into HH:MM:SS | entailment |
def __destroy(self):
"""Remove controller from parent controller and/or destroy it self."""
if self.parent:
self.parent.remove_controller(self)
else:
self.destroy() | Remove controller from parent controller and/or destroy it self. | entailment |
def register_view(self, view):
"""Called when the View was registered"""
super(PreferencesWindowController, self).register_view(view)
self.view['add_library_button'].connect('clicked', self._on_add_library)
self.view["remove_library_button"].connect('clicked', self._on_remove_library)
self.view['config_tree_view'].connect("button_press_event", self._on_row_clicked_trigger_toggle_of_boolean,
self.core_config_model, self.core_list_store)
self.view['gui_tree_view'].connect("button_press_event", self._on_row_clicked_trigger_toggle_of_boolean,
self.gui_config_model, self.gui_list_store)
self.view['core_config_value_renderer'].set_property('editable', True)
self.view['core_config_value_renderer'].connect('edited', self._on_config_value_changed, self.core_config_model,
self.core_list_store)
self.view['gui_config_value_renderer'].set_property('editable', True)
self.view['gui_config_value_renderer'].connect('edited', self._on_config_value_changed, self.gui_config_model,
self.gui_list_store)
self.view['shortcut_config_value_renderer'].set_property('editable', True)
self.view['shortcut_config_value_renderer'].connect('edited', self._on_shortcut_changed)
self.view['library_config_key_renderer'].set_property('editable', True)
self.view['library_config_key_renderer'].connect('edited', self._on_library_name_changed)
self.view['library_config_value_renderer'].set_property('editable', True)
self.view['library_config_value_renderer'].connect('edited', self._on_library_path_changed)
self.view['config_tree_view'].set_model(self.core_list_store)
self.view['library_tree_view'].set_model(self.library_list_store)
self.view['gui_tree_view'].set_model(self.gui_list_store)
self.view['shortcut_tree_view'].set_model(self.shortcut_list_store)
self.view['apply_button'].connect("clicked", self._on_apply_button_clicked)
self.view['ok_button'].connect('clicked', self._on_ok_button_clicked)
self.view['cancel_button'].connect('clicked', self._on_cancel_button_clicked)
self.view['import_button'].connect("clicked", self._on_import_config)
self.view['export_button'].connect('clicked', self._on_export_config)
self.view['preferences_window'].connect('delete_event', self._on_delete_event)
self.update_all() | Called when the View was registered | entailment |
def on_config_value_changed(self, config_m, prop_name, info):
"""Callback when a config value has been changed
Only collects information, delegates handling further to _handle_config_update
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'config'
:param dict info: Information e.g. about the changed config key
"""
config_key = info['args'][1] if "key" not in info['kwargs'] else info['kwargs']['key']
# config_value = info['args'][-1] if "value" not in info['kwargs'] else info['kwargs']['value']
self._handle_config_update(config_m, config_key) | Callback when a config value has been changed
Only collects information, delegates handling further to _handle_config_update
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'config'
:param dict info: Information e.g. about the changed config key | entailment |
def on_preliminary_config_changed(self, config_m, prop_name, info):
"""Callback when a preliminary config value has been changed
Mainly collects information, delegates handling further to _handle_config_update
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'preliminary_config'
:param dict info: Information e.g. about the changed config key
"""
self.check_for_preliminary_config()
method_name = info['method_name'] # __setitem__, __delitem__, clear, ...
if method_name in ['__setitem__', '__delitem__']:
config_key = info['args'][0]
self._handle_config_update(config_m, config_key)
# Probably the preliminary config has been cleared, update corresponding list stores
elif config_m is self.core_config_model:
self.update_core_config_list_store()
self.update_libraries_list_store()
else:
self.update_gui_config_list_store()
self.update_shortcut_settings() | Callback when a preliminary config value has been changed
Mainly collects information, delegates handling further to _handle_config_update
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'preliminary_config'
:param dict info: Information e.g. about the changed config key | entailment |
def _handle_config_update(self, config_m, config_key):
"""Handles changes in config values
The method ensure that the correct list stores are updated with the new values.
:param ConfigModel config_m: The config model that has been changed
:param config_key: The config key who's value has been changed
:return:
"""
if config_key == "LIBRARY_PATHS":
self.update_libraries_list_store()
if config_key == "SHORTCUTS":
self.update_shortcut_settings()
else:
self.update_config_value(config_m, config_key) | Handles changes in config values
The method ensure that the correct list stores are updated with the new values.
:param ConfigModel config_m: The config model that has been changed
:param config_key: The config key who's value has been changed
:return: | entailment |
def update_all(self):
"""Shorthand method to update all collection information
"""
self.update_path_labels()
self.update_core_config_list_store()
self.update_gui_config_list_store()
self.update_libraries_list_store()
self.update_shortcut_settings()
self.check_for_preliminary_config() | Shorthand method to update all collection information | entailment |
def check_for_preliminary_config(self):
"""Activates the 'Apply' button if there are preliminary changes
"""
if any([self.model.preliminary_config, self.gui_config_model.preliminary_config]):
self.view['apply_button'].set_sensitive(True)
else:
self.view['apply_button'].set_sensitive(False) | Activates the 'Apply' button if there are preliminary changes | entailment |
def update_path_labels(self):
"""Update labels showing config paths
"""
self.view['core_label'].set_text("Core Config Path: " + str(self.core_config_model.config.config_file_path))
self.view['gui_label'].set_text("GUI Config Path: " + str(self.gui_config_model.config.config_file_path)) | Update labels showing config paths | entailment |
def update_config_value(self, config_m, config_key):
"""Updates the corresponding list store of a changed config value
:param ConfigModel config_m: The config model that has been changed
:param str config_key: The config key who's value has been changed
"""
config_value = config_m.get_current_config_value(config_key)
if config_m is self.core_config_model:
list_store = self.core_list_store
elif config_m is self.gui_config_model:
list_store = self.gui_list_store
else:
return
self._update_list_store_entry(list_store, config_key, config_value) | Updates the corresponding list store of a changed config value
:param ConfigModel config_m: The config model that has been changed
:param str config_key: The config key who's value has been changed | entailment |
def _update_list_store_entry(self, list_store, config_key, config_value):
"""Helper method to update a list store
:param Gtk.ListStore list_store: List store to be updated
:param str config_key: Config key to search for
:param config_value: New config value
:returns: Row of list store that has been updated
:rtype: int
"""
for row_num, row in enumerate(list_store):
if row[self.KEY_STORAGE_ID] == config_key:
row[self.VALUE_STORAGE_ID] = str(config_value)
row[self.TOGGLE_VALUE_STORAGE_ID] = config_value
return row_num | Helper method to update a list store
:param Gtk.ListStore list_store: List store to be updated
:param str config_key: Config key to search for
:param config_value: New config value
:returns: Row of list store that has been updated
:rtype: int | entailment |
def _update_list_store(config_m, list_store, ignore_keys=None):
"""Generic method to create list store for a given config model
:param ConfigModel config_m: Config model to read into list store
:param Gtk.ListStore list_store: List store to be filled
:param list ignore_keys: List of keys that should be ignored
"""
ignore_keys = [] if ignore_keys is None else ignore_keys
list_store.clear()
for config_key in sorted(config_m.config.keys):
if config_key in ignore_keys:
continue
config_value = config_m.get_current_config_value(config_key)
# (config_key, text, text_visible, toggle_activatable, toggle_visible, text_editable, toggle_state)
if isinstance(config_value, bool):
list_store.append((str(config_key), str(config_value), False, True, True, False, config_value))
else:
list_store.append((str(config_key), str(config_value), True, False, False, True, config_value)) | Generic method to create list store for a given config model
:param ConfigModel config_m: Config model to read into list store
:param Gtk.ListStore list_store: List store to be filled
:param list ignore_keys: List of keys that should be ignored | entailment |
def update_libraries_list_store(self):
"""Creates the list store for the libraries
"""
self.library_list_store.clear()
libraries = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True, default={})
library_names = sorted(libraries.keys())
for library_name in library_names:
library_path = libraries[library_name]
self.library_list_store.append((library_name, library_path)) | Creates the list store for the libraries | entailment |
def update_shortcut_settings(self):
"""Creates the list store for the shortcuts
"""
self.shortcut_list_store.clear()
shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True, default={})
actions = sorted(shortcuts.keys())
for action in actions:
keys = shortcuts[action]
self.shortcut_list_store.append((str(action), str(keys))) | Creates the list store for the shortcuts | entailment |
def _select_row_by_column_value(tree_view, list_store, column, value):
"""Helper method to select a tree view row
:param Gtk.TreeView tree_view: Tree view who's row is to be selected
:param Gtk.ListStore list_store: List store of the tree view
:param int column: Column in which the value is searched
:param value: Value to search for
:returns: Row of list store that has selected
:rtype: int
"""
for row_num, iter_elem in enumerate(list_store):
if iter_elem[column] == value:
tree_view.set_cursor(row_num)
return row_num | Helper method to select a tree view row
:param Gtk.TreeView tree_view: Tree view who's row is to be selected
:param Gtk.ListStore list_store: List store of the tree view
:param int column: Column in which the value is searched
:param value: Value to search for
:returns: Row of list store that has selected
:rtype: int | entailment |
def _on_add_library(self, *event):
"""Callback method handling the addition of a new library
"""
self.view['library_tree_view'].grab_focus()
if react_to_event(self.view, self.view['library_tree_view'], event):
temp_library_name = "<LIB_NAME_%s>" % self._lib_counter
self._lib_counter += 1
library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
default={})
library_config[temp_library_name] = "<LIB_PATH>"
self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
self._select_row_by_column_value(self.view['library_tree_view'], self.library_list_store,
self.KEY_STORAGE_ID, temp_library_name)
return True | Callback method handling the addition of a new library | entailment |
def _on_remove_library(self, *event):
"""Callback method handling the removal of an existing library
"""
self.view['library_tree_view'].grab_focus()
if react_to_event(self.view, self.view['library_tree_view'], event):
path = self.view["library_tree_view"].get_cursor()[0]
if path is not None:
library_name = self.library_list_store[int(path[0])][0]
library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
default={})
del library_config[library_name]
self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
if len(self.library_list_store) > 0:
self.view['library_tree_view'].set_cursor(min(path[0], len(self.library_list_store) - 1))
return True | Callback method handling the removal of an existing library | entailment |
def _on_checkbox_toggled(self, renderer, path, config_m, config_list_store):
"""Callback method handling a config toggle event
:param Gtk.CellRenderer renderer: Cell renderer that has been toggled
:param path: Path within the list store
:param ConfigModel config_m: The config model related to the toggle option
:param Gtk.ListStore config_list_store: The list store related to the toggle option
"""
config_key = config_list_store[int(path)][self.KEY_STORAGE_ID]
config_value = bool(config_list_store[int(path)][self.TOGGLE_VALUE_STORAGE_ID])
config_value ^= True
config_m.set_preliminary_config_value(config_key, config_value) | Callback method handling a config toggle event
:param Gtk.CellRenderer renderer: Cell renderer that has been toggled
:param path: Path within the list store
:param ConfigModel config_m: The config model related to the toggle option
:param Gtk.ListStore config_list_store: The list store related to the toggle option | entailment |
def _on_import_config(self, *args):
"""Callback method the the import button was clicked
Shows a dialog allowing to import an existing configuration file
"""
def handle_import(dialog_text, path_name):
chooser = Gtk.FileChooserDialog(dialog_text, None,
Gtk.FileChooserAction.SAVE,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT))
chooser.set_current_folder(path_name)
response = chooser.run()
if response == Gtk.ResponseType.ACCEPT:
# get_filename() returns the whole file path inclusively the filename
config_file = chooser.get_filename()
config_path = dirname(config_file)
self._last_path = config_path
config_dict = yaml_configuration.config.load_dict_from_yaml(config_file)
config_type = config_dict.get("TYPE")
if config_type == "SM_CONFIG":
del config_dict["TYPE"]
self.core_config_model.update_config(config_dict, config_file)
logger.info("Imported Core Config from {0}".format(config_file))
elif config_type == "GUI_CONFIG":
del config_dict["TYPE"]
self.gui_config_model.update_config(config_dict, config_file)
logger.info("Imported GUI Config from {0}".format(config_file))
else:
logger.error("{0} is not a valid config file".format(config_file))
elif response == Gtk.ResponseType.CANCEL:
logger.info("Import of configuration cancelled")
chooser.destroy()
handle_import("Import Config Config from", self._last_path)
self.check_for_preliminary_config()
self.update_path_labels() | Callback method the the import button was clicked
Shows a dialog allowing to import an existing configuration file | entailment |
def _on_export_config(self, *args):
"""Callback method the the export button was clicked
Shows dialogs allowing to export the configurations into separate files
"""
response = self._config_chooser_dialog("Export configuration",
"Please select the configuration file(s) to be exported:")
if response == Gtk.ResponseType.REJECT:
return
def handle_export(dialog_text, path, config_m):
chooser = Gtk.FileChooserDialog(dialog_text, None,
Gtk.FileChooserAction.SAVE,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_SAVE_AS, Gtk.ResponseType.ACCEPT))
chooser.set_current_folder(path)
response = chooser.run()
if response == Gtk.ResponseType.ACCEPT:
config_file = chooser.get_filename()
if not config_file:
logger.error("Configuration could not be exported! Invalid file name!")
else:
if ".yaml" not in config_file:
config_file += ".yaml"
if config_m.preliminary_config:
logger.warning("There are changes in the configuration that have not yet been applied. These "
"changes will not be exported.")
self._last_path = dirname(config_file)
config_dict = config_m.as_dict()
config_copy = yaml_configuration.config.DefaultConfig(str(config_dict))
config_copy.config_file_path = config_file
config_copy.path = self._last_path
try:
config_copy.save_configuration()
logger.info("Configuration exported to {}" .format(config_file))
except IOError:
logger.error("Cannot open file '{}' for writing".format(config_file))
elif response == Gtk.ResponseType.CANCEL:
logger.warning("Export Config canceled!")
chooser.destroy()
if self._core_checkbox.get_active():
handle_export("Select file for core configuration", self._last_path, self.core_config_model)
if self._gui_checkbox.get_active():
handle_export("Select file for GUI configuration.", self._last_path, self.gui_config_model) | Callback method the the export button was clicked
Shows dialogs allowing to export the configurations into separate files | entailment |
def _on_ok_button_clicked(self, *args):
"""OK button clicked: Applies the configurations and closes the window
"""
if self.core_config_model.preliminary_config or self.gui_config_model.preliminary_config:
self._on_apply_button_clicked()
self.__destroy() | OK button clicked: Applies the configurations and closes the window | entailment |
def _on_cancel_button_clicked(self, *args):
"""Cancel button clicked: Dismiss preliminary config and close the window
"""
self.core_config_model.preliminary_config.clear()
self.gui_config_model.preliminary_config.clear()
self.__destroy() | Cancel button clicked: Dismiss preliminary config and close the window | entailment |
def _on_apply_button_clicked(self, *args):
"""Apply button clicked: Apply the configuration
"""
refresh_required = self.core_config_model.apply_preliminary_config()
refresh_required |= self.gui_config_model.apply_preliminary_config()
if not self.gui_config_model.config.get_config_value("SESSION_RESTORE_ENABLED"):
import rafcon.gui.backup.session as backup_session
logger.info("Removing current session")
backup_session.reset_session()
if refresh_required:
from rafcon.gui.singleton import main_window_controller
main_window_controller.get_controller('menu_bar_controller').on_refresh_all_activate(None, None)
self._popup_message() | Apply button clicked: Apply the configuration | entailment |
def _on_library_name_changed(self, renderer, path, new_library_name):
"""Callback handling a change of a library name
:param Gtk.CellRenderer renderer: Cell renderer showing the library name
:param path: Path of library within the list store
:param str new_library_name: New library name
"""
old_library_name = self.library_list_store[int(path)][self.KEY_STORAGE_ID]
if old_library_name == new_library_name:
return
library_path = self.library_list_store[int(path)][self.VALUE_STORAGE_ID]
library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
default={})
del library_config[old_library_name]
library_config[new_library_name] = library_path
self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
self._select_row_by_column_value(self.view['library_tree_view'], self.library_list_store,
self.KEY_STORAGE_ID, new_library_name) | Callback handling a change of a library name
:param Gtk.CellRenderer renderer: Cell renderer showing the library name
:param path: Path of library within the list store
:param str new_library_name: New library name | entailment |
def _on_library_path_changed(self, renderer, path, new_library_path):
"""Callback handling a change of a library path
:param Gtk.CellRenderer renderer: Cell renderer showing the library path
:param path: Path of library within the list store
:param str new_library_path: New library path
"""
library_name = self.library_list_store[int(path)][self.KEY_STORAGE_ID]
library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
default={})
library_config[library_name] = new_library_path
self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
self._select_row_by_column_value(self.view['library_tree_view'], self.library_list_store,
self.KEY_STORAGE_ID, library_name) | Callback handling a change of a library path
:param Gtk.CellRenderer renderer: Cell renderer showing the library path
:param path: Path of library within the list store
:param str new_library_path: New library path | entailment |
def _on_shortcut_changed(self, renderer, path, new_shortcuts):
"""Callback handling a change of a shortcut
:param Gtk.CellRenderer renderer: Cell renderer showing the shortcut
:param path: Path of shortcuts within the list store
:param str new_shortcuts: New shortcuts
"""
action = self.shortcut_list_store[int(path)][self.KEY_STORAGE_ID]
old_shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True)[action]
from ast import literal_eval
try:
new_shortcuts = literal_eval(new_shortcuts)
if not isinstance(new_shortcuts, list) and \
not all([isinstance(shortcut, string_types) for shortcut in new_shortcuts]):
raise ValueError()
except (ValueError, SyntaxError):
logger.warning("Shortcuts must be a list of strings")
new_shortcuts = old_shortcuts
shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True, default={})
shortcuts[action] = new_shortcuts
self.gui_config_model.set_preliminary_config_value("SHORTCUTS", shortcuts)
self._select_row_by_column_value(self.view['shortcut_tree_view'], self.shortcut_list_store,
self.KEY_STORAGE_ID, action) | Callback handling a change of a shortcut
:param Gtk.CellRenderer renderer: Cell renderer showing the shortcut
:param path: Path of shortcuts within the list store
:param str new_shortcuts: New shortcuts | entailment |
def _on_config_value_changed(self, renderer, path, new_value, config_m, list_store):
"""Callback handling a change of a config value
:param Gtk.CellRenderer renderer: Cell renderer showing the shortcut
:param path: Path of shortcuts within the list store
:param ConfigModel config_m: The config model that is to be changed
:param Gtk.ListStore list_store: The list store that is to be changed
"""
config_key = list_store[int(path)][self.KEY_STORAGE_ID]
old_value = config_m.get_current_config_value(config_key, use_preliminary=True)
if old_value == new_value:
return
# Try to maintain the correct data type, which is extracted from the old value
if isinstance(old_value, bool):
if new_value in ["True", "true"]:
new_value = True
elif new_value in ["False", "false"]:
new_value = False
else:
logger.warning("'{}' must be a boolean value".format(config_key))
new_value = old_value
elif isinstance(old_value, (int, float)):
try:
new_value = int(new_value)
except ValueError:
try:
new_value = float(new_value)
except ValueError:
logger.warning("'{}' must be a numeric value".format(config_key))
new_value = old_value
config_m.set_preliminary_config_value(config_key, new_value) | Callback handling a change of a config value
:param Gtk.CellRenderer renderer: Cell renderer showing the shortcut
:param path: Path of shortcuts within the list store
:param ConfigModel config_m: The config model that is to be changed
:param Gtk.ListStore list_store: The list store that is to be changed | entailment |
def _config_chooser_dialog(self, title_text, description):
"""Dialog to select which config shall be exported
:param title_text: Title text
:param description: Description
"""
dialog = Gtk.Dialog(title_text, self.view["preferences_window"],
flags=0, buttons=
(Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT,
Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT))
label = Gtk.Label(label=description)
label.set_padding(xpad=10, ypad=10)
dialog.vbox.pack_start(label, True, True, 0)
label.show()
self._gui_checkbox = Gtk.CheckButton(label="GUI Config")
dialog.vbox.pack_start(self._gui_checkbox, True, True, 0)
self._gui_checkbox.show()
self._core_checkbox = Gtk.CheckButton(label="Core Config")
self._core_checkbox.show()
dialog.vbox.pack_start(self._core_checkbox, True, True, 0)
response = dialog.run()
dialog.destroy()
return response | Dialog to select which config shall be exported
:param title_text: Title text
:param description: Description | entailment |
def check_if_dict_contains_object_reference_in_values(object_to_check, dict_to_check):
""" Method to check if an object is inside the values of a dict.
A simple object_to_check in dict_to_check.values() does not work as it uses the __eq__ function of the object
and not the object reference.
:param object_to_check: The target object.
:param dict_to_check: The dict to search in.
:return:
"""
for key, value in dict_to_check.items():
if object_to_check is value:
return True
return False | Method to check if an object is inside the values of a dict.
A simple object_to_check in dict_to_check.values() does not work as it uses the __eq__ function of the object
and not the object reference.
:param object_to_check: The target object.
:param dict_to_check: The dict to search in.
:return: | entailment |
def update_data_flows(model, data_flow_dict, tree_dict_combos):
""" Updates data flow dictionary and combo dictionary of the widget according handed model.
:param model: model for which the data_flow_dict and tree_dict_combos should be updated
:param data_flow_dict: dictionary that holds all internal and external data-flows and those respective row labels
:param tree_dict_combos: dictionary that holds all internal and external data-flow-adaptation-combos
:return:
"""
data_flow_dict['internal'] = {}
data_flow_dict['external'] = {}
tree_dict_combos['internal'] = {}
tree_dict_combos['external'] = {}
# free input ports and scopes are real to_keys and real states
[free_to_port_internal, from_ports_internal] = find_free_keys(model)
[free_to_port_external, from_ports_external] = find_free_keys(model.parent)
def take_from_dict(from_dict, key):
if key in from_dict:
return from_dict[key]
else:
logger.warning("Key '%s' is not in %s" % (key, from_dict))
pass
# from_state, to_key, to_state, to_key, external
if isinstance(model, ContainerStateModel):
for data_flow in list(model.state.data_flows.values()): # model.data_flow_list_store:
# TREE STORE LABEL
# check if from Self_state
if data_flow.from_state == model.state.state_id:
from_state = model.state
from_state_label = 'self.' + model.state.name + '.' + data_flow.from_state
else:
if take_from_dict(model.state.states, data_flow.from_state):
from_state = take_from_dict(model.state.states, data_flow.from_state)
from_state_label = from_state.name + '.' + data_flow.from_state
else:
# print(data_flow.from_state, data_flow.from_key, data_flow.to_state, data_flow.to_key)
logger.warning("DO break in ctrl/data_flow.py -1")
break
# check if to Self_state
if data_flow.to_state == model.state.state_id:
to_state = model.state
to_state_label = 'self.' + model.state.name + '.' + data_flow.to_state
else:
if take_from_dict(model.state.states, data_flow.to_state):
to_state = take_from_dict(model.state.states, data_flow.to_state)
to_state_label = to_state.name + '.' + data_flow.to_state
else:
# print(data_flow.from_state, data_flow.from_key, data_flow.to_state, data_flow.to_key)
logger.warning("DO break in ctrl/data_flow.py 0")
break
from_key_port = from_state.get_data_port_by_id(data_flow.from_key)
from_key_label = ''
if from_key_port is not None:
from_key_label = PORT_TYPE_TAG.get(type(from_key_port), 'None') + '.' + \
from_key_port.data_type.__name__ + '.' + \
from_key_port.name
to_key_port = to_state.get_data_port_by_id(data_flow.to_key)
# to_key_label = ''
if to_key_port is not None:
to_key_label = PORT_TYPE_TAG.get(type(to_key_port), 'None') + '.' + \
(to_key_port.data_type.__name__ or 'None') + '.' + \
to_key_port.name
data_flow_dict['internal'][data_flow.data_flow_id] = {'from_state': from_state_label,
'from_key': from_key_label,
'to_state': to_state_label,
'to_key': to_key_label}
# ALL INTERNAL COMBOS
from_states_store = Gtk.ListStore(GObject.TYPE_STRING)
to_states_store = Gtk.ListStore(GObject.TYPE_STRING)
if isinstance(model, ContainerStateModel):
if model.state.state_id in free_to_port_internal or model.state.state_id == data_flow.to_state:
to_states_store.append(['self.' + model.state.name + '.' + model.state.state_id])
if model.state.state_id in from_ports_internal or model.state.state_id == data_flow.from_state:
from_states_store.append(['self.' + model.state.name + '.' + model.state.state_id])
for state_model in list(model.states.values()):
if state_model.state.state_id in free_to_port_internal or \
state_model.state.state_id == data_flow.to_state:
to_states_store.append([state_model.state.name + '.' + state_model.state.state_id])
if state_model.state.state_id in from_ports_internal or \
state_model.state.state_id == data_flow.from_state:
from_states_store.append([state_model.state.name + '.' + state_model.state.state_id])
from_keys_store = Gtk.ListStore(GObject.TYPE_STRING)
if model.state.state_id == data_flow.from_state:
# print("input_ports", model.state.input_data_ports)
# print(type(model))
if isinstance(model, ContainerStateModel):
# print("scoped_variables", model.state.scoped_variables)
combined_ports = {}
combined_ports.update(model.state.scoped_variables)
combined_ports.update(model.state.input_data_ports)
get_key_combos(combined_ports, from_keys_store, data_flow.from_key)
else:
get_key_combos(model.state.input_data_ports, from_keys_store, data_flow.from_key)
else:
# print("output_ports", model.states[data_flow.from_state].state.output_data_ports)
get_key_combos(model.state.states[data_flow.from_state].output_data_ports,
from_keys_store, data_flow.from_key)
to_keys_store = Gtk.ListStore(GObject.TYPE_STRING)
if model.state.state_id == data_flow.to_state:
# print("output_ports", model.state.output_data_ports)
# print(type(model))
if isinstance(model, ContainerStateModel):
# print("scoped_variables", model.state.scoped_variables)
combined_ports = {}
combined_ports.update(model.state.scoped_variables)
combined_ports.update(model.state.output_data_ports)
get_key_combos(combined_ports, to_keys_store, data_flow.to_key)
else:
get_key_combos(model.state.output_data_ports, to_keys_store, data_flow.to_key)
else:
# print("input_ports", model.states[data_flow.to_state].state.input_data_ports)
get_key_combos(model.state.states[data_flow.to_state].input_data_ports
, to_keys_store, data_flow.to_key)
tree_dict_combos['internal'][data_flow.data_flow_id] = {'from_state': from_states_store,
'from_key': from_keys_store,
'to_state': to_states_store,
'to_key': to_keys_store}
# print("internal", data_flow_dict['internal'][data_flow.data_flow_id])
if not model.state.is_root_state:
for data_flow in list(model.parent.state.data_flows.values()): # model.parent.data_flow_list_store:
# TREE STORE LABEL
# check if from Self_state
if model.state.state_id == data_flow.from_state:
from_state = model.state
from_state_label = 'self.' + model.state.name + '.' + data_flow.from_state
else:
if model.parent.state.state_id == data_flow.from_state:
from_state = model.parent.state
from_state_label = 'parent.' + model.parent.state.name + '.' + data_flow.from_state
else:
if take_from_dict(model.parent.state.states, data_flow.from_state):
from_state = take_from_dict(model.parent.state.states, data_flow.from_state)
from_state_label = from_state.name + '.' + data_flow.from_state
else:
# print("#", data_flow.from_state, data_flow.from_key, data_flow.to_state, data_flow.to_key)
logger.warning("DO break in ctrl/data_flow.py 1")
break
# check if to Self_state
if model.state.state_id == data_flow.to_state:
to_state = model.state
to_state_label = 'self.' + model.state.name + '.' + data_flow.to_state
else:
if model.parent.state.state_id == data_flow.to_state:
to_state = model.parent.state
to_state_label = 'parent.' + model.parent.state.name + '.' + data_flow.to_state
else:
if take_from_dict(model.parent.state.states, data_flow.to_state):
to_state = take_from_dict(model.parent.state.states, data_flow.to_state)
to_state_label = to_state.name + '.' + data_flow.to_state
else:
# print("##", data_flow.from_state, data_flow.from_key, data_flow.to_state, data_flow.to_key)
logger.warning("DO break in ctrl/data_flow.py 2")
break
if model.state.state_id in [data_flow.from_state, data_flow.to_state]:
from_key_port = from_state.get_data_port_by_id(data_flow.from_key)
if from_key_port is None:
continue
from_key_label = PORT_TYPE_TAG.get(type(from_key_port), 'None') + '.' + \
from_key_port.data_type.__name__ + '.' + \
from_key_port.name
to_key_port = to_state.get_data_port_by_id(data_flow.to_key)
if to_key_port is None:
continue
to_key_label = PORT_TYPE_TAG.get(type(to_key_port), 'None') + '.' + \
to_key_port.data_type.__name__ + '.' + \
to_key_port.name
data_flow_dict['external'][data_flow.data_flow_id] = {'from_state': from_state_label,
'from_key': from_key_label,
'to_state': to_state_label,
'to_key': to_key_label}
# ALL EXTERNAL COMBOS
if model.state.state_id in [data_flow.from_state, data_flow.to_state]:
# only self-state
from_states_store = Gtk.ListStore(GObject.TYPE_STRING)
for state_id in list(from_ports_external.keys()):
if model.parent.state.state_id == state_id:
state_model = model.parent
else:
state_model = model.parent.states[state_id]
if state_model.state.state_id == model.state.state_id:
from_states_store.append(['self.' + state_model.state.name + '.' + state_model.state.state_id])
else:
from_states_store.append([state_model.state.name + '.' + state_model.state.state_id])
# from_states_store.append(['self.' + model.state.name + '.' + model.state.state_id])
# only outports of self
from_keys_store = Gtk.ListStore(GObject.TYPE_STRING)
if model.parent.state.state_id == data_flow.from_state:
# print("output_ports", model.parent.states[data_flow.from_state].state.output_data_ports)
combined_ports = {}
combined_ports.update(model.parent.state.input_data_ports)
combined_ports.update(model.parent.state.scoped_variables)
get_key_combos(combined_ports, from_keys_store, data_flow.to_key)
elif data_flow.from_state in [state_m.state.state_id for state_m in list(model.parent.states.values())]:
get_key_combos(model.parent.state.states[data_flow.from_state].output_data_ports,
from_keys_store, data_flow.to_key)
else:
logger.error(
"---------------- FAILURE %s ------------- external from_state PARENT or STATES" % model.state.state_id)
# all states and parent-state
to_states_store = Gtk.ListStore(GObject.TYPE_STRING)
for state_id in list(free_to_port_external.keys()):
if model.parent.state.state_id == state_id:
state_model = model.parent
else:
state_model = model.parent.states[state_id]
if state_model.state.state_id == model.state.state_id:
to_states_store.append(['self.' + state_model.state.name + '.' + state_model.state.state_id])
else:
to_states_store.append([state_model.state.name + '.' + state_model.state.state_id])
# all keys of actual to-state
to_keys_store = Gtk.ListStore(GObject.TYPE_STRING)
if get_state_model(model.parent, data_flow.to_state):
to_state_model = get_state_model(model.parent, data_flow.to_state)
from_state_model = get_state_model(model.parent, data_flow.to_state)
act_from_key_port = from_state_model.state.get_data_port_by_id(data_flow.from_key)
act_to_key_port = to_state_model.state.get_data_port_by_id(data_flow.to_key)
# first actual port
to_keys_store.append([PORT_TYPE_TAG.get(type(act_to_key_port), 'None') + '.#' +
str(act_to_key_port.data_port_id) + '.' +
act_to_key_port.data_type.__name__ + '.' +
act_to_key_port.name])
# second all other possible ones
if to_state_model.state is model.state.parent:
possible_port_ids = list(to_state_model.state.output_data_ports.keys()) + list(to_state_model.state.scoped_variables.keys())
else:
possible_port_ids = list(to_state_model.state.input_data_ports.keys())
for port_id in possible_port_ids:
port = to_state_model.state.get_data_port_by_id(port_id)
# to_state = get_state_model(model.parent, data_flow.to_state).state
if not (PORT_TYPE_TAG.get(type(act_from_key_port), 'None') == 'SV' and port.data_port_id == data_flow.from_key)\
and port is not act_to_key_port:
to_keys_store.append([PORT_TYPE_TAG.get(type(port), 'None') + '.#' +
str(port.data_port_id) + '.' +
port.data_type.__name__ + '.' +
port.name])
tree_dict_combos['external'][data_flow.data_flow_id] = {'from_state': from_states_store,
'from_key': from_keys_store,
'to_state': to_states_store,
'to_key': to_keys_store}
# print("external", data_flow_dict['external'][data_flow.data_flow_id])
# print("ALL SCANNED: ", data_flow_dict['internal'].keys(), data_flow_dict['external'].keys(), \)
# tree_dict_combos['internal'].keys(), tree_dict_combos['external'].keys()
return free_to_port_internal, free_to_port_external, from_ports_internal, from_ports_external | Updates data flow dictionary and combo dictionary of the widget according handed model.
:param model: model for which the data_flow_dict and tree_dict_combos should be updated
:param data_flow_dict: dictionary that holds all internal and external data-flows and those respective row labels
:param tree_dict_combos: dictionary that holds all internal and external data-flow-adaptation-combos
:return: | entailment |
def register_view(self, view):
"""Called when the View was registered
"""
super(StateDataFlowsListController, self).register_view(view)
def cell_text(column, cell_renderer, model, iter, container_model):
df_id = model.get_value(iter, self.ID_STORAGE_ID)
in_external = 'external' if model.get_value(iter, self.IS_EXTERNAL_STORAGE_ID) else 'internal'
if column.get_title() == 'Source State':
cell_renderer.set_property("model", self.tree_dict_combos[in_external][df_id]['from_state'])
cell_renderer.set_property("text-column", 0)
cell_renderer.set_property("has-entry", False)
elif column.get_title() == 'Source Port':
cell_renderer.set_property("model", self.tree_dict_combos[in_external][df_id]['from_key'])
cell_renderer.set_property("text-column", 0)
cell_renderer.set_property("has-entry", False)
elif column.get_title() == 'Target State':
cell_renderer.set_property("model", self.tree_dict_combos[in_external][df_id]['to_state'])
cell_renderer.set_property("text-column", 0)
cell_renderer.set_property("has-entry", False)
elif column.get_title() == 'Target Port':
cell_renderer.set_property("model", self.tree_dict_combos[in_external][df_id]['to_key'])
cell_renderer.set_property("text-column", 0)
cell_renderer.set_property("has-entry", False)
else:
logger.warning("Column has no cell_data_func %s %s" % (column.get_name(), column.get_title()))
view['from_state_col'].set_cell_data_func(view['from_state_combo'], cell_text, self.model)
view['to_state_col'].set_cell_data_func(view['to_state_combo'], cell_text, self.model)
view['from_key_col'].set_cell_data_func(view['from_key_combo'], cell_text, self.model)
view['to_key_col'].set_cell_data_func(view['to_key_combo'], cell_text, self.model)
if self.model.state.get_next_upper_library_root_state():
view['from_state_combo'].set_property("editable", False)
view['from_key_combo'].set_property("editable", False)
view['to_state_combo'].set_property("editable", False)
view['to_key_combo'].set_property("editable", False)
else:
self.connect_signal(view['from_state_combo'], "edited", self.on_combo_changed_from_state)
self.connect_signal(view['from_key_combo'], "edited", self.on_combo_changed_from_key)
self.connect_signal(view['to_state_combo'], "edited", self.on_combo_changed_to_state)
self.connect_signal(view['to_key_combo'], "edited", self.on_combo_changed_to_key)
self.tree_view.connect("grab-focus", self.on_focus)
self.update(initiator='"register view"') | Called when the View was registered | entailment |
def remove_core_element(self, model):
"""Remove respective core element of handed data flow model
:param DataFlowModel model: Data Flow model which core element should be removed
:return:
"""
assert model.data_flow.parent is self.model.state or model.data_flow.parent is self.model.parent.state
gui_helper_state_machine.delete_core_element_of_model(model) | Remove respective core element of handed data flow model
:param DataFlowModel model: Data Flow model which core element should be removed
:return: | entailment |
def register_view(self, view):
"""Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
"""
super(StateDataFlowsEditorController, self).register_view(view)
view['add_d_button'].connect('clicked', self.df_list_ctrl.on_add)
view['remove_d_button'].connect('clicked', self.df_list_ctrl.on_remove)
view['connected_to_d_checkbutton'].connect('toggled', self.toggled_button, 'data_flows_external')
view['internal_d_checkbutton'].connect('toggled', self.toggled_button, 'data_flows_internal')
if isinstance(self.model.state, LibraryState):
view['internal_d_checkbutton'].set_sensitive(False)
view['internal_d_checkbutton'].set_active(False)
if self.model.parent is not None and isinstance(self.model.parent.state, LibraryState) or \
self.model.state.get_next_upper_library_root_state():
view['add_d_button'].set_sensitive(False)
view['remove_d_button'].set_sensitive(False)
if self.model.state.is_root_state:
self.df_list_ctrl.view_dict['data_flows_external'] = False
view['connected_to_d_checkbutton'].set_active(False)
if not isinstance(self.model, ContainerStateModel):
self.df_list_ctrl.view_dict['data_flows_internal'] = False
view['internal_d_checkbutton'].set_active(False) | Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application | entailment |
def start(self):
"""Starts the execution of the root state.
"""
# load default input data for the state
self._root_state.input_data = self._root_state.get_default_input_values_for_state(self._root_state)
self._root_state.output_data = self._root_state.create_output_dictionary_for_state(self._root_state)
new_execution_history = self._add_new_execution_history()
new_execution_history.push_state_machine_start_history_item(self, run_id_generator())
self._root_state.start(new_execution_history) | Starts the execution of the root state. | entailment |
def join(self):
"""Wait for root state to finish execution"""
self._root_state.join()
# execution finished, close execution history log file (if present)
if len(self._execution_histories) > 0:
if self._execution_histories[-1].execution_history_storage is not None:
set_read_and_writable_for_all = global_config.get_config_value("EXECUTION_LOG_SET_READ_AND_WRITABLE_FOR_ALL", False)
self._execution_histories[-1].execution_history_storage.close(set_read_and_writable_for_all)
from rafcon.core.states.state import StateExecutionStatus
self._root_state.state_execution_status = StateExecutionStatus.INACTIVE | Wait for root state to finish execution | entailment |
def get_port_area(self, view):
"""Calculates the drawing area affected by the (hovered) port
"""
state_v = self.parent
center = self.handle.pos
margin = self.port_side_size / 4.
if self.side in [SnappedSide.LEFT, SnappedSide.RIGHT]:
height, width = self.port_size
else:
width, height = self.port_size
upper_left = center[0] - width / 2 - margin, center[1] - height / 2 - margin
lower_right = center[0] + width / 2 + margin, center[1] + height / 2 + margin
port_upper_left = view.get_matrix_i2v(state_v).transform_point(*upper_left)
port_lower_right = view.get_matrix_i2v(state_v).transform_point(*lower_right)
size = port_lower_right[0] - port_upper_left[0], port_lower_right[1] - port_upper_left[1]
return port_upper_left[0], port_upper_left[1], size[0], size[1] | Calculates the drawing area affected by the (hovered) port | entailment |
def _draw_simple_state_port(self, context, direction, color, transparency):
"""Draw the port of a simple state (ExecutionState, LibraryState)
Connector for execution states can only be connected to the outside. Thus the connector fills the whole
border of the state.
:param context: Cairo context
:param direction: The direction the port is pointing to
:param color: Desired color of the port
:param transparency: The level of transparency
"""
c = context
width, height = self.port_size
c.set_line_width(self.port_side_size * 0.03 * self._port_image_cache.multiplicator)
# Save/restore context, as we move and rotate the connector to the desired pose
c.save()
c.rel_move_to(self.port_side_size / 2., self.port_side_size / 2.)
PortView._rotate_context(c, direction)
PortView._draw_single_connector(c, width, height)
c.restore()
# Colorize the generated connector path
if self.connected:
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
else:
c.set_source_rgb(*gui_config.gtk_colors['PORT_UNCONNECTED'].to_floats())
c.fill_preserve()
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
c.stroke() | Draw the port of a simple state (ExecutionState, LibraryState)
Connector for execution states can only be connected to the outside. Thus the connector fills the whole
border of the state.
:param context: Cairo context
:param direction: The direction the port is pointing to
:param color: Desired color of the port
:param transparency: The level of transparency | entailment |
def _draw_container_state_port(self, context, direction, color, transparency):
"""Draw the port of a container state
Connector for container states are split in an inner connector and an outer connector.
:param context: Cairo context
:param direction: The direction the port is pointing to
:param color: Desired color of the port
:param float transparency: The level of transparency
"""
c = context
width, height = self.port_size
c.set_line_width(self.port_side_size / constants.BORDER_WIDTH_OUTLINE_WIDTH_FACTOR *
self._port_image_cache.multiplicator)
# Save/restore context, as we move and rotate the connector to the desired pose
cur_point = c.get_current_point()
c.save()
c.rel_move_to(self.port_side_size / 2., self.port_side_size / 2.)
PortView._rotate_context(c, direction)
PortView._draw_inner_connector(c, width, height)
c.restore()
if self.connected_incoming:
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
else:
c.set_source_rgb(*gui_config.gtk_colors['PORT_UNCONNECTED'].to_floats())
c.fill_preserve()
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
c.stroke()
c.move_to(*cur_point)
c.save()
c.rel_move_to(self.port_side_size / 2., self.port_side_size / 2.)
PortView._rotate_context(c, direction)
PortView._draw_outer_connector(c, width, height)
c.restore()
if self.connected_outgoing:
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
else:
c.set_source_rgb(*gui_config.gtk_colors['PORT_UNCONNECTED'].to_floats())
c.fill_preserve()
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
c.stroke() | Draw the port of a container state
Connector for container states are split in an inner connector and an outer connector.
:param context: Cairo context
:param direction: The direction the port is pointing to
:param color: Desired color of the port
:param float transparency: The level of transparency | entailment |
def _draw_single_connector(context, width, height):
"""Draw the connector for execution states
Connector for execution states can only be connected to the outside. Thus the connector fills the whole
border of the state.
:param context: Cairo context
:param float port_size: The side length of the port
"""
c = context
# Current pos is center
# Arrow is drawn upright
arrow_height = height / 2.0
# First move to bottom left corner
c.rel_move_to(-width / 2., height / 2.)
# Draw line to bottom right corner
c.rel_line_to(width, 0)
# Draw line to upper right corner
c.rel_line_to(0, -(height - arrow_height))
# Draw line to center top (arrow)
c.rel_line_to(-width / 2., -arrow_height)
# Draw line to upper left corner
c.rel_line_to(-width / 2., arrow_height)
# Draw line back to the origin (lower left corner)
c.close_path() | Draw the connector for execution states
Connector for execution states can only be connected to the outside. Thus the connector fills the whole
border of the state.
:param context: Cairo context
:param float port_size: The side length of the port | entailment |
def _draw_inner_connector(context, width, height):
"""Draw the connector for container states
Connector for container states can be connected from the inside and the outside. Thus the connector is split
in two parts: A rectangle on the inside and an arrow on the outside. This methods draws the inner rectangle.
:param context: Cairo context
:param float port_size: The side length of the port
"""
c = context
# Current pos is center
# Arrow is drawn upright
gap = height / 6.
connector_height = (height - gap) / 2.
# First move to bottom left corner
c.rel_move_to(-width / 2., height / 2.)
# Draw inner connector (rectangle)
c.rel_line_to(width, 0)
c.rel_line_to(0, -connector_height)
c.rel_line_to(-width, 0)
c.close_path() | Draw the connector for container states
Connector for container states can be connected from the inside and the outside. Thus the connector is split
in two parts: A rectangle on the inside and an arrow on the outside. This methods draws the inner rectangle.
:param context: Cairo context
:param float port_size: The side length of the port | entailment |
def _draw_outer_connector(context, width, height):
"""Draw the outer connector for container states
Connector for container states can be connected from the inside and the outside. Thus the connector is split
in two parts: A rectangle on the inside and an arrow on the outside. This method draws the outer arrow.
:param context: Cairo context
:param float port_size: The side length of the port
"""
c = context
# Current pos is center
# Arrow is drawn upright
arrow_height = height / 2.5
gap = height / 6.
connector_height = (height - gap) / 2.
# Move to bottom left corner of outer connector
c.rel_move_to(-width / 2., -gap / 2.)
# Draw line to bottom right corner
c.rel_line_to(width, 0)
# Draw line to upper right corner
c.rel_line_to(0, -(connector_height - arrow_height))
# Draw line to center top (arrow)
c.rel_line_to(-width / 2., -arrow_height)
# Draw line to upper left corner
c.rel_line_to(-width / 2., arrow_height)
# Draw line back to the origin (lower left corner)
c.close_path() | Draw the outer connector for container states
Connector for container states can be connected from the inside and the outside. Thus the connector is split
in two parts: A rectangle on the inside and an arrow on the outside. This method draws the outer arrow.
:param context: Cairo context
:param float port_size: The side length of the port | entailment |
def _draw_rectangle(context, width, height):
"""Draw a rectangle
Assertion: The current point is the center point of the rectangle
:param context: Cairo context
:param width: Width of the rectangle
:param height: Height of the rectangle
"""
c = context
# First move to upper left corner
c.rel_move_to(-width / 2., -height / 2.)
# Draw closed rectangle
c.rel_line_to(width, 0)
c.rel_line_to(0, height)
c.rel_line_to(-width, 0)
c.close_path() | Draw a rectangle
Assertion: The current point is the center point of the rectangle
:param context: Cairo context
:param width: Width of the rectangle
:param height: Height of the rectangle | entailment |
def _rotate_context(context, direction):
"""Moves the current position to 'position' and rotates the context according to 'direction'
:param context: Cairo context
:param direction: Direction enum
"""
if direction is Direction.UP:
pass
elif direction is Direction.RIGHT:
context.rotate(deg2rad(90))
elif direction is Direction.DOWN:
context.rotate(deg2rad(180))
elif direction is Direction.LEFT:
context.rotate(deg2rad(-90)) | Moves the current position to 'position' and rotates the context according to 'direction'
:param context: Cairo context
:param direction: Direction enum | entailment |
def draw_name(self, context, transparency, only_calculate_size=False):
"""Draws the name of the port
Offers the option to only calculate the size of the name.
:param context: The context to draw on
:param transparency: The transparency of the text
:param only_calculate_size: Whether to only calculate the size
:return: Size of the name
:rtype: float, float
"""
c = context
cairo_context = c
if isinstance(c, CairoBoundingBoxContext):
cairo_context = c._cairo
# c.set_antialias(Antialias.GOOD)
side_length = self.port_side_size
layout = PangoCairo.create_layout(cairo_context)
font_name = constants.INTERFACE_FONT
font_size = gap_draw_helper.FONT_SIZE
font = FontDescription(font_name + " " + str(font_size))
layout.set_font_description(font)
layout.set_text(self.name, -1)
ink_extents, logical_extents = layout.get_extents()
extents = [extent / float(SCALE) for extent in [logical_extents.x, logical_extents.y,
logical_extents.width, logical_extents.height]]
real_name_size = extents[2], extents[3]
desired_height = side_length * 0.75
scale_factor = real_name_size[1] / desired_height
# Determine the size of the text, increase the width to have more margin left and right of the text
margin = side_length / 4.
name_size = real_name_size[0] / scale_factor, desired_height
name_size_with_margin = name_size[0] + margin * 2, name_size[1] + margin * 2
# Only the size is required, stop here
if only_calculate_size:
return name_size_with_margin
# Current position is the center of the port rectangle
c.save()
if self.side is SnappedSide.RIGHT or self.side is SnappedSide.LEFT:
c.rotate(deg2rad(-90))
c.rel_move_to(-name_size[0] / 2, -name_size[1] / 2)
c.scale(1. / scale_factor, 1. / scale_factor)
c.rel_move_to(-extents[0], -extents[1])
c.set_source_rgba(*gap_draw_helper.get_col_rgba(self.text_color, transparency))
PangoCairo.update_layout(cairo_context, layout)
PangoCairo.show_layout(cairo_context, layout)
c.restore()
return name_size_with_margin | Draws the name of the port
Offers the option to only calculate the size of the name.
:param context: The context to draw on
:param transparency: The transparency of the text
:param only_calculate_size: Whether to only calculate the size
:return: Size of the name
:rtype: float, float | entailment |
def _draw_rectangle_path(self, context, width, height, only_get_extents=False):
"""Draws the rectangle path for the port
The rectangle is correctly rotated. Height therefore refers to the border thickness and width to the length
of the port.
:param context: The context to draw on
:param float width: The width of the rectangle
:param float height: The height of the rectangle
"""
c = context
# Current position is the center of the rectangle
c.save()
if self.side is SnappedSide.LEFT or self.side is SnappedSide.RIGHT:
c.rotate(deg2rad(90))
c.rel_move_to(-width / 2., - height / 2.)
c.rel_line_to(width, 0)
c.rel_line_to(0, height)
c.rel_line_to(-width, 0)
c.close_path()
c.restore()
if only_get_extents:
extents = c.path_extents()
c.new_path()
return extents | Draws the rectangle path for the port
The rectangle is correctly rotated. Height therefore refers to the border thickness and width to the length
of the port.
:param context: The context to draw on
:param float width: The width of the rectangle
:param float height: The height of the rectangle | entailment |
def _get_port_center_position(self, width):
"""Calculates the center position of the port rectangle
The port itself can be positioned in the corner, the center of the port rectangle however is restricted by
the width of the rectangle. This method therefore calculates the center, depending on the position of the
port and the width of the rectangle.
:param float width: The width of the rectangle
:return: The center position of the rectangle
:rtype: float, float
"""
x, y = self.pos.x.value, self.pos.y.value
if self.side is SnappedSide.TOP or self.side is SnappedSide.BOTTOM:
if x - width / 2. < 0:
x = width / 2
elif x + width / 2. > self.parent.width:
x = self.parent.width - width / 2.
else:
if y - width / 2. < 0:
y = width / 2
elif y + width / 2. > self.parent.height:
y = self.parent.height - width / 2.
return x, y | Calculates the center position of the port rectangle
The port itself can be positioned in the corner, the center of the port rectangle however is restricted by
the width of the rectangle. This method therefore calculates the center, depending on the position of the
port and the width of the rectangle.
:param float width: The width of the rectangle
:return: The center position of the rectangle
:rtype: float, float | entailment |
def register_actions(self, shortcut_manager):
"""Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions.
"""
shortcut_manager.add_callback_for_action('rename', self.rename_selected_state)
super(StatesEditorController, self).register_actions(shortcut_manager) | Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions. | entailment |
def on_config_value_changed(self, config_m, prop_name, info):
"""Callback when a config value has been changed
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'config'
:param dict info: Information e.g. about the changed config key
"""
config_key = info['args'][1]
# config_value = info['args'][2]
if config_key == "SOURCE_EDITOR_STYLE":
self.reload_style() | Callback when a config value has been changed
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'config'
:param dict info: Information e.g. about the changed config key | entailment |
def get_current_state_m(self):
"""Returns the state model of the currently open tab"""
page_id = self.view.notebook.get_current_page()
if page_id == -1:
return None
page = self.view.notebook.get_nth_page(page_id)
state_identifier = self.get_state_identifier_for_page(page)
return self.tabs[state_identifier]['state_m'] | Returns the state model of the currently open tab | entailment |
def state_machine_manager_notification(self, model, property, info):
"""Triggered whenever a new state machine is created, or an existing state machine is selected.
"""
if self.current_state_machine_m is not None:
selection = self.current_state_machine_m.selection
if len(selection.states) > 0:
self.activate_state_tab(selection.get_selected_state()) | Triggered whenever a new state machine is created, or an existing state machine is selected. | entailment |
def clean_up_tabs(self):
""" Method remove state-tabs for those no state machine exists anymore.
"""
tabs_to_close = []
for state_identifier, tab_dict in list(self.tabs.items()):
if tab_dict['sm_id'] not in self.model.state_machine_manager.state_machines:
tabs_to_close.append(state_identifier)
for state_identifier, tab_dict in list(self.closed_tabs.items()):
if tab_dict['sm_id'] not in self.model.state_machine_manager.state_machines:
tabs_to_close.append(state_identifier)
for state_identifier in tabs_to_close:
self.close_page(state_identifier, delete=True) | Method remove state-tabs for those no state machine exists anymore. | entailment |
def state_machines_set_notification(self, model, prop_name, info):
"""Observe all open state machines and their root states
"""
if info['method_name'] == '__setitem__':
state_machine_m = info.args[1]
self.observe_model(state_machine_m) | Observe all open state machines and their root states | entailment |
def state_machines_del_notification(self, model, prop_name, info):
"""Relive models of closed state machine
"""
if info['method_name'] == '__delitem__':
state_machine_m = info["result"]
try:
self.relieve_model(state_machine_m)
except KeyError:
pass
self.clean_up_tabs() | Relive models of closed state machine | entailment |
def add_state_editor(self, state_m):
"""Triggered whenever a state is selected.
:param state_m: The selected state model.
"""
state_identifier = self.get_state_identifier(state_m)
if state_identifier in self.closed_tabs:
state_editor_ctrl = self.closed_tabs[state_identifier]['controller']
state_editor_view = state_editor_ctrl.view
handler_id = self.closed_tabs[state_identifier]['source_code_changed_handler_id']
source_code_view_is_dirty = self.closed_tabs[state_identifier]['source_code_view_is_dirty']
del self.closed_tabs[state_identifier] # pages not in self.closed_tabs and self.tabs at the same time
else:
state_editor_view = StateEditorView()
if isinstance(state_m, LibraryStateModel):
state_editor_view['main_notebook_1'].set_current_page(
state_editor_view['main_notebook_1'].page_num(state_editor_view.page_dict["Data Linkage"]))
state_editor_ctrl = StateEditorController(state_m, state_editor_view)
self.add_controller(state_identifier, state_editor_ctrl)
if state_editor_ctrl.get_controller('source_ctrl') and state_m.state.get_next_upper_library_root_state() is None:
# observe changed to set the mark dirty flag
handler_id = state_editor_view.source_view.get_buffer().connect('changed', self.script_text_changed,
state_m)
self.view.get_top_widget().connect('draw', state_editor_view.source_view.on_draw)
else:
handler_id = None
source_code_view_is_dirty = False
(tab, inner_label, sticky_button) = create_tab_header('', self.on_tab_close_clicked,
self.on_toggle_sticky_clicked, state_m)
set_tab_label_texts(inner_label, state_m, source_code_view_is_dirty)
state_editor_view.get_top_widget().title_label = inner_label
state_editor_view.get_top_widget().sticky_button = sticky_button
page_content = state_editor_view.get_top_widget()
page_id = self.view.notebook.prepend_page(page_content, tab)
page = self.view.notebook.get_nth_page(page_id)
self.view.notebook.set_tab_reorderable(page, True)
page.show_all()
self.view.notebook.show()
self.tabs[state_identifier] = {'page': page, 'state_m': state_m,
'controller': state_editor_ctrl, 'sm_id': self.model.selected_state_machine_id,
'is_sticky': False,
'source_code_view_is_dirty': source_code_view_is_dirty,
'source_code_changed_handler_id': handler_id}
return page_id | Triggered whenever a state is selected.
:param state_m: The selected state model. | entailment |
def script_text_changed(self, text_buffer, state_m):
""" Update gui elements according text buffer changes
Checks if the dirty flag needs to be set and the tab label to be updated.
:param TextBuffer text_buffer: Text buffer of the edited script
:param rafcon.gui.models.state.StateModel state_m: The state model related to the text buffer
:return:
"""
state_identifier = self.get_state_identifier(state_m)
if state_identifier in self.tabs:
tab_list = self.tabs
elif state_identifier in self.closed_tabs:
tab_list = self.closed_tabs
else:
logger.warning('It was tried to check a source script of a state with no state-editor')
return
if tab_list[state_identifier]['controller'].get_controller('source_ctrl') is None:
logger.warning('It was tried to check a source script of a state with no source-editor')
return
current_text = tab_list[state_identifier]['controller'].get_controller('source_ctrl').view.get_text()
old_is_dirty = tab_list[state_identifier]['source_code_view_is_dirty']
source_script_state_m = state_m.state_copy if isinstance(state_m, LibraryStateModel) else state_m
# remove next two lines and tab is also set dirty for source scripts inside of a LibraryState (maybe in future)
if isinstance(state_m, LibraryStateModel) or state_m.state.get_next_upper_library_root_state() is not None:
return
if source_script_state_m.state.script_text == current_text:
tab_list[state_identifier]['source_code_view_is_dirty'] = False
else:
tab_list[state_identifier]['source_code_view_is_dirty'] = True
if old_is_dirty is not tab_list[state_identifier]['source_code_view_is_dirty']:
self.update_tab_label(source_script_state_m) | Update gui elements according text buffer changes
Checks if the dirty flag needs to be set and the tab label to be updated.
:param TextBuffer text_buffer: Text buffer of the edited script
:param rafcon.gui.models.state.StateModel state_m: The state model related to the text buffer
:return: | entailment |
def destroy_page(self, tab_dict):
""" Destroys desired page
Disconnects the page from signals and removes interconnection to parent-controller or observables.
:param tab_dict: Tab-dictionary that holds all necessary information of a page and state-editor.
"""
# logger.info("destroy page %s" % tab_dict['controller'].model.state.get_path())
if tab_dict['source_code_changed_handler_id'] is not None:
handler_id = tab_dict['source_code_changed_handler_id']
if tab_dict['controller'].view.source_view.get_buffer().handler_is_connected(handler_id):
tab_dict['controller'].view.source_view.get_buffer().disconnect(handler_id)
else:
logger.warning("Source code changed handler of state {0} was already removed.".format(tab_dict['state_m']))
self.remove_controller(tab_dict['controller']) | Destroys desired page
Disconnects the page from signals and removes interconnection to parent-controller or observables.
:param tab_dict: Tab-dictionary that holds all necessary information of a page and state-editor. | entailment |
def close_page(self, state_identifier, delete=True):
"""Closes the desired page
The page belonging to the state with the specified state_identifier is closed. If the deletion flag is set to
False, the controller of the page is stored for later usage.
:param state_identifier: Identifier of the page's state
:param delete: Whether to delete the controller (deletion is necessary if teh state is deleted)
"""
# delete old controller references
if delete and state_identifier in self.closed_tabs:
self.destroy_page(self.closed_tabs[state_identifier])
del self.closed_tabs[state_identifier]
# check for open page of state
if state_identifier in self.tabs:
page_to_close = self.tabs[state_identifier]['page']
current_page_id = self.view.notebook.page_num(page_to_close)
if not delete:
self.closed_tabs[state_identifier] = self.tabs[state_identifier]
else:
self.destroy_page(self.tabs[state_identifier])
del self.tabs[state_identifier]
# Finally remove the page, this triggers the callback handles on_switch_page
self.view.notebook.remove_page(current_page_id) | Closes the desired page
The page belonging to the state with the specified state_identifier is closed. If the deletion flag is set to
False, the controller of the page is stored for later usage.
:param state_identifier: Identifier of the page's state
:param delete: Whether to delete the controller (deletion is necessary if teh state is deleted) | entailment |
def find_page_of_state_m(self, state_m):
"""Return the identifier and page of a given state model
:param state_m: The state model to be searched
:return: page containing the state and the state_identifier
"""
for state_identifier, page_info in list(self.tabs.items()):
if page_info['state_m'] is state_m:
return page_info['page'], state_identifier
return None, None | Return the identifier and page of a given state model
:param state_m: The state model to be searched
:return: page containing the state and the state_identifier | entailment |
def on_tab_close_clicked(self, event, state_m):
"""Triggered when the states-editor close button is clicked
Closes the tab.
:param state_m: The desired state model (the selected state)
"""
[page, state_identifier] = self.find_page_of_state_m(state_m)
if page:
self.close_page(state_identifier, delete=False) | Triggered when the states-editor close button is clicked
Closes the tab.
:param state_m: The desired state model (the selected state) | entailment |
def on_toggle_sticky_clicked(self, event, state_m):
"""Callback for the "toggle-sticky-check-button" emitted by custom TabLabel widget.
"""
[page, state_identifier] = self.find_page_of_state_m(state_m)
if not page:
return
self.tabs[state_identifier]['is_sticky'] = not self.tabs[state_identifier]['is_sticky']
page.sticky_button.set_active(self.tabs[state_identifier]['is_sticky']) | Callback for the "toggle-sticky-check-button" emitted by custom TabLabel widget. | entailment |
def close_all_pages(self):
"""Closes all tabs of the states editor"""
states_to_be_closed = []
for state_identifier in self.tabs:
states_to_be_closed.append(state_identifier)
for state_identifier in states_to_be_closed:
self.close_page(state_identifier, delete=False) | Closes all tabs of the states editor | entailment |
def close_pages_for_specific_sm_id(self, sm_id):
"""Closes all tabs of the states editor for a specific sm_id"""
states_to_be_closed = []
for state_identifier in self.tabs:
state_m = self.tabs[state_identifier]["state_m"]
if state_m.state.get_state_machine().state_machine_id == sm_id:
states_to_be_closed.append(state_identifier)
for state_identifier in states_to_be_closed:
self.close_page(state_identifier, delete=False) | Closes all tabs of the states editor for a specific sm_id | entailment |
def on_switch_page(self, notebook, page_pointer, page_num, user_param1=None):
"""Update state selection when the active tab was changed
"""
page = notebook.get_nth_page(page_num)
# find state of selected tab
for tab_info in list(self.tabs.values()):
if tab_info['page'] is page:
state_m = tab_info['state_m']
sm_id = state_m.state.get_state_machine().state_machine_id
selected_state_m = self.current_state_machine_m.selection.get_selected_state()
# If the state of the selected tab is not in the selection, set it there
if selected_state_m is not state_m and sm_id in self.model.state_machine_manager.state_machines:
self.model.selected_state_machine_id = sm_id
self.current_state_machine_m.selection.set(state_m)
return | Update state selection when the active tab was changed | entailment |
def activate_state_tab(self, state_m):
"""Opens the tab for the specified state model
The tab with the given state model is opened or set to foreground.
:param state_m: The desired state model (the selected state)
"""
# The current shown state differs from the desired one
current_state_m = self.get_current_state_m()
if current_state_m is not state_m:
state_identifier = self.get_state_identifier(state_m)
# The desired state is not open, yet
if state_identifier not in self.tabs:
# add tab for desired state
page_id = self.add_state_editor(state_m)
self.view.notebook.set_current_page(page_id)
# bring tab for desired state into foreground
else:
page = self.tabs[state_identifier]['page']
page_id = self.view.notebook.page_num(page)
self.view.notebook.set_current_page(page_id)
self.keep_only_sticked_and_selected_tabs() | Opens the tab for the specified state model
The tab with the given state model is opened or set to foreground.
:param state_m: The desired state model (the selected state) | entailment |
def keep_only_sticked_and_selected_tabs(self):
"""Close all tabs, except the currently active one and all sticked ones"""
# Only if the user didn't deactivate this behaviour
if not global_gui_config.get_config_value('KEEP_ONLY_STICKY_STATES_OPEN', True):
return
page_id = self.view.notebook.get_current_page()
# No tabs are open
if page_id == -1:
return
page = self.view.notebook.get_nth_page(page_id)
current_state_identifier = self.get_state_identifier_for_page(page)
states_to_be_closed = []
# Iterate over all tabs
for state_identifier, tab_info in list(self.tabs.items()):
# If the tab is currently open, keep it open
if current_state_identifier == state_identifier:
continue
# If the tab is sticky, keep it open
if tab_info['is_sticky']:
continue
# Otherwise close it
states_to_be_closed.append(state_identifier)
for state_identifier in states_to_be_closed:
self.close_page(state_identifier, delete=False) | Close all tabs, except the currently active one and all sticked ones | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.