Exemple #1
0
def ensureVisionResourceFile():
    ##################################################################
    # verify or generate _visionrc file
    ##################################################################
    from Vision.nodeLibraries import libraries
    from mglutil.util.packageFilePath import getResourceFolderWithVersion

    visionrcDir = getResourceFolderWithVersion()
    if visionrcDir is None:
        return
    visionrcDir += os.sep + 'Vision'
    if os.path.isdir(visionrcDir) is False:
        try:
            os.mkdir(visionrcDir)
        except:
            txt = "can not create folder for _visionrc"
            warnings.warn(txt)
            return

    visionrcFile = visionrcDir + os.sep + '_visionrc'
    if os.path.isfile(visionrcFile) is False:
        try:
            from Vision import __path__ as lVisionPath
            shutil.copyfile(lVisionPath[0] + os.sep + '_visionrc',
                            visionrcFile)
        except:
            txt = "can not create _visionrc"
            warnings.warn(txt)
def ensureVisionResourceFile():
    ##################################################################
    # verify or generate _visionrc file
    ##################################################################
    from Vision.nodeLibraries import libraries
    from mglutil.util.packageFilePath import getResourceFolderWithVersion
    
    visionrcDir = getResourceFolderWithVersion()
    if visionrcDir is None:
        return
    visionrcDir += os.sep + 'Vision'
    if os.path.isdir(visionrcDir) is False:
        try:
            os.mkdir(visionrcDir)
        except:
            txt = "can not create folder for _visionrc"
            warnings.warn(txt)
            return

    visionrcFile = visionrcDir + os.sep + '_visionrc'
    if os.path.isfile(visionrcFile) is False:
        try:
            from Vision import __path__ as lVisionPath
            shutil.copyfile(lVisionPath[0]+os.sep+'_visionrc', visionrcFile)
        except:
            txt = "can not create _visionrc"
            warnings.warn(txt)
Exemple #3
0
 def __init__(self,
              masterApp,
              masterMenu,
              filePath=None,
              menuLabel="Open recent",
              underline=5,
              index=0):
     """Construct recent files categories. If filePath is not provided
     mglutil/recent.pkl is used to store and load the data"""
     if not filePath:  #use "mglutil/recent.pkl" to store the data
         filePath = getResourceFolderWithVersion()
         if filePath is None:
             return
         filePath += os.sep + "mglutil" + os.sep + "recent.pkl"
     if os.path.exists(filePath):
         try:
             self.categories = pickle.load(open(filePath))
         except Exception as inst:
             #print inst
             #print "Couldn't Load Recent Files."
             self.categories = {}
     else:
         self.categories = {}
     self.resourceFilePath = filePath
     self.checkCategories()
     if masterMenu != None:
         self.gui(masterMenu, menuLabel, underline=underline, index=index)
     else:
         self.mainMenu = None
     self.masterApp = masterApp
def saveFonts4CADDFile(fontDict):
    ##################################################################
    # generate and overwrite _fonts4cadd file
    ##################################################################
    from mglutil.util.packageFilePath import getResourceFolderWithVersion
    
    caddrcDir = getResourceFolderWithVersion()
    if caddrcDir is None:
        return

    caddrcDir += os.sep + 'CADD'
    if os.path.isdir(caddrcDir) is False:
        return

    fonts4CADDFile = caddrcDir + os.sep + '_fonts4cadd'
    try:
        f = open(fonts4CADDFile, "w")
        txt = txtstr %(
fontDict['Menus'][0],fontDict['Menus'][1],fontDict['Menus'][2],
fontDict['LibTabs'][0],fontDict['LibTabs'][1],fontDict['LibTabs'][2],
fontDict['Categories'][0],fontDict['Categories'][1],fontDict['Categories'][2],
fontDict['LibNodes'][0],fontDict['LibNodes'][1],fontDict['LibNodes'][2],
fontDict['NetTabs'][0],fontDict['NetTabs'][1],fontDict['NetTabs'][2],
fontDict['Nodes'][0],fontDict['Nodes'][1],fontDict['Nodes'][2],
fontDict['Root'][0],fontDict['Root'][1],fontDict['Root'][2],
)

        map( lambda x, f=f: f.write(x), txt )
        f.close()
    except:
        txt = "can not create _fonts4cadd"
        warnings.warn(txt)
Exemple #5
0
    def Update(self):
        regfile = None
        old_rc = getResourceFolder()
        rcWithVersion = getResourceFolderWithVersion()
        regfile = os.path.join(old_rc, ".registration")
        if os.path.exists(old_rc + os.sep + ".registration"):
            regfile = old_rc + os.sep + ".registration"
        else:
            dirlist = os.listdir(old_rc)
            for item in dirlist:
                tmpRegFile = old_rc + os.sep + item + os.sep + ".registration"
                if os.path.exists(tmpRegFile):
                    regfile = tmpRegFile
                    break

        regDict = pickle.load(open(regfile))
        regDict['Version'] = Version
        form_dict = {}
        form_dict['UserID'] = regDict['UserID']
        form_dict['Version'] = regDict['Version']
        import httplib, urllib
        params = urllib.urlencode(form_dict)
        headers = {
            "Content-type": "application/x-www-form-urlencoded",
            "Accept": "text/plain"
        }
        conn = httplib.HTTPConnection("www.scripps.edu:80")
        conn.request("POST", "/cgi-bin/sanner/update_mgltools_version.py",
                     params, headers)
        response = conn.getresponse()
        if response.status == 200:
            reg = open(lRessourceFolder + os.sep + ".registration", 'w')
            pickle.dump(regDict, reg)
            reg.close()
        conn.close()
def ensureCADDResourceFile():
    ##################################################################
    # verify or generate _caddrc file
    ##################################################################
    from mglutil.util.packageFilePath import getResourceFolderWithVersion
    
    caddrcDir = getResourceFolderWithVersion()
    if caddrcDir is None:
        return
    caddrcDir += os.sep + 'CADD'
    if os.path.isdir(caddrcDir) is False:
        try:
            os.mkdir(caddrcDir)
        except:
            txt = "can not create folder for _caddrc"
            warnings.warn(txt)
            return

    caddrcFile = caddrcDir + os.sep + '_caddrc'
    if os.path.isfile(caddrcFile) is False:
        try:
            from CADD import __path__ as lCADDPath
            shutil.copyfile(lCADDPath[0]+os.sep+'_caddrc', caddrcFile)
        except:
            txt = "can not create _caddrc"
            warnings.warn(txt)

    return caddrcFile
Exemple #7
0
    def findDefaultPackages(self):
        packages = findAllPackages()
        default = [
            'ARTK', 'DejaVu', 'FlexTree', 'MolKit', 'Pmv', 'Vision', 'Volume',
            'symserv', 'WebServices'
        ]

        # do these default values exist?
        tmp = []
        for k in default:
            if k in packages.keys():
                tmp.append(k)
        default = tmp

        # add the user libs to default
        from mglutil.util.packageFilePath import getResourceFolderWithVersion
        userResourceFolder = getResourceFolderWithVersion()
        if userResourceFolder is not None:
            userLibsDir = userResourceFolder + os.sep + 'Vision' + os.sep + 'UserLibs'
            from Vision import __path__
            lVisionLibrariesPath = __path__[0] + 'Libraries'
            for k, v in packages.items():
                if v.startswith(userLibsDir):
                    default.append(k)
                elif v.startswith(lVisionLibrariesPath):
                    default.append(k)

        # now build the default list
        for k in packages.keys():
            if k not in default:
                del packages[k]
        self.packages = packages
def ensureMglutilResourceFile():
    """verify or generate _mglutilrc file
"""
    #print "ensureMglutilResourceFile"

    from mglutil.util.packageFilePath import getResourceFolderWithVersion
    rcFolder = getResourceFolderWithVersion()
    if rcFolder is None:
        return None
    rcFolder += os.sep + 'mglutil'
    if not os.path.isdir(rcFolder):
        try:
            os.mkdir(rcFolder)
        except:
            txt = "Cannot create the Resource Folder %s" %rcFolder
            warnings.warn(txt)
            return None

    rcFile = rcFolder + os.sep + '_mglutilrc'
    if os.path.isfile(rcFile) is False:
        try:
            f = open(rcFile, "w")
            global mglutilrcText
            list(map( lambda x, f=f: f.write(x), mglutilrcText ))
            f.close()
        except:
            txt = "can not create _mglutilrc"
            warnings.warn(txt)
            return None

    return rcFile
def ensureMglutilResourceFile():
    """verify or generate _mglutilrc file
"""
    #print "ensureMglutilResourceFile"

    from mglutil.util.packageFilePath import getResourceFolderWithVersion
    rcFolder = getResourceFolderWithVersion()
    if rcFolder is None:
        return None
    rcFolder += os.sep + 'mglutil'
    if not os.path.isdir(rcFolder):
        try:
            os.mkdir(rcFolder)
        except:
            txt = "Cannot create the Resource Folder %s" %rcFolder
            warnings.warn(txt)
            return None

    rcFile = rcFolder + os.sep + '_mglutilrc'
    if os.path.isfile(rcFile) is False:
        try:
            f = open(rcFile, "w")
            global mglutilrcText
            map( lambda x, f=f: f.write(x), mglutilrcText )
            f.close()
        except:
            txt = "can not create _mglutilrc"
            warnings.warn(txt)
            return None

    return rcFile
 def Update(self):
     regfile = None
     old_rc = getResourceFolder()
     rcWithVersion = getResourceFolderWithVersion()
     regfile = os.path.join(old_rc, ".registration")
     if os.path.exists(old_rc + os.sep + ".registration"):
         regfile = old_rc + os.sep + ".registration"
     else:
         dirlist = os.listdir(old_rc)
         for item in dirlist:
             tmpRegFile = old_rc+os.sep+item+os.sep + ".registration"
             if os.path.exists(tmpRegFile):
                 regfile = tmpRegFile
                 break
     
     regDict = pickle.load(open(regfile))
     regDict['Version'] = Version
     form_dict = {}
     form_dict['UserID'] = regDict['UserID']
     form_dict['Version'] = regDict['Version']
     import httplib, urllib
     params = urllib.urlencode(form_dict)
     headers = {"Content-type": "application/x-www-form-urlencoded",
                                              "Accept": "text/plain"}
     conn = httplib.HTTPConnection("www.scripps.edu:80")
     conn.request("POST", "/cgi-bin/sanner/update_mgltools_version.py", 
                  params, headers)
     response = conn.getresponse()
     if response.status == 200:
         reg = open(lRessourceFolder + os.sep + ".registration", 'w')
         pickle.dump(regDict,reg)
         reg.close()
     conn.close()
    def findDefaultPackages(self):
        packages = findAllPackages()
        default =  [
            'ARTK', 'DejaVu', 'FlexTree', 'MolKit', 'Pmv', 'Vision',
            'Volume', 'symserv', 'WebServices']

        # do these default values exist?
        tmp = []
        for k in default:
            if k in packages.keys():
                tmp.append(k)
        default = tmp

        # add the user libs to default
        from mglutil.util.packageFilePath import getResourceFolderWithVersion
        userResourceFolder = getResourceFolderWithVersion()
        if userResourceFolder is not None:
            userLibsDir = userResourceFolder + os.sep + 'Vision' + os.sep + 'UserLibs'
            from Vision import __path__
            lVisionLibrariesPath = __path__[0]+'Libraries'
            for k,v in packages.items():
                if v.startswith(userLibsDir):
                    default.append(k)
                elif v.startswith(lVisionLibrariesPath):
                    default.append(k)

        # now build the default list
        for k in packages.keys():
            if k not in default:
                del packages[k]
        self.packages = packages
def ensureDejaVuResourceFile():
    """verify or generate _dejavurc file
"""
    #print "ensureDejaVuResourceFile"
    
    #import pdb;pdb.set_trace()
    
    from mglutil.util.packageFilePath import getResourceFolderWithVersion
    rcFolder = getResourceFolderWithVersion()
    if rcFolder is None:
        return
    rcFolder += os.sep + 'DejaVu'
    if not os.path.isdir(rcFolder):
        try:
            os.mkdir(rcFolder)
        except:
            txt = "Cannot create the Resource Folder %s" %rcFolder
            warnings.warn(txt)
            return None

    rcFile = rcFolder + os.sep + '_dejavurc'
    if os.path.isfile(rcFile) is False:
        try:
            f = open(rcFile, "w")
            list(map( lambda x, f=f: f.write(x), dejavurcText ))
            f.close()
        except:
            txt = "can not create _dejavurc"
            warnings.warn(txt)
            return None

    return rcFile
Exemple #13
0
def ensureCADDFontsFile():
    ##################################################################
    # verify or generate _fonts4cadd file
    ##################################################################
    from mglutil.util.packageFilePath import getResourceFolderWithVersion

    caddrcDir = getResourceFolderWithVersion()
    if caddrcDir is None:
        return
    caddrcDir += os.sep + 'CADD'
    if os.path.isdir(caddrcDir) is False:
        try:
            os.mkdir(caddrcDir)
        except:
            txt = "can not create folder for _fonts4cadd"
            warnings.warn(txt)
            return

    fonts4CADDFile = caddrcDir + os.sep + '_fonts4cadd'
    try:
        f = open(fonts4CADDFile, "w")
        txt = txtstr % ('helvetica', 10, 'normal', 'helvetica', 10, 'normal',
                        'helvetica', 10, 'normal', 'helvetica', 10, 'normal',
                        'helvetica', 10, 'normal', 'helvetica', 10, 'normal',
                        'helvetica', 10, 'normal')

        map(lambda x, f=f: f.write(x), txt)
        f.close()
    except:
        txt = "can not create _fonts4cadd"
        warnings.warn(txt)
Exemple #14
0
def ensureDejaVuResourceFile():
    """verify or generate _dejavurc file
"""
    #print "ensureDejaVuResourceFile"

    #import pdb;pdb.set_trace()

    from mglutil.util.packageFilePath import getResourceFolderWithVersion
    rcFolder = getResourceFolderWithVersion()
    if rcFolder is None:
        return
    rcFolder += os.sep + 'DejaVu'
    if not os.path.isdir(rcFolder):
        try:
            os.mkdir(rcFolder)
        except:
            txt = "Cannot create the Resource Folder %s" % rcFolder
            warnings.warn(txt)
            return None

    rcFile = rcFolder + os.sep + '_dejavurc'
    if os.path.isfile(rcFile) is False:
        try:
            f = open(rcFile, "w")
            map(lambda x, f=f: f.write(x), dejavurcText)
            f.close()
        except:
            txt = "can not create _dejavurc"
            warnings.warn(txt)
            return None

    return rcFile
Exemple #15
0
def ensureCADDResourceFile():
    ##################################################################
    # verify or generate _caddrc file
    ##################################################################
    from mglutil.util.packageFilePath import getResourceFolderWithVersion

    caddrcDir = getResourceFolderWithVersion()
    if caddrcDir is None:
        return
    caddrcDir += os.sep + 'CADD'
    if os.path.isdir(caddrcDir) is False:
        try:
            os.mkdir(caddrcDir)
        except:
            txt = "can not create folder for _caddrc"
            warnings.warn(txt)
            return

    caddrcFile = caddrcDir + os.sep + '_caddrc'
    if os.path.isfile(caddrcFile) is False:
        try:
            from CADD import __path__ as lCADDPath
            shutil.copyfile(lCADDPath[0] + os.sep + '_caddrc', caddrcFile)
        except:
            txt = "can not create _caddrc"
            warnings.warn(txt)

    return caddrcFile
    def guiCallback(self):
        if self.master == None:
            self.master = Tkinter.Toplevel()
            self.master.protocol('WM_DELETE_WINDOW',self.destroy)
                        
            self.vf.help_about.gui(master=self.master)
            self.vf.help_about.imageTk.bind('<1>', self.nextImage)


            notebook = Pmw.NoteBook(self.master)
            notebook.pack(expand='yes', fill='both')

            page = notebook.add('Authors')
            #notebook.tab('Authors').focus_set()
            # Authors
            from PIL import Image, ImageTk
            image = Image.open(self.vf.help_about.icon)
            self.icon_image = ImageTk.PhotoImage(master=page, image=image)
            self.image2 = Tkinter.Label(page, image=self.icon_image)
            self.image2.pack(side='left')

            Tkinter.Label(page, text=self.vf.help_about.authors, fg='#662626', 
                          justify='left', anchor='w', 
                          ).pack(side='left')

            # 3rd party
            if len(self.vf.help_about.third_party):
                page = notebook.add('Third party software components')
                
                Tkinter.Label(page, text=self.vf.help_about.third_party, fg='#0A3A75',
                              justify='left',  anchor='w',
                              ).pack(side='left')

    
            # app info group
            if len(self.vf.help_about.path_data):
                page = notebook.add('Path information')
                Tkinter.Label(page, text=self.vf.help_about.path_data, 
                              fg='#3A9E23', justify='left', anchor='w',
                              ).pack(side='left')

            Tkinter.Label(self.master,text = '              ').pack(side='left')
            l = Tkinter.Label(self.master, fg='Blue', cursor='hand1',
                          text='http://mgltools.scripps.edu')
            l.pack(side='left')
            l.bind(sequence="<Button-1>", func=self.openurl)
            Tkinter.Label(self.master,text = '              ').pack(side='left')

            registration = getResourceFolderWithVersion() + os.sep + '.registration'
            if not os.path.exists(registration):
                reg = Tkinter.Button(self.master,text='   Register   ',
                                     command=self.register)
                reg.pack(side = 'left')
            b = Tkinter.Button(self.master,text='   Close   ',
                               command=self.destroy)
            b.pack(side = 'left')
            notebook.setnaturalsize()
        else:
            self.master.deiconify()
            self.master.lift()
Exemple #17
0
 def showuploadpage_cb(self,sumcont,desccont,atcont,email_ent,
                       product="Pure Python", version="unspecified"):
     if self.component==None:
         return
    
     import urllib
     idnum = None
     ###################
     #find date and time
     ###################
     d = os.popen("date '+20%y-%m-%d'")
     date = d.readlines()[0][:-1]
     t = os.popen("date '+%H:%M:%S'")
     time = t.readlines()[0][:-1]
     deltaval = date+" "+time
     desccont += "\n sys.version: " + sys.version
     from mglutil.util.packageFilePath import findFilePath, getResourceFolderWithVersion
     registration = getResourceFolderWithVersion() + os.sep + '.registration'
     if os.path.exists(registration):
         import pickle
         try:
             desccont += "\n UserID: " + pickle.load(open(registration))['UserID'].strip()
         except Exception, inst:
             warnings.warn(inst)
             desccont += "\n Unregistered User"
Exemple #18
0
 def register(self, ):
     self.dictToSend = {}
     for i, k in enumerate(order):
         dk = k
         if i <= 5:
             dk = dk.replace("*", "")
             dk = dk.replace(" ", "_")
         self.dictToSend[dk] = str(self.form_dict[k]).strip()
         #print (dk,self.dictToSend[dk])
     self.dictToSend.update(self.sys_dict)
     self.dictToSend['hostname'] = self.form_dict['hostname']
     self.dictToSend['3DHost'] = self.form_dict['3DHost']
     #        for k in self.dictToSend:
     #            print k, self.dictToSend[k]
     params = urllib.urlencode(self.dictToSend)
     #print (params)
     #self.label_message.configure(text = 'Please Wait', fg = 'Red')
     headers = {
         "Content-type": "application/x-www-form-urlencoded",
         "Accept": "text/plain"
     }
     #        conn = httplib.HTTPConnection("www.scripps.edu:80")
     conn = httplib.HTTPConnection("mgldev.scripps.edu:80")
     try:
         #            conn.request("POST", "/cgi-bin/sanner/register_mgltools.py", params, headers)
         conn.request("POST", "/cgi-bin/register_mgltools.py", params,
                      headers)
         response = conn.getresponse()
     except:
         #            from traceback import print_exc
         #            print_exc()
         print("fail to connect")
         return False
     if response.status == 200:
         #            getResourceFolder
         reg_file = os.path.join(getResourceFolder(), '.registration')
         #            print (reg_file)
         UserID = response.read().decode("utf8")
         #            print (UserID)
         if UserID:
             self.form_dict['UserID'] = UserID
             file = open(reg_file, 'wb')
             pickle.dump(self.form_dict, file)
             file.close()
             c_reg_file = os.path.join(getResourceFolderWithVersion(),
                                       '.registration')
             shutil.copy(reg_file, c_reg_file)
         else:
             print("Registration failed to create User.")
             return False
     else:
         print("Unable to connect to Registration Database")
         return False
     conn.close()
     return True
Exemple #19
0
    def register(self,):
        self.dictToSend={}
        for i,k in enumerate(order) :
            dk = k
            if i <=5 :
                dk = dk.replace("*","")
                dk = dk.replace(" ","_")
            self.dictToSend[dk] = str(self.form_dict[k]).strip()
            #print (dk,self.dictToSend[dk])
        self.dictToSend.update(self.sys_dict)
        self.dictToSend['hostname'] = self.form_dict['hostname']
        self.dictToSend['3DHost'] = self.form_dict['3DHost']
#        for k in self.dictToSend:
#            print k, self.dictToSend[k]
        params = urllib.urlencode(self.dictToSend)
        #print (params)
        #self.label_message.configure(text = 'Please Wait', fg = 'Red')
        headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
#        conn = httplib.HTTPConnection("www.scripps.edu:80")
        conn = httplib.HTTPConnection("mgldev.scripps.edu:80")
        try:
#            conn.request("POST", "/cgi-bin/sanner/register_mgltools.py", params, headers)
            conn.request("POST", "/cgi-bin/register_mgltools.py", params, headers)
            response = conn.getresponse()
        except :
#            from traceback import print_exc
#            print_exc()
            print ("fail to connect")
            return  False          
        if response.status == 200:
#            getResourceFolder
            reg_file =  os.path.join(getResourceFolder(),  '.registration')
#            print (reg_file)
            UserID = response.read().decode("utf8")
#            print (UserID)
            if UserID:
                self.form_dict['UserID'] = UserID
                file = open(reg_file,'wb')
                pickle.dump(self.form_dict, file)
                file.close()
                c_reg_file = os.path.join(getResourceFolderWithVersion(),  '.registration')
                shutil.copy(reg_file, c_reg_file)
            else:
                print ("Registration failed to create User.")
                return  False
        else:
            print ("Unable to connect to Registration Database" )
            return  False
        conn.close()        
        return  True
Exemple #20
0
 def __init__(self, masterApp, masterMenu, filePath=None, 
              menuLabel="Open recent", underline=5, index=0):
     """Construct recent files categories. If filePath is not provided
     mglutil/recent.pkl is used to store and load the data"""
     if not filePath: #use "mglutil/recent.pkl" to store the data
         filePath = getResourceFolderWithVersion()
         if filePath is None:
             return
         filePath += os.sep + "mglutil" + os.sep + "recent.pkl"
     if os.path.exists(filePath):
         try:
             self.categories = pickle.load(open(filePath))
         except Exception, inst:
             #print inst
             #print "Couldn't Load Recent Files."
             self.categories = {}
Exemple #21
0
    def __init__(self):
        self.libraries = {}  # stores node libraries

        try:
            # add VisionLibraries to system path
            from Vision.UserLibBuild import addDirToSysPath
            from Vision import __path__
            addDirToSysPath(__path__[0] + 'Libraries')

            # add UserLibs to system path
            from mglutil.util.packageFilePath import getResourceFolderWithVersion
            lCADDResourceFolder = getResourceFolderWithVersion() \
                                    + os.sep + 'CADD' + os.sep
            addDirToSysPath(lCADDResourceFolder + 'UserLibs')
        except:
            pass
Exemple #22
0
def saveFonts4CADDFile(fontDict):
    ##################################################################
    # generate and overwrite _fonts4cadd file
    ##################################################################
    from mglutil.util.packageFilePath import getResourceFolderWithVersion

    caddrcDir = getResourceFolderWithVersion()
    if caddrcDir is None:
        return

    caddrcDir += os.sep + 'CADD'
    if os.path.isdir(caddrcDir) is False:
        return

    fonts4CADDFile = caddrcDir + os.sep + '_fonts4cadd'
    try:
        f = open(fonts4CADDFile, "w")
        txt = txtstr % (
            fontDict['Menus'][0],
            fontDict['Menus'][1],
            fontDict['Menus'][2],
            fontDict['LibTabs'][0],
            fontDict['LibTabs'][1],
            fontDict['LibTabs'][2],
            fontDict['Categories'][0],
            fontDict['Categories'][1],
            fontDict['Categories'][2],
            fontDict['LibNodes'][0],
            fontDict['LibNodes'][1],
            fontDict['LibNodes'][2],
            fontDict['NetTabs'][0],
            fontDict['NetTabs'][1],
            fontDict['NetTabs'][2],
            fontDict['Nodes'][0],
            fontDict['Nodes'][1],
            fontDict['Nodes'][2],
            fontDict['Root'][0],
            fontDict['Root'][1],
            fontDict['Root'][2],
        )

        map(lambda x, f=f: f.write(x), txt)
        f.close()
    except:
        txt = "can not create _fonts4cadd"
        warnings.warn(txt)
Exemple #23
0
 def __init__(self, ):
     UserDict.__init__(self)
     self.dirty = 0  # used to remember that something changed
     self.resourceFile = None
     resourceFolder = getResourceFolderWithVersion()
     if resourceFolder is None:
         return
     self.resourceFile = os.path.join(resourceFolder, '.settings')
     self.defaults = {}
     self.settings = {}
     if os.path.exists(self.resourceFile):
         try:
             pkl_file = open(self.resourceFile)
             self.settings = pickle.load(pkl_file)
             pkl_file.close()
         except Exception, inst:
             print inst, "Error in ", __file__
Exemple #24
0
 def __init__(self, ):
     UserDict.__init__(self)
     self.dirty = 0 # used to remember that something changed
     self.resourceFile = None
     resourceFolder = getResourceFolderWithVersion()
     if resourceFolder is None:
         return
     self.resourceFile =  os.path.join(resourceFolder, '.settings')
     self.defaults = {}
     self.settings = {}
     if os.path.exists(self.resourceFile):
         try:
             pkl_file = open(self.resourceFile)
             self.settings = pickle.load(pkl_file)
             pkl_file.close()
         except Exception, inst:
             print inst, "Error in ", __file__
Exemple #25
0
 def __init__(self):
     MVCommand.__init__(self)
     rc =  getResourceFolderWithVersion() + os.sep + 'ws' + os.sep
     if not os.path.exists(rc):
         os.mkdir(rc)
     self.proxy_gama = rc + 'proxy_gama'
     self.rc_ad = rc + "rc_ad"
     self.login = False
     if hasattr(self, 'vf.GUI.ROOT'):
         self.dpf = Tkinter.StringVar(self.vf.GUI.ROOT)
         self.gpf = Tkinter.StringVar(self.vf.GUI.ROOT)
         self.prev_dir = Tkinter.StringVar(self.vf.GUI.ROOT)
         self.ad_radio = Tkinter.IntVar(self.vf.GUI.ROOT)
     else:
         self.dpf = Tkinter.StringVar()
         self.gpf = Tkinter.StringVar()
         self.prev_dir = Tkinter.StringVar()
         self.ad_radio = Tkinter.IntVar()
     self.current_job = None
def ensureCADDFontsFile():
    ##################################################################
    # verify or generate _fonts4cadd file
    ##################################################################
    from mglutil.util.packageFilePath import getResourceFolderWithVersion
    
    caddrcDir = getResourceFolderWithVersion()
    if caddrcDir is None:
        return
    caddrcDir += os.sep + 'CADD'
    if os.path.isdir(caddrcDir) is False:
        try:
            os.mkdir(caddrcDir)
        except:
            txt = "can not create folder for _fonts4cadd"
            warnings.warn(txt)
            return

    fonts4CADDFile = caddrcDir + os.sep + '_fonts4cadd'
    try:
        f = open(fonts4CADDFile, "w")
        txt = txtstr % (
'helvetica', 10, 'normal',
'helvetica', 10, 'normal',
'helvetica', 10, 'normal',
'helvetica', 10, 'normal',
'helvetica', 10, 'normal',
'helvetica', 10, 'normal',
'helvetica', 10, 'normal'
)

        map( lambda x, f=f: f.write(x), txt )
        f.close()
    except:
        txt = "can not create _fonts4cadd"
        warnings.warn(txt)
    def __init__(self, name='PublicServerLigandDB', **kw):
        import urllib

        kw['name'] = name
        apply( NetworkNode.__init__, (self,), kw )

        kw['name'] = name
        apply( NetworkNode.__init__, (self,), kw )
        ip = self.inputPortsDescr
        ip.append(datatype='string', name='server_lib', required=True, )

        fqdn = "kryptonite.nbcr.net"
        url = "http://" + fqdn + "/pub_ligand_libs.txt"

        publibdir = os.path.join(getResourceFolderWithVersion(), 'ws')

        if not (os.path.exists(publibdir)):
            os.mkdir(publibdir)
        
        publiblocal = os.path.join(publibdir, 'publibs.txt')

        lock = publiblocal + '.lock'

        if os.path.exists(lock) and time.time() - os.path.getmtime(lock) > 15:
            os.remove(lock)
            
        try:
            if not(os.path.exists(lock)):
                open(lock, 'w').close()
                publibweb = urllib2.urlopen(url)
                outfile = open(publiblocal, 'w')
                outfile.write(publibweb.read())
                outfile.close()
                os.remove(lock)
        except:
            print "[INFO]: Getting list of public server libs from cache"
            pass
            

        try:
            f = open(publiblocal, 'r')
            self.choices = f.read().split()
            f.close()
        except:
            self.choices = []
            print "[ERROR]: Unable to public server libs from the web and from cache"

        self.widgetDescr['server_lib'] = {
            'class':'NEComboBox', 'master':'node',
            'choices':self.choices,
            'fixedChoices':True,
            'entryfield_entry_width':18,
            'labelGridCfg':{'sticky':'w'},
            'widgetGridCfg':{'sticky':'w'},
            'labelCfg':{'text':'Server Libraries:'}}

        op = self.outputPortsDescr
        op.append(datatype='LigandDB', name='ligDB')

        code = """def doit(self, server_lib):
    ligDB = LigandDB(server_lib=server_lib)

    self.outputData(ligDB=ligDB)
"""
        self.setFunction(code)
Exemple #28
0
def addOpalServerAsCategory(host, replace=True):
    """
Adds Category named `host` to Web Services Libary. 
replace=True: If the Nodes in `host` Category already exist, this function updates them.
"""
    if replace is False and wslib.libraryDescr.has_key(host):
        # this category is already loaded
        return

    oc = OpalCache()
    mglrd = getResourceFolderWithVersion()
    mglwsdir = os.path.join(mglrd, "ws")
    inactivedir = os.path.join(mglwsdir, "inactives")
    hn = urlparse(host).hostname
    port = urlparse(host).port

    if port != None:
        hn = hn + '+' + str(port)

    inactivehostdir = os.path.join(inactivedir, hn)
    host_cache_dir = os.path.join(mglwsdir, hn)

    if not os.path.exists(mglwsdir):
        os.mkdir(mglwsdir)

    if not os.path.exists(inactivedir):
        os.mkdir(inactivedir)

    if not os.path.exists(inactivehostdir):
        os.mkdir(inactivehostdir)

    try:
        services = Get_Opal_WS(host)  # get list of opal services on host
        active_services = []
        cached_services = []

        for s in services:
            sn = os.path.basename(s)
            active_services.append(sn)

        # old inactive services that are now active

        old_inactives = os.listdir(inactivehostdir)
        now_actives = set(old_inactives) & set(active_services)

        for s in now_actives:
            os.remove(os.path.join(inactivehostdir, s))

        if os.path.exists(host_cache_dir):
            cached_services = os.listdir(host_cache_dir)

        inactive_services = set(cached_services) - set(active_services)

        for s in inactive_services:
            iaf = os.path.join(inactivehostdir, s)

            if not os.path.exists(iaf):
                shutil.copy(os.path.join(host_cache_dir, s), iaf)

        new_inactives = os.listdir(inactivehostdir)

        for s in new_inactives:
            print "*** [WARNING]: " + host + '/services/' + s + " IS NO LONGER AVAILBLE ON THE SERVER!"
    except:  # no internet connection?
        print "WARNING: Loading services for " + host + " from cache"
        services = oc.getServicesFromCache(host, mglwsdir)

    for s in services:
        try:
            if not (os.path.exists(mglwsdir)):
                os.mkdir(mglwsdir)
            oc.writeCache(s, mglwsdir)
        except:
            pass

    if not services:
        print "No Opal web service is found on ", host
        return
    #print "services ", services
    #short_name = host.split('http://')[-1]
    #short_name = short_name.split('.')
    #short_name = short_name[0] + "." + short_name[1]

    for service in services:
        serviceNameOriginal = service.split('/')[-1]
        serviceName = serviceNameOriginal.replace('.', '_')
        serverName = urlparse(service)[1]
        serverName = serverName.replace('.', '_')
        serverName = serverName.split(':')[0]
        serviceOpalWrap = serviceName + "_" + serverName
        #print serviceOpalWrap
        if wslib.libraryDescr.has_key(host):
            for node in wslib.libraryDescr[host]['nodes']:
                if node.name == serviceOpalWrap:
                    wslib.deleteNodeFromCategoryFrame(host,
                                                      FunctionNode,
                                                      nodeName=serviceOpalWrap)
        from WebServices.OpalWrapper import OpalWrapper
        wrapper = OpalWrapper()

        try:
            wrap = wrapper.generate(
                service)  #generate the python wrapper class for the service
        except:
            wrap = wrapper.generate(service, False)

        if wrap is not None:
            #mod = __import__('__main__')
            #for modItemName in set(dir(mod)).difference(dir()):
            #    locals()[modItemName] = getattr(mod, modItemName)
            from mglutil.util.misc import importMainOrIPythonMain
            lMainDict = importMainOrIPythonMain()
            for modItemName in set(lMainDict).difference(dir()):
                locals()[modItemName] = lMainDict[modItemName]

            exec(wrap)
            #print "wrap: ", wrap
            lServiceOpalClass = eval(serviceOpalWrap)
            lServiceOpalClass.sourceCodeWrap = wrap
            # sourceCodeWrap is the source of the Python class wrapping this service
            # An instance of this object will be available in the __main__ scope
            # The source code can be obtained from an instance of this service in a Vision
            # network as follows:  node.function.sourceCodeWrap
            # ALternatively one can type <servicename>.sourceCodeWrap in the Python shell
            # e.g. print Pdb2pqrOpalService_ws_nbcr_net.sourceCodeWrap

            #checking the service name if it contains the version or not
            versionStr = serviceNameOriginal.split("_")[-1]
            versionInt = isVersionValid(versionStr)
            if (versionInt > 0):
                #ok we have a version in the serviceName
                #let's update it in the lServiceOpalClass
                serviceNameNoVersion = serviceNameOriginal.rstrip("_" +
                                                                  versionStr)
                serviceNameNoVersion.replace('.', '_')
                #print "Setting service " + serviceNameNoVersion + " with version " + str( versionInt)
                lServiceOpalClass.serviceName = serviceNameNoVersion
            else:
                #we don't have a version, let's just use the serviceName
                #as it is...
                #print "Setting service with no version " + serviceName
                lServiceOpalClass.serviceName = serviceName
            lServiceOpalClass.version = versionInt
            lServiceOpalClass.serviceOriginalName = serviceNameOriginal.replace(
                '.', '_')

            #setattr(mod, serviceOpalWrap, lServiceOpalClass)
            lMainDict[serviceOpalWrap] = lServiceOpalClass

            # the python wrapper class is callable
            # here we create a Vision FunctionNode to add this Python object
            # to the Vision library
            from WebServices.OpalUtil import OpalWSNode
            wslib.addNode(OpalWSNode,
                          serviceOpalWrap,
                          host,
                          kw={
                              'functionOrString': serviceOpalWrap,
                              'host': host
                          })
def addOpalServerAsCategory(host, replace=True):
    """
Adds Category named `host` to Web Services Libary. 
replace=True: If the Nodes in `host` Category already exist, this function updates them.
"""
    if replace is False and wslib.libraryDescr.has_key(host):
        # this category is already loaded
        return

    oc = OpalCache()
    mglrd =  getResourceFolderWithVersion()
    mglwsdir = os.path.join(mglrd, "ws")
    inactivedir = os.path.join(mglwsdir, "inactives")
    hn = urlparse(host).hostname
    port = urlparse(host).port

    if port != None:
        hn = hn + '+' + str(port)

    inactivehostdir = os.path.join(inactivedir, hn)
    host_cache_dir = os.path.join(mglwsdir, hn)

    if not os.path.exists(mglwsdir):
        os.mkdir(mglwsdir)

    if not os.path.exists(inactivedir):
        os.mkdir(inactivedir)

    if not os.path.exists(inactivehostdir):
        os.mkdir(inactivehostdir)

    try:
        services = Get_Opal_WS(host) # get list of opal services on host 
        active_services = []
        cached_services = []

        for s in services:
            sn = os.path.basename(s)
            active_services.append(sn)

        # old inactive services that are now active

        old_inactives = os.listdir(inactivehostdir)
        now_actives = set(old_inactives) & set(active_services)

        for s in now_actives:
            os.remove(os.path.join(inactivehostdir, s))

        if os.path.exists(host_cache_dir):
            cached_services = os.listdir(host_cache_dir)

        inactive_services = set(cached_services) - set(active_services)

        for s in inactive_services:
            iaf = os.path.join(inactivehostdir, s)

            if not os.path.exists(iaf):
                shutil.copy(os.path.join(host_cache_dir, s), iaf)

        new_inactives = os.listdir(inactivehostdir)

        for s in new_inactives:
            print "*** [WARNING]: " + host + '/services/' + s + " IS NO LONGER AVAILBLE ON THE SERVER!"
    except: # no internet connection?
        print "WARNING: Loading services for " + host + " from cache"
        services = oc.getServicesFromCache(host, mglwsdir)

    for s in services:
        try:
            if not(os.path.exists(mglwsdir)):
                os.mkdir(mglwsdir)
            oc.writeCache(s, mglwsdir)
        except:
            pass

    if not services:
        print "No Opal web service is found on ", host
        return
    #print "services ", services
    #short_name = host.split('http://')[-1]
    #short_name = short_name.split('.')
    #short_name = short_name[0] + "." + short_name[1]

    for service in services:
        serviceNameOriginal = service.split('/')[-1]
        serviceName = serviceNameOriginal.replace('.','_')
        serverName = urlparse(service)[1]
        serverName = serverName.replace('.','_')
        serverName = serverName.split(':')[0]
        serviceOpalWrap = serviceName + "_" + serverName
        #print serviceOpalWrap
        if wslib.libraryDescr.has_key(host):
            for node in wslib.libraryDescr[host]['nodes']:
                if node.name == serviceOpalWrap:
                    wslib.deleteNodeFromCategoryFrame(host, FunctionNode, nodeName=serviceOpalWrap)
        from WebServices.OpalWrapper import OpalWrapper
        wrapper = OpalWrapper()

        try:
            wrap = wrapper.generate(service) #generate the python wrapper class for the service
        except:
            wrap = wrapper.generate(service, False)

        if wrap is not None:
            #mod = __import__('__main__')
            #for modItemName in set(dir(mod)).difference(dir()):
            #    locals()[modItemName] = getattr(mod, modItemName)
            from mglutil.util.misc import importMainOrIPythonMain
            lMainDict = importMainOrIPythonMain()
            for modItemName in set(lMainDict).difference(dir()):
                locals()[modItemName] = lMainDict[modItemName]

            exec(wrap)
            #print "wrap: ", wrap
            lServiceOpalClass = eval(serviceOpalWrap)
            lServiceOpalClass.sourceCodeWrap = wrap
            # sourceCodeWrap is the source of the Python class wrapping this service
            # An instance of this object will be available in the __main__ scope
            # The source code can be obtained from an instance of this service in a Vision
            # network as follows:  node.function.sourceCodeWrap
            # ALternatively one can type <servicename>.sourceCodeWrap in the Python shell
            # e.g. print Pdb2pqrOpalService_ws_nbcr_net.sourceCodeWrap
            
            #checking the service name if it contains the version or not
            versionStr = serviceNameOriginal.split("_")[-1]
            versionInt = isVersionValid(versionStr)
            if ( versionInt > 0 ):
                #ok we have a version in the serviceName
                #let's update it in the lServiceOpalClass
                serviceNameNoVersion = serviceNameOriginal.rstrip("_" + versionStr)
                serviceNameNoVersion.replace('.','_')
                #print "Setting service " + serviceNameNoVersion + " with version " + str( versionInt)
                lServiceOpalClass.serviceName = serviceNameNoVersion
            else:
                #we don't have a version, let's just use the serviceName 
                #as it is...
                #print "Setting service with no version " + serviceName
                lServiceOpalClass.serviceName = serviceName
            lServiceOpalClass.version = versionInt
            lServiceOpalClass.serviceOriginalName = serviceNameOriginal.replace('.','_')
            
            #setattr(mod, serviceOpalWrap, lServiceOpalClass)
            lMainDict[serviceOpalWrap] = lServiceOpalClass

            # the python wrapper class is callable
            # here we create a Vision FunctionNode to add this Python object
            # to the Vision library
            from WebServices.OpalUtil import OpalWSNode
            wslib.addNode(OpalWSNode, serviceOpalWrap, host, 
                          kw={'functionOrString':serviceOpalWrap,
                              'host':host
                             }
                         )
Exemple #30
0
class Register_User:
    """Opens TopLevel Dialog for User Registration"""
    def __init__(self, version=None):
        self.version = version
        master = Tkinter.Toplevel()
        self.master = master
        font = self.master.option_get('font', '*')
        self.master.option_add('*font', "Times 12 bold")
        x = self.master.winfo_screenwidth() / 6
        y = self.master.winfo_screenheight() / 6
        geometry = '+%d+%d' % (x, y)
        self.master.geometry(geometry)
        #self.master.config(font="Helvetica 10 bold italic")
        master.title("MGLTools Registration Form")
        Tkinter.Label(master, text="MGLTools Registration Form").\
                                                        grid(row=0,columnspan=5)
        text = """This data will be kept confidential and will not be made available to any third party."""
        Tkinter.Label(master, text=text).grid(row=1, columnspan=5)

        Tkinter.Label(master, text="Fields in Red are Required",fg="Red" ).\
                                                        grid(row=2,columnspan=5)

        Tkinter.Label(master, text="First Name", fg='Red').grid(row=3,
                                                                sticky='W')
        Tkinter.Label(master, text="Last Name", fg='Red').grid(row=4,
                                                               sticky='W')
        Tkinter.Label(master, text="Email", fg='Red').grid(row=5, sticky='W')
        Tkinter.Label(master, text="Institution", fg='Red').grid(row=6,
                                                                 sticky='W')
        Tkinter.Label(master, text="Institution Type",
                      fg='Red').grid(row=7, sticky='W')
        Tkinter.Label(master, text="Position").grid(row=8, sticky='W')
        Tkinter.Label(
            master,
            text="Department",
        ).grid(row=9, sticky='W')

        Tkinter.Label(master, text="      ").grid(row=6,
                                                  column=2)  #placeholder
        Tkinter.Label(master, text="Address").grid(row=3, column=3, sticky='W')
        Tkinter.Label(master, text="City").grid(row=4, column=3, sticky='W')
        Tkinter.Label(master, text="State").grid(row=5, column=3, sticky='W')
        Tkinter.Label(master, text="PostalCode").grid(row=6,
                                                      column=3,
                                                      sticky='W')
        Tkinter.Label(master, text="Country").grid(row=7, column=3, sticky='W')
        Tkinter.Label(master, text="Phone").grid(row=8, column=3, sticky='W')
        Tkinter.Label(master, text="Fax").grid(row=9, column=3, sticky='W')

        self.e_First_Name = Tkinter.Entry(master, bg="White")
        self.e_Last_Name = Tkinter.Entry(master, bg="White")
        self.e_Email = Tkinter.Entry(master, bg="White")
        self.e_Institution = Tkinter.Entry(master, bg="White")
        self.e_Institution_Type = Pmw.OptionMenu(
            master,
            items=['Academic', 'Government', 'Commercial'],
            menubutton_width=16)
        self.e_Position = Tkinter.Entry(master, bg="White")
        self.e_Department = Tkinter.Entry(master, bg="White")
        self.e_Address = Tkinter.Entry(master, bg="White")
        self.e_City = Tkinter.Entry(master, bg="White")
        self.e_State = Tkinter.Entry(master, bg="White")
        self.e_PostalCode = Tkinter.Entry(master, bg="White")
        self.e_Country = Tkinter.Entry(master, bg="White")
        self.e_Phone = Tkinter.Entry(master, bg="White")
        self.e_Fax = Tkinter.Entry(master, bg="White")
        self.e_First_Name.grid(row=3, column=1)
        self.e_Last_Name.grid(row=4, column=1)
        self.e_Email.grid(row=5, column=1)
        self.e_Institution.grid(row=6, column=1)
        self.e_Institution_Type.grid(row=7, column=1)
        self.e_Position.grid(row=8, column=1)
        self.e_Department.grid(row=9, column=1)
        self.e_Address.grid(row=3, column=4)
        self.e_City.grid(row=4, column=4)
        self.e_State.grid(row=5, column=4)
        self.e_PostalCode.grid(row=6, column=4)
        self.e_Country.grid(row=7, column=4)
        self.e_Phone.grid(row=8, column=4)
        self.e_Fax.grid(row=9, column=4)

        mgl_group = Tkinter.LabelFrame(
            master,
            text="Which of the " +
            "following program(s) are you planning to use?",
            labelanchor='n')
        mgl_group.grid(row=11, columnspan=8, sticky='WESN', pady=5)
        label_message = Tkinter.Label(mgl_group, text="Check all that apply")
        label_message.grid(row=12, columnspan=5)
        self.adt_var = Tkinter.IntVar()
        checkbutton = Tkinter.Checkbutton(mgl_group,
                                          text="AutoDockTools      ",
                                          variable=self.adt_var)
        checkbutton.grid(row=13, column=0)

        self.pmv_var = Tkinter.IntVar()
        checkbutton = Tkinter.Checkbutton(mgl_group,
                                          text="PMV       ",
                                          variable=self.pmv_var)
        checkbutton.grid(row=13, column=2)

        self.vision_var = Tkinter.IntVar()
        checkbutton = Tkinter.Checkbutton(mgl_group,
                                          text="Vision      ",
                                          variable=self.vision_var)
        checkbutton.grid(row=13, column=4)

        self.DejaVu_var = Tkinter.IntVar()
        checkbutton = Tkinter.Checkbutton(mgl_group,
                                          text="DejaVu",
                                          variable=self.DejaVu_var)
        checkbutton.grid(row=13, column=5)

        bin_source = Tkinter.LabelFrame(master,
                                        text="Did you install MGLTools " +
                                        "from Binary and/or Source?",
                                        labelanchor='n')
        bin_source.grid(row=14, columnspan=8, sticky='WESN', pady=5)

        self.bin_var = Tkinter.IntVar()
        checkbutton = Tkinter.Checkbutton(bin_source,
                                          text="Binary     ",
                                          variable=self.bin_var)
        checkbutton.grid(row=15, column=0)

        self.source_var = Tkinter.IntVar()
        checkbutton = Tkinter.Checkbutton(bin_source,
                                          text="Source       ",
                                          variable=self.source_var)
        checkbutton.grid(row=15, column=2)
        self.label_message = Tkinter.Label(master, text="")
        self.label_message.grid(row=16, columnspan=5)  #placeholder

        self.regButton = Tkinter.Button(master,
                                        text='Register',
                                        command=self.Register)
        self.regButton.grid(row=17, column=1, columnspan=2)

        Tkinter.Button(master, text='Cancel',
                       command=self.Cancel).grid(row=17,
                                                 column=3,
                                                 columnspan=2,
                                                 pady=2)
        self.master.option_add('*font', font)
        self.preFill()

    def Register(self):
        self.regButton.configure(state='disabled')
        form_dict = {}
        First_Name = self.e_First_Name.get()
        First_Name = First_Name.strip()
        if not First_Name:
            self.label_message.configure(text='First Name is missing',
                                         fg='Red')
            self.e_First_Name.configure(bg='Red')
            self.regButton.configure(state='normal')
            return
        else:
            self.e_First_Name.configure(bg='White')
            self.label_message.configure(text='')
        form_dict['First_Name'] = First_Name
        Last_Name = self.e_Last_Name.get()
        Last_Name = Last_Name.strip()
        if not Last_Name:
            self.label_message.configure(text='Last Name is missing', fg='Red')
            self.e_Last_Name.configure(bg='Red')
            self.regButton.configure(state='normal')
            return
        else:
            self.e_Last_Name.configure(bg='White')
            self.label_message.configure(text='')
        form_dict['Last_Name'] = Last_Name
        Email = self.e_Email.get()
        Email = Email.strip()
        if not Email or Email.find('@') == -1:
            self.label_message.configure(
                text='Please provide a valid Email address', fg='Red')
            self.e_Email.configure(bg='Red')
            self.regButton.configure(state='normal')
            return
        else:
            self.e_Email.configure(bg='White')
            self.label_message.configure(text='')
        form_dict['Email'] = Email
        Institution = self.e_Institution.get()
        Institution = Institution.strip()
        if not Institution:
            self.label_message.configure(text='Institution is missing',
                                         fg='Red')
            self.e_Institution.configure(bg='Red')
            self.regButton.configure(state='normal')
            return
        else:
            self.e_Institution.configure(bg='White')
            self.label_message.configure(text='')
        form_dict['Institution'] = Institution
        Institution_Type = self.e_Institution_Type.getvalue()
        if Institution_Type not in ['Academic', 'Government', 'Commercial']:
            self.label_message.configure(text='Institution Type should be\
            Academic,Government or Commercial',
                                         fg='Red')
            self.regButton.configure(state='normal')
            return
        else:
            self.label_message.configure(text='')
        form_dict['Institution_Type'] = Institution_Type
        Position = self.e_Position.get()
        Position = Position.strip()
        if not Position:
            Position = ' '
        form_dict['Position'] = Position
        Department = self.e_Department.get()
        Department = Department.strip()
        form_dict['Department'] = Department
        Address = self.e_Address.get()
        Address = Address.strip()
        form_dict['Address'] = Address
        City = self.e_City.get()
        City = City.strip()
        form_dict['City'] = City
        State = self.e_State.get()
        State = State.strip()
        form_dict['State'] = State
        PostalCode = self.e_PostalCode.get()
        PostalCode = PostalCode.strip()
        form_dict['PostalCode'] = PostalCode
        Country = self.e_Country.get()
        Country = Country.strip()
        form_dict['Country'] = Country
        Phone = self.e_Phone.get()
        Phone = Phone.strip()
        form_dict['Phone'] = Phone
        Fax = self.e_Fax.get()
        Fax = Fax.strip()
        form_dict['Fax'] = Fax
        planning_to_use = ''
        if self.adt_var.get():
            planning_to_use = 'ADT'
        if self.pmv_var.get():
            planning_to_use += ',PMV'
        if self.vision_var.get():
            planning_to_use += ',Vision'
        if self.DejaVu_var.get():
            planning_to_use += ',DejaVu'

        form_dict['PlanningToUse'] = planning_to_use
        build_from = ''
        if self.bin_var.get():
            build_from = 'Binary'
        if self.source_var.get():
            build_from += ',Source'
        form_dict['BuildFrom'] = build_from
        self.label_message.configure(text='Submitting the Registration Form')
        form_dict['version'] = self.version.split('(')[0]
        os_name = os.name
        form_dict['os_name'] = os_name
        sys_platfrom = sys.platform
        form_dict['sys_platfrom'] = sys_platfrom
        sys_version = sys.version
        form_dict['sys_version'] = sys_version.replace('\n', '')
        try:
            hostname = gethostname()
            form_dict['hostname'] = hostname
        except:
            form_dict['hostname'] = "problem"
        params = urllib.urlencode(form_dict)
        self.label_message.configure(text='Please Wait', fg='Red')
        headers = {
            "Content-type": "application/x-www-form-urlencoded",
            "Accept": "text/plain"
        }
        conn = httplib.HTTPConnection("www.scripps.edu:80")
        try:
            conn.request("POST", "/cgi-bin/sanner/register_mgltools.py",
                         params, headers)
            response = conn.getresponse()
        except Exception, inst:
            from traceback import print_exc
            print_exc()
            return

        self.master.update()
        if response.status == 200:
            getResourceFolder
            reg_file = os.path.join(getResourceFolder(), '.registration')
            UserID = response.read()
            if UserID:
                form_dict['UserID'] = UserID
                file = open(reg_file, 'w')
                pickle.dump(form_dict, file)
                file.close()
                c_reg_file = os.path.join(getResourceFolderWithVersion(),
                                          '.registration')
                shutil.copy(reg_file, c_reg_file)
            else:
                tkMessageBox.showerror("ERROR", "Registration failed.")
                self.regButton.configure(state='normal')
                return
        else:
            tkMessageBox.showerror(
                "ERROR", "Unable to connect to Registration Database" +
                "\nPlease try again")
            self.regButton.configure(state='normal')
            return
        conn.close()
        self.Cancel()
        tkMessageBox.showinfo("Thank You",
                              "Thank you for registering MGLTools!")
def ensureDefaultUserLibFile():
    ##################################################################
    # verify or generate the default user lib file
    ##################################################################
    from mglutil.util.packageFilePath import getResourceFolderWithVersion
    userResourceFolder = getResourceFolderWithVersion()
    if userResourceFolder is None:
        return
    userVisionDir = userResourceFolder + os.sep + 'Vision' + os.sep
    userLibsDir = userVisionDir + 'UserLibs' + os.sep
    defaultLibDir = userLibsDir + 'MyDefaultLib' + os.sep
    defaultLibInit = defaultLibDir + '__init__.py'
    libTypesFile = defaultLibDir + 'libTypes.py'
    if os.path.isfile(defaultLibInit) is False:
        try:
            if os.path.isdir(userResourceFolder) is False:
                os.mkdir(userResourceFolder)
            if os.path.isdir(userVisionDir) is False:
                os.mkdir(userVisionDir)
            if os.path.isdir(userLibsDir) is False:
                os.mkdir(userLibsDir)
            #userLibsInit = userLibsDir + '__init__.py'
            #if os.path.isfile(userLibsInit) is False:
            #    f = open(userLibsInit, "w")
            #    f.close()
            if os.path.isdir(defaultLibDir) is False:
                os.mkdir(defaultLibDir)
            category1Dir = defaultLibDir + 'Input' + os.sep
            if os.path.isdir(category1Dir) is False:
                os.mkdir(category1Dir)
            category1Init = category1Dir + '__init__.py'
            if os.path.isfile(category1Init) is False:
                f = open(category1Init, "w")
                f.close()
            category2Dir = defaultLibDir + 'Output' + os.sep
            if os.path.isdir(category2Dir) is False:
                os.mkdir(category2Dir)
            category2Init = category2Dir + '__init__.py'
            if os.path.isfile(category2Init) is False:
                f = open(category2Init, "w")
                f.close()
            category3Dir = defaultLibDir + 'Macro' + os.sep
            if os.path.isdir(category3Dir) is False:
                os.mkdir(category3Dir)
            category3Init = category3Dir + '__init__.py'
            if os.path.isfile(category3Init) is False:
                f = open(category3Init, "w")
                f.close()
            category4Dir = defaultLibDir + 'Other' + os.sep
            if os.path.isdir(category4Dir) is False:
                os.mkdir(category4Dir)
            category4Init = category4Dir + '__init__.py'
            if os.path.isfile(category4Init) is False:
                f = open(category4Init, "w")
                f.close()
            f = open(defaultLibInit, "w")
            txt = """########################################################################
#
# Date: Jan 2006 Authors: Guillaume Vareille, Michel Sanner
#
#    [email protected]
#    [email protected]
#
#       The Scripps Research Institute (TSRI)
#       Molecular Graphics Lab
#       La Jolla, CA 92037, USA
#
# Copyright: Guillaume Vareille, Michel Sanner and TSRI
#
#    Vision Library Loader
#
#########################################################################
#
# %s
# Vision will generate this file automatically if it can't find it
#

from os import sep, path
from Vision.VPE import NodeLibrary
from Vision.UserLibBuild import userLibBuild, addDirToSysPath, addTypes

dependents = {} # {'scipy':'0.6.0',} the numbers indicate the highest tested version of the needed packages
libraryColor = '#FF7700'

addDirToSysPath(path.dirname(__file__)+sep+'..')
fileSplit = __file__.split(sep)
if fileSplit[-1] == '__init__.pyc' or fileSplit[-1] == '__init__.py':
    libInstanceName = fileSplit[-2]
else:
    libInstanceName = path.splitext(fileSplit[-1])[0]
try:
    from Vision import ed
except:
    ed = None
if ed is not None and ed.libraries.has_key(libInstanceName):
    locals()[libInstanceName] = ed.libraries[libInstanceName]
else:
    locals()[libInstanceName] = NodeLibrary(libInstanceName, libraryColor, mode='readWrite')
success = userLibBuild(eval(libInstanceName), __file__, dependents=dependents)
if success is False:
    locals().pop(libInstanceName)
elif path.isfile(path.dirname(__file__)+sep+'libTypes.py'):
    addTypes(locals()[libInstanceName], libInstanceName + '.libTypes')

""" % defaultLibInit
            map( lambda x, f=f: f.write(x), txt )
            f.close()
            os.chmod(defaultLibInit, 0444) #make it read only

            f = open(libTypesFile, "w")
            txt = """########################################################################
#
# Date: Jan 2006 Authors: Guillaume Vareille, Michel Sanner
#
#    [email protected]
#    [email protected]
#
#       The Scripps Research Institute (TSRI)
#       Molecular Graphics Lab
#       La Jolla, CA 92037, USA
#
# Copyright: Guillaume Vareille, Michel Sanner and TSRI
#
#    Vision Library Types
#
#########################################################################
#
# %s
# Vision will generate this file automatically if it can't find it
#

from NetworkEditor.datatypes import AnyArrayType

############################################################
# add new types to your library that the node ports can use. 
############################################################

#class ThingType(AnyArrayType):
#
#    from ThingPackage import Thing
#    def __init__(self, name='thing', color='#995699', shape='rect',
#                 klass=Thing):
#
#        AnyArrayType.__init__(self, name=name, color=color, shape=shape, 
#                              klass=klass)
#
## in NetworkEditor.datatypes, you should have a look at the class IntType

""" % libTypesFile
            map( lambda x, f=f: f.write(x), txt )
            f.close()

        except:
            txt = "Cannot write the init files %s and %s" %(defaultLibInit,libTypesFile)
            warnings.warn(txt)
Exemple #32
0
    def Register(self):
        self.regButton.configure(state='disabled')
        form_dict = {}
        First_Name = self.e_First_Name.get()
        First_Name = First_Name.strip()
        if not First_Name:
            self.label_message.configure(text='First Name is missing',
                                         fg='Red')
            self.e_First_Name.configure(bg='Red')
            self.regButton.configure(state='normal')
            return
        else:
            self.e_First_Name.configure(bg='White')
            self.label_message.configure(text='')
        form_dict['First_Name'] = First_Name
        Last_Name = self.e_Last_Name.get()
        Last_Name = Last_Name.strip()
        if not Last_Name:
            self.label_message.configure(text='Last Name is missing', fg='Red')
            self.e_Last_Name.configure(bg='Red')
            self.regButton.configure(state='normal')
            return
        else:
            self.e_Last_Name.configure(bg='White')
            self.label_message.configure(text='')
        form_dict['Last_Name'] = Last_Name
        Email = self.e_Email.get()
        Email = Email.strip()
        if not Email or Email.find('@') == -1:
            self.label_message.configure(
                text='Please provide a valid Email address', fg='Red')
            self.e_Email.configure(bg='Red')
            self.regButton.configure(state='normal')
            return
        else:
            self.e_Email.configure(bg='White')
            self.label_message.configure(text='')
        form_dict['Email'] = Email
        Institution = self.e_Institution.get()
        Institution = Institution.strip()
        if not Institution:
            self.label_message.configure(text='Institution is missing',
                                         fg='Red')
            self.e_Institution.configure(bg='Red')
            self.regButton.configure(state='normal')
            return
        else:
            self.e_Institution.configure(bg='White')
            self.label_message.configure(text='')
        form_dict['Institution'] = Institution
        Institution_Type = self.e_Institution_Type.getvalue()
        if Institution_Type not in ['Academic', 'Government', 'Commercial']:
            self.label_message.configure(text='Institution Type should be\
            Academic,Government or Commercial',
                                         fg='Red')
            self.regButton.configure(state='normal')
            return
        else:
            self.label_message.configure(text='')
        form_dict['Institution_Type'] = Institution_Type
        Position = self.e_Position.get()
        Position = Position.strip()
        if not Position:
            Position = ' '
        form_dict['Position'] = Position
        Department = self.e_Department.get()
        Department = Department.strip()
        form_dict['Department'] = Department
        Address = self.e_Address.get()
        Address = Address.strip()
        form_dict['Address'] = Address
        City = self.e_City.get()
        City = City.strip()
        form_dict['City'] = City
        State = self.e_State.get()
        State = State.strip()
        form_dict['State'] = State
        PostalCode = self.e_PostalCode.get()
        PostalCode = PostalCode.strip()
        form_dict['PostalCode'] = PostalCode
        Country = self.e_Country.get()
        Country = Country.strip()
        form_dict['Country'] = Country
        Phone = self.e_Phone.get()
        Phone = Phone.strip()
        form_dict['Phone'] = Phone
        Fax = self.e_Fax.get()
        Fax = Fax.strip()
        form_dict['Fax'] = Fax
        planning_to_use = ''
        if self.adt_var.get():
            planning_to_use = 'ADT'
        if self.pmv_var.get():
            planning_to_use += ',PMV'
        if self.vision_var.get():
            planning_to_use += ',Vision'
        if self.DejaVu_var.get():
            planning_to_use += ',DejaVu'

        form_dict['PlanningToUse'] = planning_to_use
        build_from = ''
        if self.bin_var.get():
            build_from = 'Binary'
        if self.source_var.get():
            build_from += ',Source'
        form_dict['BuildFrom'] = build_from
        self.label_message.configure(text='Submitting the Registration Form')
        form_dict['version'] = self.version.split('(')[0]
        os_name = os.name
        form_dict['os_name'] = os_name
        sys_platfrom = sys.platform
        form_dict['sys_platfrom'] = sys_platfrom
        sys_version = sys.version
        form_dict['sys_version'] = sys_version.replace('\n', '')
        try:
            hostname = gethostname()
            form_dict['hostname'] = hostname
        except:
            form_dict['hostname'] = "problem"

        params = urllib.urlencode(form_dict)
        self.label_message.configure(text='Please Wait', fg='Red')
        headers = {
            "Content-type": "application/x-www-form-urlencoded",
            "Accept": "text/plain"
        }
        #        conn = httplib.HTTPConnection("www.scripps.edu:80")
        conn = httplib.HTTPConnection("mgldev.scripps.edu:80")
        #print conn
        #        try:
        #            conn.request("POST", "/cgi-bin/sanner/register_mgltools.py", params, headers)
        conn.request("POST", "/cgi-bin/register_mgltools.py", params, headers)
        response = conn.getresponse()
        #        print response.status
        #        except Exception, inst:
        #            from traceback import print_exc
        #            print "problem connecting registration"
        #            print_exc()
        #            return

        self.master.update()
        if response.status == 200:
            #            getResourceFolder
            reg_file = os.path.join(getResourceFolder(), '.registration')
            UserID = response.read().decode("utf8")
            #            print  "response",response.read(),UserID
            if UserID:
                form_dict['UserID'] = UserID
                file = open(reg_file, 'w')
                pickle.dump(form_dict, file)
                file.close()
                c_reg_file = os.path.join(getResourceFolderWithVersion(),
                                          '.registration')
                shutil.copy(reg_file, c_reg_file)
            else:
                tkMessageBox.showerror("ERROR", "Registration failed.")
                self.regButton.configure(state='normal')
                return
        else:
            tkMessageBox.showerror(
                "ERROR", "Unable to connect to Registration Database" +
                "\nPlease try again")
            self.regButton.configure(state='normal')
            return
        conn.close()
        self.Cancel()
        tkMessageBox.showinfo("Thank You",
                              "Thank you for registering MGLTools!")
 def showuploadpage_cb(self,sumcont,desccont,atcont,email_ent,
                       product="Pure Python", version="unspecified"):
     if self.component==None:
         return
    
     import urllib
     idnum = None
     ###################
     #find date and time
     ###################
     d = os.popen("date '+20%y-%m-%d'")
     date = d.readlines()[0][:-1]
     t = os.popen("date '+%H:%M:%S'")
     time = t.readlines()[0][:-1]
     deltaval = date+" "+time
     desccont += "\n sys.version: " + sys.version
     from mglutil.util.packageFilePath import findFilePath, getResourceFolderWithVersion
     registration = getResourceFolderWithVersion() + os.sep + '.registration'
     if os.path.exists(registration):
         import pickle
         desccont += "\n UserID: " + pickle.load(open(registration))['UserID'].strip()
     else:
         desccont += "\n Unregistered User"
     ###############################################
     ##Feeding post_bug.cgi form with required input
     ###############################################
     params = urllib.urlencode({"Bugzilla_login":"******",
                                "Bugzilla_password":"******","version":version,
                                "rep_platform":"All","priority":"P2",
                                "op_sys":"All","bug_severity":"normal",
                                "bug_status":"NEW","cc":" ",
                                "product":product,
                                "component":"%s"  %self.component,
                                "assigned_to":"*****@*****.**",
                                "short_desc":"%s" %sumcont,
                                "comment":"%s" %desccont,
                                "bug_file_loc":" ","cc":email_ent} )
     #post
     fptr = urllib.urlopen("http://mgldev.scripps.edu/bugs/post_bug.cgi",params)
     data =fptr.readlines()
     for d in data:
         if d.endswith("Submitted</title>\n"):
             idnum = d.split(" ")[-2]
             break
     if not idnum:
         print "Failed to submit bug report"
         print "Visit http://mgldev.scripps.edu/bugs to submit this bug report. Thank you."
         return
     #for attaching files
     if len(atcont)>0:
         filelist=list(atcont)
         for f in filelist:
             if len(f)>=1:
                 params1 =  {"Bugzilla_login":"******","Bugzilla_password":"******","bugid":"%i" %int(idnum),"action":"insert","description":"file  attached","ispatch":"0","contenttypemethod":"autodetect","comment":" ","obsolete":"",'contenttypeselection':"",'contenttypeentry':"",'data':open(f)}
                 ###################
                 #HTTP + MULTIPART 
                 ########################
                 import urllib2
                 import MultipartPostHandler
                 opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
                 urllib2.install_opener(opener)
                 req = urllib2.Request("http://mgldev.scripps.edu/bugs/attachment.cgi",params1)
                 response = urllib2.urlopen(req).read().strip()
      
     return idnum       
Exemple #34
0
    def showuploadpage_cb(self,
                          sumcont,
                          desccont,
                          atcont,
                          email_ent,
                          product="Pure Python",
                          version="unspecified"):
        if self.component == None:
            return

        import urllib.request, urllib.parse, urllib.error
        idnum = None
        ###################
        #find date and time
        ###################
        d = os.popen("date '+20%y-%m-%d'")
        date = d.readlines()[0][:-1]
        t = os.popen("date '+%H:%M:%S'")
        time = t.readlines()[0][:-1]
        deltaval = date + " " + time
        desccont += "\n sys.version: " + sys.version
        from mglutil.util.packageFilePath import findFilePath, getResourceFolderWithVersion
        registration = getResourceFolderWithVersion(
        ) + os.sep + '.registration'
        if os.path.exists(registration):
            import pickle
            try:
                desccont += "\n UserID: " + pickle.load(
                    open(registration))['UserID'].strip()
            except Exception as inst:
                warnings.warn(inst)
                desccont += "\n Unregistered User"
        else:
            desccont += "\n Unregistered User"
        ###############################################
        ##Feeding post_bug.cgi form with required input
        ###############################################
        params = urllib.parse.urlencode({
            "Bugzilla_login": "******",
            "Bugzilla_password": "******",
            "version": version,
            "rep_platform": "All",
            "priority": "P2",
            "op_sys": "All",
            "bug_severity": "normal",
            "bug_status": "NEW",
            "cc": " ",
            "product": product,
            "component": "%s" % self.component,
            "assigned_to": "*****@*****.**",
            "short_desc": "%s" % sumcont,
            "comment": "%s" % desccont,
            "bug_file_loc": " ",
            "cc": email_ent
        })
        #post
        fptr = urllib.request.urlopen(
            "http://mgldev.scripps.edu/bugs/post_bug.cgi", params)
        data = fptr.readlines()
        for d in data:
            if d.endswith("</title>\n"):
                idnum = d.split(" ")[5]
                break
        if not idnum:
            return

        try:  #this part is needed for debugging
            int(idnum)
        except:
            print(data)
        #for attaching files
        if len(atcont) > 0:
            filelist = list(atcont)
            for f in filelist:
                if len(f) >= 1:
                    params1 = {
                        "Bugzilla_login": "******",
                        "Bugzilla_password": "******",
                        "bugid": "%i" % int(idnum),
                        "action": "insert",
                        "description": "file  attached",
                        "ispatch": "0",
                        "contenttypemethod": "autodetect",
                        "comment": " ",
                        "obsolete": "",
                        'contenttypeselection': "",
                        'contenttypeentry': "",
                        'data': open(f)
                    }
                    ###################
                    #HTTP + MULTIPART
                    ########################
                    import urllib.request, urllib.error, urllib.parse
                    from . import MultipartPostHandler
                    opener = urllib.request.build_opener(
                        MultipartPostHandler.MultipartPostHandler)
                    urllib.request.install_opener(opener)
                    req = urllib.request.Request(
                        "http://mgldev.scripps.edu/bugs/attachment.cgi",
                        params1)
                    req.add_header('Content-Type', 'text/plain')
                    response = urllib.request.urlopen(req).read().strip()

        return idnum
Exemple #35
0
def ensureDefaultUserLibFileCADD():
    ##################################################################
    # verify or generate the default user lib file
    ##################################################################
    from mglutil.util.packageFilePath import getResourceFolderWithVersion
    userResourceFolder = getResourceFolderWithVersion()
    if userResourceFolder is None:
        return
    userCADDDir = userResourceFolder + os.sep + 'CADD' + os.sep
    userLibsDir = userCADDDir + 'UserLibs' + os.sep
    defaultLibDir = userLibsDir + 'MyDefaultLib' + os.sep
    defaultLibInit = defaultLibDir + '__init__.py'
    libTypesFile = defaultLibDir + 'libTypes.py'
    if os.path.isfile(defaultLibInit) is False:
        try:
            if os.path.isdir(userResourceFolder) is False:
                os.mkdir(userResourceFolder)
            if os.path.isdir(userCADDDir) is False:
                os.mkdir(userCADDDir)
            if os.path.isdir(userLibsDir) is False:
                os.mkdir(userLibsDir)
            if os.path.isdir(defaultLibDir) is False:
                os.mkdir(defaultLibDir)
            category1Dir = defaultLibDir + 'Input' + os.sep
            if os.path.isdir(category1Dir) is False:
                os.mkdir(category1Dir)
            category1Init = category1Dir + '__init__.py'
            if os.path.isfile(category1Init) is False:
                f = open(category1Init, "w")
                f.close()
            category2Dir = defaultLibDir + 'Output' + os.sep
            if os.path.isdir(category2Dir) is False:
                os.mkdir(category2Dir)
            category2Init = category2Dir + '__init__.py'
            if os.path.isfile(category2Init) is False:
                f = open(category2Init, "w")
                f.close()
            category3Dir = defaultLibDir + 'Macro' + os.sep
            if os.path.isdir(category3Dir) is False:
                os.mkdir(category3Dir)
            category3Init = category3Dir + '__init__.py'
            if os.path.isfile(category3Init) is False:
                f = open(category3Init, "w")
                f.close()
            category4Dir = defaultLibDir + 'Other' + os.sep
            if os.path.isdir(category4Dir) is False:
                os.mkdir(category4Dir)
            category4Init = category4Dir + '__init__.py'
            if os.path.isfile(category4Init) is False:
                f = open(category4Init, "w")
                f.close()
            f = open(defaultLibInit, "w")
            txt = """########################################################################
#
# Date: Jan 2006 Authors: Guillaume Vareille, Michel Sanner
#
#    [email protected]
#    [email protected]
#
#       The Scripps Research Institute (TSRI)
#       Molecular Graphics Lab
#       La Jolla, CA 92037, USA
#
# Copyright: Guillaume Vareille, Michel Sanner and TSRI
#
#    Vision Library Loader
#
#########################################################################
#
# %s
# Vision will generate this file automatically if it can't find it
#

from os import sep, path
from Vision.VPE import NodeLibrary
from Vision.UserLibBuild import userLibBuild, addDirToSysPath, addTypes

dependents = {} # {'scipy':'0.6.0',} the numbers indicate the highest tested version of the needed packages
libraryColor = '#FF7700'

addDirToSysPath(path.dirname(__file__)+sep+'..')
fileSplit = __file__.split(sep)
if fileSplit[-1] == '__init__.pyc' or fileSplit[-1] == '__init__.py':
    libInstanceName = fileSplit[-2]
else:
    libInstanceName = path.splitext(fileSplit[-1])[0]
try:
    from Vision import ed
except:
    ed = None
if ed is not None and ed.libraries.has_key(libInstanceName):
    locals()[libInstanceName] = ed.libraries[libInstanceName]
else:
    locals()[libInstanceName] = NodeLibrary(libInstanceName, libraryColor, mode='readWrite')
success = userLibBuild(eval(libInstanceName), __file__, dependents=dependents)
if success is False:
    locals().pop(libInstanceName)
elif path.isfile(path.dirname(__file__)+sep+'libTypes.py'):
    addTypes(locals()[libInstanceName], libInstanceName + '.libTypes')

""" % defaultLibInit
            map(lambda x, f=f: f.write(x), txt)
            f.close()
            os.chmod(defaultLibInit, 0444)  #make it read only

            f = open(libTypesFile, "w")
            txt = """########################################################################
#
# Date: Jan 2006 Authors: Guillaume Vareille, Michel Sanner
#
#    [email protected]
#    [email protected]
#
#       The Scripps Research Institute (TSRI)
#       Molecular Graphics Lab
#       La Jolla, CA 92037, USA
#
# Copyright: Guillaume Vareille, Michel Sanner and TSRI
#
#    Vision Library Types
#
#########################################################################
#
# %s
# Vision will generate this file automatically if it can't find it
#

from NetworkEditor.datatypes import AnyArrayType

############################################################
# add new types to your library that the node ports can use. 
############################################################

#class ThingType(AnyArrayType):
#
#    from ThingPackage import Thing
#    def __init__(self, name='thing', color='#995699', shape='rect',
#                 klass=Thing):
#
#        AnyArrayType.__init__(self, name=name, color=color, shape=shape, 
#                              klass=klass)
#
## in NetworkEditor.datatypes, you should have a look at the class IntType

""" % libTypesFile
            map(lambda x, f=f: f.write(x), txt)
            f.close()

        except:
            txt = "Cannot write the init files %s and %s" % (defaultLibInit,
                                                             libTypesFile)
            warnings.warn(txt)
Exemple #36
0
    def __init__(self, name='PublicServerLigandDB', **kw):
        import urllib

        kw['name'] = name
        apply(NetworkNode.__init__, (self, ), kw)

        kw['name'] = name
        apply(NetworkNode.__init__, (self, ), kw)
        ip = self.inputPortsDescr
        ip.append(
            datatype='string',
            name='server_lib',
            required=True,
        )

        fqdn = "kryptonite.nbcr.net"
        url = "http://" + fqdn + "/pub_ligand_libs.txt"

        publibdir = os.path.join(getResourceFolderWithVersion(), 'ws')

        if not (os.path.exists(publibdir)):
            os.mkdir(publibdir)

        publiblocal = os.path.join(publibdir, 'publibs.txt')

        lock = publiblocal + '.lock'

        if os.path.exists(lock) and time.time() - os.path.getmtime(lock) > 15:
            os.remove(lock)

        try:
            if not (os.path.exists(lock)):
                open(lock, 'w').close()
                publibweb = urllib2.urlopen(url)
                outfile = open(publiblocal, 'w')
                outfile.write(publibweb.read())
                outfile.close()
                os.remove(lock)
        except:
            print "[INFO]: Getting list of public server libs from cache"
            pass

        try:
            f = open(publiblocal, 'r')
            self.choices = f.read().split()
            f.close()
        except:
            self.choices = []
            print "[ERROR]: Unable to public server libs from the web and from cache"

        self.widgetDescr['server_lib'] = {
            'class': 'NEComboBox',
            'master': 'node',
            'choices': self.choices,
            'fixedChoices': True,
            'entryfield_entry_width': 18,
            'labelGridCfg': {
                'sticky': 'w'
            },
            'widgetGridCfg': {
                'sticky': 'w'
            },
            'labelCfg': {
                'text': 'Server Libraries:'
            }
        }

        op = self.outputPortsDescr
        op.append(datatype='LigandDB', name='ligDB')

        code = """def doit(self, server_lib):
    ligDB = LigandDB(server_lib=server_lib)

    self.outputData(ligDB=ligDB)
"""
        self.setFunction(code)
  def generate(self,url,conn=True):
    oc = OpalCache()

    if conn == True:
      if oc.isCacheValid(url, os.path.join(getResourceFolderWithVersion(), 'ws')):
        conn = False

    if conn == True:
      self.metadata = self.getAppMetadata(url)
    else:
      print "[INFO]: Generating Opal Wrapper for " + url + " from cache"

    self.url = url

    #setting up for local execution
    
    if conn == True:
      try:
        executable = self.getAppConfig(url)._binaryLocation
      except:
        executable = 'NA'
        pass
    else:
      dir = os.path.join(getResourceFolderWithVersion(), 'ws')
      executable = oc.getBinaryLocation(url, dir)
      params = oc.getParams(self.url, dir)
      self.params = oc.getParams(self.url, dir)

    # assuming the server is a unix
    executable = executable.rpartition("/")[2]

    if self.which(executable) == None:
        self.executable = ""
    else:
        self.executable = self.which(executable)

    if conn == True:
      classdec = self.buildClassDeclaration(self.metadata,self.url)

      if (self.metadata._types):
        initmethod = self.buildInitMethod(self.metadata, self.url)
        callmethod = self.buildCallMethod(self.metadata)
      else:
        initmethod = self.buildDefaultInitMethod(self.url)
        callmethod = self.buildDefaultCallMethod()
    else:
      classdec = self.buildClassDeclarationFromCache(self.url, params)

      if params:
        initmethod = self.buildInitMethodFromCache(params, self.url)
        callmethod = self.buildCallMethodFromCache(params)
      else:
        initmethod = self.buildDefaultInitMethodFromCache(self.url)
        callmethod = self.buildDefaultCallMethod()

    retclass = ""

    for i in classdec:
      retclass+=(str(i)+"\n")

    allmethods = []
    allmethods.extend(initmethod)
    allmethods.extend(callmethod)
    for i in allmethods:
      retclass+=(tab+str(i)+"\n")
    #add the onStoppingExecution before returning
    return retclass
Exemple #38
0
    def guiCallback(self):
        if self.master == None:
            self.master = Tkinter.Toplevel()
            self.master.protocol('WM_DELETE_WINDOW', self.destroy)

            self.vf.help_about.gui(master=self.master)
            self.vf.help_about.imageTk.bind('<1>', self.nextImage)

            notebook = Pmw.NoteBook(self.master)
            notebook.pack(expand='yes', fill='both')

            page = notebook.add('Authors')
            #notebook.tab('Authors').focus_set()
            # Authors
            from PIL import Image, ImageTk
            image = Image.open(self.vf.help_about.icon)
            self.icon_image = ImageTk.PhotoImage(master=page, image=image)
            self.image2 = Tkinter.Label(page, image=self.icon_image)
            self.image2.pack(side='left')

            Tkinter.Label(
                page,
                text=self.vf.help_about.authors,
                fg='#662626',
                justify='left',
                anchor='w',
            ).pack(side='left')

            # 3rd party
            if len(self.vf.help_about.third_party):
                page = notebook.add('Third party software components')

                Tkinter.Label(
                    page,
                    text=self.vf.help_about.third_party,
                    fg='#0A3A75',
                    justify='left',
                    anchor='w',
                ).pack(side='left')

            # app info group
            if len(self.vf.help_about.path_data):
                page = notebook.add('Path information')
                Tkinter.Label(
                    page,
                    text=self.vf.help_about.path_data,
                    fg='#3A9E23',
                    justify='left',
                    anchor='w',
                ).pack(side='left')

            Tkinter.Label(self.master, text='              ').pack(side='left')
            l = Tkinter.Label(self.master,
                              fg='Blue',
                              cursor='hand1',
                              text='http://mgltools.scripps.edu')
            l.pack(side='left')
            l.bind(sequence="<Button-1>", func=self.openurl)
            Tkinter.Label(self.master, text='              ').pack(side='left')

            registration = getResourceFolderWithVersion(
            ) + os.sep + '.registration'
            if not os.path.exists(registration):
                reg = Tkinter.Button(self.master,
                                     text='   Register   ',
                                     command=self.register)
                reg.pack(side='left')
            b = Tkinter.Button(self.master,
                               text='   Close   ',
                               command=self.destroy)
            b.pack(side='left')
            notebook.setnaturalsize()
        else:
            self.master.deiconify()
            self.master.lift()
    def __init__(self, about, noSplash=False, app=None):
        """Constructor for SplashScreen"""
        self.app = app
        name = validFilename(about.title)
        self.version = about.version
        rcWithVersion = getResourceFolderWithVersion()
        if rcWithVersion is not None:
            registration = rcWithVersion + os.sep + '.registration'
            self.timing_rc = rcWithVersion + os.sep + '.timing_' + name
            self.usage_rc = rcWithVersion + os.sep + '.usage_' + name
            try:
                open(self.usage_rc, 'a').write(str(time.time()) + "\n")
            except:
                pass
        else:
            registration = None
            self.timing_rc = None
            self.usage_rc = None

        self.noSplash = noSplash
        self.registered = False  # change this to False to check registration
        self.register = None

        # check if the user has registered
        if registration is None or os.path.exists(registration):
            self.registered = True
            #self.check_for_updates(registration)
        else:
            # count number of use and ask to register
            lines = open(self.usage_rc).readlines()
            if len(lines) < 10:
                self.registered = True

        self.waitTk = tkinter.IntVar()
        self.percent = 0
        if self.timing_rc is None:
            self.timing_data = []
        else:

            try:
                timing_file = open(self.timing_rc, 'r+')
            except:
                timing_file = open(self.timing_rc, 'w+')
            self.timing_data = timing_file.readlines()
            timing_file.close()
            ###self.percent = 0
            if self.timing_data:
                for data in self.timing_data:
                    self.percent += int(data)
                self.percent = int(self.percent / len(self.timing_data))
                self.percent = 100 / self.percent
        if self.percent == 0: self.percent = 1
        self.counter = 0

        if self.registered and self.noSplash:
            return

        self.splash_win = tkinter.Toplevel()
        self.splash_win.overrideredirect(1)
        self.splash_win.withdraw()
        _splashDisplayed[self.app] = self

        frame = tkinter.Frame(self.splash_win, relief='raised', bd=3)
        frame.pack()
        try:
            about.gui(master=frame)
        except Exception as inst:
            print(inst)
        self.progressBar = ProgressBar(master=frame,
                                       labelside=None,
                                       width=420,
                                       height=20,
                                       mode='percent')
        self.progressBar.setLabelText('Loading Modules...')
        self.progressBar.set(0)

        if not self.registered:
            text = """ Please Register! It helps us secure funding for
supporting development and you won't have to
click these buttons again in the future. Thanks."""
            tkinter.Label(frame, text = text, font =(ensureFontCase('helvetica'), 14, 'bold') ).\
                                                                          pack()
            tkinter.Button(frame,
                           text='Register Now',
                           bg='Green',
                           command=self.Register_Now).pack(side='left')
            self.Later_Button = tkinter.Button(frame,
                                               text='Remind Me Later',
                                               state='disabled',
                                               command=self.Later)
            self.Later_Button.pack(side='right')

        self._updateprogressBar()
        self.splash_win.update_idletasks()

        width = self.splash_win.winfo_reqwidth()
        height = self.splash_win.winfo_reqheight()
        screenwidth = self.splash_win.winfo_screenwidth()
        if screenwidth > 2000:
            screenwidth = 1000
        x = (screenwidth - width) / 2 - self.splash_win.winfo_vrootx()
        y = (self.splash_win.winfo_screenheight() - height) / 4 - \
                                                    self.splash_win.winfo_vrooty()
        if x < 0:
            x = 0
        if y < 0:
            y = 0
        geometry = '%dx%d+%d+%d' % (width, height, x, y)
        self.splash_win.geometry(geometry)
        self.splash_win.update_idletasks()
        self.splash_win.deiconify()
        self.splash_win.update()
        self.splash_win_children = self.splash_win.children
        self.splash_win.children = [
        ]  # this is needed to avoid problems self.changeFont
Exemple #40
0
    def generate(self, url, conn=True):
        oc = OpalCache()

        if conn == True:
            if oc.isCacheValid(
                    url, os.path.join(getResourceFolderWithVersion(), 'ws')):
                conn = False

        if conn == True:
            self.metadata = self.getAppMetadata(url)
        else:
            print "[INFO]: Generating Opal Wrapper for " + url + " from cache"

        self.url = url

        #setting up for local execution

        if conn == True:
            try:
                executable = self.getAppConfig(url)._binaryLocation
            except:
                executable = 'NA'
                pass
        else:
            dir = os.path.join(getResourceFolderWithVersion(), 'ws')
            executable = oc.getBinaryLocation(url, dir)
            params = oc.getParams(self.url, dir)
            self.params = oc.getParams(self.url, dir)

        # assuming the server is a unix
        executable = executable.rpartition("/")[2]

        if self.which(executable) == None:
            self.executable = ""
        else:
            self.executable = self.which(executable)

        if conn == True:
            classdec = self.buildClassDeclaration(self.metadata, self.url)

            if (self.metadata._types):
                initmethod = self.buildInitMethod(self.metadata, self.url)
                callmethod = self.buildCallMethod(self.metadata)
            else:
                initmethod = self.buildDefaultInitMethod(self.url)
                callmethod = self.buildDefaultCallMethod()
        else:
            classdec = self.buildClassDeclarationFromCache(self.url, params)

            if params:
                initmethod = self.buildInitMethodFromCache(params, self.url)
                callmethod = self.buildCallMethodFromCache(params)
            else:
                initmethod = self.buildDefaultInitMethodFromCache(self.url)
                callmethod = self.buildDefaultCallMethod()

        retclass = ""

        for i in classdec:
            retclass += (str(i) + "\n")

        allmethods = []
        allmethods.extend(initmethod)
        allmethods.extend(callmethod)
        for i in allmethods:
            retclass += (tab + str(i) + "\n")
        #add the onStoppingExecution before returning
        return retclass
    def __init__(self, title="Molecule Viewer", logMode='no',
                 libraries=[], gui=1, resourceFile = '_pmvrc',
                 customizer = None, master=None, guiVisible=1,
                 withShell=1, verbose=True, trapExceptions=True):
        """
        * title:
          string used as a title. 
        * logMode:
          string specifying the mode of logging of mv.
            'no': for no loging of commands at all
            'overwrite': the log files overwrite the one from the previous
                         session the log files = mvAll.log.py
            'unique': the log file name include the date and time

        * libraries:
          list of the Python packages containing modules and commands
          that can be loaded in the application. Such a package needs the
          following files : cmdlib.py and modlib.py
        * gui :
          Flag specifying whether or not to run the application with a gui.
        * resourceFile:
          file sourced at startup and where userpreference  made as default
          are saved (default: '.pmvrc')
        * customizer :
          file when specified is sourced at startup instead of the resourceFile
        * master:
          can be specified to run PMV withing another GUI application.
        * guiVisible:
          Flag to specify whether or not to show the GUI.
        - trapExceptions should be set to False when creating a ViewerFramework
          for testing, such that exception are seen by the testing framework
        """
        libraries = ['Pmv', 'Volume','AutoDockTools'] + libraries
        _pmvrc = Find_pmvrc(resourceFile)
        if _pmvrc:
            resourceFile = _pmvrc
        if withShell:
            from traceback import print_exception
            
            def print_exception_modified(etype, value, tb, limit=None, file=None):
                """
                Modified version of traceback.print_exception
                Deiconifies pyshell when Traceback is printed
                """
                print_exception(etype, value, tb, limit, file)
                if hasattr(self, 'GUI'):
                    self.GUI.pyshell.top.deiconify()
                if not 'Pmv' in tb.tb_frame.f_code.co_filename:
                    return
                if etype == ImportError:
                    if hasattr(value,'message'):
                        package = value.message.split()[-1]
                        print "Please install " +package + " to fix this problem."
                elif etype == AssertionError:
                    pass
                else:
                    print "Please include this Traceback in your bug report. Help --> Report a Bug in PMV/ADT."
            import traceback 
            
            traceback.print_exception = print_exception_modified
        ViewerFramework.__init__(self, title, logMode, libraries, gui,
                                 resourceFile, master=master,
                                 guiVisible=guiVisible, withShell=withShell,
                                 verbose=verbose, trapExceptions=trapExceptions)
        #if sys.platform == 'win32': #this needed to account for camera size
        #    geometry = '%dx%d+%d+%d' % (800,600, 30, 30)
        #else:
        #    geometry = '%dx%d+%d+%d' % (800,200, 30, 30)    
        #self.GUI.ROOT.geometry(geometry)

        # Establish interface to Visual Programming environment.
        if self.visionAPI is not None:
            # add Molecule, Pmv, Viewer to lookup table
            from Pmv.VisionInterface.PmvNodes import PmvMolecule, PmvNode, \
                 PmvViewer, PmvSetNode, PmvVolume
            self.visionAPI.addToLookup(Protein, PmvMolecule, "Molecules")
            self.visionAPI.addToLookup(MoleculeViewer, PmvNode, "PMV")
            from DejaVu import Viewer
            self.visionAPI.addToLookup(Viewer, PmvViewer, "PMV")
            self.visionAPI.addToLookup(TreeNodeSet, PmvSetNode, "Sets")

            # Note: Molecules are added to the interface in addMolecule() below
            
            # put Pmv instance into list of objects to be added to Vision
            self.visionAPI.add(self, "Pmv", kw={
                'vf':self,
                'constrkw':{'vf':'masterNet.editor.vf'} } )
            # put Pmv Viewer instance in list of objects to be added to Vision
            if self.hasGui:
                self.visionAPI.add(self.GUI.VIEWER, "Pmv Viewer", kw={
                'viewer':self.GUI.VIEWER,
                'constrkw':{'viewer':'masterNet.editor.vf.GUI.VIEWER'} } )
            
        self.selection = MoleculeSet()  # store current selection
        # replace interactive command caller by MVInteractiveCmdCaller
        # we need the ICmdCaller even if there is no GUI because it has
        # the level variable used byu selection commands
        self.ICmdCaller = MVInteractiveCmdCaller( self )
        from mvCommand import MVSetIcomLevel
        self.addCommand( MVSetIcomLevel(), 'setIcomLevel', None )
        from mvCommand import MVSetSelectionLevel, MVSetSelectionLevelGUI
        self.addCommand( MVSetSelectionLevel(), 'setSelectionLevel',  MVSetSelectionLevelGUI)

        self.setSelectionLevel(Molecule, topCommand = 0) #should this be Protein?
        from Pmv.displayCommands import BindGeomToMolecularFragment
        from Pmv.displayCommands import BindGeomToMolecularFragmentGUI

        self.addCommand( BindGeomToMolecularFragment(),
                         'bindGeomToMolecularFragment',
                         BindGeomToMolecularFragmentGUI )

#        if self.hasGui:
#            from Pmv.mvCommand import MVPrintNodeNames, MVCenterOnNodes
#            self.addCommand( MVPrintNodeNames(), 'printNodeNames ', None )
#            self.addCommand( MVCenterOnNodes(), 'centerOnNodes', None )

            # load out default interactive command which prints out object
            # names
            #self.ICmdCaller.setCommands( self.printNodeNames )

        self.ICmdCaller.go()
        self.addMVBasicMenus()

        # load out default interactive command
        self.ICmdCaller.setCommands( self.printNodeNames, modifier=None )
        self.ICmdCaller.setCommands( self.select, modifier='Shift_L' )
        self.ICmdCaller.setCommands( self.centerOnNodes, modifier='Control_L' )
        self.ICmdCaller.setCommands( self.deselect, modifier='Alt_L' )

        #self.setIcomLevel(Molecule, topCommand = 0)
        self.setIcomLevel(Atom, topCommand = 0)

        self.Mols = MoleculeSet() # store the molecules read in
        self.objects = self.Mols
        from MolKit.sets import Sets
        self.sets = Sets()  # store user-defined sets in this dict

        # lock needs to be acquired before volume can be added
        self.volumesLock = thread.allocate_lock()

        self.Vols = [] # list of Grid3D objects storing volumetric data
        if self.visionAPI is not None:
            from Volume.Grid3D import Grid3D
            self.visionAPI.addToLookup(Grid3D, PmvVolume, "Volumes")

        self.allAtoms = AtomSet() # set of all atoms (across molecules)

        #if self.hasGui:
        #    from Pmv.controlPanelCommands import ControlPanel,ControlPanel_GUI
        #    self.addCommand(ControlPanel(), "controlPanel",ControlPanel_GUI)
        choices = ['caseSensitive', 'caseInsensitive',
                   'caseInsensWithEscapedChars']

        self.userpref.add('selectStringMatchMode', 'caseSensitive', validValues=choices,
                          doc = """When set to caseSensitive the string match
mode will be case sensitive the other possibility is to be case insensitive or
case insensitive with escaped characters.
""")
        choices = [1,0]
        self.userpref.add('showSelectionSpheres', 1, validValues=choices,
                          doc = """When set to 1 the selection visual feedback
which are the little yellow crosses will be displayed.""")
        choices = [1,0]
        self.userpref.add('raiseExceptionForMissingKey', 1, validValues=choices,
                          callbackFunc = [self.setRaiseException],
                          doc = """When set to 1 an exception will be raised
is a a key is not found in a dictionnary.
""")
        
        choices = [1, 0]
        self.userpref.add('expandNodeLogString', 0, validValues=choices,
                          doc = """When set to 1 the log string representing
the node argument of a doit will be expanded to the full name of each element
of the TreeNodeSet, when set to 0 the log string representing the node argument
of a doit will be 'self.getSelection()'. In the last case the command log will
depend on the current selection.""")

        # overwrite firstObject only with firstMoleculeOnly
        self.userpref['centerScene']['validValues'][0] = 'firstMoleculeOnly'
        self.userpref.set('centerScene', 'firstMoleculeOnly')
        
        choices = ['yes','no']
        self.userpref.add('useDepthCueing', 'yes', validValues=choices,
                          doc = """ When set to 'yes' the depthCueing is
turned on by default""")

        doc = """When set to yes a warning message is displayed when an empty
selection is about to be expanded to all the  molecules loaded in the 
application"""
        self.userpref.add('warnOnEmptySelection', 'no', validValues=choices, doc=doc)

        if self.hasGui:
            self.GUI.VIEWER.suspendRedraw = True
    
            self.GUI.drop_cb = self.drop_cb
            self.GUI.pickLabel.bind("<Button-1>",self.setSelectionLevel.guiCallback)
            if self.userpref['useDepthCueing']['value']=='yes':
                self.GUI.VIEWER.currentCamera.fog.Set(enabled=1,
                                                      tagModified=False)

            if title != 'AutoDockTools':
                toolbarDict = {}
                toolbarDict['name'] = 'ADT'
                toolbarDict['type'] = 'Checkbutton'
                toolbarDict['icon1'] = 'adt.png'
                toolbarDict['balloonhelp'] = 'AutoDock Tools'
                toolbarDict['icon_dir'] = ICONPATH
                toolbarDict['index'] = 7
                toolbarDict['cmdcb'] = self.Add_ADT
                toolbarDict['variable'] = None
                self.GUI.toolbarList.append(toolbarDict)
            self.GUI.configureToolBar(self.GUI.iconsize)
            # overwrite unsollicited picking with a version that prints atom names
            #self.GUI.VIEWER.RemovePickingCallback("unsolicitedPick")
            #self.GUI.VIEWER.AddPickingCallback(self.unsolicitedPick)

            top = self.GUI.ROOT.winfo_toplevel()
            geom = top.geometry()
            geom = geom.split('x')
            self.GUI.menuBars['Toolbar']._frame.update_idletasks()
            winfo_width = self.GUI.menuBars['Toolbar']._frame.winfo_width()        
            if int(geom[0]) < winfo_width + 10:
                geom[0] = str(winfo_width + 10)
            top.geometry(geom[0]+'x'+geom[1])   
            if not trapExceptions and customizer == './.empty':
                top.update_idletasks()
                top.deiconify()  
                #self.GUI.vwrCanvasFloating.deiconify()
                self.GUI.naturalSize()
            from Pmv.updateCommands import Update, UpdateGUI
            self.addCommand( Update(), 'update', UpdateGUI )
    
            from Pmv.aboutCommands import About, AboutGUI
            self.addCommand( About(), 'about', AboutGUI )
    
            self.GUI.VIEWER.suspendRedraw = False
            self.browseCommands('deleteCommands',package='Pmv', topCommand=0)
            self.GUI.ROOT.bind('<Delete>', self.deleteAtomSet.guiCallback)
            self.GUI.vwrCanvasFloating.bind('<Delete>', self.deleteAtomSet.guiCallback)
            self.browseCommands ('dashboardCommands', package='Pmv', topCommand=0)
        self.customize(customizer)
        if self.hasGui:
            try:
                import grid3DCommands
                self.browseCommands("grid3DCommands",package="Pmv", topCommand=0)
            except ImportError:
                print "UTpackages are not installed. Disabling grid3DCommands..."
        
        rcFile = getResourceFolderWithVersion()
        if rcFile:
            rcFile += os.sep + 'Pmv' + os.sep + "recent.pkl"
            
        if self.hasGui:
            fileMenu = self.GUI.menuBars['menuRoot'].menubuttons['File'].menu
    
            self.recentFiles = RecentFiles(self, fileMenu, filePath=rcFile, 
                                           menuLabel = 'Recent Files')
            try:
                from DejaVu.Camera import RecordableCamera
                if isinstance(self.GUI.VIEWER.cameras[0], RecordableCamera):
                    from Pmv.videoCommands import VideoCommand, VideoCommandGUI 
                    self.addCommand(VideoCommand(), 'videoCommand', VideoCommandGUI)
            except:
                pass
                #print "Recordable camera is not available"
            if len(self.dashboard.tree.columns)==0:
                # this warning is wrong, it appears during test_pmvscript
                #print "WARNING: update your _pmvrc file to load the dashboard commands"
                from Pmv.dashboard import loadAllColunms
                loadAllColunms(self)
def saveFonts4visionFile(fontDict):
    ##################################################################
    # generate and overwrite _fonts4Vision file
    ##################################################################
    from Vision.nodeLibraries import libraries
    from mglutil.util.packageFilePath import getResourceFolderWithVersion
    
    visionrcDir = getResourceFolderWithVersion()
    if visionrcDir is None:
        return

    visionrcDir += os.sep + 'Vision'
    if os.path.isdir(visionrcDir) is False:
        return

    fonts4visionFile = visionrcDir + os.sep + '_fonts4vision'
    try:
        f = open(fonts4visionFile, "w")
        txt = """########################################################################
#
# Date: Feb 2008 Authors: Guillaume Vareille, Michel Sanner
#
#    [email protected]
#    [email protected]
#
#       The Scripps Research Institute (TSRI)
#       Molecular Graphics Lab
#       La Jolla, CA 92037, USA
#
# Copyright: Guillaume Vareille, Michel Sanner and TSRI
#
#    _fonts4vision Resource File
#
########################################################################
# This file is optionnal and can be deleted,
# it is generated each time the fonts
# are modified via the Vision GUI
########################################################################

from mglutil.util.misc import ensureFontCase

self.setFont('Menus', (ensureFontCase('%s'),%s,'%s'))
self.setFont('LibTabs', (ensureFontCase('%s'),%s,'%s'))
self.setFont('Categories', (ensureFontCase('%s'),%s,'%s'))
self.setFont('LibNodes', (ensureFontCase('%s'),%s,'%s'))
self.setFont('NetTabs', (ensureFontCase('%s'),%s,'%s'))
self.setFont('Nodes', (ensureFontCase('%s'),%s,'%s'))
self.setFont('Root', (ensureFontCase('%s'),%s,'%s'))
"""%(
fontDict['Menus'][0],fontDict['Menus'][1],fontDict['Menus'][2],
fontDict['LibTabs'][0],fontDict['LibTabs'][1],fontDict['LibTabs'][2],
fontDict['Categories'][0],fontDict['Categories'][1],fontDict['Categories'][2],
fontDict['LibNodes'][0],fontDict['LibNodes'][1],fontDict['LibNodes'][2],
fontDict['NetTabs'][0],fontDict['NetTabs'][1],fontDict['NetTabs'][2],
fontDict['Nodes'][0],fontDict['Nodes'][1],fontDict['Nodes'][2],
fontDict['Root'][0],fontDict['Root'][1],fontDict['Root'][2],
)

        map( lambda x, f=f: f.write(x), txt )
        f.close()
    except:
        txt = "can not create _fonts4vision"
        warnings.warn(txt)
                self.GUI.adt4ModeLabel.bind("<Double-Button-1>", self.ADTSetMode.guiCallback)
        else:
            #self.GUI.menuBars['AutoToolsBar'].pack_forget()
            self.GUI.menuBars[self.GUI.currentADTBar].pack_forget()

def Find_pmvrc(resourceFile):
    """
    This function tries to find resource file for Pmv in the User Home folder. 
    If it can't find one, it will copy it from Pmv._pmvrc
    """
    import mglutil
    try:            
        reload(mglutil) # this is needed for updates
    except RuntimeError, e:
        print "# this is needed for updates: unable to reload mglutil\n", e
    lResourceFolderWithVersion = getResourceFolderWithVersion()
    if lResourceFolderWithVersion is not None:
        pmvrcFolder = lResourceFolderWithVersion + os.sep + 'Pmv'
        if not os.path.exists(pmvrcFolder):
            os.mkdir(pmvrcFolder)
        pmvrcFile = pmvrcFolder + os.sep + resourceFile
        if not os.path.exists(pmvrcFile):
            file_out = open(pmvrcFile,'w')
            import Pmv
            file_in = open(Pmv.__path__[0] + os.sep + resourceFile )
            file_out.write(file_in.read())
        return pmvrcFile
    else:
        return None

if __name__ == '__main__':
Exemple #44
0
def saveFonts4visionFile(fontDict):
    ##################################################################
    # generate and overwrite _fonts4Vision file
    ##################################################################
    from Vision.nodeLibraries import libraries
    from mglutil.util.packageFilePath import getResourceFolderWithVersion

    visionrcDir = getResourceFolderWithVersion()
    if visionrcDir is None:
        return

    visionrcDir += os.sep + 'Vision'
    if os.path.isdir(visionrcDir) is False:
        return

    fonts4visionFile = visionrcDir + os.sep + '_fonts4vision'
    try:
        f = open(fonts4visionFile, "w")
        txt = """########################################################################
#
# Date: Feb 2008 Authors: Guillaume Vareille, Michel Sanner
#
#    [email protected]
#    [email protected]
#
#       The Scripps Research Institute (TSRI)
#       Molecular Graphics Lab
#       La Jolla, CA 92037, USA
#
# Copyright: Guillaume Vareille, Michel Sanner and TSRI
#
#    _fonts4vision Resource File
#
########################################################################
# This file is optionnal and can be deleted,
# it is generated each time the fonts
# are modified via the Vision GUI
########################################################################

from mglutil.util.misc import ensureFontCase

self.setFont('Menus', (ensureFontCase('%s'),%s,'%s'))
self.setFont('LibTabs', (ensureFontCase('%s'),%s,'%s'))
self.setFont('Categories', (ensureFontCase('%s'),%s,'%s'))
self.setFont('LibNodes', (ensureFontCase('%s'),%s,'%s'))
self.setFont('NetTabs', (ensureFontCase('%s'),%s,'%s'))
self.setFont('Nodes', (ensureFontCase('%s'),%s,'%s'))
self.setFont('Root', (ensureFontCase('%s'),%s,'%s'))
""" % (
            fontDict['Menus'][0],
            fontDict['Menus'][1],
            fontDict['Menus'][2],
            fontDict['LibTabs'][0],
            fontDict['LibTabs'][1],
            fontDict['LibTabs'][2],
            fontDict['Categories'][0],
            fontDict['Categories'][1],
            fontDict['Categories'][2],
            fontDict['LibNodes'][0],
            fontDict['LibNodes'][1],
            fontDict['LibNodes'][2],
            fontDict['NetTabs'][0],
            fontDict['NetTabs'][1],
            fontDict['NetTabs'][2],
            fontDict['Nodes'][0],
            fontDict['Nodes'][1],
            fontDict['Nodes'][2],
            fontDict['Root'][0],
            fontDict['Root'][1],
            fontDict['Root'][2],
        )

        map(lambda x, f=f: f.write(x), txt)
        f.close()
    except:
        txt = "can not create _fonts4vision"
        warnings.warn(txt)