Exemple #1
0
        def setDefaultIcon(self):

            """Set the icon to be used in all Leo windows.

            This code does nothing for Tk versions before 8.4.3."""

            gui = self

            try:
                version = gui.root.getvar("tk_patchLevel")
                # g.trace(repr(version),g.CheckVersion(version,"8.4.3"))
                if g.CheckVersion(version,"8.4.3") and sys.platform == "win32":

                    # gtk 8.4.3 or greater: load a 16 by 16 icon.
                    path = g.os_path_join(g.app.loadDir,"..","Icons")
                    if g.os_path_exists(path):
                        theFile = g.os_path_join(path,"LeoApp16.ico")
                        if g.os_path_exists(path):
                            self.bitmap = gtk.BitmapImage(theFile)
                        else:
                            g.es("LeoApp16.ico not in Icons directory", color="red")
                    else:
                        g.es("Icons directory not found: "+path, color="red")
            except:
                print "exception setting bitmap"
                import traceback ; traceback.print_exc()
Exemple #2
0
    def setDefaultIcon(self):
        """Set the icon to be used in all Leo windows.
        
        This code does nothing for Tk versions before 8.4.3."""

        gui = self

        try:
            version = gui.root.getvar("tk_patchLevel")
            if g.CheckVersion(version,
                              "8.4.3") and sys.platform == "win32":  # 12/2/03
                # tk 8.4.3 or greater: load a 16 by 16 icon.
                path = g.os_path_join(g.app.loadDir, "..", "Icons")
                if g.os_path_exists(path):
                    theFile = g.os_path_join(path, "LeoApp16.ico")
                    if g.os_path_exists(path):
                        self.bitmap = Tk.BitmapImage(theFile)
                    else:
                        g.es("LeoApp16.ico not in Icons directory",
                             color="red")
                else:
                    g.es("Icons directory not found: " + path, color="red")
        except:
            print "exception setting bitmap"
            import traceback
            traceback.print_exc()
 def browser (self,n):
     
     types = [
         ("C/C++ files","*.c"),
         ("C/C++ files","*.cpp"),
         ("C/C++ files","*.h"),
         ("C/C++ files","*.hpp"),
         ("Java files","*.java"),
         ("Lua files", "*.lua"),
         ("Pascal files","*.pas"),
         ("Python files","*.py"),
         ("Text files","*.txt"),
         ("All files","*") ]
 
     fileName = tkFileDialog.askopenfilename(
         title="Choose compare file" + n,
         filetypes=types,
         defaultextension=".txt")
         
     if fileName and len(fileName) > 0:
         # The dialog also warns about this, so this may never happen.
         if not g.os_path_exists(fileName):
             self.show("not found: " + fileName)
             fileName = None
     else: fileName = None
         
     return fileName
Exemple #4
0
    def openOutputFile(self):

        if self.outputFileName == None:
            return
        theDir, name = g.os_path_split(self.outputFileName)
        if len(theDir) == 0:
            self.show("empty output directory")
            return
        if len(name) == 0:
            self.show("empty output file name")
            return
        if not g.os_path_exists(theDir):
            self.show("output directory not found: " + theDir)
        else:
            try:
                if self.appendOutput:
                    self.show("appending to " + self.outputFileName)
                    self.outputFile = open(self.outputFileName, "ab")
                else:
                    self.show("writing to " + self.outputFileName)
                    self.outputFile = open(self.outputFileName, "wb")
            except:
                self.outputFile = None
                self.show("exception opening output file")
                g.es_exception()
Exemple #5
0
def createFrame (fileName):
    
    """Create a LeoFrame during Leo's startup process."""
    
    import leoGlobals as g

    # Try to create a frame for the file.
    if fileName:
        if g.os_path_exists(fileName):
            ok, frame = g.openWithFileName(fileName,None)
            if ok:
                return frame.c,frame

    # Create a _new_ frame & indicate it is the startup window.
    c,frame = g.app.newLeoCommanderAndFrame(fileName=fileName)
    frame.setInitialWindowGeometry()
    frame.resizePanesToRatio(frame.ratio,frame.secondary_ratio)
    frame.startupWindow = True
    # 3/2/05: Call the 'new' hook for compatibility with plugins.
    g.doHook("new",old_c=None,c=c,new_c=c)

    # Report the failure to open the file.
    if fileName:
        g.es("File not found: " + fileName)

    return c,frame
Exemple #6
0
def computeHomeDir():
    
    """Returns the user's home directory."""
    
    import leoGlobals as g

    encoding = startupEncoding()
    dotDir = g.os_path_abspath('./',encoding)
    try: #bombs if there isn't a HOME environment variable set
        home = os.getenv('HOME')#,default=dotDir)
    except:
        home = dotDir
        
    if len(home) > 1 and home[0]=='%' and home[-1]=='%':
	    # Get the indirect reference to the true home.
	    home = os.getenv(home[1:-1],default=dotDir)
    
    home = g.os_path_abspath(home,encoding)
    
    if (
        not home or
        not g.os_path_exists(home,encoding) or
        not g.os_path_isdir(home,encoding)
    ):
        home = None

    return home
Exemple #7
0
def createFrame (fileName,relativeFileName):

    """Create a LeoFrame during Leo's startup process."""

    import leoGlobals as g

    # Try to create a frame for the file.
    if fileName and g.os_path_exists(fileName):
        ok, frame = g.openWithFileName(relativeFileName or fileName,None)
        if ok: return frame.c,frame

    # Create a _new_ frame & indicate it is the startup window.
    c,frame = g.app.newLeoCommanderAndFrame(
        fileName=fileName,
        relativeFileName=relativeFileName,
        initEditCommanders=True)
    frame.setInitialWindowGeometry()
    frame.resizePanesToRatio(frame.ratio,frame.secondary_ratio)
    frame.startupWindow = True
    if frame.c.chapterController:
        frame.c.chapterController.finishCreate()
        frame.c.setChanged(False) # Clear the changed flag set when creating the @chapters node.
    # Call the 'new' hook for compatibility with plugins.
    g.doHook("new",old_c=None,c=c,new_c=c)

    # Report the failure to open the file.
    if fileName:
        g.es("File not found:",fileName)

    return c,frame
Exemple #8
0
def open_in_emacs (tag,keywords,val=None):

    c = keywords.get('c')
    p = keywords.get('p')
    if not c or not p: return
    v = p.v

    # Search g.app.openWithFiles for a file corresponding to v.
    for d in g.app.openWithFiles:
        if d.get('v') == id(v):
            path = d.get('path','') ; break
    else: path = ''

    if (
        not g.os_path_exists(path) or
        not hasattr(v,'OpenWithOldBody') or
        v.bodyString() != v.OpenWithOldBody
    ):
        # Open a new temp file.
        if path:
            # Remove the old file and the entry in g.app.openWithFiles.
            os.remove(path)
            g.app.openWithFiles = [d for d in g.app.openWithFiles if d.get('path') != path]
            os.system(_emacs_cmd)
        v.OpenWithOldBody=v.bodyString() # Remember the old contents
        # open the node in emacs (note the space after _emacs_cmd)
        data = "os.spawnl", _emacs_cmd, None
        c.openWith(data=data)
    else:
        # Reopen the old temp file.
        os.system(_emacs_cmd)

    return val
 def openOutputFile (self):
     
     if self.outputFileName == None:
         return
     theDir,name = g.os_path_split(self.outputFileName)
     if len(theDir) == 0:
         self.show("empty output directory")
         return
     if len(name) == 0:
         self.show("empty output file name")
         return
     if not g.os_path_exists(theDir):
         self.show("output directory not found: " + theDir)
     else:
         try:
             if self.appendOutput:
                 self.show("appending to " + self.outputFileName)
                 self.outputFile = open(self.outputFileName,"ab")
             else:
                 self.show("writing to " + self.outputFileName)
                 self.outputFile = open(self.outputFileName,"wb")
         except:
             self.outputFile = None
             self.show("exception opening output file")
             g.es_exception()
Exemple #10
0
def createFrame(fileName):
    """Create a LeoFrame during Leo's startup process."""

    import leoGlobals as g

    # g.trace(g.app.tkEncoding,fileName)

    # Try to create a frame for the file.
    if fileName:
        fileName = g.os_path_join(os.getcwd(), fileName)
        fileName = g.os_path_normpath(fileName)
        if g.os_path_exists(fileName):
            ok, frame = g.openWithFileName(fileName, None)
            if ok:
                return frame.c, frame

    # Create a new frame & indicate it is the startup window.
    c, frame = g.app.gui.newLeoCommanderAndFrame(fileName=None)
    frame.setInitialWindowGeometry()
    frame.startupWindow = True

    # Report the failure to open the file.
    if fileName:
        g.es("File not found: " + fileName)

    return c, frame
Exemple #11
0
def createFrame (fileName):
    
    """Create a LeoFrame during Leo's startup process."""
    
    import leoGlobals as g
    #import java
    #import java.util.concurrent as concur
    # g.trace(g.app.tkEncoding,fileName)

    # Try to create a frame for the file.
    #class CreateCommander( concur.Callable ):
        
    #    def call( self ):
    if fileName:
        if g.os_path_exists(fileName):
            ok, frame = g.openWithFileName(fileName,None)
            if ok:
                return frame.c,frame
    
            # Create a new frame & indicate it is the startup window.
    c,frame = g.app.gui.newLeoCommanderAndFrame(fileName=fileName)
    frame.setInitialWindowGeometry()
    frame.startupWindow = True
    #        return c, frame
            
    #ft = concur.FutureTask( CreateCommander() )
    #java.awt.EventQueue.invokeAndWait( ft )
    #c,frame = ft.get()
    
    # Report the failure to open the file.
    if fileName:
        g.es("File not found: " + fileName)

    return c,frame
Exemple #12
0
def computeLoadDir():
    
    """Returns the directory containing leo.py."""
    
    import leoGlobals as g

    try:
        import leo
        encoding = startupEncoding()
        path = g.os_path_abspath(leo.__file__,encoding)
        #path = g.os_path_abspath( leoGlobals.__file__, encoding )
        
        if path:
            loadDir = g.os_path_dirname(path,encoding)
        else: loadDir = None
            
        if (
            not loadDir or
            not g.os_path_exists(loadDir,encoding) or
            not g.os_path_isdir(loadDir,encoding)
        ):
            loadDir = os.getcwd()
            print "Using emergency loadDir:",repr(loadDir)
        
        loadDir = g.os_path_abspath(loadDir,encoding)
        # g.es("load dir: %s" % (loadDir),color="blue")
        return loadDir
    except:
        print "Exception getting load directory"
        import traceback ; traceback.print_exc()
        return None
Exemple #13
0
def computeGlobalConfigDir():
    
    # None of these suppresses warning about sys.leo_config_directory
    # __pychecker__ = '--no-objattrs --no-modulo1 --no-moddefvalue'
    
    import leoGlobals as g
    
    encoding = startupEncoding()

    try:
        theDir = sys.leo_config_directory
    except AttributeError:
        theDir = g.os_path_join(g.app.loadDir,"..","config")
        
    if theDir:
        theDir = g.os_path_abspath(theDir)
        
    if (
        not theDir or
        not g.os_path_exists(theDir,encoding) or
        not g.os_path_isdir(theDir,encoding)
    ):
        theDir = None
    
    return theDir
Exemple #14
0
def loadHandlers():

    """Load all enabled plugins from the plugins directory"""
    
    plugins_path = g.os_path_join(g.app.loadDir,"..","plugins")
    manager_path = g.os_path_join(plugins_path,"pluginsManager.txt")
    
    files = glob.glob(g.os_path_join(plugins_path,"*.py"))
    #print files
    files = [g.os_path_abspath(theFile) for theFile in files]

    #@    << set enabled_files from pluginsManager.txt >>
    #@+node:ekr.20031218072017.3441:<< set enabled_files from pluginsManager.txt >>
    if not g.os_path_exists(manager_path):
        return
        
    # New in 4.3: The first reference to a plugin in pluginsManager.txt controls.
    enabled_files = []
    disabled_files = []
    try:
        theFile = open(manager_path)
        lines = theFile.readlines()
        for s in lines:
            s = s.strip()
            if s:
                if g.match(s,0,"#"):
                    s = s[1:].strip()
                    # Kludge: ignore comment lines containing a blank or not ending in '.py'.
                    if s and s.find(' ') == -1 and s[-3:] == '.py':
                        path = g.os_path_abspath(g.os_path_join(plugins_path,s))
                        if path not in enabled_files and path not in disabled_files:
                            # print 'disabled',path
                            disabled_files.append(path)
                else:
                    #print g.os_path_join( plugins_path, s )
                    path = g.os_path_abspath(g.os_path_join(plugins_path,s))
                    if path not in enabled_files and path not in disabled_files:
                        # print 'enbled',path
                        enabled_files.append(path)
        theFile.close()
    except IOError:
        g.es("Can not open: " + manager_path)
        # Don't import leoTest initially.  It causes problems.
        import leoTest ; leoTest.fail()
        return
        
    #@-node:ekr.20031218072017.3441:<< set enabled_files from pluginsManager.txt >>
    #@nl
    
    # Load plugins in the order they appear in the enabled_files list.
    if files and enabled_files:
        for theFile in enabled_files:
            if theFile in files:
                loadOnePlugin(theFile)
                
    # Note: g.plugin_signon adds module names to g.app.loadedPlugins 
    if g.app.loadedPlugins:
        g.es("%d plugins loaded" % (len(g.app.loadedPlugins)), color="blue")
 def destroyOpenWithFileWithDict (self,theDict):
     
     path = theDict.get("path")
     if path and g.os_path_exists(path):
         try:
             os.remove(path)
             print "deleting temp file:", g.shortFileName(path)
         except:
             print "can not delete temp file:", path
             
     # Remove theDict from the list so the gc can recycle the Leo window!
     g.app.openWithFiles.remove(theDict)
 def browser (self,n):
     
     types = [
         ("C/C++ files","*.c"),
         ("C/C++ files","*.cpp"),
         ("C/C++ files","*.h"),
         ("C/C++ files","*.hpp"),
         ("Java files","*.java"),
         ("Pascal files","*.pas"),
         ("Python files","*.py"),
         ("Text files","*.txt"),
         ("All files","*") ]
 
 
     import java.io as io
     f = io.File( "tmp" )
     parent = f.getParentFile()
     f = None
     
     fc = swing.JFileChooser( parent )
     fc.setDialogTitle( "Choose compare file" + n )
     
     
     haveseen = {}
     for z in types:
         if z[ 0 ] in haveseen:
             haveseen[ z[ 0 ] ].extend( z[1] )
         else:
             bf = self.brwsfilter( z )
             fc.addChoosableFileFilter( bf )
             haveseen[ z[ 0 ] ] = bf
         
     result = fc.showOpenDialog( self.top )
     if result == fc.APPROVE_OPTION:
         fileName = fc.getSelectedFile().getAbsolutePath()
     else:
         fileName = None
         
     #fileName = tkFileDialog.askopenfilename(
     #    title="Choose compare file" + n,
     #    filetypes=types,
     #    defaultextension=".txt")
         
     if fileName and len(fileName) > 0:
         # The dialog also warns about this, so this may never happen.
         if not g.os_path_exists(fileName):
             self.show("not found: " + fileName)
             fileName = None
     else: fileName = None
         
     return fileName
Exemple #17
0
    def browser(self, n):

        types = [("C/C++ files", "*.c"), ("C/C++ files", "*.cpp"),
                 ("C/C++ files", "*.h"), ("C/C++ files", "*.hpp"),
                 ("Java files", "*.java"), ("Pascal files", "*.pas"),
                 ("Python files", "*.py"), ("Text files", "*.txt"),
                 ("All files", "*")]

        import java.io as io
        f = io.File("tmp")
        parent = f.getParentFile()
        f = None

        fc = swing.JFileChooser(parent)
        fc.setDialogTitle("Choose compare file" + n)

        haveseen = {}
        for z in types:
            if z[0] in haveseen:
                haveseen[z[0]].extend(z[1])
            else:
                bf = self.brwsfilter(z)
                fc.addChoosableFileFilter(bf)
                haveseen[z[0]] = bf

        result = fc.showOpenDialog(self.top)
        if result == fc.APPROVE_OPTION:
            fileName = fc.getSelectedFile().getAbsolutePath()
        else:
            fileName = None

        #fileName = tkFileDialog.askopenfilename(
        #    title="Choose compare file" + n,
        #    filetypes=types,
        #    defaultextension=".txt")

        if fileName and len(fileName) > 0:
            # The dialog also warns about this, so this may never happen.
            if not g.os_path_exists(fileName):
                self.show("not found: " + fileName)
                fileName = None
        else:
            fileName = None

        return fileName
def onIconDoubleClick(tag,keywords):

    v = keywords.get("p") or keywords.get("v") # Use p for 4.2 code base, v for 4.1 code base.
    c = keywords.get("c")
    # g.trace(c)

    if c and v:
        h = v.headString().strip()
        if h and h[0]!='@':
            #@            << find path and start file >>
            #@+node:ekr.20040828103325.4:<< find path and start file >>
            # Set the base directory by searching for @folder directives in ancestors.
            thisdir = os.path.abspath(os.curdir) # remember the current dir
            basedir = thisdir[:] # use current dir as default.
            parv = v.parent() # start with parent
            while parv: # stop when no more parent found
                p = parv.headString().strip()
                if g.match_word(p,0,'@folder'):
                    basedir = p[8:] # take rest of headline as pathname
                    break # we found the closest @folder
                else:
                    parv = parv.parent() # try the parent of the parent
            
            fname = os.path.join(basedir,h) # join path and filename
            startdir, filename = os.path.split(fname)
            try:
                os.chdir(startdir)
                dirfound = 1
            except:
                g.es(startdir+' - folder not found')
                dirfound = 0
            
            if dirfound:
                fullpath = g.os_path_join(startdir,filename)
                fullpath = g.os_path_abspath(fullpath)
                if g.os_path_exists(filename):
                    try:
                        # Warning: os.startfile usually does not throw exceptions.
                        os.startfile(filename) # Try to open the file; it may not work for all file types.
                    except Exception:
                        g.es(filename+' - file not found in '+startdir)
                        g.es_exception()
                else:
                    g.es('%s not found in %s' % (filename,startdir),color='blue')
            os.chdir(thisdir) # restore the original current dir.
Exemple #19
0
def open_in_vim (tag,keywords,val=None):
    
    # g.trace(keywords)
    c = keywords.get('c')
    p = keywords.get("p")
    if not c or not p: return
    v = p.v
    
    vim_cmd = c.config.getString('vim_cmd') or _vim_cmd
    vim_exe = c.config.getString('vim_exe') or _vim_exe
    
    # Search g.app.openWithFiles for a file corresponding to v.
    for d in g.app.openWithFiles:
        if d.get('v') == id(v):
            path = d.get('path','') ; break
    else: path = ''

    # if the body has changed we need to open a new 
    # temp file containing the new body in vim
    if (
        not g.os_path_exists(path) or 
        not hasattr(v,'OpenWithOldBody') or
        v.bodyString() != v.OpenWithOldBody
    ):
        # Open a new temp file.
        if path:
            # Remove the old file and the entry in g.app.openWithFiles.
            os.remove(path)
            g.app.openWithFiles = [d for d in g.app.openWithFiles if d.get('path') != path]
            os.system(vim_cmd+"--remote-send '<C-\\><C-N>:bd! "+path+"<CR>'")
        v.OpenWithOldBody=v.bodyString() # Remember the previous contents.
        if subprocess:
            # New code by Jim Sizemore.
            data = "subprocess.Popen",[vim_exe, "--servername", "LEO", "--remote-silent"], None
            c.openWith(data=data)
        else:
            # Works, but gives weird error message on first open of Vim.
            # note the space after --remote.
            data = "os.spawnv", [vim_exe,"--servername LEO ","--remote "], None
            c.openWith(data=data)
    else:
        # Reopen the old temp file.
        os.system(vim_cmd+"--remote-send '<C-\\><C-N>:e "+path+"<CR>'")
        
    return val
Exemple #20
0
    def startup (self):

        path = self.lib ; global dbs, libraries

        try:
            # 'r' and 'w' fail if the database doesn't exist.
            # 'c' creates it only if it doesn't exist.
            # 'n' always creates a new database.
            if dbs.has_key(path):
                self.db = dbs [path]
                self.trace('Library reusing: %s' % path)
            elif g.os_path_exists(path):
                self.db = anydbm.open(path,"rw")
                self.trace('Library reopening: %s' % path)
                dbs [path] = self.db
            else:
                self.trace('Library creating: %s' % path)
                self.db = anydbm.open(path,"c")
            self.path = path
        except Exception, err:
            g.es('Library: Exception creating database: %s' % (err,))
Exemple #21
0
def insertWikiPicture (colorer,filename,s,i):

    '''Insert the picture with the given filename.'''

    # g.trace(i,filename)

    c = colorer.c ; p = c.currentPosition() ; w = c.frame.body.bodyCtrl

    if not p or not g.os_path_exists(filename):
        return

    try:
        # Create the image
        if PIL: # Allow many kinds of images.
            from PIL import Image, ImageTk
            image = Image.open(filename)
            photo = ImageTk.PhotoImage(image)
        else: # Allow only .gif or .pgm images.
            photo = Tk.PhotoImage(master=g.app.root, file=filename)
            image = None

        index = colorer.index(i)
        if filename in w.mark_names() and w.image_names():
            # This isn't quite correct because
            # it won't allow copies of the picture.
            pass
            # g.trace('**picture exists',filename)
        else:
            index = colorer.index(i)
            # g.trace('**inserting picture',i,index)
            image = c.frame.body.bodyCtrl.image_create(index,image=photo,padx=0)
            w.mark_set(filename,index)
            # Keep references so images stay on the canvas.
            # The reference to photo must appear, even though it is not used.
            colorer.image_references.append((photo,image,index),)
    except:
        if not PIL:
            g.es_print('PIL not loaded: wiki images must be .gif or .pgm files.',color='blue')
        else:
            g.es_exception()
Exemple #22
0
 def getDetails(self, text):
     """Get the details of the plugin
     
     We look for
         __version__
         hooks
         config
         commands
     """
     self.is_plugin = self.hasImport(text, "leoPlugins")
     self.version = self.getPattern(text, r'__version__\s*=\s*"(.*?)"', "-")
     # Allow both single and double triple-quoted strings.
     match1 = self.getMatch(text, r'"""(.*?)"""')
     match2 = self.getMatch(text, r"'''(.*?)'''")
     pat1 = match1 and match1.group(1)
     pat2 = match2 and match2.group(1)
     if pat1 and pat2:
         # Take the first pattern that appears.
         self.description = g.choose(match1.start() < match2.start(), pat1,
                                     pat2)
     else:
         # Take whatever.
         self.description = pat1 or pat2 or 'Unknown'
     # g.trace('%4d %s' % (len(self.description),self.name))
     self.commands = sets.Set(self.getPatterns(text, "def cmd_(\w*?)\("))
     self.handlers = sets.Set(
         self.getPatterns(text, r'registerHandler\("(.*?)"'))
     # Look for the matching .ini file.
     ini_file_name = g.os_path_join(g.app.loadDir, "..", "plugins",
                                    self.getName(self.filename) + ".ini")
     ini_file_name = g.os_path_abspath(ini_file_name)
     self.has_config = g.os_path_exists(ini_file_name)
     self.hash = sha.sha(text).hexdigest()
     self.can_read = True
     if USE_PRIORITY:
         self.priority = self.getPattern(
             text, r'__plugin_priority__\s*=\s*(.*?)$', "-")
     self.has_toplevel = self.hasPattern(text, "def topLevelMenu")
Exemple #23
0
    def loadIcons(self):
        """Load icons and images and set up module level variables."""

        self.treeIcons = icons = []
        self.namedIcons = namedIcons = {}

        path = g.os_path_abspath(g.os_path_join(g.app.loadDir, '..', 'Icons'))
        if g.os_path_exists(g.os_path_join(path, 'box01.GIF')):
            ext = '.GIF'
        else:
            ext = '.gif'

        for i in range(16):
            icon = self.loadIcon(g.os_path_join(path, 'box%02d'%i + ext))
            icons.append(icon)

        for name, ext in (
            ('lt_arrow_enabled', '.gif'),
            ('rt_arrow_enabled', '.gif'),
            ('lt_arrow_disabled', '.gif'),
            ('rt_arrow_disabled', '.gif'),
            ('plusnode', '.gif'),
            ('minusnode', '.gif'),
            ('Leoapp', '.GIF')
        ):
            icon = self.loadIcon(g.os_path_join(path, name + ext))
            if icon:
                namedIcons[name] = icon
            else:
                g.es_print( '~~~~~~~~~~~ failed to load', name)

        self.plusBoxIcon = namedIcons['plusnode']
        self.minusBoxIcon = namedIcons['minusnode']
        self.appIcon = namedIcons['Leoapp']

        self.globalImages = {}
 def getDetails(self, text):
     """Get the details of the plugin
     
     We look for
         __version__
         hooks
         config
         commands
     """
     self.is_plugin = self.hasImport(text, "leoPlugins") 
     self.version = self.getPattern(text, r'__version__\s*=\s*"(.*?)"', "-")
     # Allow both single and double triple-quoted strings.
     match1 = self.getMatch(text, r'"""(.*?)"""')
     match2 = self.getMatch(text, r"'''(.*?)'''")
     pat1 = match1 and match1.group(1)
     pat2 = match2 and match2.group(1)
     if pat1 and pat2:
         # Take the first pattern that appears.
         self.description = g.choose(match1.start() < match2.start(),pat1,pat2)
     else:
         # Take whatever.
         self.description = pat1 or pat2 or 'Unknown'
     # g.trace('%4d %s' % (len(self.description),self.name))
     self.commands = sets.Set(self.getPatterns(text, "def cmd_(\w*?)\("))
     self.handlers = sets.Set(self.getPatterns(text, r'registerHandler\("(.*?)"'))
     # Look for the matching .ini file.
     ini_file_name = g.os_path_join(
         g.app.loadDir,"..","plugins",
         self.getName(self.filename)+".ini")
     ini_file_name = g.os_path_abspath(ini_file_name)
     self.has_config = g.os_path_exists(ini_file_name)
     self.hash = sha.sha(text).hexdigest()
     self.can_read = True
     if USE_PRIORITY:
         self.priority = self.getPattern(text, r'__plugin_priority__\s*=\s*(.*?)$', "-")
     self.has_toplevel = self.hasPattern(text, "def topLevelMenu")
Exemple #25
0
    def setLeoID (self,verbose=True):

        tag = ".leoID.txt"
        homeDir = g.app.homeDir
        globalConfigDir = g.app.globalConfigDir
        loadDir = g.app.loadDir

        verbose = not g.app.unitTesting
        #@    << return if we can set leoID from sys.leoID >>
        #@+node:ekr.20031218072017.1979:<< return if we can set leoID from sys.leoID>>
        # This would be set by in Python's sitecustomize.py file.

        # 7/2/04: Use hasattr & getattr to suppress pychecker warning.
        # We also have to use a "non-constant" attribute to suppress another warning!

        nonConstantAttr = "leoID"

        if hasattr(sys,nonConstantAttr):
            g.app.leoID = getattr(sys,nonConstantAttr)
            if verbose and not g.app.unitTesting:
                g.es_print("leoID=",g.app.leoID,spaces=False,color='red')
            return
        else:
            g.app.leoID = None
        #@-node:ekr.20031218072017.1979:<< return if we can set leoID from sys.leoID>>
        #@nl
        #@    << return if we can set leoID from "leoID.txt" >>
        #@+node:ekr.20031218072017.1980:<< return if we can set leoID from "leoID.txt" >>
        for theDir in (homeDir,globalConfigDir,loadDir):
            # N.B. We would use the _working_ directory if theDir is None!
            if theDir:
                try:
                    fn = g.os_path_join(theDir,tag)
                    f = open(fn,'r')
                    s = f.readline()
                    f.close()
                    if s and len(s) > 0:
                        g.app.leoID = s.strip()
                        if verbose and not g.app.unitTesting:
                            g.es('leoID=',g.app.leoID,' (in ',theDir,')',spaces=False,color="red")
                        return
                    elif verbose and not g.app.unitTesting:
                        g.es('empty ',tag,' (in ',theDir,')',spaces=False,color = "red")
                except IOError:
                    g.app.leoID = None
                except Exception:
                    g.app.leoID = None
                    g.es_print('Unexpected exception in app.setLeoID',color='red')
                    g.es_exception()
        #@-node:ekr.20031218072017.1980:<< return if we can set leoID from "leoID.txt" >>
        #@nl
        #@    << return if we can set leoID from os.getenv('USER') >>
        #@+node:ekr.20060211140947.1:<< return if we can set leoID from os.getenv('USER') >>
        try:
            theId = os.getenv('USER')
            if theId:
                if verbose and not g.app.unitTesting:
                    g.es("using os.getenv('USER'):",repr(theId),color='red')
                g.app.leoID = theId
                return

        except Exception:
            pass
        #@-node:ekr.20060211140947.1:<< return if we can set leoID from os.getenv('USER') >>
        #@nl
        #@    << put up a dialog requiring a valid id >>
        #@+node:ekr.20031218072017.1981:<< put up a dialog requiring a valid id >>
        # New in 4.1: get an id for gnx's.  Plugins may set g.app.leoID.

        # Create an emergency gui and a Tk root window.
        g.app.createTkGui("startup")

        # Bug fix: 2/6/05: put result in g.app.leoID.
        g.app.leoID = g.app.gui.runAskLeoIDDialog()

        # g.trace(g.app.leoID)
        g.es('leoID=',repr(g.app.leoID),spaces=False,color="blue")
        #@-node:ekr.20031218072017.1981:<< put up a dialog requiring a valid id >>
        #@nl
        #@    << attempt to create leoID.txt >>
        #@+node:ekr.20031218072017.1982:<< attempt to create leoID.txt >>
        for theDir in (homeDir,globalConfigDir,loadDir):
            # N.B. We would use the _working_ directory if theDir is None!
            if theDir:
                try:
                    fn = g.os_path_join(theDir,tag)
                    f = open(fn,'w')
                    f.write(g.app.leoID)
                    f.close()
                    if g.os_path_exists(fn):
                        g.es_print('',tag,'created in',theDir,color='red')
                        return
                except IOError:
                   pass

                g.es('can not create',tag,'in',theDir,color='red')
Exemple #26
0
    def importDir (self,dir,compteur,compteurglobal):

        """ La routine récursive de lecture des fichiers """

        if not g.os_path_exists(dir):
            if language == 'french':
                g.es("Ce répertoire n'existe pas: %s" + dir)
            else:
                g.es("No such Directory: %s" + dir)
            return compteur, compteurglobal # EKR

        head,tail = g.os_path_split(dir)
        c = self.c ; v = c.currentVnode()
        try:
            #ici, on liste le contenu du répertoire
            body=""
            #@        << listdir >>
            #@+node:ekr.20050301083306.11:<< listdir >>
            try:
                fichiers = os.listdir(dir)
                dossiers = []
                for f in fichiers:
                    if compteur == 25:
                        self.esfm("\n")
                        compteur = 0
                    # mettre ici le code de création des noeuds
                    path = g.os_path_join(dir,f)
                    # est-ce un fichier ?
                    if g.os_path_isfile(path):
                        body += (f+"\n")
                    else:
                        # c'est alors un répertoire
                        dossiers.append(path)

                    self.esfm(".")
                    compteur += 1
                    compteurglobal += 1
            except Exception:
                if language == 'french':
                    g.es("erreur dans listage fichiers...")
                else:
                    g.es("os.listdir error...")
                g.es_exception()
            #@-node:ekr.20050301083306.11:<< listdir >>
            #@nl
            retour = c.importCommands.createHeadline(v,body,tail)
            #sélectionne le noeud nouvellement créé
            c.selectVnode(retour)
            if len(dossiers) > 0:
                for d in dossiers:
                    compteur,compteurglobal = self.importDir(d,compteur,compteurglobal)
            c.setChanged(True)
            #sélectionne le noeud parent
            c.selectVnode(v)
        except:
            if language == 'french':
                g.es("erreur d'insertion de noeud...")
            else:
                g.es("error while creating vnode...")
            g.es_exception()

        return compteur, compteurglobal