def _writeTokenData(self, tokenData): try: self.__writeTokenData(tokenData) except Exception, e: msg = (u"Could not write cookie file: '{}'!\n {}" .format(self.cookieFilePath, toStr(e))) logMsg(msg, warning=True)
def scan(proj, sDbPath): sDbPath = pathNorm(sDbPath) library = proj.libraryFromDbPath(sDbPath) sCurSite = proj.getCurrentSite() dbNodeDct = proj._db.findNodes({"file":{"$regex":"^{}".format(addEndSlash(sDbPath))}, "source_size":{"$exists":True}}, asDict=True) sortKey = lambda n: n._data["#parent"] + "_" + n.name dbVersIter = (n for n in dbNodeDct.itervalues() if ("#parent" in n._data)) dbVersList = sorted(dbVersIter, key=sortKey, reverse=True) grpIter = groupby(dbVersList, key=lambda n: n._data["#parent"]) #for k, g in grpIter: # vn = next(g) # hn = dbNodeDct.get(vn.getField("#parent")) # if int(vn.version) != int(hn.version): # print vn.version, hn.version, hn.file dbNodeList = tuple(next(g) for _, g in grpIter) numNodes = len(dbNodeList) foundList = numNodes * [None] errorList = [] for i, n in enumerate(dbNodeList): print "checking {}/{}: {}".format(i + 1, numNodes, n.file) rcEntry = library.entryFromDbPath(n.file, dbNode=False, assertLibrary=False) if not rcEntry: continue rcEntry._cacheDbNode(n) if rcEntry.fileSize != rcEntry.sourceSize: foundList[i] = rcEntry continue try: n = dbNodeDct[n.getField("#parent")] except KeyError as e: logMsg(e.message, warning=True) errorList.append((rcEntry, e)) continue rcEntry = library.entryFromDbPath(n.file, dbNode=False, assertLibrary=False) if not rcEntry: sOrigin = n.origin if sOrigin and (sOrigin in n._data): if ("synced_" + sOrigin in n._data): rcEntry = library.entryFromDbPath(n.file, weak=True, dbNode=False, assertLibrary=False) errorList.append((rcEntry, EnvironmentError("missing"))) continue rcEntry._cacheDbNode(n) if rcEntry.fileSize != rcEntry.sourceSize: foundList[i] = rcEntry return foundList, errorList, sDbPath
def getResource(self, sSpace, sRcName="entity_dir", **kwargs): bFail = kwargs.pop("fail", False) bFile = kwargs.pop("isFile", False) try: sRcPath = self.getPath(sSpace, pathVar=sRcName) except AttributeError: sMsg = "{} has no such resource: '{}' !".format(self, sRcName) if bFail: raise EnvironmentError(sMsg) logMsg(sMsg, warning=True) return None proj = self.project library = self.getLibrary(sSpace) drcEntry = proj.entryFromPath(sRcPath, library=library, **kwargs) if bFile and drcEntry and (not isinstance(drcEntry, DrcFile)): drcEntry = None if bFail and (not drcEntry): sMsg = "No such {}: '{}'".format("file" if bFile else "resource", sRcPath) raise EnvironmentError(sMsg) return drcEntry
def breakFilesLock(self, *itemList): drcFiles = tuple(item._metaobj for item in itemList) for drcFile in drcFiles: drcFile.refresh() if drcFile.setLocked(False, force=True): logMsg('{0} {1}.'.format("Lock broken:", drcFile))
def getPref(in_sKey, default=None): global DAVOS_PREFS if "|" not in in_sKey: return DAVOS_PREFS.get(in_sKey, default) sKeyList = in_sKey.split("|") iLastKey = len(sKeyList) - 1 currPrefs = DAVOS_PREFS for i, sKey in enumerate(sKeyList): if not isinstance(currPrefs, dict): k = "|".join(sKeyList[:(i + 1)]) logMsg("Not a pref dictionary: '{}'.".format(k), warning=True) return default if i == iLastKey: return currPrefs.get(sKey, default) if sKey in currPrefs: currPrefs = currPrefs[sKey] else: logMsg("No such pref: '{}'.".format(in_sKey), warning=True) return default
def getPrpty(self, sProperty, default="NoEntry"): logMsg(self.__class__.__name__, log='all') if default == "NoEntry": return getattr(self, sProperty) else: return getattr(self, sProperty, default)
def createNewDirectory(self, *itemList): item = itemList[-1] pubDir = item._metaobj #proj = self.model()._metamodel if not pubDir.allowFreePublish(): confirmDialog(title='SORRY !', message="You can't add new directories here.", button=["OK"], icon="information") return result = promptDialog(title='Please...', message='Directory Name: ', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel', scrollableField=True, ) if result == 'Cancel': logMsg("Cancelled !" , warning=True) return sDirName = promptDialog(query=True, text=True) if not sDirName: return os.mkdir(pathJoin(pubDir.absPath(), sDirName.strip().replace(" ", "_"))) pubDir.refresh(children=True)
def shadingGroupsForObject(oObj, warn=True): oShdGrpList = [] oShape = None if isinstance(oObj, pm.general.MeshFace): indiceList = oObj.indices() for oShdEng in oObj.listHistory(type="shadingEngine"): if set(indiceList).intersection(set(oShdEng.members()[0].indices())): oShdGrpList.append(oShdEng) elif isinstance(oObj, pm.general.NurbsSurfaceFace): oShape = oObj.node() elif isinstance(oObj, pm.nt.Transform): oShape = oObj.getShape() elif isinstance(oObj, (pm.nt.Mesh, pm.nt.NurbsSurface)): oShape = oObj elif warn: logMsg("Can't get shading groups from {}".format(repr(oObj)) , warning=True) if not oShdGrpList: if oShape: oShdGrpList = oShape.shadingGroups() if not oShdGrpList: oShdGrpList = oShape.connections(type="shadingEngine") return oShdGrpList
def matchPos(obj, target, **kwargs): logMsg(log='all') bPreserveChild = kwargs.get('preserveChild', kwargs.get('pc', False)) bObjSpace = kwargs.get('objectSpace', kwargs.get('os', False)) (oObj, oTarget) = argsToPyNode(obj, target) sSpace = 'world' if bObjSpace == True: sSpace = "object" fPosVec = mc.xform(oTarget.name(), q=True, ws=not bObjSpace, os=bObjSpace, t=True) oChildren = None if bPreserveChild: oChildren = oObj.getChildren(typ='transform') oParent = oObj.getParent() if oChildren: if oParent: pm.parent(oChildren, oParent) else: pm.parent(oChildren, world=True) mc.xform(oObj.name(), ws=not bObjSpace, os=bObjSpace, t=fPosVec) logMsg("'%s' translate %s to %s" % (sSpace, oObj, oTarget), log='all') if oChildren: pm.parent(oChildren, oObj)
def matchScalePivot(obj, target, **kwargs): logMsg(log='all') bPreserveChild = kwargs.get('preserveChild', kwargs.get('pc', False)) (oObj, oTarget) = argsToPyNode(obj, target) fPosVec = mc.xform(oTarget.name(), q=True, ws=True, sp=True) oChildren = None if bPreserveChild: oChildren = oObj.getChildren(typ='transform') oParent = oObj.getParent() if oChildren: if oParent: pm.parent(oChildren, oParent) else: pm.parent(oChildren, world=True) mc.xform(oObj.name(), ws=True, t=fPosVec) logMsg("'world' translate %s to %s's scale pivot" % (oObj, oTarget), log='all') if oChildren: pm.parent(oChildren, oObj)
def matchRot(obj, target, **kwargs): logMsg(log='all') bPreserveChild = kwargs.pop('preserveChild', kwargs.pop('pc', False)) bObjSpace = kwargs.get('objectSpace', kwargs.get('os', False)) (oObj, oTarget) = argsToPyNode(obj, target) sSpace = 'world' if bObjSpace == True: sSpace = "object" objWorldPos = mc.xform(oObj.name(), q=True, ws=True, t=True) objScale = mc.xform(oObj.name(), q=True, r=True, s=True) oChildren = None if bPreserveChild: oChildren = oObj.getChildren(typ='transform') oParent = oObj.getParent() if oChildren: if oParent: pm.parent(oChildren, oParent) else: pm.parent(oChildren, world=True) matchTRS(oObj, oTarget, logMsg=False, **kwargs) logMsg("'%s' rotate %s to %s" % (sSpace, oObj, oTarget), log='all') if oChildren: pm.parent(oChildren, oObj) mc.xform(oObj.name(), ws=True, t=objWorldPos) mc.xform(oObj.name(), s=objScale)
def shadingGroupsForObject(oObj, warn=True): oShdGrpList = [] oShape = None if isinstance(oObj, pm.general.MeshFace): indiceList = oObj.indices() for oShdEng in oObj.listHistory(type="shadingEngine"): if set(indiceList).intersection(set( oShdEng.members()[0].indices())): oShdGrpList.append(oShdEng) elif isinstance(oObj, pm.general.NurbsSurfaceFace): oShape = oObj.node() elif isinstance(oObj, pm.nt.Transform): oShape = oObj.getShape() elif isinstance(oObj, (pm.nt.Mesh, pm.nt.NurbsSurface)): oShape = oObj elif warn: logMsg("Can't get shading groups from {}".format(repr(oObj)), warning=True) if not oShdGrpList: if oShape: oShdGrpList = oShape.shadingGroups() if not oShdGrpList: oShdGrpList = oShape.connections(type="shadingEngine") return oShdGrpList
def iterSyncedResource(proj, sEntityType, sgEntityList): if sEntityType == "asset": EntityCls = DamAsset elif sEntityType == "shot": EntityCls = DamShot else: raise ValueError("Invalid entity type: '{}'.".format(sEntityType)) #library = proj.getLibrary("public", EntityCls.libraryName) numEntity = len(sgEntityList) for i, sgEntity in enumerate(sgEntityList): sEntityName = sgEntity["code"] print "{}/{} - {}".format(i + 1, numEntity, sEntityName) try: damEntity = EntityCls(proj, name=sEntityName) except Exception as e: logMsg(toStr(e), warning=True) continue sSection = damEntity.confSection pathIter = proj.iterRcPaths("public", sSection, tokens=vars(damEntity)) for sRcName, sAbsPath in pathIter: sSyncRuleList = proj.getRcParam(sSection, sRcName, "default_sync_rules", None) if sSyncRuleList:# and osp.exists(sAbsPath): #print damEntity, sRcName, sSyncRuleList yield damEntity, sAbsPath, sorted(sSyncRuleList)
def __initDamas(self): sDamasServerAddr = self.getVar("project", "damas_server_addr", "") from .dbtypes import DummyDbCon dummydb = DummyDbCon(sDamasServerAddr) if not sDamasServerAddr: self._damasdb = dummydb return if inDevMode(): print "connecting to damas server:", sDamasServerAddr else: print "connecting to damas..." import damas damasdb = damas.http_connection(sDamasServerAddr) try: damasdb.verify() except IOError as e: logMsg(toStr(e), warning=True) self._damasdb = dummydb else: self._damasdb = damasdb
def __init__(self): self.canDistribute = False self.menu = None self.postSceneReadJobId = None self.newSceneOpenedJobId = None self.quitMayaJobId = None self.sceneOpenedJobId = None self.preNewOrOpenedJobId = None self.sceneSavedJobId = None self.afterMayaStartJobId = None self.preCreateRefCheckCbkId = None self.mayaInitializedCbkId = None self.beforeNewCheckCbkId = None self.beforeOpenCheckCbkId = None self.afterPluginLoadCbkId = None self.currentSceneName = None self.mayaIsStarting = False logutils.logSeverity = self.getLogLevel() if self.mayaInitializedCbkId is None: args = (om.MSceneMessage.kMayaInitialized, safely(self.onMayaInitialized)) self.mayaInitializedCbkId = om.MSceneMessage.addCallback(*args) logMsg("MayaInitialized Callback Started.")
def dataRepr(self, *fields): bFilter = True if fields else False dataItems = [("id_", self.id_)] dataItems.extend(sorted(self._data.iteritems(), key=lambda x:x[0])) s = '{' for k, v in dataItems: if bFilter and (k not in fields): continue sTypeName = type(v).__name__ if k in ("time", "ino_write") or k.startswith("synced_"): try: v = datetime.fromtimestamp(int(v) / 1000).strftime("%Y-%m-%d %H:%M:%S") except Exception as e: logMsg(toStr(e)) elif isinstance(v, unicode): v = str_(v) s += "\n<{}> {}: {}".format(sTypeName, k, v) return (s + '\n}')
def matchPos(obj, target, **kwargs): logMsg(log="all") bPreserveChild = kwargs.get("preserveChild", kwargs.get("pc", False)) bObjSpace = kwargs.get("objectSpace", kwargs.get("os", False)) (oObj, oTarget) = argsToPyNode(obj, target) sSpace = "world" if bObjSpace == True: sSpace = "object" fPosVec = mc.xform(oTarget.name(), q=True, ws=not bObjSpace, os=bObjSpace, t=True) oChildren = None if bPreserveChild: oChildren = oObj.getChildren(typ="transform") oParent = oObj.getParent() if oChildren: if oParent: pm.parent(oChildren, oParent) else: pm.parent(oChildren, world=True) mc.xform(oObj.name(), ws=not bObjSpace, os=bObjSpace, t=fPosVec) logMsg("'%s' translate %s to %s" % (sSpace, oObj, oTarget), log="all") if oChildren: pm.parent(oChildren, oObj)
def deleteDbNode(self, *itemList): entryList = [] msg = "" for item in itemList: entry = item._metaobj dbNode = entry._dbnode if dbNode: r = dbNode.dataRepr("file") r = re.sub(r"[\s{}]", "", r) msg += (r + "\n") entryList.append(entry) sMsg = u'Are you sure you want to DELETE these db nodes:\n\n' + msg sConfirm = confirmDialog(title='WARNING !', message=sMsg, button=['OK', 'Cancel'], defaultButton='Cancel', cancelButton='Cancel', dismissString='Cancel', icon="warning") if sConfirm == 'Cancel': logMsg("Cancelled !", warning=True) return for entry in entryList: entry.deleteDbNode()
def __publishFiles(self, pubDir): if not pubDir.freeToPublish(): confirmDialog(title='SORRY !', message="You can't add new files here.", button=["OK"], icon="information") return sRes = confirmDialog(title="DO YOU WANT TO...", message="publish ?", button=["Files", "Packages", "Cancel"], defaultButton="Cancel", cancelButton="Cancel", dismissString="Cancel", icon="question") if sRes == "Cancel": logMsg("Canceled !", warning=True) return elif sRes == "Files": sSrcPathList = self.chooseFiles(pubDir) elif sRes == "Packages": sSrcPathList = self.choosePacks(pubDir) if not sSrcPathList: logMsg("No {} selected: Canceled.".format(sRes.lower()), warning=True) return pubDir._publishFiles(sSrcPathList, autoLock=True, autoUnlock=True)
def getLibrary(self, sSpace, sLibSection, owner="", dbNode=True, weak=False, remember=True, tokens=None): logMsg(log='all') self._assertSpaceAndSection(sSpace, sLibSection) sFullLibName = DrcLibrary.makeFullName(owner, sSpace, sLibSection) drcLib = self.loadedLibraries.get(sFullLibName, None) if not drcLib: if tokens: sLibPath = self.getPath(sSpace, sLibSection, resVars=False, tokens=tokens) else: sLibPath = self.getPath(sSpace, sLibSection) drcLib = self.__libClass(sLibSection, sLibPath, sSpace, owner=owner, project=self, dbNode=dbNode, remember=remember) if weak: return drcLib if osp.isdir(sLibPath): return drcLib else: logMsg("No such '{}': '{}'.".format(sFullLibName, sLibPath), warning=True) return None return drcLib
def matchRot(obj, target, **kwargs): logMsg(log="all") bPreserveChild = kwargs.pop("preserveChild", kwargs.pop("pc", False)) bObjSpace = kwargs.get("objectSpace", kwargs.get("os", False)) (oObj, oTarget) = argsToPyNode(obj, target) sSpace = "world" if bObjSpace == True: sSpace = "object" objWorldPos = mc.xform(oObj.name(), q=True, ws=True, t=True) objScale = mc.xform(oObj.name(), q=True, r=True, s=True) oChildren = None if bPreserveChild: oChildren = oObj.getChildren(typ="transform") oParent = oObj.getParent() if oChildren: if oParent: pm.parent(oChildren, oParent) else: pm.parent(oChildren, world=True) matchTRS(oObj, oTarget, logMsg=False, **kwargs) logMsg("'%s' rotate %s to %s" % (sSpace, oObj, oTarget), log="all") if oChildren: pm.parent(oChildren, oObj) mc.xform(oObj.name(), ws=True, t=objWorldPos) mc.xform(oObj.name(), s=objScale)
def _search(self, query, authOnFail=True, **kwargs): logMsg(query, log='all') dbconn = self._dbconn if isinstance(query, basestring): ids = dbconn.search(query) elif isinstance(query, dict): ids = dbconn.search_mongo(query, **kwargs) else: raise TypeError("Invalid query: '{}'".format(query)) if ids is None: if not authOnFail: raise DbSearchError('Failed to search: "{}"'.format(query)) bAuthOk = dbconn.verify() if not bAuthOk: try: bAuthOk = self.project.authenticate() except Exception, e: logMsg(toStr(e), warning=True) return self._search(query, authOnFail=False, **kwargs)
def _iterNodes(self, sQuery): logMsg(sQuery, log='all') ids = self._search(sQuery) if not ids: return None return (DbNode(self, r) for r in self._read(ids) if r is not None)
def loadConfigModule(self): try: self._confobj = PyConfParser(getConfigModule(self.name)) except ImportError as e: #if kwargs.pop("warn", True): logMsg(e.message , warning=True) return False
def __publishRegular(self, pubFile): sSrcFilePath = self.chooseRegularVersion(pubFile) if not sSrcFilePath: logMsg("Cancelled !", warning=True) return pubFile.publishVersion(sSrcFilePath, autoLock=True)
def owner(self): logMsg(log='all') if not self.is_locked(): return "" files = os.listdir(self.lock_file) return files[0] if files else ""
def syncTreeSelection(self, index): self.childrenWidget.updatePathBar(index) bItemPressed = self.treeView.wasAnItemPressed() logMsg("syncTreeSelection, treeView item pressed = {0}".format(bItemPressed), log='debug') if not bItemPressed: self.treeView.selectIndex(index)
def launch(dryRun=True): sg = proj._shotgundb.sg sgOperatorList = sg.find("CustomNonProjectEntity01", [], fields=["sg_login", "sg_password", "sg_company"]) dbUserDict = proj._db.findNodes("username:/.*/", asDict=True, keyField="username") #pprint(dbUserDict) for sgOpe in sgOperatorList: sSgLogin = sgOpe["sg_login"] sSgPwd = sgOpe["sg_password"] sCompany = sgOpe["sg_company"]["name"] bExists = (sSgLogin in dbUserDict) #print sSgLogin, fromUtf8(sCompany), bExists, sSgPwd if not sSgPwd: if not bExists: logMsg("Cannot create '{}': No password defined.".format(sSgLogin)) continue elif len(sSgPwd) == 32: if not bExists: logMsg("Cannot create '{}': password already encrypted.".format(sSgLogin)) continue sMd5Pwd = sSgPwd else: h = hashlib.md5() h.update(sSgPwd) sMd5Pwd = h.hexdigest() userData = {"username":sSgLogin, "password": sMd5Pwd, "company":fromUtf8(sCompany), } #print userData if bExists: userNode = dbUserDict[sSgLogin] updData = dict((k, v) for k, v in userData.iteritems() if v != userNode.getField(k)) if updData: print "\n", "update user:"******"create user:\n" sMsg += "login: {}\n".format(sSgLogin) sMsg += "pwd: {}\n".format(sSgPwd) print "\n" + sMsg if not dryRun: proj._db.createNode(userData) if (not dryRun) and (sSgPwd != sMd5Pwd): proj.updateSgEntity(sgOpe, sg_password=sMd5Pwd)
def doIt(*args, **kwargs): bUnload = kwargs.pop("unloadBefore", False) bAllIfNoSel = kwargs.pop("allIfNoSelection", False) sProcessLabel = kwargs.pop("processLabel", "Process") bSelMode = kwargs.pop("selected", kwargs.pop("sl", True)) bConfirm = kwargs.pop("confirm", True) bSelected = bSelMode if bSelMode and bAllIfNoSel: if not mc.ls(sl=True): bSelected = False oFileRefList = listReferences(sl=bSelected, **kwargs) if not oFileRefList: if bSelected: pm.displayError("No referenced objects selected !") else: pm.displayError("No referenced objects to {} !".format(sProcessLabel.lower())) return [], [] if bSelMode: if bSelected: sConfirmText = sProcessLabel + " {} Selected References ?".format(len(oFileRefList)) sRefNames = ' '.join(oFileRef.namespace for oFileRef in oFileRefList) else: sConfirmText = sProcessLabel + " All References ?" sRefNames = "" if bConfirm: sConfirmMsg = (sConfirmText + '\n\n' + sRefNames) if sRefNames else sConfirmText sConfirm = pm.confirmDialog(title='WARNING !' , message=sConfirmMsg , button=['OK', 'Cancel']) if sConfirm == 'Cancel': logMsg("Cancelled !" , warning=True) return [], [] if bUnload: for oFileRef in oFileRefList: oFileRef.unload() try: resultList = [] kwargs.update(processResults=resultList) for oFileRef in oFileRefList: func(oFileRef, *args, **kwargs) finally: if bUnload: for oFileRef in oFileRefList: try: oFileRef.load() except Exception, e: pm.displayError(e)
def updateData(self): logMsg(log='all') metaprpty = self._metaprpty self.loadData(metaprpty) image = self.data(ItemUserRole.ImageRole) if image and (not image.isNull()): self.loadImage()
def deleteChildJunkShapes(*objList): for obj in objList: junkShapeList = tuple(_yieldChildJunkShapes(obj)) if junkShapeList: logMsg('Removing junk shapes under "{0}": \n\t{1}'.format(obj, "\n\t".join(junkShapeList))) pm.delete(junkShapeList)
def loggedUser(self, **kwargs): logMsg(log='all') bForce = kwargs.get("force", False) if bForce and (not self.isAuthenticated()): self.authenticate() return self.__loggedUser
def deleteChildJunkShapes(*objList): for obj in objList: junkShapeList = tuple(_yieldChildJunkShapes(obj)) if junkShapeList: logMsg('Removing junk shapes under "{0}": \n\t{1}'.format( obj, "\n\t".join(junkShapeList))) pm.delete(junkShapeList)
def onMayaInitialized(self, clientData=None): logMsg("Maya Initialized", log="callback") #print "Maya Initialized".center(100, "!"), self.getLogLevel() self.mayaIsStarting = True self.startCallbacks() self.startScriptJobs() return True
def doIt(*args, **kwargs): bUnload = kwargs.pop("unloadBefore", False) bAllIfNoSel = kwargs.pop("allIfNoSelection", False) sProcessLabel = kwargs.pop("processLabel", "Process") bSelMode = kwargs.pop("selected", kwargs.pop("sl", True)) bConfirm = kwargs.pop("confirm", True) bSelected = bSelMode if bSelMode and bAllIfNoSel: if not mc.ls(sl=True): bSelected = False oFileRefList = listReferences(sl=bSelected, **kwargs) if not oFileRefList: if bSelected: pm.displayError("No referenced objects selected !") else: pm.displayError("No referenced objects to {} !".format(sProcessLabel.lower())) return [], [] if bSelMode: if bSelected: sConfirmText = sProcessLabel + " {} Selected References ?".format(len(oFileRefList)) sRefNames = " ".join(oFileRef.namespace for oFileRef in oFileRefList) else: sConfirmText = sProcessLabel + " All References ?" sRefNames = "" if bConfirm: sConfirmMsg = (sConfirmText + "\n\n" + sRefNames) if sRefNames else sConfirmText sConfirm = pm.confirmDialog(title="WARNING !", message=sConfirmMsg, button=["OK", "Cancel"]) if sConfirm == "Cancel": logMsg("Cancelled !", warning=True) return [], [] if bUnload: for oFileRef in oFileRefList: oFileRef.unload() try: resultList = [] kwargs.update(processResults=resultList) for oFileRef in oFileRefList: func(oFileRef, *args, **kwargs) finally: if bUnload: for oFileRef in oFileRefList: try: oFileRef.load() except Exception, e: pm.displayError(e)
def _forget(self, parent=None): DrcEntry._forget(self, parent) libCacheKey = self.fullName cacheDict = self.project.loadedLibraries if libCacheKey not in cacheDict: logMsg("<{}> Already dropped : {}.".format(getCaller(depth=4, fo=False), self), log="debug") else: return cacheDict.pop(libCacheKey)
def isAuthenticated(self): if not self._authobj: return False bAuth = self._authobj.authenticated if not bAuth: logMsg("The project is not authenticated.", warning=True) return bAuth
def _remember(self): DrcEntry._remember(self) libCacheKey = self.fullName cacheDict = self.project.loadedLibraries if libCacheKey in cacheDict: logMsg("<{}> Already loaded : {}.".format(getCaller(depth=4, fo=False), self) , log="debug") else: cacheDict[libCacheKey] = self
def _writeAllValues(self, propertyNames=None): logMsg(self.__class__.__name__, log='all') sPropertyIter = self.__class__._iterPropertyArg(propertyNames) for sProperty in sPropertyIter: value = getattr(self, sProperty) try: self.setPrpty(sProperty, value, write=True, useSetter=False) except Exception, msg: logMsg(toStr(msg), warning=True)
def loadData(self, propertyNames=None): logMsg(self.__class__.__name__, log='all') sPropertyIter = self.__class__._iterPropertyArg(propertyNames) for sProperty in sPropertyIter: metaprpty = self.__metaProperties[sProperty] if metaprpty.isReadable(): #logMsg("read", self, sProperty, metaprpty.read(), log="debug") setattr(self, metaprpty.name, metaprpty.read()) elif metaprpty.isLazy(): #logMsg("defaultValue", self, sProperty, metaprpty.defaultValue(), log="debug") setattr(self, metaprpty.name, metaprpty.defaultValue())
def copyAttrState(srcNode, destNode , *sAttrList): logMsg(log='all') sSrcNode = argToStr(srcNode) sDestNode = argToStr(destNode) for sAttr in sAttrList: sDestNodeAttr = getObject(sDestNode + "." + sAttr) if sDestNodeAttr: sSrcNodeAttr = sSrcNode + "." + sAttr mc.setAttr(sDestNodeAttr, k=mc.getAttr(sSrcNodeAttr, k=True), l=mc.getAttr(sSrcNodeAttr, l=True), cb=mc.getAttr(sSrcNodeAttr, cb=True))
def __init__(self): cls = self.__class__ self._writingValues_ = False self.__metaProperties = {} for sProperty, _ in cls.propertiesDctItems: metaprpty = cls.propertyFactoryClass(sProperty, self) setattr(self, metaprpty.name, metaprpty.defaultValue()) self.__metaProperties[sProperty] = metaprpty logMsg(cls.__name__, log='all')
def launchAction(self, actionDct, checked): bCheckable = actionDct.get("checkable", False) self.beforeActionLaunched.emit(actionDct, checked) if not bCheckable: self.assertActionTargets() if not bCheckable: sActionMsg = u"Action: {} > {}".format(actionDct["menu"], actionDct["label"]) try: logMsg(u'# Action: {} #'.format(sActionMsg)) except Exception, e: logMsg(e, warning=True)
def createInputDataUI(self, parentWidget, **kwargs): cls = self.__class__ logMsg(cls.__name__, log='all') sIgnorePrpty = kwargs.pop("ignoreInputData", []) sIgnorePrptyList = argToTuple(sIgnorePrpty) inputWdgItems = [] for sProperty, _ in cls.propertiesDctItems: if sProperty in sIgnorePrptyList: continue metaprpty = self.__metaProperties[sProperty] if metaprpty.isInput(): inputWdg = metaprpty.createEditorWidget(parentWidget) inputWdgItems.append((metaprpty.name, {"widget": inputWdg})) return inputWdgItems
def setPrpty(self, sProperty, value, write=True, **kwargs): bUseSetter = kwargs.pop("useSetter", True) bWarn = kwargs.get("warn", True) sMsg = "" setter = None if bUseSetter: sSetter = self.metaProperty(sProperty).getParam("setter", "") setter = getattr(self, sSetter) if sSetter else None sMsg = "Setting {0}.{1} to {2}( {3} ) using {4}".format( self, sProperty, type(value).__name__, toStr(value), setter if setter else "_setPrpty") logMsg(sMsg, log="debug") bSuccess = False if setter: if bWarn: logMsg("{}.{}() can be used to set '{}' property !".format( self, sSetter, sProperty), warning=True) bSuccess = setter(value, write=write, **kwargs) else: bSuccess = self._setPrpty(sProperty, value, write=write) if (not bSuccess) and sMsg: logMsg("Failed " + lowerFirst(sMsg), warning=True) return bSuccess
def initPropertiesFromKwargs(self, **kwargs): logMsg(self.__class__.__name__, log='all') logMsg("Entered kwargs:", kwargs, log="debug") bIgnoreMissing = kwargs.pop("ignoreMissingKwarg", False) cls = self.__class__ # get all keyword arguments for sProperty, _ in cls.propertiesDctItems: metaprpty = self.__metaProperties[sProperty] defaultValue = metaprpty.defaultValue() if defaultValue == "undefined" and (not bIgnoreMissing): try: value = kwargs.pop(metaprpty.name) except KeyError: msg = u'{0} needs "{1}" kwarg at least'.format( cls.__name__, metaprpty.name) raise TypeError(msg) else: setattr(self, metaprpty.name, value) else: value = kwargs.pop(metaprpty.name, defaultValue) setattr(self, metaprpty.name, value) logMsg("Remaining kwargs:", kwargs, log="debug") return kwargs
def _setPrpty(self, sProperty, value, write=True): logMsg(self.__class__.__name__, log='all') metaprpty = self.__metaProperties[sProperty] if not metaprpty.isValidValue(value): logMsg(u"{}.{} : Invalid value : '{}'".format( self, sProperty, value), warning=True) return False if write: if metaprpty.isWritable(): bSuccess = metaprpty.write(value) if not bSuccess: return False else: logMsg( u"<{}> Writing to non-writable property: {}.{} .".format( getCaller(fo=0), self, metaprpty.name), warning=True) setattr(self, metaprpty.name, value) return True
def matchScl(obj, target, **kwargs): logMsg(log='all') bPreserveChild = kwargs.get('preserveChild', kwargs.get('pc', False)) (oObj, oTarget) = argsToPyNode(obj, target) fScaleVec = mc.xform(oTarget.name(), q=True, r=True, s=True) oChildren = None if bPreserveChild: oChildren = oObj.getChildren(typ='transform') oParent = oObj.getParent() if oChildren: if oParent: pm.parent(oChildren, oParent) else: pm.parent(oChildren, world=True) mc.xform(oObj.name(), s=fScaleVec) logMsg("'object' scale %s to %s" % (oObj, oTarget), log='all') if oChildren: pm.parent(oChildren, oObj)
def killCallbacks(self): if self.mayaInitializedCbkId: self.mayaInitializedCbkId = om.MSceneMessage.removeCallback( self.mayaInitializedCbkId) logMsg("MayaInitialized Callback Killed.") if self.preCreateRefCheckCbkId: self.preCreateRefCheckCbkId = om.MSceneMessage.removeCallback( self.preCreateRefCheckCbkId) logMsg("kBeforeCreateReferenceCheck Callback Killed.") if self.beforeNewCheckCbkId: self.beforeNewCheckCbkId = om.MSceneMessage.removeCallback( self.beforeNewCheckCbkId) logMsg("kBeforeNewCheck Callback Killed.") if self.beforeOpenCheckCbkId: self.beforeOpenCheckCbkId = om.MSceneMessage.removeCallback( self.beforeOpenCheckCbkId) logMsg("kBeforeOpenCheck Callback Killed.")
def startCallbacks(self): logMsg("Start Callbacks", log="debug") if self.preCreateRefCheckCbkId is None: args = (om.MSceneMessage.kBeforeCreateReferenceCheck, safely(self.onPreCreateReferenceCheck, returns=True)) self.preCreateRefCheckCbkId = om.MSceneMessage.addCheckFileCallback( *args) logMsg("kBeforeCreateReferenceCheck Callback Started.") if self.beforeNewCheckCbkId is None: args = (om.MSceneMessage.kBeforeNewCheck, safely(self.onBeforeNewCheck, returns=True)) self.beforeNewCheckCbkId = om.MSceneMessage.addCheckCallback(*args) logMsg("kBeforeNewCheck Callback Started.") if self.beforeOpenCheckCbkId is None: args = (om.MSceneMessage.kBeforeOpenCheck, safely(self.onBeforeOpenCheck, returns=True)) self.beforeOpenCheckCbkId = om.MSceneMessage.addCheckFileCallback( *args) logMsg("kBeforeOpenCheck Callback Started.")
def deleteAllJunkShapes(dryRun=False): sJunkShapeList = listJunkIntermedShapes(nodeNames=True, not_rn=True) if not sJunkShapeList: logMsg("\nNo junk shapes found.") return sSep = "\n delete junk shape: " logMsg("\nRemoving junk shapes...{}{}".format(sSep, sSep.join(sJunkShapeList))) if not dryRun: mc.delete(sJunkShapeList) logMsg("Removed {0} junk shapes.".format(len(sJunkShapeList)))
def matchTransform(obj, target, **kwargs): logMsg(log='all') bPreserveChild = kwargs.pop('preserveChild', kwargs.pop('pc', False)) sAttr = kwargs.pop('attributeToMatch', kwargs.pop('atm', 'trs')) bObjSpace = kwargs.get('objectSpace', kwargs.get('os', False)) (oObj, oTarget) = argsToPyNode(obj, target) oChildren = None if bPreserveChild: oChildren = oObj.getChildren(typ='transform') oParent = oObj.getParent() if oChildren: if oParent: pm.parent(oChildren, oParent) else: pm.parent(oChildren, world=True) sAttrList = list(sAttr) if sAttr == "trs": matchTRS(oObj, oTarget, **kwargs) elif sAttr == "rpvt": matchRotatePivot(oObj, oTarget, **kwargs) elif sAttr == "spvt": matchScalePivot(oObj, oTarget, **kwargs) else: for sAttr in sAttrList: if sAttr == "t": matchPos(oObj, oTarget, **kwargs) elif sAttr == "r": matchRot(oObj, oTarget, **kwargs) elif sAttr == "s": if bObjSpace == True: matchScl(oObj, oTarget, **kwargs) else: logMsg('scale cannot be matched in world space !!', log='all') else: logMsg("'%s' not a valid attribute to match !!" % sAttr, log='all') if oChildren: pm.parent(oChildren, oObj)
def copyAttrs(srcNode, destNode, *sAttrList, **kwargs): logMsg(log='all') if "values" not in kwargs: kwargs["values"] = True bDelete = kwargs.pop("delete", False) bCreate = kwargs.pop("create", False) sSrcNode = argToStr(srcNode) sDestNode = argToStr(destNode) mObj = api.getNode(sSrcNode) fnNode = om.MFnDependencyNode(mObj) sCopyAttrList = [] for sAttr in sAttrList: if not getObject(sDestNode + "." + sAttr): if bCreate: mAttr = om.MFnAttribute(fnNode.attribute(sAttr)) sAddAttrCmd = mAttr.getAddAttrCmd(False).replace(";", " {};".format(sDestNode)) logMsg("Copy attr. '{}' from '{}' to '{}'." .format(sAttr, sSrcNode, sDestNode), log="info") pm.mel.eval(sAddAttrCmd) else: sAttr = "" else: if bCreate: logMsg("Attr. '{}' already exists on '{}'.".format(sAttr, sDestNode), log="info") if sAttr: sCopyAttrList.append(sAttr) mc.copyAttr(sSrcNode, sDestNode, attribute=sCopyAttrList, **kwargs) #copyAttrState(sSrcNode, sDestNode , *sCopyAttrList) if bDelete: for sAttr in sCopyAttrList: mc.deleteAttr(sSrcNode + "." + sAttr) return sCopyAttrList
def copyFile(sSrcPath, sDstPath, preserve_mode=True, preserve_times=True, in_place=False, update=False, link="", verbose=1, dry_run=False, buffer_size=512 * 1024, showProgress=True): """Copy a file 'sSrcPath' to 'sDstPath'. (Stolen and customized from distutils.file_util.copy_file) If 'sDstPath' is a directory, then 'sSrcPath' is copied there with the same name; otherwise, it must be a filename. (If the file exists, it will be ruthlessly clobbered.) If 'preserve_mode' is true (the default), the file's mode (type and permission bits, or whatever is analogous on the current platform) is copied. If 'preserve_times' is true (the default), the last-modified and last-access times are copied as well. If 'update' is true, 'sSrcPath' will only be copied if 'sDstPath' does not exist, or if 'sDstPath' does exist but is older than 'sSrcPath'. 'link' allows you to make hard links (os.link) or symbolic links (os.symlink) instead of copying: set it to "hard" or "sym"; if it is None (the default), files are copied. Don't set 'link' on systems that don't support it: 'copy_file()' doesn't check if hard or symbolic linking is available. Under Mac OS, uses the native file copy function in macostools; on other systems, uses '_copy_file_contents()' to copy file contents. Return a tuple (dest_name, copied): 'dest_name' is the actual name of the output file, and 'copied' is true if the file was copied (or would have been copied, if 'dry_run' true). """ # XXX if the destination file already exists, we clobber it if # copying, but blow up if linking. Hmmm. And I don't know what # macostools.copyfile() does. Should definitely be consistent, and # should probably blow up if destination exists and we would be # changing it (ie. it's not already a hard/soft link to sSrcPath OR # (not update) and (sSrcPath newer than sDstPath). sSrcPath = toStr(sSrcPath) sDstPath = toStr(sDstPath) # try: # sAction = _copy_action[link].capitalize() # except KeyError: # raise ValueError("Invalid value for 'link' argument: '{}'. Expected one of {}." # .format(link, _copy_action.keys())) sAction = "Copying" srcStat = os.stat(sSrcPath) if not S_ISREG(srcStat.st_mode): raise EnvironmentError("Source file NOT found: '{}'.".format(sSrcPath)) if osp.isdir(sDstPath): sDirPath = sDstPath sDstPath = osp.join(sDstPath, osp.basename(sSrcPath)) else: sDirPath = osp.dirname(sDstPath) if update and (not pathNewer(sSrcPath, sDstPath)): if verbose >= 1: logMsg("Not copying (output up-to-date): '{}'".format(sSrcPath), log="debug") return sDstPath, False if verbose >= 1: if osp.normcase(osp.basename(sDstPath)) == osp.normcase(osp.basename(sSrcPath)): logMsg("{} {}\n to {}".format(sAction, sSrcPath, sDirPath)) else: logMsg("{} {}\n as {}".format(sAction, sSrcPath, sDstPath)) if dry_run: return (sDstPath, True) # # If linking (hard or symbolic), use the appropriate system call # # (Unix only, of course, but that's the caller's responsibility) # if link == 'hard': # if not (osp.exists(sDstPath) and osp.samefile(sSrcPath, sDstPath)): # os.link(sSrcPath, sDstPath) # elif link == 'symb': # if not (osp.exists(sDstPath) and osp.samefile(sSrcPath, sDstPath)): # os.symlink(sSrcPath, sDstPath) # # # Otherwise (non-Mac, not linking), copy the file contents and # # (optionally) copy the times and mode. # else: if sameFile(sSrcPath, sDstPath): sMsg = "Source and destination files are the same:" sMsg += "\n source: ", sSrcPath sMsg += "\n destination: ", sDstPath raise EnvironmentError(sMsg) sTmpPath = "" try: dstStat = os.stat(sDstPath) except OSError: pass else:# destination path exists if not S_ISREG(dstStat.st_mode): raise EnvironmentError("Path already exists but NOT a regular file: '{}'." .format(sDstPath)) if not in_place: #pathRename(sDstPath, sDstPath) sTmpPath = sDstPath + ".tmpcopy" sCopyPath = sTmpPath if sTmpPath else sDstPath try: copyFileData(sSrcPath, sCopyPath, preserve_mode=preserve_mode, preserve_times=preserve_times, buffer_size=buffer_size, sourceStat=srcStat, showProgress=showProgress) if sTmpPath: if os.name == "nt": # on nt platform, destination must be removed first os.remove(sDstPath) pathRename(sTmpPath, sDstPath) finally: if sTmpPath and osp.exists(sTmpPath): os.remove(sTmpPath) return (sDstPath, True)
def conformShadingNetworkToNamespace(oMeshList, sNamespaceToMatch, **kwargs): bForce = kwargs.get("force", False) oShadingGroupMembersDct = {} oMatNotConformList = [] for oShape in oMeshList: # print "\nfor shape: ", oShape oMatSGList = shadingGroupsForObject(oShape) for oMatSG in oMatSGList: # print "for shadingGroup: ", oMatSG oMatList = pm.ls(oMatSG.inputs(), type=mc.listNodeTypes('shader', ex="texture")) oMat = oMatList[0] ##ignore shadingGroups where materials are defaultNode if oMat.isDefaultNode(): continue ##ignore shadingGroups where materials are already in namespace to match sMatNamespace = oMat.namespace() # print "sMatNamespace", sMatNamespace # print "sNamespaceToMatch", sNamespaceToMatch if sMatNamespace == sNamespaceToMatch: continue else: oMatNotConformList.append(oMat) oMembers = oMatSG.members() for oMember in oMembers: # print "member :", oMember if oMember.node() == oShape: oShadingGroupMembersDct.setdefault(oMatSG, []).append(oMember) # for k, v in oShadingGroupMembersDct.iteritems(): # print "for shadingGroup: ", k, ", specific members are: ", v if oMatNotConformList: if bForce: pass else: result = pm.confirmDialog( title='Materials not conform to Namespace...', message= "Found materials not conform to Namespace,\nCopy Shading Network, Conform to Namespace & Assign ?", button=["OK", 'Cancel'], defaultButton='Cancel', cancelButton='Cancel', dismissString='Cancel') if result == "Cancel": pm.warning("Materials Namespace conformation cancelled.") return bForce else: bForce = True else: if sNamespaceToMatch: logMsg('Materials already conformed to Namespace: "{0}"'.format( sNamespaceToMatch), warning=True) return bForce ##Force current namespace to the one to match to duplicate in this namespace mc.namespace(set=":") mc.namespace(set=sNamespaceToMatch if sNamespaceToMatch else ":") oMatNotConformList = [] oShapeAssignedList = [] for oMatSG, oMembers in oShadingGroupMembersDct.iteritems(): oNewMatSGs = pm.duplicate(oMatSG, rr=True, un=True) oNewMatSG = oNewMatSGs[0] # print "old shadingGroup: ", oMatSG # print "new shadingGroup: ", oNewMatSGs[0] # print "oMembers", oMembers # print oMembers[0] for oMember in oMembers: oShape = oMember.node() if oShape not in oShapeAssignedList: oShapeAssignedList.append(oShape) try: pm.sets(oNewMatSG, e=True, forceElement=oShape) logMsg('Material "{0}" assigned first to: "{1}"'.format( oNewMatSG, oShape), warning=True) except: logMsg('Could not assign material "{0}" first to: "{1}"'. format(oNewMatSG, oShape), warning=True) try: pm.sets(oNewMatSG, e=True, forceElement=oMembers) logMsg('Material "{0}" assigned to: "{1}"'.format( oNewMatSG, oMembers), warning=True) except: logMsg('Could not assign material "{0}" to: "{1}"'.format( oNewMatSG, oMembers), warning=True) mc.namespace(set=":") return bForce
def startScriptJobs(self): if pm.about(batch=True): return logMsg("Start ScriptJobs", log="debug") if self.postSceneReadJobId is None: self.postSceneReadJobId = pm.scriptJob( event=("PostSceneRead", safely(self.onPostSceneRead)), cu=True, kws=False) logMsg("PostSceneRead Job Started.") if self.newSceneOpenedJobId is None: self.newSceneOpenedJobId = pm.scriptJob( event=("NewSceneOpened", safely(self.onNewSceneOpened)), cu=True, kws=False) logMsg("NewSceneOpened Job Started.") if self.sceneOpenedJobId is None: self.sceneOpenedJobId = pm.scriptJob( event=("SceneOpened", safely(self.onSceneOpened)), cu=True, kws=False) logMsg("SceneOpened Job Started.") if self.preNewOrOpenedJobId is None: self.preNewOrOpenedJobId = pm.scriptJob( event=("PreFileNewOrOpened", safely(self.onPreFileNewOrOpened)), cu=True, kws=False) logMsg("PreNewFileOrOpened Job Started.") if self.quitMayaJobId is None: self.quitMayaJobId = pm.scriptJob( event=("quitApplication", safely(self.onQuitApplication)), cu=True, kws=False) logMsg("QuitApplication Job Started.") if self.sceneSavedJobId is None: self.sceneSavedJobId = pm.scriptJob( event=("SceneSaved", safely(self.onSceneSaved)), cu=True, kws=False) logMsg("SceneSaved Job Started.")
def averageVertexColorsToMaterial(oMatList="NoEntry"): if oMatList == "NoEntry": oMatList = pm.selected() if not oMatList: logMsg("Nothing is selected. Select meshes to apply vertex color.", warning=True) return for oMat in oMatList: logMsg("Processing {0}".format(repr(oMat))) try: colorAttr = oMat.attr("color") except pm.MayaAttributeError: logMsg("\tNo color attribute found.") continue try: oSG = oMat.shadingGroups()[0] except IndexError: print "\tNo ShadingGroup found." continue oMemberList = oSG.members() if not oMemberList: logMsg("\tShadingGroup is empty.") continue pm.select(oMemberList, r=True) pm.mel.ConvertSelectionToVertices() sSelectedVerts = mc.ls(sl=True) pm.refresh() try: vtxColorList = tuple( grouper( 3, mc.polyColorPerVertex(sSelectedVerts, q=True, rgb=True))) except: logMsg("\tNo vertex colors found.") continue numVtx = len(vtxColorList) rSum = 0.0 gSum = 0.0 bSum = 0.0 for r, g, b in vtxColorList: rSum += r gSum += g bSum += b if rSum + gSum + bSum > 0.0: avrVtxColor = (rSum / numVtx, gSum / numVtx, bSum / numVtx) try: colorAttr.disconnect() colorAttr.set(avrVtxColor) except Exception, e: logMsg("\t{0}".format(e))
def killScriptJobs(self): if pm.about(batch=True): return self.postSceneReadJobId = pm.scriptJob(kill=self.postSceneReadJobId, force=True) logMsg("PostSceneRead Job Killed.") self.newSceneOpenedJobId = pm.scriptJob(kill=self.newSceneOpenedJobId, force=True) logMsg("NewSceneOpened Job Killed.") self.sceneOpenedJobId = pm.scriptJob(kill=self.sceneOpenedJobId, force=True) logMsg("SceneOpened Job Killed.") self.preNewOrOpenedJobId = pm.scriptJob(kill=self.preNewOrOpenedJobId, force=True) logMsg("PreNewFileOrOpened Job Killed.") self.quitMayaJobId = pm.scriptJob(kill=self.quitMayaJobId, force=True) logMsg("QuitApplication Job Killed.") self.sceneSavedJobId = pm.scriptJob(kill=self.sceneSavedJobId, force=True) logMsg("SceneSaved Job Killed.")