Exemple #1
0
class SaveLoadTab(object):
    """The tab that lets the user FileSelect
       a file to open or to save.
    """

    def __init__(self, parent, frame):
        """Init. args: parent: the guiElement that this
                               tab is part of.
                       frame:  the frame this part of the
                               GUI lives in.
        """

        self.guiParent = parent
        self.frame = frame
        self.project = parent.project
        self.nmrProject = parent.nmrProject
        self.loadAndSaveButtons = None
        self.fileselectionBox = None
        self.body()

    def body(self):
        """Setting up the body of this view."""

        frame = self.frame

        file_types = [FileType("pyc", ["*.pyc"])]
        self.fileselectionBox = FileSelect(frame, multiSelect=False, file_types=file_types)
        self.fileselectionBox.grid(row=0, column=0, columnspan=6, sticky="nsew")

        texts = ["Load", "Save"]
        commands = [self.loadDataFromPyc, self.saveDataToPyc]
        self.loadAndSaveButtons = ButtonList(frame, commands=commands, texts=texts)
        self.loadAndSaveButtons.grid(row=1, column=0, sticky="nsew")

        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)

    def saveDataToPyc(self):
        """Save the data to the selected file."""

        if self.guiParent.connector.results:

            fileName = self.fileselectionBox.getFile()
            self.guiParent.connector.saveDataToPyc(fileName)
            self.fileselectionBox.updateFileList()

        else:

            string = """There are no results to save, """ """the algorithm has not run yet."""

            showWarning("No Results to Save", string, parent=self.guiParent)

    def loadDataFromPyc(self):
        """Load the data from the selected file."""

        fileName = self.fileselectionBox.getFile()
        self.guiParent.connector.loadDataFromPyc(fileName)
        self.guiParent.resultsTab.update()
Exemple #2
0
class SaveLoadTab(object):
    '''The tab that lets the user FileSelect
       a file to open or to save.
    '''
    def __init__(self, parent, frame):
        '''Init. args: parent: the guiElement that this
                               tab is part of.
                       frame:  the frame this part of the
                               GUI lives in.
        '''

        self.guiParent = parent
        self.frame = frame
        self.project = parent.project
        self.nmrProject = parent.nmrProject
        self.loadAndSaveButtons = None
        self.fileselectionBox = None
        self.body()

    def body(self):
        '''Setting up the body of this view.'''

        frame = self.frame

        file_types = [FileType('pyc', ['*.pyc'])]
        self.fileselectionBox = FileSelect(frame,
                                           multiSelect=False,
                                           file_types=file_types)
        self.fileselectionBox.grid(row=0,
                                   column=0,
                                   columnspan=6,
                                   sticky='nsew')

        texts = ['Load', 'Save']
        commands = [self.loadDataFromPyc, self.saveDataToPyc]
        self.loadAndSaveButtons = ButtonList(frame,
                                             commands=commands,
                                             texts=texts)
        self.loadAndSaveButtons.grid(row=1, column=0, sticky='nsew')

        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)

    def saveDataToPyc(self):
        '''Save the data to the selected file.'''

        if self.guiParent.connector.results:

            fileName = self.fileselectionBox.getFile()
            self.guiParent.connector.saveDataToPyc(fileName)
            self.fileselectionBox.updateFileList()

        else:

            string = ('''There are no results to save, '''
                      '''the algorithm has not run yet.''')

            showWarning('No Results to Save', string, parent=self.guiParent)

    def loadDataFromPyc(self):
        '''Load the data from the selected file.'''

        fileName = self.fileselectionBox.getFile()
        self.guiParent.connector.loadDataFromPyc(fileName)
        self.guiParent.resultsTab.update()
class FileSelectPopup(BasePopup):
    def __init__(self,
                 parent,
                 file_types=None,
                 directory=None,
                 multiSelect=False,
                 title='Browse files',
                 prompt=None,
                 show_file=True,
                 file='',
                 dismiss_text='Close',
                 extra_dismiss_text='',
                 selected_file_must_exist=False,
                 default_dir=None,
                 *args,
                 **kw):

        self.file_types = file_types
        self.directory = directory
        self.prompt = prompt
        self.show_file = show_file
        self.dismiss_text = dismiss_text
        self.extra_dismiss_text = extra_dismiss_text
        self.initial_file = file
        self.selected_file_must_exist = selected_file_must_exist
        self.default_dir = default_dir
        self.multiSelect = multiSelect

        kw['title'] = title
        kw['transient'] = True
        kw['modal'] = True
        BasePopup.__init__(self, parent=parent, *args, **kw)

    def body(self, master):

        self.geometry('600x400')
        master.grid_rowconfigure(0, weight=1)
        master.grid_columnconfigure(0, weight=1)

        self.result = ''
        self.file_select = FileSelect(master,
                                      file_types=self.file_types,
                                      directory=self.directory,
                                      prompt=self.prompt,
                                      show_file=self.show_file,
                                      file=self.initial_file,
                                      multiSelect=self.multiSelect,
                                      default_dir=self.default_dir)
        self.file_select.grid(row=0, column=0, sticky=Tkinter.NSEW)

        texts = ['Ok']
        commands = [self.ok]
        if (self.extra_dismiss_text):
            texts.append(self.extra_dismiss_text)
            commands.append(self.extra)
        buttons = createDismissHelpButtonList(master,
                                              texts=texts,
                                              commands=commands,
                                              dismiss_text=self.dismiss_text)
        buttons.grid(row=1, column=0, sticky=Tkinter.EW)

    def apply(self):

        self.result = ''

        file = self.file_select.getFile()
        if (self.selected_file_must_exist and not os.path.exists(file)):
            showError('No file', 'File does not exist', self)
            return False

        self.result = file

        return True

    def extra(self):

        self.result = None
        self.close()

    def getFile(self):

        if (self.result):
            return self.file_select.getFile()
        else:
            return self.result

    def getDirectory(self):

        if (self.result):
            return self.file_select.getDirectory()
        else:
            return self.result

    def open(self, file=''):

        if (file):
            self.setFile(file)
        BasePopup.open(self)

    def __getattr__(self, name):

        try:
            return getattr(self.__dict__['file_select'], name)
        except:
            raise AttributeError, "%s instance has no attribute '%s'" % (
                self.__class__.__name__, name)
Exemple #4
0
class FormatFilePopup(BasePopup):
    def __init__(self,
                 parent,
                 file=None,
                 files=None,
                 component=None,
                 selectionText='Select',
                 title=None,
                 format=None,
                 multiSelect=False):

        #
        # Also get format (from self?)
        #

        self.file = None  # Use this to return single file info, for backward compat

        if not multiSelect and file:
            self.files = [file]

        elif files:
            self.files = files

        else:
            self.files = []

        if self.files:
            for i in range(len(self.files)):
                self.files[i] = normalisePath(self.files[i])

        self.component = component
        self.fileSelected = False
        self.selectionText = selectionText
        self.format = format

        self.multiSelect = multiSelect

        if not title:
            title = 'Select %s file' % component

        BasePopup.__init__(self,
                           parent=parent,
                           title=title,
                           modal=True,
                           transient=True)

    def body(self, master):

        master.grid_columnconfigure(0, weight=1)
        master.grid_rowconfigure(0, weight=1)
        master.grid_rowconfigure(1, weight=1)

        self.geometry('500x500')

        fileNames = []

        # All files have to be in same directory!
        if self.files and self.files[0].find(dirsep) > -1:
            (path, fileName) = splitPath(self.files[0])
            directory = path
            fileNames.append(fileName)

            for file in self.files[1:]:
                (path, fileName) = splitPath(file)
                fileNames.append(fileName)

        else:
            path = None
            directory = normalisePath(os.path.abspath(os.curdir))
            fileNames = []

        #print directory
        #print fileName

        file_types = []

        if fileTypeDict.has_key(self.component):

            if self.format and fileTypeDict[self.component].has_key(
                    self.format):

                file_types.extend([
                    FileType(self.format,
                             fileTypeDict[self.component][self.format])
                ])

            if fileTypeDict[self.component].has_key('generic'):

                file_types.extend([
                    FileType('generic',
                             fileTypeDict[self.component]['generic'])
                ])

        file_types.extend([FileType('All', ['*'])])

        self.file_select = FileSelect(master,
                                      file_types=file_types,
                                      directory=directory,
                                      double_callback=self.ok,
                                      multiSelect=self.multiSelect)

        if self.multiSelect:
            self.file_select.setFiles(fileNames)
        else:
            if fileNames:
                fileName = fileNames[0]
            else:
                fileName = ''
            self.file_select.setFile(fileName)

        self.file_select.grid(row=0, column=0, sticky=Tkinter.NSEW)

        texts = [self.selectionText]
        commands = [self.ok]
        buttons = createDismissHelpButtonList(master,
                                              texts=texts,
                                              commands=commands)
        buttons.grid(row=1, column=0, sticky=Tkinter.EW)

    def apply(self):

        if not self.multiSelect:
            file = self.file_select.getFile()
            if file:
                files = [file]
            else:
                files = []

        else:
            files = self.file_select.getFiles()

        if (not files):
            self.files = None
            return False

        self.fileSelected = True
        self.files = []

        # Handle symbolic links in Linux/unix
        for file in files:
            symbolicLinkIndex = string.find(file, '->')
            if symbolicLinkIndex != -1:
                self.files.append(file[symbolicLinkIndex + 3:])
            else:
                self.files.append(file)

        # For single files, set self.file for backward compat
        if not self.multiSelect:
            self.file = self.files[0]

        return True
Exemple #5
0
class OpenMacroPopup(BasePopup):
  """
  **Locate Python Macro Scripts On Disk**
  
  This popup is used to locate a Python file and function definition on disk
  so that it can be loaded into Analysis as a "Macro". The top table
  is a file browser that the user can navigate to the location of the Python
  file (typically sending in ".py"). When a Python file is selected in the
  upper table the system will look through the contents of the file to find
  any macro functions that are defined within. Note that a macro function 
  is defined by the normal Python "def" keyword but must take "argSever"
  as its first input argument. 
  
  Any macro functions in the selected file will be displayed in the
  lower table. Clicking on the name of a function in this table
  selects it for opening. The user may edit the name of the macro for 
  display purposes within Analysis. Finally clicking [Load Macro]
  will add it to the CCPN project, stored in a user-specific way
  inside the current Analysis profile. Once loaded into the
  project the new macro will appear in the main macro table
  (the "Macros" tab of `User Options`_)
  
  .. _`User Options`: EditProfilesPopup.html
    
  """


  def __init__(self, parent, **kw):

    # TBD: properly
    transient = True
    BasePopup.__init__(self, parent=parent, title='Open macro', transient=transient, **kw)

  def body(self, guiParent):

    guiParent.grid_columnconfigure(1,weight=1)
    row = 0

    file_types = [  FileType('Python', ['*.py']), FileType('All', ['*']) ]
    self.file_select = FileSelect(guiParent, file_types=file_types,
                                  single_callback=self.chooseFile,
                                  double_callback=self.chooseFile)
    self.file_select.grid(row=row, column=0, columnspan=2, sticky='nsew')
    
    row = row + 1
    headingList=('Function',)
    self.scrolledMatrix = ScrolledMatrix(guiParent, initialRows=4,
                            headingList=headingList, callback=self.selectFunction)
    self.scrolledMatrix.grid(row=row, column=0, columnspan=2, sticky='nsew')
    guiParent.grid_rowconfigure(row,weight=1)

    row = row + 1
    self.moduleLabel1 = Label(guiParent, text='Module: ')
    self.moduleLabel1.grid(row=row, column=0, sticky='nw')
    self.moduleLabel2 = Label(guiParent, text=' ')
    self.moduleLabel2.grid(row=row, column=1, sticky='nw')

    row = row + 1
    self.functionLabel1 = Label(guiParent, text='Function: ')
    self.functionLabel1.grid(row=row, column=0, sticky='nw')
    self.functionLabel2 = Label(guiParent, text=' ')
    self.functionLabel2.grid(row=row, column=1, sticky='nw')

    row = row + 1
    self.nameLabel = Label(guiParent, text='Name: ')
    self.nameLabel.grid(row=row, column=0, sticky='nw')
    self.nameEntry = Entry(guiParent, text=' ', width=40)
    self.nameEntry.grid(row=row, column=1, sticky='nw')

    row = row + 1
    texts = [ 'Load Macro' ]
    commands = [ self.loadMacro ]
    buttons = UtilityButtonList(guiParent, texts=texts,
                                commands=commands, helpUrl=self.help_url)
    buttons.grid(row=row, column=0, columnspan=2, sticky='ew')
    
    self.loadButton = buttons.buttons[0]
    self.loadButton.disable()
    
    self.path     = None
    self.module   = None
    self.function = None

  def selectFunction(self, function, row, col):
  
    if function:
      self.loadButton.enable()
      self.function = function
      self.functionLabel2.set(function)
      self.nameEntry.set(function)
    
  def updateFunctions(self, file):
  
    self.loadButton.disable()
    functions = []
    fileHandle = open(file, 'r')
    line = fileHandle.readline()
    textMatrix = []
    while line :
      match = re.match('\s*def\s+(\w+)\s*\(.*argServer',line)
      if match:
        function = match.group(1)
        functions.append(function)
        textMatrix.append( [function,] )
      line = fileHandle.readline()

    self.scrolledMatrix.update(objectList=functions,textMatrix=textMatrix)

  def chooseFile(self, file):
    
    fullPath =self.file_select.getFile()
    if not os.path.isdir(fullPath) and file:
      (self.path, module) = splitPath(fullPath)
      module = re.sub('\..+?$','',module)
      self.module = module
      self.moduleLabel2.set(module)
      self.updateFunctions(file)

  def loadMacro(self):
    
    if self.module and self.function and self.path:
      name = self.nameEntry.get()
      if not name:
        name = self.function
        
      analysisProfile = self.analysisProfile
      
      m1 = analysisProfile.newMacro(name=name,path=self.path,
                                    function=self.function,
                                    module=self.module,ordering=1)
 
    self.close()