示例#1
0
def formatPath(formatString, path="", **kwargs):
    """
    Resolve the given string with the given path and kwargs.

    Example:
        print formatPath("{dirname}/meta.json", path="C:/hello/world.json")
        # "C:/hello/meta.json"

    :type formatString: str
    :type path: str
    :type kwargs: dict
    :rtype: str
    """
    logger.debug("Format String: %s", formatString)

    dirname, name, extension = splitPath(path)

    encoding = locale.getpreferredencoding()

    # Environment variables return raw strings so we need to convert them to
    # unicode using the preferred system encoding

    temp = tempfile.gettempdir()
    if temp:

        temp = six.u(temp, encoding)

    username = user()
    if username:
        username = six.u(username, encoding)

    local = os.getenv('APPDATA') or os.getenv('HOME')
    if local:
        local = six.u(local, encoding)

    kwargs.update(os.environ)

    labels = {
        "name": name,
        "path": path,
        "root": path,  # legacy
        "user": username,
        "temp": temp,
        "home": local,  # legacy
        "local": local,
        "dirname": dirname,
        "extension": extension,
    }

    kwargs.update(labels)

    resolvedString = six.u(formatString).format(**kwargs)

    logger.debug("Resolved String: %s", resolvedString)

    return normPath(resolvedString)
示例#2
0
    def showMessage(self, message, icon, msecs=None, blocking=False):
        """
        Set the given text to be displayed in the status widget.
        
        :type message: str
        :type icon: icon
        :type msecs: int
        
        :rtype: None 
        """
        msecs = msecs or self.DEFAULT_DISPLAY_TIME

        self._blocking = blocking

        if icon:
            self._button.setIcon(icon)
            self._button.show()
        else:
            self._button.hide()

        if message:
            self._label.setText(six.u(message))
            self._timer.stop()
            self._timer.start(msecs)
        else:
            self.reset()

        self.update()
示例#3
0
 def value(self):
     """
     Get the value of the combobox.
     
     :rtype: unicode 
     """
     return six.u(self.widget().currentText())
示例#4
0
 def value(self):
     """
     Get the text value of the text edit.
     
     :rtype: unicode 
     """
     return six.u(self.widget().toPlainText())
示例#5
0
 def value(self):
     """
     Get the value of the widget.
     
     :rtype: unicode 
     """
     return six.u(self.widget().text())
示例#6
0
 def __init__(self, msg):
     """
     :type: str or unicode 
     """
     msg = six.u(msg)
     super(PathError, self).__init__(msg)
     self._msg = msg
示例#7
0
 def value(self):
     """
     Get the value of the label.
     
     :rtype: str 
     """
     return six.u(self.widget().text())
示例#8
0
 def setValue(self, value):
     """
     Set the value of the label.
     
     :type value: str 
     """
     self.widget().setText(six.u(value))
     super(LabelFieldWidget, self).setValue(value)
示例#9
0
 def run(self):
     """The starting point for the thread."""
     try:
         if self._path:
             image = QtGui.QImage(six.u(self._path))
             self.signals.triggered.emit(image)
     except Exception as error:
         logger.exception("Cannot load thumbnail image.")
示例#10
0
    def sortText(self, label):
        """
        Return the sort data for the given column.

        :type label: str
        :rtype: str
        """
        return six.u(self.itemData().get(label, ''))
示例#11
0
 def __unicode__(self):
     """
     Return the decoded message using 'unicode_escape'
     
     :rtype: unicode 
     """
     msg = six.u(self._msg).decode('unicode_escape')
     return msg
示例#12
0
 def setText(self, text):
     """
     Set the text message to be displayed.
     
     :type text: str
     :rtype: None 
     """
     text = six.u(text)
     self._message.setText(text)
示例#13
0
def normPath(path):
    """
    Return a normalized path containing only forward slashes.
    
    :type path: str
    :rtype: unicode 
    """
    path = path.replace("\\", "/")
    path = six.u(path)
    return path.rstrip("/")
示例#14
0
    def searchText(self):
        """
        Return the search string used for finding the item.

        :rtype: str
        """
        if not self._searchText:
            self._searchText = six.u(self._data)

        return self._searchText
示例#15
0
    def createItems(self, data, split=None):
        """ 
        Create the items from the given data dict

        :type data: dict
        :type split: str or None

        :rtype: None
        """
        split = split or DEFAULT_SEPARATOR

        self._index = {}

        for key in data:

            root = split.join([key])

            item = None

            if self.isRootVisible():

                text = key.split(split)
                if text:
                    text = text[-1]
                else:
                    text = key

                item = SidebarWidgetItem(self)
                item.setText(0, six.u(text))
                item.setPath(root)
                item.setExpanded(True)

                self._index[root] = item

            def _recursive(parent, children, split=None, root=""):
                for text, val in sorted(children.items()):

                    if not parent:
                        parent = self

                    path = split.join([root, text])
                    path = path.replace("//", "/")

                    child = SidebarWidgetItem(parent)
                    child.setText(0, six.u(text))
                    child.setPath(path)

                    self._index[path] = child

                    _recursive(child, val, split=split, root=path)

            _recursive(item, data[key], split=split, root=root)

        self.update()
        self.refreshFilter()
示例#16
0
            def _recursive(parent, children, split=None, root=""):
                for text, val in sorted(children.items()):

                    if not parent:
                        parent = self

                    path = split.join([root, text])
                    path = path.replace("//", "/")

                    child = SidebarWidgetItem(parent)
                    child.setText(0, six.u(text))
                    child.setPath(path)

                    self._index[path] = child

                    _recursive(child, val, split=split, root=path)
示例#17
0
def movePath(src, dst):
    """
    Move the given source path to the given destination path.

    :type src: str
    :type dst: str
    :rtype: str
    """
    src = six.u(src)
    dirname, name, extension = splitPath(src)

    if not os.path.exists(src):
        raise MovePathError(u'No such file or directory: {0}'.format(src))

    if os.path.isdir(src):
        dst = u'{0}/{1}{2}'.format(dst, name, extension)
        dst = generateUniquePath(dst)

    shutil.move(src, dst)
    return dst
示例#18
0
    def match(data, queries):
        """
        Match the given data with the given queries.
        
        Examples:
            
            queries = [
                {
                    'operator': 'or',
                    'filters': [
                        ('folder', 'is' '/library/proj/test'),
                        ('folder', 'startswith', '/library/proj/test'),
                    ]
                },
                {
                    'operator': 'and',
                    'filters': [
                        ('path', 'contains' 'test'),
                        ('path', 'contains', 'run'),
                    ]
                }
            ]
            
            print(library.find(queries))
        """
        matches = []

        for query in queries:

            filters = query.get('filters')
            operator = query.get('operator', 'and')

            if not filters:
                continue

            match = False

            for key, cond, value in filters:

                if key == '*':
                    itemValue = six.u(data)
                else:
                    itemValue = data.get(key)

                if isinstance(value, six.string_types):
                    value = value.lower()

                if isinstance(itemValue, six.string_types):
                    itemValue = itemValue.lower()

                if not itemValue:
                    match = False

                elif cond == 'contains':
                    match = value in itemValue

                elif cond == 'not_contains':
                    match = value not in itemValue

                elif cond == 'is':
                    match = value == itemValue

                elif cond == 'not':
                    match = value != itemValue

                elif cond == 'startswith':
                    match = itemValue.startswith(value)

                if operator == 'or' and match:
                    break

                if operator == 'and' and not match:
                    break

            matches.append(match)

        return all(matches)