def libListType(libList): if isinstance(libList, str): return "STRING" op = libList[0] if (op == 'AND' or op == 'OR'): return op print("WHILE EXAMINING:", libList) cdErr('Invalid type encountered for a library identifier:' + str(op))
def checkIfLibFileMightSatisyNeedWithRequirements(tags, need, libFile, indent): [ReqTags, interfaceTags] = extractLibTags(libFile) Requirements = [] LibCanWork = True if need[0] == 'require': LibCanWork = False if 'provides' in interfaceTags: if need[1] in interfaceTags['provides']: #print indent, 'REQUIRE: ', need[1], ' in ' ,interfaceTags['provides'] LibCanWork = True for Req in ReqTags: # print "REQUIREMENT:", Req[0], Req[1] if Req[0] == 'feature': print "\n Nested Features should be implemented. Please implement them. (", Req[ 1], ")n" exit(2) elif Req[0] == 'require': Requirements.append(Req) elif Req[0] == 'tagOneOf': tagToCheck = Req[1] validValues = progSpec.extractListFromTagList(Req[2]) parentTag = progSpec.fetchTagValue(tags, tagToCheck) # E.g.: "platform" if parentTag == None: LibCanWork = False cdErr("ERROR: The tag '" + tagToCheck + "' was not found in" + libFile + ".\n") if not parentTag in validValues: LibCanWork = False else: cdlog(1, " Validated: " + tagToCheck + " = " + parentTag) return [LibCanWork, Requirements]
def downloadExtractZip(downloadUrl, packageName, packageDirectory): zipExtension = "" if downloadUrl.endswith(".zip"): zipExtension = ".zip" elif downloadUrl.endswith(".tar.gz"): zipExtension = ".tar.gz" elif downloadUrl.endswith(".tar.bz2"): zipExtension = ".tar.bz2" elif downloadUrl.endswith(".tar.xz"): zipExtension = ".tar.xz" elif downloadUrl.endswith(".tar"): zipExtension = ".tar" else: pass zipFileDirectory = packageDirectory + '/' + packageName innerPackageName = packageName # TODO: get actual innerPackageName innerPackageDir = zipFileDirectory + '/' + innerPackageName packagePath = zipFileDirectory + '/' + packageName + zipExtension checkDirectory = os.path.isdir(zipFileDirectory) zipFileName = os.path.basename(downloadUrl) if not checkDirectory: makeDirs(zipFileDirectory + "/INSTALL") emgr.downloadFile(packagePath, downloadUrl) try: cdlog(1, "Extracting zip file: " + zipFileName) shutil.unpack_archive(packagePath, zipFileDirectory) except: cdErr("Could not extract zip archive file: " + zipFileName)
def getFieldSpec(fieldName, structRef): #print " Searching",structRef['name'],"for", fieldName if structRef==None: cdErr('To build a list GUI for list of "'+structTypeName+'" a struct is needed but is not found.') for field in structRef['fields']: if field['fieldName'] == fieldName: return field cdErr('Field not found in model "'+fieldName+'".')
def apply(classes, tags, className, dispMode): if dispMode[:4] == 'TAG_': dispModeTagName = dispMode[4:] dispMode = progSpec.fetchTagValue(tags, dispModeTagName) if (dispMode != 'none' and dispMode != 'text' and dispMode != 'draw' and dispMode != 'Proteus' and dispMode != 'toGUI'): cdErr( 'Invalid parameter for display mode in Code Data Display pattern: ' + str(dispMode)) if dispMode == 'none': return global classesToProcess classesToProcess = [className] global classesEncoded #classesEncoded={} if (dispMode == 'Proteus'): processor = structAsProteusWriter() elif (dispMode == 'text'): processor = structToStringWriter() elif (dispMode == 'draw'): processor = structDrawingWriter() processor.addGlobalCode(classes) for classToEncode in classesToProcess: if classToEncode in classesEncoded: continue cdlog(1, " ENCODING " + dispMode + ": " + classToEncode) classesEncoded[classToEncode] = 1 pattern_GenSymbols.apply( classes, {}, [classToEncode]) # Invoke the GenSymbols pattern processor.processStruct(classes, classToEncode) return
def checkIfLibFileMightSatisyNeedWithRequirements(tags, need, libFile, indent): [ReqTags, interfaceTags, featuresNeeded] = extractLibTags(libFile) Requirements = [] LibCanWork = True if need[0] == 'require': LibCanWork = False if 'provides' in interfaceTags: if need[1] in interfaceTags['provides']: #print(indent, '{}REQUIRE: {} in {}'.format(indent, need[1], interfaceTags['provides'])) LibCanWork = True for ReqTag in ReqTags: #print("REQUIREMENT: {}".format(ReqTag)) if ReqTag[0] == 'feature': print( "\n Nested Features should be implemented. Please implement them. (", ReqTag[1], ")n") exit(2) elif ReqTag[0] == 'require': Requirements.append(ReqTag) elif ReqTag[0] == 'tagOneOf': tagToCheck = ReqTag[1] validValues = progSpec.extractListFromTagList(ReqTag[2]) parentTag = progSpec.fetchTagValue(tags, tagToCheck) # E.g.: "platform" if parentTag == None: LibCanWork = False cdErr("ERROR: The tag '" + tagToCheck + "' was not found in" + libFile + ".\n") if not parentTag in validValues: LibCanWork = False return [LibCanWork, Requirements, featuresNeeded]
def parseInput(inputStr): cdlog(2, "Parsing build-specs...") progSpec.saveTextToErrFile(inputStr) try: localResults = progSpecParser.parseString(inputStr, parseAll=True) except ParseBaseException as pe: cdErr("While parsing: {}".format(pe)) return localResults
def extractMacroDefs(macroDefMap, inputString): macroDefs = re.findall('#define.*%>', inputString) for macroStr in macroDefs: try: localResults = macroDef.parseString(macroStr, parseAll=True) except ParseException as pe: cdErr("Error Extracting Macro: {} In: {}".format(pe, macroStr)) exit(1) extractMacroSpec(macroDefMap, localResults[0])
def packageInstalled(packageManagar, packageName): cdlog(1, "Package Installing: " + packageName) if subprocess.call(f'{packageManagar} {packageName}' + " -y > /dev/null 2>&1", shell=True) == 0: cdlog(1, "Package installed Successfully") return True else: cdErr("Unable to install package. \nPlease install manually : " + packageName)
def Write_structExtracter(classes, ToStructName, FromStructName, fields, nameForFunc, logLvl): memObjFields=[] progSpec.populateCallableStructFields(memObjFields, classes, ToStructName) if memObjFields==None: cdErr("struct {} is not defined".format(ToStructName.replace('str','mem'))) S=' me string: tmpStr\n' for field in fields: # Extract all the fields in the string version. S+=Write_fieldExtracter(classes, ToStructName, field, memObjFields, 'SRec', '', True, ' ', 0, logLvl+1) if ToStructName== FromStructName and progSpec.doesClassContainFunc(classes, ToStructName, 'postParseProcessing'): S += 'memStruct.postParseProcessing()\n' return S
def doMacroSubstitutions(macros, inputString): macros['BlowPOP'] = {'ArgList': ['dummyArg'], 'Body': 'dummyArg'} macros['DESLASH'] = {'ArgList': ['dummyArg'], 'Body': 'dummyArg'} subsWereMade = True while (subsWereMade == True): subsWereMade = False for thisMacro in macros: macRefPattern = re.compile(r'(?<!#define)([^a-zA-Z0-9_]+)(' + thisMacro + ')(\s*)\(([^)]*)\)') #print("MACRO NAME:", thisMacro) newString = '' currentPos = 0 for match in macRefPattern.finditer(inputString): #print(" %s: %s %s" % (match.start(), match.group(1), match.group(2))) newText = macros[thisMacro]['Body'] #print(" START TEXT:", newText) StartPosOfParens = match.start() + len(match.group(1)) + len( match.group(2)) + len(match.group(3)) EndPos = findMacroEnd(inputString, StartPosOfParens) if EndPos == -1: print("\nERROR: Parentheses problem in macro", thisMacro, "\n") exit(2) paramStr = inputString[StartPosOfParens + 1:EndPos - 1] #match.group(4) params = paramStr.split(',') #print(' PARAMS:', params) idx = 0 numMacroArgs = len(macros[thisMacro]['ArgList']) if ((numMacroArgs > 0 and numMacroArgs != len(params)) or (numMacroArgs == 0 and len(params) != 1)): cdErr( "The macro {} has {} parameters, but is called with {}." .format(thisMacro, len(macros[thisMacro]['ArgList']), len(params))) for arg in macros[thisMacro]['ArgList']: #print(" SUBS:", arg, ', ', params[idx], ', ', thisMacro) replacement = params[idx] if thisMacro == 'BlowPOP': replacement = BlowPOPMacro(replacement) elif thisMacro == 'DESLASH': replacement = deSlashMacro(replacement) newText = newText.replace(arg, replacement) idx += 1 #print(" NEW TEXT:", newText) newString += inputString[currentPos:match.start() + len(match.group(1))] + newText currentPos = EndPos subsWereMade = True newString += inputString[currentPos:] inputString = newString #print(" RETURN STRING:[", inputString, ']') # Last, replace the text into inputString return inputString
def AddToObjectFromText(ProgSpec, clsNames, inputStr, description): macroDefs = {} # This var is not used here. If needed, make it an argument. inputStr = comment_remover(inputStr) #print '####################\n',inputStr, "\n######################^\n\n\n" errLevl=logLvl(); cdlog(errLevl, 'Parsing: '+description) progSpec.saveTextToErrFile(inputStr) # (map of classes, array of objectNames, string to parse) try: results = objectList.parseString(inputStr, parseAll = True) except ParseException , pe: cdErr( "Error parsing generated class {}: {}".format(description, pe))
def parseCodeDogLibTags(inputString): tmpMacroDefs={} inputString = comment_remover(inputString) extractMacroDefs(tmpMacroDefs, inputString) inputString = doMacroSubstitutions(tmpMacroDefs, inputString) progSpec.saveTextToErrFile(inputString) try: localResults = libTagParser.parseString(inputString, parseAll = False) except ParseException , pe: cdErr( "Error parsing lib tags: {}".format( pe))
def findMacroEnd(inputString, StartPosOfParens): nestLvl=0 if(inputString[StartPosOfParens] != '('): cdErr("NO PAREN!"); exit(2); ISLen=len(inputString) for pos in range(StartPosOfParens, ISLen): ch = inputString[pos] if ch=='(': nestLvl+=1 if ch==')': nestLvl-=1 if nestLvl==0: #print "MACRO-ARGS:", inputString[StartPosOfParens:pos+1] return pos+1 return -1
def collectLibFilenamesFromFolder(folderPath): for filename in os.listdir(folderPath): if filename.endswith("Lib.dog"): libPaths.append(os.path.join(folderPath, filename)) elif filename.endswith("Lib.dog.proxy"): line = open(os.path.join(folderPath, filename)).readline() line = line.strip() baseName = os.path.basename(line) #print("baseName: {}".format(baseName)) if (filename.strip('.proxy') == baseName): libPaths.append(os.path.realpath(line)) else: cdErr("File name " + filename + " does not match path name.")
def Write_ALT_Extracter(classes, parentStructName, fields, VarTagBase, VarTagSuffix, VarName, indent, level, logLvl): # Structname should be the name of the structure being parsed. It will be converted to the mem version to get 'to' fields. # Fields is the list of alternates. # VarTag is a string used to create local variables. # VarName is the LVAL variable name. global globalFieldCount cdlog(logLvl, "WRITING code to extract one of {} from parse tree...".format(parentStructName)) InnerMemObjFields = [] progSpec.populateCallableStructFields(InnerMemObjFields, classes, parentStructName) if parentStructName.find('::') != -1: cdErr("TODO: Make string parsing work on derived classes. Probably just select the correct fields for the destination struct.") S="" # Code to fetch the ruleIDX of this ALT. If the parse was terminal (i.e., 'const'), it will be at a different place. if(level==-1): level=1 VarTag='SRec1' VarTagSuffix='0' else: globalFieldCount+=1 VarTag=VarTagBase+str(level) VarTagSuffix=str(level-1)+'.child.next'+VarTagSuffix indent2 = indent+' ' S+='\n'+indent+'{\n' S+='\n'+indent2+'our stateRec: '+VarTag+' <- '+VarTagBase+VarTagSuffix+'\n' loopVarName = "ruleIDX"+str(globalFieldCount) S+=indent2+'me int: '+loopVarName+' <- '+VarTag+'.child.productionID\n' #print "RULEIDX:", indent, parentStructName, VarName if VarName!='memStruct': S+=indent2 + 'me string: '+VarName+'\n' count=0 S+= indent2+"switch("+loopVarName+"){\n" for altField in fields: if(altField['isNext']!=True): continue; # This field isn't in the parse stream. cdlog(logLvl+1, "ALT: {}".format(altField['parseRule'])) if not 'parseRule' in altField: print("Error: Is syntax missing a '>'?"); exit(2); S+=indent2+" case " + altField['parseRule'] + ":{\n" coFactualCode='' if 'coFactuals' in altField: #Extract field and cofactsList for coFact in altField['coFactuals']: coFactualCode+= indent2 +' ' + VarName + '.' + coFact[0] + ' <- ' + coFact[2] + "\n" cdlog(logLvl+2, "Cofactual: "+coFactualCode) S+=Write_fieldExtracter(classes, parentStructName, altField, InnerMemObjFields, VarTagBase, VarName, False, indent2+' ', level, logLvl+1) S+=coFactualCode S+=indent2+" }\n" count+=1 S+=indent2+"}" S+=indent+"}" return S
def extractFuncBody(ObjectName,funcName, funcBodyIn): if funcBodyIn[0] == "<%": funcBodyOut = "" if len(funcBodyIn)== 3: # handles new pyparsing funcTextVerbatim = funcBodyIn[1] elif len(funcBodyIn)== 2: # handles old pyparsing funcTextVerbatim = funcBodyIn[1][0] else: cdErr( "problem in funcTextVerbatim: len(funcBodyIn): {}".format( len(funcBodyIn))) exit(1) else: funcBodyOut = extractActSeqToFunc(funcName, funcBodyIn) funcTextVerbatim = "" return funcBodyOut, funcTextVerbatim
def extractObjectsOrPatterns(ProgSpec, clsNames, macroDefs, objectSpecResults): newClasses=[] for spec in objectSpecResults: s=spec[0] if s == "model" or s == "struct" or s == "string" or s == "stream": newName=extractObjectSpecs(ProgSpec, clsNames, spec, s) if newName!=None: newClasses.append(newName) elif s == "do": extractPatternSpecs(ProgSpec, clsNames, spec) elif s == "#define": extractMacroSpec(macroDefs, spec) else: cdErr("Error in extractObjectsOrPatterns; expected 'object' or 'do' and got '{}'".format(spec[0])) return newClasses
def gitClone(cloneUrl, packageName, packageDirectory): checkSys.CheckPipModules({'GitPython': '3.1'}) import urllib.request from git import Repo packagePath = packageDirectory + '/' + packageName + '/' + packageName checkRepo = os.path.isdir(packagePath) if not checkRepo: try: urllib.request.urlopen(cloneUrl) except (urllib.error.URLError, urllib.error.HTTPError): cdErr("URL not found: " + cloneUrl) cdlog(1, "Cloning git repository: " + packageName) Repo.clone_from(cloneUrl, packagePath) makeDirs(packageDirectory + '/' + packageName + "/INSTALL")
def replaceFileName(fileMatch): global currentFilesPath fileName = fileMatch.group(1) currentWD = os.getcwd() pathName = abspath(currentWD) + "/" + fileName if not os.path.isfile(pathName): dirname, filename = os.path.split(abspath(getsourcefile(lambda: 0))) pathName = dirname + "/" + fileName if not os.path.isfile(pathName): pathName = currentFilesPath + "/" + fileName if not os.path.isfile(pathName): cdErr("Cannot find include file '" + fileName + "'") includedStr = progSpec.stringFromFile(pathName) includedStr = processIncludedFiles(includedStr, pathName) return includedStr
def processStruct(self, classes, className): global classesEncoded classesEncoded[className] = 1 self.currentClassName = className modelRef = progSpec.findSpecOf(classes[0], className, 'model') self.resetVars(modelRef) self.currentModelSpec = modelRef if modelRef == None: cdErr('To write a processing function for class "' + className + '" a model is needed but is not found.') ### Write code for each field for field in modelRef['fields']: fldCat = progSpec.fieldsTypeCategory(field['typeSpec']) fieldName = field['fieldName'] self.processField(fieldName, field, fldCat) self.addOrAmendClasses(classes, className, modelRef)
def downloadFile(fileName, downloadURL): checkSys.CheckPipModules({'urllib3': '1.25'}) import urllib3 try: cdlog(1, "Downloading file: " + fileName) http = urllib3.PoolManager() r = http.request('GET', downloadURL, preload_content=False) except: cdErr("URL not found: " + downloadURL) else: with open(fileName, 'wb') as out: while True: data = r.read(1028) if not data: break out.write(data) r.release_conn()
def constructANDListFromNeeds(tags, needs, files, indent): AND_List = ['AND', []] for need in needs: #print(indent, "**need*: ", need) if need[0] == 'feature': if need[1] in featuresHandled: continue cdlog(1, "FEATURE: "+str(need[1])) featuresHandled.append(need[1]) filesToTry = [findLibrary(need[1])] if filesToTry[0]=='': cdErr('Could not find a dog file for feature '+need[1]) else: filesToTry = files if len(filesToTry)>0: solutionOptions = constructORListFromFiles(tags, need, filesToTry, indent + "| ") if len(solutionOptions[1])>0: AND_List[1].append(solutionOptions) return AND_List
def applyOwner(owner, langType, innerType, idxType, actionOrField, varMode): if owner == 'const': if actionOrField == "field": langType = "final static " + langType else: langType = "final " + langType elif owner == 'me': langType = langType elif owner == 'my': langType = langType elif owner == 'our': langType = langType elif owner == 'their': langType = langType elif owner == 'itr': langType = langType = "Iterator<Map.Entry<" + idxType + ', ' + innerType + "> >" elif owner == 'we': langType = 'static ' + langType else: cdErr("ERROR: Owner of type not valid '" + owner + "'") return langType
def extractFuncBody(funcName, funcBodyIn): '''Extract body of funcName (str) from funcBodyIn (parseResults) Returns two values: funcBodyOut for CodeDog defined body & funcTextVerbatim for verbatim text. If body is verbatim: funcBodyOut is an empty string, funcTextVerbatim is a string If body is CodeDog: funcBodyOut is a list of stuff, funcTextVerbatim is an empty string ''' if funcBodyIn.rValueVerbatim: funcBodyOut = "" funcTextVerbatim = funcBodyIn.rValueVerbatim[ 1] # opening and closing verbatim symbols are indices 0 and 2 elif funcBodyIn.actionSeq: funcBodyOut = extractActSeq(funcName, funcBodyIn.actionSeq) funcTextVerbatim = "" else: cdErr( "problem in extractFuncBody: funcBodyIn has no rValueVerbatim or actionSeq" ) exit(1) return funcBodyOut, funcTextVerbatim
def Write_structExtracter(classes, ToStructName, FromStructName, fields, nameForFunc, logLvl): global extracterFunctionAccumulator global parserFunctionAccumulator memObjFields = [] progSpec.populateCallableStructFields(memObjFields, classes, ToStructName) if memObjFields == None: cdErr("struct {} is not defined".format( ToStructName.replace('str', 'mem'))) S = ' me string: tmpStr;\n' advance = False for field in fields: # Extract all the fields in the string version. S += Write_fieldExtracter(classes, ToStructName, field, memObjFields, 'SRec', '', advance, '', ' ', 0, logLvl + 1) advance = True if ToStructName == FromStructName: if progSpec.doesClassContainFunc(classes, ToStructName, 'postParseProcessing'): postParseFuncName = "postParseProcessing_" + ToStructName S += " " + postParseFuncName + "(memStruct, SRec0)\n" newStructtxt = '\n struct ' + ToStructName + '{flag: postParseProcessed}\n' codeDogParser.AddToObjectFromText( classes[0], classes[1], newStructtxt, 'Adding ' + ToStructName + '{flag: postParseProcessed}') pppFunc = "\n void: " + postParseFuncName + "(their " + ToStructName + ": item, our stateRec: SRec) <- {item.postParseProcessing(); item.postParseProcessed<-true}\n" extracterFunctionAccumulator += pppFunc elif progSpec.doesClassContainFunc(classes, ToStructName, 'postParseProcessingEtc'): postParseFuncName = "postParseProcessingEtc_" + ToStructName S += " EP." + postParseFuncName + "(memStruct, SRec0)\n memStruct.postParseProcessed<-true\n" newStructtxt = '\n struct ' + ToStructName + '{flag: postParseProcessed}\n' codeDogParser.AddToObjectFromText( classes[0], classes[1], newStructtxt, 'Adding ' + ToStructName + '{flag: postParseProcessed}') pppFunc = "\n void: " + postParseFuncName + "(their " + ToStructName + ": item, our stateRec: SRec) <- {print(\"Override this function!\")}\n" parserFunctionAccumulator += pppFunc return S
def codeListWidgetManagerClassOverride(classes, listManagerStructName, structTypeName): funcTextToUpdateViewWidget = '' funcTextToUpdateEditWidget = '' funcTextToUpdateCrntFromWidget = '' funcTextToPushCrntToListView = '' rowHeaderCode = '' rowViewCode = '' # Find the model modelRef = progSpec.findSpecOf(classes[0], structTypeName, 'model') currentModelSpec = modelRef if modelRef==None: cdErr('To build a list GUI for list of "'+structTypeName+'" a model is needed but is not found.') ### Write code for each field for field in modelRef['fields']: typeSpec = field['typeSpec'] fldCat = progSpec.fieldsTypeCategory(typeSpec) fieldName = field['fieldName'] label = deCamelCase(fieldName) CasedFieldName = fieldName[0].upper() + fieldName[1:] widgetName = CasedFieldName + 'Widget' if not progSpec.isAContainer(typeSpec): if(fldCat!='struct'): rowHeaderCode += ' their GUI_Frame: '+fieldName + '_header <- makeLabelWidget("'+fieldName+'")\n' rowHeaderCode += ' setLabelWidth('+fieldName+'_header, 15)\n' rowHeaderCode += ' addToContainer(headerBox, '+fieldName+'_header)\n' if fldCat=='struct': funcTextToUpdateViewWidget += '' funcTextToUpdateEditWidget += ' /- updateWidgetFromVars()\n' funcTextToUpdateCrntFromWidget += ' /- updateVarsFromWidget()\n' elif fldCat=='enum' or fldCat=='mode': funcTextToUpdateViewWidget += '' funcTextToUpdateEditWidget += '' funcTextToUpdateCrntFromWidget += ''# crntRecord.'+fieldName+' <- dialog.' + widgetName + '.getValue()\n' elif fldCat=='bool': funcTextToUpdateViewWidget += '' funcTextToUpdateEditWidget += '' funcTextToUpdateCrntFromWidget += ' crntRecord.'+fieldName+' <- dialog.' + widgetName + '.getValue()\n' elif fldCat=='string': funcTextToUpdateViewWidget += '' funcTextToUpdateEditWidget += ' dialog.' + widgetName + '.setValue('+structTypeName+'_ListData[N].'+fieldName+')\n' funcTextToUpdateCrntFromWidget += ' me string: '+widgetName+'Str <- string(dialog.' + widgetName + '.getValue())\n' funcTextToUpdateCrntFromWidget += ' crntRecord.'+fieldName+' <- '+widgetName+'Str\n' rowViewCode += ' their GUI_Frame: '+fieldName + '_value <- makeLabelWidget(crntRecord.'+fieldName+'.data())\n' rowViewCode += ' setLabelWidth('+fieldName+'_value, 15)\n' rowViewCode += ' addToContainer(rowBox, '+fieldName+'_value)\n' rowViewCode += ' showWidget('+fieldName+'_value)\n' elif fldCat=='int': funcTextToUpdateViewWidget += '' funcTextToUpdateEditWidget += ' dialog.' + widgetName + '.setValue('+structTypeName+'_ListData[N].'+fieldName+')\n' #funcTextToUpdateCrntFromWidget += ' me string: '+widgetName+'Str <- string(dialog.' + widgetName + '.getValue())\n' #funcTextToUpdateCrntFromWidget += ' crntRecord.'+fieldName+' <- dataStr\n' rowViewCode += ' their GUI_Frame: '+fieldName + '_value <- makeLabelWidget(toString(crntRecord.'+fieldName+').data())\n' rowViewCode += ' setLabelWidth('+fieldName+'_value, 15)\n' rowViewCode += ' addToContainer(rowBox, '+fieldName+'_value)\n' rowViewCode += ' showWidget('+fieldName+'_value)\n' else: print"pattern_MakeGUI.codeListWidgetManagerClassOverride fldCat not specified: ", fldCat; exit(2) ############### CODE = 'struct '+listManagerStructName+''': inherits=ListWidgetManager{ our <STRUCTNAME>: crntRecord our <STRUCTNAME>[our list]: <STRUCTNAME>_ListData me <STRUCTNAME>_Dialog_GUI: dialog their GUI_Frame: listViewWidget their GUI_Frame[their list]:rows their GUI_Frame: crntRow /- Override all these for each new list editing widget their GUI_Frame: makeListHeader() <- { their GUI_Frame: box <- makeFrameWidget() their GUI_Frame: headerRow <- makeRowWidget("") their GUI_Frame: headerBox <- makeXStackWidget("") <ROWHEADERCODE> addToContainer(headerRow, headerBox) addToContainer(box, headerRow) return(box) } their GUI_Frame: makeRowView(our <STRUCTNAME>: item) <- { crntRecord <- item their GUI_Frame: rowBox <- makeXStackWidget("") <ROWVIEWCODE> showWidget(rowBox) return(rowBox) } their listWidget: makeListViewWidget() <- { listViewWidget <- makeListWidget("") setListWidgetSelectionMode (listViewWidget, SINGLE) withEach item in <STRUCTNAME>_ListData { their GUI_Frame: row <- makeRowView(item) addToContainer(listViewWidget, row) } return(listViewWidget) } me int: pushCrntToList(me int: N) <- { <STRUCTNAME>_ListData.pushLast(crntRecord); me int: listLength <- getListLength() print("listLength: ", listLength) their GUI_Frame: row <- makeRowView(crntRecord) rows.pushLast(row) addToContainer(listViewWidget, row) return(listLength) } void: deleteNthRow(me int: N) <- { rows.deleteNth(N) } their GUI_Frame: getNthRow(me int: N) <-{ crntRow <- rows[N] } me int: deleteNthItem(me int: N) <- { <STRUCTNAME>_ListData.deleteNth(N) me int: retVal <- getListLength() return(retVal) } void: updateViewableWidget() <- {<funcTextToUpdateViewWidget>} their GUI_item: makeEditableWidget() <- {return(dialog.make<STRUCTNAME>Widget(crntRecord))} void: updateEditableWidget(me int: N) <- {<funcTextToUpdateEditWidget>} void: updateCrntFromEdited(me int: N) <- {<funcTextToUpdateCrntFromWidget>} void: allocateNewCurrentItem() <- {Allocate(crntRecord)} void: copyCrntBackToList(me int: N) <- {<STRUCTNAME>_ListData[N] <- crntRecord} void: copyCrntBackToListView(me int: N) <- { print("copyCrntBackToListView ", N) } void: setCurrentItem(me int: idx) <- {crntRecord <- <STRUCTNAME>_ListData[idx]} void: setValue(our <STRUCTNAME>[our list]: ListData) <- {<STRUCTNAME>_ListData <- ListData} me int: getListLength() <- {return(<STRUCTNAME>_ListData.size())} their GUI_item: initWidget(our <STRUCTNAME>[our list]: Data) <- { <STRUCTNAME>_ListData <- Data Allocate(rows) return(ListEdBox.init_dialog(self)) } } ''' CODE = CODE.replace('<STRUCTNAME>', structTypeName) CODE = CODE.replace('<funcTextToUpdateViewWidget>', funcTextToUpdateViewWidget) CODE = CODE.replace('<funcTextToUpdateEditWidget>', funcTextToUpdateEditWidget) CODE = CODE.replace('<funcTextToUpdateCrntFromWidget>', funcTextToUpdateCrntFromWidget) CODE = CODE.replace('<funcTextToPushCrntToListView>', funcTextToPushCrntToListView) CODE = CODE.replace('<ROWHEADERCODE>', rowHeaderCode) CODE = CODE.replace('<ROWVIEWCODE>', rowViewCode) #print '==========================================================\n'+CODE codeDogParser.AddToObjectFromText(classes[0], classes[1], CODE, listManagerStructName)
def BuildGuiForStruct(classes, className, dialogStyle, newStructName): # This makes 4 types of changes to the class: # It adds a widget variable for items in model // newWidgetFields: ' their '+typeName+': '+widgetName # It adds a set Widget from Vars function // widgetFromVarsCode: Func UpdateWidgetFromVars() # It adds a set Vars from Widget function // varsFromWidgetCode: Func UpdateVarsFromWidget() # It add an initialize Widgets function. // widgetInitFuncCode: widgetName+' <- '+makeTypeNameCall+'\n addToContainer(box, '+widgetName+')\n' # dialogStyles: 'Z_stack', 'X_stack', 'Y_stack', 'TabbedStack', 'FlowStack', 'WizardStack', 'Dialog', 'SectionedDialogStack', 'V_viewable' # also, handle non-modal dialogs global classesEncoded global currentClassName global currentModelSpec classesEncoded[className]=1 currentClassName = className # reset the string vars that accumulate the code global newWidgetFields global widgetInitFuncCode global widgetFromVarsCode global varsFromWidgetCode newWidgetFields='' widgetInitFuncCode='' widgetFromVarsCode='' varsFromWidgetCode='' # Find the model modelRef = progSpec.findSpecOf(classes[0], className, 'model') currentModelSpec = modelRef if modelRef==None: cdErr('To build a GUI for class "'+className+'" a model is needed but is not found.') #TODO: write func body for: widgetFromVarsCode(selected item & click edit) & varsFromWidgetCode(ckick OK from editMode) ### Write code for each field for field in modelRef['fields']: typeSpec = field['typeSpec'] fldCat = progSpec.fieldsTypeCategory(typeSpec) fieldName = field['fieldName'] labelText = deCamelCase(fieldName) if fieldName=='settings': # add settings continue structTypeName='' if fldCat=='struct': # Add a new class to be processed structTypeName =typeSpec['fieldType'][0] if (progSpec.doesClassDirectlyImlementThisField(classes, structTypeName, structTypeName+':managedWidget') or structTypeName.endswith('Widget')): fldCat = 'widget' else: newGUIStyle = 'Dialog' guiStructName = structTypeName+'_'+newGUIStyle+'_GUI' addNewStructToProcess(guiStructName, structTypeName, 'struct', 'Dialog') if fldCat != 'widget' and progSpec.isAContainer(typeSpec):# Add a new list to be processed structTypeName = typeSpec['fieldType'][0] guiStructName = structTypeName+'_LIST_View' addNewStructToProcess(guiStructName, structTypeName, 'list', 'Dialog') #TODO: make actions for each function if fldCat=='func': if fieldName[-4:]== '_btn': buttonLabel = deCamelCase(fieldName[:-4]) # Add a button whose click calls this. print "ADDING BUTTON FOR:", fieldName getButtonHandlingCode(classes, buttonLabel, fieldName) else: # Here is the main case where code to edit this field is written getWidgetHandlingCode(classes, fldCat, fieldName, field, structTypeName, dialogStyle, '') # Parse everything initFuncName = 'make'+className[0].upper() + className[1:]+'Widget' if dialogStyle == 'Z_stack': containerWidget='makeStoryBoardWidget("makeStoryBoardWidget")' elif dialogStyle == 'TabbedStack': containerWidget='makeTabbedWidget("makeTabbedWidget")' else: containerWidget='makeFrameWidget()' CODE = ''' struct <CLASSNAME> {} struct <NEWSTRUCTNAME> { <NEWWIDGETFIELDS> our <CLASSNAME>: <CLASSNAME>_data their GUI_Frame: <INITFUNCNAME>(our <CLASSNAME>: Data) <- { <CLASSNAME>_data<-Data their GUI_Frame:box <- <CONTAINERWIDGET> <WIDGETINITFUNCCODE> return(box) } void: setValue(our <CLASSNAME>: var) <- { <WIDGETFROMVARSCODE> } void: getValue() <- { <VARSFROMWIDGETCODE> } }\n''' # TODO: add <VARSFROMWIDGETCODE> CODE = CODE.replace('<NEWSTRUCTNAME>', newStructName) CODE = CODE.replace('<NEWWIDGETFIELDS>', newWidgetFields) CODE = CODE.replace('<CLASSNAME>', className) CODE = CODE.replace('<WIDGETINITFUNCCODE>', widgetInitFuncCode) CODE = CODE.replace('<INITFUNCNAME>', initFuncName) CODE = CODE.replace('<WIDGETFROMVARSCODE>', widgetFromVarsCode) CODE = CODE.replace('<VARSFROMWIDGETCODE>', varsFromWidgetCode) CODE = CODE.replace('<CONTAINERWIDGET>', containerWidget) if newStructName == "EntryPad_Dialog_GUI":print '==========================================================\n'+CODE codeDogParser.AddToObjectFromText(classes[0], classes[1], CODE, newStructName)
def BuildGuiForList(classes, className, dialogStyle, newStructName): # This makes 4 types of changes to the class: # It adds a widget variable for items in model // newWidgetFields: ' their '+typeName+': '+widgetName # It adds a set Widget from Vars function // widgetFromVarsCode: Func UpdateWidgetFromVars() # It adds a set Vars from Widget function // varsFromWidgetCode: Func UpdateVarsFromWidget() # It add an initialize Widgets function. // widgetInitFuncCode: widgetName+' <- '+makeTypeNameCall+'\n addToContainer(box, '+widgetName+')\n' # dialogStyles: 'Z_stack', 'X_stack', 'Y_stack', 'TabbedStack', 'FlowStack', 'WizardStack', 'Dialog', 'SectionedDialogStack' # also, handle non-modal dialogs global classesEncoded global currentClassName global currentModelSpec classesEncoded[className]=1 currentClassName = className # reset the string vars that accumulate the code global newWidgetFields global widgetInitFuncCode global widgetFromVarsCode global varsFromWidgetCode newWidgetFields='' widgetInitFuncCode='' widgetFromVarsCode='' varsFromWidgetCode='' # Find the model modelRef = progSpec.findSpecOf(classes[0], className, 'model') if modelRef==None: cdErr('To build a GUI for a list of "'+className+'" a model is needed but is not found.') currentModelSpec = modelRef rowHeaderCode = '' rowViewCode = '' for field in modelRef['fields']: fieldName = field['fieldName'] typeSpec = field['typeSpec'] fldCat = progSpec.fieldsTypeCategory(typeSpec) fieldType = progSpec.fieldTypeKeyword(field['typeSpec']['fieldType']) [fieldSpec, params] = getFieldSpec(fldCat, field) structTypeName ='' if fldCat=='struct': # Add a new class to be processed structTypeName =typeSpec['fieldType'][0] newGUIStyle = 'Dialog' guiStructName = structTypeName+'_'+newGUIStyle+'_GUI' addNewStructToProcess(guiStructName, structTypeName, 'struct', 'Dialog') if progSpec.isAContainer(typeSpec):# Add a new list to be processed structTypeName = typeSpec['fieldType'][0] guiStructName = structTypeName+'_LIST_View' addNewStructToProcess(guiStructName, structTypeName, 'list', 'Dialog') CODE = '''struct <NEWSTRUCTNAME>{ our <CLASSNAME>[our list]: <CLASSNAME>_ListData our <CLASSNAME>: crntRecord } ''' CODE = CODE.replace('<NEWSTRUCTNAME>', newStructName) CODE = CODE.replace('<CLASSNAME>', className) CODE = CODE.replace('<NEWWIDGETFIELDS>', newWidgetFields) CODE = CODE.replace('<WIDGETFROMVARSCODE>', widgetFromVarsCode) CODE = CODE.replace('<VARSFROMWIDGETCODE>', varsFromWidgetCode) #print '==========================================================\n'+CODE codeDogParser.AddToObjectFromText(classes[0], classes[1], CODE, newStructName)
def findModelRef(classes, structTypeName): modelRef = progSpec.findSpecOf(classes, structTypeName, 'model') if modelRef == None: cdErr('To build a list GUI for list of "' + structTypeName + '" a model is needed but is not found.') return modelRef