예제 #1
0
def dump(ss,minwin,maxwin):
    for win,type,title in sc.gen_all_windows(minwin,maxwin,ss.pid):
        if type==0:
            type_string="basic"
        elif type==1:
            type_string="group"
        elif type==-1:
            type_string="zombie"
        else:
            type_string="unknown"

        print("%s %s"%(win,type_string))
        print("%s %s"%(win,title))
        filter=ss.get_exec(win)
        if filter!=-1:
            print("%s %s"%(win,filter))
        tty=ss.tty(win)
        print("%s %s"%(win,tty))
        if type==0:
            try:
                pids=sc.get_tty_pids(tty)
            except:
                print ("%s No access"%win)
                pass
            for pid in pids:
                try:
                    print ("%s %s %s"%(win,pid,sc.get_pid_info(pid)))
                except:
                    print ("%s No permission"%(win))
        print("\n")
예제 #2
0
def find_pids_in_windows(session, datadir, pids):
    import getpass
    import os
    tty_and_pids = sc._get_tty_pids_ps_with_cache_gen(getpass.getuser())

    #print(tty_and_pids)

    ttys = []
    for (tty, tpids) in tty_and_pids.items():

        #print('%s %s %s'%(pids,tty,tpids))

        for pid in pids:
            if pid in tpids:
                ttys.append(tty)
    wins = []
    for (cwin, cgroupid, ctype, ctty,
         ctitle) in sc.gen_all_windows_fast(session, datadir):
        try:
            ctty = int(os.path.split(ctty)[1])
            if ctty in ttys:
                wins.append(tuple([cwin, ctitle]))
        except Exception:
            pass
    return wins
예제 #3
0
def find_pids_in_windows(session, datadir, pids):
    import getpass
    import os
    tty_and_pids = sc._get_tty_pids_ps_with_cache_gen(getpass.getuser())

    #print(tty_and_pids)

    ttys = []
    for (tty, tpids) in tty_and_pids.items():

        #print('%s %s %s'%(pids,tty,tpids))

        for pid in pids:
            if pid in tpids:
                ttys.append(tty)
    wins = []
    for (cwin, cgroupid, ctype, ctty, ctitle) in sc.gen_all_windows_fast(session,
            datadir):
        try:
            ctty = int(os.path.split(ctty)[1])
            if ctty in ttys:
                wins.append(tuple([cwin, ctitle]))
        except Exception:
            pass
    return wins
예제 #4
0
def kill_current_group(ss,bKillHomeWindow=False,other_wins=[],homewindow=-1):
    if homewindow<0:
        cwin,ctitle=ss.get_number_and_title()
        homewindow=int(cwin)
    else:
        homewindow=int(homewindow)
    protected=tuple([(homewindow)]+other_wins)
    print (protected)
    cgroup=ss.get_group()
    print ('removing windows from group %s'%cgroup)
    while True:
        wins=sc.parse_windows(sc.get_windows(ss.pid))[0]
        print( wins)
        if len(wins)<=len(protected):
            break
        for w in wins:
            if w not in protected:
                print('removing %s'%w)
                ss.kill(w)
    for w in other_wins:
        ss.kill(w)
    for w in protected:
        if w != homewindow:
            print('removing protected %s'%w)
            ss.kill(w)
    if bKillHomeWindow:
        print('removing homewindow %s'%homewindow)
        ss.kill(homewindow)
예제 #5
0
    def load(self):
        if 'all' in self.force_start:
            self.primer_arg += 'S'
            self.force_start = []
        if 'all' in self.scroll:
            self._scrollfile = None
        out('session "%s" loading "%s"' % (self.pid, os.path.join(self.basedir,
            self.savedir)))

        #check if the saved session exists and get the biggest saved window number and a number of saved windows

        maxnewwindow = 0
        newwindows = 0
        try:
            winlist = list(glob.glob(os.path.join(self.basedir, self.savedir,
                           'win_*')))
            newwindows = len(winlist)
            out('%d new windows' % newwindows)
        except Exception:
            sys.stderr.write('Unable to open winlist.\n')
            return 1

        # keep original numbering, move existing windows

        self.homewindow = self.number()

        if self.exact:
            maxnewwindow = -1
            for w in winlist:
                try:
                    w = int(w.rsplit("_", 1)[1])
                    if w > maxnewwindow:
                        maxnewwindow = w
                except:
                    pass

            out('Biggest new window number: %d' % maxnewwindow)
            if self.enable_layout:
                self.__remove_all_layouts()
            self.__move_all_windows(maxnewwindow + 1, self.group_other,
                                    False)

        out("\nLoading windows:")
        self.__load_screen()

        if self.enable_layout:
            out("\nLoading layouts:")
            try:
                self.__load_layouts()
            except:
                sys.stderr.write('Layouts loading failed!\n')
                # raise

        self.__restore_mru()
        sc.cleanup()

        return 0
예제 #6
0
    def load(self):
        if "all" in self.force_start:
            self.primer_arg += "S"
            self.force_start = []
        if "all" in self.scroll:
            self._scrollfile = None
        out('session "%s" loading "%s"' % (self.pid, os.path.join(self.basedir, self.savedir)))

        # check if the saved session exists and get the biggest saved window number and a number of saved windows

        maxnewwindow = 0
        newwindows = 0
        try:
            winlist = list(glob.glob(os.path.join(self.basedir, self.savedir, "win_*")))
            newwindows = len(winlist)
            out("%d new windows" % newwindows)
        except Exception:
            sys.stderr.write("Unable to open winlist.\n")
            return 1

        # keep original numbering, move existing windows

        self.homewindow = self.number()

        if self.exact:
            maxnewwindow = -1
            for w in winlist:
                try:
                    w = int(w.rsplit("_", 1)[1])
                    if w > maxnewwindow:
                        maxnewwindow = w
                except:
                    pass

            out("Biggest new window number: %d" % maxnewwindow)
            if self.enable_layout:
                self.__remove_all_layouts()
            self.__move_all_windows(maxnewwindow + 1, self.group_other, False)

        out("\nLoading windows:")
        self.__load_screen()

        if self.enable_layout:
            out("\nLoading layouts:")
            try:
                self.__load_layouts()
            except:
                sys.stderr.write("Layouts loading failed!\n")
                # raise

        self.__restore_mru()
        sc.cleanup()

        return 0
예제 #7
0
def prime(fifoname):
    l1=sc.get_session_list()
    cmd='screen -S "MANAGER_NOATTACH" -m -d -c /dev/null python %s %s %s'%(sys.argv[0],'ui',fifoname)
    sys.stderr.write(cmd+'\n')
    os.popen(cmd)
    l2=sc.get_session_list()
    sys.stderr.write('searching for target session..\n')
    session=sc.find_new_session(l1,l2)
    sys.stderr.write('target session = %s\n'%session)

    print ('session: %s'%session)
    return session
예제 #8
0
def kill_group(session,win):
    print ('killing group %s'%win)
    ss=ScreenSaver(session,'/dev/null','/dev/null')
    tty=ss.tty(win)
    if tty!="telnet":
        print('This window is not a group. Aborting.')
        return
    ss.select(win)
    wins=sc.parse_windows(sc.get_windows(session))[0]
    print wins
    for w in wins:
       print('killing %s'%w)
예제 #9
0
def kill_win_last_proc(session,win="-1",sig="TERM"):
    import signal,os,platform
    ss=ScreenSaver(session,'/dev/null','/dev/null')
    ctty=ss.tty(win)
    if platform.system() == 'FreeBSD':
        pids=sc.get_tty_pids(ctty)
    else:
        pids=sc._get_tty_pids_pgrep(ctty)
    pid = pids[-1]

    sig=eval('signal.SIG'+sig)
    os.kill(int(pid),sig)
예제 #10
0
def prime(fifoname):
    l1 = sc.get_session_list()
    cmd = SCREEN + \
        ' -S "GNU_SCREEN_SESSIONS_MANAGER" -m -d -c /dev/null "%s" "%s" "%s" "%s"' % \
        (os.getenv('PYTHONBIN'), (sys.argv)[0], 'ui', fifoname)
    sys.stderr.write(cmd + "\n")
    os.popen(cmd)
    l2 = sc.get_session_list()
    sys.stderr.write('searching for target session..\n')
    session = sc.find_new_session(l1, l2)
    sys.stderr.write('target session = %s\n' % session)

    print 'session: %s' % session
    return session
예제 #11
0
def dump(ss,showpid=True,reverse=True,sort=False,groupids=[]):
    from sys import stdout
    bShow=True
    windows=[]
    if groupids:
        windows=subwindows(ss.pid,groupids)[1]
    for cwin,cgroupid,cgroup,ctty,ctype,ctypestr,ctitle,cfilter,cscroll,ctime in sc.gen_all_windows_full(ss.pid,reverse,sort):
        if groupids:
            if cwin in windows:
                bShow=True
            else:
                bShow=False
        if bShow:
            print("----------------------------------------")
            lines=[]
            lines.append("%s TYPE  %s\n"%(cwin,ctypestr))
            if cgroupid=='-1':
                groupstr='-1'
            else:
                groupstr=cgroupid+' '+cgroup
            lines.append("%s GRP   %s\n"%(cwin,groupstr))
            lines.append("%s TITL  %s\n"%(cwin,ctitle))
            if cfilter!='-1':
                lines.append("%s EXEC  %s\n"%(cwin,cfilter))
            if ctype==0:
                lines.append("%s TTY   %s\n"%(cwin,ctty))
                if showpid:
                    try:
                        pids=sc.get_tty_pids(ctty)
                    except:
                        lines.append ("%s No access\n"%cwin)
                        pass
                    for pid in pids:
                        try:
                            cwd,exe,cmd=sc.get_pid_info(pid)
                            lines.append ("%s PID   %s CWD %s\n"%(cwin,pid,cwd))
                            lines.append ("%s PID   %s EXE %s\n"%(cwin,pid,exe))
                            cmd=cmd.split('\0')[:-1]
                            lines.append ("%s PID   %s CMD %s\n"%(cwin,pid,cmd))
                            try:
                                if cmd[0].endswith('screen-session-primer') and cmd[1]=='-p':
                                    lines[0]=lines[0][:-1]+" / primer\n"
                                elif cmd[0] in ('vi','vim','viless','vimdiff'): 
                                    lines[0]=lines[0][:-1]+" / VIM\n"
                            except:
                                pass
                        except:
                            lines.append ("%s PID > %s < No permission\n"%(cwin,pid))
            map(stdout.write,lines)
예제 #12
0
def renumber(session, datadir):
    ss = ScreenSaver(session, '/dev/null', '/dev/null')
    wins = []
    wins_trans = {}
    for (cwin, cgroupid, ctype, ctty, ctitle) in sc.gen_all_windows_fast(session,
            datadir):
        iwin = int(cwin)
        wins.append((iwin, cgroupid, ctype))
        wins_trans[iwin] = iwin

    wins.sort(key=lambda wins: wins[0])
    print wins_trans
    i = 0
    for (win, groupid, ctype) in wins:
        if wins_trans[win] != i:

            #print("win %d(%d)(%s) as %d"%(wins_trans[win],win,group,i))

            ss.number(str(i), str(wins_trans[win]))
            tmp = wins_trans[win]
            try:
                wins_trans[win] = wins_trans[i]
            except:
                wins_trans[win] = -1
            wins_trans[i] = tmp
        i += 1
    print wins_trans
예제 #13
0
def renumber(session, datadir):
    ss = ScreenSaver(session, '/dev/null', '/dev/null')
    wins = []
    wins_trans = {}
    for (cwin, cgroupid, ctype, ctty,
         ctitle) in sc.gen_all_windows_fast(session, datadir):
        iwin = int(cwin)
        wins.append((iwin, cgroupid, ctype))
        wins_trans[iwin] = iwin

    wins.sort(key=lambda wins: wins[0])
    print wins_trans
    i = 0
    for (win, groupid, ctype) in wins:
        if wins_trans[win] != i:

            #print("win %d(%d)(%s) as %d"%(wins_trans[win],win,group,i))

            ss.number(str(i), str(wins_trans[win]))
            tmp = wins_trans[win]
            try:
                wins_trans[win] = wins_trans[i]
            except:
                wins_trans[win] = -1
            wins_trans[i] = tmp
        i += 1
    print wins_trans
예제 #14
0
def main():
    logfile="___log-nest-layout"
    dumpfile="___scs-nest-layout-dump-%d"%os.getpid()
    if not os.path.exists(tmpdir):
        os.makedirs(tmpdir)
    logfile=os.path.join(tmpdir,logfile)
    dumpfile=os.path.join(tmpdir,dumpfile)
    sys.stdout=open(logfile,'w')
    sys.stderr=sys.stdout
    session=sys.argv[1]
    tlayout=sys.argv[2]

    scs=ScreenSaver(session)
    homelayout,homelayoutname=scs.get_layout_number()
    while True:
        regions=sc.get_regions(scs.pid)
        try:
            focusminsize="%s %s"%(regions[3][0], regions[3][1])
            regions_c=regions[0]
            foff=regions[1]
            rsize=tuple([int(regions[4+foff][1]),int(regions[4+foff][2])])
            hsize=int(regions[2][0]),int(regions[2][1])
            if regions[4][0]:
                break
        except Exception,x:
            print(x)
            sys.exit(2)
            pass
예제 #15
0
def sort(session,min,max,key=None):
    ss=ScreenSaver(session,'/dev/null','/dev/null')
    wins=[]
    wins_trans={}
    groups={}
    cgroup=None
    for win,type,title in sc.gen_all_windows(min,max,session):
        iwin=int(win)
        group=ss.get_group(win)

        lastval=(group,iwin,type,title)
        try:
            groups[group].append(lastval)
        except:
            groups[group]=[lastval]
            
    win_biggest=lastval[1]
    for i in range(0,win_biggest+1):
        wins_trans[i]=i

    i=0
    for group,props in groups.items():
        props.sort(key=lambda wins:wins[3].lower())
        #print( str(len(props))+' : '+group + ' : ' + str(props))
        for group,win,type,title in props:
            if wins_trans[win]!=i:
                #print("win %d(%d)(%s) as %d"%(wins_trans[win],win,group,i))
                ss.number(str(i),str(wins_trans[win]))
                tmp=wins_trans[win]
                wins_trans[win]=wins_trans[i]
                wins_trans[i]=tmp
            i+=1
    return
예제 #16
0
    def __move_all_windows(self,shift,group,kill=False):
        homewindow=int(self.homewindow)
        # create wrap group for existing windows
        if not self.bNoGroupWrap:
            self.screen('-t \"%s\" //group' % ('%s_%s'%(group,self.__unique_ident)) )
            self.group(False,self.none_group)
            self.wrap_group_id=self.number()

        # move windows by shift and put them in a wrap group
        #for cwin,cgroupid,ctype,ctty in sc.gen_all_windows_fast(self.pid):
        for cwin,cgroupid,cgroup,ctty,ctype,ctypestr,ctitle,cfilter,cscroll,ctime in sc.gen_all_windows_full(self.pid):
            iwin=int(cwin)
            if iwin==homewindow:
                homewindow=iwin+shift
                self.homewindow=str(homewindow)
            
            cgroupid,cgroup = self.get_group(cwin)
            if not self.bNoGroupWrap and cgroup==self.none_group:
                self.select(self.wrap_group_id)
                self.group(False,group,str(cwin))
            command='%s -p %s -X number +%d' % (self.sc,cwin,shift)
            if not self.bNoGroupWrap and str(cwin)==str(self.wrap_group_id):
                out('Moving wrap group %s to %d'%(cwin,iwin+shift))
                self.wrap_group_id=str(iwin+shift)
            else:
                out('Moving window %s to %d'%(cwin,iwin+shift))
            os.system(command)
        self.select('%d'%(homewindow))
예제 #17
0
def cleanup():
    cmd = ''
    f = open(sourcefile, 'w')
    for (i, w) in enumerate(win_history):
        if w == "-1":
            w = "-"
        f.write("""select %s
at \"%s\#\" kill
focus
""" % (w, wins[i]))
    f.flush()
    f.close()
    scs.source(sourcefile)
    scs.focusminsize(focusminsize)
    sc.cleanup()
    remove(sourcefile)
예제 #18
0
def subwindows(session, datadir, groupids):
    ss = ScreenSaver(session)
    bAll = False
    try:
        if groupids[0] in ('cg', 'current', '..'):
            groupids[0] = ss.get_group()[0]
            if groupids[0] == "-1":
                bAll = True
        elif groupids[0] in ('cw', 'current-window', '.'):
            groupids[0] = ss.get_number_and_title()[0]
        elif groupids[0] == 'all':
            bAll = True
    except IndexError:
        bAll = True
    group_wins = {}
    group_groups = {}
    excluded_wins = []
    excluded_groups = []
    for (cwin, cgroupid, ctype, ctty,
         ctitle) in sc.gen_all_windows_fast(session, datadir):
        if ctype == 1:  # group
            if cwin in groupids or bAll or ctitle in groupids:
                excluded_groups.append(cwin)
            try:
                group_groups[cgroupid] += [cwin]
            except:
                group_groups[cgroupid] = [cwin]
        else:

            # anything other than group

            if cwin in groupids or bAll or ctitle in groupids:
                excluded_wins.append(cwin)
            else:
                try:
                    group_wins[cgroupid] += [cwin]
                except:
                    group_wins[cgroupid] = [cwin]
    excluded_groups_tmp = []
    while excluded_groups:
        egroup = excluded_groups.pop()
        if egroup not in excluded_groups_tmp:
            excluded_groups_tmp.append(egroup)
        try:
            ngroups = group_groups[egroup]
            if ngroups:
                for g in ngroups:
                    excluded_groups.append(g)
        except:
            pass
    excluded_groups = excluded_groups_tmp
    for egroup in excluded_groups:
        excluded_wins.append(egroup)
        try:
            for w in group_wins[egroup]:
                excluded_wins.append(w)
        except:
            pass
    return (excluded_groups, excluded_wins)
예제 #19
0
def subwindows(session, datadir, groupids):
    ss = ScreenSaver(session)
    bAll = False
    try:
        if groupids[0] in ('cg', 'current', '..'):
            groupids[0] = ss.get_group()[0]
            if groupids[0] == "-1":
                bAll = True
        elif groupids[0] in ('cw', 'current-window', '.'):
            groupids[0] = ss.get_number_and_title()[0]
        elif groupids[0] == 'all':
            bAll = True
    except IndexError:
        bAll = True
    group_wins = {}
    group_groups = {}
    excluded_wins = []
    excluded_groups = []
    for (cwin, cgroupid, ctype, ctty, ctitle) in sc.gen_all_windows_fast(session,
            datadir):
        if ctype == 1:  # group
            if cwin in groupids or bAll or ctitle in groupids:
                excluded_groups.append(cwin)
            try:
                group_groups[cgroupid] += [cwin]
            except:
                group_groups[cgroupid] = [cwin]
        else:

              # anything other than group

            if cwin in groupids or bAll or ctitle in groupids:
                excluded_wins.append(cwin)
            else:
                try:
                    group_wins[cgroupid] += [cwin]
                except:
                    group_wins[cgroupid] = [cwin]
    excluded_groups_tmp = []
    while excluded_groups:
        egroup = excluded_groups.pop()
        if egroup not in excluded_groups_tmp:
            excluded_groups_tmp.append(egroup)
        try:
            ngroups = group_groups[egroup]
            if ngroups:
                for g in ngroups:
                    excluded_groups.append(g)
        except:
            pass
    excluded_groups = excluded_groups_tmp
    for egroup in excluded_groups:
        excluded_wins.append(egroup)
        try:
            for w in group_wins[egroup]:
                excluded_wins.append(w)
        except:
            pass
    return (excluded_groups, excluded_wins)
예제 #20
0
def prepare_windows(scs):
    print('prepare_windows()')
    global focusminsize
    regions=[]
    while True:
        regions=sc.get_regions(scs.pid)
        try:
            focusminsize="%s %s"%(regions[3][0], regions[3][1])
            regions_c=regions[0]
            focus_offset=regions[1]
            if regions[4][0]:
                break
        except:
            pass
    print("regions = "+str(regions))
    scs.focusminsize('0 0')
    this_win_history=[]
    cmd=''
    for i in range(0,regions_c):
        cmd+='screen -S %s -X eval \'screen -t scs-regions-helper %s %s %s %d\' \'focus\'; '%(scs.pid,subprogram,subprogram_args,inputfile,i)
    os.system(cmd)
    
    regions_n=[]
    while True:
        regions_n=sc.get_regions(scs.pid)
        try:
            if regions_n[2+i][0]:
                break
        except:
            pass
    print("regions_n = "+str(regions_n))

    for r in regions[4+focus_offset:]:
        this_win_history.append(r[0])
    for r in regions[4:4+focus_offset]:
        this_win_history.append(r[0])

    new_windows=[]
    for r in regions_n[4+focus_offset:]:
        new_windows.append(r[0])
    for r in regions_n[4:4+focus_offset]:
        new_windows.append(r[0])
        
    return this_win_history,new_windows,regions_c
예제 #21
0
    def save(self):
        (self.homewindow, title) = self.get_number_and_title()
        out("\nCreating directories:")
        if not self.__setup_savedir(self.basedir, self.savedir):
            return 1
        sc.require_dumpscreen_window(self.pid, True)

        if self.enable_layout:
            out("\nSaving layouts:")
            self.__save_layouts()

        out("\nSaving windows:")
        self.__save_screen()

        out("\nCleaning up scrollbacks.")
        self.__scrollback_clean()
        if self.__vim_files:
            self.__wait_vim()
        return 0
예제 #22
0
def get_win_last_proc(session, win="-1", ctty = None):
    import platform
    if not ctty:
        ss = ScreenSaver(session, '/dev/null', '/dev/null')
        ctty = ss.tty(win)
    if ctty is None or ctty == -1:
        stderr.write("Window does not exist (%s)\n" % win)
        return False
    if platform.system() == 'FreeBSD':
        pids = sc.get_tty_pids(ctty)
    else:
        pids = sc._get_tty_pids_pgrep(ctty)
    if len(pids) > 0:
        return pids[-1]
    else:

        ## No processes for this window.

        return None
예제 #23
0
def kill_win_last_proc(session,win="-1",sig="TERM"):
    import signal,os
    ss=ScreenSaver(session,'/dev/null','/dev/null')
    ctty=ss.tty(win)
    pids=sc.get_tty_pids(ctty)
    pid = pids[len(pids)-1]

    sig=eval('signal.SIG'+sig)

    os.kill(int(pid),sig)
예제 #24
0
def get_win_last_proc(session, win="-1", ctty=None):
    import platform
    if not ctty:
        ss = ScreenSaver(session, '/dev/null', '/dev/null')
        ctty = ss.tty(win)
    if ctty is None or ctty == -1:
        stderr.write("Window does not exist (%s)\n" % win)
        return False
    if platform.system() == 'FreeBSD':
        pids = sc.get_tty_pids(ctty)
    else:
        pids = sc._get_tty_pids_pgrep(ctty)
    if len(pids) > 0:
        return pids[-1]
    else:

        ## No processes for this window.

        return None
예제 #25
0
    def save(self):
        (self.homewindow, title) = self.get_number_and_title()
        out("\nCreating directories:")
        if not self.__setup_savedir(self.basedir, self.savedir):
            return 1
        sc.require_dumpscreen_window(self.pid, True)

        if self.enable_layout:
            out("\nSaving layouts:")
            self.__save_layouts()

        out("\nSaving windows:")
        self.__save_screen()

        out("\nCleaning up scrollbacks.")
        self.__scrollback_clean()
        if self.__vim_files:
            self.__wait_vim()
        return 0
예제 #26
0
    def __move_all_windows(self, shift, group, kill=False):
        homewindow = int(self.homewindow)

        # create a wrap group for existing windows

        if not self.bNoGroupWrap:
            self.wrap_group_id = self.screen('-t \"%s\" //group' % ('%s_%s' % (group, self.__unique_ident)))
            self.group(False, self.none_group, self.wrap_group_id)

        # move windows by shift and put them in a wrap group
        #for cwin,cgroupid,ctype,ctty in sc.gen_all_windows_fast(self.pid):

        for (
            cwin,
            cgroupid,
            cgroup,
            ctty,
            ctype,
            ctypestr,
            ctitle,
            cfilter,
            cscroll,
            ctime,
            cmdargs,
            ) in sc.gen_all_windows_full(self.pid, sc.require_dumpscreen_window(self.pid,
                    True)):
            iwin = int(cwin)
            if iwin == homewindow:
                homewindow = iwin + shift
                self.homewindow = str(homewindow)

            if not self.bNoGroupWrap and cgroup == self.none_group:
                self.select(self.wrap_group_id)
                self.group(False, group, str(cwin))
            command = '%s -p %s -X number +%d' % (self.sc, cwin, shift)
            if not self.bNoGroupWrap and str(cwin) == str(self.wrap_group_id):
                out('Moving wrap group %s to %d' % (cwin, iwin + shift))
                self.wrap_group_id = str(iwin + shift)
            else:
                out('Moving window %s to %d' % (cwin, iwin + shift))
            os.system(command)
        self.select('%d' % homewindow)
예제 #27
0
    def __save_layouts(self):
        (homelayout, homelayoutname) = self.get_layout_number()
        findir = sc.datadir
        if homelayout == -1:
            sys.stderr.write("No layouts to save.\n")
            return False
        path_layout = os.path.join(findir, "load_layout")
        oflayout = open(path_layout, "w")
        ex_lay = []
        for lay in sc.gen_layout_info(self, sc.dumpscreen_layout_info(self)):
            try:
                num = lay[0]
                title = lay[1]
            except:
                title = ""
            if self.excluded_layouts and (num in self.excluded_layouts or title in self.excluded_layouts):
                ex_lay.append(lay)
            else:
                sys.stdout.write("%s(%s); " % (num, title))
                oflayout.write(
                    """layout select %s
layout dump \"%s\"
dumpscreen layout \"%s\"
"""
                    % (num, os.path.join(findir, "layout_" + num), os.path.join(findir, "winlayout_" + num))
                )

        oflayout.write("layout select %s\n" % homelayout)
        oflayout.close()
        self.source(path_layout)
        util.remove(path_layout)
        linkify(findir, "layout_" + homelayout, "last_layout")
        if ex_lay:
            sys.stdout.write(
                """

Excluded layouts: %s"""
                % str(ex_lay)
            )

        out("")
        return True
예제 #28
0
def kill_zombie(session,groupids=[]):
    ss=ScreenSaver(session,'/dev/null','/dev/null')
    if groupids:
        windows=subwindows(session,groupids)[1]
    for cwin,cgroupid,ctype,ctty,ctitle in sc.gen_all_windows_fast(session):
        if ctype==-1:
            if groupids:
                if cwin in windows:
                    ss.kill(cwin)
            else:
                ss.kill(cwin)
예제 #29
0
    def __move_all_windows(self, shift, group, kill=False):
        homewindow = int(self.homewindow)

        # create a wrap group for existing windows

        if not self.bNoGroupWrap:
            self.wrap_group_id = self.screen('-t "%s" //group' % ("%s_%s" % (group, self.__unique_ident)))
            self.group(False, self.none_group, self.wrap_group_id)

        # move windows by shift and put them in a wrap group
        # for cwin,cgroupid,ctype,ctty in sc.gen_all_windows_fast(self.pid):

        for (
            cwin,
            cgroupid,
            cgroup,
            ctty,
            ctype,
            ctypestr,
            ctitle,
            cfilter,
            cscroll,
            ctime,
            cmdargs,
        ) in sc.gen_all_windows_full(self.pid, sc.require_dumpscreen_window(self.pid, True)):
            iwin = int(cwin)
            if iwin == homewindow:
                homewindow = iwin + shift
                self.homewindow = str(homewindow)

            if not self.bNoGroupWrap and cgroup == self.none_group:
                self.select(self.wrap_group_id)
                self.group(False, group, str(cwin))
            command = "%s -p %s -X number +%d" % (self.sc, cwin, shift)
            if not self.bNoGroupWrap and str(cwin) == str(self.wrap_group_id):
                out("Moving wrap group %s to %d" % (cwin, iwin + shift))
                self.wrap_group_id = str(iwin + shift)
            else:
                out("Moving window %s to %d" % (cwin, iwin + shift))
            os.system(command)
        self.select("%d" % homewindow)
예제 #30
0
def kill_zombie(session, datadir, groupids=[]):
    ss = ScreenSaver(session, '/dev/null', '/dev/null')
    if groupids:
        windows = subwindows(session, datadir, groupids)[1]
    for (cwin, cgroupid, ctype, ctty,
         ctitle) in sc.gen_all_windows_fast(session, datadir):
        if ctype == -1:
            if groupids:
                if cwin in windows:
                    ss.kill(cwin)
            else:
                ss.kill(cwin)
예제 #31
0
    def __save_layouts(self):
        (homelayout, homelayoutname) = self.get_layout_number()
        findir = sc.datadir
        if homelayout == -1:
            sys.stderr.write("No layouts to save.\n")
            return False
        path_layout = os.path.join(findir, "load_layout")
        oflayout = open(path_layout, "w")
        ex_lay = []
        for lay in sc.gen_layout_info(self, sc.dumpscreen_layout_info(self)):
            try:
                num = lay[0]
                title = lay[1]
            except:
                title = ""
            if self.excluded_layouts and (num in self.excluded_layouts or
                    title in self.excluded_layouts):
                ex_lay.append(lay)
            else:
                sys.stdout.write("%s(%s); " % (num, title))
                oflayout.write('''layout select %s
layout dump \"%s\"
dumpscreen layout \"%s\"
''' %
                               (num, os.path.join(findir, "layout_" +
                               num), os.path.join(findir, "winlayout_" +
                               num)))

        oflayout.write('layout select %s\n' % homelayout)
        oflayout.close()
        self.source(path_layout)
        util.remove(path_layout)
        linkify(findir, "layout_" + homelayout, "last_layout")
        if ex_lay:
            sys.stdout.write("""

Excluded layouts: %s""" % str(ex_lay))

        out("")
        return True
예제 #32
0
def subwindows(session,groupids,datafile=None):
    ss=ScreenSaver(session)
    bAll=False
    if groupids[0] in ('cg','current'):
        groupids[0]=ss.get_group()[0]
    elif groupids[0] in ('cw','current-window'):
        groupids[0]=ss.get_number_and_title()[0]
    elif groupids[0]=='all':
        bAll=True
    group_wins={}
    group_groups={}
    excluded_wins=[]
    excluded_groups=[]
    #for cwin,cgroupid,cgroup,ctty,ctype,ctypestr,ctitle,cfilter,cscroll,ctime in sc.gen_all_windows_full(session):
    for cwin,cgroupid,ctype,ctty,ctitle in sc.gen_all_windows_fast(session,datafile):
        if(ctype==1): # group
            if cwin in groupids or bAll or ctitle in groupids:
                excluded_groups.append(cwin)
            try:
                group_groups[cgroupid]+=[cwin]
            except:
                group_groups[cgroupid]=[cwin]
        else: # anything other than group
            if cwin in groupids or ctitle in groupids:
                excluded_wins.append(cwin)
            else:
                try:
                    group_wins[cgroupid]+=[cwin]
                except:
                    group_wins[cgroupid]=[cwin]
    excluded_groups_tmp=[]
    while excluded_groups:
        egroup=excluded_groups.pop()
        if egroup not in excluded_groups_tmp:
            excluded_groups_tmp.append(egroup)
        try:
            ngroups = group_groups[egroup]
            if ngroups:
                for g in ngroups:
                    excluded_groups.append(g)
        except:
            pass
    excluded_groups = excluded_groups_tmp
    for egroup in excluded_groups:
        excluded_wins.append(egroup)
        try:
            for w in group_wins[egroup]:
                excluded_wins.append(w)
        except:
            pass
    return excluded_groups,excluded_wins
예제 #33
0
def sort(session, datadir, key=None):
    ss = ScreenSaver(session, '/dev/null', '/dev/null')
    wins = []
    wins_trans = {}
    groups = {}
    cgroup = None
    for (cwin, cgroupid, ctype, ctty,
         ctitle) in sc.gen_all_windows_fast(session, datadir):
        iwin = int(cwin)
        lastval = (groupid, iwin, ctype, ss.title('', iwin))
        try:
            groups[groupid].append(lastval)
        except:
            groups[groupid] = [lastval]
        wins_trans[iwin] = iwin

    i = 0
    for (group, props) in groups.items():
        try:
            props.sort(key=lambda wins: wins[3].lower())
        except:
            print 'FAIL'
            print str(len(props)) + ' : ' + group + ' : ' + str(props)
            pass

        #print( str(len(props))+' : '+group + ' : ' + str(props))

        for (groupid, win, ctype, title) in props:
            if wins_trans[win] != i:

                #print("win %d(%d)(%s) as %d"%(wins_trans[win],win,group,i))

                ss.number(str(i), str(wins_trans[win]))
                tmp = wins_trans[win]
                try:
                    wins_trans[win] = wins_trans[i]
                except:
                    wins_trans[win] = -1
                wins_trans[i] = tmp
            i += 1
    return
예제 #34
0
def sort(session, datadir, key=None):
    ss = ScreenSaver(session, '/dev/null', '/dev/null')
    wins = []
    wins_trans = {}
    groups = {}
    cgroup = None
    for (cwin, cgroupid, ctype, ctty, ctitle) in sc.gen_all_windows_fast(session,
            datadir):
        iwin = int(cwin)
        lastval = (groupid, iwin, ctype, ss.title('', iwin))
        try:
            groups[groupid].append(lastval)
        except:
            groups[groupid] = [lastval]
        wins_trans[iwin] = iwin

    i = 0
    for (group, props) in groups.items():
        try:
            props.sort(key=lambda wins: wins[3].lower())
        except:
            print 'FAIL'
            print str(len(props)) + ' : ' + group + ' : ' + str(props)
            pass

        #print( str(len(props))+' : '+group + ' : ' + str(props))

        for (groupid, win, ctype, title) in props:
            if wins_trans[win] != i:

                #print("win %d(%d)(%s) as %d"%(wins_trans[win],win,group,i))

                ss.number(str(i), str(wins_trans[win]))
                tmp = wins_trans[win]
                try:
                    wins_trans[win] = wins_trans[i]
                except:
                    wins_trans[win] = -1
                wins_trans[i] = tmp
            i += 1
    return
예제 #35
0
def prepare_windows(scs):
    global focusminsize
    regions = None
    regions = sc.get_regions(sc.dumpscreen_layout(scs.pid))
    sc.cleanup()
    focusminsize = "%s %s" % (regions.focusminsize_x, regions.focusminsize_x)
    regions_c = len(regions.regions)
    focus_offset = regions.focus_offset
    scs.focusminsize('0 0')
    this_win_history = []
    cmd = ''
    f = open(sourcefile, 'w')
    for i in range(0, regions_c):
        f.write("""screen -t scs-regions-helper %s %s %s %d
focus
""" %
                (subprogram, subprogram_args, inputfile, i))
    f.flush()
    f.close
    scs.source(sourcefile, "screen-session regions")
    remove(sourcefile)

    regions_n = []
    regions_n = sc.get_regions(sc.dumpscreen_layout(scs.pid))
    sc.cleanup()

    for r in (regions.regions)[focus_offset:]:
        this_win_history.append(r[0])
    for r in (regions.regions)[:focus_offset]:
        this_win_history.append(r[0])

    new_windows = []
    for r in (regions_n.regions)[focus_offset:]:
        new_windows.append(r[0])
    for r in (regions_n.regions)[:focus_offset]:
        new_windows.append(r[0])

    return (this_win_history, new_windows, regions_c)
예제 #36
0
def make_group_tabs(session,groupids,bAll=False):
    group_wins={}
    group_groups={}
    excluded_wins=[]
    excluded_groups=[]
    for cwin,cgroupid,ctype,ctty,ctitle in sc.gen_all_windows_fast(session):
        if(ctype==1): # group
            if cwin in groupids or bAll:
                excluded_groups.append(cwin)
            try:
                group_groups[cgroupid]+=[cwin]
            except:
                group_groups[cgroupid]=[cwin]
        else: # anything other than group
            if cwin in groupids:
                excluded_wins.append(cwin)
            else:
                try:
                    group_wins[cgroupid]+=[cwin]
                except:
                    group_wins[cgroupid]=[cwin]
    return group_groups,group_wins,excluded_groups,excluded_wins
예제 #37
0
def renumber(session,min,max):
    ss=ScreenSaver(session,'/dev/null','/dev/null')
    wins=[]
    wins_trans={}
    for win,type,title in sc.gen_all_windows(min,max,session):
        iwin=int(win)
        wins.append((ss.get_group(win),iwin,type))

    win_biggest=wins[len(wins)-1][1]
    for i in range(0,win_biggest+1):
        wins_trans[i]=i

    wins.sort(key=lambda wins:wins[0])

    i=0
    for group,win,type in wins:
        if wins_trans[win]!=i:
            #print("win %d(%d)(%s) as %d"%(wins_trans[win],win,group,i))
            ss.number(str(i),str(wins_trans[win]))
            tmp=wins_trans[win]
            wins_trans[win]=wins_trans[i]
            wins_trans[i]=tmp
        i+=1
예제 #38
0
        if ret:
            sys.stderr.write('session saving failed\n')
            scs.Xecho("screen-session saving FAILED")
        else:
            out('compressing...')
            scs.Xecho("screen-session compressing...")
            removeit(os.path.join(home, projectsdir, savedir_real))
            removeit(os.path.join(util.tmpdir, savedir_real))
            archiveme(util.tmpdir, home, projectsdir, savedir_real, util.archiveend,
                      savedir_real + '__tmp/*')
            removeit(os.path.join(home, projectsdir, savedir_tmp))
            removeit(os.path.join(util.tmpdir, savedir_tmp))
            scs.savedir = savedir_real
            savedir = savedir_real
            sc.cleanup()
            out('session "%s"' % scs.pid)
            out('saved as "%s"' % scs.savedir)
            scs.Xecho("screen-session finished saving as \"%s\"" %
                      savedir)
    elif mode == 2:  #mode load

        #cleanup old temporary files and directories

        cleantmp(util.tmpdir, home, projectsdir, util.archiveend, scs.blacklistfile,
                 500)

        # unpack and load

        try:
            unpackme(home, projectsdir, savedir, util.archiveend, util.tmpdir)
예제 #39
0
def dump(ss, datadir, showpid=True, reverse=True, sort=False, groupids=[]):
    from sys import stdout
    bShow = True
    windows = []
    sum_process_total = 0
    sum_win = 0
    sum_zombie = 0
    sum_basic = 0
    sum_group = 0
    sum_telnet = 0
    sum_primer = 0
    sum_vim = 0
    if groupids:
        (groups, windows) = subwindows(ss.pid, datadir, groupids)
    try:
        for (
                cwin,
                cgroupid,
                cgroup,
                ctty,
                ctype,
                ctypestr,
                ctitle,
                cfilter,
                cscroll,
                ctime,
                cmdargs,
        ) in sc.gen_all_windows_full(ss.pid, datadir, reverse, sort):
            if groupids:
                if cwin in windows:
                    bShow = True
                else:
                    bShow = False
            if bShow:
                sum_win += 1
                if ctype == -1:
                    sum_zombie += 1
                elif ctype == 0:
                    sum_basic += 1
                elif ctype == 1:
                    sum_group += 1
                elif ctype == 2:
                    sum_telnet += 1
                print "----------------------------------------"
                lines = []
                lines.append("%s TYPE %s\n" % (cwin, ctypestr))
                if cgroupid == "-1":
                    groupstr = "-1"
                else:
                    groupstr = cgroupid + " " + cgroup
                lines.append("%s GRP %s\n" % (cwin, groupstr))
                lines.append("%s TITL %s\n" % (cwin, ctitle))
                cmdargs = cmdargs.split('\0')
                pcmdargs = cmdargs[0]
                if cmdargs[1] != '':
                    pcmdargs += " " + (" ").join(
                        ["\"%s\"" % v for v in cmdargs[1:-1]])
                lines.append("%s CARG %s\n" % (cwin, pcmdargs))
                if cfilter != "-1":
                    lines.append("%s EXEC %s\n" % (cwin, cfilter))
                if ctype == 0:
                    lines.append("%s TTY %s\n" % (cwin, ctty))
                    if showpid:
                        try:
                            pids = sc.get_tty_pids(ctty)
                            for pid in pids:
                                sum_process_total += 1
                                try:
                                    (cwd, exe, cmd) = sc.get_pid_info(pid)
                                    lines.append("%s PID %s CWD %s\n" %
                                                 (cwin, pid, cwd))
                                    lines.append("%s PID %s EXE %s\n" %
                                                 (cwin, pid, exe))
                                    cmd = cmd.split('\0')
                                    pcmd = cmd[0]

                                    if cmd[1] != '':
                                        pcmd += " " + " ".join(
                                            ["\"%s\"" % v for v in cmd[1:-1]])

                                    lines.append("%s PID %s CMD %s\n" %
                                                 (cwin, pid, pcmd))

                                    if cmd[0].endswith('screen-session-primer'
                                                       ) and cmd[1] == '-p':
                                        sum_primer += 1
                                        lines[
                                            0] = lines[0][:-1] + " / primer\n"
                                    elif cmd[0] in ('vi', 'vim', 'viless',
                                                    'vimdiff'):
                                        sum_vim += 1
                                        lines[0] = lines[0][:-1] + " / VIM\n"
                                except OSError, x:
                                    lines.append(
                                        "%s PID %s Unable to access pid data ( %s )\n"
                                        % (cwin, pid, str(x)))
                        except Exception, x:
                            lines.append(
                                "%s Unable to access PIDs associated with tty ( %s )\n"
                                % (cwin, str(x)))
                try:
                    map(stdout.write, lines)
                except:
                    break

        print 'WINDOWS: %d\t[ %d basic | %d group | %d zombie | %d telnet ]' % \
            (sum_win, sum_basic, sum_group, sum_zombie, sum_telnet)
        print 'PROCESS: %d\t[ %d primer | %d vim ]' % (sum_process_total,
                                                       sum_primer, sum_vim)
예제 #40
0
import GNUScreen as sc


def out(str, active=False):
    if active:
        sys.stdout.write(str + "\n")


bPrint = False


session = "%s" % sys.argv[1]
out("session = " + session, bPrint)
session_arg = "-S %s" % session

cwin = sc.get_current_window(session)
windows_old = sc.parse_windows(sc.get_windows(session))[0]
out(str(windows_old), bPrint)

f = os.popen("screen %s -Q @tty" % session_arg)
ctty = f.readline()
f.close()
out(ctty, bPrint)
pids = sc.get_tty_pids(ctty)
# pids=sc.sort_by_ppid(pids)
thepid = pids[len(pids) - 1]
thedir = sc.get_pid_info(thepid)[0]

out(thedir, bPrint)

os.chdir(thedir)
예제 #41
0
        layhist = get_layout_history(session, layout)

        try:
            if targ > 0:
                ld = layhist.redo[targ-1][1]
            elif targ < 0:
                ld = layhist.undo[abs(targ)-1][1]
            else:
                ld = layhist.current[0]
        except IndexError:
            ld = layhist.current[0]
            targ = 0

        cur = layhist.current[0]
        term_x, term_y = map(int, ss.dinfo()[0:2])
        lay_f = sc.layout_begin(session)
        lay_f.write('only\n')
        sc.layout_load_dump(open(os.path.join(ld, layout_dump), 'r'))
        sc.layout_load_regions(sc.get_regions(os.path.join(ld, layout_regions)),
                None, term_x, term_y)
        sc.layout_end()

        os.rename(ld, os.path.join(tdir, os.path.basename(ld)))
        if targ > 0:
            ss.Xecho('layout redo ( %d left )' % (len(layhist.redo) - 1))
            os.rename(cur, os.path.join(tdir_u,
                os.path.basename(cur)))
        elif targ < 0:
            ss.Xecho('layout undo ( %d left )' % (len(layhist.undo) - 1))
            os.rename(cur, os.path.join(tdir_r,
                os.path.basename(cur)))
예제 #42
0
        session = (sys.argv)[1]
    else:
        raise Exception
except:
    session = None
try:
    s = get_sessionname(session)
except:
    s = None
    s2 = None
    try:
        badname = os.getenv('STY').split('.', 1)[0]
        if not badname:
            session = None
            raise Exception
        sclist = sc.get_session_list()
        for (sc, active) in sclist:
            if sc.startswith(badname):
                s = sc
                if not sc.endswith('-queryA'):
                    break
                    None
    except:
        pass
if s:
    try:
        if session and s.find(session) > -1:
            newname = (sys.argv)[2]
            os.popen(SCREEN + ' -S \"%s\" -X sessionname \"%s\"' %
                     (s, newname)).close()
        else:
예제 #43
0
    def __save_screen(self):
        errors = []
        homewindow = self.homewindow
        group_wins = {}
        group_groups = {}
        excluded_wins = []
        excluded_groups = []
        scroll_wins = []
        scroll_groups = []
        cwin = -1
        ctty = None
        cppids = {}
        rollback = (None, None, None)
        ctime = self.time()
        findir = sc.datadir
        os.symlink(os.path.join(findir), os.path.join(self.basedir, self.savedir))

        #sc_cwd=self.command_at(True,'hardcopydir') # it only works interactively
        # should be modified to properly restore hardcopydir(:dumpscreen settings)

        self.command_at(False,
                        'eval \'hardcopydir \"%s\"\' \'at \"\#\" hardcopy -h\' \'hardcopydir \"%s\"\'' %
                        (findir, self.homedir))
        mru_w = [homewindow + '\n']
        for (
            cwin,
            cgroupid,
            cgroup,
            ctty,
            ctype,
            ctypestr,
            ctitle,
            cfilter,
            cscroll,
            badctime,
            cmdargs,
            ) in sc.gen_all_windows_full(self.pid, sc.datadir, False,
                    False):
            mru_w.append("%s\n" % cwin)

            cpids = None
            cpids_data = None

            if ctypestr[0] == 'g':
                pass
            elif ctypestr[0] == 'z':
                cpids = []
            else:
                # get sorted pids associated with the window

                try:
                    cpids = sc.get_tty_pids(ctty)
                    cpids_data = []
                    ncpids = []
                    for pid in cpids:
                        try:
                            pidinfo = sc.get_pid_info(pid)
                            (exehead, exetail) = os.path.split(pidinfo[1])
                            if exetail in self.blacklist:
                                blacklist = True
                            else:
                                blacklist = False
                            cpids_data.append(pidinfo + tuple([blacklist]))
                            ncpids.append(pid)
                        except Exception,x:
                            if cwin != homewindow:
                                errors.append('%s PID %s: Unable to access ( %s )' %
                                    (cwin, pid, str(x)))
                    cpids = ncpids
                except Exception,x:
                    errors.append('%s Unable to access %s ( %s )' %
                            (cwin, str(ctty), str(x)))
                    cpids=[]
예제 #44
0
def menu_table(
    ss,
    screen,
    tmplay,
    curwin,
    curlay,
    layinfo,
    laytable,
    pos_x,
    pos_y,
    height,
    ):
    global MAXTITLELEN
    global mru_file
    (y, x) = screen.getmaxyx()

    # default background colors

    try:
        curses.use_default_colors()
    except:
        pass

    ## custom background
    #curses.init_pair(1,curses.COLOR_WHITE, curses.COLOR_BLACK)
    #screen.bkgd(' ',curses.color_pair(1))

    # ?universal? color scheme

    curses.init_pair(2, -1, curses.COLOR_YELLOW)
    curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLUE)
    curses.init_pair(4, -1, curses.COLOR_GREEN)
    curses.init_pair(5, -1, -1)
    curses.init_pair(6, curses.COLOR_RED, -1)
    curses.init_pair(7, curses.COLOR_RED, curses.COLOR_YELLOW)
    curses.init_pair(8, curses.COLOR_RED, curses.COLOR_BLUE)
    curses.init_pair(9, curses.COLOR_RED, curses.COLOR_GREEN)

    c_h = curses.color_pair(2) | curses.A_BOLD
    c_n = curses.A_NORMAL
    c_curlay_n = curses.color_pair(3) | curses.A_BOLD
    c_find = curses.color_pair(4)
    c_error = curses.color_pair(5) | curses.A_BOLD
    c_project = curses.color_pair(6) | curses.A_BOLD
    c_h_project = curses.color_pair(7)
    c_curlay_project = curses.color_pair(8) | curses.A_BOLD
    c_find_project = curses.color_pair(9)
    screen.keypad(1)
    x = None
    other_num = last_sel_num = sel_num_before_search = sel_num = curlay
    row_len = None
    col_len = None
    search_num = None
    search_title = ""
    n_search_title = ""
    searching_num = False
    searching_title = False
    b_force_sel_num = False
    status_len = 0
    errormsg = ""
    findNext = 0
    current_view = 'n'
    try:
        mru_layouts = pickle.load(open(mru_file, 'r'))
    except:
        mru_layouts = []
    view_layouts = []
    pos_x_c = pos_y_c = layinfo_c = laytable_c = None

    def mru_add(layout_num):
        layout_title = ""
        index = None
        for (i, lay) in enumerate(mru_layouts):
            (num, title) = lay
            if num == layout_num:
                index = i
                break
        if index != None:
            mru_layouts.pop(index)
        for lay in layinfo:
            try:
                num = lay[0]
                title = lay[1]
            except:
                title = ""
            if num == layout_num:
                layout_title = title
                break
        mru_layouts.insert(0, (layout_num, layout_title))
        pickle.dump(mru_layouts, open(mru_file, 'w'))

    mru_add(curlay)
    while True:
        view_layouts = []
        keyboard_int = False
        if findNext and n_search_title:
            layinfo_pos = 0
            for (k, e) in enumerate(layinfo):
                if e[0] == sel_num:
                    layinfo_pos = k
            layinfo_tmp = layinfo[layinfo_pos + 1:] + layinfo[:layinfo_pos]
            if findNext == -1:
                layinfo_tmp.reverse()
            for (i, entry) in enumerate(layinfo_tmp):
                try:
                    num = entry[0]
                    title = entry[1]
                except:
                    title = ""
                try:
                    tfi = title.lower().strip().index(n_search_title.lower())
                    sel_num = num
                    break
                except:
                    continue
        elif searching_num:
            bfound = False
            if not search_num:
                sn = sel_num_before_search
                searching_num = False
            else:
                sn = search_num
            for (i, row) in enumerate(laytable):
                for (j, cell) in enumerate(row):
                    (num, title) = cell
                    if sn:
                        if sn == num:
                            pos_x = j
                            pos_y = i
                            bfound = True
                            break
                    if bfound:
                        break

        project_title = None
        bfound = False
        for (i, row) in enumerate(laytable):
            for (j, cell) in enumerate(row):
                (num, title) = cell
                if sel_num == last_sel_num and j == pos_x and i == pos_y and \
                    not b_force_sel_num:
                    sel_num = num
                    last_sel_num = sel_num
                    row_len = len(row) - 1
                    project_title = title.lower()
                    bfound = True
                    break
                elif (b_force_sel_num or not sel_num == last_sel_num) and \
                    sel_num == num:
                    b_force_sel_num = False
                    pos_x = j
                    pos_y = i
                    last_sel_num = sel_num
                    row_len = len(row) - 1
                    project_title = title.lower()
                    bfound = True
                    break
            if bfound:
                break
        if sel_num != curlay:
            other_num = sel_num
        bSearchResults = False
        for (i, row) in enumerate(laytable):
            for (j, cell) in enumerate(row):
                (num, title) = cell
                bsel = False
                c_f = c_find
                if sel_num == num:
                    color = c_h
                    c_p = c_h_project
                    bsel = True
                elif num == curlay:
                    color = c_curlay_n
                    c_p = c_curlay_project
                else:
                    color = c_n
                    c_p = c_project
                try:
                    screen.addstr(i, j * (MAXTITLELEN + 5), " %-4s%s" %
                                  (num, title), color)
                    tl = title.lower()
                    if AUTOSEARCH_MIN_MATCH > 0:
                        pi = 0

                        for (k, l) in enumerate(tl):
                            try:
                                if l == project_title[k]:
                                    pi += 1
                                else:
                                    break
                            except:
                                break
                        if pi >= AUTOSEARCH_MIN_MATCH:
                            if bsel:
                                screen.addstr(i, j*(MAXTITLELEN+5), " %-4s"%(num), c_p)
                            else:
                                screen.addstr(i, j*(MAXTITLELEN+5)+5, "%s"%(title[0:pi]), c_p)
                            if not bsel:
                                c_f = c_find_project

                    if findNext:
                        s = n_search_title
                    else:
                        s = search_title
                    tfi = tl.strip().index(s.lower())
                    if not bSearchResults:
                        bSearchResults = True
                        view_layouts = []
                    screen.addstr(i, j * (MAXTITLELEN + 5) + 5 + tfi,
                                  "%s" % title[tfi:tfi + len(s)], c_f)
                except:
                    pass

        if findNext:
            findNext = 0
        if not searching_num:
            search_num = None
        if not searching_title:
            search_title = None
        try:
            screen.addstr(y - 1, 0, "> %-*s" % (status_len, ""), c_n)
            if searching_title or searching_num:
                if searching_title:
                    prompt = '> Search: '
                else:
                    prompt = '> Number: '
                if search_title:
                    search = search_title
                elif search_num:
                    search = search_num
                else:
                    search = ""
                s = "%s%s" % (prompt, search)
                status_len = len(s)
                screen.addstr(y - 1, 0, s, curses.A_BOLD)
            else:
                if errormsg:
                    s = "%s" % errormsg
                    screen.addstr(y - 1, 2, s, c_error | curses.A_BOLD)
                else:
                    s = 'Press \'?\' to view help'
                    screen.addstr(y - 1, 2, s, c_n)
                status_len = len(s)
                errormsg = ""
        except:
            pass

        screen.refresh()
        x = screen.getch()

        # layout list refresh ^C ^L ^R

        if x in (-1, 12, 18) or x in (ord('r'), ord('R')) and not searching_title and \
            not searching_num:
            if laytable_c:
                current_view = 'n'
                pos_x = pos_x_c
                pos_y = pos_y_c
                pos_x_c = pos_y_c = layinfo_c = laytable_c = None
            (y, x) = screen.getmaxyx()
            searching_title = False
            searching_num = False
            try:
                try:
                    try:
                        if NO_END:
                            f = open(lock_and_com_file, 'r')
                            from string import strip as str_strip

                            #pid,cwin,clay,MAXTITLELEN,height = map( str_strip,f.readlines() )

                            nd = map(str_strip, f.readlines())
                            curwin = nd[3]
                            sel_num = curlay = nd[4]
                            MAXTITLELEN = int(nd[5])
                            height = int(nd[6])
                            f.close()
                            screen.erase()
                            mru_add(curlay)
                    except:
                        pass
                    layinfo = list(sc.gen_layout_info(ss, sc.dumpscreen_layout_info(ss)))
                    (laytable, pos_start) = create_table(ss, screen,
                            curlay, layinfo, tmplay, height)
                    errormsg = 'Refreshed'
                finally:
                    sc.cleanup()
            except:
                errormsg = 'Layouts dumping error.'
        elif searching_title and x == ord('\n'):
            searching_title = False
            n_search_title = search_title
            findNext = True
        elif x == 27:

                      # Escape key

            searching_num = False
            searching_title = False
            search_num = None
            search_title = None
            errormsg = 'Canceled'
            n_search_title = search_title
        elif x == curses.KEY_BACKSPACE:
            try:
                if len(search_num) == 0:
                    raise Exception
                search_num = search_num[:-1]
            except:
                searching_num = False
                pass
            try:
                if len(search_title) == 0:
                    raise Exception
                search_title = search_title[:-1]
            except:
                searching_title = False
                pass
        elif searching_title:
            if x == curses.KEY_UP:
                search_title = n_search_title
            elif x == curses.KEY_DOWN:
                search_title = ""
            else:
                try:
                    search_title += chr(x)
                except:
                    pass
        elif x in (ord('/'), ord(' ')):
            searching_title = True
            searching_num = False
            search_title = ""
        elif x == ord('\n'):
            if layinfo_c:
                current_view = 'n'
                layinfo = list(layinfo_c)
                laytable = list(laytable_c)
                pos_x = pos_x_c
                pos_y = pos_y_c
                pos_x_c = pos_y_c = layinfo_c = laytable_c = None
            searching_num = False
            if not sel_num:
                curses.flash()
                errormsg = "No layout selected."
            elif sel_num == tmplay:
                curses.flash()
                errormsg = "This IS layout %s." % sel_num
            else:
                if NO_END:
                    mru_add(sel_num)
                    if curwin != '-1':
                        ss.command_at(False,
                                'eval "select %s" "layout select %s" "layout title"' %
                                (curwin, sel_num))
                    else:
                        ss.command_at(False,
                                'eval "layout select %s" "layout title"' %
                                sel_num)
                else:
                    return sel_num
        elif x in (ord('q'), ord('Q')):
            if NO_END and x == ord('q'):
                if layinfo_c:
                    current_view = 'n'
                    layinfo = list(layinfo_c)
                    laytable = list(laytable_c)
                    pos_x = pos_x_c
                    pos_y = pos_y_c
                    pos_x_c = pos_y_c = layinfo_c = laytable_c = None
                mru_add(sel_num)
                ss.command_at(False,
                              'eval "layout select %s" "layout title"' %
                              curlay)
            else:
                return curlay
        elif x in (ord('n'), ord('P')):
            findNext = 1
        elif x in (ord('p'), ord('N')):
            findNext = -1
        elif x in (curses.KEY_HOME, ord('^')):
            pos_x = 0
        elif x in (curses.KEY_END, ord('$')):
            pos_x = len(laytable[pos_y]) - 1
        elif x == curses.KEY_PPAGE:
            pos_y = pos_y - 5 > 0 and pos_y - 5 or 0
        elif x == ord('?'):
            from help import help_layoutlist
            screen.erase()
            for (i, line) in enumerate(help_layoutlist.split('\n')):
                try:
                    screen.addstr(i, 0, " %s" % line, c_n)
                except:
                    pass
            screen.refresh()
            x = screen.getch()
            screen.erase()
        elif x == ord('o'):
            if sel_num != curlay:
                other_num = sel_num
                sel_num = curlay
            else:
                sel_num = other_num
            b_force_sel_num = True
        elif x in (ord('m'), ord('a')):
            screen.erase()
            if not layinfo_c:
                current_view = 'm'
                layinfo_c = list(layinfo)
                laytable_c = list(laytable)
                layinfo = mru_layouts
                pos_x_c = pos_x
                pos_y_c = pos_y
                pos_x = pos_y = 0
                (laytable, pos_start) = create_table_std(ss, screen,
                        curlay, layinfo, tmplay)
                if len(laytable) > 1:
                    pos_y = 1
            else:
                current_view = 'n'
                b_force_sel_num = True
                layinfo = list(layinfo_c)
                laytable = list(laytable_c)
                pos_x = pos_x_c
                pos_y = pos_y_c
                pos_x_c = pos_y_c = layinfo_c = laytable_c = None
        elif x == ord('v'):
            screen.erase()
            if not layinfo_c:
                current_view = 'v'
                layinfo_c = list(layinfo)
                laytable_c = list(laytable)
                pos_x_c = pos_x
                pos_y_c = pos_y
                pos_x = pos_y = 0
                nst = n_search_title.lower()
                for lay in layinfo:
                    try:
                        num = lay[0]
                        title = lay[1]
                    except:
                        title = ""
                    tl = title.lower().strip()
                    if bSearchResults:
                        try:
                            tfi = tl.index(nst)
                            view_layouts.append((num, title))
                        except:
                            pass
                    else:
                        pi = 0
                        for (k, l) in enumerate(tl):
                            try:
                                if l == project_title[k]:
                                    pi += 1
                                else:
                                    break
                            except:
                                break
                        if pi >= AUTOSEARCH_MIN_MATCH:
                            view_layouts.append((num, title))

                (laytable, pos_start) = create_table_std(ss, screen,
                        sel_num, view_layouts, tmplay)
                (pos_x, pos_y) = pos_start
                layinfo = view_layouts
            else:
                current_view = 'n'
                b_force_sel_num = True
                layinfo = list(layinfo_c)
                laytable = list(laytable_c)
                pos_x = pos_x_c
                pos_y = pos_y_c
                pos_x_c = pos_y_c = layinfo_c = laytable_c = None
        elif x in range(ord('0'), ord('9') + 1):
            if not searching_num:
                searching_num = True
                sel_num_before_search = sel_num
            if not search_num:
                search_num = chr(x)
            else:
                try:
                    search_num += chr(x)
                except:
                    pass
        else:
            searching_num = False
            for (i, row) in enumerate(laytable):
                try:
                    a = row[pos_x]
                    col_len = i
                except:
                    break

            #sys.stderr.write("KEY(%d) POS(%d,%d) RLEN(%d) CLEN(%d)\n"%(x,pos_x,pos_y,row_len,col_len))

            if x == curses.KEY_NPAGE:
                pos_y = pos_y + 5 < col_len and pos_y + 5 or col_len
            elif x in (ord('j'), curses.KEY_DOWN):
                if pos_y < col_len:
                    pos_y += 1
                else:
                    pos_y = 0
            elif x in (ord('k'), curses.KEY_UP):
                if pos_y > 0:
                    pos_y += -1
                else:
                    pos_y = col_len
            elif x in (ord('h'), curses.KEY_LEFT):
                if pos_x > 0:
                    pos_x += -1
                else:
                    pos_x = row_len
            elif x in (ord('l'), curses.KEY_RIGHT):
                if pos_x < row_len:
                    pos_x += 1
                else:
                    pos_x = 0
            else:
                try:
                    c = chr(x)
                except:
                    c = 'UNKNOWN'
                errormsg = 'Unsupported keycode: %d \"%s\"' % (x, c)
                curses.flash()
예제 #45
0
def run(session, requirecleanup_win, requirecleanup_lay, curwin, curlay,
        height, select_other = False):
    global lock_and_com_file, mru_file
    lltmpdir = os.path.join(tmpdir, '___layoutlist')
    try:
        os.makedirs(lltmpdir)
    except:
        pass

    signal.signal(signal.SIGINT, handler)
    session = session.split('.', 1)[0]

    ret = 0
    ss = ScreenSaver(session)
    wnum = os.getenv('WINDOW')
    if requirecleanup_lay:
        lnum = ss.get_layout_number()[0]
    else:
        lnum = None

    mru_file = os.path.join(lltmpdir, '%s_MRU' % session)
    if select_other:
        mru_layouts = pickle.load(open(mru_file, 'r'))
        num, title = mru_layouts[1]
        tmp = mru_layouts[0]
        mru_layouts[0] = mru_layouts[1]
        mru_layouts[1] = tmp
        ss.command_at(False, 'eval "layout select %s" "layout title"' %
                      num)
        pickle.dump(mru_layouts, open(mru_file, 'w'))
        return ret
    if NO_END:
        lock_and_com_file = os.path.join(lltmpdir, '%s' %
                session)
        f = open(lock_and_com_file, 'w')
        f.write(str(os.getpid()) + '\n')
        if requirecleanup_win and not requirecleanup_lay:
            f.write(wnum + '\n')
        else:
            f.write('-1\n')
        if requirecleanup_lay:
            f.write(lnum + '\n')
        else:
            f.write('-1\n')
        f.close()

    try:
        try:
            layinfo = list(sc.gen_layout_info(ss, sc.dumpscreen_layout_info(ss)))
        finally:
            sc.cleanup()
    except:
        sys.stderr.write('Layouts dumping error.\n')
        return 1
    screen = curses.initscr()
    (laytable, pos_start) = create_table(ss, screen, curlay, layinfo,
            lnum, height)
    try:
        curses.start_color()
    except:
        curses.endwin()
        sys.stderr.write('start_color() failed!\n')
        return 1

    curses.noecho()

    #screen.notimeout(1)

    try:
        choice = menu_table(
            ss,
            screen,
            lnum,
            curwin,
            curlay,
            layinfo,
            laytable,
            pos_start[0],
            pos_start[1],
            height,
            )
        if requirecleanup_lay and choice == lnum:
            choice = curlay
    except Exception:
        import traceback
        traceback.print_exc(file=sys.stderr)
        choice = curlay
        ret = 1
    curses.endwin()
    if NO_END:
        from util import remove
        remove(lock_and_com_file)
    if requirecleanup_lay:
        ss.command_at(False,
                      'eval "layout select %s" "layout remove %s" "at \"%s\#\" kill" "layout title"' %
                      (choice, lnum, wnum))
    elif requirecleanup_win:
        ss.command_at(False,
                      'eval "select %s" "layout select %s" "at \"%s\#\" kill" "layout title"' %
                      (curwin, choice, wnum))
    else:
        ss.command_at(False, 'eval "layout select %s" "layout title"' %
                      choice)
    return ret
예제 #46
0
    def __load_layouts(self):
        cdinfo = map(int, self.dinfo()[0:2])
        out('Terminal size: %s %s' % (cdinfo[0], cdinfo[1]))
        homewindow = self.homewindow
        (homelayout, homelayoutname) = self.get_layout_number()
        layout_trans = {}
        layout_c = len(glob.glob(os.path.join(self.basedir, self.savedir,
                       'winlayout_*')))
        if layout_c > 0:
            self.__layouts_loaded = True
        lc = 0
        layout_file = sc.layout_begin(self.pid)
        while lc < layout_c:
            filename = None
            try:
                filename = glob.glob(os.path.join(self.basedir, self.savedir,
                        'layout_%d' % lc))[0]
                layoutnumber = filename.rsplit("_", 1)[1]
                (head, tail) = os.path.split(filename)

                # the winlayout_NUM files contain "dumpscreen layout" output 
                # (see GNUScreen.Regions class)

                filename2 = os.path.join(head, "win" + tail)
                regions = sc.get_regions(filename2)
                status = self.get_layout_new(regions.title)
                if not status:
                    sys.stderr.write('\nMaximum number of layouts reached. Ignoring layout %s (%s).\n' %
                        (layoutnumber, regions.title))
                    break
                else:
                    if self.exact:
                        self.layout('number %s' % layoutnumber, False)
                        currentlayout = layoutnumber
                    else:
                        currentlayout = self.get_layout_number()[0]
                    layout_trans[layoutnumber] = currentlayout

                    sc.layout_select_layout(currentlayout)
                    # source the output produced by "layout dump"
                    sc.layout_load_dump(open(filename,'r'))

                    regions_size = []
                    winlist = []

                    for (window, sizex, sizey) in regions.regions:
                        winlist.append(window)
                        regions_size.append((sizex, sizey))
                    sc.layout_load_regions(regions, self.__wins_trans, cdinfo[0], cdinfo[1])
                    # sys.stdout.write(" %s (%s);" % (layoutnumber, regions.title))
            except:
                # import traceback
                # traceback.print_exc(file=sys.stderr)
                # raise
                layout_c += 1
                if layout_c > 2000:
                    sys.stderr.write('\nErrors during layouts loading.\n')
                    break
            lc += 1
        out('')
        if not lc == 0:

            # select last layout

            lastname = None
            lastid_l = None

            if homelayout != -1:
                out("Returning homelayout %s" % homelayout)
                layout_file.write('layout select %s' % homelayout)
            else:
                sys.stderr.write('No homelayout - unable to return.\n')

            if os.path.exists(os.path.join(self.basedir, self.savedir,
                              "last_layout")) and len(layout_trans) > 0:
                last = os.readlink(os.path.join(self.basedir, self.savedir,
                                   "last_layout"))
                (lasthead, lasttail) = os.path.split(last)
                last = lasttail.split("_", 2)
                lastid_l = last[1]
                try:
                    out("Selecting last layout: %s (%s)" % (layout_trans[lastid_l], lastid_l))
                    layout_file.write('layout select %s' % layout_trans[lastid_l])
                    # ^^ layout numbering may change, use layout_trans={}
                except:
                    sys.stderr.write("Unable to select last layout %s\n" % lastid_l)
        else:
            self.enable_layout = False
        sc.layout_end()
예제 #47
0
except:
    ppid = -1
session = (sys.argv)[2]
sourcenumber = (sys.argv)[3]
number = (sys.argv)[4]
bRenumber = (sys.argv)[6] == '1' and True or False
tdir = (sys.argv)[6]
tgroup = (sys.argv)[7]
altdir = (sys.argv)[8]
altdir_pos = (sys.argv)[9]
title = (sys.argv)[10]

session_arg = '-S "%s"' % session

if bRenumber:
    cwin = sc.get_current_window(session)

if tdir.startswith('/') or tdir.startswith('~'):
    thedir = os.path.expanduser(tdir)
else:
    if sourcenumber == "-1":
        f = os.popen(SCREEN + ' %s -Q @tty' % session_arg)
    else:
        f = os.popen(SCREEN + ' %s -p %s -Q @tty' %
                     (session_arg, sourcenumber))
    ctty = f.readline()
    f.close()
    if ctty.startswith('/dev'):
        if platform.system() == 'FreeBSD':
            pids = sc.get_tty_pids(ctty)
        else:
예제 #48
0
def cleanup():
    sc.cleanup()