Ejemplo n.º 1
0
    def recursive_generate_models(self, load_meta_data):
        # regulate depth of library model generation to reduce resource consumption
        current_hierarchy_depth = self.state.library_hierarchy_depth
        min_temp_depth = 2
        max_hierarchy_depth = global_gui_config.get_config_value(
            "MAX_VISIBLE_LIBRARY_HIERARCHY", min_temp_depth)
        if max_hierarchy_depth < min_temp_depth:
            logger.verbose(
                "Increase MAX_VISIBLE_LIBRARY_HIERARCHY to {0} for state {1}.".
                format(min_temp_depth, self))
            max_hierarchy_depth = min_temp_depth
        no_fully_rec_lib_model = global_gui_config.get_config_value(
            "NO_FULLY_RECURSIVE_LIBRARY_MODEL", False)
        recursive_model_generation = not (
            current_hierarchy_depth >
            max_hierarchy_depth) or not no_fully_rec_lib_model
        if recursive_model_generation:
            self.initiate_library_root_state_model()
        self._load_port_models()

        if load_meta_data:
            if not self.load_meta_data():
                # TODO decide to scale here or still in the editor -> at the moment meta data is missing here
                import rafcon.gui.helpers.meta_data as gui_helper_meta_data
            else:
                self.meta_data_was_scaled = True
Ejemplo n.º 2
0
    def recursive_generate_models(self, load_meta_data):
        # TODO maybe find a different way to load the meta data of ports correctly
        # at the moment the models of state_copy get initialized and the meta data taken from there if not found in
        # state itself

        # regulate depth of library model generation to reduce resource consumption
        current_hierarchy_depth = self.state.library_hierarchy_depth
        min_temp_depth = 2
        max_hierarchy_depth = global_gui_config.get_config_value(
            "MAX_VISIBLE_LIBRARY_HIERARCHY", min_temp_depth)
        if max_hierarchy_depth < min_temp_depth:
            logger.verbose(
                "Increase MAX_VISIBLE_LIBRARY_HIERARCHY to {0} for state {1}.".
                format(min_temp_depth, self))
            max_hierarchy_depth = min_temp_depth
        no_fully_rec_lib_model = global_gui_config.get_config_value(
            "NO_FULLY_RECURSIVE_LIBRARY_MODEL", False)
        recursive_model_generation = not (
            current_hierarchy_depth >
            max_hierarchy_depth) or not no_fully_rec_lib_model
        if recursive_model_generation:
            # logger.debug("initialize state copy {0}".format(self))
            self.initiate_library_root_state_model()
        else:
            logger.verbose("Do not initialize state copy {0}".format(self))

        self._load_port_models()

        if load_meta_data:
            if not self.load_meta_data():
                # TODO decide to scale here or still in the editor -> at the moment meta data is missing here
                import rafcon.gui.helpers.meta_data as gui_helper_meta_data
                # gui_helper_meta_data.scale_library_ports_meta_data(self)
            else:
                self.meta_data_was_scaled = True
Ejemplo n.º 3
0
    def __init__(self, top_window):
        View.__init__(self)

        self.win = top_window['main_window']
        self.insert_accelerators = {'new': gtk.accelerator_parse('<control>N'),
                                    'open': gtk.accelerator_parse('<control>O'),
                                    'save': gtk.accelerator_parse('<control>S'),
                                    # 'save_as': gtk.accelerator_parse('<shift><control>S'),  # no default accelerator insert
                                    'quit': gtk.accelerator_parse('<control>Q'),
                                    'cut': gtk.accelerator_parse('<control>X'),
                                    'copy': gtk.accelerator_parse('<control>C'),
                                    'paste': gtk.accelerator_parse('<control>V'),
                                    # 'delete': gtk.accelerator_parse('Delete'),  # no default accelerator insert
                                    # 'undo': gtk.accelerator_parse('<control>Z'),  # no default accelerator insert
                                    # 'redo': gtk.accelerator_parse('<control>Y'),  # no default accelerator insert
                                    }
        self.sub_menu_open_recently = gtk.Menu()
        self['open_recent'].set_submenu(self.sub_menu_open_recently)

        for menu_item_name in self.buttons.iterkeys():
            # set icon
            self.set_menu_item_icon(menu_item_name, self.buttons[menu_item_name])
            # set accelerator if in shortcuts dictionary with menu_item_name == key
            if menu_item_name in global_gui_config.get_config_value('SHORTCUTS'):
                shortcuts = global_gui_config.get_config_value('SHORTCUTS')[menu_item_name]
                if shortcuts:
                    self.set_menu_item_accelerator(menu_item_name, shortcuts[0])
Ejemplo n.º 4
0
    def __init__(self, state_machine, meta=None, load_meta_data=True):
        """Constructor
        """
        MetaModel.__init__(self)  # pass columns as separate parameters

        assert isinstance(state_machine, StateMachine)

        self.state_machine = state_machine
        self.state_machine_id = state_machine.state_machine_id

        root_state = self.state_machine.root_state
        if isinstance(root_state, ContainerState):
            self.root_state = ContainerStateModel(
                root_state, parent=self, load_meta_data=load_meta_data)
        else:
            self.root_state = StateModel(root_state,
                                         parent=self,
                                         load_meta_data=load_meta_data)

        if isinstance(meta, Vividict):
            self.meta = meta
        else:
            self.meta = Vividict()

        # ongoing_complex_actions is updated by ComplexActionObserver -> secure encapsulated observation
        # and made observable by state machine model here
        self.ongoing_complex_actions = {}
        self.complex_action_observer = ComplexActionObserver(self)

        self.meta_signal = Signal()
        self.state_meta_signal = Signal()
        self.action_signal = Signal()
        self.state_action_signal = Signal()
        self.sm_selection_changed_signal = Signal()
        self.destruction_signal = Signal()

        self.temp = Vividict()

        if load_meta_data:
            self.load_meta_data(recursively=False)

        self.selection = Selection(self.sm_selection_changed_signal)

        self.storage_lock = threading.Lock(
        )  # lock can not be substituted by the state machine lock -> maybe because it is a RLock

        self.history = None
        if global_gui_config.get_config_value('HISTORY_ENABLED'):
            from rafcon.gui.models.modification_history import ModificationsHistoryModel
            self.history = ModificationsHistoryModel(self)
        else:
            logger.info("The modification history is disabled")

        self.auto_backup = None
        if global_gui_config.get_config_value('AUTO_BACKUP_ENABLED'):
            from rafcon.gui.models.auto_backup import AutoBackupModel
            self.auto_backup = AutoBackupModel(self)

        self.root_state.register_observer(self)
        self.register_observer(self)
Ejemplo n.º 5
0
    def register_view(self, view):
        super(SourceEditorController, self).register_view(view)

        view['open_external_button'].connect('clicked',
                                             self.open_externally_clicked)
        view['apply_button'].connect('clicked', self.apply_clicked)
        view['cancel_button'].connect('clicked', self.cancel_clicked)

        view['pylint_check_button'].set_active(
            global_gui_config.get_config_value(
                'CHECK_PYTHON_FILES_WITH_PYLINT', False))

        view['pylint_check_button'].set_tooltip_text(
            "Change global default value in GUI config.")
        view['apply_button'].set_tooltip_text(
            global_gui_config.get_config_value('SHORTCUTS')['apply'][0])
        view['open_external_button'].set_tooltip_text(
            "Open source in external editor. " +
            global_gui_config.get_config_value(
                'SHORTCUTS')['open_external_editor'][0])

        if isinstance(
                self.model.state,
                LibraryState) or self.model.state.get_library_root_state():
            view['pylint_check_button'].set_sensitive(False)
            view.textview.set_editable(False)
            view['apply_button'].set_sensitive(False)
            view['cancel_button'].set_sensitive(False)
            view['open_external_button'].set_sensitive(False)
Ejemplo n.º 6
0
    def new_buffer(self):
        style_scheme_manager = GtkSource.StyleSchemeManager()
        b = GtkSource.Buffer()
        b.set_language(self.language_manager.get_language(self.language))
        b.set_highlight_syntax(True)

        user_editor_style = global_gui_config.get_config_value(
            self.editor_style, "classic")
        if user_editor_style.startswith("rafcon"):
            user_editor_style = "rafcon"
            dark_theme = global_gui_config.get_config_value(
                'THEME_DARK_VARIANT', True)
            if dark_theme:
                user_editor_style = "rafcon-dark"
        if is_custom_design_enabled():
            user_editor_style = global_design_config.get_config_value(
                "SOURCE_VIEW_THEME")
        scheme = style_scheme_manager.get_scheme(user_editor_style)
        if scheme:
            self.style_scheme = scheme
        else:
            logger.debug(
                "The editor style '{}' is not supported. Using the default 'classic'"
                .format(user_editor_style))
            self.style_scheme = style_scheme_manager.get_scheme('classic')
        b.set_style_scheme(self.style_scheme)
        return b
Ejemplo n.º 7
0
    def __init__(self):
        super().__init__(
            builder_filename=glade.get_glade_path('menu_bar.glade'),
            parent='menubar')

        self.insert_accelerators = {
            'new': Gtk.accelerator_parse('<control>N'),
            'open': Gtk.accelerator_parse('<control>O'),
            'save': Gtk.accelerator_parse('<control>S'),
            'quit': Gtk.accelerator_parse('<control>Q'),
            'cut': Gtk.accelerator_parse('<control>X'),
            'copy': Gtk.accelerator_parse('<control>C'),
            'paste': Gtk.accelerator_parse('<control>V'),
        }
        self.sub_menu_open_recently = Gtk.Menu()
        self['open_recent'].set_submenu(self.sub_menu_open_recently)

        for menu_item_name in self.buttons:
            # set icon
            self.set_menu_item_icon(menu_item_name,
                                    self.buttons[menu_item_name])
            # set accelerator if in shortcuts dictionary with menu_item_name == key
            if menu_item_name in global_gui_config.get_config_value(
                    'SHORTCUTS'):
                shortcuts = global_gui_config.get_config_value(
                    'SHORTCUTS')[menu_item_name]
                if shortcuts:
                    main_shortcut = shortcuts[0] if isinstance(
                        shortcuts, list) else shortcuts
                    self.set_menu_item_accelerator(menu_item_name,
                                                   main_shortcut)
        for sub_menu_name in self.sub_menus:
            sub_menu = self[sub_menu_name]
            sub_menu.set_reserve_toggle_size(False)
Ejemplo n.º 8
0
    def __init__(self, state_machine_model):
        ModelMT.__init__(self)

        assert isinstance(state_machine_model, StateMachineModel)
        self.state_machine_model = state_machine_model

        # variables used for lock files
        # TODO reduce those variables
        self.__destroyed = False
        self.AUTO_RECOVERY_LOCK_ENABLED = False
        if os.path.exists(os.path.join(RAFCON_TEMP_PATH_BASE, 'lock')) and \
                global_gui_config.get_config_value('AUTO_RECOVERY_LOCK_ENABLED'):
            self.AUTO_RECOVERY_LOCK_ENABLED = True
        self.lock_file_lock = threading.Lock()
        self.lock_file = None
        self.last_lock_file_name = None

        # general auto-backup variable
        self.timed_temp_storage_enabled = global_gui_config.get_config_value(
            'AUTO_BACKUP_ENABLED')
        self.only_fix_interval = global_gui_config.get_config_value(
            'AUTO_BACKUP_ONLY_FIX_FORCED_INTERVAL')
        self.force_temp_storage_interval = global_gui_config.get_config_value(
            'AUTO_BACKUP_FORCED_STORAGE_INTERVAL')
        self.timed_temp_storage_interval = global_gui_config.get_config_value(
            'AUTO_BACKUP_DYNAMIC_STORAGE_INTERVAL')
        self.last_backup_time = time.time(
        )  # used as 'last-backup' and 'last-modification-not-backup-ed' time
        self.marked_dirty = False
        self.__perform_storage = False
        self._timer_request_time = None
        self.timer_request_lock = threading.Lock()
        self.tmp_timed_storage_thread = None
        self.meta = Vividict()
        if state_machine_model.state_machine.file_system_path is not None:
            # logger.info("store meta data of {0} to {1}".format(self, meta_data_path))
            # data used for restore tabs -> (having the information to load state machines without loading them)
            self.meta['last_saved'][
                'time'] = state_machine_model.state_machine.last_update
            self.meta['last_saved'][
                'file_system_path'] = state_machine_model.state_machine.file_system_path

        logger.debug(
            "The auto-backup for state-machine {2} is {0} and set to '{1}'"
            "".format(
                'ENABLED' if self.timed_temp_storage_enabled else 'DISABLED',
                'fix interval mode'
                if self.only_fix_interval else 'dynamic interval mode',
                self.state_machine_model.state_machine.state_machine_id))

        # register observer before initializing check loop
        self.observe_model(self.state_machine_model)
        # initializing check loop to fully initialize the model
        if not self.only_fix_interval:
            self.perform_temp_storage()
        else:
            self.check_for_auto_backup(force=True)
Ejemplo n.º 9
0
    def add_graphical_state_machine_editor(self, state_machine_m):
        """Add to for new state machine

        If a new state machine was added, a new tab is created with a graphical editor for this state machine.

        :param StateMachineModel state_machine_m: The new state machine model
        """
        assert isinstance(state_machine_m, StateMachineModel)

        sm_id = state_machine_m.state_machine.state_machine_id
        logger.debug(
            "Create new graphical editor for state machine with id %s" %
            str(sm_id))

        if global_gui_config.get_config_value(
                'GAPHAS_EDITOR', False) and GAPHAS_AVAILABLE or not GL_ENABLED:
            if not GL_ENABLED and not global_gui_config.get_config_value(
                    'GAPHAS_EDITOR', False):
                logger.info(
                    "Gaphas editor is used. "
                    "The gui-config is set to use OpenGL editor but not all libraries needed are provided."
                )
            graphical_editor_view = GraphicalEditorGaphasView(state_machine_m)
            graphical_editor_ctrl = GraphicalEditorGaphasController(
                state_machine_m, graphical_editor_view)
        else:
            graphical_editor_view = GraphicalEditorView()
            graphical_editor_ctrl = GraphicalEditorController(
                state_machine_m, graphical_editor_view)

        self.add_controller(sm_id, graphical_editor_ctrl)

        tab, tab_label = create_tab_header('', self.on_close_clicked,
                                           self.on_mouse_right_click,
                                           state_machine_m, 'refused')
        set_tab_label_texts(tab_label, state_machine_m,
                            state_machine_m.state_machine.marked_dirty)

        page = graphical_editor_view['main_frame']

        self.view.notebook.append_page(page, tab)
        self.view.notebook.set_tab_reorderable(page, True)
        page.show_all()

        self.tabs[sm_id] = {
            'page': page,
            'state_machine_m': state_machine_m,
            'file_system_path': state_machine_m.state_machine.file_system_path,
            'marked_dirty': state_machine_m.state_machine.marked_dirty,
            'root_state_name': state_machine_m.state_machine.root_state.name
        }

        self.observe_model(state_machine_m)
        graphical_editor_view.show()
        self.view.notebook.show()
        self.last_focused_state_machine_ids.append(sm_id)
Ejemplo n.º 10
0
 def refresh_shortcuts(self):
     self.shortcut_manager.remove_shortcuts()
     self.shortcut_manager.update_shortcuts()
     for item_name, shortcuts in global_gui_config.get_config_value('SHORTCUTS', {}).iteritems():
         if shortcuts and item_name in self.view.buttons:
             self.view.set_menu_item_accelerator(item_name, shortcuts[0])
     self.create_logger_warning_if_shortcuts_are_overwritten_by_menu_bar()
Ejemplo n.º 11
0
def create_tab_header(title, close_callback, sticky_callback,
                      *additional_parameters):
    def handle_middle_click(widget, event, callback, *additional_parameters):
        """Calls `callback` in case the middle mouse button was pressed"""
        if event.get_button()[1] == 2 and callback:
            callback(event, *additional_parameters)

    sticky_button = None
    label = Gtk.Label(label=title)
    label.set_max_width_chars(STATE_NAME_MAX_CHARS)
    close_button = create_tab_close_button(close_callback,
                                           *additional_parameters)

    hbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 0)
    if global_gui_config.get_config_value('KEEP_ONLY_STICKY_STATES_OPEN',
                                          True):
        sticky_button = create_sticky_button(sticky_callback,
                                             *additional_parameters)
        sticky_button.set_name('sticky_button')
        hbox.pack_start(sticky_button, expand=False, fill=False, padding=0)
    hbox.pack_start(label, expand=True, fill=True, padding=0)
    hbox.pack_start(close_button, expand=False, fill=False, padding=0)

    event_box = Gtk.EventBox()
    event_box.set_name("tab_label")  # required for gtkrc
    event_box.connect('button-press-event', handle_middle_click,
                      close_callback, *additional_parameters)
    event_box.tab_label = label
    event_box.add(hbox)
    event_box.show_all()

    return event_box, label, sticky_button
Ejemplo n.º 12
0
    def insert_history_item(self,
                            parent,
                            history_item,
                            description,
                            dummy=False):
        """Enters a single history item into the tree store

        :param gtk.TreeItem parent: Parent tree item
        :param HistoryItem history_item: History item to be inserted
        :param str description: A description to be added to the entry
        :param None dummy: Whether this is just a dummy entry (wrapper for concurrency items)
        :return: Inserted tree item
        :rtype: gtk.TreeItem
        """
        if not history_item.state_reference:
            logger.error(
                "This must never happen! Current history_item is {}".format(
                    history_item))
            return None
        content = None

        if global_gui_config.get_config_value(
                "SHOW_PATH_NAMES_IN_EXECUTION_HISTORY", False):
            content = (history_item.state_reference.name + " - " +
                       history_item.state_reference.get_path() + " - " +
                       description, None if dummy else history_item,
                       None if dummy else self.TOOL_TIP_TEXT)
        else:
            content = (history_item.state_reference.name + " - " + description,
                       None if dummy else history_item,
                       None if dummy else self.TOOL_TIP_TEXT)

        tree_item = self.history_tree_store.insert_before(
            parent, None, content)
        return tree_item
Ejemplo n.º 13
0
    def generate_right_click_menu_library(self):
        menu = gtk.Menu()
        accel_group = self.accel_group
        shortcuts_dict = global_gui_config.get_config_value('SHORTCUTS')

        self.insert_show_library_content_in_menu(menu, shortcuts_dict, accel_group)

        self.insert_is_start_state_in_menu(menu, shortcuts_dict, accel_group)

        self.insert_execution_sub_menu_in_menu(menu, shortcuts_dict, accel_group)

        self.insert_copy_cut_paste_in_menu(menu, shortcuts_dict, accel_group, no_paste=True)

        menu.append(create_image_menu_item("Group states", constants.BUTTON_GROUP, self.on_group_states_activate,
                                           accel_code=shortcuts_dict['group'][0], accel_group=accel_group))

        menu.append(create_image_menu_item("Open separately", constants.BUTTON_OPEN,
                                           self.on_open_library_state_separately_activate,
                                           accel_code=shortcuts_dict['open_library_state_separately'][0],
                                           accel_group=accel_group))

        menu.append(create_image_menu_item("Substitute state with library", constants.BUTTON_REFR,
                                           self.on_substitute_state_activate,
                                           accel_code=shortcuts_dict['substitute_state'][0], accel_group=accel_group))

        sub_menu_item, sub_menu = append_sub_menu_to_parent_menu("Substitute library with template", menu,
                                                                 constants.BUTTON_REFR)
        sub_menu.append(create_image_menu_item("Keep state name", constants.BUTTON_LEFTA,
                        partial(self.on_substitute_library_with_template_activate, keep_name=True)))

        sub_menu.append(create_image_menu_item("Take name from library", constants.BUTTON_EXCHANGE,
                        partial(self.on_substitute_library_with_template_activate, keep_name=False)))

        return menu
Ejemplo n.º 14
0
def scale_meta_data_according_states(models_dict):
    """ Offset meta data of state elements according the area used indicated by the states and
    maybe scoped variables (in case of OpenGL editor) meta data.

    Method is used by group states to set the offset for the elements in the new container state.
    The method needs some generalisation to create methods to easily scale meta data according new parents or views
    (e.g. to show inner elements of s library state).

    :param models_dict: dictionary that hold lists of meta data with state attribute consistent keys
    :return:
    """
    gaphas_editor = True if global_gui_config.get_config_value('GAPHAS_EDITOR') else False

    left, right, top, bottom = get_boundaries_of_elements_in_dict(models_dict=models_dict)

    parent_size = models_dict['state'].parent.get_meta_data_editor(for_gaphas=gaphas_editor)['size']
    _, rel_pos, size = cal_frame_according_boundaries(left, right, top, bottom, parent_size, gaphas_editor)

    # Set size and position of new container state
    models_dict['state'].set_meta_data_editor('rel_pos', rel_pos, from_gaphas=gaphas_editor)
    models_dict['state'].set_meta_data_editor('size', size, from_gaphas=gaphas_editor)
    offset = mult_two_vectors((-1., -1.), rel_pos)
    offset_rel_pos_of_all_models_in_dict(models_dict, offset, gaphas_editor)

    return True
Ejemplo n.º 15
0
 def refresh_shortcuts(self):
     self.shortcut_manager.remove_shortcuts()
     self.shortcut_manager.update_shortcuts()
     for item_name, shortcuts in global_gui_config.get_config_value(
             'SHORTCUTS', {}).iteritems():
         if shortcuts and item_name in self.view.buttons:
             self.view.set_menu_item_accelerator(item_name, shortcuts[0])
Ejemplo n.º 16
0
 def set_default_paned_positions(self):
     if global_gui_config.get_config_value("SEMANTIC_DATA_MODE", False):
         self['vpaned'].set_position(200)
     else:
         self['vpaned'].set_position(575)
     self['logic_vpaned'].set_position(300)
     self['data_vpaned'].set_position(300)
Ejemplo n.º 17
0
    def on_full_screen_activate(self, *args):
        """
        function to display the currently selected state machine in full screen mode
        :param args:
        :return:
        """
        self.sm_notebook.set_show_tabs(False)

        # Hide obsolete widgets of VBox
        self.main_window_view['graphical_editor_label_event_box'].hide()
        if not global_gui_config.get_config_value("FULLSCREEN_SHOW_TOOLBAR",
                                                  True):
            self.main_window_view['graphical_editor_toolbar'].hide()
        self.main_window_view['console_return_button'].hide()

        # Move whole VBox into fullscreen window
        self.main_window_view['central_v_pane'].remove(
            self.main_window_view['central_vbox'])
        self.full_screen_window.add(self.main_window_view['central_vbox'])

        # Show fullscreen window undecorated in same screen as main window
        position = self.main_window_view.get_top_widget().get_position()
        self.full_screen_window.show()
        self.full_screen_window.move(position[0], position[1])
        self.full_screen_window.set_decorated(False)
        self.full_screen_window.fullscreen()
        self.main_window_view.get_top_widget().iconify()
Ejemplo n.º 18
0
    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)
Ejemplo n.º 19
0
    def __init__(self):
        View.__init__(self)

        self._lock = threading.Lock()

        self.text_view = gtk.TextView()
        self.text_view.set_property('editable', False)

        self.filtered_buffer = self.create_text_buffer()

        self.text_view.set_buffer(self.filtered_buffer)

        self.text_view.set_border_width(10)

        self._enables = {}
        self._auto_scroll_handler_id = None

        scrollable = gtk.ScrolledWindow()
        scrollable.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scrollable.set_name('console_scroller')
        scrollable.add(self.text_view)
        self.text_view.show()

        self['scrollable'] = scrollable
        self.top = 'scrollable'
        self.quit_flag = False

        from rafcon.gui.config import global_gui_config
        self.logging_priority = global_gui_config.get_config_value("LOGGING_CONSOLE_GTK_PRIORITY", glib.PRIORITY_LOW)

        self._stored_line_number = None
        self._stored_line_offset = None
        self._stored_text_of_line = None
        self._stored_relative_lines = None
Ejemplo n.º 20
0
 def create_logger_warning_if_shortcuts_are_overwritten_by_menu_bar():
     shortcut_dict = global_gui_config.get_config_value('SHORTCUTS')
     shortcut_key_patterns = [elem for l in shortcut_dict.values() for elem in l]
     for key in ['E', 'F', 'V', 'X', 'H', 'e', 'f', 'v', 'x', 'h']:
         if '<Alt>' + key in shortcut_key_patterns:
             dict_pair = {k: v for k, v_list in shortcut_dict.iteritems() for v in v_list if '<Alt>' + key == v}
             logger.warning("Your current shortcut {0} is not working because a menu-bar access key "
                            "is overwriting it.".format(dict_pair))
Ejemplo n.º 21
0
 def add_description_to_tooltip(tool_tip_with_only_sm_file_system_path_in):
     from rafcon.gui.helpers.state_machine import get_root_state_description_of_sm_file_system_path
     description = get_root_state_description_of_sm_file_system_path(tool_tip_with_only_sm_file_system_path_in)
     enabled = global_gui_config.get_config_value('LIBRARY_TREE_TOOLTIP_INCLUDES_ROOT_STATE_DESCRIPTION', True)
     if description and enabled:
         return "[source]:\n{0}\n\n[description]:\n\n{1}" \
                "".format(tool_tip_with_only_sm_file_system_path_in, description)
     else:
         return "[source]:\n{0}".format(tool_tip_with_only_sm_file_system_path_in)
Ejemplo n.º 22
0
    def __init__(self, window):
        # Setup window to listen for accelerators
        self.main_window = window
        self.accel_group = Gtk.AccelGroup()
        self.main_window.add_accel_group(self.accel_group)

        self.__action_to_callbacks = {}
        self.__action_to_shortcuts = global_gui_config.get_config_value('SHORTCUTS', {})
        self.register_shortcuts()
        self.__controller_action_callbacks = {}
Ejemplo n.º 23
0
 def on_quit_activate(self, widget, data=None, force=False):
     global_runtime_config.prepare_recently_opened_state_machines_list_for_storage()
     if force:
         backup_session.reset_session()
     if not force and global_gui_config.get_config_value("SESSION_RESTORE_ENABLED"):
         backup_session.store_session()
         self.on_delete_check_sm_running()
         force = True
     avoid_shutdown = self.on_delete_event(widget, None, force=force)
     if not avoid_shutdown:
         self.on_destroy(None)
Ejemplo n.º 24
0
    def __init__(self, top_window):
        View.__init__(self)

        self.win = top_window['main_window']
        self.insert_accelerators = {
            'new': Gtk.accelerator_parse('<control>N'),
            'open': Gtk.accelerator_parse('<control>O'),
            'save': Gtk.accelerator_parse('<control>S'),
            # 'save_as': Gtk.accelerator_parse('<shift><control>S'),  # no default accelerator insert
            'quit': Gtk.accelerator_parse('<control>Q'),
            'cut': Gtk.accelerator_parse('<control>X'),
            'copy': Gtk.accelerator_parse('<control>C'),
            'paste': Gtk.accelerator_parse('<control>V'),
            # 'delete': Gtk.accelerator_parse('Delete'),  # no default accelerator insert
            # 'undo': Gtk.accelerator_parse('<control>Z'),  # no default accelerator insert
            # 'redo': Gtk.accelerator_parse('<control>Y'),  # no default accelerator insert
        }
        self.sub_menu_open_recently = Gtk.Menu()
        self['open_recent'].set_submenu(self.sub_menu_open_recently)

        # Gtk TODO: Unfortunately does not help against not showing Accel Keys
        # self.win.add_accel_group(self['accelgroup1'])

        for menu_item_name in self.buttons:
            # set icon
            self.set_menu_item_icon(menu_item_name,
                                    self.buttons[menu_item_name])
            # set accelerator if in shortcuts dictionary with menu_item_name == key
            if menu_item_name in global_gui_config.get_config_value(
                    'SHORTCUTS'):
                shortcuts = global_gui_config.get_config_value(
                    'SHORTCUTS')[menu_item_name]
                if shortcuts:
                    main_shortcut = shortcuts[0] if isinstance(
                        shortcuts, list) else shortcuts
                    self.set_menu_item_accelerator(menu_item_name,
                                                   main_shortcut)

        for sub_menu_name in self.sub_menus:
            sub_menu = self[sub_menu_name]
            sub_menu.set_reserve_toggle_size(False)
Ejemplo n.º 25
0
    def __init__(self):
        View.__init__(self)

        self._lock = threading.Lock()

        ######################################################
        # Logging text view
        ######################################################
        self.logging_console_view = LoggingConsoleView()
        self['console'].pack_start(self.logging_console_view.get_top_widget(), True, True, 0)
        self.logging_console_view.get_top_widget().show()

        ######################################################
        # initial configuration of the console
        ######################################################
        self['button_follow_logging'].set_active(global_gui_config.get_config_value('CONSOLE_FOLLOW_LOGGING', True))
        self['button_show_verbose'].set_active(global_gui_config.get_config_value('LOGGING_SHOW_VERBOSE', True))
        self['button_show_debug'].set_active(global_gui_config.get_config_value('LOGGING_SHOW_DEBUG', True))
        self['button_show_info'].set_active(global_gui_config.get_config_value('LOGGING_SHOW_INFO', True))
        self['button_show_warning'].set_active(global_gui_config.get_config_value('LOGGING_SHOW_WARNING', True))
        self['button_show_error'].set_active(global_gui_config.get_config_value('LOGGING_SHOW_ERROR', True))

        self['undock_console_button'].set_image(gui_helper_label.create_button_label(constants.BUTTON_UNDOCK))
        self['undock_console_button'].set_tooltip_text("Undock debug console widget")
        self['console_hide_button'].set_image(gui_helper_label.create_button_label(constants.BUTTON_DOWNA))

        gui_helper_label.ellipsize_labels_recursively(self['debug_console_button_hbox'])
Ejemplo n.º 26
0
    def __compare_parameters(self, width, height, zoom, parameters):
        """Compare parameters for equality

        Checks if a cached image is existing, the the dimensions agree and finally if the properties are equal. If
        so, True is returned, else False,
        :param width: The width of the image
        :param height: The height of the image
        :param zoom: The current scale/zoom factor
        :param parameters: The parameters used for the image
        :return: True if all parameters are equal, False else
        """

        # Deactivated caching
        if not global_gui_config.get_config_value('ENABLE_CACHING', True):
            return False

        # Empty cache
        if not self.__image:
            return False

        # Changed image size
        if self.__width != width or self.__height != height:
            return False

        # Current zoom greater then prepared zoom
        if zoom > self.__zoom * self.__zoom_multiplicator:
            return False

        # Current zoom much smaller than prepared zoom, causes high memory usage and imperfect anti-aliasing
        if zoom < self.__zoom / self.__zoom_multiplicator:
            return False

        # Changed drawing parameter
        for key in parameters:
            try:
                if key not in self.__last_parameters or self.__last_parameters[
                        key] != parameters[key]:
                    return False
            except (AttributeError, ValueError):
                # Some values cannot be compared and raise an exception on comparison (e.g. numpy.ndarray). In this
                # case, just return False and do not cache.
                try:
                    # Catch at least the ndarray-case, as this could occure relatively often
                    import numpy
                    if isinstance(self.__last_parameters[key], numpy.ndarray):
                        return numpy.array_equal(self.__last_parameters[key],
                                                 parameters[key])
                except ImportError:
                    return False
                return False

        return True
Ejemplo n.º 27
0
 def prepare_the_labels(self):
     for notebook_name in self.notebook_names:
         notebook = self[notebook_name]
         for i in xrange(notebook.get_n_pages()):
             child = notebook.get_nth_page(i)
             tab_label = notebook.get_tab_label(child)
             if global_gui_config.get_config_value("USE_ICONS_AS_TAB_LABELS", True):
                 tab_label_text = tab_label.get_text()
                 notebook.set_tab_label(child, gui_helper_label.create_tab_header_label(tab_label_text, self.icons))
             else:
                 tab_label.set_angle(270)
             notebook.set_tab_reorderable(child, True)
             notebook.set_tab_detachable(child, True)
Ejemplo n.º 28
0
    def __init__(self):
        super().__init__(parent='scrollable')

        self._lock = threading.Lock()

        self.text_view = Gtk.TextView()
        self.text_view.set_property('editable', False)

        self._filtered_buffer = self.create_text_buffer()
        self._filtered_buffer_lock = ReaderWriterLock(self._filtered_buffer)

        self.text_view.set_buffer(self.filtered_buffer)

        self.text_view.set_border_window_size(Gtk.TextWindowType.LEFT, 10)
        self.text_view.set_border_window_size(Gtk.TextWindowType.RIGHT, 10)
        self.text_view.set_border_window_size(Gtk.TextWindowType.TOP, 10)
        self.text_view.set_border_window_size(Gtk.TextWindowType.BOTTOM, 10)

        self._enables = {}
        self._auto_scroll_handler_id = None

        scrollable = Gtk.ScrolledWindow()
        scrollable.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        scrollable.set_name('console_scroller')
        scrollable.add(self.text_view)
        self.text_view.show()

        self['scrollable'] = scrollable
        self.top = 'scrollable'
        self.quit_flag = False

        self.logging_priority = global_gui_config.get_config_value("LOGGING_CONSOLE_GTK_PRIORITY", GLib.PRIORITY_LOW)
        self.max_logging_buffer_lines = global_gui_config.get_config_value('MAX_LOGGING_BUFFER_LINES', 5000)

        self._stored_line_number = None
        self._stored_line_offset = None
        self._stored_text_of_line = None
        self._stored_relative_lines = None
Ejemplo n.º 29
0
def offset_rel_pos_of_models_meta_data_according_parent_state(models_dict):
    """ Offset meta data of state elements according the area used indicated by the state meta data.

    The offset_rel_pos_of_models_meta_data_according_parent_state offset the position of all handed old elements
    in the dictionary.

    :param models_dict: dict that hold lists of meta data with state attribute consistent keys
    :return:
    """
    gaphas_editor = True if global_gui_config.get_config_value('GAPHAS_EDITOR') else False
    old_parent_rel_pos = models_dict['state'].get_meta_data_editor(for_gaphas=gaphas_editor)['rel_pos']
    offset_rel_pos_of_all_models_in_dict(models_dict, pos_offset=old_parent_rel_pos, gaphas_editor=gaphas_editor)

    return True
Ejemplo n.º 30
0
    def __init__(self, state, parent=None, meta=None, load_meta_data=True):
        assert isinstance(state, LibraryState)
        # TODO maybe find a different way to load the meta data of ports correctly
        # at the moment the models of state_copy get initialized and the meta data taken from there if not found in
        # state itself
        self.state_copy_initialized = False
        self.meta_data_was_scaled = False
        super(LibraryStateModel, self).__init__(state, parent, meta)

        # regulate depth of library model generation to reduce resource consumption
        current_hierarchy_depth = self.state.library_hierarchy_depth
        max_hierarchy_depth = global_gui_config.get_config_value(
            "MAX_VISIBLE_LIBRARY_HIERARCHY", 2)
        no_fully_rec_lib_model = global_gui_config.get_config_value(
            "NO_FULLY_RECURSIVE_LIBRARY_MODEL", False)
        recursive_model_generation = not (
            current_hierarchy_depth >
            max_hierarchy_depth) or not no_fully_rec_lib_model
        if recursive_model_generation:
            # logger.debug("initialize state copy {0}".format(self))
            self.initiate_library_root_state_model()
        else:
            logger.debug("Do not initialize state copy {0}".format(self))

        self._load_input_data_port_models()
        self._load_output_data_port_models()
        self._load_outcome_models()

        if load_meta_data:
            if not self.load_meta_data():
                # TODO decide to scale here or still in the editor -> at the moment meta data is missing here
                import rafcon.gui.helpers.meta_data as gui_helper_meta_data
                # gui_helper_meta_data.scale_library_ports_meta_data(self)
            else:
                self.meta_data_was_scaled = True
                if not global_gui_config.get_config_value('GAPHAS_EDITOR'):
                    self.meta_data_was_scaled = False