Example #1
0
def _textPutFile(prompt='name this file:', defaultName='name', defaultDir='',
                      extension='*', dlgVisualMethod='text', termObj=None):
    """text based ui for getting a file to save"""
    finalPath = ''
    status = -2 # init value
    # check if dir has been cleared, recheck
    if defaultDir != '': # used as default dir selection
        directory = defaultDir
    elif drawer.getcwd() != None:
        directory = drawer.getcwd()
    elif drawer.getud() != None:
        directory = drawer.getud()
    else: directory = ''
    
    directory = drawer.pathScrub(directory)
    while 1:
        usrStr = askStr(prompt, termObj) # get file name
        if usrStr == None:
            return None, -1 # error
        # check for bad chars in fileName
        if usrStr[0] not in lang.IDENTCHARS:
            msgOut(lang.msgDlgBadFileNameStart % usrStr[0], termObj)
            return None, -1 # error
        for char in usrStr:
            if char not in lang.FILECHARS:
                msgOut(lang.msgDlgBadFileNameChar % char, termObj)
                return None, -1

        # get directory
        status = askYesNoCancel((lang.msgDlgSaveInThisDir % directory), termObj)
        if status == -1:    #cancel
            break
        if status == 0: #no, get new directory
            path, ok = promptGetDir('', directory, dlgVisualMethod, termObj)
            if ok != 1:
                status = -1
                break
            else:
                directory = path
                status = 1
        if status == 1: # test for existing file 
            dirContent = os.listdir(directory)
            if usrStr in dirContent:
                ok = askYesNoCancel(lang.msgDlgFileExists, termObj)
                if ok != 1: continue
        finalPath = os.path.join(directory, usrStr)
        finalPath = drawer.pathScrub(finalPath)
        ok = askYesNoCancel((lang.msgDlgSaveThisFile % finalPath), termObj)
        if ok == -1:
            status = -1
            break
        elif ok == 0:
            continue
        elif ok == 1:
            status = 1
            break
    return finalPath, status
Example #2
0
def _macGetDirectory(prompt='select a directory'):
    carbon = drawer.isCarbon()
    if carbon:
        import EasyDialogs
        path = EasyDialogs.AskFolder(message=prompt)
        if path == None: return '', 0
        else: return path, 1
    else:
        import macfs
        fsspec, ok = macfs.GetDirectory(prompt)
        if ok != 1:
            return '', 0  # failure
        path = fsspec.as_pathname()
        drawer.pathScrub(path)
        return path, 1
Example #3
0
def _macGetDirectory(prompt='select a directory'):
    carbon = drawer.isCarbon()
    if carbon:
        import EasyDialogs
        path = EasyDialogs.AskFolder(message=prompt)
        if path == None: return '', 0
        else: return path, 1
    else:
        import macfs
        fsspec, ok = macfs.GetDirectory(prompt)
        if ok != 1:
            return '', 0 # failure
        path = fsspec.as_pathname()
        drawer.pathScrub(path)
        return path, 1
Example #4
0
 def __init__(self, usrStr):
     """usrStr may have a comma, and thus include data for
     the number of values to read; can also be set below
     w/ getPitch method"""
     if usrStr == None:
         raise ValueError, 'bad file path given'
     if usrStr.find(',') >= 0:
         filePath, maxCount = usrStr.split(',')[:2]
         maxCount = drawer.strToNum(maxCount, 'int')
         #print _MOD, 'got maxCount of', maxCount
     else:
         filePath = usrStr
         maxCount = None # default
     if maxCount != None:
         self.maxCount = maxCount
     else: self.maxCount = 10
     # file path shuold always exists
     filePath = drawer.pathScrub(filePath)
     if not os.path.exists(filePath) or os.path.isdir(filePath): 
         raise ValueError, 'bad file path given'
     self.filePath = filePath
     self.forms = ['audacity.spectrum', 'audacity.autocorrelation']
     ok = self._parseFormat()
     if ok == None:
         raise ValueError, 'bad file path given'
     self.dataEval, self.fmt = ok
Example #5
0
 def __init__(self, args, refDict):
     basePmtr.Parameter.__init__(self, args, refDict) # call base init
     self.type = 'constantFile'    
     self.doc = lang.docPoCf
     self.outputFmt = 'str' # declare outputFmt as string
     self.argTypes = ['str']
     self.argNames = ['absoluteFilePath']
     self.argDefaults = [''] # no default possible
     # check raw arguments for number, type
     ok, msg = self._checkRawArgs()
     if ok == 0: raise error.ParameterObjectSyntaxError(msg) # report error
     self.filePath = drawer.pathScrub(self.args[0])
Example #6
0
 def __init__(self, args, refDict):
     basePmtr.Parameter.__init__(self, args, refDict) # call base init
     self.type = 'constantFile'    
     self.doc = lang.docPoCf
     self.outputFmt = 'str' # declare outputFmt as string
     self.argTypes = ['str']
     self.argNames = ['absoluteFilePath']
     self.argDefaults = [''] # no default possible
     # check raw arguments for number, type
     ok, msg = self._checkRawArgs()
     if ok == 0: raise error.ParameterObjectSyntaxError(msg) # report error
     self.filePath = drawer.pathScrub(self.args[0])
Example #7
0
def _macGetFile(prompt='pick a file', defaultDir=None):
    carbon = drawer.isCarbon()
    if carbon:
        import EasyDialogs
        path = EasyDialogs.AskFileForOpen(message=prompt)
        if path == None: return '', 0
        else: return path, 1
    else:
        import macfs
        fsspec, ok = macfs.PromptGetFile(prompt)
        if ok != 1: return '', 0 # failure
        path = fsspec.as_pathname()
        path = drawer.pathScrub(path)
        return path, 1
Example #8
0
def _macGetFile(prompt='pick a file', defaultDir=None):
    carbon = drawer.isCarbon()
    if carbon:
        import EasyDialogs
        path = EasyDialogs.AskFileForOpen(message=prompt)
        if path == None: return '', 0
        else: return path, 1
    else:
        import macfs
        fsspec, ok = macfs.PromptGetFile(prompt)
        if ok != 1: return '', 0  # failure
        path = fsspec.as_pathname()
        path = drawer.pathScrub(path)
        return path, 1
Example #9
0
def _macPutFile(prompt='save a file', defaultName='test.txt', defaultDir=None):
    carbon = drawer.isCarbon()
    if carbon:
        import EasyDialogs
        path = EasyDialogs.AskFileForSave(message=prompt,
                                          savedFileName=defaultName)
        if path == None: return '', 0
        else: return path, 1
    else:
        import macfs
        fsspec, ok = macfs.PromptPutFile(prompt, defaultName)
        if ok != 1:
            return '', 0
        path = fsspec.as_pathname()
        ## check extension, add if missing
        path = drawer.pathScrub(path)
        return path, 1
Example #10
0
def _macPutFile(prompt='save a file', defaultName='test.txt', defaultDir=None):
    carbon = drawer.isCarbon()
    if carbon:
        import EasyDialogs
        path = EasyDialogs.AskFileForSave(message=prompt, 
                                        savedFileName=defaultName)
        if path == None: return '', 0
        else: return path, 1
    else:
        import macfs
        fsspec, ok = macfs.PromptPutFile(prompt, defaultName)
        if ok != 1:
            return '', 0
        path = fsspec.as_pathname()
        ## check extension, add if missing
        path = drawer.pathScrub(path)
        return path, 1
Example #11
0
def openMedia(path, prefDict=None):
    """open a media or text file, file type is determined by extension
    will assume that path is to a media file, rather than an exe
    for executable scripts, use launch
    if prefDict is provided, will get app path from there
    keys in this disc must start w/ media type; image, audio, midi, text, ps


    TODO: this should be updated to use application preferences 
    stored in prefTools.py, not here
    """
    path = drawer.pathScrub(path)
    dir, name = os.path.split(path)
    name, ext = extSplit(name)

    # this should be as method of a the pref tools
    # pref object/dict, or a function in this module or drawer
    if ext in imageEXT: fileType = 'image'
    elif ext in audioEXT: fileType = 'audio'
    elif ext in videoEXT: fileType = 'video'
    elif ext in midiEXT: fileType = 'midi'
    elif ext in textEXT or ext in codeEXT: fileType = 'text'
    elif ext in psEXT: fileType = 'ps'
    else: fileType = None

    app = None  # default nothing

    if prefDict == None and fileType != None:  # get default apps
        #         if os.name == 'mac': pass # rely on system
        if os.name == 'posix':
            if drawer.isDarwin():  # assume sys default for most
                if fileType in ['audio', 'midi', 'video']:
                    app = '/Applications/QuickTime Player.app'
            else:  # other unix
                if fileType == 'text': app = 'more'
                elif fileType == 'audio': app = 'xmms'  #'play' should work too
                elif fileType == 'midi': app = 'playmidi'  #
                elif fileType == 'image': app = 'imagemagick'
                elif fileType == 'ps': app = 'gs'
        else:  # win or other
            pass  # rely on system
    elif fileType != None:  # get from prefDict
        for key in prefDict.keys():
            # match by filetype string leading key and path string
            if key.startswith(fileType) and 'path' in key.lower():
                app = prefDict[key]  # may be a complete file path, or a name

    if app == '':
        app = None  # if given as empty, convert to none
    elif not drawer.isApp(app):
        app = None  # if not an app any more, drop

#     if os.name == 'mac':     # os9
#         cmdExe = '%s' % path # on mac, just launch txt file, rely on pref
    if os.name == 'posix':
        if drawer.isDarwin():
            if app == None:  # no app use system default
                cmdExe = 'open "%s"' % path
            elif app.lower().endswith('.app'):  # if a .app type app
                cmdExe = 'open -a "%s" "%s"' % (app, path)
            else:  # its a unix style command
                cmdExe = '%s %s' % (app, path)
        else:  # other unix
            if app == None:
                cmdExe = '%s' % (path)
            else:
                cmdExe = '%s %s' % (app, path)
    else:  # win or other, rely on system settings
        cmdExe = '%s' % path  # on win, just launch path
    return launch(cmdExe)  # returns None on success
Example #12
0
def promptGetFile(prompt='select a file',
                  defaultDir='',
                  mode='file',
                  dlgVisualMethod=None,
                  termObj=None):
    """multi platform/gui methods for selecting file to open
    text version allowes user to browse file system
    mode can be either filr or app, to allow application selection
        this is only explicitly necessary in text-based file selection
    """

    if dlgVisualMethod == None:  # test for vis method if not provided
        dlgVisualMethod = autoDlgMethod()

    if defaultDir != '': pass  # used as default dir selection
    elif drawer.getcwd() != None:
        defaultDir = drawer.getcwd()
    elif drawer.getud() != None:
        defaultDir = drawer.getud()
    else:
        defaultDir = ''
    defaultDir = drawer.pathScrub(defaultDir)

    path = None  # empty until defined
    # platform specific file dialogs.
    if dlgVisualMethod == 'mac':
        try:
            path, stat = _macGetFile(prompt, defaultDir)
            return path, stat
        except:
            print(lang.msgDlgMacError)

    # platform specific file dialogs.
    if dlgVisualMethod[:2] == 'tk':
        try:
            import tkinter
            import tkinter.filedialog
            TK = 1
        except ImportError:
            TK = 0
            print(lang.msgDlgTkError)

    if dlgVisualMethod[:2] == 'tk' and TK:
        tkTemp = tkinter.Tk()
        tkTemp.withdraw()
        options = {
            'filetypes': [("all files", "*")],
            'title': prompt,
            'parent': tkTemp
        }
        # need to check if defaultDir still exists
        if os.path.isdir(defaultDir):
            options['initialdir'] = defaultDir

        guiTemp = tkinter.filedialog.Open()
        guiTemp.options = options
        # filename = apply(tkFileDialog.Open, (), options).show(
        try:
            path = guiTemp.show()
            # clean up gui mess
            del guiTemp
            tkTemp.destroy()
        except:
            pass  # tk broke somehow
        if path not in ['', None] and drawer.isStr(path):
            path = drawer.pathScrub(path)
            return path, 1
        # may be problem here with a keyboard interupt exception
        #elif path == None: # if not set yet, something went wrong
        #    pass                 # fall below to text based
        else:
            return '', 0  # failure

    # for all other platforms, dlgVisualMethod == text
    try:
        msg, ok = _textGetFile(prompt, defaultDir, mode, dlgVisualMethod,
                               termObj)
    except (OSError,
            IOError):  # catch file errors, or dirs called tt dont exist
        msg = ''  # this is usually the path itself
        ok = 0
    return msg, ok
Example #13
0
def promptPutFile(prompt='name this file:',
                  defaultName='name',
                  defaultDir='',
                  extension='*',
                  dlgVisualMethod=None,
                  termObj=None):
    """multi platform/gui methods for selecting a file to write to
    text version allows user to browse file system
    """
    if dlgVisualMethod == None:  # test for vis method if not provided
        dlgVisualMethod = autoDlgMethod()
    path = None  # empty until defined

    # platform specific file dialogs.
    if dlgVisualMethod == 'mac':
        stat = 0
        try:
            path, stat = _macPutFile(prompt, defaultName, defaultDir)
            return path, stat
        except:  # will be MacOS.Error but must import MacOS to select?
            print(lang.msgDlgMacError)

    # platform specific file dialogs.
    if dlgVisualMethod[:2] == 'tk':
        try:
            import tkinter
            import tkinter.filedialog
            TK = 1
        except ImportError:
            TK = 0
            print(lang.msgDlgTkError)

    if dlgVisualMethod[:2] == 'tk' and TK == 1:
        tkTemp = tkinter.Tk()
        tkTemp.withdraw()
        # put extension here, but dont know if i need period or not
        options = {
            'filetypes': [("all files", "*")],
            'title': prompt,
            'parent': tkTemp
        }
        # need to check if directory still exists
        if os.path.isdir(defaultDir):
            options['initialdir'] = defaultDir

        guiTemp = tkinter.filedialog.SaveAs()
        guiTemp.options = options
        # filename = apply(tkFileDialog.Open, (), options).show(
        try:
            path = guiTemp.show()
            del guiTemp  # clean up gui mess
            tkTemp.destroy()  # return path
        except:
            pass  # tk broke somehow
        if path not in ['', None] and drawer.isStr(path):
            path = drawer.pathScrub(path)
            return path, 1
        # may be problem here with a keyboard interupt exception
        #elif path == None: # if not set yet, something went wrong
        #    pass                 # fall below to text based
        else:
            return '', 0

    # for all other platforms
    try:
        msg, ok = _textPutFile(prompt, defaultName, defaultDir, extension,
                               dlgVisualMethod, termObj)
    except (OSError,
            IOError):  # catch file errors, or dirs called tt dont exist
        msg = ''  # this is usually the path itself
        ok = 0
    return msg, ok
Example #14
0
def promptGetDir(prompt='select a directory:',
                 sampleDir='',
                 dlgVisualMethod=None,
                 termObj=None):
    """multi platform/gui methods for optaining a directory
    text based version displays dir listings
    """
    if dlgVisualMethod == None:  # test for vis method if not provided
        dlgVisualMethod = autoDlgMethod()
    # check for bad directories
    if sampleDir != '': pass  # used as default dir selection
    elif drawer.getcwd() != None:
        sampleDir = drawer.getcwd()
    elif drawer.getud() != None:
        sampleDir = drawer.getud()
    else:
        sampleDir = ''
    sampleDir = drawer.pathScrub(sampleDir)

    pathToFile = None  # empty until defined
    # platform specific file dialogs.
    if dlgVisualMethod == 'mac':
        try:
            path, stat = _macGetDirectory(prompt)
            return path, stat
        except:
            print(lang.msgDlgMacError)

    # platform specific file dialogs.
    if dlgVisualMethod[:2] == 'tk':
        try:
            import tkinter
            import tkinter.filedialog
            TK = 1
        except ImportError:
            TK = 0
            print(lang.msgDlgTkError)

    if dlgVisualMethod[:2] == 'tk' and TK == 1:
        tkTemp = tkinter.Tk()
        tkTemp.withdraw()
        ## "dir" only shows directories, but are unable to select
        options = {
            'filetypes': [("directory", "*")],
            'title': prompt,
            'parent': tkTemp
        }
        # need to check if defaultDir still exists
        if os.path.isdir(sampleDir):
            options['initialdir'] = sampleDir

        guiTemp = tkinter.filedialog.Open()
        guiTemp.options = options
        # filename = apply(tkFileDialog.Open, (), options).show(
        try:
            pathToFile = guiTemp.show()
            del guiTemp  # clean up gui mess
            tkTemp.destroy()
        except:  # tk broke somehow
            pass
        # return path
        if pathToFile not in ['', None] and drawer.isStr(pathToFile):
            pathToFile = os.path.dirname(pathToFile)  # remove file name
            pathToFile = drawer.pathScrub(pathToFile)
            return pathToFile, 1
        elif pathToFile == None:  # if not set yet, something went wrong
            pass  # fall below to text based
        else:
            return '', 0
    # for all other platforms, dlgVisualMethod == text
    try:
        msg, ok = _textGetDirectory(prompt, sampleDir, termObj)
    except (OSError,
            IOError):  # catch file errors, or dirs called tt dont exist
        msg = ''  # this is usually the path itself
        ok = 0
    return msg, ok
Example #15
0
def promptGetDir(prompt='select a directory:', sampleDir='', 
                                 dlgVisualMethod=None, termObj=None):
    """multi platform/gui methods for optaining a directory
    text based version displays dir listings
    """
    if dlgVisualMethod == None: # test for vis method if not provided
        dlgVisualMethod = autoDlgMethod()
    # check for bad directories
    if sampleDir != '': pass # used as default dir selection
    elif drawer.getcwd() != None:
        sampleDir = drawer.getcwd()
    elif drawer.getud() != None:
        sampleDir = drawer.getud()
    else: sampleDir = ''
    sampleDir = drawer.pathScrub(sampleDir)
    
    pathToFile = None # empty until defined
    # platform specific file dialogs.
    if dlgVisualMethod == 'mac':
        try:
            path, stat = _macGetDirectory(prompt)
            return path, stat
        except:
            print lang.msgDlgMacError

    # platform specific file dialogs.
    if dlgVisualMethod[:2] == 'tk':
        try:
            import Tkinter
            import tkFileDialog
            TK = 1
        except ImportError:
            TK = 0
            print lang.msgDlgTkError

    if dlgVisualMethod[:2] == 'tk' and TK == 1:
        tkTemp = Tkinter.Tk()
        tkTemp.withdraw()
        ## "dir" only shows directories, but are unable to select 
        options = {'filetypes':[("directory", "*")], 
                        'title'   : prompt,      
                        'parent'      : tkTemp}
        # need to check if defaultDir still exists
        if os.path.isdir(sampleDir):
            options['initialdir'] = sampleDir
            
        guiTemp = tkFileDialog.Open()
        guiTemp.options = options
        # filename = apply(tkFileDialog.Open, (), options).show(
        try:
            pathToFile = guiTemp.show() 
            del guiTemp # clean up gui mess
            tkTemp.destroy()
        except: # tk broke somehow
            pass
        # return path
        if pathToFile not in ['', None] and drawer.isStr(pathToFile):
            pathToFile = os.path.dirname(pathToFile)    # remove file name
            pathToFile = drawer.pathScrub(pathToFile)
            return pathToFile, 1
        elif pathToFile == None: # if not set yet, something went wrong
            pass                 # fall below to text based
        else:
            return '', 0
    # for all other platforms, dlgVisualMethod == text
    try:
        msg, ok = _textGetDirectory(prompt, sampleDir, termObj)
    except (OSError, IOError): # catch file errors, or dirs called tt dont exist
        msg = '' # this is usually the path itself
        ok = 0
    return msg, ok
Example #16
0
def _textGetDirectory(prompt='select a directory: ', sampleDir='',
                             termObj=None):
    """this method allows the user to select a directory using a text
    based interface.
    """
    if sampleDir != '':
        currentDir = sampleDir
    elif drawer.getcwd() != None:
        currentDir = drawer.getcwd()
    elif drawer.getud() != None:
        currentDir = drawer.getud()
    else: currentDir = ''       
    currentDir = drawer.pathScrub(currentDir)

    while 1:
        cwdContents = os.listdir(currentDir)
        maxLength = 0
        for fName in cwdContents:
            if len(fName) >= maxLength:
                maxLength = len(fName)
        maxLength = maxLength + 2 # add two spaces of buffer
        header = '%s' % currentDir #delete extra space here

        if termObj == None: # update termwidth
            termWidth = 70 # default
        else:
            h, termWidth = termObj.size()

        msg = typeset.formatEqCol(header, cwdContents, maxLength, termWidth)
        msgOut((msg + prompt), termObj) # dont want extra return
        usrStr = askStr(lang.msgMenuChangeDir, termObj)
        finalPath = '' # keep empty until cmds parsed
        # scan for each of the options
        if usrStr == None: continue # bad input
        if usrStr.lower() == 's': # if entry is s, return cwd
            finalPath = currentDir # selected, asuign to final
        if usrStr == '..': # up one dir, display
            pathValid = os.path.exists(currentDir)
            currentDir = os.path.dirname(currentDir)
            continue
        if finalPath == '': # still not asigned, check if its a path
            downDir = os.path.join(currentDir, usrStr)
            downDir = drawer.pathScrub(downDir) # assume this is a dir
            cwdContents = os.listdir(currentDir)
            if usrStr in cwdContents:
                if os.path.isdir(downDir) != 1: # if not a dir
                    continue
                else: # is a dir
                    currentDir = downDir # make downDir current, back to top
                    continue
        if finalPath == '': #user has entered a abs path
            absPath = drawer.pathScrub(usrStr)
            ### resolve aliases here!
            if os.path.exists(absPath) and os.path.isdir(absPath): 
                currentDir = absPath # this is a dir, same as selecting a dir
                continue
        if finalPath == '': # not assigned yet
            if usrStr.lower() == 'c':
                return '', 0 # canceled
            else: # bad input, continue
                msgOut((lang.msgDlgBadInput % usrStr), termObj)
                continue
        if not os.path.exists(finalPath): # if doesnt exist
            status = askYesNo(lang.msgDlgBadPath, 1, termObj)
            if status != 1:
                return '', 0 # cancle msg
            else: continue
        else: # its good
            finalPath = drawer.pathScrub(finalPath)
            return finalPath, 1
Example #17
0
def _textGetDirectory(prompt='select a directory: ',
                      sampleDir='',
                      termObj=None):
    """this method allows the user to select a directory using a text
    based interface.
    """
    if sampleDir != '':
        currentDir = sampleDir
    elif drawer.getcwd() != None:
        currentDir = drawer.getcwd()
    elif drawer.getud() != None:
        currentDir = drawer.getud()
    else:
        currentDir = ''
    currentDir = drawer.pathScrub(currentDir)

    while 1:
        cwdContents = os.listdir(currentDir)
        maxLength = 0
        for fName in cwdContents:
            if len(fName) >= maxLength:
                maxLength = len(fName)
        maxLength = maxLength + 2  # add two spaces of buffer
        header = '%s' % currentDir  #delete extra space here

        if termObj == None:  # update termwidth
            termWidth = 70  # default
        else:
            h, termWidth = termObj.size()

        msg = typeset.formatEqCol(header, cwdContents, maxLength, termWidth)
        msgOut((msg + prompt), termObj)  # dont want extra return
        usrStr = askStr(lang.msgMenuChangeDir, termObj)
        finalPath = ''  # keep empty until cmds parsed
        # scan for each of the options
        if usrStr == None: continue  # bad input
        if usrStr.lower() == 's':  # if entry is s, return cwd
            finalPath = currentDir  # selected, asuign to final
        if usrStr == '..':  # up one dir, display
            pathValid = os.path.exists(currentDir)
            currentDir = os.path.dirname(currentDir)
            continue
        if finalPath == '':  # still not asigned, check if its a path
            downDir = os.path.join(currentDir, usrStr)
            downDir = drawer.pathScrub(downDir)  # assume this is a dir
            cwdContents = os.listdir(currentDir)
            if usrStr in cwdContents:
                if os.path.isdir(downDir) != 1:  # if not a dir
                    continue
                else:  # is a dir
                    currentDir = downDir  # make downDir current, back to top
                    continue
        if finalPath == '':  #user has entered a abs path
            absPath = drawer.pathScrub(usrStr)
            ### resolve aliases here!
            if os.path.exists(absPath) and os.path.isdir(absPath):
                currentDir = absPath  # this is a dir, same as selecting a dir
                continue
        if finalPath == '':  # not assigned yet
            if usrStr.lower() == 'c':
                return '', 0  # canceled
            else:  # bad input, continue
                msgOut((lang.msgDlgBadInput % usrStr), termObj)
                continue
        if not os.path.exists(finalPath):  # if doesnt exist
            status = askYesNo(lang.msgDlgBadPath, 1, termObj)
            if status != 1:
                return '', 0  # cancle msg
            else:
                continue
        else:  # its good
            finalPath = drawer.pathScrub(finalPath)
            return finalPath, 1
Example #18
0
def promptPutFile(prompt='name this file:', defaultName='name', 
                defaultDir='', extension='*', dlgVisualMethod=None, termObj=None):
    """multi platform/gui methods for selecting a file to write to
    text version allows user to browse file system
    """
    if dlgVisualMethod == None: # test for vis method if not provided
        dlgVisualMethod = autoDlgMethod()
    path = None # empty until defined

    # platform specific file dialogs.
    if dlgVisualMethod == 'mac':
        stat = 0
        try:
            path, stat = _macPutFile(prompt, defaultName, defaultDir)
            return path, stat
        except: # will be MacOS.Error but must import MacOS to select?
            print lang.msgDlgMacError

    # platform specific file dialogs.
    if dlgVisualMethod[:2] == 'tk':
        try:
            import Tkinter
            import tkFileDialog
            TK = 1
        except ImportError:
            TK = 0
            print lang.msgDlgTkError

    if dlgVisualMethod[:2] == 'tk' and TK == 1:
        tkTemp = Tkinter.Tk()
        tkTemp.withdraw()
        # put extension here, but dont know if i need period or not
        options = {'filetypes':[("all files", "*")],    
                        'title'   : prompt,      
                        'parent'      : tkTemp}
        # need to check if directory still exists
        if os.path.isdir(defaultDir):
            options['initialdir'] = defaultDir
                        
        guiTemp = tkFileDialog.SaveAs()
        guiTemp.options = options
        # filename = apply(tkFileDialog.Open, (), options).show(
        try:
            path = guiTemp.show()
            del guiTemp # clean up gui mess
            tkTemp.destroy()    # return path
        except: pass # tk broke somehow
        if path not in ['', None] and drawer.isStr(path):
            path = drawer.pathScrub(path)
            return path, 1
        # may be problem here with a keyboard interupt exception
        #elif path == None: # if not set yet, something went wrong
        #    pass                 # fall below to text based
        else:
            return '', 0

    # for all other platforms
    try:
        msg, ok = _textPutFile(prompt, defaultName, defaultDir, extension, 
                                  dlgVisualMethod, termObj)
    except (OSError, IOError): # catch file errors, or dirs called tt dont exist
        msg = '' # this is usually the path itself
        ok = 0
    return msg, ok
Example #19
0
def _textPutFile(prompt='name this file:',
                 defaultName='name',
                 defaultDir='',
                 extension='*',
                 dlgVisualMethod='text',
                 termObj=None):
    """text based ui for getting a file to save"""
    finalPath = ''
    status = -2  # init value
    # check if dir has been cleared, recheck
    if defaultDir != '':  # used as default dir selection
        directory = defaultDir
    elif drawer.getcwd() != None:
        directory = drawer.getcwd()
    elif drawer.getud() != None:
        directory = drawer.getud()
    else:
        directory = ''

    directory = drawer.pathScrub(directory)
    while 1:
        usrStr = askStr(prompt, termObj)  # get file name
        if usrStr == None:
            return None, -1  # error
        # check for bad chars in fileName
        if usrStr[0] not in lang.IDENTCHARS:
            msgOut(lang.msgDlgBadFileNameStart % usrStr[0], termObj)
            return None, -1  # error
        for char in usrStr:
            if char not in lang.FILECHARS:
                msgOut(lang.msgDlgBadFileNameChar % char, termObj)
                return None, -1

        # get directory
        status = askYesNoCancel((lang.msgDlgSaveInThisDir % directory),
                                termObj)
        if status == -1:  #cancel
            break
        if status == 0:  #no, get new directory
            path, ok = promptGetDir('', directory, dlgVisualMethod, termObj)
            if ok != 1:
                status = -1
                break
            else:
                directory = path
                status = 1
        if status == 1:  # test for existing file
            dirContent = os.listdir(directory)
            if usrStr in dirContent:
                ok = askYesNoCancel(lang.msgDlgFileExists, termObj)
                if ok != 1: continue
        finalPath = os.path.join(directory, usrStr)
        finalPath = drawer.pathScrub(finalPath)
        ok = askYesNoCancel((lang.msgDlgSaveThisFile % finalPath), termObj)
        if ok == -1:
            status = -1
            break
        elif ok == 0:
            continue
        elif ok == 1:
            status = 1
            break
    return finalPath, status
Example #20
0
def _textGetFile(prompt='select a file', defaultDir='', mode='file',
                      dlgVisualMethod='text', termObj=None):
    """text based ui for user selection of files; can optionally be used
    to get applications; this is tricky as sometimes apps are folders, not files
    mode can either be file or app
    """
    finalPath = ''
    if defaultDir != '': # used as default dir selection
        directory = defaultDir
    elif drawer.getcwd() != None:
        directory = drawer.getcwd()
    elif drawer.getud() != None:
        directory = drawer.getud()
    else: directory = ''
    directory = drawer.pathScrub(directory)

    while 1:
        header = '\n%s' % directory
        msgOut('%s\n' % prompt, termObj)
        usrStr = askStr(lang.msgMenuFile, termObj)
        if usrStr == None: return None, -1 # cancel
        # check first for a complete path
        elif os.path.isfile(drawer.pathScrub(usrStr)):
            status = 1
            finalPath = drawer.pathScrub(usrStr)
        elif usrStr.lower() == 'cd': # change directory
            path, ok = promptGetDir('', directory, dlgVisualMethod, termObj)
            if not ok: # error
                status = -1
                break # cancel entire session
            else:
                directory = path
                continue
        elif usrStr.lower() == 'c': # cancel selected
            return None, -1 # cancel
        else:
            if usrStr.lower() != 'f':
                msgOut(lang.msgConfusedInput, termObj)
                continue
            status = 0 # reinit status flag
            while 1: # file selection loop
                name = askStr(lang.msgDlgNameFile, termObj)
                if name == None: return None, -1 # will cancel
                # if an application, filter path before testing
                if mode == 'app':
                    name = drawer.appPathFilter(name)
                # check first if this is an absolute file path, accept if so
                if ((os.path.isabs(name) and mode == 'file' and 
                    not os.path.isdir(name) and os.path.exists(name)) or 
                    (os.path.isabs(name) and mode == 'app' and 
                    drawer.isApp(name) and os.path.exists(name))):
                    finalPath = name
                    break
                # else see if name is in dir; cant adjust name for apps here
                # must assume that they are displayed to e user in w/ extension
                elif name in os.listdir(directory):
                    fp = os.path.join(directory, name)
                    # check: if a dir or not app, fail
                    if ((mode == 'file' and os.path.isdir(fp)) or
                        (mode == 'app' and not drawer.isApp(fp))): 
                        if mode == 'file':  
                            errorMsg = lang.msgDlgDirNotFile
                        elif mode == 'app':
                            errorMsg = lang.msgDlgNotApp
                        ok = askYesNo(errorMsg, 1, termObj)
                        if ok: continue
                        elif not ok:
                            status = -2
                            break
                    finalPath = fp
                    break
                else: # not in this directory
                    ok = askYesNoCancel(lang.msgDlgBadFileName, termObj)
                    if ok: continue
                    elif not ok:
                        status = -2 # wil continue
                        break
                    else: break
        if status == -2: continue
        # final check
        if finalPath == '':
            status = -1
            break
        else: # final check
            query = lang.msgDlgSelectThisFile % finalPath
            ok = askYesNoCancel(query, termObj)
            if ok == -1: # cancel selection
                status = -1
                break
            elif ok == 0: continue # no, retry
            elif ok:
                status = 1
                break
    finalPath = drawer.pathScrub(finalPath)
    return finalPath, status            
Example #21
0
def _textGetFile(prompt='select a file',
                 defaultDir='',
                 mode='file',
                 dlgVisualMethod='text',
                 termObj=None):
    """text based ui for user selection of files; can optionally be used
    to get applications; this is tricky as sometimes apps are folders, not files
    mode can either be file or app
    """
    finalPath = ''
    if defaultDir != '':  # used as default dir selection
        directory = defaultDir
    elif drawer.getcwd() != None:
        directory = drawer.getcwd()
    elif drawer.getud() != None:
        directory = drawer.getud()
    else:
        directory = ''
    directory = drawer.pathScrub(directory)

    while 1:
        header = '\n%s' % directory
        msgOut('%s\n' % prompt, termObj)
        usrStr = askStr(lang.msgMenuFile, termObj)
        if usrStr == None:
            return None, -1  # cancel
            # check first for a complete path
        elif os.path.isfile(drawer.pathScrub(usrStr)):
            status = 1
            finalPath = drawer.pathScrub(usrStr)
        elif usrStr.lower() == 'cd':  # change directory
            path, ok = promptGetDir('', directory, dlgVisualMethod, termObj)
            if not ok:  # error
                status = -1
                break  # cancel entire session
            else:
                directory = path
                continue
        elif usrStr.lower() == 'c':  # cancel selected
            return None, -1  # cancel
        else:
            if usrStr.lower() != 'f':
                msgOut(lang.msgConfusedInput, termObj)
                continue
            status = 0  # reinit status flag
            while 1:  # file selection loop
                name = askStr(lang.msgDlgNameFile, termObj)
                if name == None: return None, -1  # will cancel
                # if an application, filter path before testing
                if mode == 'app':
                    name = drawer.appPathFilter(name)
                # check first if this is an absolute file path, accept if so
                if ((os.path.isabs(name) and mode == 'file'
                     and not os.path.isdir(name) and os.path.exists(name))
                        or (os.path.isabs(name) and mode == 'app'
                            and drawer.isApp(name) and os.path.exists(name))):
                    finalPath = name
                    break
                # else see if name is in dir; cant adjust name for apps here
                # must assume that they are displayed to e user in w/ extension
                elif name in os.listdir(directory):
                    fp = os.path.join(directory, name)
                    # check: if a dir or not app, fail
                    if ((mode == 'file' and os.path.isdir(fp))
                            or (mode == 'app' and not drawer.isApp(fp))):
                        if mode == 'file':
                            errorMsg = lang.msgDlgDirNotFile
                        elif mode == 'app':
                            errorMsg = lang.msgDlgNotApp
                        ok = askYesNo(errorMsg, 1, termObj)
                        if ok: continue
                        elif not ok:
                            status = -2
                            break
                    finalPath = fp
                    break
                else:  # not in this directory
                    ok = askYesNoCancel(lang.msgDlgBadFileName, termObj)
                    if ok: continue
                    elif not ok:
                        status = -2  # wil continue
                        break
                    else:
                        break
        if status == -2: continue
        # final check
        if finalPath == '':
            status = -1
            break
        else:  # final check
            query = lang.msgDlgSelectThisFile % finalPath
            ok = askYesNoCancel(query, termObj)
            if ok == -1:  # cancel selection
                status = -1
                break
            elif ok == 0:
                continue  # no, retry
            elif ok:
                status = 1
                break
    finalPath = drawer.pathScrub(finalPath)
    return finalPath, status
Example #22
0
def promptGetFile(prompt='select a file', defaultDir='', mode='file',
                                 dlgVisualMethod=None, termObj=None):
    """multi platform/gui methods for selecting file to open
    text version allowes user to browse file system
    mode can be either filr or app, to allow application selection
        this is only explicitly necessary in text-based file selection
    """

    if dlgVisualMethod == None: # test for vis method if not provided
        dlgVisualMethod = autoDlgMethod()

    if defaultDir != '': pass # used as default dir selection
    elif drawer.getcwd() != None:
        defaultDir = drawer.getcwd()
    elif drawer.getud() != None:
        defaultDir = drawer.getud()
    else: defaultDir = ''
    defaultDir = drawer.pathScrub(defaultDir)
            
    path = None # empty until defined
    # platform specific file dialogs.
    if dlgVisualMethod == 'mac':
        try:
            path, stat = _macGetFile(prompt, defaultDir)
            return path, stat
        except:
            print lang.msgDlgMacError

    # platform specific file dialogs.
    if dlgVisualMethod[:2] == 'tk':
        try:
            import Tkinter
            import tkFileDialog
            TK = 1
        except ImportError:
            TK = 0
            print lang.msgDlgTkError

    if dlgVisualMethod[:2] == 'tk' and TK:
        tkTemp = Tkinter.Tk()
        tkTemp.withdraw()
        options = {'filetypes':[("all files", "*")], 
                        'title'   : prompt,      
                        'parent'      : tkTemp}
        # need to check if defaultDir still exists
        if os.path.isdir(defaultDir):
            options['initialdir'] = defaultDir
        
        guiTemp = tkFileDialog.Open()
        guiTemp.options = options
        # filename = apply(tkFileDialog.Open, (), options).show(
        try:
            path = guiTemp.show()
            # clean up gui mess
            del guiTemp
            tkTemp.destroy()
        except: pass # tk broke somehow
        if path not in ['', None] and drawer.isStr(path):
            path = drawer.pathScrub(path)
            return path, 1
        # may be problem here with a keyboard interupt exception
        #elif path == None: # if not set yet, something went wrong
        #    pass                 # fall below to text based
        else:
            return '', 0 # failure 

    # for all other platforms, dlgVisualMethod == text
    try:
        msg, ok = _textGetFile(prompt, defaultDir, mode, dlgVisualMethod, termObj)
    except (OSError, IOError): # catch file errors, or dirs called tt dont exist
        msg = '' # this is usually the path itself
        ok = 0
    return msg, ok           
Example #23
0
optRemoveMan = 0 
optInstallMan = 0 
optReport = 0
optBdistType = None # default needed when calling runDisutils()

flags = ['-o','build', 'tool', 'install', 'bdist', 'uninstall', 
            'report', 'man', 'pth', 'sdist', 'register', 'bdist_mpkg',
            'bdist_rpm', 'bdist_deb', 'bdist_wininst', 'bdist_egg']
parsedArgs = argTools.parseFlags(sys.argv, flags)

# loop through each arg pair
for argPair in parsedArgs:
    # some options will configure settings
    if argPair[0] == '-o': # changes assumed athDir
        if argPair[1] != None:
            tempPath = drawer.pathScrub(argPair[1])
            if os.path.isdir(tempPath):
                _fpPackageDir = tempPath

    elif argPair[0] == 'tool': # installs a loader script
        optWriteLauncher = 1 # write launchers to athenaCL src dir
        optInstallTool = 1 # adds athenacl to /usr/local/bin
        optInstallMan = 1 # installls man page in bin

    elif argPair[0] == 'report': # do nothing, turn off defaults
        optReport = 1

    elif argPair[0] == 'pth': # do nothing but install man
        optRemovePthLoader = 1 # always remove, may have changed locations
        optWritePthLoader = 1
Example #24
0
def openMedia(path, prefDict=None):
    """open a media or text file, file type is determined by extension
    will assume that path is to a media file, rather than an exe
    for executable scripts, use launch
    if prefDict is provided, will get app path from there
    keys in this disc must start w/ media type; image, audio, midi, text, ps


    TODO: this should be updated to use application preferences 
    stored in prefTools.py, not here
    """
    path = drawer.pathScrub(path)
    dir, name = os.path.split(path)
    name, ext = extSplit(name)

    # this should be as method of a the pref tools
    # pref object/dict, or a function in this module or drawer
    if ext in imageEXT: fileType = 'image'
    elif ext in audioEXT: fileType = 'audio'
    elif ext in videoEXT: fileType = 'video'
    elif ext in midiEXT: fileType = 'midi'
    elif ext in textEXT or ext in codeEXT: fileType = 'text'
    elif ext in psEXT: fileType = 'ps'
    else: fileType = None

    app = None # default nothing
    
    if prefDict == None and fileType != None: # get default apps
#         if os.name == 'mac': pass # rely on system
        if os.name == 'posix':
            if drawer.isDarwin(): # assume sys default for most
                if fileType in ['audio', 'midi', 'video']: 
                    app = '/Applications/QuickTime Player.app'
            else: # other unix
                if fileType   == 'text' : app = 'more'
                elif fileType == 'audio': app = 'xmms' #'play' should work too
                elif fileType == 'midi' : app = 'playmidi' #
                elif fileType == 'image': app = 'imagemagick'
                elif fileType == 'ps': app = 'gs'   
        else: # win or other
            pass # rely on system
    elif fileType != None: # get from prefDict
        for key in prefDict.keys():
            # match by filetype string leading key and path string
            if key.startswith(fileType) and 'path' in key.lower(): 
                app = prefDict[key] # may be a complete file path, or a name

    if app == '': 
        app = None # if given as empty, convert to none
    elif not drawer.isApp(app): 
        app = None # if not an app any more, drop

#     if os.name == 'mac':     # os9
#         cmdExe = '%s' % path # on mac, just launch txt file, rely on pref
    if os.name == 'posix':
        if drawer.isDarwin():
            if app == None: # no app use system default 
                cmdExe = 'open "%s"' % path 
            elif app.lower().endswith('.app'): # if a .app type app
                cmdExe = 'open -a "%s" "%s"' % (app, path)
            else: # its a unix style command
                cmdExe = '%s %s' % (app, path)
        else: # other unix
            if app == None:
                cmdExe = '%s' % (path)
            else:
                cmdExe = '%s %s' % (app, path)
    else: # win or other, rely on system settings
        cmdExe = '%s' % path # on win, just launch path          
    return launch(cmdExe) # returns None on success