Пример #1
0
def cmd_PickDir(c):
    """cmd_PickDir - Show user a folder picker to create
    a new top level @path node

    :Parameters:
    - `c`: outline
    """

    p = c.p
    aList = g.get_directives_dict_list(p)
    path = c.scanAtPathDirectives(aList)
    if p.h.startswith('@'):  # see if it's a @<file> node of some sort
        nodepath = p.h.split(None, 1)[-1]
        nodepath = g.os_path_join(path, nodepath)
        if not g.os_path_isdir(nodepath):  # remove filename
            nodepath = g.os_path_dirname(nodepath)
        if g.os_path_isdir(nodepath):  # append if it's a directory
            path = nodepath

    ocwd = os.getcwd()
    try:
        os.chdir(path)
    except OSError:
        g.es("Couldn't find path %s"%path)
    dir_ = g.app.gui.runOpenDirectoryDialog("Pick a folder", "Pick a folder")
    os.chdir(ocwd)
    
    if not dir_:
        g.es("No folder selected")
        return
    
    nd = c.p.insertAfter()
    nd.h = "@path %s" % dir_
    c.redraw()
Пример #2
0
def cmd_PickDir(event):
    """cmd_PickDir - Show user a folder picker to create
    """
    c = event.get('c')
    p = c.p
    aList = g.get_directives_dict_list(p)
    path = c.scanAtPathDirectives(aList)
    if p.h.startswith('@'):  # see if it's a @<file> node of some sort
        nodepath = p.h.split(None, 1)[-1]
        nodepath = g.os_path_join(path, nodepath)
        if not g.os_path_isdir(nodepath):  # remove filename
            nodepath = g.os_path_dirname(nodepath)
        if g.os_path_isdir(nodepath):  # append if it's a directory
            path = nodepath
    ocwd = os.getcwd()
    try:
        os.chdir(path)
    except OSError:
        g.es("Couldn't find path %s" % path)
    dir_ = g.app.gui.runOpenDirectoryDialog("Pick a folder", "Pick a folder")
    os.chdir(ocwd)
    if not dir_:
        g.es("No folder selected")
        return
    nd = c.p.insertAfter()
    nd.h = "@path %s" % dir_
    c.redraw()
Пример #3
0
def _path_from_pos(c, p):
    """_path_from_pos - get folder for position

    FIXME: should be in Leo core somewhere.

    Args:
        p (position): position

    Returns:
        str: path
    """
    p = p.copy()

    def atfile(p):
        word0 = p.h.split()[0]
        return (word0 in g.app.atFileNames | set(['@auto'])
                or word0.startswith('@auto-'))

    aList = g.get_directives_dict_list(p)
    path = c.scanAtPathDirectives(aList)
    while c.positionExists(p):
        if atfile(p):  # see if it's a @<file> node of some sort
            nodepath = p.h.split(None, 1)[-1]
            nodepath = g.os_path_join(path, nodepath)
            if not g.os_path_isdir(nodepath):  # remove filename
                nodepath = g.os_path_dirname(nodepath)
            if g.os_path_isdir(nodepath):  # append if it's a directory
                path = nodepath
            break
        p.moveToParent()

    return path
Пример #4
0
def _path_from_pos(c, p):
    """_path_from_pos - get folder for position

    FIXME: should be in Leo core somewhere.

    Args:
        p (position): position

    Returns:
        str: path
    """
    p = p.copy()

    def atfile(p):
        word0 = p.h.split()[0]
        return (
            word0 in g.app.atFileNames|set(['@auto']) or
            word0.startswith('@auto-')
        )

    aList = g.get_directives_dict_list(p)
    path = c.scanAtPathDirectives(aList)
    while c.positionExists(p):
        if atfile(p):  # see if it's a @<file> node of some sort
            nodepath = p.h.split(None, 1)[-1]
            nodepath = g.os_path_join(path, nodepath)
            if not g.os_path_isdir(nodepath):  # remove filename
                nodepath = g.os_path_dirname(nodepath)
            if g.os_path_isdir(nodepath):  # append if it's a directory
                path = nodepath
            break
        p.moveToParent()

    return path
Пример #5
0
def screen_capture_now(kwargs=None):
    """screen_capture_now - save a screenshot

    :Parameters:
    - `kwargs`: g.command arguments
    """
    if kwargs is None:
        kwargs = {}
    if not hasattr(g, '_recorder'):
        g._recorder = Recorder()
    c = g.app.commanders()[0]
    dirname = c.config.getString("screen-capture-save-path")
    if not dirname:
        dirname = g.os_path_join(
            g.computeHomeDir(),
            '.leo',
            'screen_captures'
        )
    dirname = g.os_path_expanduser(dirname)
    if not g.os_path_isdir(dirname):
        os.makedirs(dirname)
    filename = g.os_path_join(
        dirname,
        time.strftime('%Y-%m-%dT%H-%M-%S')+'.png'
    )
    g._recorder.grab_frame(filename=filename)
    # *only* print, don't want output messing up log view in screen shots
    print("Screenshot: %s"%filename)
Пример #6
0
 def has_changed(self, c, path):
     '''Return True if p's external file has changed outside of Leo.'''
     if not g.os_path_exists(path):
         return False
     if g.os_path_isdir(path):
         return False
     #
     # First, check the modification times.
     old_time = self.get_time(path)
     new_time = self.get_mtime(path)
     if not old_time:
         # Initialize.
         self.set_time(path, new_time)
         self.checksum_d[path] = self.checksum(path)
         return False
     if old_time == new_time:
         return False
     #
     # Check the checksums *only* if the mod times don't match.
     old_sum = self.checksum_d.get(path)
     new_sum = self.checksum(path)
     if new_sum == old_sum:
         # The modtime changed, but it's contents didn't.
         # Update the time, so we don't keep checking the checksums.
         # Return False so we don't prompt the user for an update.
         self.set_time(path, new_time)
         return False
     # The file has really changed.
     assert old_time, path
     # #208: external change overwrite protection only works once.
     # If the Leo version is changed (dirtied) again,
     # overwrite will occur without warning.
         # self.set_time(path, new_time)
         # self.checksum_d[path] = new_sum
     return True
Пример #7
0
 def has_changed(self, path):
     """Return True if the file at path has changed outside of Leo."""
     if not path:
         return False
     if not g.os_path_exists(path):
         return False
     if g.os_path_isdir(path):
         return False
     #
     # First, check the modification times.
     old_time = self.get_time(path)
     new_time = self.get_mtime(path)
     if not old_time:
         # Initialize.
         self.set_time(path, new_time)
         self.checksum_d[path] = self.checksum(path)
         return False
     if old_time == new_time:
         return False
     #
     # Check the checksums *only* if the mod times don't match.
     old_sum = self.checksum_d.get(path)
     new_sum = self.checksum(path)
     if new_sum == old_sum:
         # The modtime changed, but it's contents didn't.
         # Update the time, so we don't keep checking the checksums.
         # Return False so we don't prompt the user for an update.
         self.set_time(path, new_time)
         return False
     # The file has really changed.
     assert old_time, path
     return True
Пример #8
0
 def makeShadowDirectory(self, fn):
     '''Make a shadow directory for the **public** fn.'''
     x = self; path = x.shadowDirName(fn)
     if not g.os_path_exists(path):
         # Force the creation of the directories.
         g.makeAllNonExistentDirectories(path, c=None, force=True)
     return g.os_path_exists(path) and g.os_path_isdir(path)
Пример #9
0
 def makeShadowDirectory(self, fn):
     """Make a shadow directory for the **public** fn."""
     x = self; path = x.shadowDirName(fn)
     if not g.os_path_exists(path):
         # Force the creation of the directories.
         g.makeAllNonExistentDirectories(path, c=None, force=True)
     return g.os_path_exists(path) and g.os_path_isdir(path)
Пример #10
0
def screen_capture_now(kwargs=None):
    """screen_capture_now - save a screenshot

    :Parameters:
    - `kwargs`: g.command arguments
    """
    if kwargs is None:
        kwargs = {}
    if not hasattr(g, '_recorder'):
        g._recorder = Recorder()
    c = g.app.commanders()[0]
    dirname = c.config.getString("screen-capture-save-path")
    if not dirname:
        dirname = g.os_path_join(
            g.computeHomeDir(),
            '.leo',
            'screen_captures'
        )
    dirname = g.os_path_expanduser(dirname)
    if not g.os_path_isdir(dirname):
        os.makedirs(dirname)
    filename = g.os_path_join(
        dirname,
        time.strftime('%Y-%m-%dT%H-%M-%S')+'.png'
    )
    g._recorder.grab_frame(filename=filename)
    # *only* print, don't want output messing up log view in screen shots
    print("Screenshot: %s"%filename)
Пример #11
0
 def openOutlineByNameFinisher(self, fn):
     c = self.c
     if fn and g.os_path_exists(fn) and not g.os_path_isdir(fn):
         c2 = g.openWithFileName(fn, old_c=c)
         try:
             g.app.gui.runAtIdle(c2.treeWantsFocusNow)
         except Exception:
             pass
     else:
         g.es('ignoring: %s' % fn)
Пример #12
0
 def openOutlineByNameFinisher(self, fn):
     c = self.c
     if fn and g.os_path_exists(fn) and not g.os_path_isdir(fn):
         c2 = g.openWithFileName(fn, old_c=c)
         try:
             g.app.gui.runAtIdle(c2.treeWantsFocusNow)
         except Exception:
             pass
     else:
         g.es('ignoring: %s' % fn)
Пример #13
0
 def has_changed(self, c, path):
     '''Return True if p's external file has changed outside of Leo.'''
     trace = False and not g.unitTesting
     verbose_init = False
     tag = 'efc.has_changed'
     if not g.os_path_exists(path):
         if trace: print('%s:does not exist %s' % (tag, path))
         return False
     if g.os_path_isdir(path):
         if trace: print('%s: %s is a directory' % (tag, path))
         return False
     fn = g.shortFileName(path)
     # First, check the modification times.
     old_time = self.get_time(path)
     new_time = self.get_mtime(path)
     if not old_time:
         # Initialize.
         self.set_time(path, new_time)
         self.checksum_d[path] = checksum = self.checksum(path)
         if trace and verbose_init:
             print('%s:init %s %s %s' %
                   (tag, checksum, c.shortFileName(), path))
         elif trace:
             # Only print one message per commander.
             d = self.has_changed_d
             val = d.get(c)
             if not val:
                 d[c] = True
                 print('%s:init %s' % (tag, c.shortFileName()))
         return False
     if old_time == new_time:
         # print('%s:times match %s %s' % (tag,c.shortFileName(),path))
         return False
     # Check the checksums *only* if the mod times don't match.
     old_sum = self.checksum_d.get(path)
     new_sum = self.checksum(path)
     if new_sum == old_sum:
         # The modtime changed, but it's contents didn't.
         # Update the time, so we don't keep checking the checksums.
         # Return False so we don't prompt the user for an update.
         if trace: print('%s:unchanged %s %s' % (tag, old_time, new_time))
         self.set_time(path, new_time)
         return False
     else:
         # The file has really changed.
         if trace:
             print('%s:changed %s %s %s' % (tag, old_sum, new_sum, fn))
         assert old_time, path
         if 0:  # Fix bug 208: external change overwrite protection only works once
             # https://github.com/leo-editor/leo-editor/issues/208
             # These next two lines mean that if the Leo version
             # is changed (dirtied) again, overwrite will occur without warning.
             self.set_time(path, new_time)
             self.checksum_d[path] = new_sum
         return True
Пример #14
0
 def has_changed(self, c, path):
     '''Return True if p's external file has changed outside of Leo.'''
     trace = False and not g.unitTesting
     verbose_init = False
     tag = 'efc.has_changed'
     if not g.os_path_exists(path):
         if trace: print('%s:does not exist %s' % (tag, path))
         return False
     if g.os_path_isdir(path):
         if trace: print('%s: %s is a directory' % (tag, path))
         return False
     fn = g.shortFileName(path)
     # First, check the modification times.
     old_time = self.get_time(path)
     new_time = self.get_mtime(path)
     if not old_time:
         # Initialize.
         self.set_time(path, new_time)
         self.checksum_d[path] = checksum = self.checksum(path)
         if trace and verbose_init:
             print('%s:init %s %s %s' % (tag, checksum, c.shortFileName(), path))
         elif trace:
             # Only print one message per commander.
             d = self.has_changed_d
             val = d.get(c)
             if not val:
                 d[c] = True
                 print('%s:init %s' % (tag, c.shortFileName()))
         return False
     if old_time == new_time:
         # print('%s:times match %s %s' % (tag,c.shortFileName(),path))
         return False
     # Check the checksums *only* if the mod times don't match.
     old_sum = self.checksum_d.get(path)
     new_sum = self.checksum(path)
     if new_sum == old_sum:
         # The modtime changed, but it's contents didn't.
         # Update the time, so we don't keep checking the checksums.
         # Return False so we don't prompt the user for an update.
         if trace: print('%s:unchanged %s %s' % (tag, old_time, new_time))
         self.set_time(path, new_time)
         return False
     else:
         # The file has really changed.
         if trace: print('%s:changed %s %s %s' % (tag, old_sum, new_sum, fn))
         assert old_time, path
         if 0: # Fix bug 208: external change overwrite protection only works once
             # https://github.com/leo-editor/leo-editor/issues/208
             # These next two lines mean that if the Leo version
             # is changed (dirtied) again, overwrite will occur without warning.
             self.set_time(path, new_time)
             self.checksum_d[path] = new_sum
         return True
Пример #15
0
        def select_node(self, tag, kwargs):
            c = kwargs['c']
            if c != self.c:
                return

            p = kwargs['new_p']

            self.v = p.v  # to ensure unselect_node is working on the right node
            # currently (20130814) insert doesn't trigger unselect/select, but
            # even if it did, this would be safest

            data = self.template
            if p.b.startswith('<'):  # already rich text, probably
                content = p.b
                self.was_rich = True
            else:
                self.was_rich = p.b.strip() == ''
                # put anything except whitespace in a <pre/>
                content = "<pre>%s</pre>" % p.b if not self.was_rich else ''

            data = data.replace('[CONTENT]', content)

            # replace textarea with CKEditor, with or without config.
            if self.config:
                data = data.replace('[CONFIG]', ', '+self.config)
            else:
                data = data.replace('[CONFIG]', '')

            # try and make the path for URL evaluation relative to the node's path
            aList = g.get_directives_dict_list(p)
            path = c.scanAtPathDirectives(aList)
            if p.h.startswith('@'):  # see if it's a @<file> node of some sort
                nodepath = p.h.split(None, 1)[-1]
                nodepath = g.os_path_join(path, nodepath)
                if not g.os_path_isdir(nodepath):  # remove filename
                    nodepath = g.os_path_dirname(nodepath)
                if g.os_path_isdir(nodepath):  # append if it's a directory
                    path = nodepath

            self.webview.setHtml(data, QtCore.QUrl.fromLocalFile(path+"/"))
Пример #16
0
        def select_node(self, tag, kwargs):
            c = kwargs['c']
            if c != self.c:
                return

            p = kwargs['new_p']

            self.v = p.v  # to ensure unselect_node is working on the right node
            # currently (20130814) insert doesn't trigger unselect/select, but
            # even if it did, this would be safest

            data = self.template
            if p.b.startswith('<'):  # already rich text, probably
                content = p.b
                self.was_rich = True
            else:
                self.was_rich = p.b.strip() == ''
                # put anything except whitespace in a <pre/>
                content = "<pre>%s</pre>" % p.b if not self.was_rich else ''

            data = data.replace('[CONTENT]', content)

            # replace textarea with CKEditor, with or without config.
            if self.config:
                data = data.replace('[CONFIG]', ', ' + self.config)
            else:
                data = data.replace('[CONFIG]', '')

            # try and make the path for URL evaluation relative to the node's path
            aList = g.get_directives_dict_list(p)
            path = c.scanAtPathDirectives(aList)
            if p.h.startswith('@'):  # see if it's a @<file> node of some sort
                nodepath = p.h.split(None, 1)[-1]
                nodepath = g.os_path_join(path, nodepath)
                if not g.os_path_isdir(nodepath):  # remove filename
                    nodepath = g.os_path_dirname(nodepath)
                if g.os_path_isdir(nodepath):  # append if it's a directory
                    path = nodepath

            self.webview.setHtml(data, QtCore.QUrl.fromLocalFile(path + "/"))
Пример #17
0
def get_home():
    """Returns the user's home directory."""
    home = g.os_path_expanduser("~")
    # Windows searches the HOME, HOMEPATH and HOMEDRIVE
    # environment vars, then gives up.
    if home and len(home) > 1 and home[0] == '%' and home[-1] == '%':
        # Get the indirect reference to the true home.
        home = os.getenv(home[1:-1], default=None)
    if home:
        # Important: This returns the _working_ directory if home is None!
        # This was the source of the 4.3 .leoID.txt problems.
        home = g.os_path_finalize(home)
        if (not g.os_path_exists(home) or not g.os_path_isdir(home)):
            home = None
    return home
Пример #18
0
def get_home():
    """Returns the user's home directory."""
    home = g.os_path_expanduser("~")
        # Windows searches the HOME, HOMEPATH and HOMEDRIVE
        # environment vars, then gives up.
    if home and len(home) > 1 and home[0] == '%' and home[-1] == '%':
        # Get the indirect reference to the true home.
        home = os.getenv(home[1: -1], default=None)
    if home:
        # Important: This returns the _working_ directory if home is None!
        # This was the source of the 4.3 .leoID.txt problems.
        home = g.os_path_finalize(home)
        if (
            not g.os_path_exists(home) or
            not g.os_path_isdir(home)
        ):
            home = None
    return home
Пример #19
0
 def loadTreeHandlers(self):
     """Load all the handler for tree items"""
     #
     # Paths for key folders
     plugin_path = g.os_path_join(g.app.loadDir, "..", "plugins")
     self.handler_path = handler_path = g.os_path_join(
         g.app.loadDir, "..", "plugins", "trees")
     #
     if not g.os_path_isdir(handler_path):
         g.es("No tree handler folder found", color="red")
     else:
         g.es("Scanning for tree handlers", color="blue")
         #
         # Add folder locations to path
         old_path = sys.path[:]
         sys.path.insert(0, plugin_path)
         sys.path.insert(0, handler_path)
         #@+<< Get plugin manager module >>
         #@+node:ekr.20050329082101.135: *4* << Get plugin manager module >>
         # Get the manager
         try:
             self.plugin_manager = __import__("plugin_manager")
         except ImportError as err:
             g.es("Autotrees did not load plugin manager: %s" % (err, ),
                  color="red")
             self.plugin_manager = None
         #@-<< Get plugin manager module >>
         #@+<< Find all handlers >>
         #@+node:ekr.20050329082101.136: *4* << Find all handlers >>
         # Find all handlers
         for filename in glob.glob(g.os_path_join(handler_path, "*.py")):
             handler_name = g.os_path_splitext(
                 g.os_path_split(filename)[1])[0]
             g.es("... looking in %s" % handler_name, color="blue")
             try:
                 self.loadHandlersFrom(handler_name)
             except BadHandler as err:
                 g.es("... unable to load '%s' handler: %s" %
                      (handler_name, err),
                      color="red")
         #@-<< Find all handlers >>
         # Restore
         sys.path = old_path
Пример #20
0
 def has_changed(self, c, path):
     '''Return True if p's external file has changed outside of Leo.'''
     if not g.os_path_exists(path):
         return False
     if g.os_path_isdir(path):
         return False
     #
     # First, check the modification times.
     old_time = self.get_time(path)
     new_time = self.get_mtime(path)
     if not old_time:
         # Initialize.
         self.set_time(path, new_time)
         self.checksum_d[path] = self.checksum(path)
         return False
     if old_time == new_time:
         # print('%s:times match %s %s' % (tag,c.shortFileName(),path))
         return False
     #
     # Check the checksums *only* if the mod times don't match.
     old_sum = self.checksum_d.get(path)
     new_sum = self.checksum(path)
     if new_sum == old_sum:
         # The modtime changed, but it's contents didn't.
         # Update the time, so we don't keep checking the checksums.
         # Return False so we don't prompt the user for an update.
         self.set_time(path, new_time)
         return False
     else:
         # The file has really changed.
         assert old_time, path
         if 0:  # Fix bug 208: external change overwrite protection only works once
             # https://github.com/leo-editor/leo-editor/issues/208
             # These next two lines mean that if the Leo version
             # is changed (dirtied) again, overwrite will occur without warning.
             self.set_time(path, new_time)
             self.checksum_d[path] = new_sum
         return True
Пример #21
0
 def loadTreeHandlers(self):
     """Load all the handler for tree items"""
     #
     # Paths for key folders
     plugin_path = g.os_path_join(g.app.loadDir, "..", "plugins")
     self.handler_path = handler_path = g.os_path_join(g.app.loadDir, "..", "plugins", "trees")
     #
     if not g.os_path_isdir(handler_path):
         g.es("No tree handler folder found", color="red")
     else:
         g.es("Scanning for tree handlers", color="blue")
         #
         # Add folder locations to path
         old_path = sys.path[:]
         sys.path.insert(0, plugin_path)
         sys.path.insert(0, handler_path)
         #@+<< Get plugin manager module >>
         #@+node:ekr.20050329082101.135: *4* << Get plugin manager module >>
         # Get the manager
         try:
             self.plugin_manager = __import__("plugin_manager")
         except ImportError as err:
             g.es("Autotrees did not load plugin manager: %s" % (err,), color="red")
             self.plugin_manager = None
         #@-<< Get plugin manager module >>
         #@+<< Find all handlers >>
         #@+node:ekr.20050329082101.136: *4* << Find all handlers >>
         # Find all handlers
         for filename in glob.glob(g.os_path_join(handler_path, "*.py")):
             handler_name = g.os_path_splitext(g.os_path_split(filename)[1])[0]
             g.es("... looking in %s" % handler_name, color="blue")
             try:
                 self.loadHandlersFrom(handler_name)
             except BadHandler as err:
                 g.es("... unable to load '%s' handler: %s" % (handler_name, err), color="red")
         #@-<< Find all handlers >>
         # Restore
         sys.path = old_path
Пример #22
0
 def has_changed(self, c, path):
     '''Return True if p's external file has changed outside of Leo.'''
     if not g.os_path_exists(path):
         return False
     if g.os_path_isdir(path):
         return False
     #
     # First, check the modification times.
     old_time = self.get_time(path)
     new_time = self.get_mtime(path)
     if not old_time:
         # Initialize.
         self.set_time(path, new_time)
         self.checksum_d[path] = self.checksum(path)
         return False
     if old_time == new_time:
         return False
     #
     # Check the checksums *only* if the mod times don't match.
     old_sum = self.checksum_d.get(path)
     new_sum = self.checksum(path)
     if new_sum == old_sum:
         # The modtime changed, but it's contents didn't.
         # Update the time, so we don't keep checking the checksums.
         # Return False so we don't prompt the user for an update.
         self.set_time(path, new_time)
         return False
     else:
         # The file has really changed.
         assert old_time, path
         if 0: # Fix bug 208: external change overwrite protection only works once
             # https://github.com/leo-editor/leo-editor/issues/208
             # These next two lines mean that if the Leo version
             # is changed (dirtied) again, overwrite will occur without warning.
             self.set_time(path, new_time)
             self.checksum_d[path] = new_sum
         return True