Ejemplo n.º 1
0
    def __locate_code_in_project(self, queue_folders, nproject):
        file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable
        dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable
        while not self._cancel and not queue_folders.empty():
            current_dir = QDir(queue_folders.get())
            #Skip not readable dirs!
            if not current_dir.isReadable():
                continue

            #Collect all sub dirs!
            current_sub_dirs = current_dir.entryInfoList(dir_filter)
            for one_dir in current_sub_dirs:
                queue_folders.put(one_dir.absoluteFilePath())

            #all files in sub_dir first apply the filters
            current_files = current_dir.entryInfoList(
                ['*{0}'.format(x) for x in nproject.extensions], file_filter)
            #process all files in current dir!
            for one_file in current_files:
                try:
                    self._grep_file_locate(one_file.absoluteFilePath(),
                                           one_file.fileName())
                except Exception as reason:
                    logger.error('__locate_code_in_project, error: %r' %
                                 reason)
                    logger.error('__locate_code_in_project fail for file: %r' %
                                 one_file.absoluteFilePath())
Ejemplo n.º 2
0
    def locate_code(self):
        explorerContainer = explorer_container.ExplorerContainer()
        projects_obj = explorerContainer.get_opened_projects()
        projects = [p.path for p in projects_obj]
        if not projects:
            return
        queue = Queue.Queue()
        for project in projects:
            queue.put(project)
        file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable
        dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable
        while not self._cancel and not queue.empty():
            current_dir = QDir(queue.get())
            #Skip not readable dirs!
            if not current_dir.isReadable():
                continue

            #Collect all sub dirs!
            current_sub_dirs = current_dir.entryInfoList(dir_filter)
            for one_dir in current_sub_dirs:
                queue.put(one_dir.absoluteFilePath())

            current_sub_dirs = current_dir.entryInfoList(dir_filter)
            #all files in sub_dir first apply the filters
            current_files = current_dir.entryInfoList(
                ['*{0}'.format(x) for x in settings.SUPPORTED_EXTENSIONS],
                file_filter)
            #process all files in current dir!
            for one_file in current_files:
                self._grep_file_locate(unicode(one_file.absoluteFilePath()),
                    one_file.fileName())
        self.dirty = True
        self.get_locations()
Ejemplo n.º 3
0
    def locate_code(self):
        explorerContainer = explorer_container.ExplorerContainer()
        projects_obj = explorerContainer.get_opened_projects()
        projects = [p.path for p in projects_obj]
        if not projects:
            return
        queue = Queue.Queue()
        for project in projects:
            queue.put(project)
        file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable
        dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable
        while not self._cancel and not queue.empty():
            current_dir = QDir(queue.get())
            #Skip not readable dirs!
            if not current_dir.isReadable():
                continue

            #Collect all sub dirs!
            current_sub_dirs = current_dir.entryInfoList(dir_filter)
            for one_dir in current_sub_dirs:
                queue.put(one_dir.absoluteFilePath())

            current_sub_dirs = current_dir.entryInfoList(dir_filter)
            #all files in sub_dir first apply the filters
            current_files = current_dir.entryInfoList(
                ['*{0}'.format(x) for x in settings.SUPPORTED_EXTENSIONS],
                file_filter)
            #process all files in current dir!
            for one_file in current_files:
                self._grep_file_locate(unicode(one_file.absoluteFilePath()),
                                       one_file.fileName())
        self.dirty = True
        self.get_locations()
Ejemplo n.º 4
0
    def __locate_code_in_project(self, queue_folders, nproject):
        file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable
        dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable
        while not self._cancel and not queue_folders.empty():
            current_dir = QDir(queue_folders.get())
            #Skip not readable dirs!
            if not current_dir.isReadable():
                continue

            #Collect all sub dirs!
            current_sub_dirs = current_dir.entryInfoList(dir_filter)
            for one_dir in current_sub_dirs:
                queue_folders.put(one_dir.absoluteFilePath())

            #all files in sub_dir first apply the filters
            current_files = current_dir.entryInfoList(
                ['*{0}'.format(x) for x in nproject.extensions], file_filter)
            #process all files in current dir!
            global files_paths
            for one_file in current_files:
                try:
                    self._grep_file_symbols(one_file.absoluteFilePath(),
                                            one_file.fileName())
                    files_paths[nproject.path].append(
                        one_file.absoluteFilePath())
                except Exception as reason:
                    logger.error(
                        '__locate_code_in_project, error: %r' % reason)
                    logger.error(
                        '__locate_code_in_project fail for file: %r' %
                        one_file.absoluteFilePath())
    def setFullNameProjectNameChaged(self):
        if self.editFlag:
            return
        self.editFlag = True

        index = AirCraftOperation.g_projectList.Find(self.comboProjectSubproject.SelectedItem, enumProjectType.ptProject)
        if index == None:
            self.editFlag = False
            return
        projPath = AirCraftOperation.g_projectList.ProjectsList[index].Path
        d = QDir(projPath)
        fileInfoList = d.entryInfoList()

        self.listBoxSubproject.Clear()
        self.textNameSubproject.Value = ""

        piList = AirCraftOperation.g_projectList.FindProjectListByPt(enumProjectType.ptSubProject)
        if len(piList) == 0:
            self.editFlag = False
            self.textPathSubproject.Value = projPath + "/" + self.textNameSubproject.Value
            self.textFullName.Value = self.comboProjectSubproject.SelectedItem + "_" + self.textNameSubproject.Value
            return
        subProjNameList = []
        i = 0
        for pi in piList:
            if pi.ProjName == self.comboProjectSubproject.SelectedItem:
                subProjNameList.append(pi.SubProjName)
                self.listBoxSubproject.Add(pi.SubProjName)
            i += 1
        if len(subProjNameList) > 0:
            self.textNameSubproject.Value = subProjNameList[0]
        self.textFullName.Value = self.comboProjectSubproject.SelectedItem + "_" + self.textNameSubproject.Value

        self.textPathSubproject.Value = projPath + "/" + self.textNameSubproject.Value
        self.editFlag = False
Ejemplo n.º 6
0
    def __init__(self, file, recurse = True, recursion_counter = None, namingregex = None):
        super(FileSystemItem, self).__init__()

        # Raise exception if root path has too many child elements
        if recursion_counter:
            recursion_counter.increment()

        if isinstance(file, QFileInfo):
            self.fileinfo = file
        else:
            self.fileinfo = QFileInfo(file)
        self.fullpath = self.fileinfo.absoluteFilePath()
        self.basename = self.fileinfo.completeBaseName()
        self.displayname = self.fileinfo.fileName() if self.fileinfo.isDir() else self.fileinfo.completeBaseName()
        if namingregex:
            self.displayname = namingregex.match(self.displayname).group(1)
        self.icon = FileSystemItem.iconProvider.icon(self.fileinfo)
        self.isdir = self.fileinfo.isDir()
        self.children = [] if self.isdir else None
        if self.isdir and recurse:
            qdir = QDir(self.fullpath)
            for finfo in qdir.entryInfoList(
                    FileSystemItem.fileExtensions , QDir.Files | QDir.AllDirs | QDir.NoDotAndDotDot,QDir.Name):
                self.children.append(FileSystemItem(finfo, recurse, recursion_counter, namingregex))
        else:
            # file
            # Populate this if and when needed
            self.searchablecontent = None
Ejemplo n.º 7
0
def documentTemplates():
    """
    Return a dictionary of document names and their corresponding absolute file paths.
    """
    from stdm.settings.registryconfig import RegistryConfig

    docTemplates = OrderedDict()

    regConfig = RegistryConfig()
    keyName = "ComposerTemplates"

    pathConfig = regConfig.read([keyName])

    if len(pathConfig) > 0:
        templateDir = pathConfig[keyName]

        pathDir = QDir(templateDir)
        pathDir.setNameFilters(["*.sdt"])
        docFileInfos = pathDir.entryInfoList(QDir.Files, QDir.Name)

        for df in docFileInfos:

            docTemplates[df.completeBaseName()] = df.absoluteFilePath()

    return docTemplates
Ejemplo n.º 8
0
    def _cert_info_from_dir(self, path):
        """
        Create certificate info items from the user selected directory.
        :param path: Path of the selected directory.
        :type path: str
        :return: cert_info_items: List of certificate info items.
        :rtype cert_info_items: list
        """
        dir_ = QDir(path)
        dir_.setNameFilters(['*.pdf'])
        file_infos = dir_.entryInfoList(
            QDir.NoDot | QDir.NoDotDot | QDir.Files | QDir.Name
        )
        # Check if list contains file names
        cert_info_items = []
        if len(file_infos) == 0:
            msg = self.tr(
                'There are no PDF files in the selected directory.'
            )
            self.show_error_message(msg)
            self._cert_model.clear()
        else:
            # Loop through file info objects
            for f in file_infos:
                # Create certificate info object for each file
                cert_info = CertificateInfo()
                cert_info.filename = f.absoluteFilePath()
                base_name = f.completeBaseName()
                cert_info.certificate_number = base_name.replace('.', '/')
                cert_info_items.append(cert_info)

        return cert_info_items
Ejemplo n.º 9
0
def removeDir(dirName):
  d = QDir(dirName)
  if d.exists():
    for info in d.entryInfoList(QDir.Dirs | QDir.Files | QDir.NoDotAndDotDot):
      if info.isDir():
        removeDir(info.absoluteFilePath())
      else:
        d.remove(info.fileName())
    d.rmdir(dirName)
Ejemplo n.º 10
0
def removeDir(dirName):
    d = QDir(dirName)
    if d.exists():
        for info in d.entryInfoList(QDir.Dirs | QDir.Files | QDir.NoDotAndDotDot):
            if info.isDir():
                removeDir(info.absoluteFilePath())
            else:
                d.remove(info.fileName())
        d.rmdir(dirName)
Ejemplo n.º 11
0
  def importFromDirectory(self, path):
    d = QDir(path)
    d.setFilter(QDir.Files | QDir.Hidden)
    #d.setSorting(QDir.Size | QDir.Reversed)

    for fileInfo in d.entryInfoList():
      if debug_mode == 0 and fileInfo.fileName() == "debug.tsv":
        continue
      if fileInfo.suffix().lower() == "tsv":
        self.importFromTsv(fileInfo.filePath())
Ejemplo n.º 12
0
Archivo: scj.py Proyecto: Ptaah/SCJ
    def getDir(self):
        self.dir = QFileDialog.getExistingDirectory(
                                parent = self,
                                caption = self.trUtf8("Choix du repertoire"),
					            directory = QDir.homePath(),
		                        options = QFileDialog.ShowDirsOnly |
                                QFileDialog.DontResolveSymlinks)
        if self.dir :
            directory = QDir(self.dir, self.filter)
            for file in directory.entryInfoList():
                self.addFile(file, createDir=True)
Ejemplo n.º 13
0
 def deleteDir(self,dirPath):
     dr = QDir(dirPath)
     result=True
     if (dr.exists()):
         for entry in dr.entryInfoList(filters=QDir.NoDotAndDotDot.__or__(QDir.Hidden).__or__(QDir.AllDirs).__or__(QDir.Files) , sort=QDir.NoSort):
             if entry.isDir():
                 result&=self.deleteDir(entry.absoluteFilePath())
             else:
                 result&=QFile.remove(entry.absoluteFilePath())
         dr.rmdir(dirPath)
     return result
Ejemplo n.º 14
0
def documentTemplates():
    """
    Return a dictionary of document names and their corresponding absolute file paths.
    """
    docTemplates = OrderedDict()
    
    regConfig = RegistryConfig()
    keyName = "ComposerTemplates"
        
    pathConfig = regConfig.read([keyName])
        
    if len(pathConfig) > 0:
        templateDir = pathConfig[keyName]
        
        pathDir = QDir(templateDir)
        pathDir.setNameFilters(["*.sdt"])
        docFileInfos = pathDir.entryInfoList(QDir.Files,QDir.Name)
        
        for df in docFileInfos:
            docTemplates[df.completeBaseName()] = df.absoluteFilePath()
        
    return docTemplates
        

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
     


    
Ejemplo n.º 15
0
    def run(self):
        file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable
        dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable
        while not self._cancel and not self.queue.empty():
            current_dir = QDir(self.queue.get())
            #Skip not readable dirs!
            if not current_dir.isReadable():
                continue

            #Collect all sub dirs!
            if self.recursive:
                current_sub_dirs = current_dir.entryInfoList(dir_filter)
                for one_dir in current_sub_dirs:
                    self.queue.put(one_dir.absoluteFilePath())

            #all files in sub_dir first apply the filters
            current_files = current_dir.entryInfoList(
                self.filters, file_filter)
            #process all files in current dir!
            for one_file in current_files:
                self._grep_file(one_file.absoluteFilePath(),
                    one_file.fileName())
Ejemplo n.º 16
0
    def __locate_code_in_project(self, queue_folders, extensions):
        file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable
        dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable
        while not self._cancel and not queue_folders.empty():
            current_dir = QDir(queue_folders.get())
            #Skip not readable dirs!
            if not current_dir.isReadable():
                continue

            #Collect all sub dirs!
            current_sub_dirs = current_dir.entryInfoList(dir_filter)
            for one_dir in current_sub_dirs:
                queue_folders.put(one_dir.absoluteFilePath())

            #all files in sub_dir first apply the filters
            current_files = current_dir.entryInfoList(
                ['*{0}'.format(x) for x in extensions],
                file_filter)
            #process all files in current dir!
            for one_file in current_files:
                self._grep_file_locate(unicode(one_file.absoluteFilePath()),
                    one_file.fileName())
Ejemplo n.º 17
0
    def run(self):
        file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable
        dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable
        while not self._cancel and not self.queue.empty():
            current_dir = QDir(self.queue.get())
            #Skip not readable dirs!
            if not current_dir.isReadable():
                continue

            #Collect all sub dirs!
            if self.recursive:
                current_sub_dirs = current_dir.entryInfoList(dir_filter)
                for one_dir in current_sub_dirs:
                    self.queue.put(one_dir.absoluteFilePath())

            #all files in sub_dir first apply the filters
            current_files = current_dir.entryInfoList(self.filters,
                                                      file_filter)
            #process all files in current dir!
            for one_file in current_files:
                self._grep_file(one_file.absoluteFilePath(),
                                one_file.fileName())
Ejemplo n.º 18
0
    def navigate_code(self):
        explorerContainer = explorer_container.ExplorerContainer()
        projects_obj = explorerContainer.get_opened_projects()
        projects = [p.path for p in projects_obj]
        project = None
        for p in projects:
            if self._filePath.startswith(p):
                project = p
                break
        #Search in files
        if not project:
            fileName = file_manager.get_basename(self._filePath)
            self._grep_file(self._filePath, fileName)
            return
        queue = Queue.Queue()
        queue.put(project)
        file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable
        dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable
        while not self._cancel and not queue.empty():
            current_dir = QDir(queue.get())
            #Skip not readable dirs!
            if not current_dir.isReadable():
                continue

            #Collect all sub dirs!
            current_sub_dirs = current_dir.entryInfoList(dir_filter)
            for one_dir in current_sub_dirs:
                queue.put(one_dir.absoluteFilePath())

            current_sub_dirs = current_dir.entryInfoList(dir_filter)
            #all files in sub_dir first apply the filters
            current_files = current_dir.entryInfoList(
                ['*.py'], file_filter)
            #process all files in current dir!
            for one_file in current_files:
                if one_file.fileName() != '__init__.py':
                    self._grep_file(one_file.absoluteFilePath(),
                        one_file.fileName())
Ejemplo n.º 19
0
    def navigate_code(self):
        explorerContainer = explorer_container.ExplorerContainer()
        projects_obj = explorerContainer.get_opened_projects()
        projects = [p.path for p in projects_obj]
        project = None
        for p in projects:
            if self._filePath.startswith(p):
                project = p
                break
        #Search in files
        if not project:
            fileName = file_manager.get_basename(self._filePath)
            self._grep_file(self._filePath, fileName)
            return
        queue = Queue.Queue()
        queue.put(project)
        file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable
        dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable
        while not self._cancel and not queue.empty():
            current_dir = QDir(queue.get())
            #Skip not readable dirs!
            if not current_dir.isReadable():
                continue

            #Collect all sub dirs!
            current_sub_dirs = current_dir.entryInfoList(dir_filter)
            for one_dir in current_sub_dirs:
                queue.put(one_dir.absoluteFilePath())

            current_sub_dirs = current_dir.entryInfoList(dir_filter)
            #all files in sub_dir first apply the filters
            current_files = current_dir.entryInfoList(['*.py'], file_filter)
            #process all files in current dir!
            for one_file in current_files:
                if one_file.fileName() != '__init__.py':
                    self._grep_file(one_file.absoluteFilePath(),
                                    one_file.fileName())
Ejemplo n.º 20
0
 def initTree(self, notePath, parent):
     ''' When there exist foo.md, foo.mkd, foo.markdown,
         only one item will be shown in notesTree.
     '''
     if not QDir(notePath).exists():
         return
     notebookDir = QDir(notePath)
     notesList = notebookDir.entryInfoList(['*.md', '*.mkd', '*.markdown'],
                                           QDir.NoFilter,
                                           QDir.Name | QDir.IgnoreCase)
     nl = [note.completeBaseName() for note in notesList]
     noduplicate = list(set(nl))
     for name in noduplicate:
         item = QTreeWidgetItem(parent, [name])
         path = notePath + '/' + name
         self.initTree(path, item)
Ejemplo n.º 21
0
 def initTree(self, notePath, parent):
     ''' When there exist foo.md, foo.mkd, foo.markdown,
         only one item will be shown in notesTree.
     '''
     if not QDir(notePath).exists():
         return
     notebookDir = QDir(notePath)
     notesList = notebookDir.entryInfoList(['*.md', '*.mkd', '*.markdown'],
                                            QDir.NoFilter,
                                            QDir.Name|QDir.IgnoreCase)
     nl = [note.completeBaseName() for note in notesList]
     noduplicate = list(set(nl))
     for name in noduplicate:
         item = QTreeWidgetItem(parent, [name])
         path = notePath + '/' + name
         self.initTree(path, item)
Ejemplo n.º 22
0
 def fillTemplateList(self):
     """ Fill the listbox of composer template files.
     """
     if self.ui.TemplateList.currentItem() is not None:
         oldSelectedTemplate = self.ui.TemplateList.currentItem().text()
     else:
         oldSelectedTemplate = ""
     self.ui.TemplateList.clear()
     
     tempdir = QDir(self.templatepath)
     if  tempdir.exists():
         fileinfolist = tempdir.entryInfoList(["*.qpt"], QDir.Files | QDir.NoDotAndDotDot | QDir.NoSymLinks, QDir.NoSort)
         for fi in fileinfolist:
             item = QListWidgetItem(fi.fileName())
             self.ui.TemplateList.addItem(item)
             if fi.fileName() == oldSelectedTemplate:
                 self.ui.TemplateList.setCurrentItem( item )
Ejemplo n.º 23
0
    def fillTemplateList(self):
        """ Fill the listbox of composer template files.
        """
        if self.ui.TemplateList.currentItem() is not None:
            oldSelectedTemplate = self.ui.TemplateList.currentItem().text()
        else:
            oldSelectedTemplate = ""
        self.ui.TemplateList.clear()

        tempdir = QDir(self.templatepath)
        if tempdir.exists():
            fileinfolist = tempdir.entryInfoList(
                ["*.qpt"], QDir.Files | QDir.NoDotAndDotDot | QDir.NoSymLinks,
                QDir.NoSort)
            for fi in fileinfolist:
                item = QListWidgetItem(fi.fileName())
                self.ui.TemplateList.addItem(item)
                if fi.fileName() == oldSelectedTemplate:
                    self.ui.TemplateList.setCurrentItem(item)
Ejemplo n.º 24
0
    def initTree(self, notepath, parent):
        if parent == "":
            # site wide index page
            htmlfile = os.path.join(self.sitepath, "index.html")
        else:
            # append subpages to page
            htmlfile = os.path.join(self.htmlpath, parent + ".html")
        html = QFile(htmlfile)
        html.open(QIODevice.Append)
        savestream = QTextStream(html)

        noteDir = QDir(notepath)
        notesList = noteDir.entryInfoList(['*.md', '*.mkd', '*.markdown'],
                                          QDir.NoFilter,
                                          QDir.Name | QDir.IgnoreCase)
        nl = [note.completeBaseName() for note in notesList]
        noduplicate = list(set(nl))
        noduplicate.sort(key=str.lower)
        htmlDir = os.path.join(self.htmlpath, parent)
        if len(noduplicate) > 0 and not QDir(htmlDir).exists():
            QDir().mkdir(htmlDir)

        for name in noduplicate:
            path = notepath + '/' + name
            filename = os.path.join(parent, name)
            for ext in self.extName:
                notefile = os.path.join(self.notepath, filename + ext)
                if QFile.exists(notefile):
                    break
            htmlfile = os.path.join(self.htmlpath, filename + ".html")
            #print(notefile, htmlfile)
            self.convert(notefile, htmlfile, os.path.join(parent, name))
            self.initTree(path, os.path.join(parent, name))

            # append subpages to page
            savestream << '<li><a href="/notes/' + filename + '.html">' + name + '</a></li>'
        html.close()
Ejemplo n.º 25
0
    def initTree(self, notepath, parent):
        if parent == "":
        # site wide index page
            htmlfile = os.path.join(self.sitepath, "index.html")
        else:
        # append subpages to page
            htmlfile = os.path.join(self.htmlpath, parent + ".html")
        html = QFile(htmlfile)
        html.open(QIODevice.Append)
        savestream = QTextStream(html)

        noteDir = QDir(notepath)
        notesList = noteDir.entryInfoList(['*.md', '*.mkd', '*.markdown'],
                                          QDir.NoFilter,
                                          QDir.Name|QDir.IgnoreCase)
        nl = [note.completeBaseName() for note in notesList]
        noduplicate = list(set(nl))
        noduplicate.sort(key=str.lower)
        htmlDir = os.path.join(self.htmlpath, parent)
        if len(noduplicate) > 0 and not QDir(htmlDir).exists():
            QDir().mkdir(htmlDir)

        for name in noduplicate:
            path = notepath + '/' + name
            filename = os.path.join(parent, name)
            for ext in self.extName:
                notefile = os.path.join(self.notepath, filename + ext)
                if QFile.exists(notefile):
                    break
            htmlfile = os.path.join(self.htmlpath, filename + ".html")
            #print(notefile, htmlfile)
            self.convert(notefile, htmlfile, os.path.join(parent,name))
            self.initTree(path, os.path.join(parent,name))

            # append subpages to page
            savestream << '<li><a href="/notes/' + filename + '.html">' + name + '</a></li>'
        html.close()
Ejemplo n.º 26
0
class NodeLibrary ( QtCore.QObject ) : # QtCore.QObject
  #
  # __init__
  #
  def __init__ ( self, dirName ) :
    #
    self.dirName = dirName
    self.libdir = QDir ( dirName );
    self.model = 	QStandardItemModel ()
    self.parentItem = self.model.invisibleRootItem ()
    
    print '>> NodeLibrary: libdir = %s' % dirName 
    
    self.liblevel = ''
    self.scanLibDir ()
  #    
  # scanLibDir
  #
  def scanLibDir ( self ) :
    # process directories
    sortFlags = QDir.Name
    filterFlags = ( QDir.AllDirs | QDir.NoDotAndDotDot )
    fileList = self.libdir.entryInfoList ( filterFlags, sortFlags ) 
    
    for f in fileList :
      item = QStandardItem ( f.fileName () )
      item.setEditable ( False )
      item.setDragEnabled ( False )
      
      # set bold font for folders
      font = item.font()
      font.setBold ( True )
      item.setFont ( font )
      
      item.setWhatsThis ( 'folder' )
      
      currparent = self.parentItem
      self.parentItem.appendRow ( item )
      self.parentItem = item
      
      currlevel = self.liblevel # store current level
      self.liblevel = self.liblevel + f.fileName () + '/' 
      self.libdir.cd ( f.fileName () )
      
      self.scanLibDir () # recurcive call itself
      
      self.liblevel = currlevel # restore current level
      self.libdir.cdUp ()
      
      self.parentItem = currparent
        
    # process XML files
    filterFlags = QDir.Files    
    fileList = self.libdir.entryInfoList ( [ '*.xml' ], filterFlags, sortFlags ) 
    for f in fileList :
      self.scanXmlNodes ( f.fileName () )
  #
  # scanXmlNodes
  #
  def scanXmlNodes ( self, filename ) :      
    #
    dom = QtXml.QDomDocument ( '' )
    nodeFilename = self.dirName + '/' + self.liblevel + filename
    
    file = QFile ( self.libdir.filePath ( filename )  )
    
    if file.open ( QtCore.QIODevice.ReadOnly ) :
      if dom.setContent ( file ) :
        node = dom.documentElement () 
        if node.nodeName () == 'nodenet' or node.nodeName () == 'node' :
          nodeName   = node.attributes ().namedItem ( 'name' ).nodeValue ()
          nodeType   = node.attributes ().namedItem ( 'type' ).nodeValue ()
          nodeAuthor = node.attributes ().namedItem ( 'author' ).nodeValue ()
          nodeIcon   = node.attributes ().namedItem ( 'icon' ).nodeValue ()
          nodeHelp   = ''
          help_tag   = node.namedItem ('help')
          
          if not help_tag.isNull() : nodeHelp = help_tag.toElement ().text ()
          
          item = QStandardItem ( nodeName )
          item.setEditable ( False )
          
          item.setData ( QVariant ( nodeAuthor ),   QtCore.Qt.UserRole + 1 )
          item.setData ( QVariant ( nodeType ),     QtCore.Qt.UserRole + 2 )
          item.setData ( QVariant ( nodeHelp ),     QtCore.Qt.UserRole + 3 )
          item.setData ( QVariant ( nodeFilename ), QtCore.Qt.UserRole + 4 )
          item.setData ( QVariant ( nodeIcon ),     QtCore.Qt.UserRole + 5 )
          
          if node.nodeName () == 'nodenet' :
            # set Blue color for nodenet items
            brush = QtGui.QBrush ()
            brush.setColor ( QtCore.Qt.blue )
            item.setForeground ( brush )
            item.setWhatsThis ( 'nodenet' )
          else:
            item.setWhatsThis ( 'node' )
          
          self.parentItem.appendRow ( item )
    file.close ()
Ejemplo n.º 27
0
 import pqIMC
 IMC = pqIMC.tricorder() # set up a fake IMC for unit test
 IMC.settings = QSettings()
 IMC.editWidget = QPlainTextEdit()
 import pqPages
 pqPages.IMC = IMC
 IMC.pageTable=pqPages.pagedb()
 widj = pngDisplay()
 widj.pngPath = QFileDialog.getExistingDirectory(widj,"Pick a Folder of Pngs",".")
 widj.pngPath.append(u'/')
 png_dir = QDir(widj.pngPath)
 png_dir.setFilter(QDir.Files | QDir.NoSymLinks)
 png_dir.setSorting(QDir.Name)
 png_dir.setNameFilters(QStringList(QString(u'*.png')))
 fnumber = 1
 for finf in png_dir.entryInfoList():
     # Read all the pngs and for each cobble up a "page" just to get
     # some data into the page table
     fname = finf.baseName()
     IMC.editWidget.textCursor().insertText(fname)
     fakemd = "{0} {1} {2} {3} {4} {5}\n".format(
         IMC.editWidget.textCursor().position(),
         fname, QString(u'\\foo\\foo'),
         IMC.FolioRuleAdd1, IMC.FolioFormatArabic, fnumber )
     IMC.pageTable.metaStringIn(fakemd)
     fnumber +=1
 widj.lastIndex = -1
 widj.nextIndex = 0
 widj.ready = True
 widj.showPage()
 widj.show()
Ejemplo n.º 28
0
class DirDocumentTypeSelector(QDialog):
    """
    Dialog for selecting supporting documents from a given directory. Default
    filter searches for PDF files only.
    """
    def __init__(self, dir, doc_types, parent=None, filters=None):
        super(DirDocumentTypeSelector, self).__init__(parent)
        self.setWindowTitle(
            self.tr('Documents in Folder')
        )
        self._filters = filters
        # Use PDF as default filter
        if not self._filters:
            self._filters = ['*.pdf']

        self._init_ui()
        self._dir = QDir(dir)
        self._dir.setNameFilters(self._filters)
        self._doc_types = doc_types

        self._attr_model = QStandardItemModel(self)
        self._sel_doc_types = OrderedDict()

        # Notification bar
        self._notif_bar = NotificationBar(self.vl_notif)

        self.resize(320, 350)

        # Load documents
        self.load_document_types()

    @property
    def selected_document_types(self):
        """
        :return: Returns a dictionary of the document types and the
        corresponding file paths as selected by the user.
        :rtype: dict
        """
        return self._sel_doc_types

    def _init_ui(self):
        # Draw UI widgets
        layout = QVBoxLayout()

        # Add layout for notification bar
        self.vl_notif = QVBoxLayout()
        layout.addLayout(self.vl_notif)
        self.lbl_info = QLabel()
        self.lbl_info.setObjectName('lbl_info')
        self.lbl_info.setText(self.tr(
            'The selected document types have been found in the directory, '
            'check/uncheck to specify which ones to upload.'
        ))
        self.lbl_info.setWordWrap(True)
        layout.addWidget(self.lbl_info)
        self.lst_docs = QListView()
        layout.addWidget(self.lst_docs)
        self.lbl_warning = QLabel()
        self.lbl_warning.setTextFormat(Qt.RichText)
        self.lbl_warning.setText(self.tr(
            '<html><head/><body><p><span style=" font-style:italic;">'
            '* Previously uploaded documents will be replaced.</span></p>'
            '</body></html>'
        ))
        self.lbl_warning.setWordWrap(True)
        layout.addWidget(self.lbl_warning)
        self.btn_box = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel
        )
        layout.addWidget(self.btn_box)
        self.setLayout(layout)

        # Connect signals
        self.btn_box.accepted.connect(
            self.set_selected_document_types
        )
        self.btn_box.rejected.connect(
            self.reject
        )

    def set_selected_document_types(self):
        """
        Sets the collections of accepted document types and their
        corresponding file paths and accepts the dialog.
        """
        self._sel_doc_types = OrderedDict()
        for i in range(self._attr_model.rowCount()):
            doc_type_item = self._attr_model.item(i, 0)

            if doc_type_item.checkState() == Qt.Checked:
                path_item = self._attr_model.item(i, 1)
                self._sel_doc_types[doc_type_item.text()] = path_item.text()

        if len(self._sel_doc_types) == 0:
            self._notif_bar.clear()
            msg = self.tr('No matching documents found or selected.')
            self._notif_bar.insertWarningNotification(msg)

            return

        self.accept()

    def load_document_types(self):
        """
        Load all document types to the list view and enable/check the items
        for those types that have been found.
        """
        self._attr_model.clear()
        self._attr_model.setColumnCount(2)

        file_infos = self._dir.entryInfoList(
            QDir.Readable | QDir.Files,
            QDir.Name
        )

        # Index file info based on name
        idx_file_infos = {fi.completeBaseName().lower(): fi for fi in file_infos}

        for d in self._doc_types:
            doc_type_item = QStandardItem(d)
            doc_type_item.setCheckable(True)
            path_item = QStandardItem()

            item_enabled = False
            check_state = Qt.Unchecked
            dl = d.lower()
            if dl in idx_file_infos:
                item_enabled = True
                check_state = Qt.Checked
                path = idx_file_infos[dl].filePath()
                path_item.setText(path)
                doc_type_item.setToolTip(path)

            doc_type_item.setEnabled(item_enabled)
            doc_type_item.setCheckState(check_state)

            self._attr_model.appendRow([doc_type_item, path_item])

        self.lst_docs.setModel(self._attr_model)