Пример #1
0
 def spawn_subprocess(self):
 
     args = self.subprocess_arglist
 
     self.rpcpid = os.spawnv(os.P_NOWAIT, sys.executable, args)
     
     g.trace('os.spawnv returns rpcpid',self.rpcpid)
Пример #2
0
 def filename_changed_edit(self, edit):
     
     g.trace(edit)
     
     if 0: # Probably not needed for Leo.
         edit.saved_change_hook()
         try:
             key = self.inversedict[edit]
         except KeyError:
             print "Don't know this EditorWindow object.  (rename)"
             return
         filename = edit.io.filename
         if not filename:
             if key:
                 del self.dict[key]
             self.inversedict[edit] = None
             return
         filename = self.canonize(filename)
         newkey = os.path.normcase(filename)
         if newkey == key:
             return
         if self.dict.has_key(newkey):
             conflict = self.dict[newkey]
             self.inversedict[conflict] = None
             tkMessageBox.showerror(
                 "Name Conflict",
                 "You now have multiple edit windows open for %r" % (filename,),
                 master=self.root)
         self.dict[newkey] = edit
         self.inversedict[edit] = newkey
         if key:
             try:
                 del self.dict[key]
             except KeyError:
                 pass
Пример #3
0
    def bind (self,bind_shortcut,callback):

        """Wrapper for the Tkinter bind menu method."""

        g.trace(bind_shortcut,g.callers())

        return self.top.bind(bind_shortcut,callback)
Пример #4
0
 def undo (self):
 
     """Undo the operation described by the undo parmaters."""
     
     u = self ; c = u.c
     if not u.canUndo(): return
     if not u.getBead(u.bead): return
     if not c.currentPosition(): return
     # g.trace(len(u.beads),u.bead,u.peekBead(u.bead))
 
     c.endEditing()# Make sure we capture the headline for a redo.
     u.undoing = True
     u.redrawFlag = True
     u.updateSetChangedFlag = True
 
     c.beginUpdate()
     if 1: # update...
         try:
             func = u.undoDispatchDict[u.undoType]
         except KeyError:
             s = "Unknown undo key: %s" % u.undoType
             g.trace(s) ; g.es(s, color="red")
             func = None
         if func:
             func()
             if u.updateSetChangedFlag:
                 c.setChanged(True)
                 if u.p: u.p.setDirty(setDescendentsDirty=False)
     c.endUpdate(u.redrawFlag)
 
     u.undoing = False
     u.bead -= 1
     u.setUndoTypes()
Пример #5
0
 def redo (self):
 
     u = self ; c = u.c
     if not u.canRedo(): return
     if not u.getBead(u.bead+1): return
     if not  c.currentPosition(): return
     # g.trace(u.bead+1,len(u.beads),u.peekBead(u.bead+1))
 
     u.redoing = True 
     u.redrawFlag = True
     u.updateSetChangedFlag = True
     
     c.beginUpdate()
     if 1: # update...
         try:
             func = u.redoDispatchDict[u.undoType]
         except KeyError:
             s = "Unknown redo key: %s" % u.undoType
             g.trace(s) ; g.es(s, color="red")
             func = None
         if func:
             func()
             if u.updateSetChangedFlag:
                 c.setChanged(True)
                 if u.p: u.p.setDirty(setDescendentsDirty=False)
     c.endUpdate(u.redrawFlag)
 
     u.redoing = False
     u.bead += 1
     u.setUndoTypes()
Пример #6
0
    def chapterSelectHelper (self,w=None,selectEditor=True):

        c = self.c ; cc = self.cc ; name = self.name

        # g.trace(name,'self.p',self.p) # ,'self.root',self.root) # 'w.leo_p',w and w.leo_p)

        cc.selectedChapter = self

        # Next, recompute p and possibly select a new editor.
        if w:
            assert w == c.frame.body.bodyCtrl
            assert w.leo_p
            # g.trace(name,'w.leo_p',w.leo_p,'p',p)
            self.p = p = self.findPositionInChapter(w.leo_p)
            if p != w.leo_p: g.trace('****** can not happen: lost p',w.leo_p)
        else:
            # This must be done *after* switching roots.
            target_p = self.p or self.root.firstChild() or self.root
            #g.trace(name,'target_p',target_p)
            #g.trace(name,'self.p',self.p,'self.root',self.root)
            self.p = p = self.findPositionInChapter(target_p)
            if selectEditor:
                w = self.findEditorInChapter(p)
                c.frame.body.selectEditor(w) # Switches text.

        c.beginUpdate()
        try:
            if name == 'main' and cc.chaptersNode:
                cc.chaptersNode.contract()    
            c.hoistStack = self.hoistStack[:]
            c.selectPosition(p)
        finally:
            c.endUpdate()
            g.doHook('hoist-changed',c=c)
            c.bodyWantsFocusNow()
Пример #7
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
Пример #8
0
    def setMenuLabel (self,menu,name,label,underline=-1):

        if not menu:
            g.trace("no menu",name)
            return

        items = menu.get_children()

        if type(name) == type(0):
            # "name" is actually an index into the menu.
            if items and len(items) > name :
                item = items[name].GetId()
            else:
                item = None
        else:
            realName = self.getRealMenuName(name)
            realName = realName.replace("&","")
            for item in items:
                if item.getLabel() == realName:
                    break
            else:
                item = None      

        if item:
            label = self.getRealMenuName(label)
            label = label.replace("&","")
            # g.trace(name,label)
            item.setLabel(label, underline)
        else:
            g.trace("no item",name,label)
Пример #9
0
    def selectChapterForPosition (self,p):

        '''
        Select a chapter containing position p.
        Do nothing if p if p does not exist or is in the presently selected chapter.
        '''
        cc = self ; c = cc.c ; trace = False

        if not p or not c.positionExists(p):
            return

        theChapter = cc.getSelectedChapter()
        if not theChapter:
            if trace: g.trace('no chapter')
            return

        if trace: g.trace('selected:',theChapter.name)
        # First, try the presently selected chapter.
        firstName = theChapter.name
        if firstName == 'main' or theChapter.positionIsInChapter(p):
            if trace: g.trace('in chapter:',theChapter.name)
            return

        for name in cc.chaptersDict.keys():
            if name not in (firstName,'main'):
                theChapter = cc.chaptersDict.get(name)
                if theChapter.positionIsInChapter(p):
                    if trace: g.trace('select:',theChapter.name)
                    cc.selectChapterByName(name)
                    return
        else:
            if trace: g.trace('select main')
            cc.selectChapterByName('main')
Пример #10
0
def callZenity(title, multiple=False, save=False, test=False):


    command = [ 'zenity', '--file-selection', '--title=%s'%title]

    if save:
        command.append('--save')

    if multiple:
        command.append('--multiple')


    o = Popen(command, stdout=PIPE)
    o.wait()
    filename = o.communicate()[0].rstrip()

    ret = o.returncode

    if trace:
        g.trace('\n\tfiles', repr(filename))
        print '\treturncode', ret

    if ret:
        trace and g.trace(g.choose(save,'save','open'), 'cancelled')
        return ''

    if multiple:
        return filename.split('|')

    return filename
Пример #11
0
 def priority_clear(self,v):
     
     g.trace(v)
 
     d = self.getUD(v)
     del d['priority']
     self.redraw()
Пример #12
0
 def assignFileIndices (self):
     
     """Assign a file index to all tnodes"""
     
     c = self.c ; nodeIndices = g.app.nodeIndices
 
     nodeIndices.setTimestamp() # This call is fairly expensive.
 
     # Assign missing gnx's, converting ints to gnx's.
     # Always assign an (immutable) index, even if the tnode is empty.
     for p in c.allNodes_iter():
         try: # Will fail for None or any pre 4.1 file index.
             theId,time,n = p.v.t.fileIndex
         except TypeError:
             # Don't convert to string until the actual write.
             p.v.t.fileIndex = nodeIndices.getNewIndex()
             
         # New in 4.4.
         if not hasattr(p.v.gnx):
             p.v.gnx = nodeIndices.getNewIndex()
 
     if 0: # debugging:
         for p in c.allNodes_iter():
             g.trace('v',p.v.gnx)
             g.trace('t',p.v.t.fileIndex)
Пример #13
0
    def createRootWindow(self):
        """Create a hidden Tk root window."""

        if 0:  # Use Tix.
            import Tix
            self.root = root = Tix.Tk()
            #@        << fix problems with menus (XP) >>
            #@+node:ekr.20041125050302:<< fix problems with menus (XP) >>
            try:
                import WmDefault
                WmDefault.setup(root)
                d = {
                    'activebackground': 'DarkBlue',
                    'activeforeground': 'white'
                }  # works
                # d = {'activebackground':'','activeforeground':''} # doesn't work
                WmDefault.addoptions(root, d)
            except ImportError:
                g.trace("can not import WMDefault")
            #@nonl
            #@-node:ekr.20041125050302:<< fix problems with menus (XP) >>
            #@nl
        else:  # Use Tkinter.
            self.root = root = Tk.Tk()

        root.title("Leo Main Window")
        root.withdraw()

        self.setDefaultIcon()
        if g.app.config:
            self.getDefaultConfigFont(g.app.config)

        root.withdraw()

        return root
Пример #14
0
 def createRootWindow(self):
 
     """Create a hidden Tk root window."""
 
     if 0: # Use Tix.
         import Tix
         self.root = root = Tix.Tk()
         #@        << fix problems with menus (XP) >>
         #@+node:ekr.20041125050302:<< fix problems with menus (XP) >>
         try:
             import WmDefault
             WmDefault.setup(root)
             d = {'activebackground':'DarkBlue','activeforeground':'white'} # works
             # d = {'activebackground':'','activeforeground':''} # doesn't work
             WmDefault.addoptions(root,d)
         except ImportError:
             g.trace("can not import WMDefault")
         #@nonl
         #@-node:ekr.20041125050302:<< fix problems with menus (XP) >>
         #@nl
     else: # Use Tkinter.
         self.root = root = Tk.Tk()
 
     root.title("Leo Main Window")
     root.withdraw()
     
     self.setDefaultIcon()
     if g.app.config:
         self.getDefaultConfigFont(g.app.config)
         
     root.withdraw()
 
     return root
Пример #15
0
    def loadConfig(self):

        def config(s):
            s = configParser.get("Main", s)
            #g.trace(s)
            if not s:
                s = ''
            return s.strip()

        def flag(s):
             ss = config(s)
             if ss:
                 return ss.lower()[0] in ('y', 't', '1')

        g.trace(g.app.loadDir,"..","plugins","leo_to_html.ini")
        fileName = abspath(g.app.loadDir,"..","plugins","leo_to_html.ini")
        configParser = ConfigParser.ConfigParser()
        configParser.read(fileName)

        self.flagIgnoreFiles =  flag("flagIgnoreFiles")
        self.include_body = not flag("flagJustHeadlines")

        self.basedir = config("exportPath") # "/"

        self.browser_command = config("browser_command")
        self.use_xhtml =  flag("use_xhtml")

        self.bullet_type = config( "bullet_type").lower()
        if self.bullet_type not in ('bullet', 'number', 'head'):
            self.bulletType = 'number'
Пример #16
0
    def unselect (self):

        '''Remember chapter info when a chapter is about to be unselected.'''

        c = self.c ; cc = self.cc
        self.hoistStack = c.hoistStack[:]
        self.p = c.currentPosition()
        if self.trace: g.trace('chapter',self.name,'p',self.p.headString())
Пример #17
0
 def oops(self):
         
     """Default do-nothing method for nullGui class.
     
     It is NOT an error to use this method."""
     
     g.trace("nullGui",g.callerName(2))
     pass
Пример #18
0
 def trace(self):
     
     if self.tracing:
 
         g.trace("%10s: %s" % (
             self.name,
             repr(g.toEncodedString(self.val,"utf-8"))
         ))
Пример #19
0
    def parseManagerText(self, text):
        """Parse the text in the manager file"""

        # Regular expressions for scanning the file
        find_active = re.compile(r"^\s*(\w+)\.py", re.MULTILINE)
        find_inactive = re.compile(r"^\s*#\s*(\w+)\.py", re.MULTILINE)
        find_manager = re.compile(r"^\s*plugin_manager\.py", re.MULTILINE)

        if 1:  # Put the first match in the starts dict.
            starts = {}
            for kind, iter in (
                ('active', find_active.finditer(text)),
                ('inactive', find_inactive.finditer(text)),
            ):
                for match in iter:
                    name = match.groups()[0]
                    start = match.start()
                    if start != -1:
                        bunch = starts.get(name)
                        if not bunch or bunch.start > start:
                            starts[name] = g.Bunch(kind=kind,
                                                   name=name,
                                                   start=start,
                                                   match=match)

            self.actives = dict([(bunch.name, bunch.match)
                                 for bunch in starts.values()
                                 if bunch.kind == 'active'])

            self.inactives = dict([(bunch.name, bunch.match)
                                   for bunch in starts.values()
                                   if bunch.kind == 'inactive'])

            if 0:  # debugging.
                starts2 = [(bunch.start, bunch.name, bunch.kind)
                           for bunch in starts.values()]
                starts2.sort()
                g.trace(g.listToString(starts2, tag='starts2 list'))
                g.trace(g.dictToString(self.actives, tag='Active Plugins'))

        else:  # Original code.
            # Get active plugin defintions
            self.actives = dict([(match.groups()[0], match)
                                 for match in find_active.finditer(text)])

            # Get inactive plugin definitions
            self.inactives = dict([(match.groups()[0], match)
                                   for match in find_inactive.finditer(text)])

        # List of all plugins
        self.all = {}
        self.all.update(self.actives)
        self.all.update(self.inactives)

        # Locaction of the plugin_manager.py plugin - this is where
        # we add additional files
        self.manager = find_manager.search(text)
Пример #20
0
    def toggleOption (self,ivar):

        if ivar in self.intKeys:
            var = self.svarDict.get(ivar)
            val = not var.get()
            var.set(val)
            # g.trace('%s = %s' % (ivar,val),var)
        else:
            g.trace('oops: bad find ivar %s' % ivar)
Пример #21
0
 def display_executing_dialog(self):
     
     if 1: ### EKR
         g.trace('Executing a command. Please wait until it is finished')
     else:
         tkMessageBox.showerror(
             "Already executing",
             "The Python Shell window is already executing a command; "
             "please wait until it is finished.",
             master=self.tkconsole.text)
Пример #22
0
    def oops(self):

        """Default do-nothing method for nullGui class.

        It is NOT an error to use this method."""

        # It is not usually an error to call methods of this class.
        # However, this message is useful when writing gui plugins.
        if 1:
            g.trace("nullGui",g.callers())
Пример #23
0
    def setOption (self,ivar,val):

        if ivar in self.intKeys:
            if val is not None:
                var = self.svarDict.get(ivar)
                var.set(val)
                # g.trace('%s = %s' % (ivar,val))

        elif not g.app.unitTesting:
            g.trace('oops: bad find ivar %s' % ivar)
Пример #24
0
 def putDescendentUnknownAttributes (self,p):
 
     # Create a list of all tnodes having a valid unknownAttributes dict.
     # New in 4.4: create a dictionary: keys are tnodes, values are lists of vnx's.
     tnodes = [] ; vnxs = {}
     for p2 in p.subtree_iter():
         v = p2.v
         t = v.t
         if hasattr(t,"unknownAttributes"):
             if t not in tnodes :
                 tnodes.append((p,t),)
                 
         # New in 4.4.
         theList = vnxs.get(t,[])
         theList.append(v.gnx)
         vnxs[t] = theList
         
     
     # Create a list of pairs (t,d) where d contains only pickleable entries.
     data = []
     for p,t in tnodes:
         if type(t.unknownAttributes) != type({}):
              g.es("ignoring non-dictionary unknownAttributes for",p,color="blue")
         else:
             # Create a new dict containing only entries that can be pickled.
             d = dict(t.unknownAttributes) # Copy the dict.
             for key in d.keys():
                 try: pickle.dumps(d[key],bin=True)
                 except pickle.PicklingError:
                     del d[key]
                     g.es("ignoring bad unknownAttributes key %s in %s" % (
                         key,p),color="blue")
             data.append((t,d),)
             
     # Create resultDict, an enclosing dict to hold all the data.
     resultDict = {}
     nodeIndices = g.app.nodeIndices
     for t,d in data:
         gnx = nodeIndices.toString(t.fileIndex)
         resultDict[gnx]=d
     
     if 0:
         print "resultDict"
         for key in resultDict:
             print ; print key,resultDict[key]
         
     # Pickle and hexlify resultDict.
     if resultDict:
         try:
             tag = "descendentTnodeUnknownAttributes"
             s = pickle.dumps(resultDict,bin=True)
             field = ' %s="%s"' % (tag,binascii.hexlify(s))
             self.put(field)
         except pickle.PicklingError:
             g.trace("can't happen",color="red")
Пример #25
0
    def getOption (self,ivar):

        var = self.svarDict.get(ivar)

        if var:
            val = var.get()
            # g.trace('%s = %s' % (ivar,val))
            return val
        else:
            g.trace('bad ivar name: %s' % ivar)
            return None
Пример #26
0
 def close_all_callback(self, event):
     
     g.trace()
     
     if 0: # The Leo editor never closes
         for edit in self.inversedict.keys():
             reply = edit.close()
             if reply == "cancel":
                 break
 
     return "break"
Пример #27
0
    def loadIcon(self, fname):

        try:
            icon = gtk.gdk.pixbuf_new_from_file(fname)
        except:
            icon = None

        if icon and icon.get_width()>0:
            return icon

        g.trace( 'Can not load icon from', fname)
Пример #28
0
 def getMacHelpMenu (self):
     
     return None ###
     
     try:
         helpMenu = Tk.Menu('top.help')
         return helpMenu
         
     except Exception:
         g.trace('Can not get MacOS Help menu')
         g.es_exception()
         return None
 def parseManagerText(self, text):
     """Parse the text in the manager file"""
 
     # Regular expressions for scanning the file
     find_active = re.compile(r"^\s*(\w+)\.py", re.MULTILINE)
     find_inactive = re.compile(r"^\s*#\s*(\w+)\.py", re.MULTILINE)
     find_manager = re.compile(r"^\s*plugin_manager\.py", re.MULTILINE)
 
     if 1: # Put the first match in the starts dict.
         starts = {}
         for kind,iter in (
             ('active',find_active.finditer(text)),
             ('inactive',find_inactive.finditer(text)),
         ):
             for match in iter:
                 name = match.groups()[0]
                 start = match.start()
                 if start != -1:
                     bunch = starts.get(name)
                     if not bunch or bunch.start > start:
                       starts[name] = g.Bunch(
                         kind=kind,name=name,start=start,match=match)
                     
         self.actives = dict(
             [(bunch.name,bunch.match) for bunch in starts.values() if bunch.kind=='active'])
             
         self.inactives = dict(
             [(bunch.name,bunch.match) for bunch in starts.values() if bunch.kind=='inactive'])
             
         if 0: # debugging.
             starts2 = [(bunch.start,bunch.name,bunch.kind) for bunch in starts.values()]
             starts2.sort()
             g.trace(g.listToString(starts2,tag='starts2 list'))
             g.trace(g.dictToString(self.actives,tag='Active Plugins'))
                   
     else: # Original code.
         # Get active plugin defintions
         self.actives = dict([(match.groups()[0], match) 
             for match in find_active.finditer(text)])
     
         # Get inactive plugin definitions
         self.inactives = dict([(match.groups()[0], match) 
             for match in find_inactive.finditer(text)])
 
     # List of all plugins
     self.all = {}
     self.all.update(self.actives)
     self.all.update(self.inactives)
 
     # Locaction of the plugin_manager.py plugin - this is where
     # we add additional files
     self.manager = find_manager.search(text)
def on_headkey2 (tag,keywords):

    c = keywords.get("c")
    v = keywords.get("v")
    h = v.headString()
    ch = keywords.get("ch")
    
    g.trace(repr(ch))

    if ch == '\r' and g.match_word(h,0,"@read-only"):
        # on-the-fly update of @read-only directives
        changed = insert_read_only_node(c,v,h[11:])
        c.setChanged(changed)
Пример #31
0
 def start_subprocess(self):
     # spawning first avoids passing a listening socket to the subprocess
     self.spawn_subprocess()
     #time.sleep(20) # test to simulate GUI not accepting connection
     addr = (LOCALHOST, self.port)
     # Idle starts listening for connection on localhost
     for i in range(3):
         time.sleep(i)
         try:
             self.rpcclt = MyRPCClient(addr)
             g.trace(self.rpcclt)
             break
         except socket.error, err:
             pass
Пример #32
0
 def gotofileline(self, filename, lineno=None):
     
     g.trace(filename,lineno)
     
     if 1: # Leo-centric code.
         filename = self.open(filename)
         if filename:
             g.trace(filename,lineno)
             # g.gotoline(lineno)
         
     else: # IDLE-centric code.
         edit = self.open(filename)
         if edit is not None and lineno is not None:
             edit.gotoline(lineno)
Пример #33
0
 def resolveTnodeLists (self,c):
     
     for p in c.allNodes_iter():
         if hasattr(p.v,'tempTnodeList'):
             result = []
             for tnx in p.v.tempTnodeList:
                 v = self.generatedTnxs.get(tnx)
                 if v:
                     # g.trace('found',v,tnx,v.t)
                     result.append(v.t)
                 else:
                     g.trace('No tnode for %s' % tnx)
             p.v.t.tnodeList = result
             delattr(p.v,'tempTnodeList')
    def __init__(self, c):
        """Ctor for the leoTkinterPrefs class."""

        g.trace('tkinterPrefs')

        # Init the base class
        leoPrefs.leoPrefs.__init__(self, c)

        head, tail = g.os_path_split(c.frame.title)
        leoTkinterDialog.leoTkinterDialog.__init__(self,
                                                   "Prefs for " + tail,
                                                   resizeable=False)

        self.createTopFrame()  # Create the outer tkinter dialog frame.
        self.createFrame()
        self.setWidgets()
Пример #35
0
    def assignFileIndices(self, p):
        """Assign a file index to all tnodes"""

        c = self.c
        nodeIndices = g.app.nodeIndices

        nodeIndices.setTimestamp()  # This call is fairly expensive.

        # Assign missing gnx's, converting ints to gnx's.
        # Always assign an (immutable) index, even if the tnode is empty.
        for p2 in p.self_and_subtree_iter(copy=1):  #c.allNodes_iter():
            try:  # Will fail for None or any pre 4.1 file index.
                theId, time, n = p2.v.t.fileIndex
            except TypeError:
                # Don't convert to string until the actual write.
                p2.v.t.fileIndex = nodeIndices.getNewIndex()

        if 0:  # debugging:
            for p in c.allNodes_iter():
                g.trace(p.v.t.fileIndex)
Пример #36
0
 def __init__ (self,c):
     
     g.trace('prefs')
 
     self.c = c
 
     # Global options...
     self.page_width = self.default_page_width
     self.tab_width = self.default_tab_width
     self.tangle_batch_flag = 0
     self.untangle_batch_flag = 0
     
     # Default Tangle options...
     self.tangle_directory = ""
     self.use_header_flag = 0
     self.output_doc_flag = 0
     
     # Default Target Language...
     self.target_language = self.default_target_language
 
     self.init(c)
Пример #37
0
    def __init__(self, buttonType, parent_widget, **keywords):

        self.buttonType = buttonType
        self.parent_widget = parent_widget
        self.hotKey = None
        text = keywords['text']

        #@	<< set self.hotKey if '&' is in the string >>
        #@+node:ekr.20041025152712.2:<< set self.hotKey if '&' is in the string >>
        index = text.find('&')

        if index > -1:

            if index == len(text) - 1:
                # The word ends in an ampersand.  Ignore it; there is no hot key.
                text = text[:-1]
            else:
                self.hotKey = text[index + 1]
                text = text[:index] + text[index + 1:]
        #@nonl
        #@-node:ekr.20041025152712.2:<< set self.hotKey if '&' is in the string >>
        #@nl

        # Create the button...
        if self.hotKey:
            keywords['text'] = text
            keywords['underline'] = index

        if buttonType.lower() == "button":
            self.button = Tk.Button(parent_widget, keywords)
        elif buttonType.lower() == "check":
            self.button = Tk.Checkbutton(parent_widget, keywords)
        elif buttonType.lower() == "radio":
            self.button = Tk.Radiobutton(parent_widget, keywords)
        else:
            g.trace("bad buttonType")

        self.text = text  # for traces
Пример #38
0
def onStart2 (tag, keywords):
    
    """
    Showing how to define a global hook that affects all commanders.
    """

    import leoTkinterFrame
    log = leoTkinterFrame.leoTkinterLog
    
    # Replace frame.put with newPut. (not shown).
    g.funcToMethod(newPut,log,"put")
#@nonl
#@-node:ekr.20040919085752:onStart2
#@-others

# This statement needed only if the plugin uses modules that are not always available.
if Tk and Pmw and not g.app.unitTesting:
    g.trace('style_guide')
    # The following three lines needed only if the plugin uses a gui.
    if g.app.gui is None: 
        g.app.createTkGui(__file__)
    if g.app.gui.guiName() == "tkinter":
        # Shows how to create a class that binds self.c properly.
        leoPlugins.registerHandler("after-create-leo-frame", onCreate)
        # Shows how to create a hook that doesn't access commanders.
        leoPlugins.registerHandler("start2", onStart2)
        g.plugin_signon(__name__)
#@nonl
#@-node:ekr.20040919081244:@thin style_guide.py
#@-leo
Пример #39
0
    def callback(self, event):

        g.trace(self.text)

        self.button.invoke()
Пример #40
0
def test():
    g.trace('=====')
Пример #41
0
    def putVnode2(self, p, ignored, doc, vnode):
        """Write a <v> element corresponding to a vnode."""

        #print "PV2"
        fc = self
        #c = fc.c ;
        op = p
        v = p.v
        isThin = p.isAtThinFileNode()
        isIgnore = False
        if 0:  # Wrong: must check all parents.
            ignored = ignored or p.isAtIgnoreNode()
        else:
            for p2 in p.self_and_parents_iter(copy=1):
                if p2.isAtIgnoreNode():
                    isIgnore = True
                    break
        isOrphan = p.isOrphan()
        forceWrite = isIgnore or not isThin or (isThin and isOrphan)

        v_element = doc.createElement("v")
        v_element.setAttribute("vid", v.vid)
        vnode.appendChild(v_element)
        #ws = doc.createTextNode( "\n%s" % indent )
        #vnode.appendChild( ws )
        #fc.put("<v")
        #@    << Put tnode index >>
        #@+node:zorcanda!.20050912154148.1:<< Put tnode index >>
        if v.t.fileIndex:
            gnx = g.app.nodeIndices.toString(v.t.fileIndex)
            #fc.put(" t=") ; fc.put_in_dquotes(gnx)
            v_element.setAttribute("t", gnx)

            # g.trace(v.t)
            if forceWrite or self.usingClipboard:
                v.t.setWriteBit()  # 4.2: Indicate we wrote the body text.
        else:
            g.trace(v.t.fileIndex, v)
            g.es("error writing file(bad v.t.fileIndex)!")
            g.es("try using the Save To command")
        #@nonl
        #@-node:zorcanda!.20050912154148.1:<< Put tnode index >>
        #@nl
        #@    << Put attribute bits >>
        #@+node:zorcanda!.20050912154148.2:<< Put attribute bits >>
        attr = ""
        if p.v.isExpanded(): attr += "E"
        if p.v.isMarked(): attr += "M"
        if p.v.isOrphan(): attr += "O"

        if 1:  # No longer a bottleneck now that we use p.equal rather than p.__cmp__
            # Almost 30% of the entire writing time came from here!!!
            if p.equal(op): attr += "T"  # was a bottleneck
            #if c.isCurrentPosition(p):      attr += "V" # was a bottleneck

        #if attr: fc.put(' a="%s"' % attr)
        if attr:
            v_element.setAttribute("a", attr)

        #@-node:zorcanda!.20050912154148.2:<< Put attribute bits >>
        #@nl
        #@    << Put tnodeList and unKnownAttributes >>
        #@+node:zorcanda!.20050912154148.3:<< Put tnodeList and unKnownAttributes >>
        #@+at
        # # Write the tnodeList only for @file nodes.
        # # New in 4.2: tnode list is in tnode.
        #
        # if 0: # Debugging.
        #     if v.isAnyAtFileNode():
        #         if hasattr(v.t,"tnodeList"):
        #             g.trace(v.headString(),len(v.t.tnodeList))
        #         else:
        #             g.trace(v.headString(),"no tnodeList")
        #
        # if hasattr(v.t,"tnodeList") and len(v.t.tnodeList) > 0 and
        # v.isAnyAtFileNode():
        #     if isThin:
        #         if g.app.unitTesting:
        #             g.app.unitTestDict["warning"] = True
        #         g.es("deleting tnode list for %s" %
        # p.headString(),color="blue")
        #         # This is safe: cloning can't change the type of this node!
        #         delattr(v.t,"tnodeList")
        #     else:
        #         fc.putTnodeList(v) # New in 4.0
        #
        # if hasattr(v,"unknownAttributes"): # New in 4.0
        #     self.putUnknownAttributes(v)
        # if p.hasChildren() and not forceWrite and not self.usingClipboard:
        #     # We put the entire tree when using the clipboard, so no need
        # for this.
        #     self.putDescendentUnknownAttributes(p)
        #     self.putDescendentAttributes(p)
        #@-at
        #@nonl
        #@-node:zorcanda!.20050912154148.3:<< Put tnodeList and unKnownAttributes >>
        #@nl
        #fc.put(">")
        #@    << Write the head text >>
        #@+node:zorcanda!.20050912154148.4:<< Write the head text >>
        headString = p.v.headString()

        if headString:
            vh = doc.createElement("vh")
            v_element.appendChild(vh)
            vh.setTextContent(headString)

            #fc.put("<vh>")
            #fc.putEscapedString(headString)
            #fc.put("</vh>")
        #@-node:zorcanda!.20050912154148.4:<< Write the head text >>
        #@nl

        #if not self.usingClipboard:
        #
        #@nonl
        #@<< issue informational messages >>
        #@+node:zorcanda!.20050912154148.5:<< issue informational messages >>
        if p.isAtThinFileNode and p.isOrphan():
            g.es("Writing erroneous: %s" % p.headString(), color="blue")
            p.clearOrphan()

        if 0:  # For testing.
            if p.isAtIgnoreNode():
                for p2 in p.self_and_subtree_iter():
                    if p2.isAtThinFileNode():
                        g.es("Writing @ignore'd: %s" % p2.headString(),
                             color="blue")
        #@nonl
        #@-node:zorcanda!.20050912154148.5:<< issue informational messages >>
        #@nl

        # New in 4.2: don't write child nodes of @file-thin trees (except when writing to clipboard)

        if p.hasChildren():
            #fc.put_nl()
            # This optimization eliminates all "recursive" copies.
            p.moveToFirstChild()
            while 1:
                fc.putVnode2(p, ignored, doc, v_element)
                if p.hasNext(): p.moveToNext()
                else: break
            p.moveToParent()
Пример #42
0
 def print_ivars (self):
     
     """Debugging routine for Prefs panel."""
     
     for var in self.ivars:
         g.trace(var, getattr(self,var))
Пример #43
0
 def oops(self):
     
     g.trace("unitTestGui",g.callerName(2))
     
     if 0: # Fail the unit test.
         assert 0,"call to undefined method in unitTestMethod class"
Пример #44
0
     def __getattr__(self,attr):
 
         g.trace("nullGui",attr)
         return nullObject()