Ejemplo n.º 1
0
def insertWikiPicture (colorer,filename,i):
    
    """Try to insert a picture with the give filename.
    
    Returns the number of characters actually inserted"""

    if colorer.color_pass == 0:
        colorer.redoColoring = True # schedule a two-pass recoloring.
        return 0

    if colorer.color_pass == 2:
        return 0 # The second redo pass.

    if not os.path.exists(filename):
        return 0

    try:
        # Create the image
        photo = Tk.PhotoImage(master=g.app.root, file=filename)
        image = colorer.body.bodyCtrl.image_create(colorer.index(i),image=photo,padx=0)
        
        # Keep references so images stay on the canvas.
        colorer.image_references.append((photo,image,colorer.line_index,i),)
        return 1
    except:
        g.es_exception()
        return 0
Ejemplo n.º 2
0
def openURL(tag,keywords):
    c = keywords.get("c")

    w = c.frame.body.bodyCtrl
    s = w.getAllText()
    ins = w.getInsertPoint()
    row,col = g.convertPythonIndexToRowCol(s,ins)
    i,j = g.getLine(s,ins)
    line = s[i:j]
    # g.trace(repr(line))

    for match in url_regex.finditer(line):
        if match.start() <= col <= match.end():
            url = match.group()
            if 0: # I have no idea why this code was present.
                start,end = match.start(), match.end()
                c.frame.body.setSelectionRange("%s.%s" %(row,start), "%s.%s" %(row,end))
                w.setSelectionRange(start,end)
            if not g.app.unitTesting:
                try:
                    import webbrowser
                    webbrowser.open(url)
                except:
                    g.es("exception opening " + url)
                    g.es_exception()
            return url # force to skip word selection if url found
Ejemplo n.º 3
0
    def getTextFromClipboard (self):

        return None ###

        # g.app.gui.win32clipboard is always None.
        wcb = g.app.gui.win32clipboard

        if wcb:
            try:
                wcb.OpenClipboard(0)
                data = wcb.GetClipboardData()
                wcb.CloseClipboard()
                # g.trace(data)
                return data
            except TypeError:
                # g.trace(None)
                return None
            except:
                g.es_exception()
                return None
        else:
            try:
                s = self.root.selection_get(selection="CLIPBOARD")
                return s
            except:
                return None
 def compare_files (self, name1, name2):
     
     if name1 == name2:
         self.show("File names are identical.\nPlease pick distinct files.")
         return
 
     f1 = f2 = None
     try:
         f1 = self.doOpen(name1)
         f2 = self.doOpen(name2)
         if self.outputFileName:
             self.openOutputFile()
         ok = self.outputFileName == None or self.outputFile
         ok = g.choose(ok and ok != 0,1,0)
         if f1 and f2 and ok: # Don't compare if there is an error opening the output file.
             self.compare_open_files(f1,f2,name1,name2)
     except:
         self.show("exception comparing files")
         g.es_exception()
     try:
         if f1: f1.close()
         if f2: f2.close()
         if self.outputFile:
             self.outputFile.close() ; self.outputFile = None
     except:
         self.show("exception closing files")
         g.es_exception()
Ejemplo n.º 5
0
def openForRead (self,filename,rb):
    """
    Replaces the standard open for reads.
    Checks and handles shadow files:
        if the length of the real file is zero:
            update the real file from the shadow file.
        else:
            update the shadow file from the real file.
    """
    try:
        dir, simplename = os.path.split(filename)
        shadow_filename = os.path.join(dir,shadow_subdir,prefix + simplename)
        if os.path.exists(shadow_filename):
            file_to_read_from = shadow_filename 
            if os.path.exists(filename)and os.path.getsize(filename)<=2:
                if verbosity >= 2:
                    g.es("Copy %s to %s without sentinels"%(shadow_filename,filename))
                push_file(sourcefilename=shadow_filename,targetfilename=filename)
            else:
                sq = sentinel_squasher()
                if verbosity >= 2:
                    g.es("reading in shadow directory %s"% shadow_subdir,color="orange")
                sq.pull_source(sourcefile=shadow_filename,targetfile=filename)
        else:
            file_to_read_from = filename 
        return open(file_to_read_from,'rb')
    except:
        # Make sure failures to open a file generate clear messages.
        g.es_exception()
        raise 
Ejemplo n.º 6
0
    def compare_files(self, name1, name2):

        if name1 == name2:
            self.show("File names are identical.\nPlease pick distinct files.")
            return

        f1 = f2 = None
        try:
            f1 = self.doOpen(name1)
            f2 = self.doOpen(name2)
            if self.outputFileName:
                self.openOutputFile()
            ok = self.outputFileName == None or self.outputFile
            ok = g.choose(ok and ok != 0, 1, 0)
            if f1 and f2 and ok:  # Don't compare if there is an error opening the output file.
                self.compare_open_files(f1, f2, name1, name2)
        except:
            self.show("exception comparing files")
            g.es_exception()
        try:
            if f1: f1.close()
            if f2: f2.close()
            if self.outputFile:
                self.outputFile.close()
                self.outputFile = None
        except:
            self.show("exception closing files")
            g.es_exception()
 def openOutputFile (self):
     
     if self.outputFileName == None:
         return
     theDir,name = g.os_path_split(self.outputFileName)
     if len(theDir) == 0:
         self.show("empty output directory")
         return
     if len(name) == 0:
         self.show("empty output file name")
         return
     if not g.os_path_exists(theDir):
         self.show("output directory not found: " + theDir)
     else:
         try:
             if self.appendOutput:
                 self.show("appending to " + self.outputFileName)
                 self.outputFile = open(self.outputFileName,"ab")
             else:
                 self.show("writing to " + self.outputFileName)
                 self.outputFile = open(self.outputFileName,"wb")
         except:
             self.outputFile = None
             self.show("exception opening output file")
             g.es_exception()
Ejemplo n.º 8
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
Ejemplo n.º 9
0
    def openOutputFile(self):

        if self.outputFileName == None:
            return
        theDir, name = g.os_path_split(self.outputFileName)
        if len(theDir) == 0:
            self.show("empty output directory")
            return
        if len(name) == 0:
            self.show("empty output file name")
            return
        if not g.os_path_exists(theDir):
            self.show("output directory not found: " + theDir)
        else:
            try:
                if self.appendOutput:
                    self.show("appending to " + self.outputFileName)
                    self.outputFile = open(self.outputFileName, "ab")
                else:
                    self.show("writing to " + self.outputFileName)
                    self.outputFile = open(self.outputFileName, "wb")
            except:
                self.outputFile = None
                self.show("exception opening output file")
                g.es_exception()
Ejemplo n.º 10
0
 def runFindScript (self):
 
     try:
         exec self.find_text in {} # Use {} to get a pristine environment.
     except:
         g.es("exception executing find script")
         g.es_exception(full=False)
         g.app.searchDict["continue"] = False # 2/1/04
Ejemplo n.º 11
0
    def runFindScript(self):

        c = self.c
        try:
            exec self.find_text in {}  # Use {} to get a pristine environment.
        except:
            g.es("exception executing find script")
            g.es_exception(full=False)
            g.app.searchDict["continue"] = False  # 2/1/04
    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")
Ejemplo n.º 13
0
 def runChangeScript (self):
 
     try:
         assert(self.script_change)
         exec self.change_text in {} # Use {} to get a pristine environment.
     except:
         g.es("exception executing change script")
         g.es_exception(full=False)
         g.app.searchDict["continue"] = False # 2/1/04
Ejemplo n.º 14
0
def enable_body(body):
    global insertOnTime,insertOffTime
    if body.cget("state") == "disabled":
        try:
            g.es("enable")
            print insertOffTime,insertOnTime
            body.configure(state="normal")
            body.configure(insertontime=insertOnTime,insertofftime=insertOffTime)
        except: g.es_exception()
Ejemplo n.º 15
0
    def runChangeScript(self):

        c = self.c
        try:
            assert (self.script_change)
            exec self.change_text in {
            }  # Use {} to get a pristine environment.
        except:
            g.es("exception executing change script")
            g.es_exception(full=False)
            g.app.searchDict["continue"] = False  # 2/1/04
Ejemplo n.º 16
0
    def disableMenu (self,menu,name):

        try:
            menu.entryconfig(name,state="disabled")
        except: 
            try:
                realName = self.getRealMenuName(name)
                realName = realName.replace("&","")
                menu.entryconfig(realName,state="disabled")
            except:
                print "disableMenu menu,name:",menu,name
                g.es_exception()
Ejemplo n.º 17
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
Ejemplo n.º 18
0
    def new_menu(self,parent,tearoff=False):

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

        if self.font:
            try:
                return Tk.Menu(parent,tearoff=tearoff,font=self.font)
            except Exception:
                g.es_exception()
                return Tk.Menu(parent,tearoff=tearoff)
        else:
            return Tk.Menu(parent,tearoff=tearoff)
Ejemplo n.º 19
0
 def setDisabledHeadlineColors (self,p):
 
     c = self.c ; w = p.edit_widget()
 
     fg, bg = self.custom_colours(p.v)
 
     fg = fg or c.config.getColor("headline_text_selected_foreground_color") or 'black'
     bg = bg or c.config.getColor("headline_text_selected_background_color") or 'grey80'
 
     try:
         w.configure(state="disabled",highlightthickness=0,fg=fg,bg=bg)
     except:
         g.es_exception()
Ejemplo n.º 20
0
    def enableMenu (self,menu,name,val):

        state = g.choose(val,"normal","disabled")
        try:
            menu.entryconfig(name,state=state)
        except:
            try:
                realName = self.getRealMenuName(name)
                realName = realName.replace("&","")
                menu.entryconfig(realName,state=state)
            except:
                print "enableMenu menu,name,val:",menu,name,val
                g.es_exception()
Ejemplo n.º 21
0
    def disableMenu(self, menu, name):

        try:
            menu.entryconfig(name, state="disabled")
        except:
            try:
                realName = self.getRealMenuName(name)
                realName = realName.replace("&", "")
                menu.entryconfig(realName, state="disabled")
            except:
                print "disableMenu menu,name:", menu, name
                g.es_exception()
                pass
Ejemplo n.º 22
0
def onBodydclick1(tag,keywords):

    """Handle double clicks on a hyperlink."""

    c = keywords.get("c")
    url = getUrl(c, "http", "https")
    if url:
        try:
            import webbrowser
            webbrowser.open(url)
        except:
            g.es("exception opening " + url)
            g.es_exception()
 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")
Ejemplo n.º 24
0
    def enableMenu(self, menu, name, val):

        state = g.choose(val, "normal", "disabled")
        try:
            menu.entryconfig(name, state=state)
        except:
            try:
                realName = self.getRealMenuName(name)
                realName = realName.replace("&", "")
                menu.entryconfig(realName, state=state)
            except:
                print "enableMenu menu,name,val:", menu, name, val
                g.es_exception()
                pass
def newExecuteScript(self,event=None,v=None):
    
    c = self.c ; body = self.body ; s = None
    if v == None:
        v = c.currentVnode() 

    # Assume any selected body text is a script.
    start,end = body.getTextSelection() # EKR: 11/04/03
    if start and end and start != end: # 7/7/03
        s = body.bodyCtrl.get(start,end)
    else:
        s = body.bodyCtrl.get("1.0","end")
    s = s.strip()
    if s and len(s) > 0:
        s += '\n' # Make sure we end the script properly.
        # Switch output.
        import leoTkinterFrame,leoGlobals
        oldput = leoTkinterFrame.leoTkinterLog.put # 11/7/03
        oldputnl = leoTkinterFrame.leoTkinterLog.putnl # 11/7/03
        oldes = leoGlobals.es
        oldenl = leoGlobals.enl
        oldecnl = leoGlobals.ecnl
        oldecnls = leoGlobals.ecnls
        leoGlobals.es = newEs
        leoGlobals.enl = newEnl
        leoGlobals.ecnl = newEcnl
        leoGlobals.ecnls = newEcnls
        g.funcToMethod(newPut,leoTkinterFrame.leoTkinterLog,"put") #  11/7/03
        g.funcToMethod(newPutNl,leoTkinterFrame.leoTkinterLog,"putNl") # 11/7/03
        g.redirectStderr()
        g.redirectStdout()
        try:
            exec s in {} # Use {} to get a pristine environment!
            ok = True
        except:
            ok = False
        # Restore output.
        g.funcToMethod(oldput,leoTkinterFrame.leoTkinterLog,"put") # 11/7/03
        g.funcToMethod(oldputnl,leoTkinterFrame.leoTkinterLog,"putNl") # 11/7/03
        leoGlobals.es = oldes
        leoGlobals.enl = oldenl
        leoGlobals.ecnl = oldecnl
        leoGlobals.ecnls = oldecnls
        g.restoreStderr()
        g.restoreStdout()
        if not ok:
            g.es("newExecuteScript: exception executing script")
            g.es_exception(full=False)
    else:
        g.es("newExecuteScript: empty script")
Ejemplo n.º 26
0
    def replaceClipboardWith(self, s):

        # g.app.gui.win32clipboard is always None.
        wcb = g.app.gui.win32clipboard

        if wcb:
            try:
                wcb.OpenClipboard(0)
                wcb.EmptyClipboard()
                wcb.SetClipboardText(s)
                wcb.CloseClipboard()
            except:
                g.es_exception()
        else:
            self.root.clipboard_clear()
            self.root.clipboard_append(s)
Ejemplo n.º 27
0
    def replaceClipboardWith (self,s):

        # g.app.gui.win32clipboard is always None.
        wcb = g.app.gui.win32clipboard

        if wcb:
            try:
                wcb.OpenClipboard(0)
                wcb.EmptyClipboard()
                wcb.SetClipboardText(s)
                wcb.CloseClipboard()
            except:
                g.es_exception()
        else:
            self.root.clipboard_clear()
            self.root.clipboard_append(s)
Ejemplo n.º 28
0
  def text_run(self):
    frame_idx = 0

    while not self.killed:

      # Frames can come and go.
      if frame_idx > len(self.frames) - 1:
        frame_idx = 0
      f = self.frames[frame_idx]
      print f.getTitle()
      s = raw_input('Do what? (menu,key,body,frames,tree,quit) > ')

      try:
        self.doChoice(f,s)
      except Exception:
          g.es_exception()
Ejemplo n.º 29
0
def applyFileAction(p, filename, c):

    script = g.getScript(c, p)
    if script:
        working_directory = os.getcwd()
        file_directory = c.frame.openDirectory
        os.chdir(file_directory)
        script += '\n'
        #@        << redirect output >>
        #@+node:ekr.20040915105758.17:<< redirect output >>
        if c.config.redirect_execute_script_output_to_log_pane:
        
            g.redirectStdout() # Redirect stdout
            g.redirectStderr() # Redirect stderr
        #@nonl
        #@-node:ekr.20040915105758.17:<< redirect output >>
        #@nl
        try:
            namespace = {
                'c':c, 'g':g,
                'filename': filename,
                'shellScriptInWindow': shellScriptInWindow }
            exec script in namespace
            #@            << unredirect output >>
            #@+node:ekr.20040915105758.18:<< unredirect output >>
            if c.config.redirect_execute_script_output_to_log_pane:
            
                g.restoreStderr()
                g.restoreStdout()
            #@nonl
            #@-node:ekr.20040915105758.18:<< unredirect output >>
            #@nl
        except:
            #@            << unredirect output >>
            #@+node:ekr.20040915105758.18:<< unredirect output >>
            if c.config.redirect_execute_script_output_to_log_pane:
            
                g.restoreStderr()
                g.restoreStdout()
            #@nonl
            #@-node:ekr.20040915105758.18:<< unredirect output >>
            #@nl
            g.es("exception in FileAction plugin")
            g.es_exception(full=False,c=c)

        os.chdir(working_directory)
Ejemplo n.º 30
0
    def __init__(self, c, folder):
        """Initialize the collection"""

        self.c = c
        self.folder = folder
        self.templateNames = []
        self.templates = {}
        for filename in glob.glob(g.os_path_join(folder, "*.tpl")):
            try:
                # Create a new template by evaluating the file.
                text = file(filename, "r").read()
                template = eval(text)
                self.add(template)
                # g.trace(repr(template))
            except Exception:
                g.es('Exception reading template file %s' % filename)
                g.es_exception()
Ejemplo n.º 31
0
def onIconDoubleClick(tag,keywords):

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

    if c and v:
        h = v.headString().strip()
        if h and h[0]!='@':
            #@            << find path and start file >>
            #@+node:ekr.20040828103325.4:<< find path and start file >>
            # Set the base directory by searching for @folder directives in ancestors.
            thisdir = os.path.abspath(os.curdir) # remember the current dir
            basedir = thisdir[:] # use current dir as default.
            parv = v.parent() # start with parent
            while parv: # stop when no more parent found
                p = parv.headString().strip()
                if g.match_word(p,0,'@folder'):
                    basedir = p[8:] # take rest of headline as pathname
                    break # we found the closest @folder
                else:
                    parv = parv.parent() # try the parent of the parent
            
            fname = os.path.join(basedir,h) # join path and filename
            startdir, filename = os.path.split(fname)
            try:
                os.chdir(startdir)
                dirfound = 1
            except:
                g.es(startdir+' - folder not found')
                dirfound = 0
            
            if dirfound:
                fullpath = g.os_path_join(startdir,filename)
                fullpath = g.os_path_abspath(fullpath)
                if g.os_path_exists(filename):
                    try:
                        # Warning: os.startfile usually does not throw exceptions.
                        os.startfile(filename) # Try to open the file; it may not work for all file types.
                    except Exception:
                        g.es(filename+' - file not found in '+startdir)
                        g.es_exception()
                else:
                    g.es('%s not found in %s' % (filename,startdir),color='blue')
            os.chdir(thisdir) # restore the original current dir.
Ejemplo n.º 32
0
    def __init__(self):

        # Initialize the base class.
        leoGui.leoGui.__init__(self, "tkinter")

        self.bitmap_name = None
        self.bitmap = None
        self.win32clipboard = None
        self.defaultFont = None
        self.defaultFontFamily = None

        if 0:  # This seems both dangerous and non-functional.
            if sys.platform == "win32":
                try:
                    import win32clipboard
                    self.win32clipboard = win32clipboard
                except:
                    g.es_exception()
Ejemplo n.º 33
0
    def setMenuLabel(self, menu, name, label, underline=-1):

        try:
            if type(name) == type(0):
                # "name" is actually an index into the menu.
                menu.entryconfig(name, label=label, underline=underline)
            else:
                # Bug fix: 2/16/03: use translated name.
                realName = self.getRealMenuName(name)
                realName = realName.replace("&", "")
                # Bug fix: 3/25/03" use tranlasted label.
                label = self.getRealMenuName(label)
                label = label.replace("&", "")
                menu.entryconfig(realName, label=label, underline=underline)
        except:
            print "setMenuLabel menu,name,label:", menu, name, label
            g.es_exception()
            pass
Ejemplo n.º 34
0
 def __init__ (self):
 
     # Initialize the base class.
     leoGui.leoGui.__init__(self,"tkinter")
 
     self.bitmap_name = None
     self.bitmap = None
     self.win32clipboard = None
     self.defaultFont = None
     self.defaultFontFamily = None
 
     if 0: # This seems both dangerous and non-functional.
         if sys.platform == "win32":
             try:
                 import win32clipboard
                 self.win32clipboard = win32clipboard
             except:
                 g.es_exception()
 def getSelection (self):
 
     box = self.box ; color = None
     
     # Get the family name if possible, or font otherwise.
     items = box.curselection()
 
     if len(items)> 0:
         try: # This shouldn't fail now.
             items = map(int, items)
             color = box.get(items[0])
         except:
             g.es("unexpected exception")
             g.es_exception()
 
     if not color:
         color = self.color
     return color
Ejemplo n.º 36
0
 def setMenuLabel (self,menu,name,label,underline=-1):
 
     try:
         if type(name) == type(0):
             # "name" is actually an index into the menu.
             menu.entryconfig(name,label=label,underline=underline)
         else:
             # Bug fix: 2/16/03: use translated name.
             realName = self.getRealMenuName(name)
             realName = realName.replace("&","")
             # Bug fix: 3/25/03" use tranlasted label.
             label = self.getRealMenuName(label)
             label = label.replace("&","")
             menu.entryconfig(realName,label=label,underline=underline)
     except:
         print "setMenuLabel menu,name,label:",menu,name,label
         g.es_exception()
         pass
Ejemplo n.º 37
0
def startPsyco ():

    import leoGlobals as g

    try:
        import psyco
        if 0:
            theFile = r"c:\prog\test\psycoLog.txt"
            g.es("psyco now logging to:",theFile,color="blue")
            psyco.log(theFile)
            psyco.profile()
        psyco.full()
        g.es("psyco now running",color="blue")
    except ImportError:
        g.app.use_psyco = False
    except:
        print "unexpected exception importing psyco"
        g.es_exception()
        g.app.use_psyco = False
Ejemplo n.º 38
0
    def getSelection(self):

        box = self.box
        color = None

        # Get the family name if possible, or font otherwise.
        items = box.curselection()

        if len(items) > 0:
            try:  # This shouldn't fail now.
                items = map(int, items)
                color = box.get(items[0])
            except:
                g.es("unexpected exception")
                g.es_exception()

        if not color:
            color = self.color
        return color
Ejemplo n.º 39
0
def doFootprint(self, p):  
    """Do the colouring""" 
    if p and p.edit_widget(): 
        config = g.app.config 
         
        #fg = config.getWindowPref("headline_text_unselected_foreground_color") 
        #bg = config.getWindowPref("headline_text_unselected_background_color") 
        fg = COLD_FG      
        bg = "white" 
         
        if click_registry.get(p.v, 0) >= HITS_TO_HOT: 
            fg, bg = HOT_FG, "white" 
            coloured_nodes.add(p) 
 
        try: 
            p.edit_widget().configure( 
                state="disabled",highlightthickness=0, fg=fg, bg=bg) 
        except: 
         g.es_exception()
Ejemplo n.º 40
0
def openForRead (self, filename, rb):
    """
    Replaces the standard open for reads.
    Checks and handles shadow files:
        if the length of the real file is zero:
            update the real file from the shadow file.
        else:
            update the shadow file from the real file.
    """
    c = self.c
    shadow_subdir = c.config.getString('shadow_subdir') or shadow_subdir_default
    shadow_prefix = c.config.getString('shadow_prefix') or shadow_prefix_default
    shadow_verbosity = getVerbosity(c)
    try:
        dir, simplename = os.path.split(filename)
        shadow_filename = os.path.join(dir,shadow_subdir,shadow_prefix + simplename)
        if os.path.exists(shadow_filename):
            file_to_read_from = shadow_filename
            newfile = os.path.exists(filename)and os.path.getsize(filename)<=2            
            if newfile:
                if shadow_verbosity >= 2:
                    g.es("Copy %s to %s without sentinels"%(shadow_filename, filename))
                mod_shadow_core.copy_file_removing_sentinels(sourcefilename=shadow_filename,
                                             targetfilename=filename,
                                             marker_from_extension=marker_from_extension)
            else:
                sq = mod_shadow_core.sentinel_squasher(g.es, g.nullObject)
                if shadow_verbosity >= 2:
                    g.es("reading from shadow directory %s"% (
                        shadow_subdir),color="orange")
                written = sq.propagate_changes_from_file_without_sentinels_to_file_with_sentinels(
                                with_sentinels=shadow_filename,
                                without_sentinels=filename,
                                marker_from_extension=marker_from_extension)
                if written:
                    g.es("file %s updated from %s" % (shadow_filename, filename), color="orange")
        else:
            file_to_read_from = filename 
        return open(file_to_read_from,'rb')
    except:
        # Make sure failures to open a file generate clear messages.
        g.es_exception()
        raise 
    def getActiveFont(self):

        box = self.family_list_box
        family = font = None

        # Get the family name if possible, or font otherwise.
        items = box.curselection()
        if len(items) == 0:
            # Nothing selected.
            if self.last_selected_font:
                font = self.last_selected_font
            else:
                font = self.getImpliedFont()
        else:
            try:  # This shouldn't fail now.
                items = map(int, items)
                family = box.get(items[0])
            except:
                g.es("unexpected exception")
                g.es_exception()
                font = self.getImpliedFont()
        # At this point we either have family or font.
        assert (font or family)
        if not family:
            # Extract the family from the computed font.
            family, junk, junk, junk = self.getFontSettings(font)
        # At last we have a valid family name!
        # Get all other font settings from the font panel.
        bold = self.boldVar.get()
        ital = self.italVar.get()
        size = self.sizeVar.get()
        # g.trace(size)
        slant = g.choose(ital, "italic", "roman")
        weight = g.choose(bold, "bold", "normal")
        # Compute the font from all the settings.
        font = tkFont.Font(family=family,
                           size=size,
                           slant=slant,
                           weight=weight)
        self.selectFont(font)
        return font
Ejemplo n.º 42
0
def gotoLineNumberOpen (self,filename):
    """
    Open a file for "goto linenumber" command and check if a shadow file exists.
    Construct a line mapping. This line_mapping instance variable is empty if
    no shadow file exist, otherwise it contains a mapping 
    shadow file number -> real file number.
    """
    try:
        dir, simplename = os.path.split(filename)
        shadow_filename = os.path.join(dir,shadow_subdir,prefix + simplename)
        if os.path.exists(shadow_filename):
            lines = file(shadow_filename).readlines()
            self.line_mapping = push_filter_mapping(lines,marker_from_extension(simplename))
        else:
            self.line_mapping ={}
            lines = file(filename).readlines()
        return lines 
    except:
        # Make sure failures to open a file generate clear messages.
        g.es_exception()
        raise
Ejemplo n.º 43
0
    def getTextFromClipboard(self):

        # g.app.gui.win32clipboard is always None.
        wcb = g.app.gui.win32clipboard

        if wcb:
            try:
                wcb.OpenClipboard(0)
                data = wcb.GetClipboardData()
                wcb.CloseClipboard()
                # g.trace(data)
                return data
            except TypeError:
                # g.trace(None)
                return None
            except:
                g.es_exception()
                return None
        else:
            try:
                s = self.root.selection_get(selection="CLIPBOARD")
                return s
            except:
                return None
Ejemplo n.º 44
0
        """Initialize the plugin from the specified location"""

        # Initial properties
        self.filename = location
        self.name = self.getName(location)

        # Get the contents of the file
        try:
            text = self.getContents()
            self.getDetails(text)
        except InvalidPlugin, err:
            print 'InvalidPlugin', str(err)
            self.description = str(err)
        except:
            g.es('Unexpected exception in initFrom')
            g.es_exception()

    #@nonl
    #@-node:pap.20041006193013:initFrom
    #@+node:ekr.20041113095851:Must be overridden in subclasses...
    #@+node:pap.20041006212105:getName
    def getName(self, location):
        """Determine the plugin name from the location"""

        raise NotImplementedError("Must Override")

    #@-node:pap.20041006212105:getName
    #@+node:pap.20041006193239:getContents
    def getContents(self):
        """Return the contents of the file"""
Ejemplo n.º 45
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
Ejemplo n.º 46
0
    def search(self):
        """Searches the present headline or body text for self.find_text and returns True if found.
    
        self.whole_word, self.ignore_case, and self.pattern_match control the search."""

        __pychecker__ = '--no-implicitreturns'  # Suppress bad warning.

        c = self.c
        v = self.v
        t = self.s_ctrl
        gui = g.app.gui
        assert (c and t and v)
        if self.selection_only:
            index, stopindex = self.selStart, self.selEnd
            # g.trace(index,stopindex,v)
            if index == stopindex:
                return None, None
        else:
            index = gui.getInsertPoint(t)
            stopindex = g.choose(self.reverse, gui.firstIndex(),
                                 gui.lastIndex())
        while 1:
            try:
                pos = self.gui_search(t,
                                      self.find_text,
                                      index,
                                      stopindex=stopindex,
                                      backwards=self.reverse,
                                      regexp=self.pattern_match,
                                      nocase=self.ignore_case)
            except:
                g.es_exception(full=False)
                self.errors += 1
                return None, None
            if not pos:
                return None, None
            if self.find_text == '\n':
                # 2/3/04: A hack.  Time to get rid of gui indices!
                newpos = gui.moveIndexToNextLine(t, pos)
                # g.trace(pos,t.index(newpos))
            else:
                newpos = gui.moveIndexForward(t, pos, len(self.find_text))
            if newpos is None:
                return None, None
            if self.reverse and gui.compareIndices(t, newpos, "==", index):
                #@            << search again after getting stuck going backward >>
                #@+node:ekr.20031218072017.3078:<< search again after getting stuck going backward >>
                index = gui.moveIndexBackward(newpos, len(self.find_text))

                pos = self.gui_search(t,
                                      self.find_text,
                                      index,
                                      stopindex=stopindex,
                                      backwards=self.reverse,
                                      regexp=self.pattern_match,
                                      nocase=self.ignore_case)

                if not pos:
                    return None, None

                newpos = gui.moveIndexForward(t, pos, len(self.find_text))
                #@nonl
                #@-node:ekr.20031218072017.3078:<< search again after getting stuck going backward >>
                #@nl
            #@        << return if we are passed the wrap point >>
            #@+node:ekr.20031218072017.3079:<< return if we are passed the wrap point >>
            if self.wrapping and self.wrapPos and self.wrapVnode and self.v == self.wrapVnode:

                if self.reverse and gui.compareIndices(t, pos, "<",
                                                       self.wrapPos):
                    # g.trace("wrap done")
                    return None, None

                if not self.reverse and gui.compareIndices(
                        t, newpos, ">", self.wrapPos):
                    return None, None
            #@nonl
            #@-node:ekr.20031218072017.3079:<< return if we are passed the wrap point >>
            #@nl
            if self.whole_word:
                index = t.index(g.choose(self.reverse, pos, newpos))
                #@            << continue if not whole word match >>
                #@+node:ekr.20031218072017.3080:<< continue if not whole word match >>
                # Set pos to None if word characters preceed or follow the selection.
                before = gui.getCharBeforeIndex(t, pos)
                first = gui.getCharAtIndex(t, pos)
                last = gui.getCharBeforeIndex(t, newpos)
                after = gui.getCharAtIndex(t, newpos)

                #g.trace("before,first",before,first,g.is_c_id(before),g.is_c_id(first))
                #g.trace("after,last",  after,last,  g.is_c_id(after), g.is_c_id(last))

                if g.is_c_id(before) and g.is_c_id(first):
                    continue

                if g.is_c_id(after) and g.is_c_id(last):
                    continue
                #@nonl
                #@-node:ekr.20031218072017.3080:<< continue if not whole word match >>
                #@nl
            #g.trace("found:",pos,newpos,v)
            gui.setTextSelection(t, pos, newpos)
            return pos, newpos