Beispiel #1
0
def loadHandlers(tag):

    """Load all enabled plugins from the plugins directory"""

    def pr (*args,**keys):
        if not g.app.unitTesting:
            g.es_print(*args,**keys)

    plugins_path = g.os_path_abspath(g.os_path_join(g.app.loadDir,"..","plugins"))
    files = glob.glob(g.os_path_join(plugins_path,"*.py"))
    files = [g.os_path_abspath(theFile) for theFile in files]

    s = g.app.config.getEnabledPlugins()
    if not s: return

    if not g.app.silentMode:
        pr('@enabled-plugins found in %s' % (
            g.app.config.enabledPluginsFileName),color='blue')

    enabled_files = getEnabledFiles(s,plugins_path)

    # 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 0:
        if g.app.loadedPlugins:
            pr("%d plugins loaded" % (len(g.app.loadedPlugins)), color="blue")
Beispiel #2
0
def computeLoadDir():
    """Returns the directory containing leo.py."""

    import leoGlobals as g

    # g.trace(g.app.tkEncoding)

    try:
        import leo
        path = g.os_path_abspath(leo.__file__)

        if sys.platform == "win32":  # "mbcs" exists only on Windows.
            path = g.toUnicode(path, "mbcs")
        elif sys.platform == "dawwin":
            path = g.toUnicode(path, "utf-8")
        else:
            path = g.toUnicode(path, g.app.tkEncoding)

        if path:
            loadDir = g.os_path_dirname(path)
        else:
            loadDir = None
        if not loadDir:
            loadDir = g.os_path_abspath(os.getcwd())
            print "Using emergency loadDir:", repr(loadDir)

        encoding = g.choose(sys.platform == "dawwin", "utf-8",
                            g.app.tkEncoding)  # 11/18/03
        loadDir = g.toUnicode(loadDir, encoding)  # 10/20/03
        return loadDir
    except:
        print "Exception getting load directory"
        import traceback
        traceback.print_exc()
        return None
Beispiel #3
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
Beispiel #4
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
Beispiel #5
0
def getPathAndBase( p):
    path = None
    for z in p.self_and_parents_iter( copy = True):
        s = z.bodyString()  
        d = g.get_directives_dict(s)
        if d.has_key("path"):
            start = d[ 'path']
            end = s.find( "\n", start)
            if end == -1:
                s = s[ start:]
            else:
                s = s[ start: end]
                    
            stokens = s.split()
            if len( stokens)	>= 2:
                path = stokens[ 1 ]
                break
        
    if path == None:
        a =  p.atThinFileNodeName()
        ap =  g.os_path_abspath( a )
        f = java.io.File( ap )
        path = f.getParent()
            
    statuspath = g.os_path_abspath( p.atThinFileNodeName())	
    return path, statuspath
Beispiel #6
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")
Beispiel #7
0
    def runOpenFileDialog(self,title,filetypes,defaultextension,multiple=False):

        """Create and run an Tkinter open file dialog ."""

        # __pychecker__ = '--no-argsused' # defaultextension not used.

        initialdir = g.app.globalOpenDir or g.os_path_abspath(os.getcwd())

        if multiple:
            # askopenfilenames requires Python 2.3 and Tk 8.4.
            version = '.'.join([str(sys.version_info[i]) for i in (0,1,2)])
            if (
                g.CheckVersion(version,"2.3") and
                g.CheckVersion(self.root.getvar("tk_patchLevel"),"8.4")
            ):
                files = tkFileDialog.askopenfilenames(
                    title=title,filetypes=filetypes,initialdir=initialdir)
                # g.trace(files)
                return list(files)
            else:
                # Get one file and return it as a list.
                theFile = tkFileDialog.askopenfilename(
                    title=title,filetypes=filetypes,initialdir=initialdir)
                return [theFile]
        else:
            # Return a single file name as a string.
            return tkFileDialog.askopenfilename(
                title=title,filetypes=filetypes,initialdir=initialdir)
Beispiel #8
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
Beispiel #9
0
def runSaveFileDialog(initialfile=None,
                      title=None,
                      filetypes=None,
                      defaultextension=None):
    """Call runGtkDialogs save file dialog."""

    initialdir = g.app.globalOpenDir or g.os_path_abspath(os.getcwd())

    data = {
        'dialog': 'filechooser',
        'title': title,
        'initialdir': initialdir,
        'filetypes': filetypes,
        'defaultextension': defaultextension,
        'action': 'save'
    }

    ok, data = callGtkDialogs(data)
    if not ok:
        return oldsave(initialfile=initialfile,
                       title=title,
                       filetypes=none,
                       defaultextension=none)

    if data is None:
        return ''

    return data['result']
Beispiel #10
0
def runSaveFileDialog(initialfile=None,title=None,filetypes=None,defaultextension=None):

    """Call runGtkDialogs save file dialog."""


    initialdir=g.app.globalOpenDir or g.os_path_abspath(os.getcwd())


    data = {
        'dialog': 'filechooser',
        'title': title,
        'initialdir': initialdir,
        'filetypes': filetypes,
        'defaultextension': defaultextension,
        'action': 'save'
    }

    ok, data = callGtkDialogs(data)
    if not ok:
        return oldsave(initialfile=initialfile,title=title,filetypes=none,defaultextension=none)


    if data is None:
        return ''

    return data['result']
Beispiel #11
0
def callGtkDialogs(data, path='runGtkDialogs.py.txt'):


    data = pickle.dumps(data)

    path = g.os_path_abspath(g.os_path_join(g.app.loadDir, '..', 'plugins', path))

    command = [ pythoncommand or 'python', path, data ] 


    try:
        o = Popen(command, stdout=PIPE)

        o.wait()
        ok = True
    except:

        ok = False

    if not ok:
        g.es('error running gtk file chooser\nreverting to tk dialogs', color='red')
        return False, None

    data = o.communicate()[0].rstrip()

    ret = o.returncode


    if  ret or not data:
        return True, None

    return True, pickle.loads(data)
Beispiel #12
0
def runOpenFileDialog(title=None,filetypes=None,defaultextension=None,multiple=False):

    """Call runGtkDialogs open file(s) dialog."""


    initialdir = g.app.globalOpenDir or g.os_path_abspath(os.getcwd())

    data = {
        'dialog': 'filechooser',
        'title': title,
        'initialdir': initialdir,
        'filetypes': filetypes,
        'defaultextension': defaultextension,
        'multiple': multiple,
        'action': 'open',
    }


    ok, data = callGtkDialogs(data)

    if not ok:
        return oldopen(title=title,filetypes=filetypes,defaultextension=defaultextension,multiple=multiple)


    if data is None:
        return ''
    return data['result']
Beispiel #13
0
def runOpenFileDialog(title=None,
                      filetypes=None,
                      defaultextension=None,
                      multiple=False):
    """Call runGtkDialogs open file(s) dialog."""

    initialdir = g.app.globalOpenDir or g.os_path_abspath(os.getcwd())

    data = {
        'dialog': 'filechooser',
        'title': title,
        'initialdir': initialdir,
        'filetypes': filetypes,
        'defaultextension': defaultextension,
        'multiple': multiple,
        'action': 'open',
    }

    ok, data = callGtkDialogs(data)

    if not ok:
        return oldopen(title=title,
                       filetypes=filetypes,
                       defaultextension=defaultextension,
                       multiple=multiple)

    if data is None:
        return ''
    return data['result']
Beispiel #14
0
def callGtkDialogs(data, path='runGtkDialogs.py.txt'):

    data = pickle.dumps(data)

    path = g.os_path_abspath(
        g.os_path_join(g.app.loadDir, '..', 'plugins', path))

    command = [pythoncommand or 'python', path, data]

    try:
        o = Popen(command, stdout=PIPE)

        o.wait()
        ok = True
    except:

        ok = False

    if not ok:
        g.es('error running gtk file chooser\nreverting to tk dialogs',
             color='red')
        return False, None

    data = o.communicate()[0].rstrip()

    ret = o.returncode

    if ret or not data:
        return True, None

    return True, pickle.loads(data)
Beispiel #15
0
    def fixdefault (self,libN,libname):

        if libname == 'default': libname = 'default/library.dbm'

        if libname.find('default') != -1:
            pluginspath = g.os_path_join(g.app.loadDir,'../',"plugins")
            libname = g.os_path_normpath(g.os_path_abspath(
                libname.replace('default',pluginspath,1)))
            # setattr(libconfig,libN,libname)

        elif libname.find('~') != -1:
            libname = g.os_path_normpath(g.os_path_abspath(
                libname.replace('~',g.app.homeDir,1)))
            # setattr(libconfig,libN,libname)

        return libname
Beispiel #16
0
  def runOpenFileDialog(self, title, filetypes, defaultextension, multiple=False):
    import os

    initialdir = g.app.globalOpenDir or g.os_path_abspath(os.getcwd())
    ret = raw_input("Open which %s file (from %s?) > " % (`filetypes`, initialdir))
    if multiple:
      return [ret,]
    return ret
Beispiel #17
0
def runSaveFileDialog(initialfile=None,title=None,filetypes=None,defaultextension=None):

    """Call zenity's save file dialog."""

    trace and g.trace()

    initialdir=g.app.globalOpenDir or g.os_path_abspath(os.getcwd())

    return callZenity(title, save=True)
Beispiel #18
0
def runOpenFileDialog(title=None,filetypes=None,defaultextension=None,multiple=False):

    """Call zenity's open file(s) dialog."""

    trace and g.trace()

    initialdir = g.app.globalOpenDir or g.os_path_abspath(os.getcwd())

    return callZenity(title, multiple=multiple)
Beispiel #19
0
 def deleteit(result):
     if result is not None:
         # Remove old one
         tc = self.templateCollection
         tc.remove(tc.find(result))
         filename = "%s.tpl" % result
         folder = g.os_path_abspath(self.folder)
         os.remove(g.os_path_join(folder, filename))
         g.es('deleted template %s from %s' % (filename,folder),color='blue')
Beispiel #20
0
    def runSaveFileDialog(self,initialfile,title,filetypes,defaultextension):

        """Create and run an Tkinter save file dialog ."""

        # __pychecker__ = '--no-argsused' # defaultextension not used.

        initialdir=g.app.globalOpenDir or g.os_path_abspath(os.getcwd()),

        return tkFileDialog.asksaveasfilename(
            initialdir=initialdir,initialfile=initialfile,
            title=title,filetypes=filetypes)
Beispiel #21
0
def getEnabledFiles (s,plugins_path):

    enabled_files = []
    disabled_files = []
    for s in g.splitLines(s):
        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:
                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 'enabled',path
                    enabled_files.append(path)

    return enabled_files
Beispiel #22
0
 def showPlugin(self, plugin):
     """Show a plugin"""
     self.name.setentry(plugin.name)
     self.version.setentry(plugin.version)
     self.filename.setentry(g.os_path_abspath(plugin.filename))  # EKR
     self.status.setentry(plugin.enabled)
     self.has_ini.setentry(g.choose(plugin.has_config, "Yes", "No"))
     self.has_toplevel.setentry(g.choose(plugin.has_toplevel, "Yes", "No"))
     if USE_PRIORITY:
         self.priority.setentry(plugin.priority)
     self.description.settext(plugin.description.strip())
     self.commands.setlist(plugin.commands)
     self.handlers.setlist(plugin.handlers)
     self.requires.setlist(plugin.requires)
Beispiel #23
0
def profile_leo ():

    """Gather and print statistics about Leo"""

    import profile, pstats
    import leoGlobals as g

    # name = "c:/prog/test/leoProfile.txt"
    name = g.os_path_abspath(g.os_path_join(g.app.loadDir,'..','test','leoProfile.txt'))

    profile.run('leo.run()',name)

    p = pstats.Stats(name)
    p.strip_dirs()
    p.sort_stats('cum','file','name')
    p.print_stats()
 def showPlugin(self, plugin):
     """Show a plugin"""
     self.name.setentry(plugin.name)
     self.version.setentry(plugin.version)
     self.filename.setentry(g.os_path_abspath(plugin.filename)) # EKR
     self.status.setentry(plugin.enabled)
     self.has_ini.setentry(
         g.choose(plugin.has_config,"Yes","No"))
     self.has_toplevel.setentry(
         g.choose(plugin.has_toplevel,"Yes","No"))
     if USE_PRIORITY:
         self.priority.setentry(plugin.priority)
     self.description.settext(plugin.description.strip())
     self.commands.setlist(plugin.commands)
     self.handlers.setlist(plugin.handlers)
     self.requires.setlist(plugin.requires)
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.
Beispiel #26
0
    def save(self,c):

        """Save this template"""

        template_path = g.app.config.getString(c,'template_path')
        if template_path:
            filename = g.os_path_join(template_path, "%s.tpl" % self.name)
        else:
            filename = g.os_path_join(
                g.app.loadDir,"..","plugins", "templates", "%s.tpl" % self.name)

        f = file(filename, "w")

        g.es('writing template %s to %s' % (self.name,g.os_path_abspath(filename)),color='blue')

        try:
            f.write(repr(self))
        finally:
            f.close()
Beispiel #27
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")
 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")
Beispiel #29
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 = {}
Beispiel #30
0
def writeFullFileName(fname):

    path = g.os_path_join(os.getcwd(), fname)
    path = g.os_path_abspath(path)

    g.es('rst written: ' + path, color="blue")
#print 'leoID=', g.app.leoID
Id = g.choose(g.app.leoID, g.app.leoID, 'Leo')
tname = sanitize_('tmptest' + Id )+ '.py'

#use lower if on *nix. 
#windos may set TEMP and TMP by default, case insensitive.
#tmpfile = g.os_path_join(os.environ['tmp'],'tmptest.py')

tmpfile = g.os_path_join(pypath, 'Lib/site-packages', tname)
#
tname = sanitize_('python' + Id )+ '.html'
#htmlfile = g.os_path_join( os.getenv( 'tmp' ), tname )
try:
    htmlfile = g.os_path_joing( os.getenv( 'tmp' ), tname )
except:
    htmlfile = g.os_path_join( g.os_path_abspath( './' ), tname )
#os.getenv('tmp', default= g.os_path_abspath('./')), tname)


del Id, tname

#replace forwardslash to backslash if required
#frd slash usually ok except for cd and sometimes openfile
#with filename as parameter in windos frdslash might be taken as option
if sys.platform[:3] == 'win':
    #generally win doesn't care mixed slashes
    #but you might pass py, pypath et al thru here too
    tmpfile = g.os_path_abspath(tmpfile)  #.replace('/', '\\')
    htmlfile = g.os_path_abspath(htmlfile)

#enable the print if not sure its working to satisfaction.
Beispiel #32
0
    def runFileDialog(self,
        title='Open File',
        filetypes=None,
        action='open',
        multiple=False,
        initialFile=None
    ):

        g.trace()

        """Display an open or save file dialog.

        'title': The title to be shown in the dialog window.

        'filetypes': A list of (name, pattern) tuples.

        'action': Should be either 'save' or 'open'.

        'multiple': True if multiple files may be selected.

        'initialDir': The directory in which the chooser starts.

        'initialFile': The initial filename for a save dialog.

        """

        initialdir=g.app.globalOpenDir or g.os_path_abspath(os.getcwd())

        if action == 'open':
            btns = (
                gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                gtk.STOCK_OPEN, gtk.RESPONSE_OK
            )
        else:
            btns = (
                gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                gtk.STOCK_SAVE, gtk.RESPONSE_OK
            )

        gtkaction = g.choose(
            action == 'save',
            gtk.FILE_CHOOSER_ACTION_SAVE, 
            gtk.FILE_CHOOSER_ACTION_OPEN
        )

        dialog = gtk.FileChooserDialog(
            title,
            None,
            gtkaction,
            btns
        )

        try:

            dialog.set_default_response(gtk.RESPONSE_OK)
            dialog.set_do_overwrite_confirmation(True)
            dialog.set_select_multiple(multiple)
            if initialdir:
                dialog.set_current_folder(initialdir)

            if filetypes:

                for name, patern in filetypes:
                    filter = gtk.FileFilter()
                    filter.set_name(name)
                    filter.add_pattern(patern)
                    dialog.add_filter(filter)

            response = dialog.run()
            print 'dialog response' , response

            if response == gtk.RESPONSE_OK:

                if multiple:
                    result = dialog.get_filenames()
                else:
                    result = dialog.get_filename()

            elif response == gtk.RESPONSE_CANCEL:
                result = None

        finally:

            dialog.destroy()

        print 'dialog result' , result

        return result
Beispiel #33
0
def abspath(*args):
    return g.os_path_abspath(g.os_path_join(*args))
 def __init__(self, filename):
 
     """Initialize the plug-in"""
 
     # Import the file to find out some interesting stuff
     # Do not use the imp module: we only want to import these files once!
     self.mod = self.doc = self.version = None
     self.filename = g.os_path_abspath(filename)
     try:
         self.mod = __import__(g.os_path_splitext(g.os_path_basename(filename))[0])
         if not self.mod: return
         #
         self.group = getattr(self.mod, "__plugin_group__", None)
         if self.group:
             PluginDatabase.addPlugin(self, self.group)
         # g.trace('Plugin',self.mod)
         try:
             name = self.mod.__plugin_name__
         except AttributeError:
             name = self.mod.__name__
         self.name = self.getNiceName(name)
         try:
             self.priority = self.mod.__plugin_priority__
         except AttributeError:
             self.priority = 200 - ord(self.name[0])
         #
         self.doc = self.mod.__doc__
         self.version = self.mod.__dict__.get("__version__","<unknown>") # EKR: 3/17/05
         # if self.version: print self.version,g.shortFileName(filename)
     except ImportError:
         # s = 'Can not import %s in plugins_menu plugin' % g.shortFileName(filename)
         # print s ; g.es(s,color='blue')
         return
     except Exception:
         s = 'Unexpected exception in plugins_menu plugin importing %s' % filename
         print s ; g.es(s,color='red')
         return
 
     #@    << Check if this can be configured >>
     #@+node:EKR.20040517080555.5:<< Check if this can be configured >>
     # Look for a configuration file
     self.configfilename = "%s.ini" % os.path.splitext(filename)[0]
     self.hasconfig = os.path.isfile(self.configfilename)
     #@-node:EKR.20040517080555.5:<< Check if this can be configured >>
     #@nl
     #@    << Check if this has an apply >>
     #@+node:EKR.20040517080555.6:<< Check if this has an apply >>
     #@+at 
     #@nonl
     # Look for an apply function ("applyConfiguration") in the module.
     # 
     # This is used to apply changes in configuration from the properties 
     # window
     #@-at
     #@@c
     
     self.hasapply = hasattr(self.mod, "applyConfiguration")
     #@-node:EKR.20040517080555.6:<< Check if this has an apply >>
     #@nl
     #@    << Look for additional commands >>
     #@+node:EKR.20040517080555.7:<< Look for additional commands >>
     #@+at 
     #@nonl
     # Additional commands can be added to the plugin menu by having 
     # functions in the module called "cmd_whatever". These are added to 
     # the main menu and will be called when clicked
     #@-at
     #@@c
     
     self.othercmds = {}
     
     for item in self.mod.__dict__.keys():
         if item.startswith("cmd_"):
             self.othercmds[item[4:]] = self.mod.__dict__[item]
     #@-node:EKR.20040517080555.7:<< Look for additional commands >>
     #@nl
     #@    << Look for toplevel menu item >>
     #@+node:pap.20041009131822:<< Look for toplevel menu item >>
     #@+at 
     #@nonl
     # Check to see if there is a toplevel menu item - this will be used 
     # instead of the default About
     #@-at
     #@@c
     
     try:
         self.hastoplevel = self.mod.__dict__["topLevelMenu"]
     except KeyError:
         self.hastoplevel = False
#@-at
#@@c

#print 'leoID=', g.app.leoID
Id = g.choose(g.app.leoID, g.app.leoID, 'Leo')
tname = sanitize_('tmptest' + Id )+ '.py'

#use lower if on *nix. 
#windos may set TEMP and TMP by default, case insensitive.
#tmpfile = g.os_path_join(os.environ['tmp'],'tmptest.py')

tmpfile = g.os_path_join(pypath, 'Lib/site-packages', tname)
#
tname = sanitize_('python' + Id )+ '.html'
htmlfile = g.os_path_join(
           os.getenv('tmp', default= g.os_path_abspath('./')), tname)


del Id, tname

#replace forwardslash to backslash if required
#frd slash usually ok except for cd and sometimes openfile
#with filename as parameter in windos frdslash might be taken as option
if sys.platform[:3] == 'win':
    #generally win doesn't care mixed slashes
    #but you might pass py, pypath et al thru here too
    tmpfile = g.os_path_abspath(tmpfile)  #.replace('/', '\\')
    htmlfile = g.os_path_abspath(htmlfile)

#enable the print if not sure its working to satisfaction.
#print tmpfile, htmlfile, py, pypath
Beispiel #36
0
    def __init__(self, filename):
        """Initialize the plug-in"""

        # Import the file to find out some interesting stuff
        # Do not use the imp module: we only want to import these files once!
        self.mod = self.doc = self.version = None
        self.filename = g.os_path_abspath(filename)
        try:
            self.mod = __import__(
                g.os_path_splitext(g.os_path_basename(filename))[0])
            if not self.mod: return
            #
            self.group = getattr(self.mod, "__plugin_group__", None)
            if self.group:
                PluginDatabase.addPlugin(self, self.group)
            # g.trace('Plugin',self.mod)
            try:
                name = self.mod.__plugin_name__
            except AttributeError:
                name = self.mod.__name__
            self.name = self.getNiceName(name)
            try:
                self.priority = self.mod.__plugin_priority__
            except AttributeError:
                self.priority = 200 - ord(self.name[0])
            #
            self.doc = self.mod.__doc__
            self.version = self.mod.__dict__.get("__version__",
                                                 "<unknown>")  # EKR: 3/17/05
            # if self.version: print self.version,g.shortFileName(filename)
        except ImportError:
            # s = 'Can not import %s in plugins_menu plugin' % g.shortFileName(filename)
            # print s ; g.es(s,color='blue')
            return
        except Exception:
            s = 'Unexpected exception in plugins_menu plugin importing %s' % filename
            print s
            g.es(s, color='red')
            return

        #@    << Check if this can be configured >>
        #@+node:EKR.20040517080555.5:<< Check if this can be configured >>
        # Look for a configuration file
        self.configfilename = "%s.ini" % os.path.splitext(filename)[0]
        self.hasconfig = os.path.isfile(self.configfilename)
        #@-node:EKR.20040517080555.5:<< Check if this can be configured >>
        #@nl
        #@    << Check if this has an apply >>
        #@+node:EKR.20040517080555.6:<< Check if this has an apply >>
        #@+at
        #@nonl
        # Look for an apply function ("applyConfiguration") in the module.
        #
        # This is used to apply changes in configuration from the properties
        # window
        #@-at
        #@@c

        self.hasapply = hasattr(self.mod, "applyConfiguration")
        #@-node:EKR.20040517080555.6:<< Check if this has an apply >>
        #@nl
        #@    << Look for additional commands >>
        #@+node:EKR.20040517080555.7:<< Look for additional commands >>
        #@+at
        #@nonl
        # Additional commands can be added to the plugin menu by having
        # functions in the module called "cmd_whatever". These are added to
        # the main menu and will be called when clicked
        #@-at
        #@@c

        self.othercmds = {}

        for item in self.mod.__dict__.keys():
            if item.startswith("cmd_"):
                self.othercmds[item[4:]] = self.mod.__dict__[item]
        #@-node:EKR.20040517080555.7:<< Look for additional commands >>
        #@nl
        #@    << Look for toplevel menu item >>
        #@+node:pap.20041009131822:<< Look for toplevel menu item >>
        #@+at
        #@nonl
        # Check to see if there is a toplevel menu item - this will be used
        # instead of the default About
        #@-at
        #@@c

        try:
            self.hastoplevel = self.mod.__dict__["topLevelMenu"]
        except KeyError:
            self.hastoplevel = False
Beispiel #37
0
def writeFullFileName (fname):
    
    path = g.os_path_join(os.getcwd(),fname)
    path = g.os_path_abspath(path)
    
    g.es('rst written: ' + path,color="blue")