Top

ped_ssh_dialog.ssh_dialog module

module that implements file open/new dialog for the ped editor

# Copyright 2009 James P Goodwin ped tiny python editor
""" module that implements file open/new dialog for the ped editor """
import curses
from ped_ssh_dialog import ssh_mod
from ped_ssh_dialog.ssh_mod import ssh_log_name
import curses.ascii
import sys
import re
import os
from ped_dialog import dialog
from ped_core import keytab
from io import StringIO
from ped_dialog.confirm_dialog import confirm
from ped_dialog.message_dialog import message
import traceback

def get_dir_ssh( path, ssh_username, ssh_password, showhidden=False ):
    """ get a directory listing of a ssh remote path, for a particular username and password """
    def get_config():
        return { "ssh_username":ssh_username, "ssh_password":ssh_password }

    dir_list = ssh_mod.ssh_ls(path,False,get_config,False)
    dirnames = []
    filenames = []
    for item in StringIO(dir_list):
        item = item.strip()
        if item.startswith("DIR"):
            parts = item[4:].split("/")
            dirnames.append(parts[-2])
            continue
        (date,time,size,path) = re.split("\s+",item,3)
        parts = path.split("/")
        filenames.append(parts[-1])
    if not showhidden:
        dirnames = [d for d in dirnames if d[0] != "."]
        filenames = [f for f in filenames if f[0] != "." and f[-1] != "~" and not f.endswith(".bak")]
    dirnames.sort()
    filenames.sort()
    dirnames = ["<DIR> .."] + ["<DIR> "+d for d in dirnames]
    return((path,dirnames,filenames))


def get_dir(path,showhidden=False):
    """ get a directory listing of path, directories are prefixed with <DIR>
        if showhidden == False hidden files are not include, otherwise they are
        returns the directory path, the list of directories and list of files as a tuple"""
    (dirpath, dirnames, filenames) = next(os.walk(path))
    if not showhidden:
        dirnames = [d for d in dirnames if d[0] != "."]
        filenames = [f for f in filenames if f[0] != "." and f[-1] != "~" and not f.endswith(".bak")]
    dirnames.sort()
    filenames.sort()
    dirnames = ["<DIR> .."] + ["<DIR> "+d for d in dirnames]
    return (dirpath, dirnames, filenames)

class SSHFileListBox(dialog.ListBox):
    """ list box subclass for file lists, handles searching past the <DIR> prefix for incremental searches"""
    def find(self,searchfor):
        """ subclass the find method to find the string either with the dir prefix or without it """
        if not dialog.ListBox.find(self,"<DIR> "+searchfor):
            return dialog.ListBox.find(self,searchfor)
        else:
            return True

class SSHFileDialog(dialog.Dialog):
    """ dialog subclass that implements an ssh browsing experience, allowing you to put or get files
    to and from an ssh server location """
    def __init__(self,scr,title = "SSH File Dialog", remote_path="", ssh_username="", ssh_password="", local_path="."):
        """ takes a curses window scr, title for the border, and a remote starting path and credentials and a local starting path """
        max_y, max_x = scr.getmaxyx()
        dw = max_x - 4
        dh = max_y - 4
        self.prior_ssh = None
        self.prior_local = None
        y = 2
        self.ssh_username = dialog.Prompt("ssh_username",1,2,y,"SSH Username: ",dw-18,ssh_username)
        y += 1
        self.ssh_password = dialog.PasswordPrompt("ssh_password",2,2,y,"SSH Password: ",dw-18,ssh_password)
        y += 1
        self.ssh_current_dir = dialog.Prompt("ssh_dir",3,2,y,"SSH Path: ",dw-18,remote_path)
        y += 1
        self.ssh_file_list = SSHFileListBox("ssh_files",4,2,y,dh//3,dw-4,"SSH Directory Listing",0,[])
        y += dh//3
        self.ssh_file_name = dialog.Prompt("ssh_file",5,2,y,"SSH File: ",dw-18)
        y += 1
        self.current_dir = dialog.Prompt("local_dir",6,2,y,"Local Path: ",dw-18,local_path)
        y += 1
        self.file_list = SSHFileListBox("local_files",7,2,y,dh//3,dw-4,"Local Directory Listing",0,[])
        y += dh//3
        self.file_name = dialog.Prompt("local_file",8,2,y,"Local File: ",dw-18)
        y += 1
        x = 2
        iw = dw//4
        self.put_button = dialog.Button("Put",9,x,y,"PUT",dialog.Component.CMP_KEY_NOP)
        x += iw
        self.get_button = dialog.Button("Get",10,x,y,"GET",dialog.Component.CMP_KEY_NOP)
        x += iw
        self.open_button = dialog.Button("Open",10,x,y,"OPEN",dialog.Component.CMP_KEY_OK)
        x += iw
        self.cancel_button = dialog.Button("Cancel",11,x,y,"CANCEL",dialog.Component.CMP_KEY_CANCEL)
        dialog.Dialog.__init__(self,scr,"FileDialog",dh,dw, [ dialog.Frame(title),
                                                                self.ssh_username,
                                                                self.ssh_password,
                                                                self.ssh_current_dir,
                                                                self.ssh_file_list,
                                                                self.ssh_file_name,
                                                                self.file_list,
                                                                self.current_dir,
                                                                self.file_name,
                                                                self.put_button,
                                                                self.get_button,
                                                                self.open_button,
                                                                self.cancel_button
                                                            ])
        self.refresh()

    def refresh(self,force=False):
        """ populate all of the fields if something changed """
        values = self.getvalue()
        ssh_path = ""
        ssh_dirnames = []
        ssh_filenames = []
        set_values={}
        if values["ssh_username"] and values["ssh_password"] and values["ssh_dir"]:
            new_ssh = values["ssh_username"] + values["ssh_password"] + values["ssh_dir"]
            if new_ssh != self.prior_ssh or force:
                self.prior_ssh = new_ssh
                try:
                    (ssh_path,ssh_dirnames,ssh_filenames) = get_dir_ssh( values["ssh_dir"], values["ssh_username"], values["ssh_password"], False)
                    self.prior_ssh = new_ssh
                    set_values["ssh_files"] = (0, ssh_dirnames+ssh_filenames)
                except:
                    print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                    confirm(self.win, "SSH Error! Try Again ?")
        local_path = ""
        local_dirnames = []
        local_filenames = []
        if values["local_dir"]:
            if self.prior_local != values["local_dir"] or force:
                try:
                    (local_path, local_dirnames,local_filenames) = get_dir(values["local_dir"],False)
                    os.chdir(local_path)
                    self.prior_local = values["local_dir"]
                    set_values["local_files"] = (0, local_dirnames+local_filenames)
                except:
                    print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                    confirm(self.win, "File Error! Try Again ?")
        self.setvalue(set_values)


    def handle(self,ch):
        """ key handler for selection from the file and directory list,
            browsing another directory selecting a file or entering one """
        focus_index = self.current
        focus_field = self.focus_list[self.current][1]
        ret_ch = dialog.Dialog.handle(self,ch)
        if ch in [keytab.KEYTAB_TAB, keytab.KEYTAB_BACKTAB]:
            self.refresh()
        elif ch in [keytab.KEYTAB_SPACE,keytab.KEYTAB_CR]:
            if focus_field == self.file_list:
                (selection, items) = focus_field.getvalue()
                choice = items[selection]
                if choice.startswith('<DIR>'):
                    self.current_dir.setvalue(os.path.abspath(os.path.join(self.current_dir.getvalue(),choice[6:])))
                    self.current = focus_index
                    ret_ch = dialog.Component.CMP_KEY_NOP
                else:
                    self.file_name.setvalue(choice)
                    self.ssh_file_name.setvalue(choice)
                self.refresh()
            elif focus_field == self.current_dir and ch == keytab.KEYTAB_CR:
                self.refresh()
            elif focus_field == self.ssh_file_list:
                (selection, items) = focus_field.getvalue()
                choice = items[selection]
                if choice.startswith('<DIR>'):
                    dir = choice[6:]
                    curpath = self.ssh_current_dir.getvalue()
                    if dir == "..":
                        curpath = "/".join(curpath.split("/")[:-1])
                    else:
                        curpath = curpath + "/" + dir
                    self.ssh_current_dir.setvalue(curpath)
                    self.current = focus_index
                    ret_ch = dialog.Component.CMP_KEY_NOP
                else:
                    self.file_name.setvalue(choice)
                    self.ssh_file_name.setvalue(choice)
                self.refresh()
            elif focus_field == self.ssh_current_dir and ch == keytab.KEYTAB_CR:
                self.refresh()
            elif focus_field == self.put_button:
                try:
                    if not self.file_name.getvalue() or not self.ssh_file_name.getvalue():
                        confirm(self.win, "Source or destination filename not set, retry ?")
                    else:
                        message(self.win, "Putting File", "Transfering %s"%(self.file_name.getvalue()),False)
                        ssh_mod.ssh_put(os.path.join(self.current_dir.getvalue(),self.file_name.getvalue()),
                        self.ssh_current_dir.getvalue()+"/"+self.ssh_file_name.getvalue(),
                        lambda : { 'ssh_username': self.ssh_username.getvalue(), "ssh_password":self.ssh_password.getvalue() }, False)
                        self.refresh(True)
                except:
                    print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                    confirm(self.win, "SSH Error! Try Again ?")
            elif focus_field == self.get_button:
                try:
                    if not self.file_name.getvalue() or not self.ssh_file_name.getvalue():
                        confirm(self.win, "Source or destination filename not set, retry ?")
                    else:
                        message(self.win, "Getting File", "Transfering %s"%(self.file_name.getvalue()),False)
                        ssh_mod.ssh_get(self.ssh_current_dir.getvalue()+"/"+self.ssh_file_name.getvalue(),
                        os.path.join(self.current_dir.getvalue(),self.file_name.getvalue()),
                        lambda : { 'ssh_username': self.ssh_username.getvalue(), "ssh_password":self.ssh_password.getvalue() })
                        self.refresh(True)
                except:
                    print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                    confirm(self.win, "SSH Error! Try Again ?")
            elif focus_field == self.open_button:
                try:
                    if not self.file_name.getvalue() or not self.ssh_file_name.getvalue():
                        confirm(self.win, "Source or destination filename not set, retry ?")
                    else:
                        message(self.win, "Opening File", "Transfering %s"%(self.file_name.getvalue()),False)
                        ssh_mod.ssh_get(self.ssh_current_dir.getvalue()+"/"+self.ssh_file_name.getvalue(),
                        os.path.join(self.current_dir.getvalue(),self.file_name.getvalue()),
                        lambda : { 'ssh_username': self.ssh_username.getvalue(), "ssh_password":self.ssh_password.getvalue() })
                        self.refresh(True)
                except:
                    print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                    confirm(self.win, "SSH Error! Try Again ?")



        return ret_ch

def sftpDialog( scr, title = "SFTP File Manager", remote_path="", ssh_username="", ssh_password="", local_path="."):
    d = SSHFileDialog( scr, title, remote_path=remote_path, ssh_username=ssh_username, ssh_password=ssh_password, local_path=local_path )
    values = d.main()
    if "local_file" in values:
        return (values["local_file"])
    else:
        return None

def main(stdscr):
    """ test main for the ssh file dialog """
    d = SSHFileDialog(stdscr)
    d.main()

if __name__ == '__main__':
    curses.wrapper(main)

Module variables

var ssh_log_name

Functions

def get_dir(

path, showhidden=False)

get a directory listing of path, directories are prefixed with

if showhidden == False hidden files are not include, otherwise they are returns the directory path, the list of directories and list of files as a tuple

def get_dir(path,showhidden=False):
    """ get a directory listing of path, directories are prefixed with <DIR>
        if showhidden == False hidden files are not include, otherwise they are
        returns the directory path, the list of directories and list of files as a tuple"""
    (dirpath, dirnames, filenames) = next(os.walk(path))
    if not showhidden:
        dirnames = [d for d in dirnames if d[0] != "."]
        filenames = [f for f in filenames if f[0] != "." and f[-1] != "~" and not f.endswith(".bak")]
    dirnames.sort()
    filenames.sort()
    dirnames = ["<DIR> .."] + ["<DIR> "+d for d in dirnames]
    return (dirpath, dirnames, filenames)

def get_dir_ssh(

path, ssh_username, ssh_password, showhidden=False)

get a directory listing of a ssh remote path, for a particular username and password

def get_dir_ssh( path, ssh_username, ssh_password, showhidden=False ):
    """ get a directory listing of a ssh remote path, for a particular username and password """
    def get_config():
        return { "ssh_username":ssh_username, "ssh_password":ssh_password }

    dir_list = ssh_mod.ssh_ls(path,False,get_config,False)
    dirnames = []
    filenames = []
    for item in StringIO(dir_list):
        item = item.strip()
        if item.startswith("DIR"):
            parts = item[4:].split("/")
            dirnames.append(parts[-2])
            continue
        (date,time,size,path) = re.split("\s+",item,3)
        parts = path.split("/")
        filenames.append(parts[-1])
    if not showhidden:
        dirnames = [d for d in dirnames if d[0] != "."]
        filenames = [f for f in filenames if f[0] != "." and f[-1] != "~" and not f.endswith(".bak")]
    dirnames.sort()
    filenames.sort()
    dirnames = ["<DIR> .."] + ["<DIR> "+d for d in dirnames]
    return((path,dirnames,filenames))

def main(

stdscr)

test main for the ssh file dialog

def main(stdscr):
    """ test main for the ssh file dialog """
    d = SSHFileDialog(stdscr)
    d.main()

def sftpDialog(

scr, title='SFTP File Manager', remote_path='', ssh_username='', ssh_password='', local_path='.')

def sftpDialog( scr, title = "SFTP File Manager", remote_path="", ssh_username="", ssh_password="", local_path="."):
    d = SSHFileDialog( scr, title, remote_path=remote_path, ssh_username=ssh_username, ssh_password=ssh_password, local_path=local_path )
    values = d.main()
    if "local_file" in values:
        return (values["local_file"])
    else:
        return None

Classes

class SSHFileDialog

dialog subclass that implements an ssh browsing experience, allowing you to put or get files to and from an ssh server location

class SSHFileDialog(dialog.Dialog):
    """ dialog subclass that implements an ssh browsing experience, allowing you to put or get files
    to and from an ssh server location """
    def __init__(self,scr,title = "SSH File Dialog", remote_path="", ssh_username="", ssh_password="", local_path="."):
        """ takes a curses window scr, title for the border, and a remote starting path and credentials and a local starting path """
        max_y, max_x = scr.getmaxyx()
        dw = max_x - 4
        dh = max_y - 4
        self.prior_ssh = None
        self.prior_local = None
        y = 2
        self.ssh_username = dialog.Prompt("ssh_username",1,2,y,"SSH Username: ",dw-18,ssh_username)
        y += 1
        self.ssh_password = dialog.PasswordPrompt("ssh_password",2,2,y,"SSH Password: ",dw-18,ssh_password)
        y += 1
        self.ssh_current_dir = dialog.Prompt("ssh_dir",3,2,y,"SSH Path: ",dw-18,remote_path)
        y += 1
        self.ssh_file_list = SSHFileListBox("ssh_files",4,2,y,dh//3,dw-4,"SSH Directory Listing",0,[])
        y += dh//3
        self.ssh_file_name = dialog.Prompt("ssh_file",5,2,y,"SSH File: ",dw-18)
        y += 1
        self.current_dir = dialog.Prompt("local_dir",6,2,y,"Local Path: ",dw-18,local_path)
        y += 1
        self.file_list = SSHFileListBox("local_files",7,2,y,dh//3,dw-4,"Local Directory Listing",0,[])
        y += dh//3
        self.file_name = dialog.Prompt("local_file",8,2,y,"Local File: ",dw-18)
        y += 1
        x = 2
        iw = dw//4
        self.put_button = dialog.Button("Put",9,x,y,"PUT",dialog.Component.CMP_KEY_NOP)
        x += iw
        self.get_button = dialog.Button("Get",10,x,y,"GET",dialog.Component.CMP_KEY_NOP)
        x += iw
        self.open_button = dialog.Button("Open",10,x,y,"OPEN",dialog.Component.CMP_KEY_OK)
        x += iw
        self.cancel_button = dialog.Button("Cancel",11,x,y,"CANCEL",dialog.Component.CMP_KEY_CANCEL)
        dialog.Dialog.__init__(self,scr,"FileDialog",dh,dw, [ dialog.Frame(title),
                                                                self.ssh_username,
                                                                self.ssh_password,
                                                                self.ssh_current_dir,
                                                                self.ssh_file_list,
                                                                self.ssh_file_name,
                                                                self.file_list,
                                                                self.current_dir,
                                                                self.file_name,
                                                                self.put_button,
                                                                self.get_button,
                                                                self.open_button,
                                                                self.cancel_button
                                                            ])
        self.refresh()

    def refresh(self,force=False):
        """ populate all of the fields if something changed """
        values = self.getvalue()
        ssh_path = ""
        ssh_dirnames = []
        ssh_filenames = []
        set_values={}
        if values["ssh_username"] and values["ssh_password"] and values["ssh_dir"]:
            new_ssh = values["ssh_username"] + values["ssh_password"] + values["ssh_dir"]
            if new_ssh != self.prior_ssh or force:
                self.prior_ssh = new_ssh
                try:
                    (ssh_path,ssh_dirnames,ssh_filenames) = get_dir_ssh( values["ssh_dir"], values["ssh_username"], values["ssh_password"], False)
                    self.prior_ssh = new_ssh
                    set_values["ssh_files"] = (0, ssh_dirnames+ssh_filenames)
                except:
                    print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                    confirm(self.win, "SSH Error! Try Again ?")
        local_path = ""
        local_dirnames = []
        local_filenames = []
        if values["local_dir"]:
            if self.prior_local != values["local_dir"] or force:
                try:
                    (local_path, local_dirnames,local_filenames) = get_dir(values["local_dir"],False)
                    os.chdir(local_path)
                    self.prior_local = values["local_dir"]
                    set_values["local_files"] = (0, local_dirnames+local_filenames)
                except:
                    print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                    confirm(self.win, "File Error! Try Again ?")
        self.setvalue(set_values)


    def handle(self,ch):
        """ key handler for selection from the file and directory list,
            browsing another directory selecting a file or entering one """
        focus_index = self.current
        focus_field = self.focus_list[self.current][1]
        ret_ch = dialog.Dialog.handle(self,ch)
        if ch in [keytab.KEYTAB_TAB, keytab.KEYTAB_BACKTAB]:
            self.refresh()
        elif ch in [keytab.KEYTAB_SPACE,keytab.KEYTAB_CR]:
            if focus_field == self.file_list:
                (selection, items) = focus_field.getvalue()
                choice = items[selection]
                if choice.startswith('<DIR>'):
                    self.current_dir.setvalue(os.path.abspath(os.path.join(self.current_dir.getvalue(),choice[6:])))
                    self.current = focus_index
                    ret_ch = dialog.Component.CMP_KEY_NOP
                else:
                    self.file_name.setvalue(choice)
                    self.ssh_file_name.setvalue(choice)
                self.refresh()
            elif focus_field == self.current_dir and ch == keytab.KEYTAB_CR:
                self.refresh()
            elif focus_field == self.ssh_file_list:
                (selection, items) = focus_field.getvalue()
                choice = items[selection]
                if choice.startswith('<DIR>'):
                    dir = choice[6:]
                    curpath = self.ssh_current_dir.getvalue()
                    if dir == "..":
                        curpath = "/".join(curpath.split("/")[:-1])
                    else:
                        curpath = curpath + "/" + dir
                    self.ssh_current_dir.setvalue(curpath)
                    self.current = focus_index
                    ret_ch = dialog.Component.CMP_KEY_NOP
                else:
                    self.file_name.setvalue(choice)
                    self.ssh_file_name.setvalue(choice)
                self.refresh()
            elif focus_field == self.ssh_current_dir and ch == keytab.KEYTAB_CR:
                self.refresh()
            elif focus_field == self.put_button:
                try:
                    if not self.file_name.getvalue() or not self.ssh_file_name.getvalue():
                        confirm(self.win, "Source or destination filename not set, retry ?")
                    else:
                        message(self.win, "Putting File", "Transfering %s"%(self.file_name.getvalue()),False)
                        ssh_mod.ssh_put(os.path.join(self.current_dir.getvalue(),self.file_name.getvalue()),
                        self.ssh_current_dir.getvalue()+"/"+self.ssh_file_name.getvalue(),
                        lambda : { 'ssh_username': self.ssh_username.getvalue(), "ssh_password":self.ssh_password.getvalue() }, False)
                        self.refresh(True)
                except:
                    print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                    confirm(self.win, "SSH Error! Try Again ?")
            elif focus_field == self.get_button:
                try:
                    if not self.file_name.getvalue() or not self.ssh_file_name.getvalue():
                        confirm(self.win, "Source or destination filename not set, retry ?")
                    else:
                        message(self.win, "Getting File", "Transfering %s"%(self.file_name.getvalue()),False)
                        ssh_mod.ssh_get(self.ssh_current_dir.getvalue()+"/"+self.ssh_file_name.getvalue(),
                        os.path.join(self.current_dir.getvalue(),self.file_name.getvalue()),
                        lambda : { 'ssh_username': self.ssh_username.getvalue(), "ssh_password":self.ssh_password.getvalue() })
                        self.refresh(True)
                except:
                    print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                    confirm(self.win, "SSH Error! Try Again ?")
            elif focus_field == self.open_button:
                try:
                    if not self.file_name.getvalue() or not self.ssh_file_name.getvalue():
                        confirm(self.win, "Source or destination filename not set, retry ?")
                    else:
                        message(self.win, "Opening File", "Transfering %s"%(self.file_name.getvalue()),False)
                        ssh_mod.ssh_get(self.ssh_current_dir.getvalue()+"/"+self.ssh_file_name.getvalue(),
                        os.path.join(self.current_dir.getvalue(),self.file_name.getvalue()),
                        lambda : { 'ssh_username': self.ssh_username.getvalue(), "ssh_password":self.ssh_password.getvalue() })
                        self.refresh(True)
                except:
                    print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                    confirm(self.win, "SSH Error! Try Again ?")



        return ret_ch

Ancestors (in MRO)

  • SSHFileDialog
  • ped_dialog.dialog.Dialog
  • ped_dialog.dialog.Component
  • builtins.object

Class variables

var CMP_KEY_CANCEL

var CMP_KEY_NOP

var CMP_KEY_OK

var history

Static methods

def __init__(

self, scr, title='SSH File Dialog', remote_path='', ssh_username='', ssh_password='', local_path='.')

takes a curses window scr, title for the border, and a remote starting path and credentials and a local starting path

def __init__(self,scr,title = "SSH File Dialog", remote_path="", ssh_username="", ssh_password="", local_path="."):
    """ takes a curses window scr, title for the border, and a remote starting path and credentials and a local starting path """
    max_y, max_x = scr.getmaxyx()
    dw = max_x - 4
    dh = max_y - 4
    self.prior_ssh = None
    self.prior_local = None
    y = 2
    self.ssh_username = dialog.Prompt("ssh_username",1,2,y,"SSH Username: ",dw-18,ssh_username)
    y += 1
    self.ssh_password = dialog.PasswordPrompt("ssh_password",2,2,y,"SSH Password: ",dw-18,ssh_password)
    y += 1
    self.ssh_current_dir = dialog.Prompt("ssh_dir",3,2,y,"SSH Path: ",dw-18,remote_path)
    y += 1
    self.ssh_file_list = SSHFileListBox("ssh_files",4,2,y,dh//3,dw-4,"SSH Directory Listing",0,[])
    y += dh//3
    self.ssh_file_name = dialog.Prompt("ssh_file",5,2,y,"SSH File: ",dw-18)
    y += 1
    self.current_dir = dialog.Prompt("local_dir",6,2,y,"Local Path: ",dw-18,local_path)
    y += 1
    self.file_list = SSHFileListBox("local_files",7,2,y,dh//3,dw-4,"Local Directory Listing",0,[])
    y += dh//3
    self.file_name = dialog.Prompt("local_file",8,2,y,"Local File: ",dw-18)
    y += 1
    x = 2
    iw = dw//4
    self.put_button = dialog.Button("Put",9,x,y,"PUT",dialog.Component.CMP_KEY_NOP)
    x += iw
    self.get_button = dialog.Button("Get",10,x,y,"GET",dialog.Component.CMP_KEY_NOP)
    x += iw
    self.open_button = dialog.Button("Open",10,x,y,"OPEN",dialog.Component.CMP_KEY_OK)
    x += iw
    self.cancel_button = dialog.Button("Cancel",11,x,y,"CANCEL",dialog.Component.CMP_KEY_CANCEL)
    dialog.Dialog.__init__(self,scr,"FileDialog",dh,dw, [ dialog.Frame(title),
                                                            self.ssh_username,
                                                            self.ssh_password,
                                                            self.ssh_current_dir,
                                                            self.ssh_file_list,
                                                            self.ssh_file_name,
                                                            self.file_list,
                                                            self.current_dir,
                                                            self.file_name,
                                                            self.put_button,
                                                            self.get_button,
                                                            self.open_button,
                                                            self.cancel_button
                                                        ])
    self.refresh()

def btab(

self)

def btab(self):
    if self.focus_list:
        self.push_history(self.focus_list[self.current][1])
        self.current -= 1
        if self.current < 0:
            self.current = len(self.focus_list)-1

def focus(

self)

called when component is the focus

def focus(self):
    self.focus_list = []
    for c in self.children:
        self.pop_history(c)
        if c.getorder() > 0:
            self.focus_list.append((c.getorder(),c))
    if not self.focus_list:
        self.current = 0
        return
    self.focus_list.sort(key=lambda x: x[0])
    self.current = 0

def getname(

self)

get the name of this component

def getname(self):
    """ get the name of this component """
    return self.name

def getorder(

self)

get this component's tab order number

def getorder(self):
    """ get this component's tab order number """
    return self.order

def getparent(

self)

get this component's curses target window

def getparent(self):
    """ get this component's curses target window """
    return self.parent

def getvalue(

self)

return the current value of the component

def getvalue(self):
    value = {}
    for c in self.children:
        if c.getname():
            value[c.getname()] = c.getvalue()
    return value

def goto(

self, component)

move focus to this component

def goto(self, component):
    """ move focus to this component """
    for i in range(0,len(self.focus_list)):
        if self.focus_list[i][1] == component:
            self.current = i
            return True
    return False

def handle(

self, ch)

key handler for selection from the file and directory list, browsing another directory selecting a file or entering one

def handle(self,ch):
    """ key handler for selection from the file and directory list,
        browsing another directory selecting a file or entering one """
    focus_index = self.current
    focus_field = self.focus_list[self.current][1]
    ret_ch = dialog.Dialog.handle(self,ch)
    if ch in [keytab.KEYTAB_TAB, keytab.KEYTAB_BACKTAB]:
        self.refresh()
    elif ch in [keytab.KEYTAB_SPACE,keytab.KEYTAB_CR]:
        if focus_field == self.file_list:
            (selection, items) = focus_field.getvalue()
            choice = items[selection]
            if choice.startswith('<DIR>'):
                self.current_dir.setvalue(os.path.abspath(os.path.join(self.current_dir.getvalue(),choice[6:])))
                self.current = focus_index
                ret_ch = dialog.Component.CMP_KEY_NOP
            else:
                self.file_name.setvalue(choice)
                self.ssh_file_name.setvalue(choice)
            self.refresh()
        elif focus_field == self.current_dir and ch == keytab.KEYTAB_CR:
            self.refresh()
        elif focus_field == self.ssh_file_list:
            (selection, items) = focus_field.getvalue()
            choice = items[selection]
            if choice.startswith('<DIR>'):
                dir = choice[6:]
                curpath = self.ssh_current_dir.getvalue()
                if dir == "..":
                    curpath = "/".join(curpath.split("/")[:-1])
                else:
                    curpath = curpath + "/" + dir
                self.ssh_current_dir.setvalue(curpath)
                self.current = focus_index
                ret_ch = dialog.Component.CMP_KEY_NOP
            else:
                self.file_name.setvalue(choice)
                self.ssh_file_name.setvalue(choice)
            self.refresh()
        elif focus_field == self.ssh_current_dir and ch == keytab.KEYTAB_CR:
            self.refresh()
        elif focus_field == self.put_button:
            try:
                if not self.file_name.getvalue() or not self.ssh_file_name.getvalue():
                    confirm(self.win, "Source or destination filename not set, retry ?")
                else:
                    message(self.win, "Putting File", "Transfering %s"%(self.file_name.getvalue()),False)
                    ssh_mod.ssh_put(os.path.join(self.current_dir.getvalue(),self.file_name.getvalue()),
                    self.ssh_current_dir.getvalue()+"/"+self.ssh_file_name.getvalue(),
                    lambda : { 'ssh_username': self.ssh_username.getvalue(), "ssh_password":self.ssh_password.getvalue() }, False)
                    self.refresh(True)
            except:
                print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                confirm(self.win, "SSH Error! Try Again ?")
        elif focus_field == self.get_button:
            try:
                if not self.file_name.getvalue() or not self.ssh_file_name.getvalue():
                    confirm(self.win, "Source or destination filename not set, retry ?")
                else:
                    message(self.win, "Getting File", "Transfering %s"%(self.file_name.getvalue()),False)
                    ssh_mod.ssh_get(self.ssh_current_dir.getvalue()+"/"+self.ssh_file_name.getvalue(),
                    os.path.join(self.current_dir.getvalue(),self.file_name.getvalue()),
                    lambda : { 'ssh_username': self.ssh_username.getvalue(), "ssh_password":self.ssh_password.getvalue() })
                    self.refresh(True)
            except:
                print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                confirm(self.win, "SSH Error! Try Again ?")
        elif focus_field == self.open_button:
            try:
                if not self.file_name.getvalue() or not self.ssh_file_name.getvalue():
                    confirm(self.win, "Source or destination filename not set, retry ?")
                else:
                    message(self.win, "Opening File", "Transfering %s"%(self.file_name.getvalue()),False)
                    ssh_mod.ssh_get(self.ssh_current_dir.getvalue()+"/"+self.ssh_file_name.getvalue(),
                    os.path.join(self.current_dir.getvalue(),self.file_name.getvalue()),
                    lambda : { 'ssh_username': self.ssh_username.getvalue(), "ssh_password":self.ssh_password.getvalue() })
                    self.refresh(True)
            except:
                print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                confirm(self.win, "SSH Error! Try Again ?")
    return ret_ch

def handle_mouse(

self)

def handle_mouse(self):
    if self.focus_list and self.win:
        try:
            mid, mx, my, mz, mtype = curses.getmouse()
            by,bx = self.win.getbegyx()
            oy = my - by
            ox = mx - bx
            for i in range(0,len(self.focus_list)):
                c = self.focus_list[i][1]
                ret = c.mouse_event(ox,oy,mtype)
                if ret >= 0:
                    self.current = i
                    return ret
            else:
                return -1
        except:
            return -1

def isempty(

self)

test if the component entry is empty

def isempty(self):
    """ test if the component entry is empty """
    return False

def main(

self, blocking=True, force=False, ch_in=None)

def main(self,blocking = True,force=False,ch_in = None):
    curses.mousemask( curses.BUTTON1_PRESSED| curses.BUTTON1_RELEASED| curses.BUTTON1_CLICKED)
    self.win.nodelay(1)
    self.win.notimeout(0)
    self.win.timeout(0)
    old_cursor = curses.curs_set(1)
    while (1):
        if (not keymap.keypending(self.win)) or force:
            self.render()
        if not ch_in:
            ch = self.handle(keymap.get_keyseq(self.win,keymap.getch(self.win)))
        else:
            ch = self.handle(ch_in)
        if blocking:
            if ch == Component.CMP_KEY_CANCEL:
                curses.curs_set(old_cursor)
                return {}
            elif ch == Component.CMP_KEY_OK:
                curses.curs_set(old_cursor)
                return self.getvalue()
        else:
            if ch == Component.CMP_KEY_CANCEL:
                curses.curs_set(old_cursor)
                return (ch, {})
            else:
                curses.curs_set(old_cursor)
                return (ch, self.getvalue())

def mouse_event(

self, ox, oy, mtype)

handle mouse events return key value or -1 for not handled

def mouse_event(self, ox, oy, mtype):
    """ handle mouse events return key value or -1 for not handled """
    return -1

def pop_history(

self, child)

def pop_history( self, child ):
    if not self.enable_history:
        return
    if not issubclass(child.__class__, Prompt):
        return
    if self.getname() and child.getname() and child.getorder() >= 0:
        key = (self.getname(), child.getname())
        if key in Dialog.history:
            hist = Dialog.history[key]
            self.hist_idx += 1
            if self.hist_idx > len(hist):
                self.hist_idx = 0
            child.setvalue(hist[-self.hist_idx])

def push_history(

self, child)

def push_history( self, child ):
    if not self.enable_history:
        return
    if not issubclass(child.__class__, Prompt):
        return
    if self.getname() and child.getname() and child.getorder() >= 0 and not child.isempty():
        key = (self.getname(), child.getname())
        if key in Dialog.history:
            if Dialog.history[key][-1] != child.getvalue():
                Dialog.history[key].append(child.getvalue())
        else:
            Dialog.history[key] = [child.getvalue()]

def refresh(

self, force=False)

populate all of the fields if something changed

def refresh(self,force=False):
    """ populate all of the fields if something changed """
    values = self.getvalue()
    ssh_path = ""
    ssh_dirnames = []
    ssh_filenames = []
    set_values={}
    if values["ssh_username"] and values["ssh_password"] and values["ssh_dir"]:
        new_ssh = values["ssh_username"] + values["ssh_password"] + values["ssh_dir"]
        if new_ssh != self.prior_ssh or force:
            self.prior_ssh = new_ssh
            try:
                (ssh_path,ssh_dirnames,ssh_filenames) = get_dir_ssh( values["ssh_dir"], values["ssh_username"], values["ssh_password"], False)
                self.prior_ssh = new_ssh
                set_values["ssh_files"] = (0, ssh_dirnames+ssh_filenames)
            except:
                print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                confirm(self.win, "SSH Error! Try Again ?")
    local_path = ""
    local_dirnames = []
    local_filenames = []
    if values["local_dir"]:
        if self.prior_local != values["local_dir"] or force:
            try:
                (local_path, local_dirnames,local_filenames) = get_dir(values["local_dir"],False)
                os.chdir(local_path)
                self.prior_local = values["local_dir"]
                set_values["local_files"] = (0, local_dirnames+local_filenames)
            except:
                print(traceback.format_exc(), file=open(ssh_log_name,"a"))
                confirm(self.win, "File Error! Try Again ?")
    self.setvalue(set_values)

def render(

self)

render the component use parent as target

def render(self):
    self.win.leaveok(1)
    for c in self.children:
        if not self.focus_list or self.focus_list[self.current][1] != c:
            c.render()
    self.win.leaveok(0)
    if self.focus_list:
        self.focus_list[self.current][1].focus()
        self.focus_list[self.current][1].render()
    self.win.refresh()

def resize(

self)

def resize(self):
    pass

def set_history(

self, state)

def set_history( self, state ):
    self.enable_history = state

def setparent(

self, parent)

set the parent curses target window

def setparent(self,parent):
    """ set the parent curses target window """
    self.parent = parent

def setpos(

self, x, y)

set the position of this component

def setpos(self, x, y ):
    """ set the position of this component """
    self.x = x
    self.y = y

def setsize(

self, height, width)

set the width of this component

def setsize(self, height, width ):
    """ set the width of this component """
    self.height = height
    self.width = width

def setvalue(

self, value)

set the components value, may be tuple or other data structure

def setvalue(self, value):
    for c in self.children:
        if c.getname() in value:
            c.setvalue(value[c.getname()])
            self.push_history(c)

def tab(

self)

def tab(self):
    if self.focus_list:
        self.push_history(self.focus_list[self.current][1])
        self.current += 1
        if self.current >= len(self.focus_list):
            self.current = 0

Instance variables

var cancel_button

var current_dir

var file_list

var file_name

var get_button

var open_button

var prior_local

var prior_ssh

var put_button

var ssh_current_dir

var ssh_file_list

var ssh_file_name

var ssh_password

var ssh_username

class SSHFileListBox

list box subclass for file lists, handles searching past the

prefix for incremental searches

class SSHFileListBox(dialog.ListBox):
    """ list box subclass for file lists, handles searching past the <DIR> prefix for incremental searches"""
    def find(self,searchfor):
        """ subclass the find method to find the string either with the dir prefix or without it """
        if not dialog.ListBox.find(self,"<DIR> "+searchfor):
            return dialog.ListBox.find(self,searchfor)
        else:
            return True

Ancestors (in MRO)

  • SSHFileListBox
  • ped_dialog.dialog.ListBox
  • ped_dialog.dialog.Component
  • builtins.object

Class variables

var CMP_KEY_CANCEL

var CMP_KEY_NOP

var CMP_KEY_OK

Static methods

def __init__(

self, name, order, x, y, height, width, label, selection=0, lst=[])

all components have a name and a tab order, order == -1 means exclude from tab

def __init__(self, name, order, x, y, height, width, label, selection = 0, lst = []):
    Component.__init__(self,name,order)
    self.x = x
    self.y = y
    self.height = height
    self.width = width
    self.label = label
    self.selection = selection
    self.search = ""
    self.top = selection
    if self.top < 0:
        self.top = 0
    self.list = lst
    self.isfocus = False

def cdown(

self)

def cdown(self):
    if len(self.list):
        self.selection += 1
        if self.selection >= len(self.list):
            self.selection = len(self.list)-1
        if self.selection < self.top:
            self.top = self.selection
        if self.selection > self.top+(self.height-3):
            self.top = self.selection-(self.height-3)

def cpgdn(

self)

def cpgdn(self):
    if len(self.list):
        self.selection += (self.height-2)
        if self.selection >= len(self.list):
           self.selection = len(self.list)-1
        if self.selection < self.top:
            self.top = self.selection
        if self.selection > self.top+(self.height-3):
            self.top = self.selection-(self.height-3)

def cpgup(

self)

def cpgup(self):
    if len(self.list):
        self.selection -= (self.height-2)
        if self.selection < 0:
            self.selection = 0
        if self.selection < self.top:
            self.top = self.selection
        if self.selection > self.top+(self.height-3):
            self.top = self.selection-(self.height-3)

def cup(

self)

def cup(self):
    if len(self.list):
        self.selection -= 1
        if self.selection < 0:
            self.selection = 0
        if self.selection < self.top:
            self.top = self.selection
        if self.selection > self.top+(self.height-3):
            self.top = self.selection-(self.height-3)

def end(

self)

def end(self):
    if len(self.list):
        self.selection = len(self.list)-1
        self.top = self.selection-(self.height-3)
        if self.top < 0:
            self.top = 0

def find(

self, searchfor)

subclass the find method to find the string either with the dir prefix or without it

def find(self,searchfor):
    """ subclass the find method to find the string either with the dir prefix or without it """
    if not dialog.ListBox.find(self,"<DIR> "+searchfor):
        return dialog.ListBox.find(self,searchfor)
    else:
        return True

def focus(

self)

called when component is the focus

def focus(self):
    self.isfocus = True

def getname(

self)

get the name of this component

def getname(self):
    """ get the name of this component """
    return self.name

def getorder(

self)

get this component's tab order number

def getorder(self):
    """ get this component's tab order number """
    return self.order

def getparent(

self)

get this component's curses target window

def getparent(self):
    """ get this component's curses target window """
    return self.parent

def getvalue(

self)

return the current value of the component

def getvalue(self):
    return (self.selection,self.list)

def handle(

self, ch)

handle keystrokes for this component

def handle(self,ch):
    if len(ch) == 1 and curses.ascii.isprint(ord(ch[0])):
        self.search += ch
        self.find(self.search)
    elif ch == keytab.KEYTAB_BACKSPACE:
        if self.search:
            self.search = self.search[0:-1]
            self.find(self.search)
    elif ch == keytab.KEYTAB_F03:
        if self.search:
            self.cdown()
            if not self.find(self.search):
                self.cup()
    elif ch == keytab.KEYTAB_LEFT or ch == keytab.KEYTAB_UP:
        self.cup()
    elif ch == keytab.KEYTAB_RIGHT or ch == keytab.KEYTAB_DOWN:
        self.cdown()
    elif ch == keytab.KEYTAB_HOME:
        self.home()
    elif ch == keytab.KEYTAB_END:
        self.end()
    elif ch == keytab.KEYTAB_PAGEUP:
        self.cpgup()
    elif ch == keytab.KEYTAB_PAGEDOWN:
        self.cpgdn()
    elif ch == keytab.KEYTAB_RESIZE:
        return ch
    elif ch in [keytab.KEYTAB_SPACE,keytab.KEYTAB_CR,keytab.KEYTAB_TAB,keytab.KEYTAB_ESC,keytab.KEYTAB_BTAB]:
        self.search = ""
        return ch
    return Component.CMP_KEY_NOP

def home(

self)

def home(self):
    if len(self.list):
        self.selection = 0
        self.top = 0

def isempty(

self)

test if the component entry is empty

def isempty(self):
    """ test if the component entry is empty """
    return False

def mouse_event(

self, ox, oy, mtype)

handle mouse events return key value or -1 for not handled

def mouse_event(self, ox, oy, mtype):
    if ox >= self.x and ox < self.x+self.width and oy >= self.y and oy <= self.y+self.height:
        oy = (oy - self.y) - 1
        if oy >= 0:
            if mtype & curses.BUTTON1_CLICKED:
                if self.top+oy < len(self.list):
                    self.selection = self.top+oy
                    return keytab.KEYTAB_CR
    return -1

def render(

self)

render the component use parent as target

def render(self):
    win = self.getparent()
    if win:
        if self.isfocus:
            lattr = curses.A_BOLD
        else:
            lattr = curses.A_NORMAL
        x = self.x
        y = self.y
        width = self.width
        height = self.height
        rect(win,x,y,width,height,self.label,lattr)
        x+=1
        y+=1
        width -=2
        height -=2
        top = self.top
        off = 0
        cy = -1
        while top < len(self.list) and off < height:
            if top == self.selection:
                rattr = curses.A_REVERSE
                cy = y+off
            else:
                if self.isfocus:
                    rattr = curses.A_BOLD
                else:
                    rattr = curses.A_NORMAL
            win.addstr(y+off,x,pad(self.list[top],width)[0:width],rattr)
            top += 1
            off += 1
        if self.isfocus and cy > 0:
            win.move(cy,x)
        self.isfocus = False

def setparent(

self, parent)

set the parent curses target window

def setparent(self,parent):
    """ set the parent curses target window """
    self.parent = parent

def setpos(

self, x, y)

set the position of this component

def setpos(self, x, y ):
    """ set the position of this component """
    self.x = x
    self.y = y

def setsize(

self, height, width)

set the width of this component

def setsize(self, height, width ):
    """ set the width of this component """
    self.height = height
    self.width = width

def setvalue(

self, value)

set the components value, may be tuple or other data structure

def setvalue(self,value):
    self.selection = value[0]
    self.list = value[1]
    if self.selection < self.top:
        self.top = self.selection
    if self.selection > self.top+(self.height-3):
        self.top = self.selection-(self.height-3)