def _refresh(self, pillow, path):
        if self._path is None:
            return
        try:
            # selection changed!
            if path == self._path + ".*":
                try:
                    idx = PathHelper.getValue(self._document.selection, path + '._selection') 
                    if self._delegate:
                        self._ignoreSelect = True
                        self._delegate.selectRow(idx)
                except: pass

            elif Viewer.matchPath(self._path, path, mode=Viewer.OUTER):
                value = None
                if self._document:
                    if self._isList:
                        value = self._document.get(self._path, asList=True, wrap=self._wrapInList)
                    else:
                        value = self._document.get(self._path, asDict=True)

                if value and self._credentials:
                    credential = self._credentials.getFlat(self._path)
                    if credential == None or 'view' in credential or self._path == '_id':
                        if self._delegate: self._delegate.dataCB(value)
                        if not self._resolved:  
                            if self._document.hasConflicts():
                                d = self._document.loadConflicts()
                                d.addCallback(self._conflictsArrived)
                            else:
                                self._noConflict()

                        if self._delegate and self._inserted != None:
                            self._delegate.editRow(self._inserted)
                else:
                    if self._delegate: self._delegate.dataCB(None)

                if self._document != None and self._document.selection != None:
                    # FIXME: Should we clear the selection here
                    # if "*" in self._path:
                    #     self._document.select(self._path, None)

                    sel = PathHelper.getValue(self._document.selection, self._path + '.*._selection')
                    if sel != None and self._delegate != None: self._delegate.selectRow(sel)

            elif Viewer.matchPath(self._path, path, mode=Viewer.INNER):
                if self._delegate: self._delegate.changedCB()

        except SelectionNotSpecified as e:
            self._delegate.dataCB(None)

        self._inserted = None
    def sub(self, key, path=None, dct=None):
        if dct == None: dct = {} 

        if isinstance(key, dict):
            for k,v in key.items():
                subpath = k
                if path != None: subpath = path + "." + k

                self.sub(v, subpath, dct)
        else:
            PathHelper.setValue(dct, path, PathHelper.getValue(self._data, path))

        return dct
    def select(self, idx):
        if self._ignoreSelect: 
            self._ignoreSelect = False
            return

        if self._document:
            try:
                currentIdx = PathHelper.getValue(self._document.selection, self._path + '.*._selection') 
                # already selected
                if currentIdx == idx: return 

            except: pass

        from documentChanger import DocumentChanger
        self._throw(DocumentChanger.In.Select, (self._path, idx))
Exemple #4
0
def replaceValue(dct, val):
    if isinstance(val, dict) and '_path' in dct:
        from wallaby.common.pathHelper import PathHelper
        val = PathHelper.getValue(val, dct['_path'])

    if val == None: 
        val = "-"

    if isinstance(val, (bool, int, float)):
        val = str(val)

    if val in dct:
        val = dct[val]
    elif "*" in dct:
        val = dct["*"].replace("*", val)

    return val
    def _fillComboBox(self, document):
        self._changed = False

        self._translate = {}
        self._translateReverse = {}
        self.clear()


        if self.source != None and "__DOC__" in self.source:
            if document is not None and self._subPath != None:
                from wallaby.common.pathHelper import PathHelper
                titles = []
                for dct in document:
                    titles.append(PathHelper.getValue(dct, self._subPath))
            else:
                titles = document
        else:
            path = self.sourcePath
            if path == None: path = 'titles'
            titles = document.get(path)

        found = False

        if titles:
            for i in range(len(titles)):
                value = titles[i]
                if isinstance(value, (list, tuple)):
                    displayValue, value = value
                else:
                    displayValue = value

                self._translate[displayValue] = value
                # if isinstance(value, (unicode, str)):
                self._translateReverse[unicode(value)] = displayValue

                self.insertItem(i, displayValue)
                if value == self._lastValue:
                    self.setCurrentIndex(i)
                    found = True

        if not found and self._lastValue != None and self.lineEdit() != None:
            self.setCurrentIndex(-1)
            self.lineEdit().setText(self._lastValue)

        self._changed = True
    def __translate(self, feathers, doc, path, value):
        if feathers != None:
            from wallaby.common.pathHelper import PathHelper
            import re
            if isinstance(feathers, (str, unicode)):
                if '%VALUE' in feathers:
                    reg = re.compile('(.*?)%VALUE:?(.*?)%(.*)', re.DOTALL)
                    match = reg.match(feathers)
                    if match and match.group(2):
                        try:
                            if match.group(1) or match.group(3):
                                if doc is not None:
                                    feathers = match.group(1) + unicode(doc.get(".".join( (path, match.group(2)) ))) + match.group(3)
                                else:
                                    feathers = match.group(1) + unicode(PathHelper.getValue(value, match.group(2))) + match.group(3)
                            else:
                                if doc is not None:
                                    feathers = doc.get(".".join( (path, match.group(2)) ))
                                else:
                                    feathers = PathHelper.getValue(value, match.group(2))
                        except:
                            feathers = None
            
                    else:
                        if match and (match.group(1) or match.group(3)):
                            feathers = match.group(1) + unicode(value) + match.group(3)
                        else:
                            feathers = value

                if '%path%' in feathers:
                    feathers = re.sub('%path%', path, feathers)

            if isinstance(feathers, dict):
                import copy
                feathers = copy.deepcopy(feathers)
                for k, v in feathers.items():
                    if isinstance(v, (str, unicode)) and '%VALUE' in v:
                        match = re.match('(.*?)%VALUE:?(.*?)%(.*)', v)

                        if match.group(2):
                            try:
                                if match.group(1) or match.group(3):
                                    if doc is not None:
                                        v = match.group(1) + unicode(doc.get(".".join( (path, match.group(2)) ))) + match.group(3)
                                    else:
                                        v = match.group(1) + unicode(PathHelper.getValue(value, match.group(2))) + match.group(3)
                                else:
                                    if doc is not None:
                                        v = doc.get(".".join( (path, match.group(2)) ))
                                    else:
                                        v = PathHelper.getValue(value, match.group(2))
                            except Exception as e:
                                v = None

                        else:
                            if match.group(1) or match.group(3):
                                v = match.group(1) + unicode(value) + match.group(3)
                            else:
                                v = value

                    if isinstance(v, (str, unicode)) and '%PATH%' in v:
                        v = re.sub('%PATH%', path, v)

                    feathers[k] = v
        return feathers 
 def merge(self, path, value):
     return PathHelper.setValue(self._data, path, value, merge=True)
 def set(self, path, value):
     return PathHelper.setValue(self._data, path, value)
 def get(self, path, **ka):
     return PathHelper.getValue(self._data, path, **ka)
    def data(self, index, role): 
        if not index.isValid(): 
            return None
        elif role != QtCore.Qt.EditRole and role != QtCore.Qt.DisplayRole and role != QtCore.Qt.SizeHintRole:  
            return None

        row = index.row()
        if self.rowCount(self._parent) <= row: return None

        col = index.column()
        if len(self._columns) <= col: return None
 

        if role == QtCore.Qt.SizeHintRole:
            if self._columns[col] in self._sizeHints and isinstance(self._sizeHints[self._columns[col]], dict):
                hint = self._sizeHints[self._columns[col]]
                w = self._minColumnWidth
                h = self._minRowHeight
                if 'width' in hint and hint['width'] is not None: w = int(hint['width'])
                if 'height' in hint and hint['height'] is not None: h = int(hint['height'])
                # print w, h, col
                return QtCore.QSize(w, h)
            else:
                size = QtCore.QSize(self._minColumnWidth, self._minRowHeight)

            # if isinstance(val, QtGui.QPixmap):
            #     size.setWidth(max(val.width()+1, size.width()))
            #     size.setHeight(max(val.height(), size.height()))
            return size

        key = self.getKey(row)

        path = self._columns[col]
        type = self._types[col]
        typeArg = self._typeArgs[col]

        pathes = []
        types = []
        typeArgs = []
        
        if path != None and '|' in path:
            pathes = path.split('|')

            if type != None and '|' in type:
                types = type.split('|')
            else:
                for p in pathes: types.append(type)

            if typeArg != None and '|' in typeArg:
                typeArgs = typeArg.split('|')
            else:
                for p in pathes: typeArgs.append(typeArg)

            type = types[-1]
            for i in range(len(types), len(pathes)):
                types.append(type)

            typeArg = typeArgs[-1]
            for i in range(len(typeArgs), len(pathes)):
                typeArgs.append(typeArg)
        else:
            pathes = [path] 
            types = [type]
            typeArgs = [typeArg]

        i = 0
        for i in range(len(pathes)):
            path = pathes[i]
            type = types[i]
            typeArg = typeArgs[i]

            if path == '*':
                if (self._isList and key < len(self._data)) or key in self._data:
                    val = self._data[key]
                else:
                    val = u""
            elif path == '__key__':
                val = key
            else:
                val = PathHelper.getValue(self._data[key], path)
                # print "get", key, self._data[key], self._columns[col], val

            if type == "imagelist":
                if not isinstance(val, list):
                    continue

                images = []

                for dct in val:
                    if isinstance(dct, (unicode, str)):
                        images.append(dct)
                    elif isinstance(dct, dict):
                        if typeArg in dct:
                            images.append(dct[typeArg])
                    elif isinstance(dct, list):
                        if typeArg != None and int(typeArg) < len(dct):
                            images.append(dct[int(typeArg)])

                if str(images) in self._imageCache:
                    return self._imageCache[str(images)]

                dList = []

                for img in images:
                    dList.append(self._peer.getImage(img))

                d = defer.DeferredList(dList)
                d.addCallback(partial(self._updateField, row, col, str(images)))
                return  [QtGui.QPixmap()]

            if type == "image":
                if val in self._imageCache:
                    val = self._imageCache[val]
                else:
                    if not self._peer.hasImage(val):
                        val = None
                        continue

                    d = self._peer.getImage(val)
                    d.addCallback(partial(self._updateField, row, col, val))
                    val = QtGui.QPixmap()
            else:
                val = FXUI.renderType(val, type, typeArg, role == QtCore.Qt.EditRole) 

            if val != None:
                return val
        return val
    def setData(self, index, value, role):
        if role == QtCore.Qt.EditRole:
            col = index.column()
            row = index.row()

            if self.rowCount(self._parent) <= row: return False

            key = self.getKey(row)

            oldVal = None 

            if self._columns[col] == '*':
                if (self._isList and key < len(self._data)) or key in self._data:
                    oldVal = self._data[key]
                else:
                    val = u""
            elif self._columns[col] == '__key__':
                oldVal = key
            else:
                if self._isList:
                    if key < len(self._data): oldVal = PathHelper.getValue(self._data[key], self._columns[col])
                else:
                    if key in self._data: oldVal = PathHelper.getValue(self._data[key], self._columns[col])

            vtype = self._types[col]

            if vtype not in ("autoedit", "dictedit", "listedit") and self._columns[col] == "*" and isinstance(oldVal, (dict, list, tuple)):
                return False

            if vtype == "autoedit":
                if isinstance(oldVal, (float, int)):
                    vtype = "doubleedit"
                elif isinstance(oldVal, bool):
                    vtype = "booledit"
                else:
                    if isinstance(value, (str, unicode)):
                        import re
                        if value == "true" or value == "false":
                            vtype = "booledit"
                        elif re.match(r"^\d+\.?\d*$", value):
                            vtype = "doubleedit"
                        elif re.match(r"^\[", value):
                            vtype = "stringedit"
                            if oldVal is None or not isinstance(oldVal, list): oldVal = []
                        elif re.match(r"^\{", value):
                            vtype = "stringedit"
                            if oldVal is None or not isinstance(oldVal, dict): oldVal = []
                        else:
                            vtype = "stringedit"
                    else:
                        vtype = "stringedit"
            elif vtype == "dictedit":
                vtype = "stringedit"
                if oldVal is None or not isinstance(oldVal, dict): oldVal = {}
            elif vtype == "listedit":
                vtype = "stringedit"
                if oldVal is None or not isinstance(oldVal, list): oldVal = []

            if vtype == "stringedit":
                val = unicode(value)

                if isinstance(oldVal, (list, dict)):
                    import json
                    try:
                        value = json.loads(u'{"value":' + val + u'}')
                        val = value['value']

                    except Exception as e:
                        if isinstance(oldVal, list): val = []
                        elif isinstance(oldVal, dict): val = {}

                if self._columns[col] == '*':
                    self._data[key] = val
                elif not self._isList and self._columns[col] == '__key__':
                    if val != key:
                        if key in self._data:
                            self._data[val] = self._data[key]
                            del self._data[key]

                        del self._rows[self._keys[row]]
                        self._keys[row] = val
                        self._rows[val] = row
                        self._peer.select(val)
                else:
                    if self._data[key] == None or not isinstance(self._data[key], dict): 
                        self._data[key] = {}

                    PathHelper.setValue(self._data[key], self._columns[col], val)

            elif vtype in ("doubleedit", "numberedit", "currencyedit"):
                val = 0
                if isinstance(value, (unicode, str)):
                    try:
                        if re.match(r"^\d+$", value):
                            val = int(value)
                        else:
                            val = float(value)
                    except: pass
                elif isinstance(value, (float, int, bool)):
                    val = value

                if self._columns[col] == '*':
                    self._data[key] = val
                elif not self._isList and self._columns[col] == '__key__':
                    self._data[val] = self._data[key]
                    del self._data[key]
                    del self._rows[self._keys[row]]
                    self._keys[row] = val
                    self._rows[val] = row
                    self._peer.select(val)
                else:
                    PathHelper.setValue(self._data[key], self._columns[col], val)
            elif vtype in ("booledit"):
                val = False
                if isinstance(value, (unicode, str)):
                    try:
                        if value == "true": val = True
                        elif value == "false": val = False
                        else: val = bool(value)
                    except: pass
                elif isinstance(value, (bool)):
                    val = value

                if self._columns[col] == '*':
                    self._data[key] = val
                elif not self._isList and self._columns[col] == '__key__':
                    self._data[val] = self._data[key]
                    del self._data[key]
                    del self._rows[self._keys[row]]
                    self._keys[row] = val
                    self._rows[val] = row
                    self._peer.select(val)
                else:
                    PathHelper.setValue(self._data[key], self._columns[col], val)
 
            if vtype in ("stringedit", "doubleedit", "numberedit", "currencyedit", "booledit"):
                self.dataChanged.emit(index, index)
                self._peer.fieldChanged(key, self._columns[col])
                return True

        return False
 def select(self, path, index):
     PathHelper.setValue(self.selection, path + "._selection", index)
 def overwrite(self, path, value):
     return PathHelper.setValue(self._data, path, value, self.selection, recurse=True)
 def getSelection(self, path):
     return PathHelper.getSelection(path, self.selection)
 def get(self, path, **kw):
     return PathHelper.getValue(self._data, path, self.selection, **kw)