Beispiel #1
0
    def __init__(self, selectCallback=None, showHiddens=True):
        """
        @summary: Create new TreeExplorer.
        @param selectCallback: Callback that will call when an item will be selected.
        @param showHiddens: True to show hidden folders.
        @note: selectCallback must be a funtion reference, like function(path : str)
        """
        self.__selectedPath__ = ""
        self.__ioUtils__ = IOUtils()

        # Define Treeview explorer
        self.__explorer__ = gtk.TreeView()
        self.__explorer__.connect("cursor-changed", self.__selectRowTvOneClickSignal__)
        self.__explorer__.connect("row-collapsed", self.__collapsedRowTVSignal__)
        self.__explorer__.connect("row-expanded", self.__expandRowTVSignal__)
        
        self.__exportControl__ = gtk.ScrolledWindow()
        self.__exportControl__.add(self.__explorer__)
        
        self.__HOME_NODE__ = _("home")
        
        # Initialize TreeView explorer
        self.__initializeExplorer__()
        
        self.__selectCallback__ = selectCallback
        self.__showHiddens__ = showHiddens
Beispiel #2
0
 def __applyNumber__(self, item, iter, count, key, value):
     """
     @summary: Apply a number to a item.
     @param item: pycamimg.core.CamItem.CamItem
     @param iter: GtkTreeIter.
     @param count: Current item. 
     @param value: Tuple of format and initial. 
     """
     format, initial = value
     ioUtils = IOUtils()
     
     ext = ioUtils.getExtension(item.getPath()) 
     
     if (initial != -1):
         return "%s%s" % (format % (initial + count), ext)
     else:
         return "%s%s" % (format, ext)
Beispiel #3
0
def __loadPlugin__(pathPluginsTypes, plugin, key, iou=None):
    """
    @summary: Load a plugin.
    @param pathPluginsTypes: Path of directory where plugin is.
    @param key: Name of directory parent.
    @param plugin: Name of plugin.
    @param iou: IOUtils object. 
    @return: Int with value of op.
        0 - Ok
        1 - No deps
        2 - Fail
    """
    iRes = 0
    delIou = False
    if iou == None:
        delIou = True
        iou = IOUtils()
    
    py_mod = None
    filesPluginPath = os.path.join(pathPluginsTypes, plugin)
    files = iou.getFiles(filesPluginPath)
    isPlugin = False
    isCompilled = False
    
    if ((files.count("camimgplugin.py") > 0) and (files.count("__init__.py") > 0)):
        isCompilled = False
        isPlugin = True
    """
    if ((files.count("camimgplugin.pyc") > 0) and (files.count("__init__.pyc") > 0)):
        isCompilled = True
        isPlugin = True
    """
    if (isPlugin):
        pluginPath = os.path.join(filesPluginPath, "camimgplugin.pyc" if isCompilled else "camimgplugin.py")
        pluginModAccess = ("%s.%s" % (key, plugin))
        
        if (not isCompilled):
            pluginPackagePath = os.path.join(filesPluginPath, "__init__.py")
            imp.load_source(pluginModAccess, pluginPackagePath)
            __log__.debug("__init__.py imported from package %s", filesPluginPath)
            py_mod = imp.load_source("%s.cammingplugin" % pluginModAccess, pluginPath)
        else:
            pluginPackagePath = os.path.join(filesPluginPath, "__init__.pyc")
            imp.load_compiled(pluginModAccess, pluginPackagePath)
            __log__.debug("__init__.pyc imported from package %s", filesPluginPath)
            py_mod = imp.load_compiled("%s.cammingplugin" % pluginModAccess, pluginPath)
            
        __log__.info("It detected a plugin in %s" % pluginPath)

    if (isPlugin and (py_mod != None)):
        
        sys.path.append(filesPluginPath)
        if __classplugin__ in dir(py_mod):
            __log__.debug("Loading %s..." % pluginPath)
            plugin = py_mod.camimgplugin()
            if (plugin.getType() != None):
                py_mod_class = None
                if (plugin.isNeedLoad()):
                    if ((plugin.getPluginDependecies() != None) and (len(plugin.getPluginDependecies()) > 0)):
                        for dep in plugin.getPluginDependecies():
                            if not (dep in pluginsLoadedArray):
                                iRes = 1
                                __log__.info("\t%s deps no satisfied." % pluginPath)
                                break
                    if (iRes == 0):
                        if (plugin.isCompiled()):
                            __log__.debug("\t%s is compiled plugin." % pluginPath)
                            
                            pluginPath = os.path.join(filesPluginPath, "%s.pyc" % plugin.getPluginModule())
                            pluginModName = "%s.%s" % (pluginModAccess, plugin.getPluginModule())
                            try:
                                py_mod_class = imp.load_compiled(pluginModName, pluginPath)
                            except ImportError, ie:
                                __log__.error("It could not load %s from %s. %s" % (pluginModName, pluginPath, ie))
                                iRes = 2
                        else:
                            __log__.debug("\t%s is source plugin." % pluginPath)
                            
                            pluginPath = os.path.join(filesPluginPath, "%s.py" % plugin.getPluginModule())
                            pluginModName = "%s.%s" % (pluginModAccess, plugin.getPluginModule())
                            try:
                                py_mod_class = imp.load_source(pluginModName, pluginPath)
                            except ImportError, ie:
                                __log__.error("It could not load %s from %s. %s" % (pluginModName, pluginPath, ie))
                                iRes = 2
                else:
                    __log__.debug("\t%s is need load." % pluginPath)
                
                if (iRes == 0):
                    if (pluginsLoaded.has_key(plugin.getType())):
                        pluginsLoaded[plugin.getType()].append((plugin, (py_mod_class.CamimgPlugin if py_mod_class else None)))
                    else:
                        pluginsLoaded[plugin.getType()] = [(plugin, (py_mod_class.CamimgPlugin if py_mod_class else None))]
                        
                    pluginsLoadedArray.append(plugin.getId())
                        
                    plugin.initialize()
            else:
                __log__.warning("It can not determinate type of the plugin %s" % pluginPath)
Beispiel #4
0
 def __addTargetFiles__(self, files, defaultIcon,
                        iterOp,
                        iter=None,
                        position=gtk.TREE_VIEW_DROP_AFTER,
                        recursiveLevel=0,
                        gtkLock=True):
     """
     @summary: Add files to target listview.
     @param files: List of files to add.
     @param defaultIcon: Default icon to associate with each file.
     @param iterOp: GtkIter of operation progress bar.
     @param recursiveLevel: Current recursive level.
     @param iter: Iter that it will use as reference to insert new files.
     @param position: Position over iter.    
     @param gtkLock: True to do a lock on gtk loop.
     """
     if (files != None):
         operations = RegOperations()
         
         # Add each file into target TreeView
         for file in files:
             __log__.debug("Adding %s" % file)
             if (iterOp != None):
                 operations.stepOperation(iterOp)
             if (file == ""):
                 __log__.warn("Empty file path. Skip file")
                 continue
             if (self.__core__.getItem(file) != None):
                 __log__.info("File %s already exists in target file list" % file)
                 continue
             
             # Checks if is a folder and system is configured to add files recursively
             if (os.path.isdir(file) and Configuration().getConfiguration().getboolean("UI_CORE", "add_recursive")):
                 __log__.debug("%s is folder. Adding images into folder." % file)
                 # Do recursivity
                 if (recursiveLevel < Configuration().getConfiguration().getint("UI_CORE", "recursive_level")):
                     ioUtils = IOUtils()
                     listNewFiles = []
                     if ((recursiveLevel + 1) != Configuration().getConfiguration().getint("UI_CORE", "recursive_level")):
                         listNewFiles += ioUtils.getDirectories(file, Configuration().getConfiguration().getboolean("NAVIGATOR", "show_hiddens"), getFullpath=True)
                     
                     listNewFiles += ioUtils.getFiles(file, Configuration().getConfiguration().getboolean("NAVIGATOR", "show_hiddens"), getFullpath=True)
                     __log__.debug("Adding images from folder %s" % file)
                     
                     operations.addElements(iterOp, len(listNewFiles), gtkLock=gtkLock)
                     self.__addTargetFiles__(listNewFiles, defaultIcon, iterOp,
                                             iter=iter, position=position,
                                             recursiveLevel=(recursiveLevel + 1), gtkLock=gtkLock)
                     
                     del ioUtils
                 else:
                     __log__.debug("Max. recursive level got.")
                 continue
 
             head, filename = os.path.split(file)
             item = CamItem(file, target=filename)
             __log__.debug("New CamItem created for filename %s. %s" % (filename, item))
                 
             # Create a new row
             newRowData = [defaultIcon,
                           file,
                           _("Loading..."),
                           filename ,
                           item.getDescription(),
                           defaultIcon,
                           False,
                           True]
             
             iterAdd = UIUtils.insertIterAtPathPosition(self.__model__, newRowData,
                                                        iter, position=position,
                                                        doGObject=gtkLock)
             __log__.info("New file inserted into target treeview. %s" % file)
         
             if (iterAdd != None):
                 self.__core__.addItem(file, item)
                 self.updateItem(iterAdd, item, gtkLock=gtkLock)
             else:
                 __log__.error("It could not insert new item into project. %s" % file)
                 del newRowData
                 del item
     else:
         __log__.warning("Files parameter is None")
Beispiel #5
0
class TreeExplorer:
    """
    @summary: This class is a handler for a TreeView, for
        simulating a tree explorer, like nautilus has.
    """
    
    __selectCallback__ = None
    __showHiddens__ = True

    __TEMP_NODE__ = " !TempCamimg"    
    
    # Index of each column
    __IMG_COLUMN__ = 0
    __NAME_COLUMN__ = 1
    __PATH_COLUMN__ = 2
    
    def __init__(self, selectCallback=None, showHiddens=True):
        """
        @summary: Create new TreeExplorer.
        @param selectCallback: Callback that will call when an item will be selected.
        @param showHiddens: True to show hidden folders.
        @note: selectCallback must be a funtion reference, like function(path : str)
        """
        self.__selectedPath__ = ""
        self.__ioUtils__ = IOUtils()

        # Define Treeview explorer
        self.__explorer__ = gtk.TreeView()
        self.__explorer__.connect("cursor-changed", self.__selectRowTvOneClickSignal__)
        self.__explorer__.connect("row-collapsed", self.__collapsedRowTVSignal__)
        self.__explorer__.connect("row-expanded", self.__expandRowTVSignal__)
        
        self.__exportControl__ = gtk.ScrolledWindow()
        self.__exportControl__.add(self.__explorer__)
        
        self.__HOME_NODE__ = _("home")
        
        # Initialize TreeView explorer
        self.__initializeExplorer__()
        
        self.__selectCallback__ = selectCallback
        self.__showHiddens__ = showHiddens
    
    def __initializeExplorer__(self):
        """
        @summary: Initialize TreeView explorer. Add drives of OS.
        """
        # Make a model for TreeView explorer
        self.__model__ = gtk.TreeStore(gtk.gdk.Pixbuf,
                                       gobject.TYPE_STRING,
                                       gobject.TYPE_STRING)
        
        __log__.debug("Created model for TreeExplorer.")
        # Gets home icon
        iconHome = FactoryControls.getPixbufFromStock(gtk.STOCK_HOME)
        
        # Gets drive icon
        icon = FactoryControls.getPixbufFromStock(gtk.STOCK_HARDDISK)
    
        self.__explorer__.set_model(None)
    
        # Apply look to TreeView
        self.__explorer__.set_headers_visible(False)
        self.__explorer__.set_show_expanders(True)
        self.__explorer__.get_selection().set_mode(gtk.SELECTION_SINGLE)
    
        column = FactoryControls.getTreeColumnTextAndPixbuf(_("Explorer"),
                                                            self.__NAME_COLUMN__,
                                                            self.__IMG_COLUMN__)
        self.__explorer__.append_column(column)
    
        __log__.debug("Added columns to TreeExplorer")
        
        # Add home node
        self.addDirectory(self.__HOME_NODE__, os.path.expanduser("~"), iconHome, glock=False)
        
        # Gets drives from the OS
        for sDrive in self.__ioUtils__.getDrives():
            if (sDrive != None) and (sDrive != ""):
                self.addDirectory (sDrive, sDrive, icon, glock=False)
        
        __log__.debug("Drives added.")
        
        # Set model to explorer TreeView
        self.__explorer__.set_model(self.__model__)
     
    def __fillDirectory__(self, path):
        """
        @summary: Fills a node with sub-directories.
        @param path: Folder path to fill. 
        """
        newExpand = False
        # Gets current path
        iter = self.__model__.get_iter(path)
        sPath = self.__model__.get_value(iter, self.__PATH_COLUMN__)
        
        monitor = FactoryDirectoryMonitor.getMonitor(sPath)
        
        # Checks if first child y a temporal node. If it is, it must be removed
        itFirstChild = self.__model__.iter_children(iter)
        if (itFirstChild != None):
            if (self.__model__.get_value(itFirstChild, self.__PATH_COLUMN__) == self.__TEMP_NODE__):
                # Gets number of nodes. If nNodes > 1, 
                # there is another thread that is loading the directory 
                nNodes = self.__model__.iter_n_children(iter)
                if (nNodes > 1):
                    return
                newExpand = True
        else:
            __log__.warning("It can not get first child of %s" % sPath)
    
        # Gets directories of the path
        lDirectories = self.__ioUtils__.getDirectories(sPath,
                                                       showhidden=self.__showHiddens__)
    
        if (lDirectories != None):
            icon = FactoryControls.getPixbufFromStock(gtk.STOCK_DIRECTORY)
                
            if (not newExpand):
                __log__.debug("It is not a new expand. Checking directories...")
                
                iterStep = self.__model__.iter_children(iter)
                # Find deleted iters
                while (iterStep != None):
                    doStep = True
                    sDirFind = self.__model__.get_value(iterStep, self.__NAME_COLUMN__)
                    if (sDirFind != None):
                        try:
                            index = lDirectories.index(sDirFind)
                        except ValueError, ve:
                            __log__.debug("It can not get index of %s. %s" % (sDirFind, ve))
                            index = -1
                        if (index == -1):
                            # In case of directory does not exist, it will remove from treeview
                            iterDelete = iterStep
                            iterStep = self.__model__.iter_next(iterStep)
                            self.deleteNode(iterDelete)
                            __log__.debug("Delete node %s" % sDirFind)
                            
                            doStep = False
                        else:
                            # In case of directory just exists, it will remove from list
                            lDirectories.remove(sDirFind)
                            __log__.debug("%s skipped" % sDirFind)
        
                    if (doStep):
                        iterStep = self.__model__.iter_next(iterStep)
                
                # Check directories in the list 
                for sDir in lDirectories:
                    sFullPath = os.path.join(sPath, sDir)
                    checkIter = self.__findDirectoryOnParent__(iter, sDir)
                    if (checkIter == None):
                        self.addDirectory(sDir, sFullPath, icon, iter)
                        __log__.debug("Add %s" % sFullPath)
            
            # Insert directories
            for sDir in lDirectories:
                sFullPath = os.path.join(sPath, sDir)
                self.addDirectory(sDir, sFullPath, icon, iter)
                __log__.debug("Add %s" % sFullPath)
                    
            if ((itFirstChild != None) and newExpand):
                __log__.debug("Remove temporal node.")
                self.deleteNode(itFirstChild)
                
            monitor.addDirectories(lDirectories)
            monitor.addListener(self.__handlerDirectoryMonitorEvents__)
            
        else:  # When there isn't any directory