def processField(self, fieldName, field, fldCat):
     S = ""
     itemName = '_' + fieldName + '_item'
     if fldCat == 'func': return ''
     typeSpec = field['typeSpec']
     if progSpec.isAContainer(typeSpec):
         if (progSpec.getDatastructID(typeSpec) == "list"):
             innerFieldType = progSpec.getFieldType(typeSpec)
             #print "ARRAYSPEC:",innerFieldType, field
             fldCatInner = progSpec.innerTypeCategory(innerFieldType)
             itemName = '_' + fieldName + '_item'
             calcdName = fieldName + '["+toString(' + itemName + '_key)+"]'
             S += "    withEach " + itemName + " in " + fieldName + "{\n"
             S += "        " + self.displayTextFieldAction(
                 calcdName, itemName, field, fldCatInner) + "    }\n"
         else:
             cdlog(2, "Map not supported")
     else:
         S += self.displayTextFieldAction(fieldName, fieldName, field,
                                          fldCat)
     if progSpec.typeIsPointer(typeSpec):
         T = "    if(" + fieldName + ' == NULL){SRet_ <- SRet_ + ' + 'indent + dispFieldAsText("' + fieldName + '", 15)+"NULL\\n"}\n'
         T += "    else{\n    " + S + "    }\n"
         S = T
     self.textFuncBody += S
Beispiel #2
0
def writeNonTermParseRule(classes, tags, modelName, fields, SeqOrAlt, nameSuffix, logLvl):
    global nextParseNameID
    nameIn=modelName+nameSuffix

    # Allocate or fetch a rule identifier for each '>' field.

    partIndexes=[]
    for field in fields:
        fname=field['fieldName']
        if fname==None: fname=''
        else: fname='_'+fname
        typeSpec   =field['typeSpec']
        if(field['isNext']==True): # means in the parse there was a '>' symbol, a sequence seperator
            firstItm=progSpec.getFieldType(field['typeSpec'])[0]
            if firstItm=='[' or firstItm=='{': # Handle an ALT or SEQ sub structure
                cdlog(logLvl, "NonTERM: {} = {}".format(fname, firstItm))
                nextParseNameID+=1
                if firstItm=='[':
                    innerSeqOrAlt='parseALT'
                    newNameSuffix = nameSuffix+fname+'_ALT'+str(nextParseNameID)
                else:
                    innerSeqOrAlt='parseSEQ'
                    newNameSuffix = nameSuffix+fname+'_SEQ'+str(nextParseNameID)
                innerFields=field['innerDefs']
                ruleIdxStr = writeNonTermParseRule(classes, tags, modelName, innerFields, innerSeqOrAlt, newNameSuffix, logLvl+1)
                field['parseRule']=ruleIdxStr


                if progSpec.isAContainer(typeSpec):
                    # anything with [] is a container: lists and optionals
                    global rules
                    containerSpec = progSpec.getContainerSpec(typeSpec)
                    idxType=''
                    if 'indexType' in containerSpec:
                        idxType=containerSpec['indexType']
                    if(isinstance(containerSpec['datastructID'], str)):
                        datastructID = containerSpec['datastructID']
                    else:   # it's a parseResult
                        datastructID = containerSpec['datastructID'][0]
                    if idxType[0:4]=='uint': pass
                    if(datastructID=='list'):
                        ruleIdxStr=appendRule(ruleIdxStr+'_REP', "nonterm", "parseREP", [ruleIdxStr, 0, 0])
                    elif datastructID=='opt':
                        ruleIdxStr=appendRule(ruleIdxStr+'_OPT', "nonterm", "parseREP", [ruleIdxStr, 0, 1])
            else:
                ruleIdxStr = fetchOrWriteTerminalParseRule(modelName, field, logLvl)

            partIndexes.append(ruleIdxStr)
        else: pass; # These fields probably have corresponding cofactuals

    nameOut=appendRule(nameIn, "nonterm", SeqOrAlt, partIndexes)
    return nameOut
Beispiel #3
0
def xlateLangType(TypeSpec, owner, fieldType, varMode, actionOrField, xlator):
    # varMode is 'var' or 'arg'.
    if (isinstance(fieldType, basestring)):
        if (fieldType == 'uint8' or fieldType == 'uint16'):
            fieldType = 'uint32'
        elif (fieldType == 'int8' or fieldType == 'int16'):
            fieldType = 'int32'
        langType = convertToJavaType(fieldType)
    else:
        langType = progSpec.flattenObjectName(fieldType[0])
    langType = applyOwner(owner, langType, 'Itr-Error', 'ITR-ERROR',
                          actionOrField, varMode)
    if langType == 'TYPE ERROR': print langType, owner, fieldType
    InnerLangType = langType

    if 'fieldType' in TypeSpec and not (isinstance(
            TypeSpec['fieldType'],
            basestring)) and TypeSpec['fieldType'][0] == 'DblLinkedList':
        print "xlateLangType DblLinkedList"
        return [langType, InnerLangType]

    if progSpec.isAContainer(TypeSpec):
        containerSpec = progSpec.getContainerSpec(TypeSpec)
        if (containerSpec):  # Make list, map, etc
            [containerType, idxType,
             owner] = getContainerType(TypeSpec, actionOrField)
            if 'owner' in containerSpec:
                containerOwner = containerSpec['owner']
            else:
                containerOwner = 'me'
            if idxType == 'int': idxType = "Integer"
            if langType == 'int':
                langType = "Integer"
                InnerLangType = "Integer"
            if idxType == 'long': idxType = "Long"
            if langType == 'long': langType = "Long"
            if idxType == 'timeValue':
                idxType = "Long"  # this is hack and should be removed ASAP
            if containerType == 'ArrayList':
                langType = "ArrayList<" + langType + ">"
            elif containerType == 'TreeMap':
                langType = "TreeMap<" + idxType + ', ' + langType + ">"
            elif containerType == 'multimap':
                langType = "multimap<" + idxType + ', ' + langType + ">"

            if varMode != 'alloc':
                langType = applyOwner(containerOwner, langType, InnerLangType,
                                      idxType, actionOrField, varMode)
    if owner == "const":
        InnerLangType = fieldType
    return [langType, InnerLangType]
Beispiel #4
0
def getFieldSpec(fldCat, field):
    parameters={}
    if fldCat=='mode': fldCat='enum'
    elif fldCat=='double': fldCat='float'

    if fldCat=='enum':
        parameters=field['typeSpec']['enumList']
    elif fldCat=='RANGE':
        parameters={1, 10}

    typeSpec=field['typeSpec']
    if progSpec.isAContainer(typeSpec):
        innerFieldType=typeSpec['fieldType']
        datastructID = progSpec.getDatastructID(typeSpec)
        return [datastructID, innerFieldType]
    else:
        if fldCat=='struct':
            fldCat='struct' #field['typeSpec']['fieldType'][0]
        return [fldCat, parameters]
Beispiel #5
0
 def processField(self, fieldName, field, fldCat):
     S = ""
     if fldCat == 'func': return ''
     typeSpec = field['typeSpec']
     if progSpec.isAContainer(typeSpec):
         innerFieldType = progSpec.getFieldType(typeSpec)
         #print "ARRAYSPEC:",innerFieldType, field
         fldCatInner = progSpec.innerTypeCategory(innerFieldType)
         calcdName = fieldName + '["+toString(_item_key)+"]'
         S += "    withEach _item in " + fieldName + "{\n"
         S += "        " + self.toProteusTextFieldAction(
             calcdName, '_item', field, fldCatInner) + "    }\n"
     else:
         S += "        " + self.toProteusTextFieldAction(
             fieldName, fieldName, field, fldCat)
     if progSpec.typeIsPointer(typeSpec):
         T = "    if(" + fieldName + ' == NULL){S <- S + ' + 'indent, dispFieldAsText("' + fieldName + '", 15)+"NULL\\n")}\n'
         T += "    else{\n    " + S + "    }\n"
         S = T
     self.textFuncBody += S
Beispiel #6
0
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)
Beispiel #7
0
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)
Beispiel #8
0
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)
Beispiel #9
0
def getWidgetHandlingCode(classes, fldCat, fieldName, field, structTypeName, dialogStyle, indent):
    # _Dialog_GUI is editable widget
    global newWidgetFields
    global widgetInitFuncCode
    global widgetFromVarsCode
    global varsFromWidgetCode

    label               = deCamelCase(fieldName)
    [fieldSpec, params] = getFieldSpec(fldCat, field)
    typeName            = fieldSpec+'Widget'
    CasedFieldName      = fieldName[0].upper() + fieldName[1:]
    widgetName          = CasedFieldName + 'Widget'
    fieldType           = field['typeSpec']['fieldType'][0]
    typeSpec            = field['typeSpec']
    widgetBoxName       = widgetName
    localWidgetVarName  = widgetName

    if fieldType=='timeValue':
        typeName              = 'dateWidget'
        widgetBoxName         =  widgetName +'.box'
        makeTypeNameCall      =  "Allocate("+widgetName+"); " + widgetBoxName + ' <- '+ widgetName+'.makeDateWidget("'+label+'")\n'
        widgetFromVarsCode   += "        " + widgetName+ '.setValue(var.'+ fieldName +')\n'
        varsFromWidgetCode   += "        "+currentClassName+"_data." + fieldName + ' <- ' + widgetName + '.getValue()\n'
    elif fieldSpec=='widget':
        typeName              = CasedFieldName +'Widget'
        widgetName            = fieldName +'Widget'
        widgetBoxName         = fieldName
        localWidgetVarName    = fieldName
        newWidgetFields      += '    their GUI_item' + ': ' + fieldName + '\n'
        makeTypeNameCall      = widgetName+" <- Data." + fieldName + "\n" + fieldName + '<- '+widgetName+".init()\n"
    elif fieldSpec=='struct':
        typeName              = 'GUI_Frame'
        guiStructName         = structTypeName + '_Dialog_GUI'
        guiMgrName            = fieldType + '_GUI_Mgr'
        if progSpec.typeIsPointer(typeSpec): widgetInitFuncCode += '        Allocate('+currentClassName+'_data.'+fieldName+')\n'
        widgetInitFuncCode   += '        Allocate('+guiMgrName+')\n'
        makeTypeNameCall      = widgetName+' <- '+guiMgrName+'.make'+structTypeName+'Widget('+currentClassName+'_data.'+fieldName+')\n'
        newWidgetFields      += '    our ' + guiStructName + ': '+ guiMgrName+'\n'
        widgetFromVarsCode   += '        ' + guiMgrName+ '.setValue(var.'+fieldName+')\n'
        varsFromWidgetCode   += '        ' + guiMgrName + '.getValue()\n'
    elif fieldSpec=='enum':
        typeName = 'enumWidget'
        EnumItems=[]
        for enumItem in params: EnumItems.append('"'+deCamelCase(enumItem)+'"')
        optionString          = '[' + ', '.join(EnumItems) + ']'
        widgetBoxName         =  widgetName +'.box'
        makeTypeNameCall      = "Allocate("+widgetName+"); " + widgetBoxName+' <- '+ widgetName+'.makeEnumWidget("'+label+'", '+optionString+')\n'
        widgetFromVarsCode   += '        ' + widgetName+ '.setValue(var.'+ fieldName +')\n'
        varsFromWidgetCode   += '        '+currentClassName+"_data." + fieldName + ' <- ' + widgetName + '.getValue()\n'
    elif fieldSpec=='string':
        widgetBoxName         =  widgetName +'.box'
        makeTypeNameCall      = "Allocate("+widgetName+"); " + widgetBoxName + ' <- '+ widgetName+'.makeStringWidget("'+label+'")\n'
        widgetFromVarsCode   += '        ' + widgetName+ '.setValue(var.'+ fieldName +')\n'
        varsFromWidgetCode   += '        ' +currentClassName+"_data." + fieldName + ' <- ' + widgetName + '.getValue()\n'
    elif fieldSpec=='int':
        widgetBoxName         =  widgetName +'.box'
        makeTypeNameCall      =  "Allocate("+widgetName+"); " + widgetBoxName + ' <- '+ widgetName+'.makeIntWidget("'+label+'")\n'
        widgetFromVarsCode   += "        " + widgetName+ '.setValue(var.'+ fieldName +')\n'
        varsFromWidgetCode   += "        "+currentClassName+"_data." + fieldName + ' <- ' + widgetName + '.getValue()\n'
    elif fieldSpec=='bool':
        widgetBoxName         =  widgetName +'.box'
        makeTypeNameCall      =  "Allocate("+widgetName+"); " + widgetBoxName + ' <- '+ widgetName+'.makeBoolWidget("'+label+'")\n'
        widgetFromVarsCode   += '        ' + widgetName+ '.setValue(var.'+ fieldName +')\n'
        varsFromWidgetCode   += '        ' + currentClassName+"_data." + fieldName + ' <- ' + widgetName + '.getValue()\n'
    elif fieldSpec=='list' or fieldSpec=='map': pass
    else: print"pattern_MakeGUI.getWidgetHandlingCode fieldSpec not specified: ", fieldSpec;  exit(2)

    # If this is a list or map, populate it
    if progSpec.isAContainer(typeSpec):
        makeTypeNameCall      =  widgetName+' <- make'+typeName[0].upper() + typeName[1:]+'("'+label+'")\n'
        innerFieldType        = typeSpec['fieldType']
        fldCatInner           = progSpec.innerTypeCategory(innerFieldType)

        # If it hasn't already been added, make a struct <ItemType>_ListWidgetManager:ListWidgetManager{}
        listManagerStructName = structTypeName+'_ListWidgetManager'
        codeListWidgetManagerClassOverride(classes, listManagerStructName, structTypeName)

        listWidMgrName        = widgetName+'_LEWM'
        newWidgetFields      += '    me '+listManagerStructName+': '+listWidMgrName+'\n'

        widgetListEditorName  = widgetName+'_Editor'
        localWidgetVarName    = widgetListEditorName
        if progSpec.typeIsPointer(typeSpec): widgetInitFuncCode += '        Allocate('+currentClassName+'_data.'+fieldName+')\n'
        widgetInitFuncCode   += '        their GUI_item: '+widgetListEditorName+' <- '+listWidMgrName+'.initWidget('+currentClassName+'_data.'+fieldName+')\n'
        widgetInitFuncCode   += '        addToContainer(box, '+widgetListEditorName+')\n'
        widgetFromVarsCode   += "        " + listWidMgrName + '.setValue(var.'+ fieldName +')\n'
#        varsFromWidgetCode   += "        " + listWidMgrName + ' <- ' + widgetName + '.getValue()\n'
    else: # Not an ArraySpec:
        newWidgetFields      += '    our '+typeName+': '+widgetName+'\n'
        widgetInitFuncCode   += '        '+makeTypeNameCall
        widgetInitFuncCode   += '        addToContainer(box, '+widgetBoxName+')\n'
    if dialogStyle == 'TabbedStack':
        widgetInitFuncCode+='             '+'gtk_notebook_set_tab_label_text(GTK_NOTEBOOK(box), '+ localWidgetVarName+', "'+label+'")\n'
    def getDashDeclAndUpdateCode(self, owner, fieldLabel, fieldRef, fieldName,
                                 field, skipFlags, indent):
        global classesToProcess
        global classesEncoded
        itemName = '_' + fieldName + '_item'
        dashKeyName = '_' + fieldName + '_dash_key'
        OldElementsName = '_' + fieldName + 'OldElements'
        [
            structText, updateFuncText, setPosFuncText, drawFuncText,
            handleClicksFuncText
        ] = ['', '', '', '', '']
        typeSpec = field['typeSpec']
        fldCat = progSpec.fieldsTypeCategory(typeSpec)
        if fldCat == 'func': return ['', '', '', '', '']
        if progSpec.typeIsPointer(
                typeSpec) and skipFlags != 'skipPtr':  # Header for a POINTER
            fieldName += 'Ptr'
            if fieldRef == 'data.itmItr':
                innerUpdateFuncStr = '"ItmItr"'  # TODO: unhard code this reference to itmItr
            else:
                innerUpdateFuncStr = fieldRef + '.mySymbol(' + fieldRef + ')'
            updateFuncText += '        ' + fieldName + '.dashParent <- self\n'
            updateFuncText += "        " + fieldName + '.update(' + fieldLabel + ', ' + innerUpdateFuncStr + ', isNull(' + innerUpdateFuncStr + '))\n'
            structText += "    " + owner + " ptrToItem: " + fieldName + "\n"

        elif progSpec.isAContainer(
                typeSpec
        ) and skipFlags != 'skipLists':  # Header and items for LIST
            dispStructTypeName = "display_" + progSpec.getFieldType(
                field['typeSpec'])[0]
            innerUpdateFuncStr = '"Size:"+toString(data.' + fieldName + '.size())'
            updateFuncText += "        " + fieldName + '.dashParent <- self\n'
            updateFuncText += '        ' + 'our dash[our list]: ' + OldElementsName + ' <- ' + fieldName + '.elements\n'
            updateFuncText += "        " + fieldName + '.update(' + fieldLabel + ', ' + innerUpdateFuncStr + ', isNull(' + innerUpdateFuncStr + '), true)\n'
            ## Now push each item
            innerFieldType = progSpec.getFieldType(typeSpec)
            containerTypeSpec = progSpec.getContainerSpec(typeSpec)
            if len(containerTypeSpec) > 3 and (
                    containerTypeSpec[1] == 'map' or containerTypeSpec[1]
                    == 'multimap') and containerTypeSpec[2][0] == 'string':
                itemKeyCode = itemName + '_key'
            else:
                itemKeyCode = 'toString(' + itemName + '_key)'
            fldCatInner = progSpec.innerTypeCategory(innerFieldType)
            if fieldRef == 'data.itmItr' or fieldRef == 'data.items':
                newFieldRef = itemName + ''  # TODO: unhard code this reference to itmItr
            else:
                newFieldRef = 'data.' + fieldName + '[' + itemName + '_key]'
            newFieldLabel = '"["+' + itemKeyCode + '+"]  "+ ' + itemName + '.mySymbol(' + itemName + ')'
            updateFuncText += '\n        ' + 'me int64: ' + dashKeyName + ' <- 0'
            updateFuncText += "\n        withEach " + itemName + " in data." + fieldName + "{\n"
            [
                innerStructText, innerUpdateFuncText, innerDrawFuncText,
                innerSetPosFuncText, innerHandleClicksFuncText
            ] = self.getDashDeclAndUpdateCode('our', newFieldLabel,
                                              newFieldRef, 'newItem', field,
                                              'skipLists', '        ')
            updateFuncText += '            ' + innerStructText
            updateFuncText += '            me bool: _elementExists <- false\n'
            updateFuncText += '            ' + 'if(' + OldElementsName + '!=NULL){\n'
            updateFuncText += '                ' + 'withEach _ElItem in ' + OldElementsName + '{\n'
            updateFuncText += '                    ' + 'if(asClass(' + dispStructTypeName + ', _ElItem).data === ' + itemName + '){\n'
            updateFuncText += '                        ' + '_elementExists <- true; break();\n'

            updateFuncText += '            ' + '}}}\n'
            updateFuncText += '            ' + 'if(!_elementExists){\n'
            updateFuncText += '                Allocate(newItem)\n'
            updateFuncText += '                newItem.dashParent <- self\n'
            updateFuncText += '               ' + 'addDependent(' + itemName + '.mySymbol(' + itemName + '), newItem)'
            updateFuncText += '\n            } else {\n               newItem <- asClass(' + dispStructTypeName + ', ' + OldElementsName + '[' + dashKeyName + '])\n            ' + dashKeyName + ' <- ' + dashKeyName + ' + 1'
            updateFuncText += '\n            }'
            updateFuncText += '\n            ' + innerUpdateFuncText
            updateFuncText += '            ' + fieldName + '.updatePush(newItem)'
            updateFuncText += '\n        }\n'
            structText += '    ' + owner + ' listOfItems: ' + fieldName + '\n'
        elif (fldCat == 'struct'):  # Header for a STRUCT
            updateFuncText += "        " + fieldName + '.dashParent <- self\n'
            updateFuncText += "        " + fieldName + '.update(' + fieldLabel + ', ">", ' + fieldRef + ')\n'
            structTypeName = progSpec.getNewContainerFirstElementTypeTempFunc(
                typeSpec)
            if structTypeName == None:
                structTypeName = progSpec.getFieldType(typeSpec)[0]
            structText += "    " + owner + " display_" + structTypeName + ': ' + fieldName + "\n"

            # Add new classname to a list so it can be encoded.
            if not (structTypeName in classesToProcess):
                classesToProcess.append(structTypeName)

        else:  # Display field for a BASIC TYPES
            valStr = ''
            if (fldCat == 'int' or fldCat == 'double'):
                valStr = 'toString(data.' + fieldName + ')'
            elif (fldCat == 'string' or fldCat == 'char'):
                valStr = '"\'"+' + 'data.' + fieldName + '+"\'"'
            elif (fldCat == 'flag' or fldCat == 'bool'):
                valStr = 'toString((data.' + fieldName + ')!=0)'
            elif (fldCat == 'mode'):
                valStr = fieldRef + 'Strings[data.' + fieldName + '] '

            updateFuncText = "        " + fieldName + '.update(100, 180, ' + fieldLabel + ', ' + valStr + ', isNull(' + valStr + '))\n'
            structText += "    " + owner + " dataField: " + fieldName + "\n"

        drawFuncText = "        " + fieldName + '.draw(cr)\n'
        setPosFuncText += '''        if(!<fieldName>.isNullLike or displayMode==fullDisplay){
                <fieldName>.setPos(x,y,extC)
                extC <- <fieldName>.extC
                y <- y + <fieldName>.height
                extX <- max(extX, <fieldName>.extX)
                extY <- max(extY, <fieldName>.extY)
                width<- max(width, <fieldName>.width)
                <fieldName>.isHidden<-false
            } else {<fieldName>.isHidden<-true}
    '''.replace('<fieldName>', fieldName)
        #  updateFuncText+='        if(crntWidth<'+fieldName+'.width){crntWidth <- '+fieldName+'.width}'
        handleClicksFuncText = '            ' + fieldName + '.primaryClick(event)'
        return [
            structText, updateFuncText, drawFuncText, setPosFuncText,
            handleClicksFuncText
        ]
Beispiel #11
0
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 setValue()
    #   It adds a set Vars from Widget function      // varsFromWidgetCode: Func getValue()
    #   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
    global clearWidgetCode

    newWidgetFields = ''
    widgetInitFuncCode = ''
    widgetFromVarsCode = ''
    varsFromWidgetCode = ''
    clearWidgetCode = ''
    containerWidget = ''
    boxFooterCode = ''
    scrollerCode = ''
    onLoadedCode = ''
    tagCode = ''
    makeBoxFooter = False
    makeBackBtn = False
    makeNextBtn = False
    makeVScroller = False

    # Find the model
    modelRef = findModelRef(classes[0], className)
    currentModelSpec = modelRef
    classPrimaryGuiItem = progSpec.searchATagStore(modelRef['tags'],
                                                   'primaryGuiItem')
    if classPrimaryGuiItem != None:  # This GUI Item is important visually
        classPrimaryGuiItem = classPrimaryGuiItem[0]
    classOptionsTags = progSpec.searchATagStore(modelRef['tags'],
                                                'classOptions')
    guiStyleTag = progSpec.searchATagStore(modelRef['tags'], 'dialogStyle')
    if guiStyleTag != None:  # This GUI Item is important visually
        guiStyleTag = guiStyleTag[0]
        if guiStyleTag == 'WizardStack': dialogStyle = 'WizardStack'
        if guiStyleTag == 'Z_stack': dialogStyle = 'Z_stack'
        if guiStyleTag == 'WizardChild':
            dialogStyle = 'WizardChild'
            makeBoxFooter = True
            makeBackBtn = True
            makeNextBtn = True
            clickNextLabel = "Next"
        if guiStyleTag == 'WizardChildLast':
            dialogStyle = 'WizardChild'
            makeBoxFooter = True
            makeBackBtn = True
            makeNextBtn = True
            clickNextLabel = "Done"
        if guiStyleTag == 'WizardChildFirst':
            dialogStyle = 'WizardChild'
            makeBoxFooter = True
            makeNextBtn = True
            clickNextLabel = "Next"
    classProperties = progSpec.searchATagStore(modelRef['tags'], 'properties')
    if classProperties != None:
        for classProperty in classProperties:
            if classProperty[0] == 'vScroller': makeVScroller = True
    ### Write code for each field
    for field in modelRef['fields']:
        typeSpec = field['typeSpec']
        fldCat = progSpec.fieldsTypeCategory(typeSpec)
        fieldName = field['fieldName']
        labelText = deCamelCase(fieldName)
        fieldType = typeSpec['fieldType']
        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
            if not isinstance(fieldType, str): fieldType = fieldType[0]
            structTypeName = fieldType
            guiStructName = structTypeName + '_ROW_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,
                                  classPrimaryGuiItem, classOptionsTags, '')

    onLoadedCode = 'onLoaded()\n'
    returnCode = '        return(box)'
    if dialogStyle == 'Z_stack':
        newWidgetFields += '    their GUI_ZStack: Zbox\n'
        newWidgetFields += '    me List<me string>: children\n'
        newWidgetFields += '    me int: activeScreenIdx <-1\n'
        newWidgetFields += '    void: setActiveChild(me int: N) <- {\n'
        newWidgetFields += '        if (N >= 0 and N < children.size()){'
        newWidgetFields += '            me string: childName <- children[N]\n'
        #newWidgetFields   += '            print("^^^setZStackActive: ",N)\n'
        newWidgetFields += '            setZStackActive(Zbox, childName)\n'
        newWidgetFields += '            activeScreenIdx <- N\n'
        newWidgetFields += '        }\n'
        newWidgetFields += '    }\n'
        containerWidget = 'Zbox <- makeZStack("' + className + '")\n'
        onLoadedCode = 'setActiveChild(0)\n'
        onLoadedCode += '        onLoaded()\n'
        returnCode = '        return(Zbox)\n'
    elif dialogStyle == 'TabbedStack':
        containerWidget = 'their GUI_Frame:box <- makeTabbedWidget("makeTabbedWidget")'
    elif dialogStyle == 'WizardStack':
        newWidgetFields += '    our wizardWidget: wiz\n'
        newWidgetFields += '    their GUI_Frame: box\n'
        newWidgetFields += '''    void: clickNext() <-{
            me int: size <- wiz.children.size()
            if (wiz.activeScreenIdx == size-1){
                _data.wizardFinished(wiz.widgetID)
            }
            else if (wiz.activeScreenIdx < size-1){
                wiz.activeScreenIdx <- wiz.activeScreenIdx+1
                wiz.setActiveChild(wiz.activeScreenIdx)
            }
        }\n'''
        newWidgetFields += '''    void: clickBack() <-{
            me int: size <- wiz.children.size()
            if (wiz.activeScreenIdx > 0){wiz.activeScreenIdx <- wiz.activeScreenIdx-1}
            wiz.setActiveChild(wiz.activeScreenIdx)
        }\n'''
        containerWidget = 'Allocate(wiz)\n'
        containerWidget += '        box <- wiz.initWidget("' + currentClassName + '")\n'
        containerWidget += '        wiz._data <- _data\n'
        containerWidget += '        wiz.parentGuiMgr <- self\n'
        widgetInitFuncCode += '        wiz.activeScreenIdx <- 0\n'
        widgetInitFuncCode += '        wiz.setActiveChild(wiz.activeScreenIdx)\n'
    elif dialogStyle == 'X_stack':
        newWidgetFields += '    their GUI_XStack:box\n'
        containerWidget = 'box <- makeXStack("")'
    elif dialogStyle == 'rowWidget':
        newWidgetFields += '    their GUI_XStack: box\n'
        containerWidget = 'box <- makeXStack("")'
    else:
        newWidgetFields += '    their GUI_Frame:box\n'
        containerWidget = 'box <- makeYStack("")'
    if makeBoxFooter:
        newWidgetFields += '    their GUI_Frame:  boxFooter\n'
        boxFooterCode += 'boxFooter       <- makeXStack("")\n'
        if makeBackBtn:
            newWidgetFields += '    their GUI_button: backBtn\n'
            newWidgetFields += '    void: clickBack() <-{parentGuiMgr.clickBack()}\n'
            boxFooterCode += '        backBtn         <- makeButtonWidget("Back")\n'
            boxFooterCode += '        GUI.setBtnCallback(backBtn, "clicked", clickBack, this)\n'
            boxFooterCode += '        addToContainer(boxFooter, backBtn)\n'
            tagCode += ''
        if makeNextBtn:
            newWidgetFields += '    their GUI_button: nextBtn\n'
            newWidgetFields += '''    void: clickNext() <-{
                if(isComplete()){
                    save()
                    parentGuiMgr.clickNext()
                }
            }\n'''
            newWidgetFields += '''    void: setNextBtnActive(me bool: checkState) <-{
                nextBtn.setWidgetActive(checkState)
            }\n'''
            newWidgetFields += '''    void: onChanged() <- {
                getValue()
                setNextBtnActive(isComplete())
            }\n'''
            boxFooterCode += '        nextBtn         <- makeButtonWidget("' + clickNextLabel + '")\n'
            boxFooterCode += '        nextBtn.setWidgetActive(false)\n'
            boxFooterCode += '        GUI.setBtnCallback(nextBtn, "clicked", clickNext, this)\n'
            boxFooterCode += '        addToContainer(boxFooter, nextBtn)\n'
            tagCode += ''
        boxFooterCode += '        addToContainer(box, boxFooter)\n'
    if makeVScroller:
        scrollerCode = 'their GUI_VerticalScroller: scroller <- makeVerticalScroller()\n'
        scrollerCode += 'addToContainerAndExpand(scroller, box)\n'
        returnCode = 'return (scroller)'

    CODE =  '''
struct <CLASSNAME>:inherits=appComponentData{}
struct <NEWSTRUCTNAME>:inherits=appComponentGUI '''+tagCode+'''{
    '''+newWidgetFields+'''
    our <CLASSNAME>: _data
    their GUI_Frame: initWidget(our <CLASSNAME>: Data) <- {
        _data <- Data
        _data.guiMgr <- self
        '''+containerWidget+'''
        '''+widgetInitFuncCode+'''
        '''+boxFooterCode+'''
        '''+scrollerCode+'''
        '''+onLoadedCode+'''
        '''+returnCode+'''
    }
    void: setValue(our <CLASSNAME>: var) <- {
        '''+widgetFromVarsCode+'''
    }
    void: getValue() <- {
        '''+varsFromWidgetCode+'''
    }
    void: clear() <- {
        '''+clearWidgetCode+'''
    }
}\n'''  # TODO: add <VARSFROMWIDGETCODE>

    CODE = CODE.replace('<NEWSTRUCTNAME>', newStructName)
    CODE = CODE.replace('<CLASSNAME>', className)
    #print ('==========================================================\n'+CODE)
    codeDogParser.AddToObjectFromText(classes[0], classes[1], CODE,
                                      newStructName)
Beispiel #12
0
def buildListRowView(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
    global clearWidgetCode

    newWidgetFields = ''
    widgetInitFuncCode = ''
    widgetFromVarsCode = ''
    varsFromWidgetCode = ''
    clearWidgetCode = ''
    funcTextToUpdateViewWidget = ''
    funcTextToUpdateEditWidget = ''
    funcTextToUpdateCrntFromWidget = ''

    # Find the model
    modelRef = findModelRef(classes[0], className)
    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 + '_ROW_View'
            addNewStructToProcess(guiStructName, structTypeName, 'list',
                                  'Dialog')
        else:
            print("field::", fieldName, fldCat)
            if (fldCat != 'struct'):
                rowHeaderCode += '        their GUI_Label: ' + fieldName + '_header <- makeLabelWidget("' + fieldName + '")\n'
                rowHeaderCode += '        setLabelWidth(' + fieldName + '_header, 15)\n'
                rowHeaderCode += '        addToContainer(headerBox, ' + fieldName + '_header)\n'
            if fldCat == 'struct':
                funcTextToUpdateViewWidget += ''
            elif fldCat == 'enum' or fldCat == 'mode':
                funcTextToUpdateViewWidget += ''
                #funcTextToUpdateEditWidget     += ''
                funcTextToUpdateCrntFromWidget += ''  #  crntRecord.'+fieldName+' <- dialog.' + widgetName + '.getValue()\n'
            elif fldCat == 'bool':
                funcTextToUpdateViewWidget += ''
            elif fldCat == 'string':
                #funcTextToUpdateViewWidget     += ''
                #funcTextToUpdateEditWidget     += '    dialog.' + widgetName + '.setValue('+structTypeName+'_ListData[N].'+fieldName+')\n'
                #funcTextToUpdateCrntFromWidget += '    me string: '+widgetName+'Str <- dialog.' + widgetName + '.getValue()\n'
                #funcTextToUpdateCrntFromWidget += '    crntRecord.'+fieldName+' <- '+widgetName+'Str\n'
                rowViewCode += '        their GUI_Label: ' + fieldName + '_value <- makeLabelWidget2(Data.' + fieldName + ')\n'
                rowViewCode += '        setLabelWidth(' + fieldName + '_value, 15)\n'
                rowViewCode += '        addToContainer(box, ' + 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_Label: ' + fieldName + '_value <- makeLabelWidget2(toString(Data.' + fieldName + '))\n'
                rowViewCode += '        setLabelWidth(' + fieldName + '_value, 15)\n'
                rowViewCode += '        addToContainer(box, ' + fieldName + '_value)\n'
                rowViewCode += '        showWidget(' + fieldName + '_value)\n'
            else:
                print(
                    'pattern_MakeGUI.codeListWidgetManagerClassOverride fldCat not specified: ',
                    fldCat)
                exit(2)

    CODE = '''struct ''' + newStructName + '''{
    their GUI_Frame:            box
    their GUI_Frame: makeHeaderView() <- {
        their GUI_Frame: headerBox <- makeXStack("")
        ''' + rowHeaderCode + '''
        showWidget(headerBox)
        return(headerBox)
    }
    their GUI_Frame: initWidget(their ''' + className + ''': Data) <- {
        box <- makeXStack("")
        ''' + rowViewCode + '''
        showWidget(box)
        return(box)
    }
}
'''
    #print ('==========================================================\n'+CODE)
    codeDogParser.AddToObjectFromText(classes[0], classes[1], CODE,
                                      newStructName)
Beispiel #13
0
def getWidgetHandlingCode(classes, fldCat, fieldName, field, structTypeName,
                          dialogStyle, classPrimaryGuiItem, classOptionsTags,
                          indent):
    # _Dialog_GUI is editable widget
    global newWidgetFields
    global widgetInitFuncCode
    global widgetFromVarsCode
    global varsFromWidgetCode
    global clearWidgetCode

    label = deCamelCase(fieldName)
    [fieldSpec, params] = getFieldSpec(fldCat, field)
    typeName = fieldSpec + 'Widget'
    CasedFieldName = fieldName[0].upper() + fieldName[1:]
    widgetName = CasedFieldName + 'Widget'
    typeSpec = field['typeSpec']
    innerFieldType = typeSpec['fieldType']
    fieldType = innerFieldType[0]
    widgetBoxName = widgetName
    localWidgetVarName = widgetName
    makeTypeNameCall = ''

    if fieldType == 'timeValue':
        typeName = 'dateWidget'
        widgetBoxName = widgetName + '.box'
        makeTypeNameCall = 'Allocate(' + widgetName + ');\n' + widgetBoxName + ' <- ' + widgetName + '.initWidget("' + label + '")\n'
        makeTypeNameCall += '        ' + widgetName + '.parentGuiMgr <- self\n'
        widgetFromVarsCode += '        ' + widgetName + '.setValue(var.' + fieldName + ')\n'
        varsFromWidgetCode += '        _data.' + fieldName + ' <- ' + widgetName + '.getValue()\n'
        clearWidgetCode += '        ' + widgetName + '.clear()\n'
    elif fieldType == 'Agreement':
        typeName = 'AgreeWidget'
        widgetBoxName = widgetName + '.box'
        makeTypeNameCall = 'Allocate(' + widgetName + ')\n'
        makeTypeNameCall += '        ' + widgetBoxName + ' <- ' + widgetName + '.initWidget("' + fieldName + '")\n'
        makeTypeNameCall += '        ' + widgetName + '.parentGuiMgr <- self\n'
        widgetFromVarsCode += ''
        varsFromWidgetCode += ''
    elif fieldType == 'DateValue':
        typeName = 'DateWidget'
        widgetBoxName = widgetName + '.box'
        makeTypeNameCall = 'Allocate(' + widgetName + ')\n'
        makeTypeNameCall += '        ' + widgetBoxName + ' <- ' + widgetName + '.initCrnt("' + label + '")\n'
        makeTypeNameCall += '        ' + widgetName + '.parentGuiMgr <- self\n'
        widgetFromVarsCode += ''
        varsFromWidgetCode += '        ' + widgetName + '.getValue()\n'
        clearWidgetCode += '        ' + widgetName + '.clear()\n'
    elif fieldType == 'timeOfDay':
        typeName = 'TimeWidget'
        widgetBoxName = widgetName + '.box'
        makeTypeNameCall = 'Allocate(' + widgetName + ')\n'
        makeTypeNameCall += '        ' + widgetBoxName + ' <- ' + widgetName + '.initCrnt("' + label + '")\n'
        makeTypeNameCall += '        ' + widgetName + '.parentGuiMgr <- self\n'
        widgetFromVarsCode += ''
        varsFromWidgetCode += '        ' + widgetName + '.getValue()\n'
        clearWidgetCode += '        ' + widgetName + '.clear()\n'
    elif fieldType == 'DateTime':
        typeName = 'DateTimeWidget'
        widgetBoxName = widgetName + '.box'
        makeTypeNameCall = 'Allocate(' + widgetName + ')\n'
        makeTypeNameCall += '        ' + widgetBoxName + ' <- ' + widgetName + '.initCrnt("' + label + '")\n'
        makeTypeNameCall += '        ' + widgetName + '.parentGuiMgr <- self\n'
        widgetFromVarsCode += ''
        varsFromWidgetCode += '        ' + widgetName + '.getValue()\n'
        clearWidgetCode += '        ' + widgetName + '.clear()\n'
    elif fieldType == 'FoodData':
        typeName = 'FoodDataWidget'
        widgetBoxName = widgetName + '.box'
        makeTypeNameCall = 'Allocate(' + widgetName + ')\n'
        makeTypeNameCall += '        ' + widgetBoxName + ' <- ' + widgetName + '.initWidget("' + label + '", _data.' + fieldName + ')\n'
        #widgetFromVarsCode   += '        '+widgetName+'.setValue(var.'+ fieldName +')\n'
        #varsFromWidgetCode   += '        '+widgetName+'.getValue()\n'
    elif fieldType == 'MedItemData':
        typeName = 'MedItemDataWidget'
        widgetBoxName = widgetName + '.box'
        makeTypeNameCall = 'Allocate(' + widgetName + ')\n'
        makeTypeNameCall += '        ' + widgetBoxName + ' <- ' + widgetName + '.initWidget("' + label + '", _data.' + fieldName + ')\n'
        #widgetFromVarsCode   += '        '+widgetName+'.setValue(var.'+ fieldName +')\n'
        #varsFromWidgetCode   += '        '+widgetName+'.getValue()\n'
    elif fieldType == 'MedData':
        typeName = 'MedBunchDataWidget'
        widgetBoxName = widgetName + '.box'
        makeTypeNameCall = 'Allocate(' + widgetName + ')\n'
        makeTypeNameCall += 'Allocate(_data.' + fieldName + ')\n'
        makeTypeNameCall += '        ' + widgetBoxName + ' <- ' + widgetName + '.initWidget("' + label + '", _data.' + fieldName + ')\n'
        #widgetFromVarsCode   += '        '+widgetName+'.setValue(var.'+ fieldName +')\n'
        varsFromWidgetCode += '        ' + widgetName + '.getValue()\n'
        clearWidgetCode += '        ' + widgetName + '.clear()\n'
    elif fieldType == 'matterTerm':
        typeName = 'MatterTermWidget'
        widgetBoxName = widgetName + '.box'
        makeTypeNameCall = 'Allocate(' + widgetName + ')\n'
        makeTypeNameCall += '        ' + widgetBoxName + ' <- ' + widgetName + '.initWidget("' + label + '", _data.' + fieldName + ')\n'
        makeTypeNameCall += '        ' + widgetName + '.parentGuiMgr <- self\n'
        widgetFromVarsCode += '        ' + widgetName + '.setValue(var.' + fieldName + ')\n'
        varsFromWidgetCode += '        ' + widgetName + '.getValue()\n'
        clearWidgetCode += '        ' + widgetName + '.clear()\n'
    elif fieldSpec == 'widget':
        typeName = fieldType
        localWidgetVarName = fieldName
        if fieldType == 'graphWidget':
            widgetName = fieldName + 'Widget'
            widgetBoxName = fieldName
            newWidgetFields += '    their GUI_item' + ': ' + fieldName + '\n'
            makeTypeNameCall = widgetName + ' <- Data.' + fieldName + '\n' + fieldName + '<- ' + widgetName + '.init("' + label + '")\n'
        else:
            widgetBoxName = widgetName + '.box'
            dataType = changeDataFieldType(classes, structTypeName, typeSpec)
            makeTypeNameCall = 'Allocate(' + widgetName + ')\n'
            makeTypeNameCall += '        ' + widgetBoxName + ' <- ' + widgetName + '.initWidget("' + label + '")\n'
            makeTypeNameCall += '        ' + widgetName + '.parentGuiMgr <- self\n'
    elif fieldSpec == 'struct':
        typeName = 'GUI_Frame'
        guiStructName = structTypeName + '_Dialog_GUI'
        guiMgrName = fieldType + '_GUI_Mgr'
        if progSpec.typeIsPointer(typeSpec):
            widgetInitFuncCode += '        Allocate(_data.' + fieldName + ')\n'
        widgetInitFuncCode += 'Allocate(' + guiMgrName + ')\n'
        makeTypeNameCall = widgetName + ' <- ' + guiMgrName + '.initWidget(_data.' + fieldName + ')\n'
        makeTypeNameCall += '        ' + guiMgrName + '.parentGuiMgr <- self\n'
        newWidgetFields += '    our ' + guiStructName + ': ' + guiMgrName + '\n'
        widgetFromVarsCode += '        ' + guiMgrName + '.setValue(var.' + fieldName + ')\n'
        varsFromWidgetCode += '        ' + guiMgrName + '.getValue()\n'
        clearWidgetCode += '        ' + guiMgrName + '.clear()\n'
        makeTypeNameCall += '        ' + guiMgrName + '.load()\n'
    elif fieldSpec == 'enum':
        typeName = 'enumWidget'
        EnumItems = []
        for enumItem in params:
            EnumItems.append('"' + deCamelCase(enumItem) + '"')
        optionString = '[' + ', '.join(EnumItems) + ']'
        widgetBoxName = widgetName + '.box'
        makeTypeNameCall = 'Allocate(' + widgetName + '); ' + widgetBoxName + ' <- ' + widgetName + '.initWidget("' + label + '", ' + optionString + ')\n'
        makeTypeNameCall += '        ' + widgetName + '.parentGuiMgr <- self\n'
        widgetFromVarsCode += '        ' + widgetName + '.setValue(var.' + fieldName + ')\n'
        varsFromWidgetCode += '        _data.' + fieldName + ' <- ' + widgetName + '.getValue()\n'
        clearWidgetCode += '        ' + widgetName + '.clear()\n'
    elif fieldSpec == 'string':
        widgetBoxName = widgetName + '.box'
        makeTypeNameCall = 'Allocate(' + widgetName + '); ' + widgetBoxName + ' <- ' + widgetName + '.initWidget("' + label + '")\n'
        makeTypeNameCall += '        ' + widgetName + '.parentGuiMgr <- self\n'
        widgetFromVarsCode += '        ' + widgetName + '.setValue(var.' + fieldName + ')\n'
        varsFromWidgetCode += '        _data.' + fieldName + ' <- ' + widgetName + '.getValue()\n'
        clearWidgetCode += '        ' + widgetName + '.clear()\n'
    elif fieldSpec == 'int':
        widgetBoxName = widgetName + '.box'
        makeTypeNameCall = 'Allocate(' + widgetName + ')\n'
        makeTypeNameCall += '        ' + widgetName + '.parentGuiMgr <- self\n'
        if progSpec.typeIsNumRange(innerFieldType):
            range1 = innerFieldType[0]
            range2 = innerFieldType[2]
            makeTypeNameCall += '        ' + widgetName + '.minValue <- ' + range1 + '\n        ' + widgetName + '.maxValue <- ' + range2 + '\n'
        makeTypeNameCall += '        ' + widgetBoxName + ' <- ' + widgetName + '.initWidget("' + label + '")\n'
        widgetFromVarsCode += '        ' + widgetName + '.setValue(var.' + fieldName + ')\n'
        varsFromWidgetCode += '        _data.' + fieldName + ' <- ' + widgetName + '.getValue()\n'
        clearWidgetCode += '        ' + widgetName + '.clear()\n'
    elif fieldSpec == 'bool':
        widgetBoxName = widgetName + '.box'
        makeTypeNameCall = 'Allocate(' + widgetName + '); ' + widgetBoxName + ' <- ' + widgetName + '.initWidget("' + label + '")\n'
        makeTypeNameCall += '        ' + widgetName + '.parentGuiMgr <- self\n'
        widgetFromVarsCode += '        ' + widgetName + '.setValue(var.' + fieldName + ')\n'
        varsFromWidgetCode += '        _data.' + fieldName + ' <- ' + widgetName + '.getValue()\n'
        clearWidgetCode += '        ' + widgetName + '.clear()\n'
    elif fieldSpec == 'list' or fieldSpec == 'map':
        pass
    else:
        print(
            'pattern_MakeGUI.getWidgetHandlingCode fieldSpec not specified: ',
            fieldSpec)
        exit(2)

    if typeName == 'GUI_Frame': owner = 'their '
    else: owner = 'our '
    # If this is a list or map, populate it
    if progSpec.isAContainer(typeSpec):
        makeTypeNameCall = widgetName + ' <- make' + typeName[0].upper(
        ) + typeName[1:] + '("' + label + '")\n'
        fldCatInner = progSpec.innerTypeCategory(innerFieldType)

        # If it hasn't already been added, make a struct <ItemType>_ListWidgetManager:ListWidgetManager{}
        listManagerStructName = structTypeName + '_ListWidgetManager'
        getListWidgetMgrCode(classes, listManagerStructName, structTypeName,
                             fieldName, classOptionsTags)

        listWidMgrName = 'LEWM'
        newWidgetFields += '    me ' + listManagerStructName + ': ' + listWidMgrName + '\n'

        widgetListEditorName = widgetName + '_Editor'
        localWidgetVarName = widgetListEditorName
        if progSpec.typeIsPointer(typeSpec):
            widgetInitFuncCode += 'Allocate(_data.' + fieldName + ')\n'
        widgetInitFuncCode += '        their GUI_YStack: ' + widgetListEditorName + ' <- ' + listWidMgrName + '.initWidget(_data.' + fieldName + ', "' + label + '")\n'
        if classPrimaryGuiItem == fieldName:
            widgetInitFuncCode += '        addToContainerAndExpand(box, ' + widgetListEditorName + ')\n'
        else:
            widgetInitFuncCode += '        addToContainer(box, ' + widgetListEditorName + ')\n'
        #        widgetFromVarsCode   += '        ' + listWidMgrName + '.setValue(var.'+ fieldName +')\n'
        varsFromWidgetCode += '        ' + listWidMgrName + '.getValue()\n'
        clearWidgetCode += '        ' + listWidMgrName + '.clear()\n'
    elif dialogStyle == 'WizardStack':
        newWidgetFields += '    ' + owner + typeName + ': ' + widgetName + '\n'
        widgetInitFuncCode += '        ' + makeTypeNameCall
        widgetInitFuncCode += '        addToZStack(wiz.ZStack, ' + widgetBoxName + ', "' + CasedFieldName + '")\n'
        widgetInitFuncCode += '        wiz.children.pushLast("' + CasedFieldName + '")\n'
    elif dialogStyle == 'Z_stack':
        widgetBoxName = guiMgrName + '.box'
        newWidgetFields += '    ' + owner + typeName + ': ' + widgetName + '\n'
        widgetInitFuncCode += '        ' + makeTypeNameCall + '\n'
        widgetInitFuncCode += '        addToZStack(Zbox, ' + widgetBoxName + ', "' + CasedFieldName + '")\n'
        widgetInitFuncCode += '        children.pushLast("' + CasedFieldName + '")\n'
    else:  # Not an ArraySpec:
        newWidgetFields += '    ' + owner + typeName + ': ' + widgetName + '\n'
        widgetInitFuncCode += '        ' + makeTypeNameCall
        if classPrimaryGuiItem == fieldName:
            widgetInitFuncCode += '        addToContainerAndExpand(box, ' + widgetBoxName + ')\n'
        else:
            widgetInitFuncCode += '        addToContainerAndExpand(box, ' + widgetBoxName + ')\n'
    if dialogStyle == 'TabbedStack':
        widgetInitFuncCode += '             ' + 'setTabLabelText(box, ' + localWidgetVarName + ', "' + label + '")\n'
Beispiel #14
0
def Write_fieldExtracter(classes, ToStructName, field, memObjFields, VarTagBase, VarName, advancePtr, indent, level, logLvl):
    debugTmp=False # Erase this line
    VarTag=VarTagBase+str(level)
    ###################   G a t h e r   N e e d e d   I n f o r m a t i o n
    global  globalFieldCount
    global  globalTempVarIdx
    S=''
    fieldName  = field['fieldName']
    fieldIsNext= field['isNext']
    fieldValue = field['value']
    typeSpec   = field['typeSpec']
    fieldType  = progSpec.getFieldType(typeSpec)
    fieldOwner =typeSpec['owner']
    fromIsEmbeddedAlt = (not isinstance(fieldType, str) and fieldType[0]=='[')
    fromIsEmbeddedSeq = (not isinstance(fieldType, str) and fieldType[0]=='{')
    fromIsEmbedded    = fromIsEmbeddedAlt or fromIsEmbeddedSeq

    if(fieldIsNext!=True): return '' # This field isn't in the parse stream.

    [memObj, memVersionName]=fetchMemVersion(classes, ToStructName)

    toField = progSpec.fetchFieldByName(memObjFields, fieldName)
    if(toField==None):
        #print "   TOFIELD == None", fieldName
        # Even tho there is no LVAL, we need to move the cursor. Also, there could be a co-factual.
        toFieldType = progSpec.TypeSpecsMinimumBaseType(classes, typeSpec)
        toTypeSpec=typeSpec
        toFieldOwner="me"
    else:
        toTypeSpec   = toField['typeSpec']
        toFieldType  = progSpec.getFieldType(toTypeSpec)
        toFieldOwner = progSpec.getInnerContainerOwner(toTypeSpec)

        if debugTmp:
            print('        toFieldType:', toFieldType)

    LHS_IsPointer=progSpec.typeIsPointer(toTypeSpec)

   # print "        CONVERTING:", fieldName, str(toFieldType)[:100]+'... ', str(typeSpec)[:100]+'... '
   # print "            TOFieldTYPE1:", str(toField)[:100]
   # print "            TOFieldTYPE :", toFieldOwner, toFieldType
   # print "       fieldValue:",ToStructName, fieldType, fieldValue
    cdlog(logLvl, "FIELD {}: '{}'".format(fieldName, str(fieldValue)))

    fields=[]
    fromIsStruct=progSpec.isStruct(fieldType)
    toIsStruct=progSpec.isStruct(toFieldType)
    ToIsEmbedded = toIsStruct and (toFieldType[0]=='[' or toFieldType[0]=='{')
    [fromIsALT, fields] = progSpec.isAltStruct(classes, fieldType)
    fromIsOPT =False
    fromIsList=False
    toIsList  =False
    if progSpec.isAContainer(typeSpec):
        datastructID = progSpec.getDatastructID(typeSpec)
        if datastructID=='opt': fromIsOPT=True;
        else: fromIsList=True

    if progSpec.isAContainer(toTypeSpec):
        if datastructID != 'opt': toIsList=True

    if debugTmp:
        print('        fromIsOPT:', fromIsOPT)
        print('        fromIsList:', fromIsList)
        print('        toIsList:', toIsList)
        print('        fromIsStruct:', fromIsStruct)
        print('        toIsStruct:', toIsStruct)
        print('        fieldType:', fieldType)
        print('        ToIsEmbedded:', ToIsEmbedded)
        print('        ToStructName:', ToStructName)
        print('        memVersionName:', memVersionName, "\n")
    ###################   W r i t e   L V A L   R e f e r e n c e
    finalCodeStr=''
    CodeLVAR_Alloc=''
    CODE_LVAR_v2=''
    if VarName=='' or VarName=='memStruct':  # Default to the target argument name
        #if VarName=='': print "        VARNAME was ''; FIELDNAME:", fieldName
        VarName='memStruct'
        if(fieldName==None): # Field hasn't a name so in memory it's a cofactual or this is a parser marker.
            globalFieldCount+=1
            # We need two versions in case this is set in a function instead of assignment
            CODE_LVAR_v2 = 'S'+str(globalFieldCount)
            CodeLVAR_Alloc='    me string: '+CODE_LVAR_v2
            CODE_LVAR = CodeLVAR_Alloc
            if debugTmp: print('        CODE_LVARS:', CODE_LVAR)
        else:
            CODE_LVAR = VarName+'.'+fieldName
            if fieldName=='inf': CODE_LVAR = VarName
            CODE_LVAR_v2 = CODE_LVAR
    else:
        CODE_LVAR = VarName
        CODE_LVAR_v2 = CODE_LVAR

    ###################   W r i t e   R V A L   C o d e
    CODE_RVAL=''
    objName=''
    humanIDType= VarTag+' ('+str(fieldName)+' / '+str(fieldValue) + ' / '+str(fieldType)[:40] +')'
    humanIDType=humanIDType.replace('"', "'")
    #print humanIDType

    if advancePtr:
        S+=indent+VarTag+' <- getNextStateRec('+VarTag+')\n'
        # UNCOMMENT FOR DEGUG: S+='    docPos('+str(level)+', '+VarTag+', "Get Next in SEQ for: '+humanIDType+'")\n'


    if fieldOwner=='const'and (toField == None):
        #print'CONSTFIELDVALUE("'+fieldValue+'")\n'
        finalCodeStr += indent + 'tmpStr'+' <- makeStr('+VarTag+"<LVL_SUFFIX>"+'.child)\n'

    else:
        if toIsStruct:
            if debugTmp: print('        toFieldType:', toFieldType)
            if not ToIsEmbedded:
                objName=toFieldType[0]
                if  progSpec.typeIsInteger(objName):
                    strFieldType = fieldType[0]
                    if(strFieldType == "BigInt"):
                        CODE_RVAL='makeStr('+VarTag+'.child'+')'
                    elif(strFieldType == "HexNum"):
                        CODE_RVAL='makeHexInt('+VarTag+'.child'+')'
                    elif(strFieldType == "BinNum"):
                        CODE_RVAL='makeBinInt('+VarTag+'.child'+')'
                    else:
                        CODE_RVAL='makeStr('+VarTag+'.child'+')'
                    toIsStruct=False; # false because it is really a base type.
                elif (objName=='ws' or objName=='wsc' or objName=='quotedStr1' or objName=='quotedStr2' or objName=='CID' or objName=='UniID'
                      or objName=='printables' or objName=='toEOL' or objName=='alphaNumSeq'):
                    CODE_RVAL='makeStr('+VarTag+'.child'+')'
                    toIsStruct=False; # false because it is really a base type.
                else:
                    #print "toObjName:", objName, memVersionName, fieldName
                    [toMemObj, toMemVersionName]=fetchMemVersion(classes, objName)
                    if toMemVersionName==None:
                        # make alternate finalCodeStr. Also, write the extractor that extracts toStruct fields to memVersion of this
                        childStr = ".child"
                        if fromIsOPT:
                            childStr += ".next"
                        finalCodeStr=(indent + CodeLVAR_Alloc + '\n' +indent+'    '+getFunctionName(fieldType[0], memVersionName)+'('+VarTag+"<LVL_SUFFIX>"+childStr+', memStruct)\n')
                        objSpec = progSpec.findSpecOf(classes[0], objName, 'string')
                        ToFields=objSpec['fields']
                        FromStructName=objName
                        Write_Extracter(classes, ToStructName, FromStructName, logLvl+1)
                    else:
                        fromFieldTypeCID = fieldType[0].replace('::', '_')
                        toFieldTypeCID = toMemVersionName.replace('::', '_')
                        #print "FUNC:", getFunctionName(fromFieldTypeCID, toFieldTypeCID)
                        if fromFieldTypeCID != toFieldTypeCID:
                            Write_Extracter(classes, toFieldTypeCID, fromFieldTypeCID, logLvl+1)
                        finalCodeStr=indent + CodeLVAR_Alloc + '\n' +indent+'    '+getFunctionName(fromFieldTypeCID, toFieldTypeCID)+'('+VarTag+"<LVL_SUFFIX>"+'.child, '+CODE_LVAR_v2+')\n'
            else: pass

        else:
            CODE_RVAL = CodeRValExpr(toFieldType, VarTag, "")


    #print "CODE_RVAL:", CODE_RVAL

    ###################   H a n d l e   o p t i o n a l   a n d   r e p e t i t i o n   a n d   a s s i g n m e n t   c a s e s
    gatherFieldCode=''
    if fromIsList and toIsList:
        CODE_RVAL='tmpVar'
        globalFieldCount +=1
        childRecName='SRec' + str(globalFieldCount)
        gatherFieldCode+='\n'+indent+'\nour stateRec: '+childRecName+' <- '+VarTag+'.child.next'
        gatherFieldCode+='\n'+indent+'while('+childRecName+'){\n'
        if fromIsALT:
          #  print "ALT-#1"
            gatherFieldCode+=Write_ALT_Extracter(classes, fieldType[0], fields, childRecName, '', 'tmpVar', indent+'    ', level)

        elif fromIsStruct and toIsStruct:
            gatherFieldCode+='\n'+indent+toFieldOwner+' '+progSpec.baseStructName(toFieldType[0])+': tmpVar'
            if toFieldOwner!='me':
                gatherFieldCode+='\n'+indent+'Allocate('+CODE_RVAL+')'
            #print "##### FUNCT:", getFunctionName(fieldType[0], fieldType[0])
            gatherFieldCode+='\n'+indent+getFunctionName(fieldType[0], toFieldType[0])+'('+childRecName+'.child, tmpVar)\n'

        else:
            CODE_RVAL = CodeRValExpr(toFieldType, childRecName, ".next")

        # Now code to push the chosen alternative into the data field# This is a LIST, not an OPT:
        gatherFieldCode+='\n'+indent+CODE_LVAR+'.pushLast('+CODE_RVAL+')'

        gatherFieldCode+=indent+'    '+childRecName+' <- getNextStateRec('+childRecName+')\n'
        # UNCOMMENT FOR DEGUG: S+= '    docPos('+str(level)+', '+VarTag+', "Get Next in LIST for: '+humanIDType+'")\n'


        gatherFieldCode+='\n'+indent+'}\n'
        if(fromIsOPT):
            print("Handle when the optional item is a list.");
            exit(2)
    else:
        if toIsList: print("Error: parsing a non-list to a list is not supported.\n"); exit(1);
        levelSuffix=''
        assignerCode=''
        oldIndent=indent
        if (fromIsOPT):
            setTrueCode=''
            assignerCode+='\n'+indent+'if('+VarTag+'.child.next' +' == NULL){'
            if toFieldOwner=='me':
                if debugTmp: print('        toFieldOwner:', toFieldOwner)
                ## if fieldName==None and a model of fromFieldType has no cooresponding model But we are in EXTRACT_ mode:
                        ## Make a special form of Extract_fromFieldType_to_ToFieldType()
                        ## Call that function instead of the one in Code_LVAR
                # First, create a new flag field
                if fieldName==None:
                    fieldName="TEMP"+str(globalTempVarIdx)
                    globalTempVarIdx += globalTempVarIdx
                newFieldsName=fieldName   #'has_'+fieldName
                fieldDef=progSpec.packField(ToStructName, False, 'me', 'flag', None, None, newFieldsName, None, None, None, False)
                progSpec.addField(classes[0], memVersionName, 'struct', fieldDef)

                # Second, generate the code to set the flag
                assignerCode+='\n'+indent+'    '+VarName+'.'+newFieldsName+' <- false'
                setTrueCode += VarName+'.'+newFieldsName+' <- true'
            elif LHS_IsPointer: # If owner is my, our or their
                assignerCode+='\n'+indent+'    '+CODE_LVAR+' <- NULL'
            else:
                print("ERROR: OPTional fields must not be '"+toFieldOwner+"'.\n")
                exit(1)
            assignerCode+='\n'+indent+'} else {\n'
            levelSuffix='.child.next'
            indent+='    '
            assignerCode+=indent+setTrueCode+'\n'


        if fromIsALT or fromIsEmbeddedAlt:
            if(fromIsEmbeddedAlt):
               # print "ALT-#2"
                assignerCode+=Write_ALT_Extracter(classes, ToStructName, field['innerDefs'], VarTagBase, levelSuffix, VarName, indent+'    ', level+1, logLvl+1)
            else:
              #  print "ALT-#3"
                assignerCode+=Write_ALT_Extracter(classes, fieldType[0], fields, VarTagBase, levelSuffix, VarName+'X', indent+'    ', level, logLvl+1)
                assignerCode+=indent+CODE_LVAR+' <- '+(VarName+'X')+"\n"
        elif fromIsEmbeddedSeq:
            globalFieldCount +=1
            childRecNameBase='childSRec' + str(globalFieldCount)
            childRecName=childRecNameBase+str(level)
            assignerCode+='\n'+indent+'our stateRec: '+childRecName+' <- '+VarTag+levelSuffix+'.child\n'
            for innerField in field['innerDefs']:
                assignerCode+=Write_fieldExtracter(classes, ToStructName, innerField, memObjFields, childRecNameBase, '', True, '    ', level, logLvl+1)
        elif fromIsStruct and toIsStruct:
            assignerCode+=finalCodeStr.replace("<LVL_SUFFIX>", levelSuffix);
            if debugTmp: print('        assignerCode:', assignerCode)
        else:
           # if toFieldOwner == 'const': print "Error: Attempt to extract a parse to const field.\n"; exit(1);
            if CODE_RVAL!="":
                if LHS_IsPointer:
                    assignerCode+='        '+CODE_LVAR+' <deep- '+CODE_RVAL+"\n"
                else: assignerCode+='        '+CODE_LVAR+' <- '+CODE_RVAL+"\n"
            elif finalCodeStr!="": assignerCode+=finalCodeStr.replace("<LVL_SUFFIX>", levelSuffix);

        if (fromIsOPT):
            indent=oldIndent
            assignerCode += indent+'}\n'
            #print '######################\n'+assignerCode, memVersionName, '\n'
           # exit(2)
        gatherFieldCode = assignerCode
    #print ("##########################\n",S,"\n#####################################\n")
    if LHS_IsPointer: # LVAL is a pointer and should be allocated or cleared.
        S+= indent + 'AllocateOrClear(' +CODE_LVAR +')\n'

    S+=gatherFieldCode
    #print "ASSIGN_CODE", S
 #   if debugTmp: exit(2)
    return S
Beispiel #15
0
def fetchOrWriteTerminalParseRule(modelName, field, logLvl):
    global nextParseNameID
    #print "FIELD_IN:", modelName, field
    fieldName='N/A'
    fieldValue=''
    if 'value' in field: fieldValue =field['value']
    typeSpec   = field['typeSpec']
    fieldType  = progSpec.getFieldType(typeSpec)
    fieldOwner = typeSpec['owner']
    if 'fieldName' in field: fieldName  =field['fieldName']
    cdlog(logLvl, "WRITING PARSE RULE for: {}.{}".format(modelName, fieldName))
    #print "WRITE PARSE RULE:", modelName, fieldName

    nameIn=None
    nameOut=None
    if fieldOwner=='const':
        if fieldType=='string':
            if fieldValue in definedRules: nameOut=definedRules[fieldValue]
            else: nameOut=appendRule(nameIn, "term", "parseSEQ",  fieldValue)
        elif fieldType[0:4]=='uint':   nameOut=appendRule(nameIn, "term", "parseSEQ",  fieldValue)
        elif fieldType[0:3]=='int':    nameOut=appendRule(nameIn, "term", "parseSEQ",  fieldValue)
        elif fieldType[0:6]=='double': nameOut=appendRule(nameIn, "term", "parseSEQ",  fieldValue)
        elif fieldType[0:4]=='char':   nameOut=appendRule(nameIn, "term", "parseSEQ",  fieldValue)
        elif fieldType[0:4]=='bool':   nameOut=appendRule(nameIn, "term", "parseSEQ",  fieldValue)
        else:
            print("Unusable const type in fetchOrWriteTerminalParseRule():", fieldType); exit(2);

    elif fieldOwner=='me' or  fieldOwner=='their' or  fieldOwner=='our':
        if fieldType=='string':        nameOut='quotedStr'
        elif fieldType[0:4]=='uint':   nameOut='uintSeq'
        elif fieldType[0:3]=='int':    nameOut='intSeq'
        elif fieldType[0:6]=='double': nameOut='RdxSeq'
        elif fieldType[0:4]=='char':   nameOut=appendRule(nameIn,       "term", "parseSEQ",  None)
        elif fieldType[0:4]=='bool':   nameOut=appendRule(nameIn,       "term", "parseSEQ",  None)
        elif progSpec.isStruct(fieldType):
            objName=fieldType[0]
            if (objName=='ws' or objName=='wsc' or objName=='quotedStr' or objName=='quotedStr1' or objName=='quotedStr2'
                  or objName=='CID' or objName=='UniID' or objName=='printables' or objName=='toEOL' or objName=='alphaNumSeq'
                  or progSpec.typeIsInteger(objName)):
                nameOut=objName
            else:
                if objName=='[' or objName=='{': # This is an ALT or SEQ sub structure
                    print("ERROR: These should be handled in writeNonTermParseRule().\n")
                    exit(1)
                else: nameOut=objName+'_str'
        elif progSpec.isAlt(fieldType):
            pass
        elif progSpec.isCofactual(fieldType):
            pass
        else:
            print("Unusable type in fetchOrWriteTerminalParseRule():", fieldType); exit(2);
    else: print("Pointer types not yet handled in fetchOrWriteTerminalParseRule():", fieldType); exit(2);

    if progSpec.isAContainer(typeSpec):
        global rules
        containerSpec = progSpec.getContainerSpec(typeSpec)
        idxType=''
        if 'indexType' in containerSpec:
            idxType=containerSpec['indexType']
        if(isinstance(containerSpec['datastructID'], str)):
            datastructID = containerSpec['datastructID']
        else:   # it's a parseResult
            datastructID = containerSpec['datastructID'][0]
        if idxType[0:4]=='uint': pass
        if(datastructID=='list'):
            nameOut=appendRule(nameOut+'_REP', "nonterm", "parseREP", [nameOut, 0, 0])
        elif datastructID=='opt':
            nameOut=appendRule(nameOut+'_OPT', "nonterm", "parseREP", [nameOut, 0, 1])
            #print("NAMEOUT:", nameOut)
    field['parseRule']=nameOut
    return nameOut
Beispiel #16
0
    def getDashDeclAndUpdateCode(self, owner, fieldLabel, fieldRef, fieldName,
                                 field, skipFlags, indent):
        global classesToProcess
        global classesEncoded
        [
            structText, updateFuncText, setPosFuncText, drawFuncText,
            handleClicksFuncText
        ] = ['', '', '', '', '']
        typeSpec = field['typeSpec']
        fldCat = progSpec.fieldsTypeCategory(typeSpec)
        if fldCat == 'func': return ['', '', '', '', '']
        if progSpec.typeIsPointer(
                typeSpec) and skipFlags != 'skipPtr':  # Header for a POINTER
            fieldName += 'Ptr'
            if fieldRef == 'data.itmItr':
                innerUpdateFuncStr = '"ItmItr"'  # TODO: unhard code this reference to itmItr
            else:
                innerUpdateFuncStr = fieldRef + '.mySymbol(' + fieldRef + ')'
            updateFuncText += "        " + fieldName + '.dashParent <- self\n'
            updateFuncText += "        " + fieldName + '.update(' + fieldLabel + ', ' + innerUpdateFuncStr + ', isNull(' + innerUpdateFuncStr + '))\n'
            structText += "    " + owner + " ptrToItem: " + fieldName + "\n"

        elif progSpec.isAContainer(
                typeSpec
        ) and skipFlags != 'skipLists':  # Header and items for LIST
            dispStructTypeName = "display_" + progSpec.getFieldType(
                field['typeSpec'])[0]
            innerUpdateFuncStr = '"Size:"+toString(data.' + fieldName + '.size())'
            updateFuncText += "        " + fieldName + '.dashParent <- self\n'
            updateFuncText += "        " + "our dash[our list]: oldElements <- " + fieldName + ".elements\n"
            updateFuncText += "        " + fieldName + '.update(' + fieldLabel + ', ' + innerUpdateFuncStr + ', isNull(' + innerUpdateFuncStr + '), true)\n'
            ## Now push each item
            innerFieldType = progSpec.getFieldType(typeSpec)
            #print "ARRAYSPEC:",innerFieldType, field
            fldCatInner = progSpec.innerTypeCategory(innerFieldType)
            if fieldRef == 'data.itmItr' or fieldRef == 'data.items':
                newFieldRef = '_item'  # TODO: unhard code this reference to itmItr
            else:
                newFieldRef = 'data.' + fieldName + '[_item_key]'
            newFieldLabel = '"["+toString(_item_key)+"]  "+ _item.mySymbol(_item)'
            updateFuncText += "\n        " + "me int64: dash_key <- 0"
            updateFuncText += "\n        withEach _item in data." + fieldName + "{\n"
            [
                innerStructText, innerUpdateFuncText, innerDrawFuncText,
                innerSetPosFuncText, innerHandleClicksFuncText
            ] = self.getDashDeclAndUpdateCode('our', newFieldLabel,
                                              newFieldRef, 'newItem', field,
                                              'skipLists', '        ')
            updateFuncText += "            " + innerStructText
            updateFuncText += "            " + "if(oldElements==NULL or (oldElements!=NULL and !(asClass(" + dispStructTypeName + ", oldElements[dash_key]).data === _item))){\n"
            updateFuncText += '                Allocate(newItem)\n'
            updateFuncText += '                newItem.dashParent <- self\n'
            updateFuncText += '               ' + 'addDependent(_item.mySymbol(_item), newItem)'
            updateFuncText += '\n            } else {\n               newItem <- asClass(' + dispStructTypeName + ', oldElements[dash_key])\n            dash_key <- dash_key + 1'
            updateFuncText += '\n            }'
            updateFuncText += '\n            ' + innerUpdateFuncText
            updateFuncText += '            ' + fieldName + '.updatePush(newItem)'
            updateFuncText += '\n        }\n'
            structText += "    " + owner + " listOfItems: " + fieldName + "\n"
        elif (fldCat == 'struct'):  # Header for a STRUCT
            updateFuncText += "        " + fieldName + '.dashParent <- self\n'
            updateFuncText += "        " + fieldName + '.update(' + fieldLabel + ', ">", ' + fieldRef + ')\n'
            if 'fieldType' in typeSpec and not (isinstance(
                    typeSpec['fieldType'], basestring
            )) and typeSpec['fieldType'][0] == 'DblLinkedList':
                structTypeName = 'infon'
            else:
                structTypeName = progSpec.getFieldType(typeSpec)[0]
            structText += "    " + owner + " display_" + structTypeName + ': ' + fieldName + "\n"

            # Add new classname to a list so it can be encoded.
            if not (structTypeName in classesToProcess):
                classesToProcess.append(structTypeName)

        else:  # Display field for a BASIC TYPES
            valStr = ''
            if (fldCat == 'int' or fldCat == 'double'):
                valStr = 'toString(data.' + fieldName + ')'
            elif (fldCat == 'string' or fldCat == 'char'):
                valStr = '"\'"+' + 'data.' + fieldName + '+"\'"'
            elif (fldCat == 'flag' or fldCat == 'bool'):
                valStr = 'dispBool((data.' + fieldName + ')!=0)'
            elif (fldCat == 'mode'):
                valStr = fieldRef + 'Strings[data.' + fieldName + '] '

            updateFuncText = "        " + fieldName + '.update(100, 180, ' + fieldLabel + ', ' + valStr + ', isNull(' + valStr + '))\n'
            structText += "    " + owner + " dataField: " + fieldName + "\n"

        drawFuncText = "        " + fieldName + '.draw(cr)\n'
        setPosFuncText += '''        if(!<fieldName>.isNullLike or displayMode==fullDisplay){
                <fieldName>.setPos(x,y,extC)
                extC <- <fieldName>.extC
                y <- y + <fieldName>.height
                extX <- max(extX, <fieldName>.extX)
                extY <- max(extY, <fieldName>.extY)
                width<- max(width, <fieldName>.width)
                <fieldName>.isHidden<-false
            } else {<fieldName>.isHidden<-true}
    '''.replace('<fieldName>', fieldName)
        #  updateFuncText+='        if(crntWidth<'+fieldName+'.width){crntWidth <- '+fieldName+'.width}'
        handleClicksFuncText = '            ' + fieldName + '.primaryClick(event)'
        return [
            structText, updateFuncText, drawFuncText, setPosFuncText,
            handleClicksFuncText
        ]