def loadPathHistoryFromPrefs(self): proj = self.project pathSelector = self.treeWidget.childrenWidget.pathSelector pathSelector.clear() sPathList = getPref("file_browser|path_history", []) for sPath in sPathList: sFullLibName, sRelPath = addEndSlash(sPath).split("/", 1) rcLib = proj.loadedLibraries.get(sFullLibName) if not rcLib: continue if sRelPath: rcDir = rcLib.getEntry(sRelPath, dbNode=False) if not rcDir: continue sRelPath = rcDir.relPath() sTreePath = addEndSlash(("/" + pathJoin(rcLib.label, sRelPath))) sEntryPath = pathJoin(rcLib.fullName, sRelPath) pathSelector.addItem(sTreePath, sEntryPath) self.treeWidget.childrenWidget.pathHistoryLoaded = True pathSelector.setCurrentIndex(-1)
def createItems(self, parentItem, tree, data, parentPath="", rootPath=""): loadedItems = self.loadedItems itemCls = self.itemClass for current, children in tree.iteritems(): p = pathJoin(parentPath, current) bBypassItem = False if rootPath: rp = pathRelativeTo(p, rootPath) if (rp == ".") or (".." in rp): bBypassItem = True if bBypassItem: item = parentItem elif p in loadedItems: item = loadedItems[p] else: kwargs = data.get(p, {}).copy() texts = parentItem.columnCount() * [""] texts[0] = current texts = kwargs.pop("texts", texts) item = itemCls(parentItem, texts, **kwargs) loadedItems[p] = item if children: self.createItems(item, children, data, p, rootPath=rootPath)
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 __init__(self, project): super(DamasAuth, self).__init__() if project._damasdb is None: raise AssertionError(u"No Damas instance found in {}".format(project)) self._damasdb = project._damasdb self.cookieFilePath = pathJoin(os.getenv("USERPROFILE"), "damas_auth.json")
def contains(self, sAbsPath): sLibPath = normCase(self.absPath()) sPathDirs = pathSplitDirs(normCase(sAbsPath)) numDirs = len(pathSplitDirs(sLibPath)) sAlignedPath = pathJoin(*sPathDirs[:numDirs]) return sAlignedPath == sLibPath
def mkIconPath(sRelPath): global _ICON_DIR_PATH if (not _ICON_DIR_PATH) or (not osp.exists(_ICON_DIR_PATH)): p = sys.modules["davos"].__file__ p = osp.abspath(osp.join(osp.dirname(p), "..", "resources", "icon")) _ICON_DIR_PATH = p return pathJoin(_ICON_DIR_PATH, sRelPath)
def currentMayapy(): if sys.platform == "win32": p = pathJoin(os.environ["MAYA_LOCATION"], "bin", "mayapy.exe") else: raise NotImplementedError("Platform not supported yet: '{}'".format( sys.platform)) if not os.path.exists(p): raise EnvironmentError( "Could not found Maya's python interpreter: '{}'".format(p)) return p
def walk(self, parentPath="", rootPath=""): for sChild, children in self.iteritems(): p = pathJoin(parentPath, sChild) bYield = True if rootPath: rp = pathRelativeTo(p, rootPath) if (rp == ".") or (".." in rp): bYield = False if bYield: yield p, children for cp in children.walk(p, rootPath): yield cp
def iterPaths(self, parentPath="", rootPath=""): for sChild, children in self.iteritems(): p = pathJoin(parentPath, sChild) bYield = True if rootPath: rp = pathRelativeTo(p, rootPath) if (rp == ".") or (".." in rp): bYield = False if bYield: yield p for cp in children.iterPaths(p, rootPath): yield cp
def launch(rootDirList, update=False, dryRun=True, project="", dialogParent=None): global TREE_ITEM_DCT TREE_ITEM_DCT = {} app = qtGuiApp() if not app: app = QtGui.QApplication(sys.argv) proj = initProject(project) dlg = QuickTreeDialog(dialogParent) treeWdg = dlg.treeWidget treeWdg.setHeaderLabels(("Entity Name", "Infos")) missingPathItems = listMissingPathItems(rootDirList, update=update) badEntityList = [] treeDataList = [] for damEntity, sMissingPaths in missingPathItems: if isinstance(damEntity, basestring): p = pathJoin("Errors", damEntity) badEntityList.append({"path":p, "texts":[damEntity, sMissingPaths], "flags":Qt.ItemIsEnabled, "roles":{Qt.ForegroundRole:(1, QtGui.QBrush(Qt.red))} }) continue drcLib = proj.getLibrary("public", damEntity.libraryName) sLibPath = drcLib.absPath() sEntityTitle = damEntity.sgEntityType + 's' sEntityPath = damEntity.getPath("public") sEntiTreePath = re.sub("^" + sLibPath, sEntityTitle, sEntityPath) roleData = {Qt.UserRole:(0, damEntity)} treeDataList.append({"path":sEntiTreePath, "flags":None, "roles":roleData}) sTreePathList = tuple(re.sub("^" + sLibPath, sEntityTitle, p) for p in sMissingPaths) tree = OrderedTree.fromPaths(sTreePathList) for sTreePath in tree.iterPaths(rootPath=sEntiTreePath): treeDataList.append({"path":sTreePath, "flags":Qt.NoItemFlags}) treeWdg.createTree(badEntityList) treeWdg.defaultFlags |= Qt.ItemIsTristate treeWdg.defaultRoles = {Qt.CheckStateRole:(0, Qt.Unchecked)} treeWdg.createTree(treeDataList) topItemCount = treeWdg.topLevelItemCount() if topItemCount == 1: curItem = treeWdg.topLevelItem(0) treeWdg.setRootIndex(treeWdg.indexFromItem(curItem)) while curItem.childCount() == 1: curItem = curItem.child(0) curItem.setExpanded(True) else: for i in xrange(topItemCount): treeWdg.topLevelItem(i).setExpanded(True) dlg.show() while True: bOk = dlg.exec_() if not bOk: return bApply = False flags = (QTreeWidgetItemIterator.Checked | QTreeWidgetItemIterator.Enabled) treeIter = QTreeWidgetItemIterator(treeWdg, flags) damEntities = tuple(it.value().data(0, Qt.UserRole) for it in treeIter) damAssets = tuple(e for e in damEntities if isinstance(e, DamAsset)) damShots = tuple(e for e in damEntities if isinstance(e, DamShot)) if damAssets or damShots: sMsg = "Create directories and files for:\n" if damAssets: sMsg += "\n - {} Assets".format(len(damAssets)) if damShots: sMsg += "\n - {} Shots".format(len(damShots)) sConfirm = confirmDialog(title="WARNING !", message=sMsg, button=("Yes", "No"), defaultButton="No", cancelButton="No", dismissString="No", icon="warning", ) if sConfirm == "Yes": bApply = True break if bApply: entityDirList = len(damEntities) * [None] for i, damEntity in enumerate(damEntities): if not damEntity: continue damEntity.createDirsAndFiles(dryRun=dryRun, checkDb=False) entityDirList[i] = damEntity.getResource("public", "entity_dir") for drcDir in entityDirList: if drcDir: drcDir.setSyncRules(drcDir.syncRules)
def relToAbsPath(self, sRelPath): return pathJoin(self.absPath(), sRelPath)
import os from pytd.util.fsutils import pathJoin, copyFile from davos.core.damproject import DamProject #from davos.core.dbtypes import DummyDbCon, DrcDb proj = DamProject("zombtest") sMaFilePath = pathJoin(proj.getPath("template", "project"), "initial_files", "maya_2016.ma") print sMaFilePath, os.path.isfile(sMaFilePath) for sAstType in proj.getVar("asset_lib", "asset_types"): for sPathVar in proj.getVar(sAstType, "all_tree_vars"): p = proj.getTemplatePath(sAstType, sPathVar) if p.endswith(".ma"): copyFile(sMaFilePath, p, dry_run=False)
def launch_old(entityType="", dryRun=True, project="", dialogParent=None): global TREE_ITEM_DCT TREE_ITEM_DCT = {} app = qtGuiApp() if not app: app = QtGui.QApplication(sys.argv) sProject = os.environ["DAVOS_INIT_PROJECT"] if not project else project proj = DamProject(sProject) print sProject.center(80, "-") dlg = QuickTreeDialog(dialogParent) treeWdg = dlg.treeWidget treeWdg.setHeaderLabels(("Entity Name", "Infos")) dlg.show() missingPathItems = listMissingPathItems(proj, entityType) badEntityItems = [] for damEntity, sMissingPaths in missingPathItems: if isinstance(damEntity, basestring): badEntityItems.append((damEntity, sMissingPaths)) continue drcLib = proj.getLibrary("public", damEntity.libraryName) sLibPath = drcLib.absPath() sEntityTitle = damEntity.sgEntityType + 's' sEntityPath = damEntity.getPath("public") sEntityPath = re.sub("^" + sLibPath, sEntityTitle, sEntityPath) sEntityPathDirs = pathSplitDirs(sEntityPath) for sAbsPath in sMissingPaths: sTreePath = re.sub("^" + sLibPath, sEntityTitle, sAbsPath) sParentPath, sFilename = osp.split(pathNorm(sTreePath)) parentItem = TREE_ITEM_DCT.get(sParentPath) if not parentItem: sDirList = pathSplitDirs(sParentPath) curParentItem = treeWdg for i, sDirName in enumerate(sDirList): if i == 0: sItemPath = sDirName else: sItemPath = pathJoin(*sDirList[:i + 1]) item = TREE_ITEM_DCT.get(sItemPath) if not item: flags = None if sItemPath.startswith(sEntityPath): if len(pathSplitDirs(sItemPath)) > len(sEntityPathDirs): flags = Qt.NoItemFlags userData = None if sItemPath == sEntityPath: userData = damEntity item = loadTreeItem(curParentItem, sItemPath, [sDirName], flags=flags, userData=userData) curParentItem = item parentItem = curParentItem flags = None if sTreePath.startswith(sEntityPath): if len(pathSplitDirs(sTreePath)) > len(sEntityPathDirs): flags = Qt.NoItemFlags userData = None if sTreePath == sEntityPath: userData = damEntity loadTreeItem(parentItem, sTreePath, [sFilename], flags=flags, userData=userData) if badEntityItems: errorsItem = loadTreeItem(None, "Errors", ["ERRORS"]) treeWdg.insertTopLevelItem(0, errorsItem) for sEntityName, sError in badEntityItems: loadTreeItem(errorsItem, sEntityName, [sEntityName, sError], checkable=False) for i in xrange(treeWdg.topLevelItemCount()): treeWdg.topLevelItem(i).setExpanded(True) while True: bOk = dlg.exec_() if not bOk: return bApply = False flags = (QTreeWidgetItemIterator.Checked | QTreeWidgetItemIterator.Enabled) treeIter = QTreeWidgetItemIterator(treeWdg, flags) damEntities = tuple(it.value().data(0, Qt.UserRole) for it in treeIter) damAssets = tuple(e for e in damEntities if isinstance(e, DamAsset)) damShots = tuple(e for e in damEntities if isinstance(e, DamShot)) if damAssets or damShots: sMsg = "Create directories and files for:\n" if damAssets: sMsg += "\n - {} Assets".format(len(damAssets)) if damShots: sMsg += "\n - {} Shots".format(len(damShots)) sConfirm = confirmDialog(title="WARNING !", message=sMsg, button=("Yes", "No"), defaultButton="No", cancelButton="No", dismissString="No", icon="warning", ) if sConfirm == "Yes": bApply = True break if bApply: for damEntity in damEntities: if not damEntity: continue damEntity.createDirsAndFiles(dryRun=dryRun)
def getPath(self, sSpace, sSection, pathVar="", tokens=None, default="NoEntry", **kwargs): bResVars = kwargs.get("resVars", True) bResEnvs = kwargs.get("resEnvs", True) sRcPath = "" if sSpace: sRcPath = self.getVar(sSection, sSpace + "_path", default=default, resVars=bResVars) if not sRcPath: return sRcPath if pathVar: try: sRcPath = pathJoin(sRcPath, self.getVar(sSection, pathVar)) except AttributeError: if default != "NoEntry": return default raise if bResEnvs: sRcPath = pathResolve(sRcPath) sFieldSet = set() if bResVars: # resolve vars from config sFieldSet = set(findFmtFields(sRcPath)) if sFieldSet: confTokens = self.getVar(sSection, pathVar + "_tokens", default={}) sConfFieldSet = set(confTokens.iterkeys()) for sField in sFieldSet: if sField in confTokens: continue value = self.getVar(sSection, sField, "") if value: sConfFieldSet.add(sField) else: value = '{' + sField + '}' confTokens[sField] = value if confTokens: sRcPath = sRcPath.format(**confTokens) sFieldSet -= sConfFieldSet # resolve remaining vars from input tokens if tokens: if not isinstance(tokens, dict): raise TypeError("argument 'tokens' must be of type <dict>. Got {}" .format(type(tokens))) sFieldSet = sFieldSet - set(tokens.iterkeys()) if sFieldSet: msg = ("Cannot resolve path: '{}'. \n\tMissing tokens: {}" .format(sRcPath, list(sFieldSet))) raise RuntimeError(msg) sRcPath = sRcPath.format(**tokens) return pathNorm(sRcPath, keepEndSlash=True)
def mkPackFilePath(sPackDirPath): return pathJoin(sPackDirPath, "_package.json")
def __init__(self): self.cookieFilePath = pathJoin(os.getenv("USERPROFILE"), "dev_auth.json")