Ejemplo n.º 1
0
 def load(self, argv):
     '''
     @param argv: the list with argv parameter needed to load the launch file.
                  The name and value are separated by C{:=}
     @type argv: C{[str]}
     @return True, if the launch file was loaded
     @rtype boolean
     @raise LaunchConfigException: on load errors
     '''
     try:
         roscfg = roslaunch.ROSLaunchConfig()
         loader = roslaunch.XmlLoader()
         self.argv = self.resolveArgs(argv)
         loader.load(self.Filename, roscfg, verbose=False, argv=self.argv)
         self.__roscfg = roscfg
         nm.file_watcher().add_launch(self.__masteruri, self.__launchFile, self.__launch_id, self.getIncludedFiles(self.Filename))
         if not nm.is_local(nm.nameres().getHostname(self.__masteruri)):
             files = self.getIncludedFiles(self.Filename,
                                           regexp_list=[QRegExp("\\bdefault\\b"),
                                                        QRegExp("\\bvalue=.*pkg:\/\/\\b"),
                                                        QRegExp("\\bvalue=.*package:\/\/\\b"),
                                                        QRegExp("\\bvalue=.*\$\(find\\b")])
             nm.file_watcher_param().add_launch(self.__masteruri,
                                                self.__launchFile,
                                                self.__launch_id,
                                                files)
     except roslaunch.XmlParseException, e:
         test = list(re.finditer(r"environment variable '\w+' is not set", str(e)))
         message = str(e)
         if test:
             message = ''.join([message, '\n', 'environment substitution is not supported, use "arg" instead!'])
         raise LaunchConfigException(message)
Ejemplo n.º 2
0
    def __init__(self, parent=None):
        QSyntaxHighlighter.__init__(self, parent)
        self.rules = []
        self.commentStart = QRegExp("#")
        self.commentEnd = QRegExp("\n")
        self.commentFormat = QTextCharFormat()
        self.commentFormat.setFontItalic(True)
        self.commentFormat.setForeground(Qt.darkGray)
        f = QTextCharFormat()
        r = QRegExp()
        r.setMinimal(True)
        f.setFontWeight(QFont.Normal)
        f.setForeground(Qt.darkBlue)
        tagList = [
            "\\bignore_hosts\\b", "\\bsync_hosts\\b", "\\bignore_nodes\\b",
            "\\bsync_nodes\\b", "\\bignore_topics\\b",
            "\\bignore_publishers\\b", "\\bignore_topics\\b",
            "\\bsync_topics\\b", "\\bignore_subscribers\\b",
            "\\bsync_services\\b", "\\bsync_topics_on_demand\\b",
            "\\bsync_remote_nodes\\b"
        ]
        for tag in tagList:
            r.setPattern(tag)
            self.rules.append((QRegExp(r), QTextCharFormat(f)))

        f.setForeground(Qt.darkGreen)
        f.setFontWeight(QFont.Bold)
        attrList = ["\\b\\*|\\*\\B|\\/\\*"]
        for attr in attrList:
            r.setPattern(attr)
            self.rules.append((QRegExp(r), QTextCharFormat(f)))
Ejemplo n.º 3
0
    def __init__(self, parent=None):
        QSyntaxHighlighter.__init__(self, parent)
        self.rules = []
        self.commentStart = QRegExp("#")
        self.commentEnd = QRegExp("\n|\r")
        self.default_format = QTextCharFormat()
        self.default_format.setForeground(QColor(24, 24, 24))
        self.commentFormat = QTextCharFormat()
        self.commentFormat.setFontItalic(True)
        self.commentFormat.setForeground(Qt.darkGray)

        tagList = ["\\btrue\\b", "\\bfalse\\b"]
        # create patterns for tags
        for tag in tagList:
            self.rules.append(
                (self._create_regexp(tag), self._create_format(Qt.blue)))

        # create pattern for digits
        self.rules.append((self._create_regexp("\\d+"),
                           self._create_format(QColor(127, 64, 127))))

        # create pattern for params
        self.rules.append((self._create_regexp("\s*[_.\w]*\s*:"),
                           self._create_format(Qt.darkBlue)))

        # create pattern for params
        self.rules.append(
            (self._create_regexp(":\s*:[_\.\w]*$|:\s*\@[_\.\w]*$"),
             self._create_format(Qt.darkBlue)))

        # create pattern for list signes
        self.rules.append((self._create_regexp("^\s*-"),
                           self._create_format(Qt.darkRed, 'bold')))

        # create pattern for ???
        self.rules.append(
            (self._create_regexp("^---$"), self._create_format(Qt.darkRed)))

        # create pattern for braces
        self.rules.append((self._create_regexp("[\[\]\{\}\,]"),
                           self._create_format(Qt.darkGreen)))

        # create patterns for strings
        self.rules.append((self._create_regexp("\".*\"|\'.*\'"),
                           self._create_format(Qt.blue)))

        # create patterns for substitutions
        self.rules.append((self._create_regexp("\\$\\(.*\\)"),
                           self._create_format(QColor(127, 64, 127))))

        # create patterns for DOCTYPE
        self.rules.append((self._create_regexp("<!DOCTYPE.*>"),
                           self._create_format(Qt.lightGray)))
        self.rules.append((self._create_regexp("<\\?xml.*\\?>"),
                           self._create_format(Qt.lightGray)))
Ejemplo n.º 4
0
    def __on_show_erroneous_check_box_state_changed(self, activated):
        """
        If this checkBox is set, only erroneous hosts and nodes will be displayed.

        :param activated: 2 if checkBox is set, 0 if check is unset
        :type activated: Integer
        """
        if activated is 2:
            self.__filter_proxy.setFilterRegExp(QRegExp("error"))
            self.__filter_proxy.setFilterKeyColumn(2)
        else:
            self.__filter_proxy.setFilterRegExp(QRegExp(""))
 def __init__(self, parent=None):
     QSyntaxHighlighter.__init__(self, parent)
     self.rules = []
     self.comment_start = QRegExp("<!--")
     self.comment_end = QRegExp("-->")
     self.comment_format = self._create_format(Qt.darkGray, 'italic')
     #        self.mark_background = QBrush(QColor(251, 247, 222))
     # create patterns for braces
     self.rules.append((self._create_regexp("</?|/?>"),
                        self._create_format(QColor(24, 24, 24))))
     # create patterns for TAG
     tag_list = '|'.join(
         ["\\b%s\\b" % t for t in self.LAUNCH_CHILDS.keys()])
     self.rules.append(
         (self._create_regexp(tag_list), self._create_format(Qt.darkRed)))
     # create patterns for ATTRIBUTES
     attr_list = '|'.join(
         set([
             "\\b%s" % attr for v in self.LAUNCH_ATTR.values()
             for attr in v.keys()
         ]))
     self.rules.append((self._create_regexp(attr_list),
                        self._create_format(QColor(0, 100,
                                                   0))))  # darkGreen
     # create patterns for substitutions
     self.rule_arg = (self._create_regexp("\\$\\(.*\\)"),
                      self._create_format(QColor(77, 0, 38)))
     # create patterns for DOCTYPE
     self.rules.append((self._create_regexp("<!DOCTYPE.*>"),
                        self._create_format(Qt.lightGray)))
     self.rules.append((self._create_regexp("<\\?xml.*\\?>"),
                        self._create_format(Qt.lightGray)))
     # create patterns for yaml parameter inside
     self.rules.append((self._create_regexp("^\s*[_.\w]*\s*:"),
                        self._create_format(Qt.darkBlue)))
     # create patterns for yaml oneline strings inside
     self.rules.append(
         (self._create_regexp("'.*'"), self._create_format(Qt.blue)))
     # create pattern for list signes
     self.rules.append((self._create_regexp("^\s*-"),
                        self._create_format(Qt.darkRed, 'bold')))
     # create pattern for digits
     self.rules.append((self._create_regexp("\\d+"),
                        self._create_format(QColor(127, 64, 127))))
     # create patterns for strings
     self.string_pattern = QRegExp("\"")
     self.string_format = self._create_format(Qt.blue)
     # part to select an XML block
     self._tag_hl_range = []  # list with puples (start, length)
     self._tag_hl_last = set()  # set with blocks of last highlighted tags
Ejemplo n.º 6
0
    def discover_frames(self):

        # Define a search pattern, it will look for all namespaces that contain the 'received_control_mode' topic
        search_pattern = re.compile(r'^(?!.*link).*')
        # search_pattern = re.compile(r'^((?!.*link)|(.*base)).*$')

        # Get the list of all currently availabel frames in TF1 (this is a temporary solution until a better one is found)
        time.sleep(1) # Give tf time to start working
        # all_frames = self._tf_listener.getFrameStrings()

        yaml_frames = yaml.load(self._tf2_buffer.all_frames_as_yaml())

        # Look through all avaiable topics
        for entry in yaml_frames:
            namespace = search_pattern.findall(entry)
            if len(namespace):
                self._available_frames.append(namespace[0])

        # Sort the namespaces alphabetically
        self._available_frames.sort()

        # rospy.logdebug out the result of the search
        # rospy.loginfo("Found robots with namespace: \n%s", self._available_frames)

        # Add robots namespaces to combobox
        self._combobox = self._widget.findChildren(QComboBox, QRegExp('frameSelector'))[0]
        self._combobox.insertItems(0, self._available_frames)
        self._namespace = self._combobox.currentText()

        # Quit if no robots are found
        if len(self._available_frames) == 0:
            rospy.logerr("[%s]: No robots available !!", rospy.get_name())
            sys.exit()
 def _included_files(self, path):
     '''
     Returns all included files in the given file.
     '''
     result = []
     with open(path, 'r') as f:
         data = f.read()
         reg = QRegExp("=[\s\t]*\".*\"")
         reg.setMinimal(True)
         pos = reg.indexIn(data)
         while pos != -1 and self._isrunning:
             try:
                 pp = interpret_path(reg.cap(0).strip('"'))
                 f = QFile(pp)
                 ext = os.path.splitext(pp)
                 if f.exists() and ext[1] in nm.settings().SEARCH_IN_EXT:
                     result.append(pp)
             except Exception as exp:
                 parsed_text = pp
                 try:
                     parsed_text = reg.cap(0).strip('"')
                 except:
                     pass
                 self.warning_signal.emit("Error while parse '%s': %s" %
                                          (parsed_text, exp))
             pos += reg.matchedLength()
             pos = reg.indexIn(data, pos)
     return result
 def _create_regexp(self,
                    pattern='',
                    cs=Qt.CaseInsensitive,
                    syntax=QRegExp.Wildcard,
                    minimal=False):
     _regexp = QRegExp(pattern, cs, syntax)
     _regexp.setMinimal(minimal)
     return _regexp
Ejemplo n.º 9
0
    def __init__(self, filename, parent=None):
        self.parent = parent
        QTextEdit.__init__(self, parent)
        self.setObjectName('Editor - %s' % filename)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.show_custom_context_menu)
#        self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
        self.setAcceptRichText(False)
        font = QFont()
        font.setFamily("Fixed".decode("utf-8"))
        font.setPointSize(12)
        self.setFont(font)
        self.setLineWrapMode(QTextEdit.NoWrap)
        self.setTabStopWidth(25)
        self.setAcceptRichText(False)
        self.setCursorWidth(2)
        self.setFontFamily("courier new")
        self.setProperty("backgroundVisible", True)
        bg_style = "QTextEdit { background-color: #fffffc;}"
        self.setStyleSheet("%s" % (bg_style))
        self.setTextColor(QColor(0, 0, 0))
        self.regexp_list = [QRegExp("\\binclude\\b"), QRegExp("\\btextfile\\b"),
                            QRegExp("\\bfile\\b"), QRegExp("\\bvalue=.*pkg:\/\/\\b"),
                            QRegExp("\\bvalue=.*package:\/\/\\b"),
                            QRegExp("\\bvalue=.*\$\(find\\b"),
                            QRegExp("\\bargs=.*\$\(find\\b"),
                            QRegExp("\\bdefault=.*\$\(find\\b")]
        self.filename = filename
        self.file_mtime = 0
#             f = QFile(filename)
#             if f.open(QIODevice.ReadOnly | QIODevice.Text):
#                 self.file_info = QFileInfo(filename)
#                 self.setText(unicode(f.readAll(), "utf-8"))

        self.path = '.'
        # enables drop events
        self.setAcceptDrops(True)
        # variables for threaded search
        self._search_thread = None
        self._stop = False
        self._internal_args = {}
        ext = os.path.splitext(filename)
        if self.filename:
            self.setText("")
            _, self.file_mtime, file_content = nm.nmd().file.get_file_content(filename)
            if ext[1] in ['.launch', '.xml']:
                self._internal_args = get_internal_args(file_content)
            self.setText(file_content)
        self._is_launchfile = False
        if ext[1] in ['.launch', '.xml', '.xacro', '.srdf', '.urdf']:
            if ext[1] in ['.launch']:
                self._is_launchfile = True
            self.hl = XmlHighlighter(self.document(), is_launch=False)
            self.cursorPositionChanged.connect(self._document_position_changed)
        else:
            self.hl = YamlHighlighter(self.document())
Ejemplo n.º 10
0
    def setUp(self):
        unittest.TestCase.setUp(self)

        syntax_nr = QRegExp.RegExp
        syntax = QRegExp.PatternSyntax(syntax_nr)
        self._regExp = QRegExp(self._query_text, Qt.CaseInsensitive, syntax)

        self._filter = TextFilter(self._regExp)
        self._filter.set_text(self._query_text)
Ejemplo n.º 11
0
    def filter_by_item(self, item):
        """
        Used to tell the filter by which item should filter. If the AbstractItem is None all log entries should be shown.

        :param item: the item by which the filter should filter
        :type item: AbstractItem
        """
        self.invalidateFilter()
        if item is not None:
            self.setFilterRegExp(QRegExp(".*" + item.get_seuid() + ".*"))
            self.setFilterKeyColumn(2)
Ejemplo n.º 12
0
 def included_files(cls, text_or_path, regexp_list=[QRegExp("\\btextfile\\b"),
                                                    QRegExp("\\bfile\\b"),
                                                    QRegExp("\\bdefault\\b"),
                                                    QRegExp("\\bvalue=.*pkg:\/\/\\b"),
                                                    QRegExp("\\bvalue=.*package:\/\/\\b"),
                                                    QRegExp("\\bvalue=.*\$\(find\\b"),
                                                    QRegExp("\\bargs=.*\$\(find\\b")],
                    recursive=True, unique=True):
     result = []
     lines = []
     pwd = '.'
     f = QFile(text_or_path)
     if f.exists():
         pwd = os.path.dirname(text_or_path)
         with open(text_or_path, 'r') as f:
             content = f.read()
             # remove the comments
             comment_pattern = QRegExp("<!--.*?-->")
             pos = comment_pattern.indexIn(content)
             while pos != -1:
                 content = content[:pos] + content[pos + comment_pattern.matchedLength():]
                 pos = comment_pattern.indexIn(content)
             lines = content.splitlines()
     else:
         lines = [text_or_path]
     line_index = 0
     for line in lines:
         index = cls._index(line, regexp_list)
         if index > -1:
             startIndex = line.find('"', index)
             if startIndex > -1:
                 endIndex = line.find('"', startIndex + 1)
                 fileName = line[startIndex + 1:endIndex]
                 if len(fileName) > 0:
                     try:
                         path = cls.interpretPath(fileName, pwd)
                         if os.path.isfile(path):
                             if not unique:
                                 result.append((line_index, path))
                             else:
                                 result.append(path)
                             ext = os.path.splitext(path)
                             if recursive and ext[1] in nm.settings().SEARCH_IN_EXT:
                                 result += cls.included_files(path, regexp_list)
                     except Exception:
                         import traceback
                         print traceback.format_exc()
         line_index += 1
     if unique:
         return list(set(result))
     return result
Ejemplo n.º 13
0
    def __init__(self, filename, parent=None):
        self.parent = parent
        QTextEdit.__init__(self, parent)
        self.setObjectName('Editor - %s' % filename)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.show_custom_context_menu)
        #        self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
        self.setAcceptRichText(False)
        font = QFont()
        font.setFamily('Fixed')
        font.setPointSize(12)
        self.setFont(font)
        self.setLineWrapMode(QTextEdit.NoWrap)
        self.setTabStopWidth(25)
        self.setAcceptRichText(False)
        self.setCursorWidth(2)
        self.setFontFamily("courier new")
        self.setProperty("backgroundVisible", True)
        bg_style = "QTextEdit { background-color: #fffffc;}"
        self.setStyleSheet("%s" % (bg_style))
        self.setTextColor(QColor(0, 0, 0))
        self.regexp_list = [
            QRegExp("\\binclude\\b"),
            QRegExp("\\btextfile\\b"),
            QRegExp("\\bfile\\b"),
            QRegExp("\\bvalue=.*pkg:\/\/\\b"),
            QRegExp("\\bvalue=.*package:\/\/\\b"),
            QRegExp("\\bvalue=.*\$\(find\\b"),
            QRegExp("\\bargs=.*\$\(find\\b"),
            QRegExp("\\bdefault=.*\$\(find\\b")
        ]
        self.filename = filename
        self.file_mtime = 0
        #             f = QFile(filename)
        #             if f.open(QIODevice.ReadOnly | QIODevice.Text):
        #                 self.file_info = QFileInfo(filename)
        #                 self.setText(unicode(f.readAll(), "utf-8"))

        self.path = '.'
        # variables for threaded search
        self._search_thread = None
        self._stop = False
        self._internal_args = {}
        self._ext = os.path.splitext(filename)[1]
        self.setText("Loading file content ... press F5 to reload!")
        self.setReadOnly(True)
        self._to_select = []
        nm.nmd().file.file_content.connect(self._apply_file_content)
        nm.nmd().file.error.connect(self._on_nmd_error)
        if self.filename:
            nm.nmd().file.get_file_content_threaded(filename)
Ejemplo n.º 14
0
    def set_text(self, text):
        """
        Setter for _text
        :param text: text to set ''str''
        :emits filter_changed_signal: If _enabled is true
        """
        super(TextFilter, self).set_text(text)

        syntax_nr = QRegExp.RegExp
        syntax = QRegExp.PatternSyntax(syntax_nr)
        self.regex = QRegExp(text, Qt.CaseInsensitive, syntax)
        self.set_regex(self.regex)
Ejemplo n.º 15
0
 def getIncludedFiles(cls,
                      inc_file,
                      regexp_list=[
                          QRegExp("\\binclude\\b"),
                          QRegExp("\\btextfile\\b"),
                          QRegExp("\\bfile\\b"),
                          QRegExp("\\bdefault\\b"),
                          QRegExp("\\bvalue=.*pkg:\/\/\\b"),
                          QRegExp("\\bvalue=.*package:\/\/\\b"),
                          QRegExp("\\bvalue=.*\$\(find\\b")
                      ]):
     '''
     Reads the configuration file and searches for included files. This files
     will be returned in a list.
     @param inc_file: path of the ROS launch file
     @param regexp_list: pattern of
     @return: the list with all files needed for the configuration
     @rtype: C{[str,...]}
     '''
     result = set()
     with open(inc_file, 'r') as f:
         content = f.read()
         # remove the comments
         comment_pattern = QRegExp("<!--.*?-->")
         pos = comment_pattern.indexIn(content)
         while pos != -1:
             content = content[:pos] + content[pos + comment_pattern.
                                               matchedLength():]
             pos = comment_pattern.indexIn(content)
         lines = content.splitlines()
     for line in lines:
         index = cls._index(line, regexp_list)
         if index > -1:
             startIndex = line.find('"', index)
             if startIndex > -1:
                 endIndex = line.find('"', startIndex + 1)
                 fileName = line[startIndex + 1:endIndex]
                 if len(fileName) > 0:
                     try:
                         path = cls.interpretPath(fileName,
                                                  os.path.dirname(inc_file))
                         if os.path.isfile(path):
                             result.add(path)
                             if path.endswith('.launch'):
                                 result.update(
                                     cls.getIncludedFiles(
                                         path, regexp_list))
                     except:
                         pass
     return list(result)
Ejemplo n.º 16
0
    def __init__(self, filename, parent=None):
        self.parent = parent
        QTextEdit.__init__(self, parent)
        self.setObjectName(' - '.join(['Editor', filename]))
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.show_custom_context_menu)
        #        self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
        self.setAcceptRichText(False)
        font = QFont()
        font.setFamily("Fixed".decode("utf-8"))
        font.setPointSize(12)
        self.setFont(font)
        self.setLineWrapMode(QTextEdit.NoWrap)
        self.setTabStopWidth(25)
        self.setAcceptRichText(False)
        self.setCursorWidth(2)
        self.setFontFamily("courier new")
        self.setProperty("backgroundVisible", True)
        self.regexp_list = [
            QRegExp("\\binclude\\b"),
            QRegExp("\\btextfile\\b"),
            QRegExp("\\bfile\\b"),
            QRegExp("\\bvalue=.*pkg:\/\/\\b"),
            QRegExp("\\bvalue=.*package:\/\/\\b"),
            QRegExp("\\bvalue=.*\$\(find\\b"),
            QRegExp("\\bargs=.*\$\(find\\b"),
            QRegExp("\\bdefault=.*\$\(find\\b")
        ]
        self.filename = filename
        self.file_info = None
        if self.filename:
            f = QFile(filename)
            if f.open(QIODevice.ReadOnly | QIODevice.Text):
                self.file_info = QFileInfo(filename)
                self.setText(unicode(f.readAll(), "utf-8"))

        self.path = '.'
        # enables drop events
        self.setAcceptDrops(True)
        if filename.endswith('.launch'):
            self.hl = XmlHighlighter(self.document())
            self.cursorPositionChanged.connect(self._document_position_changed)
        else:
            self.hl = YamlHighlighter(self.document())
        # variables for threaded search
        self._search_thread = None
        self._stop = False
 def __init__(self, nodename, masteruri, layout, parent=None):
     '''
     Creates a new item.
     '''
     QObject.__init__(self, parent)
     self.setObjectName("LoggerHandler")
     self.nodename = nodename
     self.masteruri = masteruri
     self._filter = QRegExp('', Qt.CaseInsensitive, QRegExp.Wildcard)
     self._logger_items = {}  # logger name: LoggerItem
     self.layout = layout
     self._change_all_cancel = False
     self._stored_values = {}
     self.loggers_signal.connect(self._handle_loggers)
     self._thread_update = None
     self._thread_set_all = None
Ejemplo n.º 18
0
 def _test_message(self, value):
     if not self.is_enabled():
         return False
     if self._text != '':
         if self._regex:
             temp = self._text
             if temp[0] != '^':
                 temp = '.*' + temp
             if temp[-1] != '$':
                 temp += '.*'
             if QRegExp(temp).exactMatch(value):
                 return True
         else:
             if value.find(self._text) != -1:
                 return True
     return False
    def __init__(self, parent=None, topic_type=str(), is_action_topic=False):
        QWidget.__init__(self, parent)

        if is_action_topic:
            self.topic_type = topic_type + "Goal"
        else:
            self.topic_type = topic_type
        self.is_action_topic = is_action_topic

        # start widget
        hbox = QHBoxLayout()
        hbox.setMargin(0)
        hbox.setContentsMargins(0, 0, 0, 0)

        # topic combo box
        self.topic_combo_box = QComboBox()
        self.topic_combo_box.setEnabled(False)
        self.topic_combo_box.blockSignals(True)
        self.topic_combo_box.setValidator(
            QRegExpValidator(QRegExp('((\d|\w|/)(?!//))*'), self))
        self.topic_combo_box.currentIndexChanged[str].connect(
            self.topic_changed)
        hbox.addWidget(self.topic_combo_box)

        # get system icon
        icon = QIcon.fromTheme("view-refresh")
        size = icon.actualSize(QSize(32, 32))

        # add refresh button
        refresh_topics_button = QPushButton()
        refresh_topics_button.clicked.connect(self.update_topic_list)
        refresh_topics_button.setIcon(icon)
        refresh_topics_button.setFixedSize(size.width() + 2, size.height() + 2)
        hbox.addWidget(refresh_topics_button)

        # end widget
        self.setLayout(hbox)

        # init widget
        self.update_topic_list()
Ejemplo n.º 20
0
    def test_message(self, message):
        """
        Tests if the message matches the filter.
        If the regex flag is False simple 'is this in that' text matching is used
        on _text. If the regex flag is True _text is treated as a regular expression
        with one exception. If it does not start with a ^ a .* is appended, and if
        it does not end with a $ then a .* is added to the end.

        :param message: the message to be tested against the filters, ''Message''
        :returns: True if the message matches, ''bool''
        """
        if self.is_enabled() and self._text != '':
            if self._regex:
                temp = self._text
                if temp[0] != '^':
                    temp = '.*' + temp
                if temp[-1] != '$':
                    temp += '.*'
                if QRegExp(temp).exactMatch(message._location):
                    return True
            else:
                if message._location.find(self._text) != -1:
                    return True
        return False
Ejemplo n.º 21
0
 def set_package_filter(self, text):
     self.launchlist_proxyModel.setFilterRegExp(QRegExp(text,
                                                        Qt.CaseInsensitive,
                                                        QRegExp.Wildcard))
Ejemplo n.º 22
0
    def createEditor(self, parent, option, index):

        print option

        print index.column()
        indices = [2, 3, 4]
        if index.column() not in indices:
            return None



        print "create_edit"

        if index.column() == 3:
                
            widget = QWidget(parent)

            slider = QSlider(Qt.Horizontal, widget)


            text_edit = QLineEdit(widget)
            text_edit.setFocus()
            text_edit.selectAll()

            text_edit.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

            hbox = QVBoxLayout()

            # slider.setMinimumWidth(400)

            # hbox.setMargin(0);
            hbox.setContentsMargins(2,1,2,1);

            # min_label = QLabel("min")
            # max_label = QLabel("max")
            # vbox.addWidget(min_label)
            
            
            hbox.addWidget(slider)
            hbox.addWidget(text_edit)
            # vbox.addWidget(max_label)

            
            widget.setLayout(hbox)
            # widget.setMinimumWidth(400)

            slider.setMinimumHeight(32)
            text_edit.setMinimumHeight(36)

            widget.setMinimumHeight(80)
            widget.setAutoFillBackground(True)
            widget.setStyleSheet(".QWidget { background:rgb(200, 200, 200); margin:0px; border:1px solid rgb(170, 170, 170); }")
            # parent.setMinimumWidth(300)

            row = index.row()
            imin = index.sibling(row, self._column_names.index("min"))
            imax = index.sibling(row, self._column_names.index("max"))

            

            smin = index.model().data(imin, Qt.EditRole)
            smax = index.model().data(imax, Qt.EditRole)         

            fmin = 0
            fmax = 100

            def isFloat(s):
                try: 
                    float(s)
                    return True
                except:
                    return False

            if isFloat(smin):
                fmin = float(smin)

            if isFloat(smax):
                fmax = float(smax)

            print fmin, fmax

            slider.setMinimum(int(fmin * 100))
            slider.setMaximum(int(fmax * 100))

            slider.setMouseTracking(True)

            @Slot(int)
            def sliderValueChanged(value):
                text_edit.setText(str(float(value)/100.))
                print "slider value changed to %d" % value

                text_edit.setFocus()
                text_edit.selectAll()
                pass

            @Slot()
            def sliderDown():
                print "slider pressed"



            @Slot()
            def sliderUp():
                print "slider released"

            @Slot()
            def editingFinished():
                text = text_edit.text()

                value = float(text)
                nvalue = value
                nvalue = min(nvalue, fmax)
                nvalue = max(nvalue, fmin)
                # print "nvalue is", nvalue

                if value != nvalue:
                    text_edit.setText(str(nvalue))                

                svalue = int(nvalue*100)

                print "text changed to %s" % text
                print "nvalue is", nvalue
                print "svalue is %d" % svalue

                slider.blockSignals(True)
                slider.setSliderPosition(svalue)
                slider.blockSignals(False)
                pass



            @Slot(str)
            def lineEditTextChanged(text):
                # text_edit.setText(str(value))                

                # slider.setSliderDown(True)

                # slider.sliderPressed.emit()
                print "setSliderDown"

                if not isFloat(text):
                    return

                

                value = float(text)
                nvalue = value
                # nvalue = min(nvalue, fmax)
                # nvalue = max(nvalue, fmin)
                # print "nvalue is", nvalue

                if value != nvalue:
                    text_edit.setText(str(nvalue))

                svalue = int(nvalue*100)

                print "text changed to %s" % text
                print "nvalue is", nvalue
                print "svalue is %d" % svalue

                slider.blockSignals(True)
                slider.setSliderPosition(svalue)
                slider.blockSignals(False)

                
                pass

            slider.valueChanged.connect(sliderValueChanged)

            slider.sliderPressed.connect(sliderDown)

            slider.sliderReleased.connect(sliderUp)

            text_edit.textChanged.connect(lineEditTextChanged)
            text_edit.editingFinished.connect(editingFinished)


            

            text_edit.selectAll()
            text_edit.setFocus()

            rx = QRegExp("^-?([1-9]\d*|0)(\.\d*)?$")
            v = QRegExpValidator(rx)
            text_edit.setValidator(v)

            widget.setFocusProxy(text_edit)
            
            edt = widget
        else:
            edt = QLineEdit(parent)

            if index.column() == 2:
                edt.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            elif index.column() == 4:
                edt.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)

            rx = QRegExp("^-?([1-9]\d*|0)(\.\d*)?$")
            v = QRegExpValidator(rx);
            edt.setValidator(v)
        # edt.setInputMask("#00000000")
        return edt    
Ejemplo n.º 23
0
 def _create_regexp(self, pattern=''):
     _regexp = QRegExp()
     _regexp.setMinimal(True)
     _regexp.setPattern(pattern)
     return _regexp
Ejemplo n.º 24
0
 def mark_block(self, block, position):
     text = block.text()
     word, idx_word = self._get_current_word(text, position)
     for hlblock in self._tag_hl_last:
         self.rehighlightBlock(hlblock)
     del self._tag_hl_last[:]
     self._tag_hl_range = [(idx_word, len(word))]
     next_block = block
     open_braces = 0
     closed_braces = 0
     idx_search = idx_word
     rindex = -1
     loop = 0
     tag_len = 0
     if self._isclosetag(word):
         # we are at the close tag: search for the open tag
         opentag = '<%s' % self._get_tag(word)
         tag_len = len(opentag)
         while rindex == -1 and next_block.isValid():
             rindex = text.rfind(opentag, 0, idx_search)
             obr, cbr = self._get_braces_count(
                 text[rindex if rindex != -1 else 0:idx_search])
             open_braces += obr
             closed_braces += cbr
             loop += 1
             if loop > 50000:
                 rindex = -1
                 break
             if rindex == -1:
                 next_block = next_block.previous()
                 text = next_block.text()
                 idx_search = len(text)
             elif open_braces <= closed_braces:
                 idx_search = rindex
                 rindex = -1
     elif self._isopentag(word):
         # we are at the open tag: search for the close tag
         closetag = QRegExp("</%s>|/>" % self._get_tag(word))
         closetag.setMinimal(True)
         while rindex == -1 and next_block.isValid():
             rindex = closetag.indexIn(text, idx_search)
             max_search_idx = rindex + closetag.matchedLength(
             ) if rindex != -1 else len(text)
             obr, cbr = self._get_braces_count(
                 text[idx_search:max_search_idx])
             open_braces += obr
             closed_braces += cbr
             loop += 1
             if loop > 50000:
                 rindex = -1
                 break
             if rindex == -1:
                 next_block = next_block.next()
                 text = next_block.text()
                 idx_search = 0
             elif open_braces > closed_braces:
                 idx_search = rindex + closetag.matchedLength()
                 rindex = -1
             tag_len = closetag.matchedLength()
     else:
         self._tag_hl_range = []
     self._end_tag_found = rindex != -1
     if self._tag_hl_range and block != next_block:
         self.rehighlightBlock(block)
         self._tag_hl_last.append(block)
     if rindex != -1:
         self._tag_hl_range.append((rindex, tag_len))
         self.rehighlightBlock(next_block)
         self._tag_hl_last.append(next_block)
Ejemplo n.º 25
0
 def __init__(self, parent=None, is_launch=True):
     QSyntaxHighlighter.__init__(self, parent)
     self._is_launch = is_launch
     self.rules = []
     self.comment_start = QRegExp("<!--")
     self.comment_end = QRegExp("-->")
     self.comment_format = self._create_format(Qt.darkGray, 'italic')
     #        self.mark_background = QBrush(QColor(251, 247, 222))
     # create patterns for braces
     self.rules.append((self._create_regexp("</?|/?>"),
                        self._create_format(QColor(24, 24, 24))))
     # create patterns for TAG
     if self._is_launch:
         tag_list = '|'.join(
             ["\\b%s\\b" % t for t in self.LAUNCH_CHILDS.keys()])
         self.rules.append((self._create_regexp(tag_list),
                            self._create_format(Qt.darkRed)))
     else:
         self.rules.append(
             (self._create_regexp(">|/>|<[/.\w:]*[\s\t>]|<[/.\w:]*$"),
              self._create_format(Qt.darkRed)))
     # create patterns for ATTRIBUTES
     if self._is_launch:
         attr_list = '|'.join(
             set([
                 "\\b%s" % attr for v in self.LAUNCH_ATTR.values()
                 for attr in v.keys()
             ]))
         self.rules.append((self._create_regexp(attr_list),
                            self._create_format(QColor(0, 100,
                                                       0))))  # darkGreen
     else:
         self.rules.append((self._create_regexp("[_.\w]*="),
                            self._create_format(QColor(0, 100,
                                                       0))))  # darkGreen
     # create patterns for substitutions
     self.rule_arg = (self._create_regexp("\\$\\(.*\\)"),
                      self._create_format(QColor(77, 0, 38)))
     # create patterns for DOCTYPE
     self.rules.append((self._create_regexp("<!DOCTYPE.*>"),
                        self._create_format(Qt.lightGray)))
     self.rules.append((self._create_regexp("<\\?xml.*\\?>"),
                        self._create_format(Qt.lightGray)))
     # create patterns for yaml parameter inside
     self.rules.append((self._create_regexp("[_.\w]*\s*:"),
                        self._create_format(Qt.darkBlue)))
     # create patterns for yaml oneline strings inside
     self.rules.append(
         (self._create_regexp("'.*'"), self._create_format(Qt.blue)))
     # create pattern for list signes
     self.rules.append((self._create_regexp("^\s*-"),
                        self._create_format(Qt.darkRed, 'bold')))
     # create pattern for digits
     self.rules.append((self._create_regexp("\\d+"),
                        self._create_format(QColor(127, 64, 127))))
     self.yaml_comment_rule = (self._create_regexp("#[.]*"),
                               self._create_format(Qt.darkGray))
     # create deprecated
     self.dep_pattern = []
     if self.DEPRECATED_PARAMETER:
         attr_list = '|'.join(
             set([
                 r'name="%s"' % attr
                 for attr in self.DEPRECATED_PARAMETER.keys()
             ]))
         # print(attr_list)
         self.dep_pattern.append(
             (self._create_regexp(attr_list),
              self._create_format(QColor(250, 0, 0), 'bold')))  # red
     # create patterns for strings
     self.string_pattern = QRegExp("\"")
     self.string_format = self._create_format(Qt.blue)
     # part to select an XML block
     self._tag_hl_range = []  # list with puples (start, length)
     self._tag_hl_last = []  # set with blocks of last highlighted tags
     self._color_hl_tag = QColor(255, 128, 0)
Ejemplo n.º 26
0
    def _process_highlight_exclude_filter(self,
                                          selection,
                                          selectiontype,
                                          exclude=False):
        """
        Modifies the relevant filters (based on selectiontype) to remove (exclude=True)
        or highlight (exclude=False) the selection from the dataset in the tableview.
        :param selection: the actual selection, ''str''
        :param selectiontype: the type of selection, ''str''
        :param exclude: If True process as an exclude filter, False process as an highlight filter, ''bool''
        """
        types = {
            self.tr('Node'): 2,
            self.tr('Topic'): 4,
            self.tr('Severity'): 1,
            self.tr('Message'): 0
        }
        try:
            col = types[selectiontype]
        except:
            raise RuntimeError(
                "Bad Column name in ConsoleWidget._process_highlight_exclude_filter()"
            )

        if col == 0:
            unique_messages = set()
            selected_indexes = self.table_view.selectionModel(
            ).selectedIndexes()
            num_selected = len(selected_indexes) / 6
            for index in range(num_selected):
                unique_messages.add(selected_indexes[num_selected * col +
                                                     index].data())
            unique_messages = list(unique_messages)
            for message in unique_messages:
                message = message.replace('\\', '\\\\')
                message = message.replace('.', '\\.')
                if exclude:
                    filter_index = self._add_exclude_filter(
                        selectiontype.lower())
                    filter_widget = self._exclude_filters[filter_index][
                        1].findChildren(QWidget,
                                        QRegExp('.*FilterWidget.*'))[0]
                else:
                    filter_index = self._add_highlight_filter(col)
                    filter_widget = self._highlight_filters[filter_index][
                        1].findChildren(QWidget,
                                        QRegExp('.*FilterWidget.*'))[0]
                filter_widget.set_regex(True)
                filter_widget.set_text('^' + message + '$')

        else:
            if exclude:
                # Test if the filter we are adding already exists if it does use the existing filter
                if self.filter_factory[selectiontype.lower()][1] not in [
                        type(item) for sublist in self._exclude_filters
                        for item in sublist
                ]:
                    filter_index = self._add_exclude_filter(
                        selectiontype.lower())
                else:
                    for index, item in enumerate(self._exclude_filters):
                        if type(item[0]) == self.filter_factory[
                                selectiontype.lower()][1]:
                            filter_index = index
            else:
                # Test if the filter we are adding already exists if it does use the existing filter
                if self.filter_factory[selectiontype.lower()][1] not in [
                        type(item) for sublist in self._highlight_filters
                        for item in sublist
                ]:
                    filter_index = self._add_highlight_filter(col)
                else:
                    for index, item in enumerate(self._highlight_filters):
                        if type(item[0]) == self.filter_factory[
                                selectiontype.lower()][1]:
                            filter_index = index

            if exclude:
                filter_widget = self._exclude_filters[filter_index][
                    1].findChildren(QWidget, QRegExp('.*FilterWidget.*'))[0]
                filter_widget.select_item(selection)
            else:
                filter_widget = self._highlight_filters[filter_index][
                    1].findChildren(QWidget, QRegExp('.*FilterWidget.*'))[0]
                filter_widget.select_item(selection)
Ejemplo n.º 27
0
 def filter(self, text):
     self._filter = QRegExp(text, Qt.CaseInsensitive, QRegExp.Wildcard)
     for name, item in self._logger_items.items():
         hidden = self._filter.indexIn(name) != -1
         item.setVisible(hidden)
Ejemplo n.º 28
0
    def __init__(self, document, is_dark=False, default=None):
        QSyntaxHighlighter.__init__(self, document)

        def contents_changed():
            self.highlightBlock("document.toPlainText()")

        document.contentsChanged.connect(contents_changed)

        self.is_dark = is_dark
        self.default = default

        global reformat

        if is_dark:
            STYLES = DARK_STYLES
        else:
            STYLES = BRIGHT_STYLES

        if default != None:
            STYLES['defaults'] = reformat(*default)

        # Multi-line strings (expression, flag, style)
        # FIXME: The triple-quotes in these two lines will mess up the
        # syntax highlighting from this point onward
        self.tri_single = (QRegExp("'''"), 1, STYLES['string2'])
        self.tri_double = (QRegExp('"""'), 2, STYLES['string2'])

        rules = []

        rules += [(r'%s' % w, 0, STYLES['defaults'])
                  for w in PythonHighlighter.defaults]
        # Keyword, operator, and brace rules
        rules += [(r'\b%s\b' % w, 0, STYLES['keyword'])
                  for w in PythonHighlighter.keywords]
        rules += [(r'%s' % o, 0, STYLES['operator'])
                  for o in PythonHighlighter.operators]
        rules += [(r'%s' % b, 0, STYLES['brace'])
                  for b in PythonHighlighter.braces]

        # All other rules
        rules += [
            # 'self'
            (r'\bself\b', 0, STYLES['self']),

            # Double-quoted string, possibly containing escape sequences
            (r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']),
            # Single-quoted string, possibly containing escape sequences
            (r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES['string']),

            # 'def' followed by an identifier
            (r'\bdef\b\s*(\w+)', 1, STYLES['defclass']),
            # 'class' followed by an identifier
            (r'\bclass\b\s*(\w+)', 1, STYLES['defclass']),

            # From '#' until a newline
            (r'#[^\n]*', 0, STYLES['comment']),

            # Numeric literals
            (r'\b[+-]?[0-9]+[lL]?\b', 0, STYLES['numbers']),
            (r'\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b', 0, STYLES['numbers']),
            (r'\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b', 0,
             STYLES['numbers']),
        ]

        # Build a QRegExp for each pattern
        self.rules = [(QRegExp(pat), index, fmt)
                      for (pat, index, fmt) in rules]
Ejemplo n.º 29
0
    def __init__(self, model):
        """
        Initializes the Widget.
        
        :param model: the model of the widget
        :type model: ROSModel
        """
        super(SelectionWidget, self).__init__()
        self.setObjectName('selection_widget')
        self.__model = model

        # Get path to UI file which is a sibling of this file
        self.rp = rospkg.RosPack()
        ui_file = os.path.join(self.rp.get_path('arni_rqt_detail_plugin'), 'resources', 'SelectionWidget.ui')
        # Extend the widget with all attributes and children from UI file
        loadUi(ui_file, self)
        self.setObjectName('SelectionWidgetUi')

        self.__selected_item = None


        self.__draw_graphs = True
        self.__current_combo_box_index = 0

        self.__last_update = rospy.Time.now()

        try:
            if rospy.get_param("/enable_statistics") == False:
                raise KeyError('/enable_statistics')
        except KeyError:
            self.__overview_widget = None
            raise EnvironmentError("/enable_statistics is either not set or set to false - arni gui would not work correctly. Please make sure to start "
                             "roscore with the neccesary parameters or to load these while running (see init_params.launch)")

        self.__values_dict = {
            "bandwidth_mean": 0,
            "bandwidth_stddev": 0,
            "bandwidth_max": 0,
        }

        self.__logger = self.__model.get_logger()
        self.__log_filter_proxy = LogFilterProxy()       
        self.__log_filter_proxy.filter_by_item(self.__selected_item)
        self.__log_filter_proxy.setDynamicSortFilter(True)        
        self.__log_filter_proxy.setSourceModel(self.__logger.get_representation())
        self.log_tab_tree_view.setModel(self.__log_filter_proxy)
        self.__log_delegate = LogDelegate()
        self.log_tab_tree_view.setItemDelegate(self.__log_delegate)

        self.__style_string = ".detailed_data {\n" \
                               "    font-size: 12\n;" \
                               "}\n"
        self.__style_string = ".erroneous_entry {\n" \
                               "    color: red\n;" \
                               "}\n"

        self.information_tab_text_browser.setStyleSheet(self.__style_string)

        self.range_combo_box.clear()
        self.range_combo_box.addItem("10 " + self.tr("Seconds"))
        self.range_combo_box.addItem("30 " + self.tr("Seconds"))
        self.range_combo_box.addItem("60 " + self.tr("Seconds"))
        self.range_combo_box.setCurrentIndex(0)

        #self.scrollAreaWidgetContents_2.setWidget(self.host_node_label)

        self.tab_widget.setTabText(0, self.tr("Information"))
        self.tab_widget.setTabText(1, self.tr("Graphs"))
        self.tab_widget.setTabText(2, self.tr("Log"))
        self.tab_widget.setTabText(3, self.tr("Actions"))

        self.stop_push_button.setText(self.tr("Stop Node"))
        self.restart_push_button.setText(self.tr("Restart Node"))
        self.stop_push_button.setEnabled(False)
        self.restart_push_button.setEnabled(False)
        
        ### CARSON ADDED ###
        # set default values for throttle rate and window sliders
        self.throttle_rate_slider.setFocusPolicy(Qt.StrongFocus)
        self.throttle_rate_slider.setValue(5000) 
        self.throttle_window_slider.setFocusPolicy(Qt.StrongFocus)
        self.throttle_window_slider.setValue(500)
        
        # set up validator for throttle rate and window text fields 
        # only allows floating point numbers
        regex = QRegExp(r'[0-9]*\.?[0-9]+')
        validator = QRegExpValidator(regex)
        self.throttle_rate.setValidator(validator)
        self.throttle_window.setValidator(validator)
        
        # set up QButtonGroup for message/bandwidth throttle type radio buttons
        self.throttle_radio_group = QButtonGroup()
        self.throttle_radio_group.addButton(self.throttle_message_radio)
        self.throttle_radio_group.addButton(self.throttle_bandwidth_radio)
        self.throttle_radio_group.buttonClicked.connect(self.__on_type_button_clicked)
        
        ### ###
        
        self.selected_label.setText(self.tr("Selected") + ":")
        self.range_label.setText(self.tr("Range") + ":")
        
        self.log_tab_tree_view.setRootIsDecorated(False)
        self.log_tab_tree_view.setAlternatingRowColors(True)
        self.log_tab_tree_view.setSortingEnabled(True)
        self.log_tab_tree_view.sortByColumn(1, Qt.AscendingOrder)

        self.__current_range_combo_box_index = 0
        self.__current_selected_combo_box_index = 0

        self.set_selected_item(self.__selected_item)
        self.__model.layoutChanged.connect(self.update)

        self.__state = "ok"
        self.__previous_state = "ok"

        self.__selected_item_changed = True

        self.__deleted = False
        
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        self.__graph_layout = ResizeableGraphicsLayoutWidget(self.__on_graph_window_size_changed)
        self.graph_scroll_area.setWidget(self.__graph_layout)
        self.__plotable_items = None#self.__selected_item.get_plotable_items()
        self.__items_per_group = 1
        self.__expected_items_per_group = 1
        self.__number_of_groups = 1

        self.__update_graphs_lock = Lock()
        self.__first_update_pending = True

        self.__graph_dict = {}

        self.__plotted_curves = {}
        #self.create_graphs()

        self.__timer = Timer(Duration(secs=1.0), self.update_graphs)