Ejemplo n.º 1
0
def runSaveFileDialog(initialfile=None,
                      title=None,
                      filetypes=None,
                      defaultextension=None):
    """Call zenity's save file dialog."""
    initialdir = g.app.globalOpenDir or g.os_path_abspath(os.getcwd())
    return callZenity(title, save=True)
Ejemplo n.º 2
0
 def __init__(self, c):
     '''Ctor for the GitDiffController class.'''
     self.c = c
     self.file_node = None
     self.old_dir = g.os_path_abspath('.')
     self.repo_dir = None
     self.root = None
Ejemplo n.º 3
0
    def fixdefault (self,libN,libname):

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

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

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

        return libname
Ejemplo n.º 4
0
    def runOpenFileDialog(self,c,title,filetypes,defaultextension,multiple=False,startpath=None):

        initialdir = g.app.globalOpenDir or g.os_path_abspath(os.getcwd())
        ret = get_input("Open which %s file (from %s?) > " % (repr(filetypes), initialdir))
        if multiple:
            return [ret,]
        return ret
Ejemplo n.º 5
0
 def __init__ (self, c, repo_dir=None):
     '''Ctor for the GitDiffController class.'''
     self.c = c
     self.file_node = None
     self.old_dir = g.os_path_abspath('.')
     self.repo_dir = repo_dir
     self.root = None
Ejemplo n.º 6
0
def runOpenFileDialog(title=None,
                      filetypes=None,
                      defaultextension=None,
                      multiple=False):
    """Call zenity's open file(s) dialog."""
    initialdir = g.app.globalOpenDir or g.os_path_abspath(os.getcwd())
    return callZenity(title, multiple=multiple)
Ejemplo n.º 7
0
    def fixdefault(self, libN, libname):

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

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

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

        return libname
Ejemplo n.º 8
0
 def find_git_working_directory(self):
     '''Return the git working directory.'''
     path = g.os_path_abspath('.')
     while path:
         if g.os_path_exists(g.os_path_finalize_join(path, '.git')):
             return path
         path = g.os_path_finalize_join(path, '..')
     return None
Ejemplo n.º 9
0
 def find_git_working_directory(self):
     '''Return the git working directory.'''
     path = g.os_path_abspath('.')
     while path:
         if g.os_path_exists(g.os_path_finalize_join(path, '.git')):
             return path
         path = g.os_path_finalize_join(path, '..')
     return None
Ejemplo n.º 10
0
    def loadIcons(self, p, clear=False):

        com = self.c.editCommands
        allIcons = com.getIconList(p)
        icons = [i for i in allIcons if 'cleoIcon' not in i]

        if clear:
            iterations = []
        else:
            iterations = [True, False]

        for which in iterations:

            if which == (self.icon_order == 'pri-first'):
                pri = self.getat(p.v, 'priority')
                if pri: pri = int(pri)
                if pri in self.priorities:
                    iconDir = g.os_path_abspath(
                      g.os_path_normpath(
                        g.os_path_join(g.app.loadDir,"..","Icons")))
                    com.appendImageDictToList(icons, iconDir,
                        g.os_path_join('cleo',self.priorities[pri]['icon']),
                        2, on='vnode', cleoIcon='1', where=self.icon_location)
                        # Icon location defaults to 'beforeIcon' unless cleo_icon_location global defined.
                        # Example: @strings[beforeIcon,beforeHeadline] cleo_icon_location = beforeHeadline
                    com.setIconList(p, icons)
            else:

                prog = self.getat(p.v, 'progress')
                if prog is not '':
                    prog = int(prog)
                    use = prog//10*10
                    use = 'prg%03d.png' % use

                    iconDir = g.os_path_abspath(
                      g.os_path_normpath(
                        g.os_path_join(g.app.loadDir,"..","Icons")))

                    com.appendImageDictToList(icons, iconDir,
                        g.os_path_join('cleo',use),
                        2, on='vnode', cleoIcon='1', where=self.prog_location)
                    com.setIconList(p, icons)

        if len(allIcons) != len(icons):  # something to add / remove
            com.setIconList(p, icons)
Ejemplo n.º 11
0
def runSaveFileDialog(initialfile=None,title=None,filetypes=None,defaultextension=None):

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

    trace and g.trace()

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

    return callZenity(title, save=True)
Ejemplo n.º 12
0
 def test_official_g_app_directories(self):
     ivars = ('extensionsDir', 'globalConfigDir', 'loadDir', 'testDir')
     for ivar in ivars:
         assert hasattr(g.app, ivar), 'missing g.app directory: %s' % ivar
         val = getattr(g.app, ivar)
         assert val is not None, 'null g.app directory: %s' % ivar
         assert g.os_path_exists(g.os_path_abspath(
             val)), 'non-existent g.app directory: %s' % ivar
     assert hasattr(g.app, 'homeDir')  # May well be None.
Ejemplo n.º 13
0
def main():
    '''External entry point for Leo's beautifier.'''
    t1 = time.time()
    base = g.os_path_abspath(os.curdir)
    files, options = scan_options()
    for path in files:
        path = g.os_path_finalize_join(base, path)
        beautify(options, path)
    print('beautified %s files in %4.2f sec.' % (len(files), time.time() - t1))
Ejemplo n.º 14
0
def main():
    '''External entry point for Leo's beautifier.'''
    t1 = time.time()
    base = g.os_path_abspath(os.curdir)
    files, options = scan_options()
    for path in files:
        path = g.os_path_finalize_join(base, path)
        beautify(options, path)
    print('beautified %s files in %4.2f sec.' % (len(files), time.time() - t1))
Ejemplo n.º 15
0
def runOpenFileDialog(title=None,filetypes=None,defaultextension=None,multiple=False):

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

    trace and g.trace()

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

    return callZenity(title, multiple=multiple)
Ejemplo n.º 16
0
 def __init__ (self, c, rev1=None, rev2=None):
     '''Ctor for the GitDiffController class.'''
     self.c = c
     self.file_node = None
     self.old_dir = g.os_path_abspath('.')
     self.repo_dir = self.find_git_working_directory()
     self.rev1 = rev1
     self.rev2 = rev2
     self.root = None
Ejemplo n.º 17
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')
Ejemplo n.º 18
0
 def __init__ (self, c, rev1=None, rev2=None):
     '''Ctor for the GitDiffController class.'''
     self.c = c
     self.file_node = None
     self.old_dir = g.os_path_abspath('.')
     self.repo_dir = self.find_git_working_directory()
     self.rev1 = rev1
     self.rev2 = rev2
     self.root = None
Ejemplo n.º 19
0
 def deleteit(result):
     if result is not None:
         # Remove old one
         tc = self.templateCollection
         tc.remove(tc.find(result))
         filename = "%s.tpl" % result
         folder = g.os_path_abspath(self.folder)
         os.remove(g.os_path_join(folder, filename))
         g.es('deleted template %s from %s' % (filename, folder),
              color='blue')
Ejemplo n.º 20
0
 def run(self):
     '''The main line of the git diff command.'''
     if self.repo_dir:
         files = self.get_files()
         if files:
             self.root = self.create_root()
             for fn in files:
                 self.diff_file(fn)
             self.finish()
         else:
             g.es_print('empty git diff')
     else:
         g.es_print('no git repo found in', g.os_path_abspath('.'))
Ejemplo n.º 21
0
  def runOpenFileDialog(self, title, filetypes, defaultextension, multiple=False):
    import os

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

    if g.isPython3: get_input = input
    else:           get_input = raw_input

    ret = get_input("Open which %s file (from %s?) > " % (repr(filetypes), initialdir))

    if multiple:
      return [ret,]
    return ret
Ejemplo n.º 22
0
    def __init__ (self,c):

        self.c = c
        c.cleo = self
        self.donePriority = 100
        self.menuicons = {}  # menu icon cache
        self.recentIcons = []
        #X self.smiley = None
        self.redrawLevels = 0
        
        self.iconDir = g.os_path_abspath(
            g.os_path_normpath(
                g.os_path_join(g.app.loadDir,"..","Icons")))

        #@+<< set / read default values >>
        #@+node:tbrown.20090119215428.12: *4* << set / read default values >>
        self.time_name = 'days'
        if c.config.getString('todo_time_name'):
            self.time_name = c.config.getString('todo_time_name')

        self.icon_location = 'beforeHeadline'
        if c.config.getString('todo_icon_location'):
            self.icon_location = c.config.getString('todo_icon_location')

        self.prog_location = 'beforeHeadline'
        if c.config.getString('todo_prog_location'):
            self.prog_location = c.config.getString('todo_prog_location')

        self.icon_order = 'pri-first'
        if c.config.getString('todo_icon_order'):
            self.icon_order = c.config.getString('todo_icon_order')
        #@-<< set / read default values >>

        self.handlers = [
           ("close-frame",self.close),
           ('select3', self.updateUI),
           ('save2', self.loadAllIcons),
        ]

        # chdir so the Icons can be located
        owd = os.getcwd()
        os.chdir(os.path.split(__file__)[0])
        self.ui = cleoQtUI(self)
        os.chdir(owd)

        for i in self.handlers:
            g.registerHandler(i[0], i[1])

        self.loadAllIcons()
Ejemplo n.º 23
0
 def runOpenFileDialog(self,
                       c,
                       title,
                       filetypes,
                       defaultextension,
                       multiple=False,
                       startpath=None):
     initialdir = g.app.globalOpenDir or g.os_path_abspath(os.getcwd())
     ret = get_input("Open which %s file (from %s?) > " %
                     (repr(filetypes), initialdir))
     if multiple:
         return [
             ret,
         ]
     return ret
Ejemplo n.º 24
0
 def get_plugins(self):
     """Return a list of all plugins *without* importing them."""
     excludes = (
         # These are not real plugins...
         'babel_api.py',
         'babel_kill.py',
         'babel_lib.py',
         'baseNativeTree.py',
         'leocursor.py',
         'leo_cloud_server.py',
         'leo_mypy_plugin.py',
         'nested_splitter.py',
         'qtGui.py',
         'qt_gui.py',
         'qt_big_text.py',
         'qt_commands.py',
         'qt_events.py',
         'qt_frame.py',
         'qt_idle_time.py',
         'qt_main.py',
         'qt_quickheadlines.py',
         'qt_quicksearch_sub.py',
         'qt_text.py',
         'qt_tree.py',
         'qt_quicksearch.py',
         'swing_gui.py',
         # Experimental.
         'leo_pdf.py',
     )
     plugins = g.os_path_join(g.app.loadDir, '..', 'plugins', '*.py')
     plugins = g.os_path_abspath(plugins)
     files = glob.glob(plugins)
     files = [z for z in files if not z.endswith('__init__.py')]
     files = [z for z in files if g.shortFileName(z) not in excludes]
     files = [g.os_path_abspath(z) for z in files]
     return sorted(files)
Ejemplo n.º 25
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.h.strip()
        if h and h[0] != '@':
            #@+<< find path and start file >>
            #@+node:ekr.20040828103325.4: *3* << 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.h.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.warning('%s not found in %s' % (filename, startdir))
            os.chdir(thisdir)  # restore the original current dir.
Ejemplo n.º 26
0
 def get_rc_file(self):
     '''Return the path to the pylint configuration file.'''
     base = 'pylint-leo-rc.txt'
     table = (
         g.os_path_finalize_join(g.app.homeDir, '.leo', base),
             # In ~/.leo
         g.os_path_finalize_join(g.app.loadDir, '..', '..', 'leo', 'test', base),
             # In leo/test
     )
     for fn in table:
         fn = g.os_path_abspath(fn)
         if g.os_path_exists(fn):
             return fn
     g.es_print('no pylint configuration file found in\n%s' % (
         '\n'.join(table)))
     return None
Ejemplo n.º 27
0
 def get_rc_file(self):
     '''Return the path to the pylint configuration file.'''
     base = 'pylint-leo-rc.txt'
     table = (
         g.os_path_finalize_join(g.app.homeDir, '.leo', base),
             # In ~/.leo
         g.os_path_finalize_join(g.app.loadDir, '..', '..', 'leo', 'test', base),
             # In leo/test
     )
     for fn in table:
         fn = g.os_path_abspath(fn)
         if g.os_path_exists(fn):
             return fn
     g.es_print('no pylint configuration file found in\n%s' % (
         '\n'.join(table)))
     return None
Ejemplo n.º 28
0
 def get_flake8_config(self):
     """Return the path to the pylint configuration file."""
     join = g.os_path_finalize_join
     dir_table = (
         g.app.homeDir,
         join(g.app.homeDir, '.leo'),
         join(g.app.loadDir, '..', '..', 'leo', 'test'),
     )
     for base in ('flake8', 'flake8.txt'):
         for path in dir_table:
             fn = g.os_path_abspath(join(path, base))
             if g.os_path_exists(fn):
                 return fn
     if not g.unitTesting:
         table_s = '\n'.join(dir_table)
         g.es_print(f"no flake8 configuration file found in\n{table_s}")
     return None
Ejemplo n.º 29
0
 def get_rc_file(self):
     """Return the path to the pylint configuration file."""
     base = 'pylint-leo-rc.txt'
     table = (
         # In ~/.leo
         g.os_path_finalize_join(g.app.homeDir, '.leo', base),
         # In leo/test
         g.os_path_finalize_join(g.app.loadDir, '..', '..', 'leo', 'test',
                                 base),
     )
     for fn in table:
         fn = g.os_path_abspath(fn)
         if g.os_path_exists(fn):
             return fn
     table_s = '\n'.join(table)
     g.es_print(f"no pylint configuration file found in\n{table_s}")
     return None
Ejemplo n.º 30
0
 def run(self):
     '''The main line of the git diff command.'''
     if self.repo_dir:
         # 1. Diff the given revs.
         ok = self.diff_revs()
         # Go back several revs...
         n1, n2 = 1, 0
         while not ok and n1 <= 5:
             # 2. Diff HEAD@{0} HEAD@{1}
             self.rev1 = 'HEAD@{%s}' % (n1)
             self.rev2 = 'HEAD@{%s}' % (n2)
             ok = self.diff_revs()
             n1, n2 = n1+1, n2+1
         if not ok:
             g.es_print('no changed readable files from HEAD@{1}..HEAD@(5)')
     else:
         g.es_print('no git repo found in', g.os_path_abspath('.'))
Ejemplo n.º 31
0
 def run(self):
     '''The main line of the git diff command.'''
     if self.repo_dir:
         # 1. Diff the given revs.
         ok = self.diff_revs()
         # Go back several revs...
         n1, n2 = 1, 0
         while not ok and n1 <= 5:
             # 2. Diff HEAD@{0} HEAD@{1}
             self.rev1 = 'HEAD@{%s}' % (n1)
             self.rev2 = 'HEAD@{%s}' % (n2)
             ok = self.diff_revs()
             n1, n2 = n1 + 1, n2 + 1
         if not ok:
             g.es_print('no changed readable files from HEAD@{1}..HEAD@(5)')
     else:
         g.es_print('no git repo found in', g.os_path_abspath('.'))
Ejemplo n.º 32
0
def open_theme_file_helper(event, closeFlag, fn):
    '''Open a theme file and apply the theme.'''
    trace = False and not g.unitTesting
    c = event and event.get('c')
    if not c: return
    old_dir = g.os_path_abspath(os.curdir)
    themes_dir = g.os_path_finalize_join(g.app.loadDir, '..', 'themes')
    if fn:
        fn = c.styleSheetManager.find_theme_file(fn)
        if not fn: return
    else:
        fn = g.app.gui.runOpenFileDialog(c,
            title="Open Theme",
            filetypes=[
                 g.fileFilters("LEOFILES"),
                ("All files", "*"),
            ],
            defaultextension=g.defaultLeoFileExtension(c),
            startpath=themes_dir,
        )
    c.bringToFront()
    c.init_error_dialogs()
    # Adapted from c.open().
    if fn and g.app.loadManager.isLeoFile(fn):
        # Close the file if it is already open, provided there is another.
        aList = g.app.commanders()
        if len(aList) > 1:
            for c2 in aList:
                if trace: g.trace('COMPARE\n%s\n%s' % (fn, c2.fileName()))
                if fn == c2.fileName():
                    if trace: g.trace('===== CLOSING', fn)
                    c2.close(new_c=c)
                    break
        c2 = g.openWithFileName(fn, old_c=c)
        if c2:
            c2.k.makeAllBindings()
            g.chdir(fn)
            g.setGlobalOpenDir(fn)
            if closeFlag:
                g.app.destroyWindow(c2.frame)
                g.app.windowList.remove(c2.frame)
    os.chdir(old_dir)
    c.raise_error_dialogs(kind='write')
    g.app.runAlreadyOpenDialog(c)
    c.initialFocusHelper()
Ejemplo n.º 33
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.h.strip()
        if h and h[0]!='@':
            #@+<< find path and start file >>
            #@+node:ekr.20040828103325.4: *3* << 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.h.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.warning('%s not found in %s' % (filename,startdir))
            os.chdir(thisdir) # restore the original current dir.
Ejemplo n.º 34
0
 def set_directory(self, directory):
     """
     Handle directory inits.
     Return True if the .git directory has been found.
     """
     if not directory:
         if self.repo_dir:
             # Use previously-computed result.
             return self.repo_dir
         directory = g.os_path_abspath(os.curdir)
     #
     # Change to the new directory.
     self.repo_dir = self.find_git_working_directory(directory)
     if self.repo_dir:
         os.chdir(directory)
     else:
         g.es_print(f"no .git directory found in {directory!r}")
     return self.repo_dir
Ejemplo n.º 35
0
def get_flake8_config():
    '''Return the path to the flake8 configuration file.'''
    join = g.os_path_finalize_join
    homeDir = get_home()
    loadDir = g.os_path_finalize_join(g.__file__, '..', '..')
    base_table = ('flake8', 'flake8.txt')
    dir_table = (
        homeDir,
        join(homeDir, '.leo'),
        join(loadDir, '..', '..', 'leo', 'test'),
    )
    for base in base_table:
        for path in dir_table:
            fn = g.os_path_abspath(join(path, base))
            if g.os_path_exists(fn):
                return fn
    print('no flake8 configuration file found in\n%s' % ('\n'.join(dir_table)))
    return None
Ejemplo n.º 36
0
 def set_directory(self, directory):
     '''
     Handle directory inits.
     Return True if the .git directory has been found.
     '''
     if not directory:
         if self.repo_dir:
             # Use previously-computed result.
             return self.repo_dir
         directory = g.os_path_abspath(os.curdir)
     #
     # Change to the new directory.
     self.repo_dir = self.find_git_working_directory(directory)
     if self.repo_dir:
         os.chdir(directory)
     else:
         g.es_print('no .git directory found in %r' % directory)
     return self.repo_dir
Ejemplo n.º 37
0
def doSubprocessTable():

    if 1:
        pythonDir = g.os_path_dirname(sys.executable)
        idle = g.os_path_abspath(
            g.os_path_join(pythonDir, 'Lib', 'idlelib', 'idle.pyw'))
        table = (
            (
                "Idle",
                "Alt+Ctrl+I",
                (
                    "subprocess.Popen",
                    # ["pythonw", "C:/Python24/Lib/idlelib/idle.pyw"], ".py")),
                    ["pythonw", idle],
                    ".py")),
            ("Word", "Alt+Ctrl+W",
             ("subprocess.Popen",
              "C:/Program Files/Microsoft Office/Office/WINWORD.exe", None)),
            ("WordPad", "Alt+Ctrl+T",
             ("subprocess.Popen",
              "C:/Program Files/Windows NT/Accessories/wordpad.exe", None)),
        )
    else:  # Jim Sizelove's table
        table = (
            ("Emacs", "Alt+Ctrl+E",
             ("subprocess.Popen", "C:/Program Files/Emacs/bin/emacs.exe",
              None)),
            ("Gvim", "Alt+Ctrl+G", ("subprocess.Popen", [
                "C:/Program Files/Vim/vim63/gvim.exe", "--servername", "LEO",
                "--remote-silent"
            ], None)),
            ("Idle", "Alt+Ctrl+I",
             ("subprocess.Popen",
              ["pythonw", "C:/Python24/Lib/idlelib/idle.pyw"], ".py")),
            ("NotePad", "Alt+Ctrl+N", ("os.startfile", None, ".txt")),
            ("PythonWin", "Alt+Ctrl+P",
             ("subprocess.Popen",
              "C:/Python24/Lib/site-packages/pythonwin/Pythonwin.exe", None)),
            ("WordPad", "Alt+Ctrl+W",
             ("subprocess.Popen",
              "C:/Program Files/Windows NT/Accessories/wordpad.exe", None)),
        )

    return table
Ejemplo n.º 38
0
def doDefaultTable ():

    if 1: # Default table.
        pythonDir = g.os_path_dirname(sys.executable)
        idle = g.os_path_abspath(g.os_path_join(pythonDir,'tools','idle','idle.py'))
        idle_arg = "%s -e" % idle
        table = (
            # Opening idle this way doesn't work so well.
            # ("&Idle",   "Alt+Shift+I",("os.system",idle_arg,".py")),
            ("&Word",   "Alt+Shift+W",("os.startfile",None,".doc")),
            ("Word&Pad","Alt+Shift+T",("os.startfile",None,".txt")))

    elif 0: # Test table.
        table = ("&Word","Alt+Shift+W",("os.startfile",None,".doc")),

    elif 0: # David McNab's table.
        table = ("X&Emacs", "Ctrl+E", ("os.spawnl","/usr/bin/gnuclient", None)),

    return table
Ejemplo n.º 39
0
def get_flake8_config():
    '''Return the path to the flake8 configuration file.'''
    join = g.os_path_finalize_join
    homeDir = get_home()
    loadDir = g.os_path_finalize_join(g.__file__, '..', '..')
    base_table = ('flake8', 'flake8.txt')
    dir_table = (
        homeDir,
        join(homeDir, '.leo'),
        join(loadDir, '..', '..', 'leo', 'test'),
    )
    for base in base_table:
        for path in dir_table:
            fn = g.os_path_abspath(join(path, base))
            if g.os_path_exists(fn):
                return fn
    print('no flake8 configuration file found in\n%s' % (
        '\n'.join(dir_table)))
    return None
Ejemplo n.º 40
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()
Ejemplo n.º 41
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()
Ejemplo n.º 42
0
def doDefaultTable():

    if 1:  # Default table.
        pythonDir = g.os_path_dirname(sys.executable)
        idle = g.os_path_abspath(
            g.os_path_join(pythonDir, 'tools', 'idle', 'idle.py'))
        idle_arg = "%s -e" % idle
        table = (
            # Opening idle this way doesn't work so well.
            # ("&Idle",   "Alt+Shift+I",("os.system",idle_arg,".py")),
            ("&Word", "Alt+Shift+W", ("os.startfile", None, ".doc")),
            ("Word&Pad", "Alt+Shift+T", ("os.startfile", None, ".txt")))

    elif 0:  # Test table.
        table = ("&Word", "Alt+Shift+W", ("os.startfile", None, ".doc")),

    elif 0:  # David McNab's table.
        table = ("X&Emacs", "Ctrl+E", ("os.spawnl", "/usr/bin/gnuclient",
                                       None)),

    return table
Ejemplo n.º 43
0
 def get_flake8_config(self):
     '''Return the path to the pylint configuration file.'''
     join = g.os_path_finalize_join
     dir_table = (
         g.app.homeDir,
         join(g.app.homeDir, '.leo'),
         join(g.app.loadDir, '..', '..', 'leo', 'test'),
     )
     if g.isPython3:
         base_table = ('flake8', 'flake8.txt')
     else:
         base_table = ('flake8',)
     for base in base_table:
         for path in dir_table:
             fn = g.os_path_abspath(join(path, base))
             if g.os_path_exists(fn):
                 return fn
     if not g.unitTesting:
         g.es_print('no flake8 configuration file found in\n%s' % (
             '\n'.join(dir_table)))
     return None
Ejemplo n.º 44
0
 def get_flake8_config(self):
     '''Return the path to the pylint configuration file.'''
     join = g.os_path_finalize_join
     dir_table = (
         g.app.homeDir,
         join(g.app.homeDir, '.leo'),
         join(g.app.loadDir, '..', '..', 'leo', 'test'),
     )
     if g.isPython3:
         base_table = ('flake8', 'flake8.txt')
     else:
         base_table = ('flake8',)
     for base in base_table:
         for path in dir_table:
             fn = g.os_path_abspath(join(path, base))
             if g.os_path_exists(fn):
                 return fn
     if not g.unitTesting:
         g.es_print('no flake8 configuration file found in\n%s' % (
             '\n'.join(dir_table)))
     return None
Ejemplo n.º 45
0
def start_file(c,p):

    # Set the base directory by searching for @folder directives in ancestors.
    h = p.h.strip()
    thisdir = os.path.abspath(os.curdir) # remember the current dir
    basedir = thisdir[:] # use current dir as default.
    parent = p.parent() # start with parent
    while parent: # stop when no more parent found
        p = parent.h.strip()
        if g.match_word(p,0,'@folder'):
            basedir = p[8:] # take rest of headline as pathname
            break # we found the closest @folder
        else:
            parent = parent.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.
                # pylint: disable=no-member
                # Previous code checks that os.startfile exists.
                os.startfile(filename)
                    # This may not work for all file types.
            except Exception:
                g.es(filename+' - file not found in '+startdir)
                g.es_exception()
        else:
            g.warning('%s not found in %s' % (filename,startdir))
    os.chdir(thisdir) # restore the original current dir.
Ejemplo n.º 46
0
def doSubprocessTable ():

    if 1:
        pythonDir = g.os_path_dirname(sys.executable)
        idle = g.os_path_abspath(g.os_path_join(pythonDir,'Lib','idlelib','idle.pyw'))
        table = (
            ("Idle", "Alt+Ctrl+I",
                ("subprocess.Popen",
                    # ["pythonw", "C:/Python24/Lib/idlelib/idle.pyw"], ".py")),
                    ["pythonw", idle], ".py")),
            ("Word", "Alt+Ctrl+W",
                ("subprocess.Popen",
                "C:/Program Files/Microsoft Office/Office/WINWORD.exe",
                None)),
            ("WordPad", "Alt+Ctrl+T",
                ("subprocess.Popen",
                "C:/Program Files/Windows NT/Accessories/wordpad.exe",
                None)),
        )
    else: # Jim Sizelove's table
        table = (
            ("Emacs", "Alt+Ctrl+E",
                ("subprocess.Popen", "C:/Program Files/Emacs/bin/emacs.exe", None)),
            ("Gvim", "Alt+Ctrl+G",
                ("subprocess.Popen",
                ["C:/Program Files/Vim/vim63/gvim.exe", 
                "--servername", "LEO", "--remote-silent"], None)),
            ("Idle", "Alt+Ctrl+I",
                ("subprocess.Popen",
                ["pythonw", "C:/Python24/Lib/idlelib/idle.pyw"], ".py")),
            ("NotePad", "Alt+Ctrl+N",
                ("os.startfile", None, ".txt")),
            ("PythonWin", "Alt+Ctrl+P",
                ("subprocess.Popen", "C:/Python24/Lib/site-packages/pythonwin/Pythonwin.exe", None)),
            ("WordPad", "Alt+Ctrl+W",
                ("subprocess.Popen", "C:/Program Files/Windows NT/Accessories/wordpad.exe", None)),
        )

    return table
Ejemplo n.º 47
0
def start_file(c,p):

    # Set the base directory by searching for @folder directives in ancestors.
    h = p.h.strip()
    thisdir = os.path.abspath(os.curdir) # remember the current dir
    basedir = thisdir[:] # use current dir as default.
    parent = p.parent() # start with parent
    while parent: # stop when no more parent found
        p = parent.h.strip()
        if g.match_word(p,0,'@folder'):
            basedir = p[8:] # take rest of headline as pathname
            break # we found the closest @folder
        else:
            parent = parent.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 Exception:
        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.
                # pylint: disable=no-member
                # Previous code checks that os.startfile exists.
                os.startfile(filename)
                    # This may not work for all file types.
            except Exception:
                g.es(filename+' - file not found in '+startdir)
                g.es_exception()
        else:
            g.warning('%s not found in %s' % (filename,startdir))
    os.chdir(thisdir) # restore the original current dir.
Ejemplo n.º 48
0
Archivo: todo.py Proyecto: vivainio/leo
    def menuicon(self, pri, progress=False):
        """return icon from cache, placing it there if needed"""

        if progress:
            prog = pri
            pri = 'prog-%d'%pri

        if pri not in self.menuicons:

            if progress:
                fn = 'prg%03d.png' % prog
            else:
                fn = self.priorities[pri]["icon"]

            iconDir = g.os_path_abspath(
              g.os_path_normpath(
                g.os_path_join(g.app.loadDir,"..","Icons")))

            fn = g.os_path_join(iconDir,'cleo',fn)

            self.menuicons[pri] = QtGui.QIcon(fn)

        return self.menuicons[pri]
Ejemplo n.º 49
0
 def loadIcons(self, p):
     com = self.c.editCommands
     allIcons = com.getIconList(p)
     icons = [i for i in allIcons if 'cleoIcon' not in i]
     pri = self.getat(p.v, 'priority')
     if pri: pri = int(pri)
     if pri in self.priorities:
         cleo_icon_path = self.c.config.getString('cleo_icon_path')
         if not cleo_icon_path:
             cleo_icon_path = 'cleo'  # relative to leo Icons dir
         iconDir = g.os_path_abspath(
           g.os_path_normpath(
             g.os_path_join(g.app.loadDir,"..","Icons")))
         com.appendImageDictToList(icons, iconDir,
             g.os_path_join(cleo_icon_path,self.priorities[pri]['icon']),
             2, on='vnode', cleoIcon='1', where=self.icon_location)
             # Icon location defaults to 'beforeIcon' unless cleo_icon_location global defined.
             # Example: @strings[beforeIcon,beforeHeadline] cleo_icon_location = beforeHeadline
             # Note: 'beforeBox' and 'afterHeadline' collide with other elements on the line.
         com.setIconList(p, icons)
     else:
         if len(allIcons) != len(icons):  # something to remove
             com.setIconList(p, icons)
Ejemplo n.º 50
0
 def finalize(self, fn):
     '''Finalize and regularize a filename.'''
     return g.os_path_normpath(g.os_path_abspath(g.os_path_expanduser(fn)))
Ejemplo n.º 51
0
 def __init__(self, c, repo_dir=None):
     self.c = c
     self.file_node = None
     self.old_dir = g.os_path_abspath('.')
     self.repo_dir = repo_dir
     self.root = None
Ejemplo n.º 52
0
 def _no_image():
     """return QGraphicsPixmapItem with "No Image" image loaded"""
     testpath = g.os_path_abspath(g.os_path_join(
         g.app.loadDir,'../plugins/GraphCanvas/no_image.png'))
     return QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap(testpath))
Ejemplo n.º 53
0
 def _no_image():
     """return QGraphicsPixmapItem with "No Image" image loaded"""
     testpath = g.os_path_abspath(
         g.os_path_join(g.app.loadDir,
                        '../plugins/GraphCanvas/no_image.png'))
     return QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap(testpath))
Ejemplo n.º 54
0
 def finalize(self, fn):
     '''Finalize and regularize a filename.'''
     return g.os_path_normpath(
         g.os_path_abspath(g.os_path_expanduser(fn)))
Ejemplo n.º 55
0
    def _babelExec(babelG, babelCmdr, babelRoot):
        """ Execute a Script

        Arguments:
            babelG: Babel globals
            babelCmdr: Leo-Editor commander for the file containing
                the script to execute
            babelRoot:  The "Babel Root" for the script to execute

        Returns:
            None

        Side Effects:
            For each line <line> in the target node body,
                A child node is created with empty body and headline "<elapsed time> - <line>"
                If <line> writes any non-blanks to stdout, then a child node is created with
                headline "stdout - <line>" and body containing the standard output.
                If <line> writes any non-blanks to stderr, then a child node is created with
                headline "stderr - <line>" and body containing the standard error output.

        Most importantly the output nodes are created in real time when they occur, not
        later when the <line> terminates.

        If there is a selected range, then this selected range is executed.
        If there is no selected range, then the whole body of the currently selected
        node is executed.

        If the language at the current cursor position is "python," then the
        Python interpreter executes the target text.
        If the language at the current cursor position is "shell," then the
        Bash interpreter executes the target text.

        The scheme for real-time streaming of stdout and stderr while the script is still executing is taken from:

        http://stackoverflow.com/questions/18421757/live-output-from-subprocess-command


        """

        script = getScript(cmdr, babelRoot, useSelectedText=False, language='python')
        code = compile(script, 'Babel Parameter Script', 'exec')

        gld = {'babel': babelG.babel_api,
            'b': babelG.babel_api,
            '__file__': 'Babel Parameter Script',
            'c': cmdr,
            'g': leoG,
            'p': babelRoot}
        exec(code, gld)

        # Create Nodes?
        createNodes = gld.get('babel_node_creation')
        if createNodes is None:
            createNodes = babelCmdr.nodeCreationDefault
        cmdrScr, scriptRoot = scrOrResRoot(cmdr, gld, babelG, babelRoot, 'script')
        if createNodes:
            cmdrRes, resultsRoot = scrOrResRoot(cmdr, gld, babelG, babelRoot, 'results')
        else:
            cmdrRes = None
            resultsRoot = None

        # Determine the language and then the interpreter
        langx = leoG.scanForAtLanguage(cmdrScr, scriptRoot)
        if langx == 'python':
            interpreter = gld.get('babel_python')
            if not interpreter:
                interpreter = babelCmdr.interpreterPython
            cmdList = [interpreter, '-u']
        elif langx == 'shell':
            interpreter = gld.get('babel_shell')
            if not interpreter:
                interpreter =  babelCmdr.interpreterShell
            cmdList = [interpreter]
        else:
            babelCmdr.babelExecCnt += 1
            raise  babelG.babel_api.BABEL_LANGUAGE('Unknown language "{0}"'.format(langx))

        script = getScript(cmdrScr, scriptRoot, useSelectedText=False, language=langx)

        cmdrScr.setCurrentDirectoryFromContext(scriptRoot)
        cwd = leoG.os_path_abspath(os.getcwd())

        pathScript = cmdr.writeScriptFile(script)
        cmdList.append(pathScript)
        babel_script_args = gld.get('babel_script_args')
        if babel_script_args:
            cmdList.extend(babel_script_args)
        # pylint: disable=unexpected-keyword-arg
        wro = tempfile.NamedTemporaryFile(buffering=0)
        wre = tempfile.NamedTemporaryFile(buffering=0)
        reo = io.open(wro.name, 'rb', buffering=0)
        ree = io.open(wre.name, 'rb', buffering=0)

        if gld.get('babel_redirect_stdout'):
            # Redirect stdout to stderr
            wro = wre

        babelCmdr.cmdDoneFlag = False
        babelCmdr.cmdDoneStdPolled = False
        babelCmdr.cmdDoneErrPolled = False

        start = time.time()
        subPscript = subprocess.Popen(cmdList, cwd=cwd, stdout=wro, stderr=wre)
        subPbabKill = subprocess.Popen([babelG.pathBabelKill, str(subPscript.pid)])

        babelCmdr.reo = reo     # Kludge to allow itf() to determine which output it polls
        itOut = leoG.IdleTime((lambda ito: itf(babelCmdr.colorStdout, reo, babelCmdr)), delay=1000)
        itErr = leoG.IdleTime((lambda ito: itf(babelCmdr.colorStderr, ree, babelCmdr)), delay=1000)
        if (not itOut) or (not itErr):
            raise babelG.babel_api.BABEL_ERROR('leoG.IdleTime() failed')
        itOut.start()
        itErr.start()

        itPoll = leoG.IdleTime((lambda itobj: itp(itobj, cmdr, cmdrRes, resultsRoot,
            subPscript, subPbabKill, wro, reo, wre, ree, itOut, itErr, start,
            createNodes)), delay=1000)
        if not itPoll:
            raise babelG.babel_api.BABEL_ERROR('leoG.IdleTime() failed')
        itPoll.start()