Пример #1
0
    def body(self, guiFrame):

        guiFrame.grid_columnconfigure(1, weight=1)
        guiFrame.grid_rowconfigure(1, weight=1)

        self.usernameEntry = LabeledEntry(guiFrame, 'username')
        self.usernameEntry.grid(row=0)

        self.passwordEntry = LabeledEntry(guiFrame, 'password', show="*")
        self.passwordEntry.grid(row=1)
        
        texts = ['Upload']
        commands = [self.serverUpload]
        buttonList = createDismissHelpButtonList(guiFrame, texts=texts, commands=commands, expands=True)
        buttonList.grid(row=2)
Пример #2
0
    def __init__(self,
                 parent,
                 file_types=None,
                 directory=None,
                 single_callback=None,
                 double_callback=None,
                 select_dir_callback=None,
                 change_dir_callback=None,
                 should_change_dir_callback=None,
                 prompt=None,
                 show_file=True,
                 file='',
                 multiSelect=False,
                 default_dir=None,
                 getRowColor=None,
                 getExtraCell=None,
                 extraHeadings=None,
                 extraJustifies=None,
                 displayExtra=True,
                 manualFileFilter=False,
                 extraTipTexts=None,
                 *args,
                 **kw):

        if file_types is None:
            file_types = [FileType("All", ["*"])]

        if manualFileFilter:
            self.manualFilter = FileType("Manual")
            file_types.append(self.manualFilter)
        else:
            self.manualFilter = None

        if directory is None:
            directory = normalisePath(os.getcwd())

        if extraHeadings is None:
            extraHeadings = ()
        else:
            extraHeadings = tuple(extraHeadings)

        if extraJustifies is None:
            extraJustifies = ()
        else:
            extraJustifies = tuple(extraJustifies)

        if extraHeadings or extraJustifies:
            assert len(extraHeadings) == len(extraJustifies)
            assert getExtraCell

        self.extraHeadings = extraHeadings
        self.extraJustifies = extraJustifies
        self.extraTipTexts = extraTipTexts or []
        self.displayExtra = displayExtra

        Frame.__init__(self, parent, *args, **kw)

        self.file_types = file_types
        self.fileType = file_types[0]
        self.single_callback = single_callback
        self.double_callback = double_callback
        self.select_dir_callback = select_dir_callback
        self.change_dir_callback = change_dir_callback
        self.should_change_dir_callback = should_change_dir_callback
        self.show_file = show_file
        self.directory = None
        self.historyBack = []
        self.historyFwd = []
        self.determineDir(directory)
        self.default_dir = default_dir
        self.getRowColor = getRowColor
        self.getExtraCell = getExtraCell

        self.grid_columnconfigure(0, weight=1)

        row = 0
        if prompt:
            label = Label(self, text=prompt, grid=(row, 0))
            row += 1

        self.grid_rowconfigure(row, weight=1)
        if show_file:
            headings = ('Name', 'Size', 'Date')
            justifies = ('left', 'right', 'right')
            tipTexts = [
                'Name of file, directory or link', 'Size of file in bytes',
                'Date of last modification'
            ]
        else:
            headings = ('Directory', )
            justifies = ('left', )
            tipTexts = ['Name of directory']

        self.normalHeadings = headings
        self.normalJustifies = justifies
        self.normalTipTexts = tipTexts
        headings = headings + extraHeadings
        justifies = justifies + extraJustifies
        tipTexts += [None] * len(extraHeadings)

        self.fileList = ScrolledMatrix(self,
                                       headingList=headings,
                                       justifyList=justifies,
                                       initialRows=10,
                                       callback=self.singleCallback,
                                       doubleCallback=self.doubleCallback,
                                       tipTexts=tipTexts,
                                       multiSelect=multiSelect,
                                       grid=(row, 0))

        row += 1
        tipTexts = [
            'Go to previous location in history',
            'Go forward in location history', 'Go up one directory level',
            'Go to root directory', 'Go to home directory',
            'Make a new directory', 'Refresh directory listing'
        ]

        texts = ['Back', 'Forward', 'Up', 'Top', 'Home', 'New', 'Refresh']
        commands = [
            self.backDir, self.fwdDir, self.upDir, self.topDir, self.homeDir,
            self.createDir, self.updateFileList
        ]

        if self.default_dir:
            texts.append('Default')
            commands.append(self.setDefaultDir)
            tipTexts.append('Set the current directory as the default')

        self.icons = []
        for name in ICON_NAMES:
            icon = Tkinter.PhotoImage(
                file=os.path.join(GFX_DIR, name + '.gif'))
            self.icons.append(icon)

        self.buttons = ButtonList(self,
                                  texts=texts,
                                  commands=commands,
                                  images=self.icons,
                                  grid=(row, 0),
                                  tipTexts=tipTexts)

        if show_file:
            row += 1
            self.file_entry = LabeledEntry(self,
                                           label='File name',
                                           label_width=10,
                                           entry_width=40,
                                           returnCallback=self.setSelectedFile)
            self.file_entry.grid(row=row, column=0, sticky=Tkinter.EW)
        else:
            self.file_entry = None

        row += 1
        self.directory_entry = LabeledEntry(self,
                                            label='Directory',
                                            entry=directory,
                                            label_width=10,
                                            entry_width=40,
                                            returnCallback=self.entryDir)
        self.directory_entry.grid(row=row, column=0, sticky=Tkinter.EW)

        row += 1
        subFrame = Frame(self, grid=(row, 0))
        subFrame.expandGrid(None, 6)

        if show_file:

            label = Label(subFrame, text='File type:', grid=(0, 0))

            type_labels = self.determineTypeLabels()
            self.fileType_menu = PulldownList(
                subFrame,
                callback=self.typeCallback,
                texts=type_labels,
                objects=self.file_types,
                grid=(0, 1),
                tipText='Restrict listed files to selected suffix')

        label = Label(subFrame, text=' Show hidden:', grid=(0, 2))

        self.hidden_checkbutton = CheckButton(
            subFrame,
            text='',
            selected=False,
            callback=self.updateFileList,
            grid=(0, 3),
            tipText='Show hidden files beginning with "." etc.')

        label = Label(subFrame, text='Dir path:', grid=(0, 4))

        self.pathMenu = PulldownList(
            subFrame,
            callback=self.dirCallback,
            objects=range(len(self.dirs)),
            texts=self.dirs,
            index=len(self.dirs) - 1,
            indent='  ',
            prefix=dirsep,
            grid=(0, 5),
            tipText='Directory navigation to current location')

        if show_file and self.manualFilter is not None:
            row += 1
            self.manual_filter_entry = LabeledEntry(
                self,
                label='Manual Select',
                entry=defaultFilter,
                label_width=13,
                entry_width=40,
                returnCallback=self.entryFilter,
                tipText=
                'Path specification with wildcards to select multiple files')
            self.manual_filter_entry.grid(row=row, column=0, sticky=Tkinter.EW)

        self.updateFileList()
        self.updateButtons()

        if file:
            self.setFile(file)
Пример #3
0
class FileSelect(Frame):
    def __init__(self,
                 parent,
                 file_types=None,
                 directory=None,
                 single_callback=None,
                 double_callback=None,
                 select_dir_callback=None,
                 change_dir_callback=None,
                 should_change_dir_callback=None,
                 prompt=None,
                 show_file=True,
                 file='',
                 multiSelect=False,
                 default_dir=None,
                 getRowColor=None,
                 getExtraCell=None,
                 extraHeadings=None,
                 extraJustifies=None,
                 displayExtra=True,
                 manualFileFilter=False,
                 extraTipTexts=None,
                 *args,
                 **kw):

        if file_types is None:
            file_types = [FileType("All", ["*"])]

        if manualFileFilter:
            self.manualFilter = FileType("Manual")
            file_types.append(self.manualFilter)
        else:
            self.manualFilter = None

        if directory is None:
            directory = normalisePath(os.getcwd())

        if extraHeadings is None:
            extraHeadings = ()
        else:
            extraHeadings = tuple(extraHeadings)

        if extraJustifies is None:
            extraJustifies = ()
        else:
            extraJustifies = tuple(extraJustifies)

        if extraHeadings or extraJustifies:
            assert len(extraHeadings) == len(extraJustifies)
            assert getExtraCell

        self.extraHeadings = extraHeadings
        self.extraJustifies = extraJustifies
        self.extraTipTexts = extraTipTexts or []
        self.displayExtra = displayExtra

        Frame.__init__(self, parent, *args, **kw)

        self.file_types = file_types
        self.fileType = file_types[0]
        self.single_callback = single_callback
        self.double_callback = double_callback
        self.select_dir_callback = select_dir_callback
        self.change_dir_callback = change_dir_callback
        self.should_change_dir_callback = should_change_dir_callback
        self.show_file = show_file
        self.directory = None
        self.historyBack = []
        self.historyFwd = []
        self.determineDir(directory)
        self.default_dir = default_dir
        self.getRowColor = getRowColor
        self.getExtraCell = getExtraCell

        self.grid_columnconfigure(0, weight=1)

        row = 0
        if prompt:
            label = Label(self, text=prompt, grid=(row, 0))
            row += 1

        self.grid_rowconfigure(row, weight=1)
        if show_file:
            headings = ('Name', 'Size', 'Date')
            justifies = ('left', 'right', 'right')
            tipTexts = [
                'Name of file, directory or link', 'Size of file in bytes',
                'Date of last modification'
            ]
        else:
            headings = ('Directory', )
            justifies = ('left', )
            tipTexts = ['Name of directory']

        self.normalHeadings = headings
        self.normalJustifies = justifies
        self.normalTipTexts = tipTexts
        headings = headings + extraHeadings
        justifies = justifies + extraJustifies
        tipTexts += [None] * len(extraHeadings)

        self.fileList = ScrolledMatrix(self,
                                       headingList=headings,
                                       justifyList=justifies,
                                       initialRows=10,
                                       callback=self.singleCallback,
                                       doubleCallback=self.doubleCallback,
                                       tipTexts=tipTexts,
                                       multiSelect=multiSelect,
                                       grid=(row, 0))

        row += 1
        tipTexts = [
            'Go to previous location in history',
            'Go forward in location history', 'Go up one directory level',
            'Go to root directory', 'Go to home directory',
            'Make a new directory', 'Refresh directory listing'
        ]

        texts = ['Back', 'Forward', 'Up', 'Top', 'Home', 'New', 'Refresh']
        commands = [
            self.backDir, self.fwdDir, self.upDir, self.topDir, self.homeDir,
            self.createDir, self.updateFileList
        ]

        if self.default_dir:
            texts.append('Default')
            commands.append(self.setDefaultDir)
            tipTexts.append('Set the current directory as the default')

        self.icons = []
        for name in ICON_NAMES:
            icon = Tkinter.PhotoImage(
                file=os.path.join(GFX_DIR, name + '.gif'))
            self.icons.append(icon)

        self.buttons = ButtonList(self,
                                  texts=texts,
                                  commands=commands,
                                  images=self.icons,
                                  grid=(row, 0),
                                  tipTexts=tipTexts)

        if show_file:
            row += 1
            self.file_entry = LabeledEntry(self,
                                           label='File name',
                                           label_width=10,
                                           entry_width=40,
                                           returnCallback=self.setSelectedFile)
            self.file_entry.grid(row=row, column=0, sticky=Tkinter.EW)
        else:
            self.file_entry = None

        row += 1
        self.directory_entry = LabeledEntry(self,
                                            label='Directory',
                                            entry=directory,
                                            label_width=10,
                                            entry_width=40,
                                            returnCallback=self.entryDir)
        self.directory_entry.grid(row=row, column=0, sticky=Tkinter.EW)

        row += 1
        subFrame = Frame(self, grid=(row, 0))
        subFrame.expandGrid(None, 6)

        if show_file:

            label = Label(subFrame, text='File type:', grid=(0, 0))

            type_labels = self.determineTypeLabels()
            self.fileType_menu = PulldownList(
                subFrame,
                callback=self.typeCallback,
                texts=type_labels,
                objects=self.file_types,
                grid=(0, 1),
                tipText='Restrict listed files to selected suffix')

        label = Label(subFrame, text=' Show hidden:', grid=(0, 2))

        self.hidden_checkbutton = CheckButton(
            subFrame,
            text='',
            selected=False,
            callback=self.updateFileList,
            grid=(0, 3),
            tipText='Show hidden files beginning with "." etc.')

        label = Label(subFrame, text='Dir path:', grid=(0, 4))

        self.pathMenu = PulldownList(
            subFrame,
            callback=self.dirCallback,
            objects=range(len(self.dirs)),
            texts=self.dirs,
            index=len(self.dirs) - 1,
            indent='  ',
            prefix=dirsep,
            grid=(0, 5),
            tipText='Directory navigation to current location')

        if show_file and self.manualFilter is not None:
            row += 1
            self.manual_filter_entry = LabeledEntry(
                self,
                label='Manual Select',
                entry=defaultFilter,
                label_width=13,
                entry_width=40,
                returnCallback=self.entryFilter,
                tipText=
                'Path specification with wildcards to select multiple files')
            self.manual_filter_entry.grid(row=row, column=0, sticky=Tkinter.EW)

        self.updateFileList()
        self.updateButtons()

        if file:
            self.setFile(file)

    def updateDisplayExtra(self, displayExtra):

        self.displayExtra = displayExtra
        self.updateFileList()

    def isRootDirectory(self, directory=''):

        if not directory:
            directory = self.directory

        if directory:
            return os.path.dirname(directory) == directory

        return True  # arbitrary

    def updateButtons(self):

        buttons = self.buttons.buttons
        isRoot = self.isRootDirectory

        if self.historyBack:
            buttons[0].enable()
        else:
            buttons[0].disable()

        if self.historyFwd:
            buttons[1].enable()
        else:
            buttons[1].disable()

        if self.directory and not isRoot(self.directory):
            buttons[2].enable()
            buttons[3].enable()
        else:
            buttons[2].disable()
            buttons[3].disable()

        homeDir = self.getHomeDir()
        if homeDir and os.path.isdir(homeDir):
            buttons[4].enable()
        else:
            buttons[4].disable()

    def backDir(self):

        if self.historyBack:
            self.historyFwd.insert(0, self.directory)
            dirName = self.historyBack.pop()
            self.changeDir(dirName, addHistory=False)

    def fwdDir(self):

        if self.historyFwd:
            self.historyBack.append(self.directory)
            dirName = self.historyFwd.pop(0)
            self.changeDir(dirName, addHistory=False)

    def topDir(self):

        if self.directory:
            isRoot = self.isRootDirectory
            dirName = self.directory
            while not isRoot(dirName):
                dirName = joinPath(dirName, os.pardir)

            self.changeDir(dirName)

    def homeDir(self):

        homeDir = self.getHomeDir()
        if homeDir:
            self.changeDir(homeDir)

    def getHomeDir(self):

        return os.environ.get('HOME') or os.environ.get('HOMEPATH')

    def upDir(self):

        self.changeDir(joinPath(self.directory, os.pardir))

    def setDefaultDir(self):

        self.changeDir(self.default_dir)

    def createDir(self):

        from memops.gui.DataEntry import askString

        msg = 'Enter new sub-directory name'
        dirName = askString('New directory', msg, parent=self)
        if dirName:
            dirName = joinPath(self.directory, dirName)
            if os.path.exists(dirName):
                msg = 'Directory "%s" already exists' % dirName
                showError('Directory exists', msg, parent=self)
            else:
                os.mkdir(dirName)
                self.updateFileList()

    def determineTypeLabels(self):

        type_labels = []
        for t in self.file_types:
            s = t.message + ' (' + ', '.join(t.filters) + ')'
            type_labels.append(s)

        return type_labels

    def setFileTypes(self, file_types):

        self.file_types = file_types
        if self.fileType not in file_types:
            self.fileType = file_types[0]
        if self.show_file:
            ind = self.file_types.index(self.fileType)
            type_labels = self.determineTypeLabels()
            self.fileType_menu.setup(type_labels, self.file_types, ind)
            self.updateFileList()

    def determineDir(self, directory):

        directory = normalisePath(directory)

        assert os.path.isdir(directory), '"%s" is not a directory' % directory

        self.prev_directory = self.directory

        if not os.path.isabs(directory):
            if self.directory is None:  # first time around
                directory = joinPath(normalisePath(os.getcwd()), directory)
            else:
                directory = joinPath(self.directory, directory)

        self.directory = directory
        self.dirs = self.directory.split(dirsep)

    def setSelectedFile(self, *event):

        file = self.file_entry.getEntry()
        try:
            self.fileList.selectObject(file)
        except:
            showError('Some err', 'some err')

    def entryDir(self, *event):

        dirName = self.directory_entry.getEntry()
        try:
            self.changeDir(dirName)
        except:
            showError('Not a directory',
                      '"' + dirName + '" is not a directory.')

    def entryFilter(self, *event):

        filterString = self.manual_filter_entry.getEntry()
        filters = [str.strip(x) for x in filterString.split(',')]
        self.manualFilter.filters = filters
        self.fileType = self.manualFilter

        self.setFileTypes(
            self.file_types)  # to trigger update after filter change
        self.updateFileList()

        self.manual_filter_entry.setEntry(filterString)

    def changeDir(self, dirName, addHistory=True):

        if not os.path.isdir(dirName):
            return

        if self.should_change_dir_callback:
            if not self.should_change_dir_callback(dirName):
                return

        oldDir = self.directory

        self.determineDir(dirName)
        self.updateFileList()
        self.directory_entry.setEntry(self.directory)

        if self.change_dir_callback:
            self.change_dir_callback(self.directory)

        nDirs = len(self.dirs)

        self.pathMenu.setup(self.dirs, range(nDirs), index=nDirs - 1)

        if addHistory:
            if oldDir and (self.directory != oldDir):
                self.historyBack.append(oldDir)
            self.historyFwd = []

        self.updateButtons()

    def getEntryInfo(self, entry):

        file = joinPath(self.directory, entry)

        if os.path.islink(file):
            # plain arrow: u' \u2192 '
            entry = entry + u' \u21D2 ' + unicode(os.readlink(file), 'utf-8')
            size = None
            color = '#E0D0C0'

        elif os.path.isdir(file):
            if not self.isRootDirectory(entry):
                entry = entry + dirsep
            size = None
            color = '#C0D0C0'

        else:
            color = '#C0C0D0'

            if self.show_file:
                try:
                    size = str(os.path.getsize(file))
                except:
                    size = None
            else:
                size = None

        try:
            fileTime = self.fileTime(file)
        except:
            fileTime = ''

        return (entry, size, fileTime, color)

    def getDrives(self):

        if isWindowsOS():
            #import win32api
            #drives = win32api.GetLogicalDriveStrings()
            #drives = drives.split('\x00')
            #drives = [normalisePath(drive) for drive in drives if drive]
            #drives.sort()
            # 19 Mar 2012: do not use win32api because not standard
            from ctypes import windll
            import string
            drives = []
            bitmask = windll.kernel32.GetLogicalDrives()
            for letter in string.ascii_uppercase:
                if bitmask & 1:
                    drives.append(letter)
                bitmask >>= 1
            drives = [drive + ':\\' for drive in drives]
            drives = [normalisePath(drive) for drive in drives]
        else:
            drives = []

        return drives

    def updateFileList(self, *extra):

        try:
            if self.directory:
                directory = self.directory
            else:
                directory = dirsep
            entries = self.getFilterFiles(directory)
        except OSError, e:
            showError('OS Error', str(e))
            if self.prev_directory:
                self.directory = None
                self.changeDir(self.prev_directory)
            return

        if self.directory:
            if self.isRootDirectory():
                entries[:0] = [
                    drive for drive in self.getDrives()
                    if drive not in self.directory
                ]
            else:
                entries[:0] = [os.pardir
                               ]  # add parent directory at front of list

        # DJOD: Not elegant, but robust !?!
        showHidden = self.hidden_checkbutton.getSelected()
        show_ent = []
        for entry in entries:
            if not showHidden:
                if not entry.startswith('.'):
                    show_ent.append(entry)
            else:
                show_ent.append(entry)

        # if not show_ent.__contains__('.'):
        #   show_ent.append('.')

        if not show_ent.__contains__('..'):
            show_ent.insert(0, '..')

        entries = show_ent

        textMatrix = []
        colorMatrix = []
        for entryActual in entries:

            (entry, size, fileTime, color) = self.getEntryInfo(entryActual)
            fullEntry = joinPath(directory, entryActual)
            if self.getRowColor:
                color = self.getRowColor(fullEntry)

            if self.displayExtra and self.getExtraCell:
                data = self.getExtraCell(fullEntry)
                headingList = self.normalHeadings + self.extraHeadings
                justifyList = self.normalJustifies + self.extraJustifies
                tipTexts = self.normalTipTexts + self.extraTipTexts
            else:
                data = ()
                headingList = self.normalHeadings
                justifyList = self.normalJustifies
                tipTexts = self.normalTipTexts
                # in case we had sorted on a now removed line :
                self.fileList.lastSortLine = None

            if self.show_file:
                text = [entry, size, fileTime]
            else:
                text = [
                    entry,
                ]
            text = text + list(data)

            textMatrix.append(text)
            numCols = len(headingList)
            colorMatrix.append(numCols * [color])

        self.fileList.update(objectList=entries,
                             textMatrix=textMatrix,
                             colorMatrix=colorMatrix,
                             headingList=headingList,
                             justifyList=justifyList,
                             tipTexts=tipTexts)
Пример #4
0
  def __init__(self, parent, file_types = None, directory = None,
               single_callback = None, double_callback = None,
               prompt = None, show_file = True, file = '', multiSelect=False,
               default_dir = None, getRowColor = None,
               getExtraCell = None, extraHeadings = None, extraJustifies = None,
               displayExtra = True, *args, **kw):

    if file_types is None:
      file_types = [ FileType("All", ["*"]) ]

    if directory is None:
      directory = normalisePath(os.getcwd())

    if extraHeadings is None:
      extraHeadings = ()
    else:
      extraHeadings = tuple(extraHeadings)

    if extraJustifies is None:
      extraJustifies = ()
    else:
      extraJustifies = tuple(extraJustifies)

    if extraHeadings or extraJustifies:
      assert len(extraHeadings) == len(extraJustifies)
      assert getExtraCell

    self.extraHeadings = extraHeadings
    self.extraJustifies = extraJustifies
    self.displayExtra = displayExtra

    Frame.__init__(self, parent, *args, **kw)

    self.file_types = file_types
    self.fileType = file_types[0]
    self.single_callback = single_callback
    self.double_callback = double_callback
    self.show_file = show_file
    self.directory = None
    self.historyBack = []
    self.historyFwd = []
    self.determineDir(directory)
    self.default_dir = default_dir
    self.getRowColor = getRowColor
    self.getExtraCell = getExtraCell

    
    self.grid_columnconfigure(0, weight=1)

    row = 0
    if prompt:
      label = Label(self, text=prompt, grid=(row,0))
      row += 1

    self.grid_rowconfigure(row, weight=1)
    if show_file:
      headings = ('Name', 'Size', 'Date')
      justifies = ('left','right','right')
    else:
      headings = ('Directory',)
      justifies = ('left',)
    self.normalHeadings = headings
    self.normalJustifies = justifies
    headings = headings + extraHeadings
    justifies = justifies + extraJustifies

    self.fileList = ScrolledMatrix(self, headingList=headings, justifyList=justifies,
                                    initialRows=10, callback=self.singleCallback,
                                    doubleCallback=self.doubleCallback,
                                    multiSelect=multiSelect, grid=(row,0))

    row += 1
    texts = ['Back', 'Up', 'Forward', 'Top', 'Home', 'New', 'Refresh']
    commands = [self.backDir, self.fwdDir, self.upDir, self.topDir,
                self.homeDir, self.createDir, self.updateFileList ]

    if self.default_dir:
      texts.append('Default')
      commands.append(self.setDefaultDir)
      
    self.icons = []
    for name in ICON_NAMES:
      icon = Tkinter.PhotoImage(file=os.path.join(GFX_DIR,name+'.gif'))
      self.icons.append(icon)
      
    self.buttons = ButtonList(self, texts=texts, commands=commands,
                              images=self.icons, grid=(row,0))


    if show_file:
      row += 1
      self.file_entry = LabeledEntry(self, label='File name',
                              label_width=10, entry_width=40,
                              returnCallback=self.setSelectedFile)
      self.file_entry.grid(row=row, column=0, sticky=Tkinter.EW)
    else:
      self.file_entry = None

    row += 1
    self.directory_entry = LabeledEntry(self, label='Directory',
                                        entry = directory,
                                        label_width=10, entry_width=40,
                                        returnCallback=self.entryDir)
    self.directory_entry.grid(row=row, column=0, sticky=Tkinter.EW)


    row += 1
    subFrame = Frame(self, grid=(row,0))
    subFrame.expandGrid(None,6)

    if show_file:

      label = Label(subFrame, text='File type:', grid=(0,0))

      type_labels = self.determineTypeLabels()
      self.fileType_menu = PulldownList(subFrame, callback=self.typeCallback,
                                        texts=type_labels, objects=self.file_types,
                                        grid=(0,1))

    label = Label(subFrame, text=' Show hidden:', grid=(0,2))

    self.hidden_checkbutton = CheckButton(subFrame, text='', selected=False,
                                          callback=self.updateFileList, grid=(0,3))

    label = Label(subFrame, text='Dir path:', grid=(0,4))

    self.pathMenu = PulldownList(subFrame, callback=self.dirCallback,
                                 objects=range(len(self.dirs)),
                                 texts=self.dirs, index=len(self.dirs)-1,
                                 indent='  ', prefix=dirsep, grid=(0,5))

    self.updateFileList()
    self.updateButtons()

    if file:
      self.setFile(file)
Пример #5
0
class FileSelect(Frame):

  def __init__(self, parent, file_types = None, directory = None,
               single_callback = None, double_callback = None,
               prompt = None, show_file = True, file = '', multiSelect=False,
               default_dir = None, getRowColor = None,
               getExtraCell = None, extraHeadings = None, extraJustifies = None,
               displayExtra = True, *args, **kw):

    if file_types is None:
      file_types = [ FileType("All", ["*"]) ]

    if directory is None:
      directory = normalisePath(os.getcwd())

    if extraHeadings is None:
      extraHeadings = ()
    else:
      extraHeadings = tuple(extraHeadings)

    if extraJustifies is None:
      extraJustifies = ()
    else:
      extraJustifies = tuple(extraJustifies)

    if extraHeadings or extraJustifies:
      assert len(extraHeadings) == len(extraJustifies)
      assert getExtraCell

    self.extraHeadings = extraHeadings
    self.extraJustifies = extraJustifies
    self.displayExtra = displayExtra

    Frame.__init__(self, parent, *args, **kw)

    self.file_types = file_types
    self.fileType = file_types[0]
    self.single_callback = single_callback
    self.double_callback = double_callback
    self.show_file = show_file
    self.directory = None
    self.historyBack = []
    self.historyFwd = []
    self.determineDir(directory)
    self.default_dir = default_dir
    self.getRowColor = getRowColor
    self.getExtraCell = getExtraCell

    
    self.grid_columnconfigure(0, weight=1)

    row = 0
    if prompt:
      label = Label(self, text=prompt, grid=(row,0))
      row += 1

    self.grid_rowconfigure(row, weight=1)
    if show_file:
      headings = ('Name', 'Size', 'Date')
      justifies = ('left','right','right')
    else:
      headings = ('Directory',)
      justifies = ('left',)
    self.normalHeadings = headings
    self.normalJustifies = justifies
    headings = headings + extraHeadings
    justifies = justifies + extraJustifies

    self.fileList = ScrolledMatrix(self, headingList=headings, justifyList=justifies,
                                    initialRows=10, callback=self.singleCallback,
                                    doubleCallback=self.doubleCallback,
                                    multiSelect=multiSelect, grid=(row,0))

    row += 1
    texts = ['Back', 'Up', 'Forward', 'Top', 'Home', 'New', 'Refresh']
    commands = [self.backDir, self.fwdDir, self.upDir, self.topDir,
                self.homeDir, self.createDir, self.updateFileList ]

    if self.default_dir:
      texts.append('Default')
      commands.append(self.setDefaultDir)
      
    self.icons = []
    for name in ICON_NAMES:
      icon = Tkinter.PhotoImage(file=os.path.join(GFX_DIR,name+'.gif'))
      self.icons.append(icon)
      
    self.buttons = ButtonList(self, texts=texts, commands=commands,
                              images=self.icons, grid=(row,0))


    if show_file:
      row += 1
      self.file_entry = LabeledEntry(self, label='File name',
                              label_width=10, entry_width=40,
                              returnCallback=self.setSelectedFile)
      self.file_entry.grid(row=row, column=0, sticky=Tkinter.EW)
    else:
      self.file_entry = None

    row += 1
    self.directory_entry = LabeledEntry(self, label='Directory',
                                        entry = directory,
                                        label_width=10, entry_width=40,
                                        returnCallback=self.entryDir)
    self.directory_entry.grid(row=row, column=0, sticky=Tkinter.EW)


    row += 1
    subFrame = Frame(self, grid=(row,0))
    subFrame.expandGrid(None,6)

    if show_file:

      label = Label(subFrame, text='File type:', grid=(0,0))

      type_labels = self.determineTypeLabels()
      self.fileType_menu = PulldownList(subFrame, callback=self.typeCallback,
                                        texts=type_labels, objects=self.file_types,
                                        grid=(0,1))

    label = Label(subFrame, text=' Show hidden:', grid=(0,2))

    self.hidden_checkbutton = CheckButton(subFrame, text='', selected=False,
                                          callback=self.updateFileList, grid=(0,3))

    label = Label(subFrame, text='Dir path:', grid=(0,4))

    self.pathMenu = PulldownList(subFrame, callback=self.dirCallback,
                                 objects=range(len(self.dirs)),
                                 texts=self.dirs, index=len(self.dirs)-1,
                                 indent='  ', prefix=dirsep, grid=(0,5))

    self.updateFileList()
    self.updateButtons()

    if file:
      self.setFile(file)

  def updateDisplayExtra(self, displayExtra):

    self.displayExtra = displayExtra
    self.updateFileList()

  def isRootDirectory(self, directory = ''):

    if not directory:
      directory = self.directory

    if directory:
      return os.path.dirname(directory) == directory

    return True  # arbitrary

  def updateButtons(self):
  
    buttons = self.buttons.buttons
    isRoot = self.isRootDirectory

    if self.historyBack:
      buttons[0].enable()
    else:  
      buttons[0].disable()
    
    if self.historyFwd:
      buttons[1].enable()
    else:  
      buttons[1].disable()
    
    if self.directory and not isRoot(self.directory):
      buttons[2].enable()
      buttons[3].enable()
    else:  
      buttons[2].disable()
      buttons[3].disable()
   
    homeDir = self.getHomeDir()
    if homeDir and os.path.isdir(homeDir):
      buttons[4].enable()
    else:  
      buttons[4].disable()

  def backDir(self):

    if self.historyBack:
      self.historyFwd.insert(0, self.directory)
      dirName = self.historyBack.pop()
      self.changeDir(dirName, addHistory=False)

  def fwdDir(self):

    if self.historyFwd:
      self.historyBack.append(self.directory)
      dirName = self.historyFwd.pop(0)
      self.changeDir(dirName, addHistory=False)
  
  def topDir(self):
  
    if self.directory:
      isRoot = self.isRootDirectory
      dirName = self.directory
      while not isRoot(dirName):
        dirName = joinPath(dirName, os.pardir)
  
      self.changeDir(dirName)
  
  def homeDir(self):
  
    homeDir = self.getHomeDir()
    if homeDir:
      self.changeDir(homeDir)

  def getHomeDir(self):
  
    return os.environ.get('HOME') or os.environ.get('HOMEPATH')

  def upDir(self):

    self.changeDir(joinPath(self.directory, os.pardir))

  def setDefaultDir(self):

    self.changeDir(self.default_dir)

  def createDir(self):

    from memops.gui.DataEntry import askString
    
    msg = 'Enter new sub-directory name'
    dirName = askString('New directory', msg, parent=self)
    if dirName:
      dirName = joinPath(self.directory, dirName)
      if os.path.exists(dirName):
        msg = 'Directory "%s" already exists' % dirName
        showError('Directory exists', msg, parent=self)
      else:
        os.mkdir(dirName)
        self.updateFileList()

  def determineTypeLabels(self):

    type_labels = []
    for t in self.file_types:
      s = t.message + ' (' + ', '.join(t.filters) + ')'
      type_labels.append(s)

    return type_labels

  def setFileTypes(self, file_types):

    self.file_types = file_types
    if self.fileType not in file_types:
      self.fileType = file_types[0]

    if self.show_file:
      ind = self.file_types.index(self.fileType)
      type_labels = self.determineTypeLabels()
      self.fileType_menu.setup(type_labels, self.file_types, ind)
      self.updateFileList()

  def determineDir(self, directory):

    directory = normalisePath(directory)

    assert os.path.isdir(directory), '"%s" is not a directory' % directory

    self.prev_directory = self.directory

    if not os.path.isabs(directory):
      if self.directory is None: # first time around
        directory = joinPath(normalisePath(os.getcwd()), directory)
      else:
        directory = joinPath(self.directory, directory)

    self.directory = directory
    self.dirs = self.directory.split(dirsep)

  def setSelectedFile(self, *event):

    file = self.file_entry.getEntry()
    try:
      self.fileList.selectObject(file)
    except:
      showError('Some err', 'some err')

  def entryDir(self, *event):

    dirName = self.directory_entry.getEntry()
    try:
      self.changeDir(dirName)
    except:
      showError('Not a directory', '"' + dirName + '" is not a directory.')

  def changeDir(self, dirName, addHistory=True):

    if not os.path.isdir(dirName):
      return

    oldDir = self.directory


    self.determineDir(dirName)
    self.updateFileList()
    self.directory_entry.setEntry(self.directory)
    
    nDirs = len(self.dirs)
    
    self.pathMenu.setup(self.dirs, range(nDirs), index=nDirs-1)
    
    if addHistory:
      if oldDir and (self.directory != oldDir):
        self.historyBack.append(oldDir)
      self.historyFwd = []
    
    self.updateButtons()

  def getEntryInfo(self, entry):

    file = joinPath(self.directory, entry)

    if os.path.islink(file):
      # plain arrow: u' \u2192 '
      entry = entry + u' \u21D2 ' + os.readlink(file)
      size  = None
      color = '#E0D0C0'
      
    elif os.path.isdir(file):
      if not self.isRootDirectory(entry):
        entry = entry + dirsep
      size = None
      color = '#C0D0C0'
      
    else:
      color = '#C0C0D0'
      
      if self.show_file:
        try:
          size = str(os.path.getsize(file))
        except:
          size = None
      else:
        size = None
        
    try:
      fileTime = self.fileTime(file)
    except:
      fileTime = ''

    return (entry, size, fileTime, color)

  def getDrives(self):

    if isWindowsOS():
      import win32api
      drives = win32api.GetLogicalDriveStrings()
      drives = drives.split('\x00')
      drives = [normalisePath(drive) for drive in drives if drive]
      drives.sort()
    else:
      drives = []

    return drives

  def updateFileList(self, *extra):

    try:
      if self.directory:
        dir = self.directory
      else:
        dir = dirsep
      entries = self.getFilterFiles(dir)
    except OSError, e:
      showError('OS Error', str(e))
      if self.prev_directory:
        self.directory = None
        self.changeDir(self.prev_directory)
      return
    entries.sort()
    if self.directory:
      if self.isRootDirectory():
        entries[:0] = [drive for drive in self.getDrives() if drive not in self.directory]
      else:
        entries[:0] = [os.pardir] # add parent directory at front of list

    # DJOD: Not elegant, but robust !?!
    show_ent = []
    for entry in entries:
      if not self.hidden_checkbutton.getSelected():
        if not entry.startswith('.'):
          show_ent.append( entry )
      else:
        show_ent.append( entry )

    # if not show_ent.__contains__('.'):
    #   show_ent.append('.')

    if not show_ent.__contains__('..'):
      show_ent.append('..')

    entries = show_ent
    entries.sort()

    textMatrix = []
    colorMatrix = []
    for entry in entries:

      (entry, size, fileTime, color) = self.getEntryInfo(entry)
      fullEntry = joinPath(dir, entry)
      if self.getRowColor:
        color = self.getRowColor(fullEntry)

      if self.displayExtra and self.getExtraCell:
        data = self.getExtraCell(fullEntry)
        headingList = self.normalHeadings + self.extraHeadings
        justifyList = self.normalJustifies + self.extraJustifies
      else:
        data = ()
        headingList = self.normalHeadings
        justifyList = self.normalJustifies

      if self.show_file:
        text = [entry, size, fileTime]
      else:
        text = [entry,]
      text = text + list(data)

      textMatrix.append(text)
      numCols = len(headingList)
      colorMatrix.append(numCols*[color])

    self.fileList.update(objectList=entries, textMatrix=textMatrix, colorMatrix=colorMatrix,
                          headingList=headingList, justifyList=justifyList, resetScrollbars=True)
Пример #6
0
class EditPeakDrawParamsPopup(BasePopup):
  """
  **Control How Peak Symbols and Annotations Are Drawn**
  
  This popup window controls the display of picked peak positions within
  spectrum windows and also how their annotations are displayed in
  many of the tables throughout the rest of Analysis.

  **Peak Annotations**

  The "Annotation Style" tab, as the name suggests, controls which bits of
  information go to form the assignment annotation that is used to label peaks
  in spectra and when listing their identities in tables. The user can toggle
  various options on or off to dictate what should be included. With no options
  selected at all peaks will show only resonance number information like
  "[123],[45]", irrespective of any atomic assignments. Switching the atom
  assignments on will substitute the atom and residue name for  the resonance
  names. The spin system toggle is used to control the display of spin system
  numbers like the curly bracketed numbers of "{89}[123],[45]" or a residue name
  if the spin system is assigned, although the atom assignment option will also
  give any residue name. The chain and molecular system toggles are used when
  there are several sequences in the assignment that need to be distinguished, so
  that you can identify "A25LsyH,N" separately to "B25LysH,N" or even
  "MS2:A25LysH,N". The details toggle allows the user to contribute to peak
  annotations; such details are set in the relevant column of the peak tables
  (e.g. `Selected Peaks`_)or the "Peak::Set details" option of the right-click
  window menu. The last "Minimal Annotations" option is special because it gives
  a quick replacement for spectrum annotations that overrides all other settings,
  for example "25LysH,N" becomes "25K", which is useful to reduce clutter when
  printing out an HSQC.

  It should be noted that, with the exception of the "Minimal Annotations"
  option, any changes to the annotation options for existing peak assignments
  will not be visible until [Update Full Annotations] is pressed, which can take
  a while to update if the number of peaks in the project is large. Any new
  assignments will observe the current settings.

  **Draw Size**
  
  The second tab controls how the peak cross symbols, which indicate the pick
  position, are drawn in the spectrum display. Here, the user has four choices:
  the default is to use a fixed number of screen pixels, so that all symbols are
  the same size, irrespective of zoom level; uniform size in ppm (with the 
  appropriate values for each isotope set in the lower table that appears)
  allows the peak symbol maintain a constant size relative to the contours, and
  thus differ in on-screen size according to the contour zoom level; and two
  choices for a "scaled" size where the peak symbol is larger or smaller
  depending on the intensity of the peak, either relative to its peak list or an
  absolute globally applied value.

  **Figure of Merit**

  The last "Merit Symbols" tab allows the user to add textual markers to a peak
  depending on the figure-of-merit value, which is an indication of reliability
  (although the precise context is at the discretion of the user). The merit
  value for a peak is set via the peak tables or the "Peak::Set merit" option of
  the right-click window menu. Aside from display purposes the merit value is
  used at a few points throughout Analysis to optionally exclude peaks. Typically
  a peak with a merit value of 0.0 may be ignored during certain analyses, e.g.
  for making NOE derived distance restraints.

  **Caveats & Tips**

  When assigning peaks via the `Assignment Panel`_ the resonance annotation will
  always display spin system information, given that this grouping is critical
  to assignment, but the chain and atom assignment will reflect the peak
  display, and thus these details may be missing if unset in this Draw
  Parameters popup.


  .. _`Assignment Panel`: EditAssignmentPopup.html
  .. _`Selected Peaks`: SelectedPeaksPopup.html
  """
  def __init__(self, parent, *args, **kw):
 
    BasePopup.__init__(self, parent=parent, title='Peak : Draw Parameters', **kw)

  def body(self, guiParent):
 
    self.geometry('380x250')

    analysisProject = self.analysisProject

    self.smallFont    = '-schumacher-clean-medium-r-normal--14-140-75-75-c-70-iso646.1991-irv'
    guiParent.grid_columnconfigure(0, weight=1)
    guiParent.grid_rowconfigure(0, weight=1)
    
    row = 0
    
    tipTexts = ['Options specifying how peak annotations are drawn in spectrum windows and in tables etc.',
                'Options to specify how large the peak crosses/symbols are drawn in spectrum windows',
                'Enables the user to specify special symbols to annotate peaks according to quality']
    options=['Annotation Style','Draw Size','Merit Symbols']
    tabbedFrame = TabbedFrame(guiParent, options=options,
                              grid=(row,0), tipTexts=tipTexts)
    
    frame1, frame2, frame3 = tabbedFrame.frames
    frame1.expandGrid(7,1)
    frame2.expandGrid(2,0)
    frame3.expandGrid(3,1)
    
    self.drawFrame = frame2
    
 
    # Annotations

    tipText = 'Whether to show unassigned spin system numbers like "{123}" in peak annotations; does not affect the display of full residue assignments'
    self.spinSystAnnoSelect = CheckButton(frame1, callback=self.setSpinSystAnno, grid=(0,0),
                                          selected=analysisProject.doSpinSystemAnnotations,
                                          tipText=tipText)
    spinSystAnnoLabel = Label(frame1, text='Spin System Info', grid=(0,1))

    tipText = 'Whether to show assigned atom names in peak annotations rather than resonance numbers, e.g. "21LeuH,N" or "21Leu[55],[56]"'
    self.resonanceAnnoSelect = CheckButton(frame1, callback=self.setResonanceAnno, grid=(1,0),
                                           selected=analysisProject.doAssignmentAnnotations,
                                           tipText=tipText)
    resonanceAnnoLabel = Label(frame1, text='Atom Assignment', grid=(1,1))

    tipText = 'Whether to show the molecular chain code letter in peak annotations, e.g. "21LeuH,N" or "A21LeuH,N"'
    self.chainAnnoSelect = CheckButton(frame1, callback=self.setChainAnno, grid=(2,0),
                                       selected=analysisProject.doChainAnnotations,
                                       tipText=tipText)
    chainAnnoLabel = Label(frame1, text='Chain Assignment', grid=(2,1))

    tipText = 'Whether to show the molecular system code name in peak annotations, e.g. "MS1:21LeuH,N" or "21LeuH,N"'
    self.molSysAnnoSelect = CheckButton(frame1, callback=self.setMolSysAnno, grid=(3,0),
                                       selected=analysisProject.doMolSysAnnotations,
                                       tipText=tipText)
    molSysAnnoLabel = Label(frame1, text='Molecular System', grid=(3,1))

    tipText = 'Whether to show a symbol indicating the quality of a peak; these symbols must be set in the "Merit Symbols" tab'
    self.meritAnnoSelect = CheckButton(frame1, callback=self.setMeritAnno, grid=(4,0),
                                       selected=analysisProject.doMeritAnnotations,
                                       tipText=tipText)
    meritAnnoLabel = Label(frame1, text='Merit Symbol', grid=(4,1))

    tipText = 'Whether to show the details text for a peak in spectrum windows (set in the peak tables)'
    self.detailAnnoSelect = CheckButton(frame1, callback=self.setDetailAnno, grid=(5,0),
                                        selected=analysisProject.doDetailAnnotations,
                                        tipText=tipText)
    detailAnnoLabel = Label(frame1, text='Details', grid=(5,1))

    tipText = 'Whether to ignore above settings, and use a short peak annotation using only residue numbers and one-letter codes, e.g. "21L"'
    self.simpleAnnoSelect = CheckButton(frame1, callback=self.setSimpleAnnotations,
                                        grid=(6,0), tipText=tipText,
                                        selected=analysisProject.doMinimalAnnotations)
    simpleAnnoLabel = Label(frame1, text='Minimal Annotations (overriding option)', grid=(6,1))

    tipText = 'Manually cause an update of all peak annotations; may take some time but recommended to see the immediate effect of changes'
    self.updateFullAnnoButton = Button(frame1, text='Update Full Annotations',
                                       command=self.updateAnnotations, grid=(7,0),
                                       gridSpan=(1,2), sticky='nsew', tipText=tipText)

    # Size
    
    tipText = 'The width of the displayed peak cross/symbol in screen pixels; the number of pixels from the centre point'
    self.pixel_entry = LabeledEntry(frame2, label='Number of pixels',
                                    entry=analysisProject.peakPixelSize,
                                    returnCallback=self.updatePixelSize,
                                    entry_width=8, tipText=tipText)

    tipText = 'Specifies which peak height corresponds to the specific per-isotope ppm size; actual peak symbol sizes are scaled, according to relative height (and volume)'
    self.intensity_entry = LabeledEntry(frame2, label='Height scale',
                                        entry=analysisProject.peakIntensityScale,
                                        returnCallback=self.updateIntensityScale,
                                        entry_width=8, tipText=tipText)
                                        
    tipText = 'Specifies which peak volume corresponds to the specific per-isotope ppm size; actual peak symbol sizes are scaled, according to relative volume (and height)'
    self.volume_entry = LabeledEntry(frame2, label='Volume scale',
                                     entry=analysisProject.peakVolumeScale,
                                     returnCallback=self.updateVolumeScale,
                                     entry_width=8, tipText=tipText)

    tipTexts = ['The kind of nuclear isotope, as found on the axis if a spectrum window',
                'The ppm width of the peak cross/symbol along the specific kind of isotope axis']
    headings = ['Isotope', 'Peak Size (ppm)']
    self.peakSizeEntry = FloatEntry(self, returnCallback=self.setPeakSize, width=10)
    editWidgets = [None, self.peakSizeEntry]
    editGetCallbacks = [None, self.getPeakSize]
    editSetCallbacks = [None, self.setPeakSize]
    self.peak_size_table = ScrolledMatrix(frame2, headingList=headings,
                                          initialRows=5, editWidgets=editWidgets,
                                          editGetCallbacks=editGetCallbacks,
                                          editSetCallbacks=editSetCallbacks,
                                          tipTexts=tipTexts)

    self.selected_method = None
    self.method_widgets = {}
    self.method_widgets[peak_draw_methods[0]] = [self.pixel_entry]
    self.method_widgets[peak_draw_methods[1]] = [self.peak_size_table]
    self.method_widgets[peak_draw_methods[2]] = [self.intensity_entry, self.volume_entry, self.peak_size_table]
    self.method_widgets[peak_draw_methods[3]] = [self.peak_size_table]
    self.method_widgets[peak_draw_methods[4]] = []
    self.method_widgets[peak_draw_methods[5]] = []

    selected_index = peak_draw_methods.index(analysisProject.peakDrawMethod)
    tipText = 'Selects which mode to use for determining peak cross/symbol sizes; a fixed pixel/ppm value or scaled by intensity for all peaks or just one peak list'
    self.method_menu = PulldownList(frame2, texts=peak_draw_methods, gridSpan=(1,2), 
                                    grid=(0,0), tipText=tipText,
                                    callback=self.setMethod, index=selected_index)
    
    # Merit symbol
    
    label = Label(frame3, text='Good merit (>0.66)', grid=(0,0))
    tipText = 'Although typically blank, sets a symbol to display for good quality peaks (merit value > 0.66), if the relevant option is selected in the "Annotation Style" tab'
    self.meritGoodEntry = Entry(frame3, text=analysisProject.meritAnnotationGood,
                                width=8, grid=(0,1), sticky='ew', tipText=tipText,
                                returnCallback=self.setMeritAnnotation)

    label = Label(frame3, text='Medium merit', grid=(1,0))
    tipText = 'Sets a symbol to display for mediocre quality peaks (merit value between 0.34 & 0.66), if the relevant option is selected in the "Annotation Style" tab'
    self.meritUglyEntry = Entry(frame3, text=analysisProject.meritAnnotationMediocre,
                                width=8, grid=(1,1), sticky='ew', tipText=tipText,
                                returnCallback=self.setMeritAnnotation)

    label = Label(frame3, text='Poor merit (<0.34)', grid=(2,0))
    tipText = 'Sets a symbol to display for poor quality peaks (merit value < 0.34), if the relevant option is selected in the "Annotation Style" tab'
    self.meritBadEntry  = Entry(frame3, text=analysisProject.meritAnnotationBad,
                                width=8, grid=(2,1), sticky='ew', tipText=tipText,
                                returnCallback=self.setMeritAnnotation)

    tipText = 'Commit the changes to the merit symbols; this will not automatically update the display - see the "Annotation Style" tab'
    setButton = Button(frame3, text='Set symbols', command=self.setMeritAnnotation,
                       grid=(3,0), gridSpan=(1,2), tipText=tipText, sticky='nsew')

    buttons = UtilityButtonList(tabbedFrame.sideFrame, grid=(0,0), 
                                helpUrl=self.help_url, sticky='e')

    self.updatePeakSizeTable()
    self.updateMethod()

    for func in ('__init__', 'delete', ''):                                           
      self.registerNotify(self.updatePeakSizeTable, 'ccpnmr.Analysis.AxisType', func)

    self.registerNotify(self.changedDoSpinSystemAnnotations, 'ccpnmr.Analysis.AnalysisProject', 'setDoSpinSystemAnnotations')
    self.registerNotify(self.changedDoAssignmentAnnotations, 'ccpnmr.Analysis.AnalysisProject', 'setDoAssignmentAnnotations')
    self.registerNotify(self.changedDoChainAnnotations, 'ccpnmr.Analysis.AnalysisProject', 'setDoChainAnnotations')
    self.registerNotify(self.changedPeakDrawMethod, 'ccpnmr.Analysis.AnalysisProject', 'setPeakDrawMethod')
    self.registerNotify(self.changedPeakPixelSize, 'ccpnmr.Analysis.AnalysisProject', 'setPeakPixelSize')

  def open(self):
  
    self.updatePeakSizeTable()
    self.updateMethod()
    BasePopup.open(self)
    

  def close(self):
  
    self.setMeritAnnotation()
    BasePopup.close(self)

  def destroy(self):
 
    for func in ('__init__', 'delete', ''):                                           
      self.unregisterNotify(self.updatePeakSizeTable, 'ccpnmr.Analysis.AxisType', func)

    self.unregisterNotify(self.changedDoSpinSystemAnnotations, 'ccpnmr.Analysis.AnalysisProject', 'setDoSpinSystemAnnotations')
    self.unregisterNotify(self.changedDoAssignmentAnnotations, 'ccpnmr.Analysis.AnalysisProject', 'setDoAssignmentAnnotations')
    self.unregisterNotify(self.changedDoChainAnnotations, 'ccpnmr.Analysis.AnalysisProject', 'setDoChainAnnotations')
    self.unregisterNotify(self.changedPeakDrawMethod, 'ccpnmr.Analysis.AnalysisProject', 'setPeakDrawMethod')
    self.unregisterNotify(self.changedPeakPixelSize, 'ccpnmr.Analysis.AnalysisProject', 'setPeakPixelSize')

    BasePopup.destroy(self)

  def setMeritAnnotation(self, *opt):
    
    analysisProject = self.analysisProject
    analysisProject.meritAnnotationGood     = self.meritGoodEntry.get() or None
    analysisProject.meritAnnotationMediocre = self.meritUglyEntry.get() or None
    analysisProject.meritAnnotationBad      = self.meritBadEntry.get() or None
   
  def updateAnnotations(self):
  
    self.setMeritAnnotation()
    refreshPeakAnnotations(self.project)
  
  def setSimpleAnnotations(self, trueOrFalse):
  
    self.analysisProject.doMinimalAnnotations = trueOrFalse

  def setSpinSystAnno(self, trueOrFalse):
  
    self.analysisProject.doSpinSystemAnnotations = trueOrFalse

  def setResonanceAnno(self, trueOrFalse):
  
    self.analysisProject.doAssignmentAnnotations = trueOrFalse
    
  def setMolSysAnno(self, trueOrFalse):
  
    self.analysisProject.doMolSysAnnotations = trueOrFalse
    
  def setChainAnno(self, trueOrFalse):
  
    self.analysisProject.doChainAnnotations = trueOrFalse
    
  def setMeritAnno(self, trueOrFalse):

    self.analysisProject.doMeritAnnotations = trueOrFalse

  def setDetailAnno(self, trueOrFalse):   

    self.analysisProject.doDetailAnnotations = trueOrFalse
    
  def changedDoSpinSystemAnnotations(self, analysisProject):

    self.spinSystAnnoSelect.set(analysisProject.doSpinSystemAnnotations)

  def changedDoAssignmentAnnotations(self, analysisProject):

    self.resonanceAnnoSelect.set(analysisProject.doAssignmentAnnotations)

  def changedDoChainAnnotations(self, analysisProject):

    self.chainAnnoSelect.set(analysisProject.doChainAnnotations)

  def changedPeakDrawMethod(self, analysisProject):
 
    self.updateMethod()

  def changedPeakPixelSize(self, analysisProject):
 
    self.pixel_entry.setEntry(analysisProject.peakPixelSize)

  def setMethod(self, text):
  
    self.analysisProject.peakDrawMethod = text

  def updateMethod(self):

    selected = self.analysisProject.peakDrawMethod
    if selected == self.selected_method:
      return

    self.unsetMethod()

    widgets = self.method_widgets[selected]

    row = 1
    for widget in widgets:
      if isinstance(widget, ScrolledMatrix):
        widget.grid(row=row, column=0, sticky='nsew')
        self.drawFrame.grid_rowconfigure(row, weight=1)
      else:
        widget.grid(row=row, column=0, sticky='new')
        self.drawFrame.grid_rowconfigure(row, weight=0)
  
      row += 1

    self.selected_method = selected

  def unsetMethod(self):

    selected = self.selected_method
    if selected is None:
      return

    widgets = self.method_widgets[selected]

    for widget in widgets:
      widget.grid_forget()

    self.selected_method = None

  def updatePeakSizeTable(self, *extra):
 
    axisTypes = self.parent.getAxisTypes()
 
    textMatrix = []
    n = 0
    for axisType in axisTypes:
      if (len(axisType.isotopeCodes) == 1):
        n = n + 1
        text = []
        text.append(', '.join(axisType.isotopeCodes))
        text.append(axisType.peakSize)
        textMatrix.append(text)
 
    self.peak_size_table.update(objectList=axisTypes, textMatrix=textMatrix)

  def getPeakSize(self, axisType):
 
    self.peakSizeEntry.set(axisType.peakSize)
 
  def setPeakSize(self, *extra):
 
    axisType = self.getAxisType()
    try:
      axisType.peakSize = self.peakSizeEntry.get()
    except Implementation.ApiError, e:
      showError('Setting peak size', e.error_msg, parent=self)
Пример #7
0
  def body(self, guiParent):
 
    self.geometry('380x250')

    analysisProject = self.analysisProject

    self.smallFont    = '-schumacher-clean-medium-r-normal--14-140-75-75-c-70-iso646.1991-irv'
    guiParent.grid_columnconfigure(0, weight=1)
    guiParent.grid_rowconfigure(0, weight=1)
    
    row = 0
    
    tipTexts = ['Options specifying how peak annotations are drawn in spectrum windows and in tables etc.',
                'Options to specify how large the peak crosses/symbols are drawn in spectrum windows',
                'Enables the user to specify special symbols to annotate peaks according to quality']
    options=['Annotation Style','Draw Size','Merit Symbols']
    tabbedFrame = TabbedFrame(guiParent, options=options,
                              grid=(row,0), tipTexts=tipTexts)
    
    frame1, frame2, frame3 = tabbedFrame.frames
    frame1.expandGrid(7,1)
    frame2.expandGrid(2,0)
    frame3.expandGrid(3,1)
    
    self.drawFrame = frame2
    
 
    # Annotations

    tipText = 'Whether to show unassigned spin system numbers like "{123}" in peak annotations; does not affect the display of full residue assignments'
    self.spinSystAnnoSelect = CheckButton(frame1, callback=self.setSpinSystAnno, grid=(0,0),
                                          selected=analysisProject.doSpinSystemAnnotations,
                                          tipText=tipText)
    spinSystAnnoLabel = Label(frame1, text='Spin System Info', grid=(0,1))

    tipText = 'Whether to show assigned atom names in peak annotations rather than resonance numbers, e.g. "21LeuH,N" or "21Leu[55],[56]"'
    self.resonanceAnnoSelect = CheckButton(frame1, callback=self.setResonanceAnno, grid=(1,0),
                                           selected=analysisProject.doAssignmentAnnotations,
                                           tipText=tipText)
    resonanceAnnoLabel = Label(frame1, text='Atom Assignment', grid=(1,1))

    tipText = 'Whether to show the molecular chain code letter in peak annotations, e.g. "21LeuH,N" or "A21LeuH,N"'
    self.chainAnnoSelect = CheckButton(frame1, callback=self.setChainAnno, grid=(2,0),
                                       selected=analysisProject.doChainAnnotations,
                                       tipText=tipText)
    chainAnnoLabel = Label(frame1, text='Chain Assignment', grid=(2,1))

    tipText = 'Whether to show the molecular system code name in peak annotations, e.g. "MS1:21LeuH,N" or "21LeuH,N"'
    self.molSysAnnoSelect = CheckButton(frame1, callback=self.setMolSysAnno, grid=(3,0),
                                       selected=analysisProject.doMolSysAnnotations,
                                       tipText=tipText)
    molSysAnnoLabel = Label(frame1, text='Molecular System', grid=(3,1))

    tipText = 'Whether to show a symbol indicating the quality of a peak; these symbols must be set in the "Merit Symbols" tab'
    self.meritAnnoSelect = CheckButton(frame1, callback=self.setMeritAnno, grid=(4,0),
                                       selected=analysisProject.doMeritAnnotations,
                                       tipText=tipText)
    meritAnnoLabel = Label(frame1, text='Merit Symbol', grid=(4,1))

    tipText = 'Whether to show the details text for a peak in spectrum windows (set in the peak tables)'
    self.detailAnnoSelect = CheckButton(frame1, callback=self.setDetailAnno, grid=(5,0),
                                        selected=analysisProject.doDetailAnnotations,
                                        tipText=tipText)
    detailAnnoLabel = Label(frame1, text='Details', grid=(5,1))

    tipText = 'Whether to ignore above settings, and use a short peak annotation using only residue numbers and one-letter codes, e.g. "21L"'
    self.simpleAnnoSelect = CheckButton(frame1, callback=self.setSimpleAnnotations,
                                        grid=(6,0), tipText=tipText,
                                        selected=analysisProject.doMinimalAnnotations)
    simpleAnnoLabel = Label(frame1, text='Minimal Annotations (overriding option)', grid=(6,1))

    tipText = 'Manually cause an update of all peak annotations; may take some time but recommended to see the immediate effect of changes'
    self.updateFullAnnoButton = Button(frame1, text='Update Full Annotations',
                                       command=self.updateAnnotations, grid=(7,0),
                                       gridSpan=(1,2), sticky='nsew', tipText=tipText)

    # Size
    
    tipText = 'The width of the displayed peak cross/symbol in screen pixels; the number of pixels from the centre point'
    self.pixel_entry = LabeledEntry(frame2, label='Number of pixels',
                                    entry=analysisProject.peakPixelSize,
                                    returnCallback=self.updatePixelSize,
                                    entry_width=8, tipText=tipText)

    tipText = 'Specifies which peak height corresponds to the specific per-isotope ppm size; actual peak symbol sizes are scaled, according to relative height (and volume)'
    self.intensity_entry = LabeledEntry(frame2, label='Height scale',
                                        entry=analysisProject.peakIntensityScale,
                                        returnCallback=self.updateIntensityScale,
                                        entry_width=8, tipText=tipText)
                                        
    tipText = 'Specifies which peak volume corresponds to the specific per-isotope ppm size; actual peak symbol sizes are scaled, according to relative volume (and height)'
    self.volume_entry = LabeledEntry(frame2, label='Volume scale',
                                     entry=analysisProject.peakVolumeScale,
                                     returnCallback=self.updateVolumeScale,
                                     entry_width=8, tipText=tipText)

    tipTexts = ['The kind of nuclear isotope, as found on the axis if a spectrum window',
                'The ppm width of the peak cross/symbol along the specific kind of isotope axis']
    headings = ['Isotope', 'Peak Size (ppm)']
    self.peakSizeEntry = FloatEntry(self, returnCallback=self.setPeakSize, width=10)
    editWidgets = [None, self.peakSizeEntry]
    editGetCallbacks = [None, self.getPeakSize]
    editSetCallbacks = [None, self.setPeakSize]
    self.peak_size_table = ScrolledMatrix(frame2, headingList=headings,
                                          initialRows=5, editWidgets=editWidgets,
                                          editGetCallbacks=editGetCallbacks,
                                          editSetCallbacks=editSetCallbacks,
                                          tipTexts=tipTexts)

    self.selected_method = None
    self.method_widgets = {}
    self.method_widgets[peak_draw_methods[0]] = [self.pixel_entry]
    self.method_widgets[peak_draw_methods[1]] = [self.peak_size_table]
    self.method_widgets[peak_draw_methods[2]] = [self.intensity_entry, self.volume_entry, self.peak_size_table]
    self.method_widgets[peak_draw_methods[3]] = [self.peak_size_table]
    self.method_widgets[peak_draw_methods[4]] = []
    self.method_widgets[peak_draw_methods[5]] = []

    selected_index = peak_draw_methods.index(analysisProject.peakDrawMethod)
    tipText = 'Selects which mode to use for determining peak cross/symbol sizes; a fixed pixel/ppm value or scaled by intensity for all peaks or just one peak list'
    self.method_menu = PulldownList(frame2, texts=peak_draw_methods, gridSpan=(1,2), 
                                    grid=(0,0), tipText=tipText,
                                    callback=self.setMethod, index=selected_index)
    
    # Merit symbol
    
    label = Label(frame3, text='Good merit (>0.66)', grid=(0,0))
    tipText = 'Although typically blank, sets a symbol to display for good quality peaks (merit value > 0.66), if the relevant option is selected in the "Annotation Style" tab'
    self.meritGoodEntry = Entry(frame3, text=analysisProject.meritAnnotationGood,
                                width=8, grid=(0,1), sticky='ew', tipText=tipText,
                                returnCallback=self.setMeritAnnotation)

    label = Label(frame3, text='Medium merit', grid=(1,0))
    tipText = 'Sets a symbol to display for mediocre quality peaks (merit value between 0.34 & 0.66), if the relevant option is selected in the "Annotation Style" tab'
    self.meritUglyEntry = Entry(frame3, text=analysisProject.meritAnnotationMediocre,
                                width=8, grid=(1,1), sticky='ew', tipText=tipText,
                                returnCallback=self.setMeritAnnotation)

    label = Label(frame3, text='Poor merit (<0.34)', grid=(2,0))
    tipText = 'Sets a symbol to display for poor quality peaks (merit value < 0.34), if the relevant option is selected in the "Annotation Style" tab'
    self.meritBadEntry  = Entry(frame3, text=analysisProject.meritAnnotationBad,
                                width=8, grid=(2,1), sticky='ew', tipText=tipText,
                                returnCallback=self.setMeritAnnotation)

    tipText = 'Commit the changes to the merit symbols; this will not automatically update the display - see the "Annotation Style" tab'
    setButton = Button(frame3, text='Set symbols', command=self.setMeritAnnotation,
                       grid=(3,0), gridSpan=(1,2), tipText=tipText, sticky='nsew')

    buttons = UtilityButtonList(tabbedFrame.sideFrame, grid=(0,0), 
                                helpUrl=self.help_url, sticky='e')

    self.updatePeakSizeTable()
    self.updateMethod()

    for func in ('__init__', 'delete', ''):                                           
      self.registerNotify(self.updatePeakSizeTable, 'ccpnmr.Analysis.AxisType', func)

    self.registerNotify(self.changedDoSpinSystemAnnotations, 'ccpnmr.Analysis.AnalysisProject', 'setDoSpinSystemAnnotations')
    self.registerNotify(self.changedDoAssignmentAnnotations, 'ccpnmr.Analysis.AnalysisProject', 'setDoAssignmentAnnotations')
    self.registerNotify(self.changedDoChainAnnotations, 'ccpnmr.Analysis.AnalysisProject', 'setDoChainAnnotations')
    self.registerNotify(self.changedPeakDrawMethod, 'ccpnmr.Analysis.AnalysisProject', 'setPeakDrawMethod')
    self.registerNotify(self.changedPeakPixelSize, 'ccpnmr.Analysis.AnalysisProject', 'setPeakPixelSize')
Пример #8
0
class HaddockServerUpload(BasePopup):

    def __init__(self,parent,hProject=None,latestRun=None,ccpnProject=None):

        self.parent         = parent  #GUI parent
        self.hProject        = hProject
        self.latestRun         = latestRun
        self.ccpnProject     = ccpnProject
        
        self.username        = None
        self.password        = None
        
        BasePopup.__init__(self, parent=parent, title='HADDOCK server upload')

    def body(self, guiFrame):

        guiFrame.grid_columnconfigure(1, weight=1)
        guiFrame.grid_rowconfigure(1, weight=1)

        self.usernameEntry = LabeledEntry(guiFrame, 'username')
        self.usernameEntry.grid(row=0)

        self.passwordEntry = LabeledEntry(guiFrame, 'password', show="*")
        self.passwordEntry.grid(row=1)
        
        texts = ['Upload']
        commands = [self.serverUpload]
        buttonList = createDismissHelpButtonList(guiFrame, texts=texts, commands=commands, expands=True)
        buttonList.grid(row=2)

    def serverUpload(self):
        
        """Process username and password. If both valid then start uploading otherwise issue warning.
           Export the project and run as a .web file to disk. Than upload this file
        """
        warning = ''
        
        if self.usernameEntry.getEntry(): self.username = self.usernameEntry.getEntry()
        else: warning += ' No username defined ' 
        
        if self.passwordEntry.getEntry(): self.password = self.passwordEntry.getEntry()
        else: warning += ' No password defined '            
        
        if len(warning): showWarning('Warning', warning, parent=self)
        else:
            exportParams = exportParam(hProject=self.hProject,
                                       latestRun=self.latestRun,
                                       ccpnProject=self.ccpnProject)
            if len(exportParams.filestring): upload = ServerUpload(exportParams.filestring,
                                                                     self.hProject.name,
                                                                     str(self.latestRun.serial),
                                                                     self.username,
                                                                     self.password)
            else: print("ERROR: Export project as parameter file failed")
                
    def open(self):

        BasePopup.open(self)    

    def destroy(self):

        BasePopup.destroy(self)