def onItemDoubleClicked(self, item, col):
     '''Handle a double click in a baseNativeTree widget item.'''
     trace = False and not g.unitTesting
     verbose = False
     if self.busy(): return
     c = self.c
     if trace: g.trace(col, self.traceItem(item))
     try:
         self.selecting = True
         e, wrapper = self.createTreeEditorForItem(item)
         if not e:
             g.trace('*** no e')
         p = self.item2position(item)
     # 2011/07/28: End the lockout here, not at the end.
     finally:
         self.selecting = False
     if p:
         # 2014/02/21: generate headddlick1/2 instead of icondclick1/2.
         event = None
         if g.doHook("headdclick1", c=c, p=p, v=p, event=event) is None:
             c.frame.tree.OnIconDoubleClick(
                 p)  # Call the base class method.
         g.doHook("headclick2", c=c, p=p, v=p, event=event)
     else:
         g.trace('*** no p')
     c.outerUpdate()
def new(self, event=None, gui=None):
    '''Create a new Leo window.'''
    lm = g.app.loadManager
    old_c = self
    # Clean out the update queue so it won't interfere with the new window.
    self.outerUpdate()
    # Send all log messages to the new frame.
    g.app.setLog(None)
    g.app.lockLog()
    c = g.app.newCommander(fileName=None, gui=gui)
    frame = c.frame
    g.app.unlockLog()
    frame.setInitialWindowGeometry()
    frame.deiconify()
    frame.lift()
    frame.resizePanesToRatio(frame.ratio, frame.secondary_ratio)
        # Resize the _new_ frame.
    c.frame.createFirstTreeNode()
    lm.createMenu(c)
    lm.finishOpen(c)
    if g.app.loadedThemes:
        c.config.settingsDict = old_c.config.settingsDict
        lm.loadAllLoadedThemes(c=c, old_c=old_c)
    g.app.writeWaitingLog(c)
    g.doHook("new", old_c=old_c, c=c, new_c=c)
    c.setLog()
    c.setChanged(False) # Fix #387
    c.redraw()
    return c # For unit tests and scripts.
Exemple #3
0
 def createFrame(self, fileName):
     '''Create a commander and frame for the given file.
     Create a new frame if the fileName is empty or non-exisent.'''
     trace = False
     g = self.g
     if fileName.strip():
         if g.os_path_exists(fileName):
             if trace:
                 import time; t1 = time.time()
             # This takes a long time due to imports in c.__init__
             c = g.openWithFileName(fileName)
             if trace:
                 t2 = time.time()
                 g.trace('g.openWithFileName: %0.2fsec' % (t2 - t1))
             if c: return c
         elif not self.silentMode:
             print('file not found: %s. creating new window' % (fileName))
     # Create a new frame. Unlike leo.run, this is not a startup window.
     c = g.app.newCommander(fileName)
     frame = c.frame
     frame.createFirstTreeNode() # 2013/09/27: bug fix.
     assert c.rootPosition()
     frame.setInitialWindowGeometry()
     frame.resizePanesToRatio(frame.ratio, frame.secondary_ratio)
     # Call the 'new' hook for compatibility with plugins.
     # 2011/11/07: Do this only if plugins have been loaded.
     g.doHook("new", old_c=None, c=c, new_c=c)
     return c
    def open_with(self, c, d):
        '''
        Called by c.openWith to handle items in the Open With... menu.

        'd' a dict created from an @openwith settings node with these keys:

            'args':     the command-line arguments to be used to open the file.
            'ext':      the file extension.
            'kind':     the method used to open the file, such as subprocess.Popen.
            'name':     menu label (used only by the menu code).
            'p':        the nearest @<file> node, or None.
            'shortcut': menu shortcut (used only by the menu code).
        '''
        try:
            ext = d.get('ext')
            if not g.doHook('openwith1', c=c, p=c.p, v=c.p.v, d=d):
                root = d.get('p')
                if root:
                    # Open the external file itself.
                    directory = g.setDefaultDirectory(c, root)
                    path = c.os_path_finalize_join(directory, root.anyAtFileNodeName())
                    self.open_file_in_external_editor(c, d, path)
                else:
                    # Open a temp file containing just the node.
                    p = c.p
                    ext = self.compute_ext(c, p, ext)
                    path = self.compute_temp_file_path(c, p, ext)
                    if path:
                        self.remove_temp_file(p, path)
                        self.create_temp_file(c, ext, p)
                        self.open_file_in_external_editor(c, d, path)
            g.doHook('openwith2', c=c, p=c.p, v=c.p.v, d=d)
        except Exception:
            g.es('unexpected exception in c.openWith')
            g.es_exception()
def new(self, event=None, gui=None):
    '''Create a new Leo window.'''
    import leo.core.leoApp as leoApp
    lm = g.app.loadManager
    old_c = self
    # Clean out the update queue so it won't interfere with the new window.
    self.outerUpdate()
    # Send all log messages to the new frame.
    g.app.setLog(None)
    g.app.lockLog()
    # Retain all previous settings. Very important for theme code.
    c = g.app.newCommander(
        fileName=None,
        gui=gui,
        previousSettings=leoApp.PreviousSettings(
            settingsDict=lm.globalSettingsDict,
            shortcutsDict=lm.globalBindingsDict,
        ))    
    frame = c.frame
    g.app.unlockLog()
    frame.setInitialWindowGeometry()
    frame.deiconify()
    frame.lift()
    frame.resizePanesToRatio(frame.ratio, frame.secondary_ratio)
        # Resize the _new_ frame.
    c.frame.createFirstTreeNode()
    lm.createMenu(c)
    lm.finishOpen(c)
    g.app.writeWaitingLog(c)
    g.doHook("new", old_c=old_c, c=c, new_c=c)
    c.setLog()
    c.setChanged(False) # Fix #387
    c.redraw()
    return c # For unit tests and scripts.
Exemple #6
0
def openRecentFile(self, event=None, fn=None):
    c = self
    # Automatically close the previous window if...
    closeFlag = (
        c.frame.startupWindow and
        # The window was open on startup
        not c.changed and not c.frame.saved and
        # The window has never been changed
        g.app.numberOfUntitledWindows == 1)
    # Only one untitled window has ever been opened.
    if g.doHook("recentfiles1",
                c=c,
                p=c.p,
                v=c.p,
                fileName=fn,
                closeFlag=closeFlag):
        return
    c2 = g.openWithFileName(fn, old_c=c)
    if c2:
        g.app.makeAllBindings()
    if closeFlag and c2 and c2 != c:
        g.app.destroyWindow(c.frame)
        c2.setLog()
        g.doHook("recentfiles2",
                 c=c2,
                 p=c2.p,
                 v=c2.p,
                 fileName=fn,
                 closeFlag=closeFlag)
Exemple #7
0
    def open_with(self, c, d):
        '''
        Called by c.openWith to handle items in the Open With... menu.

        'd' a dict created from an @openwith settings node with these keys:

            'args':     the command-line arguments to be used to open the file.
            'ext':      the file extension.
            'kind':     the method used to open the file, such as subprocess.Popen.
            'name':     menu label (used only by the menu code).
            'p':        the nearest @<file> node, or None.
            'shortcut': menu shortcut (used only by the menu code).
        '''
        try:
            ext = d.get('ext')
            if not g.doHook('openwith1', c=c, p=c.p, v=c.p.v, d=d):
                root = d.get('p')
                if root:
                    # Open the external file itself.
                    directory = g.setDefaultDirectory(c, root)
                    path = c.os_path_finalize_join(directory, root.anyAtFileNodeName())
                    self.open_file_in_external_editor(c, d, path)
                else:
                    # Open a temp file containing just the node.
                    p = c.p
                    ext = self.compute_ext(c, p, ext)
                    path = self.compute_temp_file_path(c, p, ext)
                    if path:
                        self.remove_temp_file(p, path)
                        self.create_temp_file(c, ext, p)
                        self.open_file_in_external_editor(c, d, path)
            g.doHook('openwith2', c=c, p=c.p, v=c.p.v, d=d)
        except Exception:
            g.es('unexpected exception in c.openWith')
            g.es_exception()
 def createFrame(self, fileName):
     '''Create a commander and frame for the given file.
     Create a new frame if the fileName is empty or non-exisent.'''
     trace = False
     g = self.g
     if fileName.strip():
         if g.os_path_exists(fileName):
             if trace:
                 import time
                 t1 = time.time()
             # This takes a long time due to imports in c.__init__
             c = g.openWithFileName(fileName)
             if trace:
                 t2 = time.time()
                 g.trace('%s %0.2fsec' % (fileName, (t2 - t1)))
             if c: return c
         elif not self.silentMode:
             print('file not found: %s. creating new window' % (fileName))
     # Create a new frame. Unlike leo.run, this is not a startup window.
     c = g.app.newCommander(fileName)
     frame = c.frame
     frame.createFirstTreeNode()  # 2013/09/27: bug fix.
     assert c.rootPosition()
     frame.setInitialWindowGeometry()
     frame.resizePanesToRatio(frame.ratio, frame.secondary_ratio)
     # Call the 'new' hook for compatibility with plugins.
     # 2011/11/07: Do this only if plugins have been loaded.
     g.doHook("new", old_c=None, c=c, new_c=c)
     return c
def new(self, event=None, gui=None):
    '''Create a new Leo window.'''
    lm = g.app.loadManager
    # Clean out the update queue so it won't interfere with the new window.
    self.outerUpdate()
    # Send all log messages to the new frame.
    g.app.setLog(None)
    g.app.lockLog()
    c = g.app.newCommander(fileName=None, gui=gui)
    frame = c.frame
    g.app.unlockLog()
    frame.setInitialWindowGeometry()
    frame.deiconify()
    frame.lift()
    frame.resizePanesToRatio(frame.ratio, frame.secondary_ratio)
        # Resize the _new_ frame.
    c.frame.createFirstTreeNode()
    lm.createMenu(c)
    lm.finishOpen(c)
    g.app.writeWaitingLog(c)
    g.doHook("new", old_c=self, c=c, new_c=c)
    c.setLog()
    c.setChanged(False) # Fix #387
    c.redraw()
    return c # For unit tests and scripts.
    def rClickRight(self, event):
        """Show a popup menu to choose a previously visited node."""

        c = self.c

        menu = [('*', 'nav-next-menu')]
        g.doHook('rclick-popup', c=c, event=event, context_menu=menu)
 def onItemDoubleClicked (self,item,col):
     '''Handle a double click in a baseNativeTree widget item.'''
     trace = False and not g.unitTesting
     verbose = False
     if self.busy(): return
     c = self.c
     if trace: g.trace(col,self.traceItem(item))
     try:
         self.selecting = True
         e,wrapper = self.createTreeEditorForItem(item)
         if not e:
             g.trace('*** no e')
         p = self.item2position(item)
     # 2011/07/28: End the lockout here, not at the end.
     finally:
         self.selecting = False
     if p:
         # 2014/02/21: generate headddlick1/2 instead of icondclick1/2.
         event = None
         if g.doHook("headdclick1",c=c,p=p,v=p,event=event) is None:
             c.frame.tree.OnIconDoubleClick(p) # Call the base class method.
         g.doHook("headclick2",c=c,p=p,v=p,event=event)
     else:
         g.trace('*** no p')
     c.outerUpdate()
def new(self, event=None, gui=None):
    '''Create a new Leo window.'''
    import leo.core.leoApp as leoApp
    lm = g.app.loadManager
    old_c = self
    # Clean out the update queue so it won't interfere with the new window.
    self.outerUpdate()
    # Send all log messages to the new frame.
    g.app.setLog(None)
    g.app.lockLog()
    # Retain all previous settings. Very important for theme code.
    c = g.app.newCommander(
        fileName=None,
        gui=gui,
        previousSettings=leoApp.PreviousSettings(
            settingsDict=lm.globalSettingsDict,
            shortcutsDict=lm.globalShortcutsDict,
        ))    
    frame = c.frame
    g.app.unlockLog()
    frame.setInitialWindowGeometry()
    frame.deiconify()
    frame.lift()
    frame.resizePanesToRatio(frame.ratio, frame.secondary_ratio)
        # Resize the _new_ frame.
    c.frame.createFirstTreeNode()
    lm.createMenu(c)
    lm.finishOpen(c)
    g.app.writeWaitingLog(c)
    g.doHook("new", old_c=old_c, c=c, new_c=c)
    c.setLog()
    c.setChanged(False) # Fix #387
    c.redraw()
    return c # For unit tests and scripts.
    def rClickMarks(self, event):
        """Show a popup menu to select a mark."""

        c = self.c

        menu_table = [('*', 'nav-marks-menu')]

        g.doHook('rclick-popup', c=c, event=event, context_menu=menu_table)
Exemple #14
0
 def on_idle(self):
     '''Call all idle-time hooks.'''
     if g.app.idle_time_hooks_enabled:
         for frame in g.app.windowList:
             c = frame.c
             # Do NOT compute c.currentPosition.
             # This would be a MAJOR leak of positions.
             g.doHook("idle", c=c)
    def rClickRight(self,event):

        """Show a popup menu to choose a previously visited node."""

        c = self.c

        menu = [('*', 'nav-next-menu')]
        g.doHook('rclick-popup', c=c, event=event, context_menu=menu)
Exemple #16
0
 def on_idle(self):
     """Call all idle-time hooks."""
     if g.app.idle_time_hooks_enabled:
         for frame in g.app.windowList:
             c = frame.c
             # Do NOT compute c.currentPosition.
             # This would be a MAJOR leak of positions.
             g.doHook("idle", c=c)
Exemple #17
0
    def onHeadlineRightClick (self,event,p):

        c = self.c

        try:
            g.doHook("headrclick1",c=c,p=p,v=p,event=event)
            g.doHook("headrclick2",c=c,p=p,v=p,event=event)
        except:
            g.es_event_exception("headrclick")
Exemple #18
0
    def onPlusBoxRightClick (self,event,p=None):

        if self.busy(): return

        c = self.c

        g.doHook('rclick-popup',c=c,p=p,event=event,context_menu='plusbox')

        c.outerUpdate()
    def onPlusBoxRightClick (self,event,p=None):

        if self.busy(): return

        c = self.c

        g.doHook('rclick-popup',c=c,p=p,event=event,context_menu='plusbox')

        c.outerUpdate()
    def onHeadlineRightClick (self,event,p):

        c = self.c

        try:
            g.doHook("headrclick1",c=c,p=p,v=p,event=event)
            g.doHook("headrclick2",c=c,p=p,v=p,event=event)
        except:
            g.es_event_exception("headrclick")
    def rClickMarks(self, event):

        """Show a popup menu to select a mark."""

        c = self.c

        menu_table = [('*', 'nav-marks-menu')]   

        g.doHook('rclick-popup', c=c, event=event, context_menu=menu_table)
    def onClickBoxRightClick(self, event, p=None):

        if self.busy(): return

        c = self.c

        g.doHook("boxrclick1",c=c,p=p,v=p,event=event)
        g.doHook("boxrclick2",c=c,p=p,v=p,event=event)

        c.outerUpdate()
    def onDoubleClickHeadline (self,event,p):

        c = self.c

        try:
            if not g.doHook("headdclick1",c=c,p=p,v=p,event=event):
                self.editLabel(p,selectAll=True,selection=None)
            g.doHook("headdclick2",c=c,p=p,v=p,event=event)
        except:
            g.es_event_exception("headdclick")
Exemple #24
0
    def onIconBoxClick (self,event,p=None):

        if self.busy(): return

        c = self.c

        g.doHook("iconclick1",c=c,p=p,v=p,event=event)
        g.doHook("iconclick2",c=c,p=p,v=p,event=event)

        c.outerUpdate()
Exemple #25
0
    def onClickBoxRightClick(self, event, p=None):

        if self.busy(): return

        c = self.c

        g.doHook("boxrclick1",c=c,p=p,v=p,event=event)
        g.doHook("boxrclick2",c=c,p=p,v=p,event=event)

        c.outerUpdate()
Exemple #26
0
    def onDoubleClickHeadline (self,event,p):

        c = self.c

        try:
            if not g.doHook("headdclick1",c=c,p=p,v=p,event=event):
                self.editLabel(p,selectAll=True,selection=None)
            g.doHook("headdclick2",c=c,p=p,v=p,event=event)
        except:
            g.es_event_exception("headdclick")
    def onIconBoxClick (self,event,p=None):

        if self.busy(): return

        c = self.c

        g.doHook("iconclick1",c=c,p=p,v=p,event=event)
        g.doHook("iconclick2",c=c,p=p,v=p,event=event)

        c.outerUpdate()
    def onIconBoxRightClick(self, event, p=None):
        """Handle a right click in any outline widget."""

        if self.busy(): return

        c = self.c

        g.doHook("iconrclick1", c=c, p=p, v=p, event=event)
        g.doHook("iconrclick2", c=c, p=p, v=p, event=event)

        c.outerUpdate()
Exemple #29
0
    def onIconBoxRightClick (self,event,p=None):

        """Handle a right click in any outline widget."""

        if self.busy(): return

        c = self.c

        g.doHook("iconrclick1",c=c,p=p,v=p,event=event)
        g.doHook("iconrclick2",c=c,p=p,v=p,event=event)

        c.outerUpdate()
Exemple #30
0
 def on_idle(self):
     '''Call all idle-time hooks.'''
     trace = False and not g.unitTesting
     if g.app.idle_time_hooks_enabled:
         for frame in g.app.windowList:
             c = frame.c
             # Do NOT compute c.currentPosition.
             # This would be a MAJOR leak of positions.
             if trace:
                 g.trace('(leoPlugins.py) calling g.doHook(c=%s)' %
                         (c.shortFileName()))
             g.doHook("idle", c=c)
Exemple #31
0
 def on_idle(self):
     '''Call all idle-time hooks.'''
     trace = False and not g.unitTesting
     if g.app.idle_time_hooks_enabled:
         for frame in g.app.windowList:
             c = frame.c
             # Do NOT compute c.currentPosition.
             # This would be a MAJOR leak of positions.
             if trace:
                 g.trace('(leoPlugins.py) calling g.doHook(c=%s)' % (
                     c.shortFileName()))
             g.doHook("idle", c=c)
Exemple #32
0
    def chapterSelectHelper(self, w=None, selectEditor=True):

        trace = False and not g.unitTesting
        c = self.c
        cc = self.cc
        name = self.name

        if trace:
            g.trace('%s exists: %s p: %s' %
                    (name, c.positionExists(self.p), self.p))

        cc.selectedChapter = self

        # 2011/06/08
        if self.p and not c.positionExists(self.p):
            self.p = self.root()
            if trace: g.trace('*** switching to root', self.p)

        p = self.p

        # Next, recompute p and possibly select a new editor.
        if w:
            assert w == c.frame.body.bodyCtrl
            assert w.leo_p
            self.p = p = self.findPositionInChapter(w.leo_p) or self.root()
            if trace: g.trace('recomputed: %s' % (self.p))
        else:
            # This must be done *after* switching roots.
            self.p = p = self.findPositionInChapter(p) or self.root()
            if trace: g.trace('recomputed: %s' % (self.p))

            if selectEditor:
                c.selectPosition(p)  ##
                w = self.findEditorInChapter(p)
                c.frame.body.selectEditor(w)  # Switches text.

        if name != 'main' and g.match_word(p.h, 0, '@chapter'):
            if p.hasChildren():
                p = p.firstChild()
            else:
                if trace: g.trace('can not happen: no child of @chapter node')

        chaptersNode = cc.findChaptersNode()

        if name == 'main' and chaptersNode:
            chaptersNode.contract()

        c.hoistStack = self.hoistStack[:]
        c.selectPosition(p)
        g.doHook('hoist-changed', c=c)
        c.redraw_now(p)
Exemple #33
0
    def onIconBoxDoubleClick (self,event,p=None):

        if self.busy(): return

        c = self.c
        if not p: p = c.p

        if not g.doHook("icondclick1",c=c,p=p,v=p,event=event):
            self.endEditLabel()
            self.OnIconDoubleClick(p) # Call the method in the base class.

        g.doHook("icondclick2",c=c,p=p,v=p,event=event)

        c.outerUpdate()
    def onIconBoxDoubleClick (self,event,p=None):

        if self.busy(): return

        c = self.c
        if not p: p = c.p

        if not g.doHook("icondclick1",c=c,p=p,v=p,event=event):
            self.endEditLabel()
            self.OnIconDoubleClick(p) # Call the method in the base class.

        g.doHook("icondclick2",c=c,p=p,v=p,event=event)

        c.outerUpdate()
def new(self, event=None, gui=None):
    """Create a new Leo window."""
    t1 = time.process_time()
    from leo.core import leoApp
    lm = g.app.loadManager
    old_c = self
    # Clean out the update queue so it won't interfere with the new window.
    self.outerUpdate()
    # Supress redraws until later.
    g.app.disable_redraw = True
    # Send all log messages to the new frame.
    g.app.setLog(None)
    g.app.lockLog()
    # Retain all previous settings. Very important for theme code.
    t2 = time.process_time()
    c = g.app.newCommander(fileName=None,
                           gui=gui,
                           previousSettings=leoApp.PreviousSettings(
                               settingsDict=lm.globalSettingsDict,
                               shortcutsDict=lm.globalBindingsDict,
                           ))
    t3 = time.process_time()
    frame = c.frame
    g.app.unlockLog()
    if not old_c:
        frame.setInitialWindowGeometry()
    # #1643: This doesn't work.
    # g.app.restoreWindowState(c)
    frame.deiconify()
    frame.lift()
    frame.resizePanesToRatio(frame.ratio, frame.secondary_ratio)
    # Resize the _new_ frame.
    c.frame.createFirstTreeNode()
    lm.createMenu(c)
    lm.finishOpen(c)
    g.app.writeWaitingLog(c)
    g.doHook("new", old_c=old_c, c=c, new_c=c)
    c.setLog()
    c.clearChanged()  # Fix #387: Clear all dirty bits.
    g.app.disable_redraw = False
    c.redraw()
    t4 = time.process_time()
    if 'speed' in g.app.debug:
        g.trace()
        print(f"    1: {t2-t1:5.2f}\n"  # 0.00 sec.
              f"    2: {t3-t2:5.2f}\n"  # 0.36 sec: c.__init__
              f"    3: {t4-t3:5.2f}\n"  # 0.17 sec: Everything else.
              f"total: {t4-t1:5.2f}")
    return c  # For unit tests and scripts.
Exemple #36
0
    def chapterSelectHelper (self,w=None,selectEditor=True):

        trace = False and not g.unitTesting
        c = self.c ; cc = self.cc ; name = self.name

        if trace:
            g.trace('%s exists: %s p: %s' % (
                name,c.positionExists(self.p),self.p))

        cc.selectedChapter = self
        
        # 2011/06/08
        if self.p and not c.positionExists(self.p):
            self.p = self.root()
            if trace: g.trace('*** switching to root',self.p)

        p = self.p

        # Next, recompute p and possibly select a new editor.
        if w:
            assert w == c.frame.body.bodyCtrl
            assert w.leo_p
            self.p = p = self.findPositionInChapter(w.leo_p) or self.root()
            if trace: g.trace('recomputed: %s' % (self.p))
        else:
            # This must be done *after* switching roots.
            self.p = p = self.findPositionInChapter(p) or self.root()
            if trace: g.trace('recomputed: %s' % (self.p))

            if selectEditor:
                c.selectPosition(p) ##
                w = self.findEditorInChapter(p)
                c.frame.body.selectEditor(w) # Switches text.
                
        if name != 'main' and g.match_word(p.h,0,'@chapter'):
            if p.hasChildren():
                p = p.firstChild()
            else:
                if trace: g.trace('can not happen: no child of @chapter node')
                
        chaptersNode = cc.findChaptersNode()

        if name == 'main' and chaptersNode:
            chaptersNode.contract()

        c.hoistStack = self.hoistStack[:]
        c.selectPosition(p)
        g.doHook('hoist-changed',c=c)
        c.redraw_now(p)
def restartLeo(self, event=None):
    """Restart Leo, reloading all presently open outlines."""
    c, lm = self, g.app.loadManager
    trace = 'shutdown' in g.app.debug
    # 1. Write .leoRecentFiles.txt.
    g.app.recentFilesManager.writeRecentFilesFile(c)
    # 2. Abort the restart if the user veto's any close.
    for c in g.app.commanders():
        if c.changed:
            veto = False
            try:
                c.promptingForClose = True
                veto = c.frame.promptForSave()
            finally:
                c.promptingForClose = False
            if veto:
                g.es_print('Cancelling restart-leo command')
                return
    # 3. Officially begin the restart process. A flag for efc.ask.
    g.app.restarting = True  # #1240.
    # 4. Save session data.
    if g.app.sessionManager:
        g.app.sessionManager.save_snapshot()
    # 5. Close all unsaved outlines.
    g.app.setLog(None)  # Kill the log.
    for c in g.app.commanders():
        frame = c.frame
        # This is similar to g.app.closeLeoWindow.
        g.doHook("close-frame", c=c)
        # Save the window state
        g.app.commander_cacher.commit()  # store cache, but don't close it.
        # This may remove frame from the window list.
        if frame in g.app.windowList:
            g.app.destroyWindow(frame)
            g.app.windowList.remove(frame)
        else:
            # #69.
            g.app.forgetOpenFile(fn=c.fileName())
    # 6. Complete the shutdown.
    g.app.finishQuit()
    # 7. Restart, restoring the original command line.
    args = ['-c'] + lm.old_argv
    if trace:
        g.trace('restarting with args', args)
    sys.stdout.flush()
    sys.stderr.flush()
    os.execv(sys.executable, args)
 def chapterSelectHelper(self, w=None, selectEditor=True):
     trace = False and not g.unitTesting
     c, cc = self.c, self.cc
     if trace: g.trace('-----------', self, 'w:', bool(w))
     cc.selectedChapter = self
     if self.name == 'main':
         return  # 2016/04/20
     # Remember the root (it may have changed) for dehoist.
     self.root = root = self.findRootNode()
     if not root:
         # Might happen during unit testing or startup.
         return
     if self.p and not c.positionExists(self.p):
         self.p = p = root.copy()
         if trace: g.trace('switch to root', self)
     # Next, recompute p and possibly select a new editor.
     if w:
         assert w == c.frame.body.wrapper
         assert w.leo_p
         self.p = p = self.findPositionInChapter(w.leo_p) or root.copy()
         if trace: g.trace('recomputed1:', self)
     else:
         # This must be done *after* switching roots.
         self.p = p = self.findPositionInChapter(self.p) or root.copy()
         if trace: g.trace('recomputed2', self)
         if selectEditor:
             # Careful: c.selectPosition would pop the hoist stack.
             w = self.findEditorInChapter(p)
             c.frame.body.selectEditor(w)  # Switches text.
             self.p = p  # 2016/04/20: Apparently essential.
         if trace: g.trace('recomputed3', self)
     if g.match_word(p.h, 0, '@chapter'):
         if p.hasChildren():
             self.p = p = p.firstChild()
         else:
             # 2016/04/20: Create a dummy first child.
             self.p = p = p.insertAsLastChild()
             p.h = 'New Headline'
             if trace: g.trace('inserted child of @chapter node', p.h)
     c.hoistStack.append(g.Bunch(p=root.copy(), expanded=True))
     # Careful: c.selectPosition would pop the hoist stack.
     if trace: g.trace('done:', self)
     c.setCurrentPosition(p)
     g.doHook('hoist-changed', c=c)
Exemple #39
0
 def chapterSelectHelper(self, w=None, selectEditor=True):
     trace = False and not g.unitTesting
     c, cc = self.c, self.cc
     if trace: g.trace('-----------', self, 'w:', bool(w))
     cc.selectedChapter = self
     if self.name == 'main':
         return # 2016/04/20
     # Remember the root (it may have changed) for dehoist.
     self.root = root = self.findRootNode()
     if not root:
         # Might happen during unit testing or startup.
         return
     if self.p and not c.positionExists(self.p):
         self.p = p = root.copy()
         if trace: g.trace('switch to root', self)
     # Next, recompute p and possibly select a new editor.
     if w:
         assert w == c.frame.body.wrapper
         assert w.leo_p
         self.p = p = self.findPositionInChapter(w.leo_p) or root.copy()
         if trace: g.trace('recomputed1:', self)
     else:
         # This must be done *after* switching roots.
         self.p = p = self.findPositionInChapter(self.p) or root.copy()
         if trace: g.trace('recomputed2', self)
         if selectEditor:
             # Careful: c.selectPosition would pop the hoist stack.
             w = self.findEditorInChapter(p)
             c.frame.body.selectEditor(w) # Switches text.
             self.p = p # 2016/04/20: Apparently essential.
         if trace: g.trace('recomputed3', self)
     if g.match_word(p.h, 0, '@chapter'):
         if p.hasChildren():
             self.p = p = p.firstChild()
         else:
             # 2016/04/20: Create a dummy first child.
             self.p = p = p.insertAsLastChild()
             p.h = 'New Headline'
             if trace: g.trace('inserted child of @chapter node', p.h)
     c.hoistStack.append(g.Bunch(p=root.copy(), expanded=True))
     # Careful: c.selectPosition would pop the hoist stack.
     if trace: g.trace('done:', self)
     c.setCurrentPosition(p)
     g.doHook('hoist-changed', c=c)
Exemple #40
0
def insertHeadlineBefore(self, event=None):
    """Insert a node before the presently selected node."""
    c, current, u = self, self.p, self.undoer
    op_name = 'Insert Node Before'
    if not current:
        return None
    # Can not insert before the base of a hoist.
    if c.hoistStack and current == c.hoistStack[-1].p:
        g.warning('can not insert a node before the base of a hoist')
        return None
    c.endEditing()
    undoData = u.beforeInsertNode(current)
    p = current.insertBefore()
    g.doHook('create-node', c=c, p=p)
    p.setDirty()
    c.setChanged()
    u.afterInsertNode(p, op_name, undoData)
    c.redrawAndEdit(p, selectAll=True)
    return p
Exemple #41
0
    def chapterSelectHelper (self,w=None,selectEditor=True):

        trace = False and not g.unitTesting
        c,cc,name = self.c,self.cc,self.name
        if trace:
            g.trace('%s exists: %s p: %s' % (
                name,c.positionExists(self.p),self.p))
        cc.selectedChapter = self
        root = self.findRootNode()
        if not root:
            return # New. Might happen during unit testing or startup.
        if self.p and not c.positionExists(self.p):
            self.p = root.copy()
            if trace: g.trace('*** switching to root',self.p)
        p = self.p
        # Next, recompute p and possibly select a new editor.
        if w:
            assert w == c.frame.body.wrapper
            assert w.leo_p
            self.p = p = self.findPositionInChapter(w.leo_p) or root.copy()
            if trace: g.trace('recomputed: %s' % (self.p))
        else:
            # This must be done *after* switching roots.
            self.p = p = self.findPositionInChapter(p) or root.copy()
            if trace: g.trace('recomputed: %s' % (self.p))
            if selectEditor:
                c.selectPosition(p)
                w = self.findEditorInChapter(p)
                c.frame.body.selectEditor(w) # Switches text.
        if name != 'main' and g.match_word(p.h,0,'@chapter'):
            if p.hasChildren():
                p = p.firstChild()
            else:
                if trace: g.trace('can not happen: no child of @chapter node')
        chaptersNode = cc.findChaptersNode()
        if name == 'main' and chaptersNode:
            chaptersNode.contract()
        if name != 'main':
            c.hoistStack.append(g.Bunch(p=root and root.copy(),expanded=True))
        c.selectPosition(p)
        g.doHook('hoist-changed',c=c)
        c.redraw_now(p)
Exemple #42
0
 def handleSpecialMenus(self, name, parentName, table=None):
     '''Handle a special menu if name is the name of a special menu.
     return True if this method handles the menu.'''
     c = self.c
     if table is None: table = []
     name2 = name.replace('&', '').replace(' ', '').lower()
     if name2 == 'plugins':
         # Create the plugins menu using a hook.
         g.doHook("create-optional-menus", c=c)
         return True
     elif name2.startswith('recentfiles'):
         # Just create the menu.
         # createRecentFilesMenuItems will create the contents later.
         self.createNewMenu(name, parentName)
         return True
     elif name2 == 'help' and sys.platform == 'darwin':
         helpMenu = self.getMacHelpMenu(table)
         return helpMenu is not None
     else:
         return False
    def OnPopup (self,p,event):

        """Handle right-clicks in the outline.

        This is *not* an event handler: it is called from other event handlers."""

        # Note: "headrclick" hooks handled by vnode callback routine.

        if event != None:
            c = self.c
            c.setLog()

            if not g.doHook("create-popup-menu",c=c,p=p,v=p,event=event):
                self.createPopupMenu(event)
            if not g.doHook("enable-popup-menu-items",c=c,p=p,v=p,event=event):
                self.enablePopupMenuItems(p,event)
            if not g.doHook("show-popup-menu",c=c,p=p,v=p,event=event):
                self.showPopupMenu(event)

        return "break"
Exemple #44
0
def dehoist(self, event=None):
    """Undo a previous hoist of an outline."""
    c = self
    if not c.p or not c.hoistStack:
        return
    # Don't de-hoist an @chapter node.
    if c.chapterController and c.p.h.startswith('@chapter '):
        if not g.unitTesting:
            g.es('can not de-hoist an @chapter node.', color='blue')
        return
    bunch = c.hoistStack.pop()
    p = bunch.p
    if bunch.expanded: p.expand()
    else: p.contract()
    c.setCurrentPosition(p)
    c.redraw()
    c.frame.clearStatusLine()
    c.frame.putStatusLine("De-Hoist: " + p.h)
    c.undoer.afterDehoist(p, 'DeHoist')
    g.doHook('hoist-changed', c=c)
Exemple #45
0
def hoist(self, event=None):
    """Make only the selected outline visible."""
    c = self
    p = c.p
    if not p:
        return
    # Don't hoist an @chapter node.
    if c.chapterController and p.h.startswith('@chapter '):
        if not g.unitTesting:
            g.es('can not hoist an @chapter node.', color='blue')
        return
    # Remember the expansion state.
    bunch = g.Bunch(p=p.copy(), expanded=p.isExpanded())
    c.hoistStack.append(bunch)
    p.expand()
    c.redraw(p)
    c.frame.clearStatusLine()
    c.frame.putStatusLine("Hoist: " + p.h)
    c.undoer.afterHoist(p, 'Hoist')
    g.doHook('hoist-changed', c=c)
def openRecentFile(self, event=None, fn=None):
    c = self
    # Automatically close the previous window if...
    closeFlag = (
        c.frame.startupWindow and
            # The window was open on startup
        not c.changed and not c.frame.saved and
            # The window has never been changed
        g.app.numberOfUntitledWindows == 1)
            # Only one untitled window has ever been opened.
    if g.doHook("recentfiles1", c=c, p=c.p, v=c.p, fileName=fn, closeFlag=closeFlag):
        return
    c2 = g.openWithFileName(fn, old_c=c)
    if c2:
        g.app.makeAllBindings()
    if closeFlag and c2 and c2 != c:
        g.app.destroyWindow(c.frame)
        c2.setLog()
        g.doHook("recentfiles2",
            c=c2, p=c2.p, v=c2.p, fileName=fn, closeFlag=closeFlag)
Exemple #47
0
    def OnPopup (self,p,event):

        """Handle right-clicks in the outline.

        This is *not* an event handler: it is called from other event handlers."""

        # Note: "headrclick" hooks handled by vnode callback routine.

        if event != None:
            c = self.c
            c.setLog()

            if not g.doHook("create-popup-menu",c=c,p=p,v=p,event=event):
                self.createPopupMenu(event)
            if not g.doHook("enable-popup-menu-items",c=c,p=p,v=p,event=event):
                self.enablePopupMenuItems(p,event)
            if not g.doHook("show-popup-menu",c=c,p=p,v=p,event=event):
                self.showPopupMenu(event)

        return "break"
Exemple #48
0
 def chapterSelectHelper(self, w=None, selectEditor=True):
     trace = False and not g.unitTesting
     c, cc, name = self.c, self.cc, self.name
     if trace:
         g.trace('%s exists: %s p: %s' % (
             name, c.positionExists(self.p), self.p))
     cc.selectedChapter = self
     root = self.findRootNode()
     if not root:
         return # New. Might happen during unit testing or startup.
     if self.p and not c.positionExists(self.p):
         self.p = root.copy()
         if trace: g.trace('*** switching to root', self.p)
     p = self.p
     # Next, recompute p and possibly select a new editor.
     if w:
         assert w == c.frame.body.wrapper
         assert w.leo_p
         self.p = p = self.findPositionInChapter(w.leo_p) or root.copy()
         if trace: g.trace('recomputed: %s' % (self.p))
     else:
         # This must be done *after* switching roots.
         self.p = p = self.findPositionInChapter(p) or root.copy()
         if trace: g.trace('recomputed: %s' % (self.p))
         if selectEditor:
             c.selectPosition(p)
             w = self.findEditorInChapter(p)
             c.frame.body.selectEditor(w) # Switches text.
     if name != 'main' and g.match_word(p.h, 0, '@chapter'):
         if p.hasChildren():
             p = p.firstChild()
         else:
             if trace: g.trace('can not happen: no child of @chapter node')
     chaptersNode = cc.findChaptersNode()
     if name == 'main' and chaptersNode:
         chaptersNode.contract()
     if name != 'main':
         c.hoistStack.append(g.Bunch(p=root and root.copy(), expanded=True))
     c.selectPosition(p)
     g.doHook('hoist-changed', c=c)
     c.redraw_now(p)
def new(self, event=None, gui=None):
    """Create a new Leo window."""
    import leo.core.leoApp as leoApp
    lm = g.app.loadManager
    old_c = self
    # Clean out the update queue so it won't interfere with the new window.
    self.outerUpdate()
    # Supress redraws until later.
    g.app.disable_redraw = True
    # Send all log messages to the new frame.
    g.app.setLog(None)
    g.app.lockLog()
    # Retain all previous settings. Very important for theme code.
    c = g.app.newCommander(
        fileName=None,
        gui=gui,
        previousSettings=leoApp.PreviousSettings(
            settingsDict=lm.globalSettingsDict,
            shortcutsDict=lm.globalBindingsDict,
        ))    
    frame = c.frame
    g.app.unlockLog()
    if not old_c:
        frame.setInitialWindowGeometry()
    # #1340: Don't do this. It is no longer needed.
        # g.app.restoreWindowState(c, use_default=True)
            # #1198: New documents have collapsed body pane.
    frame.deiconify()
    frame.lift()
    frame.resizePanesToRatio(frame.ratio, frame.secondary_ratio)
        # Resize the _new_ frame.
    c.frame.createFirstTreeNode()
    lm.createMenu(c)
    lm.finishOpen(c)
    g.app.writeWaitingLog(c)
    g.doHook("new", old_c=old_c, c=c, new_c=c)
    c.setLog()
    c.setChanged(False) # Fix #387
    g.app.disable_redraw = False
    c.redraw()
    return c # For unit tests and scripts.
Exemple #50
0
def unmarkAll(self, event=None):
    """Unmark all nodes in the entire outline."""
    c = self; u = c.undoer; undoType = 'Unmark All'
    current = c.p
    if not current: return
    c.endEditing()
    u.beforeChangeGroup(current, undoType)
    changed = False
    p = None  # To keep pylint happy.
    for p in c.all_unique_positions():
        if p.isMarked():
            bunch = u.beforeMark(p, undoType)
            # c.clearMarked(p) # Very slow: calls a hook.
            p.v.clearMarked()
            p.setDirty()
            u.afterMark(p, undoType, bunch)
            changed = True
    if changed:
        g.doHook("clear-all-marks", c=c, p=p)
        c.setChanged()
    u.afterChangeGroup(current, undoType)
    c.redraw_after_icons_changed()
Exemple #51
0
    def open_with(self, c, d):
        '''
        Called by c.openWith to handle items in the Open With... menu.

        d is a dictionary created from an @openwith settings node.

        'args':     the command-line arguments to be used to open the file.
        'ext':      the file extension.
        'kind':     the method used to open the file, such as subprocess.Popen.
        'name':     menu label (used only by the menu code).
        'shortcut': menu shortcut (used only by the menu code).

        d may also have the following entry, created by c.openWith:

        'p':        the nearest @<file> node.
        '''
        trace = False and not g.unitTesting
        if trace: self.dump_d(d, 'open_with')
        try:
            ext = d.get('ext')
            if not g.doHook('openwith1', c=c, p=c.p, v=c.p.v, d=d):
                root = d.get('p')
                if root:
                    # Called from open-with menu.
                    dir_ = g.setDefaultDirectory(c, root)
                    fn = c.os_path_finalize_join(dir_,
                                                 root.anyAtFileNodeName())
                    self.open_temp_file(c, d, fn)
                else:
                    p = c.p
                    d['ext'] = self.get_ext(c, p, ext)
                    fn = self.open_with_helper(c, d, p)
                    if fn:
                        self.open_temp_file(c, d, fn)
            g.doHook('openwith2', c=c, p=c.p, v=c.p.v, d=d)
        except Exception:
            g.es('unexpected exception in c.openWith')
            g.es_exception()
Exemple #52
0
    def onItemDoubleClicked (self,item,col):

        trace = False and not g.unitTesting
        verbose = False

        if self.busy(): return

        c = self.c

        if trace: g.trace(col,self.traceItem(item))

        try:
            self.selecting = True

            e,wrapper = self.createTreeEditorForItem(item)
            if e:
                wrapper.setEditorColors(
                    c.k.insert_mode_bg_color,
                    c.k.insert_mode_fg_color)
            else:
                g.trace('*** no e')

            p = self.item2position(item)
            
        # 2011/07/28: End the lockout here, not at the end.
        finally:
            self.selecting = False
            
        if p:
            event = None
            if g.doHook("icondclick1",c=c,p=p,v=p,event=event) is None:
                c.frame.tree.OnIconDoubleClick(p) # Call the base class method.
            g.doHook("icondclick2",c=c,p=p,v=p,event=event)
        else:
            g.trace('*** no p')

        c.outerUpdate()
    def open_with(self, c, d):
        '''
        Called by c.openWith to handle items in the Open With... menu.

        d is a dictionary created from an @openwith settings node.

        'args':     the command-line arguments to be used to open the file.
        'ext':      the file extension.
        'kind':     the method used to open the file, such as subprocess.Popen.
        'name':     menu label (used only by the menu code).
        'shortcut': menu shortcut (used only by the menu code).

        d may also have the following entry, created by c.openWith:

        'p':        the nearest @<file> node.
        '''
        trace = False and not g.unitTesting
        if trace: self.dump_d(d, 'open_with')
        try:
            ext = d.get('ext')
            if not g.doHook('openwith1', c=c, p=c.p, v=c.p.v, d=d):
                root = d.get('p')
                if root:
                    # Called from open-with menu.
                    dir_ = g.setDefaultDirectory(c, root)
                    fn = c.os_path_finalize_join(dir_, root.anyAtFileNodeName())
                    self.open_temp_file(c, d, fn)
                else:
                    p = c.p
                    ext = self.get_ext(c, p, ext)
                    fn = self.open_with_helper(c, ext, p)
                    if fn:
                        self.open_temp_file(c, d, fn)
            g.doHook('openwith2', c=c, p=c.p, v=c.p.v, d=d)
        except Exception:
            g.es('unexpected exception in c.openWith')
            g.es_exception()
 def onItemClicked (self,item,col,auto_edit=False):
     '''Handle a click in a baseNativeTree widget item.'''
     # This is called after an item is selected.
     trace = False and not g.unitTesting
     verbose = False
     if self.busy(): return
     c = self.c
     qt = QtCore.Qt
     # if trace: g.trace(self.traceItem(item),g.callers(4))
     try:
         self.selecting = True
         p = self.item2position(item)
         auto_edit = self.prev_v == p.v
         if p:
             self.prev_v = p.v
             event = None
             mods = g.app.gui.qtApp.keyboardModifiers()
             isCtrl = bool(mods & qt.ControlModifier)
             if trace: g.trace('auto_edit',auto_edit,'ctrl',isCtrl,p.h)
             # We could also add support for qt.ShiftModifier, qt.AltModifier	& qt.MetaModifier.
             if isCtrl:
                 if g.doHook("iconctrlclick1",c=c,p=p,v=p,event=event) is None:
                     c.frame.tree.OnIconCtrlClick(p) # Call the base class method.
                 g.doHook("iconctrlclick2",c=c,p=p,v=p,event=event)
             else:
                 # 2014/02/21: generate headclick1/2 instead of iconclick1/2
                 g.doHook("headclick1",c=c,p=p,v=p,event=event)
                 g.doHook("headclick2",c=c,p=p,v=p,event=event)
         else:
             auto_edit = None
             g.trace('*** no p')
         # 2011/05/27: click here is like ctrl-g.
         c.k.keyboardQuit(setFocus=False)
         c.treeWantsFocus() # 2011/05/08: Focus must stay in the tree!
         c.outerUpdate()
         # 2011/06/01: A second *single* click on a selected node
         # enters editing state.
         if auto_edit and self.auto_edit:
             e,wrapper = self.createTreeEditorForItem(item)
     finally:
         self.selecting = False
Exemple #55
0
    def onHeadChanged (self,p,undoType='Typing',s=None,e=None):

        '''Officially change a headline.'''

        trace = False and not g.unitTesting
        verbose = False

        c = self.c ; u = c.undoer
        if not p:
            if trace: g.trace('** no p')
            return

        item = self.getCurrentItem()
        if not item:
            if trace and verbose: g.trace('** no item')
            return
        if not e:
            e = self.getTreeEditorForItem(item)
        if not e:
            if trace and verbose: g.trace('** not editing')
            return

        s = g.u(e.text())

        if g.doHook("headkey1",c=c,p=c.p,v=c.p,s=s):
            return

        self.closeEditorHelper(e,item)
        oldHead = p.h
        changed = s != oldHead
        if changed:
            # New in Leo 4.10.1.
            if trace: g.trace('new',repr(s),'old',repr(p.h))
            #@+<< truncate s if it has multiple lines >>
            #@+node:ekr.20120409185504.10028: *4* << truncate s if it has multiple lines >>
            # Remove trailing newlines before warning of truncation.
            while s and s[-1] == '\n':
                s = s[:-1]

            # Warn if there are multiple lines.
            i = s.find('\n')
            if i > -1:
                s = s[:i]
                if s != oldHead:
                    g.warning("truncating headline to one line")

            limit = 1000
            if len(s) > limit:
                s = s[:limit]
                if s != oldHead:
                    g.warning("truncating headline to",limit,"characters")
            #@-<< truncate s if it has multiple lines >>
            p.initHeadString(s)
            item.setText(0,s) # Required to avoid full redraw.
            undoData = u.beforeChangeNodeContents(p,oldHead=oldHead)
            if not c.changed: c.setChanged(True)
            # New in Leo 4.4.5: we must recolor the body because
            # the headline may contain directives.
            c.frame.body.recolor(p,incremental=True)
            dirtyVnodeList = p.setDirty()
            u.afterChangeNodeContents(p,undoType,undoData,
                dirtyVnodeList=dirtyVnodeList)

        g.doHook("headkey2",c=c,p=c.p,v=c.p,s=s)

        # This is a crucial shortcut.
        if g.unitTesting: return

        if changed:
            self.redraw_after_head_changed()

        if 0: # Don't do this: it interferes with clicks, and is not needed.
            if self.stayInTree:
                c.treeWantsFocus()
            else:
                c.bodyWantsFocus()

        p.v.contentModified()
        c.outerUpdate()
Exemple #56
0
 def openurl_rclick_cb():
     if not g.doHook("@url1",c=c,p=p,url=url):
         g.handleUrl(url,c=c,p=p)
     g.doHook("@url2",c=c,p=p)
    def onRightClick(self, event):

        g.doHook('rclick-popup', c=self.c, event=event, context_menu=self.entry_menu)