Beispiel #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()
Beispiel #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 addJarsToPath( self ): #change: added for JyLeo
     
     import sys
     import java
     import java.lang as jl
     jpath = g.os_path_join(g.app.loadDir,"..","jars") 
     ppath = g.os_path_join(g.app.loadDir,"..","plugins")
     import os
     psep = os.pathsep
     cp = [ jl.System.getProperty( "java.class.path" ), ]
     #for z in jl.System.getProperty( "java.class.path" ).split( os.pathsep ):
     #    print z
     def visit( args, directory, files, cp = cp ):
         
         for z in files:
             #if z.endswith( ".jar" ):
             sys.path.append( g.os_path_join( directory, z ) )
             #print g.os_path_join( directory, z )
             #cp[ 0 ] = "%s%s%s" %( cp[ 0 ], psep, g.os_path_join( directory, z ) )
             f = java.io.File( g.os_path_join( directory, z ) )
             can_p = f.getCanonicalPath()
             cp[ 0 ] = "%s%s%s" % ( cp[ 0 ], psep, can_p )
             #print f.getCanonicalPath()
     
     import os    
     
     os.path.walk( jpath, visit, None )
     sys.path.append( g.app.loadDir )
     sys.path.append( ppath )
     jl.System.setProperty( "java.class.path", cp[ 0 ] )
     paths = cp[ 0 ].split( ':' )
Beispiel #4
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 #5
0
 def __init__( self, c ):
     self.c = c
     self.browser = browser.WebBrowser()
     self.base = swing.JPanel( java.awt.BorderLayout() )
     self.base.add( self.browser )
     bf = swing.JToolBar()
     path = g.os_path_join( g.app.loadDir,"..","Icons/webbrowser", "left.png" )
     ii = swing.ImageIcon( path )
     self.bbutton = back = swing.JButton( ii )
     back.setText( "Back" )
     back.setHorizontalTextPosition( swing.SwingConstants.CENTER )
     back.setVerticalTextPosition( swing.SwingConstants.BOTTOM )
     back.actionPerformed = lambda event : self.back()
     bf.add( back )
     path = g.os_path_join( g.app.loadDir,"..","Icons/webbrowser", "right.png" )
     ii = swing.ImageIcon( path )
     self.fbutton = forward = swing.JButton( ii )
     forward.setText( "Forward" )
     forward.setHorizontalTextPosition( swing.SwingConstants.CENTER )
     forward.setVerticalTextPosition( swing.SwingConstants.BOTTOM )
     forward.actionPerformed = lambda event: self.forward()
     bf.add( forward )
     path = g.os_path_join( g.app.loadDir,"..","Icons/webbrowser", "reload.png" )
     ii = swing.ImageIcon( path )
     refresh = swing.JButton( ii )
     refresh.setText( "Reload" )
     refresh.setHorizontalTextPosition( swing.SwingConstants.CENTER )
     refresh.setVerticalTextPosition( swing.SwingConstants.BOTTOM )
     refresh.actionPerformed = lambda event: self.browser.refresh()
     bf.add( refresh )
     self.base.add( bf, java.awt.BorderLayout.NORTH )
     jp2 = swing.JPanel( java.awt.BorderLayout())
     self.jtf = swing.JTextField()
     CutCopyPaste( self.jtf )
     jp2.add( self.jtf )
     path = g.os_path_join( g.app.loadDir,"..","Icons", "do-it.gif" )
     ii = swing.ImageIcon( path )
     self.jb = swing.JButton( ii )
     self.jb.actionPerformed = self.go
     jp2.add( self.jb, java.awt.BorderLayout.EAST )
     jp3 = swing.JPanel( java.awt.GridLayout( 2, 1 ) )
     jp3.add( jp2 )
     jp4 = swing.JPanel()
     headline = swing.JButton( "Goto Headline" )
     headline.actionPerformed = self.goToHeadline
     jp4.add( headline )
     store = swing.JButton( "Store Page In Node" )
     store.actionPerformed = self.storePage
     jp4.add( store )
     feed = swing.JButton( "Feed Tree To Browser" )
     feed.actionPerformed = self.feedNodesBodyContents
     jp4.add( feed )
     jp3.add( jp4 )
     self.base.add( jp3, java.awt.BorderLayout.SOUTH )
     self.history = []
     self.historypointer = -1
     self.ignore = 0
     self.enableButtons()
     self.browser.addWebBrowserListener( self )
def unsetDefaultParams():
	
	print "unsetDefaultParams"
	
	pats = (("use_plugins = 0","use_plugins = 1"),)

	replacePatterns(g.os_path_join("config","leoConfig.leo"),pats)
	replacePatterns(g.os_path_join("config","leoConfig.txt"),pats)
Beispiel #7
0
def unsetDefaultParams():

    print "unsetDefaultParams"

    pats = (("use_plugins = 0", "use_plugins = 1"), )

    replacePatterns(g.os_path_join("config", "leoConfig.leo"), pats)
    replacePatterns(g.os_path_join("config", "leoConfig.txt"), pats)
Beispiel #8
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 visit( args, directory, files, cp = cp ):
     
     for z in files:
         #if z.endswith( ".jar" ):
         sys.path.append( g.os_path_join( directory, z ) )
         #print g.os_path_join( directory, z )
         #cp[ 0 ] = "%s%s%s" %( cp[ 0 ], psep, g.os_path_join( directory, z ) )
         f = java.io.File( g.os_path_join( directory, z ) )
         can_p = f.getCanonicalPath()
         cp[ 0 ] = "%s%s%s" % ( cp[ 0 ], psep, can_p )
 def initLocalCollection(self):
     """Initialize the local plugin collection"""
 
     # Get the local plugins information
     self.local = LocalPluginCollection()
     self.local.initFrom(g.os_path_join(g.app.loadDir,"..","plugins"))
 
     # Get the active status of the plugins
     self.enable = EnableManager()
     self.enable.initFrom(g.os_path_join(g.app.loadDir,"..","plugins"))
     self.local.setEnabledStateFrom(self.enable)
Beispiel #11
0
    def initLocalCollection(self):
        """Initialize the local plugin collection"""

        # Get the local plugins information
        self.local = LocalPluginCollection()
        self.local.initFrom(g.os_path_join(g.app.loadDir, "..", "plugins"))

        # Get the active status of the plugins
        self.enable = EnableManager()
        self.enable.initFrom(g.os_path_join(g.app.loadDir, "..", "plugins"))
        self.local.setEnabledStateFrom(self.enable)
Beispiel #12
0
    def __init__(self, emacs):

        self.emacs = emacs
        path, file = g.os_path_split(g.app.loadDir)
        path = g.os_path_join(path, "swingmacs_exts", "lib_locations.txt")
        self.path = path
        llfile = java.io.File(path)
        data = []
        if llfile.exists():
            fos = java.io.FileInputStream(llfile)
            isr = java.io.InputStreamReader(fos)
            brd = java.io.BufferedReader(isr)

            while 1:
                line = brd.readLine()
                if line == None:
                    break
                else:
                    data.append(line)

        else:
            llfile.createNewFile()

        self.libraries = {}
        for z in data:
            nl = z.split('=')
            if len(nl) == 2:
                name, location = nl
                self.libraries[name] = location

        self.jd = None
Beispiel #13
0
 def parse_opml_file (self,inputFileName):
 
     if not inputFileName or not inputFileName.endswith('.opml'):
         return None
         
     c = self.c
     path = g.os_path_normpath(g.os_path_join(g.app.loadDir,inputFileName))
     
     try: f = open(path)
     except IOError:
         g.trace('can not open %s'%path)
         return None
     try:
         try:
             node = None
             parser = xml.sax.make_parser()
             # Do not include external general entities.
             # The actual feature name is "http://xml.org/sax/features/external-general-entities"
             parser.setFeature(xml.sax.handler.feature_external_ges,0)
             handler = contentHandler(c,inputFileName)
             parser.setContentHandler(handler)
             parser.parse(f)
             node = handler.getNode()
         except xml.sax.SAXParseException:
             g.es_print('Error parsing %s' % (inputFileName),color='red')
             g.es_exception()
             return None
         except Exception:
             g.es_print('Unexpected exception parsing %s' % (inputFileName),color='red')
             g.es_exception()
             return None
     finally:
         f.close()
         return node
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 replacePatterns(file, pats):

    try:
        path = os.getcwd()
        name = g.os_path_join(path, file)
        f = open(name)
    except:
        print "*****", file, "not found"
        return
    try:
        data = f.read()
        f.close()
        changed = False
        for pat1, pat2 in pats:
            newdata = data.replace(pat1, pat2)
            if data != newdata:
                changed = True
                data = newdata
                print file, "replaced", pat1, "by", pat2
        if changed:
            f = open(name, "w")
            f.write(data)
            f.close()
    except:
        import traceback
        traceback.print_exc()
        sys.exit()
    def attachLeoIcon(self, window):
        """Attach the Leo icon to a window."""

        sicon = g.os_path_join(g.app.loadDir, "..", "Icons", "Leoapp.GIF")
        #ii = swing.ImageIcon( "../Icons/Leosplash.GIF" )
        ii = swing.ImageIcon(sicon)
        window.setIconImage(ii.getImage())
Beispiel #17
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)
    def run(self):
        self.splash = splash = swing.JWindow()
        splash.setAlwaysOnTop(1)
        cpane = splash.getContentPane()
        rp = splash.getRootPane()
        tb = sborder.TitledBorder("Leo")
        tb.setTitleJustification(tb.CENTER)
        rp.setBorder(tb)
        splash.setBackground(awt.Color.ORANGE)
        dimension = awt.Dimension(400, 400)
        splash.setPreferredSize(dimension)
        splash.setSize(400, 400)

        sicon = g.os_path_join(g.app.loadDir, "..", "Icons", "Leosplash.GIF")
        #ii = swing.ImageIcon( "../Icons/Leosplash.GIF" )
        ii = swing.ImageIcon(sicon)
        image = swing.JLabel(ii)
        image.setBackground(awt.Color.ORANGE)
        cpane.add(image)
        self.splashlabel = splashlabel = swing.JLabel("Leo Starting....")
        splashlabel.setBackground(awt.Color.ORANGE)
        splashlabel.setForeground(awt.Color.BLUE)
        cpane.add(splashlabel, awt.BorderLayout.SOUTH)
        w, h = self._calculateCenteredPosition(splash)
        splash.setLocation(w, h)
        splash.visible = True
Beispiel #19
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
    def loadPlugin(self, p):

        global atPluginNodes

        c = self.c
        tag = "@plugin"
        h = p.headString()
        assert (g.match(h, 0, tag))

        # Get the name of the module.
        theFile = h[len(tag):].strip()
        if theFile[-3:] == ".py":
            theFile = theFile[:-3]
        theFile = g.toUnicode(theFile, g.app.tkEncoding)

        if not atPluginNodes:
            g.es("disabled @plugin: %s" % (theFile), color="blue")
        elif theFile in g.app.loadedPlugins:
            g.es("plugin already loaded: %s" % (theFile), color="blue")
        else:
            plugins_path = g.os_path_join(g.app.loadDir, "..", "plugins")
            theModule = g.importFromPath(theFile,
                                         plugins_path,
                                         pluginName=__name__,
                                         verbose=False)
            if theModule:
                g.es("plugin loaded: %s" % (theFile), color="blue")
                g.app.loadedPlugins.append(theFile)
            else:
                g.es("can not load plugin: %s" % (theFile), color="blue")
 def __init__( self, emacs  ):
     
     self.emacs = emacs
     path,file = g.os_path_split(g.app.loadDir)
     path = g.os_path_join(path,"swingmacs_exts","lib_locations.txt") 
     self.path = path
     llfile = java.io.File( path )
     data = []
     if llfile.exists():
         fos = java.io.FileInputStream( llfile )
         isr = java.io.InputStreamReader( fos )
         brd = java.io.BufferedReader( isr )
         
         while 1:
             line = brd.readLine()
             if line == None:
                 break
             else:
                 data.append( line )
                 
     else:
         llfile.createNewFile()
 
     
     self.libraries = {}
     for z in data:
         nl = z.split( '=' )
         if len( nl ) == 2:
             name, location = nl
             self.libraries[ name ] = location
             
     
     self.jd = None
 def run( self ):
     self.splash = splash = swing.JWindow()
     splash.setAlwaysOnTop( 1 )
     cpane = splash.getContentPane()
     rp = splash.getRootPane()
     tb = sborder.TitledBorder( "Leo" )
     tb.setTitleJustification( tb.CENTER )
     rp.setBorder( tb )
     splash.setBackground( awt.Color.ORANGE )
     dimension = awt.Dimension( 400, 400 )
     splash.setPreferredSize( dimension )
     splash.setSize( 400, 400 )
     
     sicon = g.os_path_join( g.app.loadDir ,"..","Icons","Leosplash.GIF")
     #ii = swing.ImageIcon( "../Icons/Leosplash.GIF" )
     ii = swing.ImageIcon( sicon )
     image = swing.JLabel( ii )
     image.setBackground( awt.Color.ORANGE )
     cpane.add( image )
     self.splashlabel = splashlabel = swing.JLabel( "Leo Starting...." )
     splashlabel.setBackground( awt.Color.ORANGE )
     splashlabel.setForeground( awt.Color.BLUE )
     cpane.add( splashlabel, awt.BorderLayout.SOUTH )
     w, h = self._calculateCenteredPosition( splash )
     splash.setLocation( w, h )
     splash.visible = True
Beispiel #23
0
def getBatchScript ():

    import leoGlobals as g
    windowFlag = False

    name = None ; i = 1 # Skip the dummy first arg.
    while i + 1 < len(sys.argv):
        arg = sys.argv[i].strip().lower()
        if arg in ("--script","-script"):
            name = sys.argv[i+1].strip() ; break
        if arg in ("--script-window","-script-window"):
            name = sys.argv[i+1].strip() ; windowFlag = True ; break
        i += 1

    if not name:
        return None, windowFlag
    name = g.os_path_join(g.app.loadDir,name)
    try:
        f = None
        try:
            f = open(name,'r')
            script = f.read()
            # g.trace("script",script)
        except IOError:
            g.es_print("can not open script file:",name, color="red")
            script = None
    finally:
        if f: f.close()

    # Bug fix 4/27/07: Don't put a return in a finally clause.
    return script, windowFlag
Beispiel #24
0
    def printKeys(self):
        """Print the keys"""
        fname = os.path.abspath(g.os_path_join(g.app.loadDir,"..", "plugins", "keyreport.html"))
        f = file(fname, "w")
        report = ["<html><title>Leo Key Bindings</title><body>"
                  '<link type="text/css" rel="stylesheet" href="keys.css" />',
                  "<table>",
                    "<tr><th colspan=2>Report</th></tr>"
                    "<tr><td>Pane</td><td>%(filter_pane)s</td></tr>"
                    "<tr><td>Key filter</td><td>%(filter_keys)s</td></tr>"
                    "<tr><td>Command filter</td><td>%(filter_commands)s</td></tr>"
                    "<tr><td>Sorted</td><td>%(sort_by)s</td></tr>" 
                  "</table>" % self.__dict__,
                  "<table>",
                    "<tr><th>Pane</th><th>Key</th><th>Command</th></tr>",
        ]

        for item in self.full_bindings:
            _, key, command, pane = item
            report.append("<tr><td>%s</td><td>%s</td><td>%s</td></tr>" % (pane, key, command))

        report.append("</table>")

        f.write("\n".join(report))
        f.close()

        webbrowser.open(fname)
Beispiel #25
0
def getBatchScript ():
    
    import leoGlobals as g
    
    name = None ; i = 1 # Skip the dummy first arg.
    while i + 1 < len(sys.argv):
        arg = sys.argv[i].strip().lower()
        if arg in ("--script","-script"):
            name = sys.argv[i+1].strip() ; break
        i += 1

    if not name:
        return None
    name = g.os_path_join(g.app.loadDir,name)
    try:
        f = None
        try:
            f = open(name,'r')
            script = f.read()
            # g.trace("script",script)
        except IOError:
            g.es("can not open script file: " + name, color="red")
            script = None
    finally:
        if f: f.close()
        return script
 def loadPlugin (self,p):
     
     global atPluginNodes
     
     c = self.c
     tag = "@plugin"
     h = p.headString()
     assert(g.match(h,0,tag))
     
     # Get the name of the module.
     theFile = h[len(tag):].strip()
     if theFile[-3:] == ".py":
         theFile = theFile[:-3]
     theFile = g.toUnicode(theFile,g.app.tkEncoding)
     
     if not atPluginNodes:
         g.es("disabled @plugin: %s" % (theFile),color="blue")
     elif theFile in g.app.loadedPlugins:
         g.es("plugin already loaded: %s" % (theFile),color="blue")
     else:
         plugins_path = g.os_path_join(g.app.loadDir,"..","plugins")
         theModule = g.importFromPath(theFile,plugins_path,
             pluginName=__name__,verbose=False)
         if theModule:
             g.es("plugin loaded: %s" % (theFile),color="blue")
             g.app.loadedPlugins.append(theFile)
         else:
             g.es("can not load plugin: %s" % (theFile),color="blue")
 def attachLeoIcon (self,window):
     """Attach the Leo icon to a window."""
     
     sicon = g.os_path_join( g.app.loadDir,"..","Icons","Leoapp.GIF")
     #ii = swing.ImageIcon( "../Icons/Leosplash.GIF" )
     ii = swing.ImageIcon( sicon )
     window.setIconImage( ii.getImage() )
def replacePatterns (file,pats):

	try:
		path = os.getcwd()
		name  = g.os_path_join(path,file)
		f = open(name)
	except:
		print "*****", file, "not found"
		return
	try:
		data = f.read()
		f.close()
		changed = False
		for pat1,pat2 in pats:
			newdata = data.replace(pat1,pat2)
			if data != newdata:
				changed = True
				data = newdata
				print file,"replaced",pat1,"by",pat2
		if changed:
			f = open(name,"w")
			f.write(data)
			f.close()
	except:
		import traceback ; traceback.print_exc()
		sys.exit()
Beispiel #29
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
def getConfiguration():
    
    """Called when the user presses the "Apply" button on the Properties form"""

    fileName = g.os_path_join(g.app.loadDir,"../","plugins","word_export.ini")
    config = ConfigParser.ConfigParser()
    config.read(fileName)
    return config
 def setPaths(self):
     """Set paths to the plugin locations"""
     self.local_path = g.os_path_join(g.app.loadDir,"..","src")
     self.remote_path = r"cvs.sourceforge.net/viewcvs.py/leo/leo/src"
     self.file_text = "File"
     self.has_enable_buttons = False
     self.has_conflict_buttons = False
     self.install_text = "Install all"
Beispiel #32
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 #33
0
    def createFrame (self):

        """Create the frame for an About Leo dialog."""

        if g.app.unitTesting: return

        frame = self.frame
        theCopyright = self.copyright ; email = self.email
        url = self.url ; version = self.version

        # Calculate the approximate height & width. (There are bugs in Tk here.)
        lines = string.split(theCopyright,'\n')
        height = len(lines) + 8 # Add lines for version,url,email,spacing.
        width = 0
        for line in lines:
            width = max(width,len(line))
        width = max(width,len(url))
        width += 10 # 9/9/02

        frame.pack(padx=6,pady=4)

        self.text = w = g.app.gui.plainTextWidget(
            frame,height=height,width=width,bd=0,bg=frame.cget("background"))
        w.pack(pady=10)

        try:
            bitmap_name = g.os_path_join(g.app.loadDir,"..","Icons","Leoapp.GIF") # 5/12/03
            image = Tk.PhotoImage(file=bitmap_name)
            w.image_create("1.0",image=image,padx=10)
        except Exception:
            pass # This can sometimes happen for mysterious reasons.

        w.insert("end",version) #,tag="version")
        w.tag_add('version','end-%dc' %(len(version)+1),'end-1c')
        w.insert("end",theCopyright) #,tag="copyright")
        w.tag_add('copyright','end-%dc' %(len(theCopyright)+1),'end-1c')
        w.insert("end",'\n')
        w.insert("end",url)
        w.tag_add('url','end-%dc' %(len(url)+1),'end-1c')
        w.insert("end",'\n')
        w.insert("end",email)
        w.tag_add('url','end-%dc' %(len(email)+1),'end-1c')

        w.tag_config("version",justify="center")
        w.tag_config("copyright",justify="center",spacing1="3")
        w.tag_config("url",underline=1,justify="center",spacing1="10")

        w.tag_bind("url","<Button-1>",self.onAboutLeoUrl)
        w.tag_bind("url","<Enter>",self.setArrowCursor)
        w.tag_bind("url","<Leave>",self.setDefaultCursor)

        w.tag_config("email",underline=1,justify="center",spacing1="10")
        w.tag_bind("email","<Button-1>",self.onAboutLeoEmail)
        w.tag_bind("email","<Enter>",self.setArrowCursor)
        w.tag_bind("email","<Leave>",self.setDefaultCursor)

        w.configure(state="disabled")
    def createFrame(self):
        """Create the frame for an About Leo dialog."""

        frame = self.frame
        theCopyright = self.copyright
        email = self.email
        url = self.url
        version = self.version

        # Calculate the approximate height & width. (There are bugs in Tk here.)
        lines = string.split(theCopyright, '\n')
        height = len(lines) + 8  # Add lines for version,url,email,spacing.
        width = 0
        for line in lines:
            width = max(width, len(line))
        width = max(width, len(url))
        width += 10  # 9/9/02

        frame.pack(padx=6, pady=4)

        self.text = text = Tk.Text(frame,
                                   height=height,
                                   width=width,
                                   bd=0,
                                   bg=frame.cget("background"))
        text.pack(pady=10)

        try:
            bitmap_name = g.os_path_join(g.app.loadDir, "..", "Icons",
                                         "Leoapp.GIF")  # 5/12/03
            image = Tk.PhotoImage(file=bitmap_name)
            text.image_create("1.0", image=image, padx=10)
        except:
            g.es("exception getting icon")
            g.es_exception()

        text.insert("end", version, "version")
        text.insert("end", theCopyright, "copyright")
        text.insert("end", '\n')
        text.insert("end", url, "url")  # Add "url" tag.
        text.insert("end", '\n')
        text.insert("end", email, "email")  # Add "email" tag.

        text.tag_config("version", justify="center")
        text.tag_config("copyright", justify="center", spacing1="3")

        text.tag_config("url", underline=1, justify="center", spacing1="10")
        text.tag_bind("url", "<Button-1>", self.onAboutLeoUrl)
        text.tag_bind("url", "<Enter>", self.setArrowCursor)
        text.tag_bind("url", "<Leave>", self.setDefaultCursor)

        text.tag_config("email", underline=1, justify="center", spacing1="10")
        text.tag_bind("email", "<Button-1>", self.onAboutLeoEmail)
        text.tag_bind("email", "<Enter>", self.setArrowCursor)
        text.tag_bind("email", "<Leave>", self.setDefaultCursor)

        text.configure(state="disabled")
Beispiel #35
0
    def attachLeoIcon(self, w):
        """Try to attach a Leo icon to the Leo Window.
        
        Use tk's wm_iconbitmap function if available (tk 8.3.4 or greater).
        Otherwise, try to use the Python Imaging Library and the tkIcon package."""

        if self.bitmap != None:
            # We don't need PIL or tkicon: this is tk 8.3.4 or greater.
            try:
                w.wm_iconbitmap(self.bitmap)
            except:
                self.bitmap = None

        if self.bitmap == None:
            try:
                #@            << try to use the PIL and tkIcon packages to draw the icon >>
                #@+node:ekr.20031218072017.4069:<< try to use the PIL and tkIcon packages to draw the icon >>
                #@+at
                #@nonl
                # This code requires Fredrik Lundh's PIL and tkIcon packages:
                #
                # Download PIL    from
                # http://www.pythonware.com/downloads/index.htm#pil
                # Download tkIcon from http://www.effbot.org/downloads/#tkIcon
                #
                # Many thanks to Jonathan M. Gilligan for suggesting this
                # code.
                #@-at
                #@@c

                import Image, tkIcon, _tkicon

                # Wait until the window has been drawn once before attaching the icon in OnVisiblity.
                def visibilityCallback(event, self=self, w=w):
                    try:
                        self.leoIcon.attach(w.winfo_id())
                    except:
                        pass

                w.bind("<Visibility>", visibilityCallback)
                if not self.leoIcon:
                    # Load a 16 by 16 gif.  Using .gif rather than an .ico allows us to specify transparency.
                    icon_file_name = g.os_path_join(g.app.loadDir, '..',
                                                    'Icons', 'LeoWin.gif')
                    icon_file_name = g.os_path_normpath(icon_file_name)
                    icon_image = Image.open(icon_file_name)
                    if 1:  # Doesn't resize.
                        self.leoIcon = self.createLeoIcon(icon_image)
                    else:  # Assumes 64x64
                        self.leoIcon = tkIcon.Icon(icon_image)
                #@nonl
                #@-node:ekr.20031218072017.4069:<< try to use the PIL and tkIcon packages to draw the icon >>
                #@nl
            except:
                # import traceback ; traceback.print_exc()
                self.leoIcon = None
Beispiel #36
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 #37
0
    def attachLeoIcon (self,w):

        """Try to attach a Leo icon to the Leo Window.

        Use tk's wm_iconbitmap function if available (tk 8.3.4 or greater).
        Otherwise, try to use the Python Imaging Library and the tkIcon package."""

        if self.bitmap != None:
            # We don't need PIL or tkicon: this is tk 8.3.4 or greater.
            try:
                w.wm_iconbitmap(self.bitmap)
            except:
                self.bitmap = None

        if self.bitmap == None:
            try:
                #@            << try to use the PIL and tkIcon packages to draw the icon >>
                #@+node:ekr.20031218072017.4069:<< try to use the PIL and tkIcon packages to draw the icon >>
                #@+at 
                #@nonl
                # This code requires Fredrik Lundh's PIL and tkIcon packages:
                # 
                # Download PIL    from 
                # http://www.pythonware.com/downloads/index.htm#pil
                # Download tkIcon from http://www.effbot.org/downloads/#tkIcon
                # 
                # Many thanks to Jonathan M. Gilligan for suggesting this 
                # code.
                #@-at
                #@@c

                import Image
                import tkIcon # pychecker complains, but this *is* used.

                # Wait until the window has been drawn once before attaching the icon in OnVisiblity.
                def visibilityCallback(event,self=self,w=w):
                    try: self.leoIcon.attach(w.winfo_id())
                    except: pass
                w.bind("<Visibility>",visibilityCallback)

                if not self.leoIcon:
                    # Load a 16 by 16 gif.  Using .gif rather than an .ico allows us to specify transparency.
                    icon_file_name = g.os_path_join(g.app.loadDir,'..','Icons','LeoWin.gif')
                    icon_file_name = g.os_path_normpath(icon_file_name)
                    icon_image = Image.open(icon_file_name)
                    if 1: # Doesn't resize.
                        self.leoIcon = self.createLeoIcon(icon_image)
                    else: # Assumes 64x64
                        self.leoIcon = tkIcon.Icon(icon_image)
                #@-node:ekr.20031218072017.4069:<< try to use the PIL and tkIcon packages to draw the icon >>
                #@nl
            except:
                # import traceback ; traceback.print_exc()
                # g.es_exception()
                self.leoIcon = None
 def __init__ (self):
     
     self.path = g.os_path_join(g.app.loadDir,'..','Icons')
     
     # Create images and set ivars.
     for ivar,icon in (
         ('lt_nav_disabled_image','lt_arrow_disabled.gif'),
         ('lt_nav_enabled_image', 'lt_arrow_enabled.gif'),
         ('rt_nav_disabled_image','rt_arrow_disabled.gif'),
         ('rt_nav_enabled_image', 'rt_arrow_enabled.gif'),
     ):
         image = self.createImage(icon)
         setattr(self,ivar,image)
Beispiel #39
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
 def createFrame (self):
     
     """Create the frame for an About Leo dialog."""
     
     frame = self.frame
     theCopyright = self.copyright ; email = self.email
     url = self.url ; version = self.version
     
     # Calculate the approximate height & width. (There are bugs in Tk here.)
     lines = string.split(theCopyright,'\n')
     height = len(lines) + 8 # Add lines for version,url,email,spacing.
     width = 0
     for line in lines:
         width = max(width,len(line))
     width = max(width,len(url))
     width += 10 # 9/9/02
 
     frame.pack(padx=6,pady=4)
     
     self.text = text = Tk.Text(frame,height=height,width=width,bd=0,bg=frame.cget("background"))
     text.pack(pady=10)
     
     try:
         bitmap_name = g.os_path_join(g.app.loadDir,"..","Icons","Leoapp.GIF") # 5/12/03
         image = Tk.PhotoImage(file=bitmap_name)
         text.image_create("1.0",image=image,padx=10)
     except:
         g.es("exception getting icon")
         g.es_exception()
 
     text.insert("end",version,"version")
     text.insert("end",theCopyright,"copyright")
     text.insert("end",'\n')
     text.insert("end",url,"url") # Add "url" tag.
     text.insert("end",'\n')
     text.insert("end",email,"email") # Add "email" tag.
     
     text.tag_config("version",justify="center")
     text.tag_config("copyright",justify="center",spacing1="3")
     
     text.tag_config("url",underline=1,justify="center",spacing1="10")
     text.tag_bind("url","<Button-1>",self.onAboutLeoUrl)
     text.tag_bind("url","<Enter>",self.setArrowCursor)
     text.tag_bind("url","<Leave>",self.setDefaultCursor)
 
     text.tag_config("email",underline=1,justify="center",spacing1="10")
     text.tag_bind("email","<Button-1>",self.onAboutLeoEmail)
     text.tag_bind("email","<Enter>",self.setArrowCursor)
     text.tag_bind("email","<Leave>",self.setDefaultCursor)
 
     text.configure(state="disabled")
def getFiles(dir):

    from leoGlobals import os_path_join, os_path_split, os_path_splitext

    # Generate the list of modules.
    allFiles = os.listdir(dir)
    files = []
    for f in allFiles:
        head, tail = g.os_path_split(f)
        root, ext = g.os_path_splitext(tail)
        if ext == ".py":
            files.append(g.os_path_join(dir, f))

    return files
def getFiles (dir):
	
	from leoGlobals import os_path_join,os_path_split,os_path_splitext

	# Generate the list of modules.
	allFiles = os.listdir(dir)
	files = []
	for f in allFiles:
		head,tail = g.os_path_split(f)
		root,ext = g.os_path_splitext(tail)
		if ext==".py":
			files.append(g.os_path_join(dir,f))
			
	return files
Beispiel #43
0
def scanForMultiPath (c):

    '''Return a dictionary whose keys are fileNames and whose values are
    lists of paths to which the fileName is to be written.
    New in version 0.6 of this plugin: use ';' to separate paths in @multipath statements.'''

    global multiprefix, multipath
    at = c.atFileCommands ; sep = ';' ; d = {}
    for fileName in files.keys(): # Keys are fileNames, values are root positions.
        root = files[fileName]
        at.scanDefaultDirectory(root) # Using root here may be dubious.
        fileName = g.os_path_join(at.default_directory,fileName)
        # g.trace(fileName,at.default_directory)
        positions = [p.copy() for p in root.self_and_parents_iter()]
        positions.reverse()
        prefix = ''
        for p in positions:
            lines = p.bodyString().split('\n')
            # Calculate the prefix fisrt.
            for s in lines:
                if s.startswith(multiprefix):
                    prefix = s[len(multiprefix):].strip()
            # Handle the paths after the prefix is in place.
            for s in lines:
                if s.startswith(multipath):
                    s = s[len(multipath):].strip()
                    paths = s.split(sep)
                    paths = [z.strip() for z in paths]
                    if prefix:
                        paths = [g.os_path_join(at.default_directory,prefix,z) for z in paths]
                    else:
                        paths = [g.os_path_join(at.default_directory,z) for z in paths]
                    aList = d.get(fileName,[])
                    aList.extend(paths)
                    # g.trace(fileName,aList)
                    d[fileName] = aList
    return d
Beispiel #44
0
def completeFileName (fileName):
    
    import leoGlobals as g
    
    if not fileName:
        return None
        
    # This does not depend on config settings.
    fileName = g.os_path_join(os.getcwd(),fileName)

    head,ext = g.os_path_splitext(fileName)
    if not ext:
        fileName = fileName + ".leo"

    return fileName
Beispiel #45
0
    def __init__(self, c, jtab, i):
        swing.JPanel.__init__(self)
        self.c = c
        self.createWidgets()
        self.tdata = self.CommentTableModel()
        #self.slist.setModel( self.tdata )
        #self.slist.getSelectionModel().addListSelectionListener( self )
        self.commentarea.getDocument().addDocumentListener(self)
        #print self.slist.getCellEditor()
        #self.slist.getDefaultEditor( java.lang.Object.__class__ ).addCellEditorListener( self )
        import leoPlugins
        leoPlugins.registerHandler("select1", self.nodeSelected)
        self.jtab = jtab
        self.i = i

        self.icon = swing.ImageIcon(
            g.os_path_join(g.app.loadDir, "..", "Icons", "Cloud24.gif"))
Beispiel #46
0
    def installPlugin(self):
        """Install the selected plugin"""

        # Write the file
        plugin = self.remote_plugin_list.getSelectedPlugin()
        if not plugin: return

        self.messagebar.message("busy", "Writing file")
        plugin.writeTo(g.os_path_join(g.app.loadDir, "..", "plugins"))
        self.messagebar.message("busy", "Scanning local plugins")
        # Go and check local filesystem for all plugins
        self.initLocalCollection()
        # View is still pointing to the old list, so switch it now
        self.plugin_list.plugins = self.local
        self.plugin_list.populateList()
        plugin.enabled = "Up to date"
        # Update the current list too
        self.remote_plugin_list.populateList()
        self.messagebar.resetmessages('busy')
Beispiel #47
0
    def updateState(self, plugin):
        """Update the state for the given plugin"""
        # Get the filename for the new entry
        if plugin.enabled == "Active":
            newentry = "%s.py" % plugin.name
        else:
            newentry = "#%s.py" % plugin.name

        if plugin.name in self.all:
            # Plugin exists in the management file
            item = self.all[plugin.name]
            # TODO: Unicode issues with the following line??
            self.text = "%s%s%s" % (self.text[:item.start()], str(newentry),
                                    self.text[item.end():])
        else:
            # Plugin doesn't exist - add it at a suitale place
            self.text = "%s%s\n%s" % (self.text[:self.manager.start()],
                                      str(newentry),
                                      self.text[self.manager.start():])

        self.writeFile(g.os_path_join(g.app.loadDir, "..", "plugins"))
    def __init__(self):

        self.cached_pages = {}
        self.seen_elements = []
        self.entered = []
        dbf = jparse.DocumentBuilderFactory.newInstance()
        dbf.setValidating(0)
        dbf.setIgnoringComments(1)
        self.documentBuilder = dbf.newDocumentBuilder()
        self.documentBuilder.setEntityResolver(DoNothingEntityResolver())
        self.htmlPane = swing.JEditorPane("text/html",
                                          "",
                                          editable=0,
                                          hyperlinkUpdate=self.followHyperlink)
        self.jsp = swing.JScrollPane(self.htmlPane)
        self.html_dir = g.os_path_join(g.app.loadDir, "..", "doc", "html",
                                       "leo_TOC.html")
        self.fakeDoc = html.HTMLDocument()
        ifile = io.File(self.html_dir)
        self.homeUrl = url = ifile.getCanonicalFile().toURL()
        self.setPage(url)
Beispiel #49
0
def loadOnePlugin (moduleOrFileName, verbose=False):
    
    global loadedModules
    
    if moduleOrFileName [-3:] == ".py":
        moduleName = moduleOrFileName [:-3]
    else:
        moduleName = moduleOrFileName
    moduleName = g.shortFileName(moduleName)

    if isLoaded(moduleName):
        module = loadedModules.get(moduleName)
        if verbose:
            print 'plugin %s already loaded' % moduleName
        return module

    plugins_path = g.os_path_join(g.app.loadDir,"..","plugins")
    moduleName = g.toUnicode(moduleName,g.app.tkEncoding)
    
    # This import typically results in calls to registerHandler.
    global loadingModuleNameStack
    loadingModuleNameStack.append(moduleName)
    result = g.importFromPath(moduleName,plugins_path)
    if hasattr( result, 'init' ):
        result.init()
    
    loadingModuleNameStack.pop()

    if result:
        loadedModules[moduleName] = result
    
    if verbose:
        if result is None:
            s = 'can not load %s plugin' % moduleName
            print s ; g.es(s,color="blue")
        else:
            print 'loaded %s plugin' % moduleName
    
    return result
def convertRSTfilesToHTML(root_list):

    """This routine creates .html files from all .rst files in root_list, the list of files that have just been tangled."""
    
    for root in root_list: 
        base,fullname = g.os_path_split(root)
        name,ext = g.os_path_splitext(fullname)
        if ext == ".rst":
            file = g.os_path_join(base,name+".html")
            #@            << Convert root to corresponding .html file >>
            #@+node:EKR.20040502194930.3:<< Convert root to corresponding .html file >>
            # Leo will report the execption if docutils is not installed.
            from docutils.core import Publisher 
            from docutils.io import FileInput,StringOutput,StringInput 
            
            # Read .rst file into s.
            f = open(root,"r")
            s = f.read()
            f.close()
            
            # Restucture s into output.
            pub = Publisher() 
            pub.source = StringInput(pub.settings,source=s) 
            pub.destination = StringOutput(pub.settings,encoding="utf-8") 
            pub.set_reader('standalone',None,'restructuredtext') 
            pub.set_writer('html') 
            output = pub.publish()
            
            # EKR: 3/7/03: convert output using the present encoding.
            dict = g.scanDirectives(self.c,p=root)
            encoding = dict.get("encoding",None)
            if encoding == None:
                encoding = g.app.config.default_derived_file_encoding
            output = g.toEncodedString(output,encoding,reportErrors=True) 
            
            # Write the corresponding html file.
            f = open(file,"w")
            f.write(output)
            f.close()
Beispiel #51
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")
Beispiel #52
0
def tangleLeoConfigDotLeo():

    c = None
    name = g.os_path_join("config", "leoConfig.leo")
    oldtop = g.top()
    for frame in g.app.windowList:
        if frame.c.mFileName == name:
            c = frame.c
            break

    if c == None:
        c = g.top()
        flag, frame = g.openWithFileName(name, c)
        if not flag:
            print "can not open ", name
            return
        c = frame.c

    print "Tangling ", name
    g.app.setLog(
        oldtop.frame.log)  # Keep sending messages to the original frame.
    c.tangleCommands.tangleAll()
    c.close()
    g.app.setLog(oldtop.frame.log)
Beispiel #53
0
    def walk(self, arg, path, namelist):

        for z in namelist:
            if z.endswith(".jar") and z.startswith("jazzy"):
                self.addJar(g.os_path_join(path, z))
Beispiel #54
0
                self.addJar(g.os_path_join(path, z))

    def importClass(self, name, clazzname):

        clazz = self.loadClass(clazzname)
        self.resolve(clazz)
        self.gdict[name] = clazz


#@-node:zorcanda!.20051111215311.13:<<ClassLoaderBase2>>
#@nl
load_ok = True
try:

    clb2 = ClassLoaderBase2(globals())
    path = g.os_path_join(g.app.loadDir, "..", "jars")
    os.path.walk(path, clb2.walk, None)  #must find the jazzy-core.jar file...

    #we import the resources via this classloader because just adding the jar file to the sys.path is inadequate
    clb2.importClass("SpellCheckListener",
                     "com.swabunga.spell.event.SpellCheckListener")
    clb2.importClass("SpellChecker", "com.swabunga.spell.event.SpellChecker")
    clb2.importClass("SpellDictionaryHashMap",
                     "com.swabunga.spell.engine.SpellDictionaryHashMap")
    #clb2.importClass( "SpellDictionaryCachedDichoDisk", "com.swabunga.spell.engine.SpellDictionaryCachedDichoDisk" )
    clb2.importClass("StringWordTokenizer",
                     "com.swabunga.spell.event.StringWordTokenizer")

    proppath = g.os_path_join(
        g.app.loadDir, "..", "plugins", "spellingdicts",
        "which.txt")  #we start to determine which dictionary to use
Beispiel #55
0
    def createWidgets(self):

        blayout = java.awt.BorderLayout()
        self.setLayout(blayout)
        #hbox = swing.JPanel( java.awt.GridLayout( 1, 2 ) )
        #tcontainer = swing.JPanel( java.awt.BorderLayout() )
        #self.slist = slist = swing.JTable()
        #slist.getSelectionModel().setSelectionMode( swing.ListSelectionModel.SINGLE_SELECTION )
        #rh = slist.getRowHeight()
        #pvs = slist.getPreferredScrollableViewportSize()
        #pvs2 = pvs.clone()
        #pvs2.height = rh * 5
        #slist.setPreferredScrollableViewportSize( pvs2 )
        #lsp = swing.JScrollPane( slist )
        #tcontainer.add( lsp, java.awt.BorderLayout.CENTER )
        #hbox.add( tcontainer )

        self.commentarea = commentarea = swing.JTextPane()
        #self.__configureEditor()
        CutCopyPaste(commentarea)
        self.csp = csp = swing.JScrollPane(commentarea)
        self.backdrop = swing.JPanel()
        overlay = swing.OverlayLayout(self.backdrop)
        self.backdrop.setLayout(overlay)
        self.backdrop.add(csp)
        mb_ca = swing.JPanel(java.awt.BorderLayout())
        mb_ca.add(self.backdrop, java.awt.BorderLayout.CENTER)
        mb = swing.JMenuBar()
        #jm = swing.JMenu( "Options" )
        #mb.add( jm )
        #jmi = swing.JCheckBoxMenuItem( "Show Comments In Outline" )
        #jm.add( jmi )
        #jmi.setState( 1 )
        #jmi.actionPerformed = self.__showCommentsInOutline
        mb_ca.add(mb, java.awt.BorderLayout.NORTH)
        #hbox.add( mb_ca )
        #self.add( hbox, java.awt.BorderLayout.CENTER )
        self.add(mb_ca)
        self.__configureEditor()
        #jm.add( tcontainer )
        #jm2 = swing.JMenu( "Commentaries" )

        #jm2.add( tcontainer )
        #mb.add( jm2 )

        aballoon = swing.ImageIcon(
            g.os_path_join(g.app.loadDir, "..", "Icons", "AddTBalloon.gif"))
        sballoon = swing.ImageIcon(
            g.os_path_join(g.app.loadDir, "..", "Icons",
                           "SubtractTBalloon.gif"))
        #bpanel = swing.JPanel()
        add = swing.JMenuItem("Add Comment", aballoon)
        add.setToolTipText("Add Comment")
        add.actionPerformed = self.addComment
        remove = swing.JMenuItem("Remove Comment", sballoon)
        remove.setToolTipText("Remove Comment")
        remove.actionPerformed = self.removeComment
        #bpanel.add( add )
        #bpanel.add( remove )
        #tcontainer.add( bpanel, java.awt.BorderLayout.SOUTH )
        jm2 = swing.JMenu("Commentaries")
        jmi = swing.JCheckBoxMenuItem("Show Comments In Outline")
        jm2.add(jmi)
        jmi.setState(1)
        jmi.actionPerformed = self.__showCommentsInOutline
        jm2.add(add)
        jm2.add(remove)
        #jm2.add( tcontainer )
        mb.add(jm2)

        self.ccbmodel = self.CommentCBModel(self)
        self.jcb = jcb = swing.JComboBox(self.ccbmodel)
        #print jcb.getEditor().getEditorComponent().__class__.__bases__
        self.jcb.getEditor().getEditorComponent().getDocument(
        ).addDocumentListener(self.ccbmodel)
        jcb.addItemListener(self)
        jcb.setEditable(1)
        mb.add(jcb)
Beispiel #56
0
    def compare_directories(self, path1, path2):

        # Ignore everything except the directory name.
        dir1 = g.os_path_dirname(path1)
        dir2 = g.os_path_dirname(path2)
        dir1 = g.os_path_normpath(dir1)
        dir2 = g.os_path_normpath(dir2)

        if dir1 == dir2:
            self.show(
                "Directory names are identical.\nPlease pick distinct directories."
            )
            return

        try:
            list1 = os.listdir(dir1)
        except:
            self.show("invalid directory:" + dir1)
            return
        try:
            list2 = os.listdir(dir2)
        except:
            self.show("invalid directory:" + dir2)
            return

        if self.outputFileName:
            self.openOutputFile()
        ok = self.outputFileName == None or self.outputFile
        if not ok:
            return

        # Create files and files2, the lists of files to be compared.
        files1 = []
        files2 = []
        for f in list1:
            junk, ext = g.os_path_splitext(f)
            if self.limitToExtension:
                if ext == self.limitToExtension:
                    files1.append(f)
            else:
                files1.append(f)
        for f in list2:
            junk, ext = g.os_path_splitext(f)
            if self.limitToExtension:
                if ext == self.limitToExtension:
                    files2.append(f)
            else:
                files2.append(f)

        # Compare the files and set the yes, no and fail lists.
        yes = []
        no = []
        fail = []
        for f1 in files1:
            head, f2 = g.os_path_split(f1)
            if f2 in files2:
                try:
                    name1 = g.os_path_join(dir1, f1)
                    name2 = g.os_path_join(dir2, f2)
                    val = filecmp.cmp(name1, name2, 0)
                    if val: yes.append(f1)
                    else: no.append(f1)
                except:
                    self.show("exception in filecmp.cmp")
                    g.es_exception()
                    fail.append(f1)
            else:
                fail.append(f1)

        # Print the results.
        for kind, files in (("----- matches --------",
                             yes), ("----- mismatches -----", no),
                            ("----- not found ------", fail)):
            self.show(kind)
            for f in files:
                self.show(f)

        if self.outputFile:
            self.outputFile.close()
            self.outputFile = None