def exportTrlSubtree(self, fileRef, nodeList, addBranches=True): """Write subtree TRL file starting form item""" lines = [u'<?xml version="1.0" encoding="utf-8" ?>'] if self.xlstLink: lines.append(u'<?%s?>' % self.xlstLink) if not addBranches: newList = [] for item in nodeList: # replace items with childless items newItem = TreeItem(item.parent, item.formatName) newItem.data = item.data newList.append(newItem) nodeList = newList if len(nodeList) > 1: format = nodeformat.NodeFormat(TreeFormats.rootFormatDefault, {}, TreeFormats.fieldDefault) self.treeFormats.addIfMissing(format) item = TreeItem(None, format.name) item.data[TreeFormats.fieldDefault] = TreeDoc.rootTitleDefault for child in nodeList: item.childList.append(child) child.parent = item else: item = nodeList[0] lines.extend(item.branchXml([], True)) try: f = self.getWriteFileObj(fileRef, self.compressFile) f.writelines([(line + '\n').encode('utf-8') for line in lines]) except IOError: print 'Error - could not write file' self.treeFormats.removeQuiet(TreeDoc.copyFormat) raise f.close() self.treeFormats.removeQuiet(TreeDoc.copyFormat)
def readLines(self, fileRef, errors='strict'): """Import plain text, node per line""" try: f = self.getEncodedFileObj(fileRef, globalref.localTextEncoding, errors) filePath = unicode(f.name, sys.getfilesystemencoding()) textList = f.readlines() except UnicodeError: print 'Warning - bad unicode characters were replaced' if errors == 'strict': self.readLines(fileRef, 'replace') else: f.close() return f.close() self.treeFormats = TreeFormats({}, True) # set defaults ROOT & DEFAULT newRoot = TreeItem(None, TreeFormats.rootFormatDefault) defaultFormat = self.treeFormats[TreeFormats.formatDefault] defaultFormat.fieldList = [] defaultFormat.lineList = [] defaultFormat.addTableFields([TreeFormats.textFieldName]) newRoot.setTitle(TreeDoc.rootTitleDefault) for line in textList: line = line.strip() if line: newItem = TreeItem(newRoot, TreeFormats.formatDefault) newRoot.childList.append(newItem) newItem.data[TreeFormats.textFieldName] = line self.root = newRoot self.fileName = filePath
def startElement(self, name, attrs): """Called by the reader at the open tag of each element""" if name == u'folder' or name == u'xbel': newItem = TreeItem(self.currentItem, self.folderFormat.name) if self.currentItem: self.currentItem.childList.append(newItem) else: self.rootItem = newItem if attrs.get(u'folded', '') == 'no': newItem.open = True self.currentItem = newItem elif name == u'bookmark': newItem = TreeItem(self.currentItem, self.bookmarkFormat.name) if self.currentItem: self.currentItem.childList.append(newItem) else: raise xml.sax.SAXException, 'No valid parent folder' newItem.data[TreeFormats.linkFieldName] = attrs.get(u'href', '') self.currentItem = newItem elif name == u'title': self.text = '' elif name == u'separator': newItem = TreeItem(self.currentItem, self.separatorFormat.name) if self.currentItem: self.currentItem.childList.append(newItem) else: raise xml.sax.SAXException, 'No valid parent folder' self.currentItem = newItem else: # unsupported tags pass
def handle_starttag(self, tag, attrs): """Called by the reader at each open tag""" if tag == 'dt' or tag == 'h1': # start any entry self.text = '' elif tag == 'dl': # start indent self.currentParent = self.currentItem self.currentItem = None elif tag == 'h3': # start folder if not self.currentParent: raise HtmlParseError, 'No valid parent folder' self.currentItem = TreeItem(self.currentParent, self.folderFormat.name) self.currentParent.childList.append(self.currentItem) elif tag == 'a': # start link if not self.currentParent: raise HtmlParseError, 'No valid parent folder' self.currentItem = TreeItem(self.currentParent, self.bookmarkFormat.name) self.currentParent.childList.append(self.currentItem) for name, value in attrs: if name == 'href': self.currentItem.data[TreeFormats.linkFieldName] = value elif tag == 'hr': # separator if not self.currentParent: raise HtmlParseError, 'No valid parent folder' item = TreeItem(self.currentParent, self.separatorFormat.name) self.currentParent.childList.append(item) self.currentItem = None
def readPara(self, fileRef, errors='strict'): """Import plain text, blank line delimitted""" try: f = self.getEncodedFileObj(fileRef, globalref.localTextEncoding, errors) filePath = unicode(f.name, sys.getfilesystemencoding()) fullText = f.read().replace('\r', '') except UnicodeError: print 'Warning - bad unicode characters were replaced' if errors == 'strict': self.readPara(fileRef, 'replace') else: f.close() return textList = fullText.split('\n\n') f.close() self.treeFormats = TreeFormats({}, True) # set defaults ROOT & DEFAULT newRoot = TreeItem(None, TreeFormats.rootFormatDefault) defaultFormat = self.treeFormats[TreeFormats.formatDefault] defaultFormat.fieldList = [] defaultFormat.lineList = [] defaultFormat.iconName = 'doc' defaultFormat.addTableFields([TreeFormats.textFieldName]) defaultFormat.fieldList[0].numLines = globalref.options.\ intData('MaxEditLines', 1, optiondefaults.maxNumLines) newRoot.setTitle(TreeDoc.rootTitleDefault) for line in textList: line = line.strip() if line: newItem = TreeItem(newRoot, TreeFormats.formatDefault) newRoot.childList.append(newItem) newItem.data[TreeFormats.textFieldName] = line self.root = newRoot self.fileName = filePath
def __set_card_treeview_status(self): card_list = [] cards = pypulse.PULSE.get_cards() for idx in cards: active_profile = cards[idx]['active_profile'] if active_profile: if active_profile['n_sinks'] > 1: io_num = _("%d Outputs") % active_profile['n_sinks'] else: io_num = _("%d Output") % active_profile['n_sinks'] if active_profile['n_sources'] > 1: io_num += " / " + _("%d Inputs") % active_profile['n_sources'] else: io_num += " / " + _("%d Input") % active_profile['n_sources'] if 'device.description' in cards[idx]['proplist']: description = cards[idx]['proplist']['device.description'].strip('\x00') else: description = "" card_info = "%s(%s)[%s]" % (description, io_num, active_profile['description']) else: if 'device.description' in cards[idx]['proplist']: card_info = cards[idx]['proplist']['device.description'] else: card_info = " " card_list.append(TreeItem(self.image_widgets["device"], card_info, cards[idx]['name'], idx)) self.view_widgets["ad_hardware"].add_items(card_list, clear_first=True) if card_list: self.view_widgets["ad_hardware"].set_select_rows([0])
def exportDirPage(self, dirName, nodeList): """Write tree to nested direct struct with html page for each node""" oldDir = os.getcwd() os.chdir(dirName.encode(sys.getfilesystemencoding())) cssLines = [ '#sidebar {', 'width: 16em;', 'float: left;', 'clear: left;', 'border-right: 1px solid black;', 'margin-right: 1em;', '}' ] try: f = codecs.open('default.css', 'w', 'utf-8') f.writelines([(line + '\n').encode('utf-8') for line in cssLines]) except (IOError, UnicodeError): print 'Error - could not write file to default.css' raise IOError(_('Error - cannot write file to %s') % 'default.css') f.close() if len(nodeList) > 1: self.treeFormats.addIfMissing(TreeDoc.copyFormat) item = TreeItem(None, TreeDoc.copyFormat.name) item.data[TreeFormats.fieldDefault] = TreeDoc.rootTitleDefault for child in nodeList: item.childList.append(child) child.parent = item else: item = nodeList[0] linkDict = {} item.createDirPageLinkDict(linkDict, os.getcwd()) item.exportDirPage(linkDict) self.treeFormats.removeQuiet(TreeDoc.copyFormat) os.chdir(oldDir)
def readTabbed(self, fileRef, errors='strict'): """Import tabbed data into a flat tree - raise exception on failure""" try: f = self.getEncodedFileObj(fileRef, globalref.localTextEncoding, errors) filePath = unicode(f.name, sys.getfilesystemencoding()) textList = f.readlines() except UnicodeError: print 'Warning - bad unicode characters were replaced' if errors == 'strict': self.readTabbed(fileRef, 'replace') else: f.close() return f.close() bufList = [(text.count('\t', 0, len(text) - len(text.lstrip())), text.strip()) for text in textList if text.strip()] if bufList: buf = bufList.pop(0) if buf[0] == 0: # set default formats ROOT & DEFAULT self.treeFormats = TreeFormats({}, True) newRoot = TreeItem(None, TreeFormats.rootFormatDefault) newRoot.setTitle(buf[1]) if newRoot.loadTabbedChildren(bufList): self.root = newRoot self.fileName = filePath return raise ReadFileError(_('Error in tabbed list'))
def readOdf(self, fileRef): """Read an Open Document Format (ODF) file""" self.treeFormats = TreeFormats(None, True) rootItem = TreeItem(None, TreeFormats.rootFormatDefault, TreeDoc.rootTitleDefault) defaultFormat = self.treeFormats[TreeFormats.formatDefault] defaultFormat.addNewField(TreeFormats.textFieldName, { u'html': 'n', u'lines': '6' }) defaultFormat.changeOutputLines([ u'<b>{*%s*}</b>' % TreeFormats.fieldDefault, u'{*%s*}' % TreeFormats.textFieldName ]) try: f = self.getReadFileObj(fileRef) filePath = unicode(f.name, sys.getfilesystemencoding()) zip = zipfile.ZipFile(f, 'r') text = zip.read('content.xml') handler = treexmlparse.OdfSaxHandler(rootItem, defaultFormat) xml.sax.parseString(text, handler) except (zipfile.BadZipfile, KeyError): f.close() raise ReadFileError(_('Could not unzip ODF file')) except UnicodeError: f.close() raise ReadFileError(_('Problem with Unicode characters in file')) except xml.sax.SAXException: f.close() raise ReadFileError(_('Could not open corrupt ODF file')) f.close() self.root = rootItem self.fileName = filePath
def __init__(self, headers, data, parent=None) -> None: super(TreeModel, self).__init__(parent) rootData = [] for header in headers: rootData.append(header) self._rootItem = TreeItem(rootData)
def __init__(self, headers, data, tablemodel, parent=None): super(TreeModel, self).__init__(parent) rootData = [header for header in headers] self.rootItem = TreeItem(rootData) self.treeDict = data self.tablemodel = tablemodel self.setupModelData(data, self.rootItem) self.examingParents = False self.examiningChildren = False
def __init__(self, folderFormat, bookmarkFormat, separatorFormat): HTMLParser.HTMLParser.__init__(self) self.folderFormat = folderFormat self.bookmarkFormat = bookmarkFormat self.separatorFormat = separatorFormat self.rootItem = TreeItem(None, self.folderFormat.name) self.rootItem.data[TreeFormats.fieldDefault] = _('Bookmarks') self.currentItem = self.rootItem self.currentParent = None self.text = ''
def readTreepad(self, fileRef, errors='strict'): """Read Treepad text-node file""" try: f = self.getEncodedFileObj(fileRef, globalref.localTextEncoding, errors) filePath = unicode(f.name, sys.getfilesystemencoding()) textList = f.read().split('<end node> 5P9i0s8y19Z') f.close() except UnicodeError: # error common - broken unicode on windows print 'Warning - bad unicode characters were replaced' if errors == 'strict': self.readTreepad(fileRef, 'replace') else: f.close() return self.treeFormats = TreeFormats() format = nodeformat.NodeFormat(TreeFormats.formatDefault) titleFieldName = _('Title', 'title field name') format.addNewField(titleFieldName) format.addLine(u'{*%s*}' % titleFieldName) numLines = globalref.options.intData('MaxEditLines', 1, optiondefaults.maxNumLines) format.addNewField(TreeFormats.textFieldName, {'lines': repr(numLines)}) format.addLine(u'{*%s*}' % TreeFormats.textFieldName) self.treeFormats[format.name] = format itemList = [] for text in textList: text = text.strip() if text: try: text = text.split('<node>', 1)[1].lstrip() lines = text.split('\n') title = lines[0] level = int(lines[1]) lines = lines[2:] except (ValueError, IndexError): print 'Error - bad file format in %s' % \ filePath.encode(globalref.localTextEncoding) raise ReadFileError(_('Bad file format in %s') % filePath) item = TreeItem(None, format.name) item.data[titleFieldName] = title item.data[TreeFormats.textFieldName] = '\n'.join(lines) item.level = level itemList.append(item) self.root = itemList[0] parentList = [] for item in itemList: if item.level != 0: parentList = parentList[:item.level] item.parent = parentList[-1] parentList[-1].childList.append(item) parentList.append(item) self.root = itemList[0] self.fileName = filePath
def __init__(self, filePath=None, setNewDefaults=False, importType=None): """Open filePath (can also be file ref) if given, setNewDefaults uses user defaults for compression & encryption, importType gives an import method to read the file""" globalref.docRef = self self.root = None self.treeFormats = TreeFormats() self.fileInfoItem = TreeItem(None, nodeformat.FileInfoFormat.name) self.fileInfoFormat = None TreeDoc.copyFormat = nodeformat.NodeFormat('_DUMMY__ROOT_', {}, TreeFormats.fieldDefault) self.undoStore = undo.UndoRedoStore() self.redoStore = undo.UndoRedoStore() self.sortFields = [''] self.fileName = '' self.spaceBetween = True self.lineBreaks = True self.formHtml = True self.childFieldSep = TreeDoc.childFieldSepDflt self.spellChkLang = '' self.xlstLink = '' self.xslCssLink = '' self.tlVersion = __version__ self.fileInfoFormat = nodeformat.FileInfoFormat() if filePath: if importType: getattr(self, importType)(filePath) else: self.readFile(filePath) else: self.treeFormats = TreeFormats({}, True) self.root = TreeItem(None, TreeFormats.rootFormatDefault) self.root.setTitle(TreeDoc.rootTitleDefault) self.modified = False if setNewDefaults or not hasattr(self, 'compressFile'): self.compressFile = globalref.options.boolData('CompressNewFiles') self.encryptFile = globalref.options.boolData('EncryptNewFiles') elif not hasattr(self, 'encryptFile'): self.encryptFile = False self.selection = treeselection.TreeSelection([self.root]) self.fileInfoFormat.translateFields() self.fileInfoFormat.updateFileInfo()
def readTable(self, fileRef, errors='strict'): """Import table data into a flat tree - raise exception on failure""" try: f = self.getEncodedFileObj(fileRef, globalref.localTextEncoding, errors) filePath = unicode(f.name, sys.getfilesystemencoding()) textList = f.readlines() except UnicodeError: print 'Warning - bad unicode characters were replaced' if errors == 'strict': self.readTable(fileRef, 'replace') else: f.close() return f.close() self.treeFormats = TreeFormats({}, True) # set defaults ROOT & DEFAULT newRoot = TreeItem(None, TreeFormats.rootFormatDefault) defaultFormat = self.treeFormats[TreeFormats.formatDefault] defaultFormat.fieldList = [] defaultFormat.lineList = [] defaultFormat.addTableFields(textList.pop(0).strip().split('\t')) newRoot.setTitle(TreeDoc.rootTitleDefault) for line in textList: newItem = TreeItem(newRoot, TreeFormats.formatDefault) newRoot.childList.append(newItem) lineList = line.strip().split('\t') try: for num in range(len(lineList)): newItem.data[self.treeFormats[TreeFormats.formatDefault]. fieldList[num].name] = lineList[num].strip() except IndexError: print 'Too few headings to read data as a table' raise ReadFileError( _('Too few headings to read data as table')) self.root = newRoot self.fileName = filePath
def startElement(self, name, attrs): """Called by the reader at the open tag of each element""" format = self.formats.get(name, None) if not format: format = nodeformat.NodeFormat(name) self.formats[name] = format newItem = TreeItem(self.currentItem, name) if self.currentItem: self.currentItem.childList.append(newItem) elif self.rootItem: raise xml.sax.SAXException, 'Invalid XML file' else: self.rootItem = newItem self.currentItem = newItem for key in attrs.keys(): format.addFieldIfNew(key) newItem.data[key] = attrs[key]
def startElement(self, name, attrs): """Called by the reader at the open tag of each element""" if attrs.get(u'item', ''): # reading TreeItem or bare format format = self.formats.get(name, None) if not format: format = nodeformat.NodeFormat(name, attrs) self.formats[name] = format if attrs.get(u'item', '') == 'y': # reading TreeItem newItem = TreeItem(self.currentItem, name) if self.currentItem: self.currentItem.childList.append(newItem) else: self.rootItem = newItem if attrs.get(u'nospace', '').startswith('y'): self.docRef.spaceBetween = False if attrs.get(u'nobreaks', '').startswith('y'): self.docRef.lineBreaks = False if attrs.get(u'nohtml', '').startswith('y'): self.docRef.formHtml = False if attrs.get(u'childsep', ''): self.docRef.childFieldSep = attrs.get(u'childsep', '') self.docRef.spellChkLang = attrs.get(u'spellchk', '') self.docRef.xslCssLink = attrs.get(u'xslcss', '') self.docRef.tlVersion = attrs.get(u'tlversion', '') self.currentItem = newItem else: # reading bare format self.bareFormat = format else: # reading data self.text = '' self.dataEntry = name if not self.currentItem: raise xml.sax.SAXException, 'No valid item' currentFormat = self.bareFormat if not currentFormat: try: currentFormat = self.formats[self.currentItem.formatName] except KeyError: raise xml.sax.SAXException, 'Invalid node type' if name not in currentFormat.fieldNames( ): # add new field to format try: currentFormat.addNewField(name, attrs) except (NameError, KeyError): raise xml.sax.SAXException, 'Invalid field type'
def __set_input_treeview_status(self): current_source = pypulse.get_fallback_source_index() sources = pypulse.PULSE.get_input_devices() input_list = [] i = 0 selected_row = -1 for idx in sources: if current_source is not None and current_source == idx: selected_row = i if 'device.description' in sources[idx]['proplist']: description = sources[idx]['proplist']['device.description'].strip('\x00') else: description = "" input_list.append(TreeItem(self.image_widgets["device"], description, sources[idx]['name'], idx)) i += 1 self.view_widgets["ad_input"].add_items(input_list, clear_first=True) if not (selected_row < 0): self.view_widgets["ad_input"].set_select_rows([selected_row])
def exportDirTable(self, dirName, nodeList, addHeader=False): """Write tree to nested directory struct with html tables""" oldDir = os.getcwd() os.chdir(dirName.encode(sys.getfilesystemencoding())) if addHeader: header = self.fileInfoFormat.getHeaderFooter(True) footer = self.fileInfoFormat.getHeaderFooter(False) else: header = footer = '' if len(nodeList) > 1: self.treeFormats.addIfMissing(TreeDoc.copyFormat) item = TreeItem(None, TreeDoc.copyFormat.name) item.data[TreeFormats.fieldDefault] = TreeDoc.rootTitleDefault for child in nodeList: item.childList.append(child) child.parent = item else: item = nodeList[0] linkDict = {} item.createDirTableLinkDict(linkDict, os.getcwd()) item.exportDirTable(linkDict, None, header, footer) self.treeFormats.removeQuiet(TreeDoc.copyFormat) os.chdir(oldDir)
def setupModelData(self, lines, parent): parents = [] indentations = [] parents.append(parent) indentations.append(0) number = 0 while number < len(lines): position = 0 while position < len(lines[number]): if lines[number][position] != ' ': break position = position + 1 lineData = lines[number][position:].strip() if lineData: # Read the column data from the rest of the line. columnStrings = [x for x in lineData.split('\t') if x] columnData = [None] * len(columnStrings) for i, columnString in enumerate(columnStrings): columnData[i] = columnString if position > indentations[-1]: # The last child of the current parent is now the new parent # unless the current parent has no children. if parents[-1].childCount() > 0: parents.append(parents[-1].child(parents[-1].childCount() - 1)) indentations.append(position) else: while position < indentations[-1] and len(parents) > 0: parents.pop(-1) indentations.pop(-1) # Append a new item to the current parent's list of children. parents[-1].appendChild(TreeItem(columnData, parents[-1])) number = number + 1
def __init__(self, data, parent=None): super().__init__(parent) self.rootItem = TreeItem([self.tr('title'), self.tr('summary')]) self.setupModelData(data.split('\n'), self.rootItem)
def addItem(self, level): """Add a child of the current item""" item = TreeItem(self.currentItem, self.defaultFormat.name) self.currentItem.childList.append(item) self.currentItem = item self.currentLevel = level