rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
properties[propname] = (getterValue, setterValue, propType, propIndex)
properties[propname] = { "GetterValue" : getterValue, "SetterValue" : setterValue, "PropertyType" : propType, "IndexParamType" : propIndex, "IndexParamName" : propIndexName, "Category" : (getter or setter)["Category"], "GetterName" : getterName, "SetterName" : setterName, "GetterComment" : getter and getter["Comment"], "SetterComment" : setter and setter["Comment"] }
def printIFaceTableCXXFile(f,out): constants = [] functions = {} properties = {} for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not StartsWith(name, "SCLEX_"): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterIndexName, getterType = 0, None, None, None setterValue, setterIndex, setterIndexName, setterType = 0, None, None, None propType, propIndex, propIndexName = None, None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' getterIndexName = getter['Param1Name'] isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterIndexName = setter['Param1Name'] setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex propIndexName = getterIndexName or setterIndexName if isok: # do the types appear to be useable? THIS IS OVERRIDDEN BELOW isok = (propType in ('int', 'position', 'colour', 'bool', 'string') and propIndex in ('void','int','position','string','bool')) # If there were getters on string properties (which there are not), # they would have to follow a different protocol, and would not have # matched the signature above. I suggest this is the signature for # a string getter and setter: # get int funcname(void,stringresult) # set void funcname(void,string) # # For an indexed string getter and setter, the indexer goes in # wparam and must not be called 'int length', since 'int length' # has special meaning. # A bool indexer has a special meaning. It means "if the script # assigns the language's nil value to the property, call the # setter with args (0,0); otherwise call it with (1, value)." # # Although there are no getters indexed by bool, I suggest the # following protocol: If getter(1,0) returns 0, return nil to # the script. Otherwise return getter(0,0). if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) # If it is exposed as a property, it should not be exposed as a function. if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname]) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: funclist = functions.items() funclist.sort() first = 1 for name, features in funclist: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] returnType = features["ReturnType"] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], returnType, paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties)) out.write("};\n\n")
constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName])
constants.append( ("SCI_" + string.upper(getterName), getter))
def printIFaceTableCXXFile(f,out): constants = [] functions = {} properties = {} for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not StartsWith(name, "SCLEX_"): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterIndexName, getterType = 0, None, None, None setterValue, setterIndex, setterIndexName, setterType = 0, None, None, None propType, propIndex, propIndexName = None, None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' getterIndexName = getter['Param1Name'] isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterIndexName = setter['Param1Name'] setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex propIndexName = getterIndexName or setterIndexName if isok: # do the types appear to be useable? THIS IS OVERRIDDEN BELOW isok = (propType in ('int', 'position', 'colour', 'bool', 'string') and propIndex in ('void','int','position','string','bool')) # If there were getters on string properties (which there are not), # they would have to follow a different protocol, and would not have # matched the signature above. I suggest this is the signature for # a string getter and setter: # get int funcname(void,stringresult) # set void funcname(void,string) # # For an indexed string getter and setter, the indexer goes in # wparam and must not be called 'int length', since 'int length' # has special meaning. # A bool indexer has a special meaning. It means "if the script # assigns the language's nil value to the property, call the # setter with args (0,0); otherwise call it with (1, value)." # # Although there are no getters indexed by bool, I suggest the # following protocol: If getter(1,0) returns 0, return nil to # the script. Otherwise return getter(0,0). if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) # If it is exposed as a property, it should not be exposed as a function. if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname]) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: funclist = functions.items() funclist.sort() first = 1 for name, features in funclist: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] returnType = features["ReturnType"] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], returnType, paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties)) out.write("};\n\n")
constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName])
constants.append( ("SCI_" + string.upper(setterName), setter))
def printIFaceTableCXXFile(f,out): constants = [] functions = {} properties = {} for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not StartsWith(name, "SCLEX_"): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterIndexName, getterType = 0, None, None, None setterValue, setterIndex, setterIndexName, setterType = 0, None, None, None propType, propIndex, propIndexName = None, None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' getterIndexName = getter['Param1Name'] isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterIndexName = setter['Param1Name'] setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex propIndexName = getterIndexName or setterIndexName if isok: # do the types appear to be useable? THIS IS OVERRIDDEN BELOW isok = (propType in ('int', 'position', 'colour', 'bool', 'string') and propIndex in ('void','int','position','string','bool')) # If there were getters on string properties (which there are not), # they would have to follow a different protocol, and would not have # matched the signature above. I suggest this is the signature for # a string getter and setter: # get int funcname(void,stringresult) # set void funcname(void,string) # # For an indexed string getter and setter, the indexer goes in # wparam and must not be called 'int length', since 'int length' # has special meaning. # A bool indexer has a special meaning. It means "if the script # assigns the language's nil value to the property, call the # setter with args (0,0); otherwise call it with (1, value)." # # Although there are no getters indexed by bool, I suggest the # following protocol: If getter(1,0) returns 0, return nil to # the script. Otherwise return getter(0,0). if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) # If it is exposed as a property, it should not be exposed as a function. if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname]) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: funclist = functions.items() funclist.sort() first = 1 for name, features in funclist: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] returnType = features["ReturnType"] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], returnType, paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties)) out.write("};\n\n")
constants.sort()
def printIFaceTableCXXFile(f,out): constants = [] functions = {} properties = {} for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not StartsWith(name, "SCLEX_"): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterIndexName, getterType = 0, None, None, None setterValue, setterIndex, setterIndexName, setterType = 0, None, None, None propType, propIndex, propIndexName = None, None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' getterIndexName = getter['Param1Name'] isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterIndexName = setter['Param1Name'] setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex propIndexName = getterIndexName or setterIndexName if isok: # do the types appear to be useable? THIS IS OVERRIDDEN BELOW isok = (propType in ('int', 'position', 'colour', 'bool', 'string') and propIndex in ('void','int','position','string','bool')) # If there were getters on string properties (which there are not), # they would have to follow a different protocol, and would not have # matched the signature above. I suggest this is the signature for # a string getter and setter: # get int funcname(void,stringresult) # set void funcname(void,string) # # For an indexed string getter and setter, the indexer goes in # wparam and must not be called 'int length', since 'int length' # has special meaning. # A bool indexer has a special meaning. It means "if the script # assigns the language's nil value to the property, call the # setter with args (0,0); otherwise call it with (1, value)." # # Although there are no getters indexed by bool, I suggest the # following protocol: If getter(1,0) returns 0, return nil to # the script. Otherwise return getter(0,0). if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) # If it is exposed as a property, it should not be exposed as a function. if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname]) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: funclist = functions.items() funclist.sort() first = 1 for name, features in funclist: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] returnType = features["ReturnType"] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], returnType, paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties)) out.write("};\n\n")
for name, value in constants:
for name, features in constants:
def printIFaceTableCXXFile(f,out): constants = [] functions = {} properties = {} for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not StartsWith(name, "SCLEX_"): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterIndexName, getterType = 0, None, None, None setterValue, setterIndex, setterIndexName, setterType = 0, None, None, None propType, propIndex, propIndexName = None, None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' getterIndexName = getter['Param1Name'] isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterIndexName = setter['Param1Name'] setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex propIndexName = getterIndexName or setterIndexName if isok: # do the types appear to be useable? THIS IS OVERRIDDEN BELOW isok = (propType in ('int', 'position', 'colour', 'bool', 'string') and propIndex in ('void','int','position','string','bool')) # If there were getters on string properties (which there are not), # they would have to follow a different protocol, and would not have # matched the signature above. I suggest this is the signature for # a string getter and setter: # get int funcname(void,stringresult) # set void funcname(void,string) # # For an indexed string getter and setter, the indexer goes in # wparam and must not be called 'int length', since 'int length' # has special meaning. # A bool indexer has a special meaning. It means "if the script # assigns the language's nil value to the property, call the # setter with args (0,0); otherwise call it with (1, value)." # # Although there are no getters indexed by bool, I suggest the # following protocol: If getter(1,0) returns 0, return nil to # the script. Otherwise return getter(0,0). if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) # If it is exposed as a property, it should not be exposed as a function. if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname]) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: funclist = functions.items() funclist.sort() first = 1 for name, features in funclist: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] returnType = features["ReturnType"] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], returnType, paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties)) out.write("};\n\n")
out.write('\n\t{"%s",%s}' % (name, value))
out.write('\n\t{"%s",%s}' % (name, features["Value"]))
def printIFaceTableCXXFile(f,out): constants = [] functions = {} properties = {} for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not StartsWith(name, "SCLEX_"): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterIndexName, getterType = 0, None, None, None setterValue, setterIndex, setterIndexName, setterType = 0, None, None, None propType, propIndex, propIndexName = None, None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' getterIndexName = getter['Param1Name'] isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterIndexName = setter['Param1Name'] setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex propIndexName = getterIndexName or setterIndexName if isok: # do the types appear to be useable? THIS IS OVERRIDDEN BELOW isok = (propType in ('int', 'position', 'colour', 'bool', 'string') and propIndex in ('void','int','position','string','bool')) # If there were getters on string properties (which there are not), # they would have to follow a different protocol, and would not have # matched the signature above. I suggest this is the signature for # a string getter and setter: # get int funcname(void,stringresult) # set void funcname(void,string) # # For an indexed string getter and setter, the indexer goes in # wparam and must not be called 'int length', since 'int length' # has special meaning. # A bool indexer has a special meaning. It means "if the script # assigns the language's nil value to the property, call the # setter with args (0,0); otherwise call it with (1, value)." # # Although there are no getters indexed by bool, I suggest the # following protocol: If getter(1,0) returns 0, return nil to # the script. Otherwise return getter(0,0). if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) # If it is exposed as a property, it should not be exposed as a function. if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname]) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: funclist = functions.items() funclist.sort() first = 1 for name, features in funclist: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] returnType = features["ReturnType"] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], returnType, paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties)) out.write("};\n\n")
funclist = functions.items() funclist.sort()
def printIFaceTableCXXFile(f,out): constants = [] functions = {} properties = {} for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not StartsWith(name, "SCLEX_"): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterIndexName, getterType = 0, None, None, None setterValue, setterIndex, setterIndexName, setterType = 0, None, None, None propType, propIndex, propIndexName = None, None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' getterIndexName = getter['Param1Name'] isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterIndexName = setter['Param1Name'] setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex propIndexName = getterIndexName or setterIndexName if isok: # do the types appear to be useable? THIS IS OVERRIDDEN BELOW isok = (propType in ('int', 'position', 'colour', 'bool', 'string') and propIndex in ('void','int','position','string','bool')) # If there were getters on string properties (which there are not), # they would have to follow a different protocol, and would not have # matched the signature above. I suggest this is the signature for # a string getter and setter: # get int funcname(void,stringresult) # set void funcname(void,string) # # For an indexed string getter and setter, the indexer goes in # wparam and must not be called 'int length', since 'int length' # has special meaning. # A bool indexer has a special meaning. It means "if the script # assigns the language's nil value to the property, call the # setter with args (0,0); otherwise call it with (1, value)." # # Although there are no getters indexed by bool, I suggest the # following protocol: If getter(1,0) returns 0, return nil to # the script. Otherwise return getter(0,0). if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) # If it is exposed as a property, it should not be exposed as a function. if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname]) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: funclist = functions.items() funclist.sort() first = 1 for name, features in funclist: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] returnType = features["ReturnType"] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], returnType, paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties)) out.write("};\n\n")
for name, features in funclist:
for name, features in functions:
def printIFaceTableCXXFile(f,out): constants = [] functions = {} properties = {} for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not StartsWith(name, "SCLEX_"): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterIndexName, getterType = 0, None, None, None setterValue, setterIndex, setterIndexName, setterType = 0, None, None, None propType, propIndex, propIndexName = None, None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' getterIndexName = getter['Param1Name'] isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterIndexName = setter['Param1Name'] setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex propIndexName = getterIndexName or setterIndexName if isok: # do the types appear to be useable? THIS IS OVERRIDDEN BELOW isok = (propType in ('int', 'position', 'colour', 'bool', 'string') and propIndex in ('void','int','position','string','bool')) # If there were getters on string properties (which there are not), # they would have to follow a different protocol, and would not have # matched the signature above. I suggest this is the signature for # a string getter and setter: # get int funcname(void,stringresult) # set void funcname(void,string) # # For an indexed string getter and setter, the indexer goes in # wparam and must not be called 'int length', since 'int length' # has special meaning. # A bool indexer has a special meaning. It means "if the script # assigns the language's nil value to the property, call the # setter with args (0,0); otherwise call it with (1, value)." # # Although there are no getters indexed by bool, I suggest the # following protocol: If getter(1,0) returns 0, return nil to # the script. Otherwise return getter(0,0). if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) # If it is exposed as a property, it should not be exposed as a function. if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname]) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: funclist = functions.items() funclist.sort() first = 1 for name, features in funclist: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] returnType = features["ReturnType"] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], returnType, paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties)) out.write("};\n\n")
out.write('{""}};\n')
out.write('{"",0,iface_void,{iface_void,iface_void}} };\n')
def printIFaceTableCXXFile(f,out): constants = [] functions = {} properties = {} for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not StartsWith(name, "SCLEX_"): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterIndexName, getterType = 0, None, None, None setterValue, setterIndex, setterIndexName, setterType = 0, None, None, None propType, propIndex, propIndexName = None, None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' getterIndexName = getter['Param1Name'] isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterIndexName = setter['Param1Name'] setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex propIndexName = getterIndexName or setterIndexName if isok: # do the types appear to be useable? THIS IS OVERRIDDEN BELOW isok = (propType in ('int', 'position', 'colour', 'bool', 'string') and propIndex in ('void','int','position','string','bool')) # If there were getters on string properties (which there are not), # they would have to follow a different protocol, and would not have # matched the signature above. I suggest this is the signature for # a string getter and setter: # get int funcname(void,stringresult) # set void funcname(void,string) # # For an indexed string getter and setter, the indexer goes in # wparam and must not be called 'int length', since 'int length' # has special meaning. # A bool indexer has a special meaning. It means "if the script # assigns the language's nil value to the property, call the # setter with args (0,0); otherwise call it with (1, value)." # # Although there are no getters indexed by bool, I suggest the # following protocol: If getter(1,0) returns 0, return nil to # the script. Otherwise return getter(0,0). if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) # If it is exposed as a property, it should not be exposed as a function. if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname]) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: funclist = functions.items() funclist.sort() first = 1 for name, features in funclist: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] returnType = features["ReturnType"] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], returnType, paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties)) out.write("};\n\n")
proplist = properties.items() proplist.sort()
def printIFaceTableCXXFile(f,out): constants = [] functions = {} properties = {} for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not StartsWith(name, "SCLEX_"): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterIndexName, getterType = 0, None, None, None setterValue, setterIndex, setterIndexName, setterType = 0, None, None, None propType, propIndex, propIndexName = None, None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' getterIndexName = getter['Param1Name'] isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterIndexName = setter['Param1Name'] setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex propIndexName = getterIndexName or setterIndexName if isok: # do the types appear to be useable? THIS IS OVERRIDDEN BELOW isok = (propType in ('int', 'position', 'colour', 'bool', 'string') and propIndex in ('void','int','position','string','bool')) # If there were getters on string properties (which there are not), # they would have to follow a different protocol, and would not have # matched the signature above. I suggest this is the signature for # a string getter and setter: # get int funcname(void,stringresult) # set void funcname(void,string) # # For an indexed string getter and setter, the indexer goes in # wparam and must not be called 'int length', since 'int length' # has special meaning. # A bool indexer has a special meaning. It means "if the script # assigns the language's nil value to the property, call the # setter with args (0,0); otherwise call it with (1, value)." # # Although there are no getters indexed by bool, I suggest the # following protocol: If getter(1,0) returns 0, return nil to # the script. Otherwise return getter(0,0). if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) # If it is exposed as a property, it should not be exposed as a function. if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname]) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: funclist = functions.items() funclist.sort() first = 1 for name, features in funclist: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] returnType = features["ReturnType"] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], returnType, paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties)) out.write("};\n\n")
for propname, (getter, setter, valueType, paramType) in proplist:
for propname, property in properties:
def printIFaceTableCXXFile(f,out): constants = [] functions = {} properties = {} for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not StartsWith(name, "SCLEX_"): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterIndexName, getterType = 0, None, None, None setterValue, setterIndex, setterIndexName, setterType = 0, None, None, None propType, propIndex, propIndexName = None, None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' getterIndexName = getter['Param1Name'] isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterIndexName = setter['Param1Name'] setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex propIndexName = getterIndexName or setterIndexName if isok: # do the types appear to be useable? THIS IS OVERRIDDEN BELOW isok = (propType in ('int', 'position', 'colour', 'bool', 'string') and propIndex in ('void','int','position','string','bool')) # If there were getters on string properties (which there are not), # they would have to follow a different protocol, and would not have # matched the signature above. I suggest this is the signature for # a string getter and setter: # get int funcname(void,stringresult) # set void funcname(void,string) # # For an indexed string getter and setter, the indexer goes in # wparam and must not be called 'int length', since 'int length' # has special meaning. # A bool indexer has a special meaning. It means "if the script # assigns the language's nil value to the property, call the # setter with args (0,0); otherwise call it with (1, value)." # # Although there are no getters indexed by bool, I suggest the # following protocol: If getter(1,0) returns 0, return nil to # the script. Otherwise return getter(0,0). if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) # If it is exposed as a property, it should not be exposed as a function. if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname]) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: funclist = functions.items() funclist.sort() first = 1 for name, features in funclist: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] returnType = features["ReturnType"] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], returnType, paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties)) out.write("};\n\n")
propname, getter, setter, valueType, paramType
propname, property["GetterValue"], property["SetterValue"], property["PropertyType"], property["IndexParamType"]
def printIFaceTableCXXFile(f,out): constants = [] functions = {} properties = {} for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not StartsWith(name, "SCLEX_"): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterIndexName, getterType = 0, None, None, None setterValue, setterIndex, setterIndexName, setterType = 0, None, None, None propType, propIndex, propIndexName = None, None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' getterIndexName = getter['Param1Name'] isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterIndexName = setter['Param1Name'] setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex propIndexName = getterIndexName or setterIndexName if isok: # do the types appear to be useable? THIS IS OVERRIDDEN BELOW isok = (propType in ('int', 'position', 'colour', 'bool', 'string') and propIndex in ('void','int','position','string','bool')) # If there were getters on string properties (which there are not), # they would have to follow a different protocol, and would not have # matched the signature above. I suggest this is the signature for # a string getter and setter: # get int funcname(void,stringresult) # set void funcname(void,string) # # For an indexed string getter and setter, the indexer goes in # wparam and must not be called 'int length', since 'int length' # has special meaning. # A bool indexer has a special meaning. It means "if the script # assigns the language's nil value to the property, call the # setter with args (0,0); otherwise call it with (1, value)." # # Although there are no getters indexed by bool, I suggest the # following protocol: If getter(1,0) returns 0, return nil to # the script. Otherwise return getter(0,0). if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) # If it is exposed as a property, it should not be exposed as a function. if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname]) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: funclist = functions.items() funclist.sort() first = 1 for name, features in funclist: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] returnType = features["ReturnType"] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], returnType, paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties)) out.write("};\n\n")
out.write('{""}};\n')
out.write('{"", 0, iface_void, iface_void} };\n')
def printIFaceTableCXXFile(f,out): constants = [] functions = {} properties = {} for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not StartsWith(name, "SCLEX_"): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterIndexName, getterType = 0, None, None, None setterValue, setterIndex, setterIndexName, setterType = 0, None, None, None propType, propIndex, propIndexName = None, None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' getterIndexName = getter['Param1Name'] isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterIndexName = setter['Param1Name'] setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex propIndexName = getterIndexName or setterIndexName if isok: # do the types appear to be useable? THIS IS OVERRIDDEN BELOW isok = (propType in ('int', 'position', 'colour', 'bool', 'string') and propIndex in ('void','int','position','string','bool')) # If there were getters on string properties (which there are not), # they would have to follow a different protocol, and would not have # matched the signature above. I suggest this is the signature for # a string getter and setter: # get int funcname(void,stringresult) # set void funcname(void,string) # # For an indexed string getter and setter, the indexer goes in # wparam and must not be called 'int length', since 'int length' # has special meaning. # A bool indexer has a special meaning. It means "if the script # assigns the language's nil value to the property, call the # setter with args (0,0); otherwise call it with (1, value)." # # Although there are no getters indexed by bool, I suggest the # following protocol: If getter(1,0) returns 0, return nil to # the script. Otherwise return getter(0,0). if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) # If it is exposed as a property, it should not be exposed as a function. if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname]) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: funclist = functions.items() funclist.sort() first = 1 for name, features in funclist: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] returnType = features["ReturnType"] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], returnType, paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties)) out.write("};\n\n")
if Contains(line, "//++Autogenerated"):
if Contains(line, "//++Autogenerated") or Contains(line, "<!-- <Autogenerated> -->"):
def CopyWithInsertion(input, output, genfn, definition): copying = 1 for line in input.readlines(): if copying: output.write(line) if Contains(line, "//++Autogenerated"): copying = 0 genfn(definition, output) if Contains(line, "//--Autogenerated"): copying = 1 output.write(line)
if Contains(line, "//--Autogenerated"):
if Contains(line, "//--Autogenerated") or Contains(line, "<!-- </Autogenerated> -->"):
def CopyWithInsertion(input, output, genfn, definition): copying = 1 for line in input.readlines(): if copying: output.write(line) if Contains(line, "//++Autogenerated"): copying = 0 genfn(definition, output) if Contains(line, "//--Autogenerated"): copying = 1 output.write(line)
functions = []
functions = {} properties = {}
def printIFaceTableCXXFile(f,out): constants = [] functions = [] for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not (Contains(name, "SCE_") or Contains(name, "SCLEX_")): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions.append((name, features)) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: functions.sort() first = 1 for name, features in functions: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], features["ReturnType"] or "void", paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d\n" % len(constants)) out.write("};\n\n")
functions.append((name, features))
functions[name] = features if features["FeatureType"] == "get": propname = string.replace(name, "Get", "", 1) properties[propname] = (name, properties.get(propname,(None,None))[1]) elif features["FeatureType"] == "set": propname = string.replace(name, "Set", "", 1) properties[propname] = (properties.get(propname,(None,None))[0], name) for propname, (getterName, setterName) in properties.items(): getter = getterName and functions[getterName] setter = setterName and functions[setterName] getterValue, getterIndex, getterType = 0, None, None setterValue, setterIndex, setterType = 0, None, None propType, propIndex = None, None isok = (getterName or setterName) and not (getter is setter) if isok and getter: getterValue = getter['Value'] getterType = getter['ReturnType'] getterIndex = getter['Param1Type'] or 'void' isok = ((getter['Param2Type'] or 'void') == 'void') if isok and setter: setterValue = setter['Value'] setterType = setter['Param1Type'] or 'void' setterIndex = 'void' if (setter['Param2Type'] or 'void') <> 'void': setterIndex = setterType setterType = setter['Param2Type'] isok = (setter['ReturnType'] == 'void') if isok and getter and setter: isok = (getterType == setterType) and (getterIndex == setterIndex) propType = getterType or setterType propIndex = getterIndex or setterIndex if isok: isok = (propType in ('int', 'position', 'colour', 'bool') and propIndex in ('void','int','position','string','bool')) isok = (isok and propIndex in ('bool', 'void')) if isok: properties[propname] = (getterValue, setterValue, propType, propIndex) if getter: constants.append( ("SCI_" + string.upper(getterName), getterValue) ) del(functions[getterName]) if setter: constants.append( ("SCI_" + string.upper(setterName), setterValue) ) del(functions[setterName]) else: del(properties[propname])
def printIFaceTableCXXFile(f,out): constants = [] functions = [] for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not (Contains(name, "SCE_") or Contains(name, "SCLEX_")): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions.append((name, features)) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: functions.sort() first = 1 for name, features in functions: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], features["ReturnType"] or "void", paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d\n" % len(constants)) out.write("};\n\n")
functions.sort()
funclist = functions.items() funclist.sort()
def printIFaceTableCXXFile(f,out): constants = [] functions = [] for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not (Contains(name, "SCE_") or Contains(name, "SCLEX_")): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions.append((name, features)) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: functions.sort() first = 1 for name, features in functions: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], features["ReturnType"] or "void", paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d\n" % len(constants)) out.write("};\n\n")
for name, features in functions:
for name, features in funclist:
def printIFaceTableCXXFile(f,out): constants = [] functions = [] for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not (Contains(name, "SCE_") or Contains(name, "SCLEX_")): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions.append((name, features)) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: functions.sort() first = 1 for name, features in functions: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], features["ReturnType"] or "void", paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d\n" % len(constants)) out.write("};\n\n")
name, features["Value"], features["ReturnType"] or "void", paramTypes[0], paramTypes[1]
name, features["Value"], returnType, paramTypes[0], paramTypes[1]
def printIFaceTableCXXFile(f,out): constants = [] functions = [] for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not (Contains(name, "SCE_") or Contains(name, "SCLEX_")): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions.append((name, features)) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: functions.sort() first = 1 for name, features in functions: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], features["ReturnType"] or "void", paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d\n" % len(constants)) out.write("};\n\n")
else: out.write('{""}};\n') out.write("\nstatic IFaceProperty ifaceProperties[] = {") if properties: proplist = properties.items() proplist.sort() first = 1 for propname, (getter, setter, valueType, paramType) in proplist: if first: first = 0 else: out.write(",") out.write('\n\t{"%s", %s, %s, iface_%s, iface_%s}' % ( propname, getter, setter, valueType, paramType )) out.write("\n};\n")
def printIFaceTableCXXFile(f,out): constants = [] functions = [] for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not (Contains(name, "SCE_") or Contains(name, "SCLEX_")): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions.append((name, features)) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: functions.sort() first = 1 for name, features in functions: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], features["ReturnType"] or "void", paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d\n" % len(constants)) out.write("};\n\n")
out.write("\tifaceConstantCount = %d\n" % len(constants))
out.write("\tifaceConstantCount = %d,\n" % len(constants)) out.write("\tifacePropertyCount = %d\n" % len(properties))
def printIFaceTableCXXFile(f,out): constants = [] functions = [] for name in f.order: features = f.features[name] if features["Category"] != "Deprecated": if features["FeatureType"] == "val": if not (Contains(name, "SCE_") or Contains(name, "SCLEX_")): constants.append( (name, features["Value"]) ) elif features["FeatureType"] in ["fun","get","set"]: functions.append((name, features)) out.write("\nstatic IFaceConstant ifaceConstants[] = {") if constants: constants.sort() first = 1 for name, value in constants: if first: first = 0 else: out.write(",") out.write('\n\t{"%s",%s}' % (name, value)) out.write("\n};\n") else: out.write('{"",0}};\n') # Write an array of function descriptions. This can be # used as a sort of compiled typelib. out.write("\nstatic IFaceFunction ifaceFunctions[] = {") if functions: functions.sort() first = 1 for name, features in functions: if first: first = 0 else: out.write(",") paramTypes = [ features["Param1Type"] or "void", features["Param2Type"] or "void" ] # Fix-up: if a param is an int named length, change to iface_type_length. if features["Param1Type"] == "int" and features["Param1Name"] == "length": paramTypes[0] = "length" if features["Param2Type"] == "int" and features["Param2Name"] == "length": paramTypes[1] = "length" out.write('\n\t{"%s", %s, iface_%s, {iface_%s, iface_%s}}' % ( name, features["Value"], features["ReturnType"] or "void", paramTypes[0], paramTypes[1] )) out.write("\n};\n") else: out.write('{""}};\n') out.write("\nenum {\n") out.write("\tifaceFunctionCount = %d,\n" % len(functions)) out.write("\tifaceConstantCount = %d\n" % len(constants)) out.write("};\n\n")
'from MGI_Synonym_MusMarker_View s ' + \ 'where s.synonymType in ("similar", "broad", "narrow") '
'from MGI_SynonymType st, MGI_Synonym s ' + \ 'where st._MGIType_key = 2 ' + \ 'and st._Organism_key = 1 ' + \ 'and st.synonymType in ("similar", "broad", "narrow") ' + \ 'and st._SynonymType_key = s._SynonymType_key '
def priority10(): # mouse synonyms (similar, broad, narrow) print 'processing priority 10...%s' % mgi_utils.date() cmd = 'select _Marker_key = s._Object_key, s._Organism_key, _OrthologOrganism_key = NULL, label = s.synonym ' + \ 'from MGI_Synonym_MusMarker_View s ' + \ 'where s.synonymType in ("similar", "broad", "narrow") ' if markerKey is not None: cmd = cmd + 'and s._Object_key = %s\n' % markerKey writeRecord(db.sql(cmd, 'auto'), 1, 10, 'MY', 'related synonym')
server = os.environ['DBSERVER'] database = os.environ['DBNAME'] user = os.environ['DBUSER'] passwordFile = os.environ['DBPASSWORDFILE']
user = os.environ['MGD_DBUSER'] passwordFile = os.environ['MGD_DBPASSWORDFILE']
def createBCPfile(): ''' # # Create bcp file # ''' print 'Creating %s.bcp...' % (table) bcpFile = open(outDir + '/%s.bcp' % (table), 'w') # delete existing entries db.sql('delete from %s where _Refs_key = %s' % (table, refsKey), None) # exclude all problem Molecular Segments # (those with at least one Sequence of Low Quality) db.sql('select distinct c._Probe_key ' + \ 'into #excluded ' + \ 'from SEQ_Probe_Cache c, SEQ_Sequence s ' + \ 'where c._Sequence_key = s._Sequence_key ' + \ 'and s._SequenceQuality_key = %s' % (lowQualityKey), None) db.sql('create nonclustered index idx_key on #excluded(_Probe_key)', None) # select all mouse probes (exclude primers, 63473) db.sql('select p._Probe_key ' + \ 'into #mouseprobes ' + \ 'from SEQ_Probe_Cache c, PRB_Probe p, PRB_Source s ' + \ 'where c._Probe_key = p._Probe_key ' + \ 'and p._SegmentType_key != 63473 ' + \ 'and p._Source_key = s._Source_key ' + \ 'and s._Organism_key = 1', None) db.sql('create nonclustered index idx_key on #mouseprobes(_Probe_key)', None) # select all mouse Probes and Markers which are annotated to the same nucleotide Sequence db.sql('select distinct p._Probe_key, m._Marker_key ' + \ 'into #annotations ' + \ 'from ACC_Accession a, SEQ_Marker_Cache m, SEQ_Probe_Cache p ' + \ 'where a._LogicalDB_key = 9 ' + \ 'and a._MGIType_key = 19 ' + \ 'and a._Object_key = m._Sequence_key ' + \ 'and m._Organism_key = 1 ' + \ 'and a._Object_key = p._Sequence_key ' + \ 'and exists (select 1 from #mouseprobes mp ' + \ 'where p._Probe_key = mp._Probe_key)', None) db.sql('create nonclustered index idx_pkey on #annotations(_Probe_key)', None) db.sql('create nonclustered index idx_mkey on #annotations(_Marker_key)', None) # select all Probes and Markers with Putative annotation db.sql('select _Probe_key, _Marker_key into #putatives from %s where relationship = "P"' % (table), None) db.sql('create nonclustered index idx_pkey on #putatives(_Probe_key)', None) db.sql('create nonclustered index idx_mkey on #putatives(_Marker_key)', None) # select all Probes and Markers with a non-Putative (E, H), or null Annotation db.sql('select _Probe_key, _Marker_key into #nonputatives from %s where relationship != "P" or relationship is null' % (table), None) db.sql('create nonclustered index idx_pkey on #nonputatives(_Probe_key)', None) db.sql('create nonclustered index idx_mkey on #nonputatives(_Marker_key)', None) # select all Molecular Segments which share a Sequence object with a Marker # and which already have a "P" association with that Marker db.sql('select distinct a._Probe_key, a._Marker_key ' + \ 'into #haveputative ' + \ 'from #annotations a ' + \ 'where exists (select 1 from #putatives p ' + \ 'where a._Probe_key = p._Probe_key ' + \ 'and a._Marker_key = p._Marker_key) ' + \ 'and not exists (select 1 from #excluded e ' + \ 'where a._Probe_key = e._Probe_key)', None) # select all mouse Molecular Segments which share a Seq ID with a mouse Marker # and which do not have a non-P/null association with that Marker # that is, we don't want to overwrite a curated relationship (even if it's a null relationship) db.sql('select distinct a._Probe_key, a._Marker_key ' + \ 'into #createautoe ' + \ 'from #annotations a ' + \ 'where not exists (select 1 from #nonputatives p ' + \ 'where a._Probe_key = p._Probe_key ' + \ 'and a._Marker_key = p._Marker_key) ' + \ 'and not exists (select 1 from #excluded e ' + \ 'where a._Probe_key = e._Probe_key)', None) # delete any putatives which can be trumped by an auto-E relationship db.sql('delete %s ' % (table) + \ 'from #haveputative p, #createautoe e, %s pm ' % (table) + \ 'where p._Probe_key = e._Probe_key ' + \ 'and p._Marker_key = e._Marker_key ' + \ 'and e._Probe_key = pm._Probe_key ' + \ 'and e._Marker_key = pm._Marker_key ' + \ 'and pm.relationship = "P"', None) # for each molecular segment/marker, create an auto-E relationship results = db.sql('select distinct _Probe_key, _Marker_key from #createautoe', 'auto') for r in results: bcpFile.write(mgi_utils.prvalue(r['_Probe_key']) + COLDL + \ mgi_utils.prvalue(r['_Marker_key']) + COLDL + \ mgi_utils.prvalue(refsKey) + COLDL + \ relationship + COLDL + \ createdBy + COLDL + \ createdBy + COLDL + \ cdate + COLDL + \ cdate + LINEDL) bcpFile.close()
db.set_sqlLogin(user, password, server, database)
db.set_sqlUser(user) db.set_sqlPassword(password)
def createBCPfile(): ''' # # Create bcp file # ''' print 'Creating %s.bcp...' % (table) bcpFile = open(outDir + '/%s.bcp' % (table), 'w') # delete existing entries db.sql('delete from %s where _Refs_key = %s' % (table, refsKey), None) # exclude all problem Molecular Segments # (those with at least one Sequence of Low Quality) db.sql('select distinct c._Probe_key ' + \ 'into #excluded ' + \ 'from SEQ_Probe_Cache c, SEQ_Sequence s ' + \ 'where c._Sequence_key = s._Sequence_key ' + \ 'and s._SequenceQuality_key = %s' % (lowQualityKey), None) db.sql('create nonclustered index idx_key on #excluded(_Probe_key)', None) # select all mouse probes (exclude primers, 63473) db.sql('select p._Probe_key ' + \ 'into #mouseprobes ' + \ 'from SEQ_Probe_Cache c, PRB_Probe p, PRB_Source s ' + \ 'where c._Probe_key = p._Probe_key ' + \ 'and p._SegmentType_key != 63473 ' + \ 'and p._Source_key = s._Source_key ' + \ 'and s._Organism_key = 1', None) db.sql('create nonclustered index idx_key on #mouseprobes(_Probe_key)', None) # select all mouse Probes and Markers which are annotated to the same nucleotide Sequence db.sql('select distinct p._Probe_key, m._Marker_key ' + \ 'into #annotations ' + \ 'from ACC_Accession a, SEQ_Marker_Cache m, SEQ_Probe_Cache p ' + \ 'where a._LogicalDB_key = 9 ' + \ 'and a._MGIType_key = 19 ' + \ 'and a._Object_key = m._Sequence_key ' + \ 'and m._Organism_key = 1 ' + \ 'and a._Object_key = p._Sequence_key ' + \ 'and exists (select 1 from #mouseprobes mp ' + \ 'where p._Probe_key = mp._Probe_key)', None) db.sql('create nonclustered index idx_pkey on #annotations(_Probe_key)', None) db.sql('create nonclustered index idx_mkey on #annotations(_Marker_key)', None) # select all Probes and Markers with Putative annotation db.sql('select _Probe_key, _Marker_key into #putatives from %s where relationship = "P"' % (table), None) db.sql('create nonclustered index idx_pkey on #putatives(_Probe_key)', None) db.sql('create nonclustered index idx_mkey on #putatives(_Marker_key)', None) # select all Probes and Markers with a non-Putative (E, H), or null Annotation db.sql('select _Probe_key, _Marker_key into #nonputatives from %s where relationship != "P" or relationship is null' % (table), None) db.sql('create nonclustered index idx_pkey on #nonputatives(_Probe_key)', None) db.sql('create nonclustered index idx_mkey on #nonputatives(_Marker_key)', None) # select all Molecular Segments which share a Sequence object with a Marker # and which already have a "P" association with that Marker db.sql('select distinct a._Probe_key, a._Marker_key ' + \ 'into #haveputative ' + \ 'from #annotations a ' + \ 'where exists (select 1 from #putatives p ' + \ 'where a._Probe_key = p._Probe_key ' + \ 'and a._Marker_key = p._Marker_key) ' + \ 'and not exists (select 1 from #excluded e ' + \ 'where a._Probe_key = e._Probe_key)', None) # select all mouse Molecular Segments which share a Seq ID with a mouse Marker # and which do not have a non-P/null association with that Marker # that is, we don't want to overwrite a curated relationship (even if it's a null relationship) db.sql('select distinct a._Probe_key, a._Marker_key ' + \ 'into #createautoe ' + \ 'from #annotations a ' + \ 'where not exists (select 1 from #nonputatives p ' + \ 'where a._Probe_key = p._Probe_key ' + \ 'and a._Marker_key = p._Marker_key) ' + \ 'and not exists (select 1 from #excluded e ' + \ 'where a._Probe_key = e._Probe_key)', None) # delete any putatives which can be trumped by an auto-E relationship db.sql('delete %s ' % (table) + \ 'from #haveputative p, #createautoe e, %s pm ' % (table) + \ 'where p._Probe_key = e._Probe_key ' + \ 'and p._Marker_key = e._Marker_key ' + \ 'and e._Probe_key = pm._Probe_key ' + \ 'and e._Marker_key = pm._Marker_key ' + \ 'and pm.relationship = "P"', None) # for each molecular segment/marker, create an auto-E relationship results = db.sql('select distinct _Probe_key, _Marker_key from #createautoe', 'auto') for r in results: bcpFile.write(mgi_utils.prvalue(r['_Probe_key']) + COLDL + \ mgi_utils.prvalue(r['_Marker_key']) + COLDL + \ mgi_utils.prvalue(refsKey) + COLDL + \ relationship + COLDL + \ createdBy + COLDL + \ createdBy + COLDL + \ cdate + COLDL + \ cdate + LINEDL) bcpFile.close()
cmd = 'select o._Marker_key, o._Organism_key, o._OrthologOrganism_key, label = s.synonym ' + \
cmd = 'select distinct o._Marker_key, o._Organism_key, o._OrthologOrganism_key, label = s.synonym ' + \
def priority8(): # human synonyms of mouse orthologs print 'processing priority 8...%s' % mgi_utils.date() cmd = 'select distinct m._Marker_key, m2 = m2._Marker_key, m._Organism_key, _OrthologOrganism_key = m2._Organism_key ' + \ 'into #orthology1 ' + \ 'from MRK_Marker m, MRK_Marker m2, HMD_Homology h1, HMD_Homology h2, ' + \ 'HMD_Homology_Marker hm1, HMD_Homology_Marker hm2, MGI_Organism s ' + \ 'where m._Organism_key = 1 ' + \ 'and m._Marker_key = hm1._Marker_key ' + \ 'and hm1._Homology_key = h1._Homology_key ' + \ 'and h1._Class_key = h2._Class_key ' + \ 'and h2._Homology_key = hm2._Homology_key ' + \ 'and hm2._Marker_key = m2._Marker_key ' + \ 'and m2._Organism_key = 2 ' + \ 'and m2._Organism_key = s._Organism_key ' if markerKey is not None: cmd = cmd + 'and m._Marker_key = %s\n' % markerKey db.sql(cmd, None) db.sql('create index idx1 on #orthology1(m2)', None) db.sql('create index idx2 on #orthology1(_OrthologOrganism_key)', None) # human synonym cmd = 'select o._Marker_key, o._Organism_key, o._OrthologOrganism_key, label = s.synonym ' + \ 'from #orthology1 o, MGI_SynonymType st, MGI_Synonym s ' + \ 'where st._MGIType_key = 2 ' + \ 'and st._Organism_key = o._OrthologOrganism_key ' + \ 'and st._SynonymType_key = s._SynonymType_key ' + \ 'and o.m2 = s._Object_key ' if markerKey is not None: cmd = cmd + 'where s._Object_key = %s\n' % markerKey writeRecord(db.sql(cmd, 'auto'), 1, 8, 'MY', 'human synonym')
cmd = cmd + 'where s._Object_key = %s\n' % markerKey
cmd = cmd + 'and s._Object_key = %s\n' % markerKey
def priority8(): # human synonyms of mouse orthologs print 'processing priority 8...%s' % mgi_utils.date() cmd = 'select distinct m._Marker_key, m2 = m2._Marker_key, m._Organism_key, _OrthologOrganism_key = m2._Organism_key ' + \ 'into #orthology1 ' + \ 'from MRK_Marker m, MRK_Marker m2, HMD_Homology h1, HMD_Homology h2, ' + \ 'HMD_Homology_Marker hm1, HMD_Homology_Marker hm2, MGI_Organism s ' + \ 'where m._Organism_key = 1 ' + \ 'and m._Marker_key = hm1._Marker_key ' + \ 'and hm1._Homology_key = h1._Homology_key ' + \ 'and h1._Class_key = h2._Class_key ' + \ 'and h2._Homology_key = hm2._Homology_key ' + \ 'and hm2._Marker_key = m2._Marker_key ' + \ 'and m2._Organism_key = 2 ' + \ 'and m2._Organism_key = s._Organism_key ' if markerKey is not None: cmd = cmd + 'and m._Marker_key = %s\n' % markerKey db.sql(cmd, None) db.sql('create index idx1 on #orthology1(m2)', None) db.sql('create index idx2 on #orthology1(_OrthologOrganism_key)', None) # human synonym cmd = 'select o._Marker_key, o._Organism_key, o._OrthologOrganism_key, label = s.synonym ' + \ 'from #orthology1 o, MGI_SynonymType st, MGI_Synonym s ' + \ 'where st._MGIType_key = 2 ' + \ 'and st._Organism_key = o._OrthologOrganism_key ' + \ 'and st._SynonymType_key = s._SynonymType_key ' + \ 'and o.m2 = s._Object_key ' if markerKey is not None: cmd = cmd + 'where s._Object_key = %s\n' % markerKey writeRecord(db.sql(cmd, 'auto'), 1, 8, 'MY', 'human synonym')
cmd = 'select o._Marker_key, o._Organism_key, o._OrthologOrganism_key, label = s.synonym ' + \
cmd = 'select distinct o._Marker_key, o._Organism_key, o._OrthologOrganism_key, label = s.synonym ' + \
def priority9(): # rat synonyms of mouse orthologs print 'processing priority 9...%s' % mgi_utils.date() cmd = 'select distinct m._Marker_key, m2 = m2._Marker_key, m._Organism_key, _OrthologOrganism_key = m2._Organism_key ' + \ 'into #orthology2 ' + \ 'from MRK_Marker m, MRK_Marker m2, HMD_Homology h1, HMD_Homology h2, ' + \ 'HMD_Homology_Marker hm1, HMD_Homology_Marker hm2, MGI_Organism s ' + \ 'where m._Organism_key = 1 ' + \ 'and m._Marker_key = hm1._Marker_key ' + \ 'and hm1._Homology_key = h1._Homology_key ' + \ 'and h1._Class_key = h2._Class_key ' + \ 'and h2._Homology_key = hm2._Homology_key ' + \ 'and hm2._Marker_key = m2._Marker_key ' + \ 'and m2._Organism_key = 40 ' + \ 'and m2._Organism_key = s._Organism_key ' if markerKey is not None: cmd = cmd + 'and m._Marker_key = %s\n' % markerKey db.sql(cmd, None) db.sql('create index idx1 on #orthology2(m2)', None) db.sql('create index idx2 on #orthology2(_OrthologOrganism_key)', None) # rat synonym cmd = 'select o._Marker_key, o._Organism_key, o._OrthologOrganism_key, label = s.synonym ' + \ 'from #orthology2 o, MGI_SynonymType st, MGI_Synonym s ' + \ 'where st._MGIType_key = 2 ' + \ 'and st._Organism_key = o._OrthologOrganism_key ' + \ 'and st._SynonymType_key = s._SynonymType_key ' + \ 'and o.m2 = s._Object_key ' if markerKey is not None: cmd = cmd + 'where s._Object_key = %s\n' % markerKey writeRecord(db.sql(cmd, 'auto'), 1, 9, 'MY', 'rat synonym')
cmd = cmd + 'where s._Object_key = %s\n' % markerKey
cmd = cmd + 'and s._Object_key = %s\n' % markerKey
def priority9(): # rat synonyms of mouse orthologs print 'processing priority 9...%s' % mgi_utils.date() cmd = 'select distinct m._Marker_key, m2 = m2._Marker_key, m._Organism_key, _OrthologOrganism_key = m2._Organism_key ' + \ 'into #orthology2 ' + \ 'from MRK_Marker m, MRK_Marker m2, HMD_Homology h1, HMD_Homology h2, ' + \ 'HMD_Homology_Marker hm1, HMD_Homology_Marker hm2, MGI_Organism s ' + \ 'where m._Organism_key = 1 ' + \ 'and m._Marker_key = hm1._Marker_key ' + \ 'and hm1._Homology_key = h1._Homology_key ' + \ 'and h1._Class_key = h2._Class_key ' + \ 'and h2._Homology_key = hm2._Homology_key ' + \ 'and hm2._Marker_key = m2._Marker_key ' + \ 'and m2._Organism_key = 40 ' + \ 'and m2._Organism_key = s._Organism_key ' if markerKey is not None: cmd = cmd + 'and m._Marker_key = %s\n' % markerKey db.sql(cmd, None) db.sql('create index idx1 on #orthology2(m2)', None) db.sql('create index idx2 on #orthology2(_OrthologOrganism_key)', None) # rat synonym cmd = 'select o._Marker_key, o._Organism_key, o._OrthologOrganism_key, label = s.synonym ' + \ 'from #orthology2 o, MGI_SynonymType st, MGI_Synonym s ' + \ 'where st._MGIType_key = 2 ' + \ 'and st._Organism_key = o._OrthologOrganism_key ' + \ 'and st._SynonymType_key = s._SynonymType_key ' + \ 'and o.m2 = s._Object_key ' if markerKey is not None: cmd = cmd + 'where s._Object_key = %s\n' % markerKey writeRecord(db.sql(cmd, 'auto'), 1, 9, 'MY', 'rat synonym')
if markerKey is not None: cmd = cmd + 'and _Marker_key = %s\n' % markerKey
def priority11(): # human ortholog (symbol) print 'processing priority 11...%s' % mgi_utils.date()
if markerKey is not None: cmd = cmd + 'and _Marker_key = %s\n' % markerKey
def priority12(): # human ortholog (name) print 'processing priority 12...%s' % mgi_utils.date() cmd = 'select o.*, label = m.name, labelTypeName = s.commonName + " ortholog name" ' + \ 'from #orthology1 o, MRK_Marker m, MGI_Organism s ' + \ 'where o.m2 = m._Marker_key ' + \ 'and o._OrthologOrganism_key = s._Organism_key ' writeRecord(db.sql(cmd, 'auto'), 1, 12, 'ON', None) # human name cmd = 'select _Marker_key, _Organism_key, _OrthologOrganism_key = NULL, label = name ' + \ 'from MRK_Marker ' + \ 'where _Organism_key = 2 ' if markerKey is not None: cmd = cmd + 'and _Marker_key = %s\n' % markerKey writeRecord(db.sql(cmd, 'auto'), 1, 12, 'MN', 'current name')
if markerKey is not None: cmd = cmd + 'and _Marker_key = %s\n' % markerKey
def priority13(): # rat ortholog (symbol) print 'processing priority 13...%s' % mgi_utils.date() cmd = 'select o.*, label = m.symbol, labelTypeName = s.commonName + " ortholog symbol" ' + \ 'from #orthology2 o, MRK_Marker m, MGI_Organism s ' + \ 'where o.m2 = m._Marker_key ' + \ 'and o._OrthologOrganism_key = s._Organism_key ' # rat symbol writeRecord(db.sql(cmd, 'auto'), 1, 13, 'OS', None) cmd = 'select _Marker_key, _Organism_key, _OrthologOrganism_key = NULL, label = symbol ' + \ 'from MRK_Marker ' + \ 'where _Organism_key = 40 ' if markerKey is not None: cmd = cmd + 'and _Marker_key = %s\n' % markerKey # rat name writeRecord(db.sql(cmd, 'auto'), 1, 13, 'MS', 'current symbol') cmd = 'select _Marker_key, _Organism_key, _OrthologOrganism_key = NULL, label = name ' + \ 'from MRK_Marker ' + \ 'where _Organism_key = 40 ' if markerKey is not None: cmd = cmd + 'and _Marker_key = %s\n' % markerKey writeRecord(db.sql(cmd, 'auto'), 1, 13, 'MN', 'current name')
cmd = 'select _Marker_key = s._Object_key, st._Organism_key, _OrthologOrganism_key = NULL, label = s.synonym ' + \
cmd = 'select distinct _Marker_key = s._Object_key, st._Organism_key, _OrthologOrganism_key = NULL, label = s.synonym ' + \
def priority10(): # mouse synonyms (similar, broad, narrow) print 'processing priority 10...%s' % mgi_utils.date() cmd = 'select _Marker_key = s._Object_key, st._Organism_key, _OrthologOrganism_key = NULL, label = s.synonym ' + \ 'from MGI_SynonymType st, MGI_Synonym s ' + \ 'where st._MGIType_key = 2 ' + \ 'and st._Organism_key = 1 ' + \ 'and st.synonymType in ("similar", "broad", "narrow") ' + \ 'and st._SynonymType_key = s._SynonymType_key ' if markerKey is not None: cmd = cmd + 'and s._Object_key = %s\n' % markerKey writeRecord(db.sql(cmd, 'auto'), 1, 10, 'MY', 'related synonym')
cmd = 'select _Marker_key = s._Object_key, s._Organism_key, _OrthologOrganism_key = NULL, label = s.synonym ' + \
cmd = 'select _Marker_key = s._Object_key, st._Organism_key, _OrthologOrganism_key = NULL, label = s.synonym ' + \
def priority10(): # mouse synonyms (similar, broad, narrow) print 'processing priority 10...%s' % mgi_utils.date() cmd = 'select _Marker_key = s._Object_key, s._Organism_key, _OrthologOrganism_key = NULL, label = s.synonym ' + \ 'from MGI_SynonymType st, MGI_Synonym s ' + \ 'where st._MGIType_key = 2 ' + \ 'and st._Organism_key = 1 ' + \ 'and st.synonymType in ("similar", "broad", "narrow") ' + \ 'and st._SynonymType_key = s._SynonymType_key ' if markerKey is not None: cmd = cmd + 'and s._Object_key = %s\n' % markerKey writeRecord(db.sql(cmd, 'auto'), 1, 10, 'MY', 'related synonym')
for fileName in files: fileList.append(os.path.join(root, fileName))
for fileName in files: if guess_type(os.path.join(root,fileName))[0] in walFormats: fileList.append(os.path.join(root, fileName))
def makeWallpapersList(path): """ Do a wallpaper list: from directory, file with list and from image. """ walFormats = ['image/jpeg', 'image/png'] if os.path.isdir(path): fileList = [] for root, dirs, files in os.walk(path): for fileName in files: fileList.append(os.path.join(root, fileName)) return fileList if guess_type(path)[0] in walFormats: return [path] try: return [path[:-1] for path in open(path).readlines() \ if guess_type(path)[0] in walFormats] except: raise ActionError, 'Cannot open selected file'
os.system(tool.replace('FILENAME', "'%s'" % options.file.replace("'","\'")))
os.system(tool.replace('FILENAME', "%s" % config['wallpapers'][config['currentWal']].replace("'","\\'").replace(" ","\\ ")))
def doAction(options, config): """ Do specified in options action and return modified config """ if options.external_tool: tool = options.external_tool else: try: tool = [tool for tool in config['tools'] if \ tool.split()[0] == (options.tool or config['defaultTool'])][0] except: raise ParseError, 'Cannot find specified tool in database' if options.show_current: print config['wallpapers'][config['currentWal']] return config if options.export: for wal in config['wallpapers']: print wal return config if options.add: if not os.path.exists(options.add): raise ActionError, 'File doesn\'t exist' fileList = makeWallpapersList(options.add) for fileName in fileList: if not fileName in config['wallpapers']: config['wallpapers'].append(fileName) return config if options.remove_current: options.remove = config['currentWal'] if not options.remove is None and options.remove != '': try: path = config['wallpapers'][int(options.remove)] except IndexError: raise ActionError, 'No such wallpaper in database.' except ValueError: if not os.path.exists(path): raise ActionError, 'File doesn\'t exist' fileList = makeWallpapersList(path) for fileName in fileList: config['wallpapers'].remove(fileName) return config if options.clear: config['wallpapers'] = [] config['currentWal'] = 0 return config if options.file: os.system(tool.replace('FILENAME', "'%s'" % options.file.replace("'","\'"))) return config if not config['wallpapers']: raise ActionError, 'The wallpapers database is empty. Use --add option to add images.' if options.number: if options.number < len(config['wallpapers']): config['currentWal'] = options.number else: raise ActionError, 'No such wallpaper in database.' if options.next: if len(config['wallpapers']) - 1 > config['currentWal']: config['currentWal'] += 1 else: config['currentWal'] = 0 if options.previous: if config['currentWal'] > 0: config['currentWal'] -= 1 else: config['currentWal'] = len(config['wallpapers']) - 1 if options.random: config['currentWal'] = random.randrange(len(config['wallpapers'])) if config['currentWal'] >= len(config['wallpapers']): raise ActionError, 'Selected wallpaper not in database' os.system(tool.replace('FILENAME', "'%s'" % config['wallpapers'][config['currentWal']].replace("'","\'"))) return config
os.system(tool.replace('FILENAME', "'%s'" % config['wallpapers'][config['currentWal']].replace("'","\'")))
os.system(tool.replace('FILENAME', "%s" % config['wallpapers'][config['currentWal']].replace("'","\\'").replace(" ","\\ ")))
def doAction(options, config): """ Do specified in options action and return modified config """ if options.external_tool: tool = options.external_tool else: try: tool = [tool for tool in config['tools'] if \ tool.split()[0] == (options.tool or config['defaultTool'])][0] except: raise ParseError, 'Cannot find specified tool in database' if options.show_current: print config['wallpapers'][config['currentWal']] return config if options.export: for wal in config['wallpapers']: print wal return config if options.add: if not os.path.exists(options.add): raise ActionError, 'File doesn\'t exist' fileList = makeWallpapersList(options.add) for fileName in fileList: if not fileName in config['wallpapers']: config['wallpapers'].append(fileName) return config if options.remove_current: options.remove = config['currentWal'] if not options.remove is None and options.remove != '': try: path = config['wallpapers'][int(options.remove)] except IndexError: raise ActionError, 'No such wallpaper in database.' except ValueError: if not os.path.exists(path): raise ActionError, 'File doesn\'t exist' fileList = makeWallpapersList(path) for fileName in fileList: config['wallpapers'].remove(fileName) return config if options.clear: config['wallpapers'] = [] config['currentWal'] = 0 return config if options.file: os.system(tool.replace('FILENAME', "'%s'" % options.file.replace("'","\'"))) return config if not config['wallpapers']: raise ActionError, 'The wallpapers database is empty. Use --add option to add images.' if options.number: if options.number < len(config['wallpapers']): config['currentWal'] = options.number else: raise ActionError, 'No such wallpaper in database.' if options.next: if len(config['wallpapers']) - 1 > config['currentWal']: config['currentWal'] += 1 else: config['currentWal'] = 0 if options.previous: if config['currentWal'] > 0: config['currentWal'] -= 1 else: config['currentWal'] = len(config['wallpapers']) - 1 if options.random: config['currentWal'] = random.randrange(len(config['wallpapers'])) if config['currentWal'] >= len(config['wallpapers']): raise ActionError, 'Selected wallpaper not in database' os.system(tool.replace('FILENAME', "'%s'" % config['wallpapers'][config['currentWal']].replace("'","\'"))) return config
if not os.path.exists(path):
if not os.path.exists(options.add):
def doAction(options, config): """ Do specified in options action and return modified config """ try: tool = [tool for tool in config['tools'] if \ tool.split()[0] == (options.tool or config['defaultTool'])][0] except: raise ParseError, 'Cannot find specified tool in database' if options.export: for wal in config['wallpapers']: print wal return config if options.add: if not os.path.exists(path): raise ActionError, 'File doesn\'t exist' fileList = makeWallpapersList(path) for fileName in fileList: if not fileName in config['wallpapers']: config['wallpapers'].append(fileName) return config if options.remove_current: options.remove = config['currentWal'] if not options.remove is None and options.remove != '': try: path = config['wallpapers'][int(options.remove)] except IndexError: raise ActionError, 'No such wallpaper in database.' except ValueError: if not os.path.exists(path): raise ActionError, 'File doesn\'t exist' fileList = makeWallpapersList(path) for fileName in fileList: config['wallpapers'].remove(fileName) return config if options.clear: config['wallpapers'] = [] config['currentWal'] = 0 return config if options.file: os.system(tool.replace('FILENAME', options.file)) return config if not config['wallpapers']: raise ActionError, 'The wallpapers database is empty. Use --add option to add images.' if options.number: if options.number < len(config['wallpapers']): config['currentWal'] = options.number else: raise ActionError, 'No such wallpaper in database.' if options.next: if len(config['wallpapers']) - 1 > config['currentWal']: config['currentWal'] += 1 else: config['currentWal'] = 0 if options.previous: if config['currentWal'] > 0: config['currentWal'] -= 1 else: config['currentWal'] = len(config['wallpapers']) - 1 if options.random: config['currentWal'] = random.randrange(len(config['wallpapers'])) if config['currentWal'] >= len(config['wallpapers']): raise ActionError, 'Selected wallpaper not in database' os.system(tool.replace('FILENAME', config['wallpapers'][config['currentWal']])) return config
fileList = makeWallpapersList(path)
fileList = makeWallpapersList(options.add)
def doAction(options, config): """ Do specified in options action and return modified config """ try: tool = [tool for tool in config['tools'] if \ tool.split()[0] == (options.tool or config['defaultTool'])][0] except: raise ParseError, 'Cannot find specified tool in database' if options.export: for wal in config['wallpapers']: print wal return config if options.add: if not os.path.exists(path): raise ActionError, 'File doesn\'t exist' fileList = makeWallpapersList(path) for fileName in fileList: if not fileName in config['wallpapers']: config['wallpapers'].append(fileName) return config if options.remove_current: options.remove = config['currentWal'] if not options.remove is None and options.remove != '': try: path = config['wallpapers'][int(options.remove)] except IndexError: raise ActionError, 'No such wallpaper in database.' except ValueError: if not os.path.exists(path): raise ActionError, 'File doesn\'t exist' fileList = makeWallpapersList(path) for fileName in fileList: config['wallpapers'].remove(fileName) return config if options.clear: config['wallpapers'] = [] config['currentWal'] = 0 return config if options.file: os.system(tool.replace('FILENAME', options.file)) return config if not config['wallpapers']: raise ActionError, 'The wallpapers database is empty. Use --add option to add images.' if options.number: if options.number < len(config['wallpapers']): config['currentWal'] = options.number else: raise ActionError, 'No such wallpaper in database.' if options.next: if len(config['wallpapers']) - 1 > config['currentWal']: config['currentWal'] += 1 else: config['currentWal'] = 0 if options.previous: if config['currentWal'] > 0: config['currentWal'] -= 1 else: config['currentWal'] = len(config['wallpapers']) - 1 if options.random: config['currentWal'] = random.randrange(len(config['wallpapers'])) if config['currentWal'] >= len(config['wallpapers']): raise ActionError, 'Selected wallpaper not in database' os.system(tool.replace('FILENAME', config['wallpapers'][config['currentWal']])) return config
'habak -i FILENAME -S',
'habak -hi FILENAME -mS',
def createConfiguration(): """ Create empty configuration. """ tools = ['hsetroot -fill FILENAME', 'habak -i FILENAME -S', 'Esetroot FILENAME'] try: defTool = [tool.split()[0] for tool in tools if not \ os.system('which %s &>/dev/null' % tool.split()[0])][0] except: raise ParseError, 'Cannot find any usable tool to set wallpaper' return {'wallpapers': [], 'currentWal': 0, 'tools': tools, 'defaultTool': defTool}
os.system(tool.replace('FILENAME', options.file))
os.system(tool.replace('FILENAME', "'%s'" % options.file.replace("'","\'")))
def doAction(options, config): """ Do specified in options action and return modified config """ if options.external_tool: tool = options.external_tool else: try: tool = [tool for tool in config['tools'] if \ tool.split()[0] == (options.tool or config['defaultTool'])][0] except: raise ParseError, 'Cannot find specified tool in database' if options.export: for wal in config['wallpapers']: print wal return config if options.add: if not os.path.exists(options.add): raise ActionError, 'File doesn\'t exist' fileList = makeWallpapersList(options.add) for fileName in fileList: if not fileName in config['wallpapers']: config['wallpapers'].append(fileName) return config if options.remove_current: options.remove = config['currentWal'] if not options.remove is None and options.remove != '': try: path = config['wallpapers'][int(options.remove)] except IndexError: raise ActionError, 'No such wallpaper in database.' except ValueError: if not os.path.exists(path): raise ActionError, 'File doesn\'t exist' fileList = makeWallpapersList(path) for fileName in fileList: config['wallpapers'].remove(fileName) return config if options.clear: config['wallpapers'] = [] config['currentWal'] = 0 return config if options.file: os.system(tool.replace('FILENAME', options.file)) return config if not config['wallpapers']: raise ActionError, 'The wallpapers database is empty. Use --add option to add images.' if options.number: if options.number < len(config['wallpapers']): config['currentWal'] = options.number else: raise ActionError, 'No such wallpaper in database.' if options.next: if len(config['wallpapers']) - 1 > config['currentWal']: config['currentWal'] += 1 else: config['currentWal'] = 0 if options.previous: if config['currentWal'] > 0: config['currentWal'] -= 1 else: config['currentWal'] = len(config['wallpapers']) - 1 if options.random: config['currentWal'] = random.randrange(len(config['wallpapers'])) if config['currentWal'] >= len(config['wallpapers']): raise ActionError, 'Selected wallpaper not in database' os.system(tool.replace('FILENAME', config['wallpapers'][config['currentWal']])) return config
os.system(tool.replace('FILENAME', config['wallpapers'][config['currentWal']]))
os.system(tool.replace('FILENAME', "'%s'" % config['wallpapers'][config['currentWal']].replace("'","\'")))
def doAction(options, config): """ Do specified in options action and return modified config """ if options.external_tool: tool = options.external_tool else: try: tool = [tool for tool in config['tools'] if \ tool.split()[0] == (options.tool or config['defaultTool'])][0] except: raise ParseError, 'Cannot find specified tool in database' if options.export: for wal in config['wallpapers']: print wal return config if options.add: if not os.path.exists(options.add): raise ActionError, 'File doesn\'t exist' fileList = makeWallpapersList(options.add) for fileName in fileList: if not fileName in config['wallpapers']: config['wallpapers'].append(fileName) return config if options.remove_current: options.remove = config['currentWal'] if not options.remove is None and options.remove != '': try: path = config['wallpapers'][int(options.remove)] except IndexError: raise ActionError, 'No such wallpaper in database.' except ValueError: if not os.path.exists(path): raise ActionError, 'File doesn\'t exist' fileList = makeWallpapersList(path) for fileName in fileList: config['wallpapers'].remove(fileName) return config if options.clear: config['wallpapers'] = [] config['currentWal'] = 0 return config if options.file: os.system(tool.replace('FILENAME', options.file)) return config if not config['wallpapers']: raise ActionError, 'The wallpapers database is empty. Use --add option to add images.' if options.number: if options.number < len(config['wallpapers']): config['currentWal'] = options.number else: raise ActionError, 'No such wallpaper in database.' if options.next: if len(config['wallpapers']) - 1 > config['currentWal']: config['currentWal'] += 1 else: config['currentWal'] = 0 if options.previous: if config['currentWal'] > 0: config['currentWal'] -= 1 else: config['currentWal'] = len(config['wallpapers']) - 1 if options.random: config['currentWal'] = random.randrange(len(config['wallpapers'])) if config['currentWal'] >= len(config['wallpapers']): raise ActionError, 'Selected wallpaper not in database' os.system(tool.replace('FILENAME', config['wallpapers'][config['currentWal']])) return config
self.NbrJobsSignal = Signal()
def __init__(self): """ """ self.__label = "Un moment..." self.startSignal = Signal() self.refreshSignal = Signal() self.finishSignal = Signal()
else: if os.path.splitext(File)[1] in config.Extensions: AlsoProcess+=1
def start(self,List): """ Lance les calculs """ self.startSignal.emit(self.__label, max(1,len(List)))
self.NbrJobsSignal = Signal()
def __init__(self): """ """ self.__label = "Rangement photo" self.startSignal = Signal() self.refreshSignal = Signal() self.finishSignal = Signal()
if not os.path.isdir(config.SelectedDirectory): mkdir(config.SelectedDirectory)
if not os.path.isdir(SelectedDir): mkdir(SelectedDir)
def start(self,List): """ Lance les calculs """ self.startSignal.emit(self.__label, len(List))
for day in os.listdir(config.SelectedDirectory): for File in os.listdir(os.path.join(config.SelectedDirectory,day)):
for day in os.listdir(SelectedDir): for File in os.listdir(os.path.join(SelectedDir,day)):
def start(self,List): """ Lance les calculs """ self.startSignal.emit(self.__label, len(List))
if os.path.isdir(os.path.join(config.SelectedDirectory,day,File)): for ImageFile in os.listdir(os.path.join(config.SelectedDirectory,day,File)): src=os.path.join(config.SelectedDirectory,day,File,ImageFile) dst=os.path.join(config.SelectedDirectory,day,ImageFile)
if os.path.isdir(os.path.join(SelectedDir,day,File)): for ImageFile in os.listdir(os.path.join(SelectedDir,day,File)): src=os.path.join(SelectedDir,day,File,ImageFile) dst=os.path.join(SelectedDir,day,ImageFile)
def start(self,List): """ Lance les calculs """ self.startSignal.emit(self.__label, len(List))
dest=os.path.join(config.SelectedDirectory,File)
dest=os.path.join(SelectedDir,File)
def start(self,List): """ Lance les calculs """ self.startSignal.emit(self.__label, len(List))
dirs=os.listdir(config.SelectedDirectory)
dirs=os.listdir(SelectedDir)
def start(self,List): """ Lance les calculs """ self.startSignal.emit(self.__label, len(List))
pathday=os.path.join(config.SelectedDirectory,day)
pathday=os.path.join(SelectedDir,day)
def start(self,List): """ Lance les calculs """ self.startSignal.emit(self.__label, len(List))
self.pb.set_fraction(float(h+1)/self.__nbVal)
if h<self.__nbVal: self.pb.set_fraction(float(h+1)/self.__nbVal) else: self.pb.set_fraction(1.0)
def updateProgressBar(self,h,filename): """ Mise jour de la progressbar Dans le cas d'un toolkit, c'est ici qu'il faudra appeler le traitement des vnements. set the progress-bar to the given value with the given name @param h: current number of the file @type val: integer or float @param name: name of the current element @type name: string @return: None""" self.pb.set_fraction(float(h+1)/self.__nbVal) self.pb.set_text(filename) while gtk.events_pending():gtk.main_iteration()
print "Gnration des vignettes pour %s "%filename
def ScaleImage(filename): """common processing for one image : create a subfolder "scaled" and "thumb" : """ print "Gnration des vignettes pour %s "%filename config=Config() rootdir=os.path.dirname(filename) scaledir=os.path.join(rootdir,config.ScaledImages["Suffix"]) thumbdir=os.path.join(rootdir,config.Thumbnails["Suffix"]) if not os.path.isdir(scaledir) : mkdir(scaledir) if not os.path.isdir(thumbdir) : mkdir(thumbdir) Img=photo(filename) Param=config.ScaledImages.copy() Param.pop("Suffix") Param["Thumbname"]=os.path.join(scaledir,os.path.basename(filename))[:-4]+"--%s.jpg"%config.ScaledImages["Suffix"] Img.SaveThumb(**Param) Param=config.Thumbnails.copy() Param.pop("Suffix") Param["Thumbname"]=os.path.join(thumbdir,os.path.basename(filename))[:-4]+"--%s.jpg"%config.Thumbnails["Suffix"] Img.SaveThumb(**Param)
def SplitIntoPages(pathday)
def SplitIntoPages(pathday):
def SplitIntoPages(pathday) """Split a directory (pathday) into pages of 20 images""" files=[] for i in os.listdir(pathday): if os.path.splitext(i)[1] in config.Extensions:files.append(i) files.sort() if len(files)>config.NbrPerPage: pages=1+(len(files)-1)/config.NbrPerPage for i in range(1, pages+1): folder=os.path.join(pathday,config.PagePrefix+str(i)) if not os.path.isdir(folder): mkdir(folder) for j in range(len(files)): i=1+(j)/config.NbrPerPage filename=os.path.join(pathday,config.PagePrefix+str(i),files[j]) self.refreshSignal.emit(GlobalCount,files[j]) GlobalCount+=1 shutil.move(os.path.join(pathday,files[j]),filename) ScaleImage(filename,filigrane) else: for j in files: self.refreshSignal.emit(GlobalCount,j) GlobalCount+=1 ScaleImage(os.path.join(pathday,j),filigrane)
for filename in daydir
for filename in daydir:
def SplitIntoPages(pathday) """Split a directory (pathday) into pages of 20 images""" files=[] for i in os.listdir(pathday): if os.path.splitext(i)[1] in config.Extensions:files.append(i) files.sort() if len(files)>config.NbrPerPage: pages=1+(len(files)-1)/config.NbrPerPage for i in range(1, pages+1): folder=os.path.join(pathday,config.PagePrefix+str(i)) if not os.path.isdir(folder): mkdir(folder) for j in range(len(files)): i=1+(j)/config.NbrPerPage filename=os.path.join(pathday,config.PagePrefix+str(i),files[j]) self.refreshSignal.emit(GlobalCount,files[j]) GlobalCount+=1 shutil.move(os.path.join(pathday,files[j]),filename) ScaleImage(filename,filigrane) else: for j in files: self.refreshSignal.emit(GlobalCount,j) GlobalCount+=1 ScaleImage(os.path.join(pathday,j),filigrane)
filename=os.path.join(pathday,PagePrefix+str(i),files[j])
filename=os.path.join(pathday,config.PagePrefix+str(i),files[j])
def start(self,List): """ Lance les calculs """ self.startSignal.emit(self.__label, len(List))
x,y=self.taille() return x-y
self.taille() return self.x-self.y
def larg(self): """width-height of a jpeg file""" x,y=self.taille() return x-y
return self.x,self.y
def taille(self): """width and height of a jpeg file""" self.LoadPIL() self.x,self.y=self.f.size return self.x,self.y
config=Config() Trashdir=os.path.join(config.DefaultRepository,config.TrashDirectory)
Trashdir=os.path.join(self.config.DefaultRepository,self.config.TrashDirectory)
def Trash(self): """Send the file to the trash folder""" config=Config() Trashdir=os.path.join(config.DefaultRepository,config.TrashDirectory) td=os.path.dirname(os.path.join(Trashdir,self.filename)) tf=os.path.join(Trashdir,self.filename) if not os.path.isdir(td): makedir(td) shutil.move(self.fn,os.path.join(Trashdir,self.filename))
x,y=self.taille() data["Resolution"]="%s x %s "%(x,y)
self.taille() data["Resolution"]="%s x %s "%(self.x,self.y)
def exif(self): """return exif data + title from the photo""" clef={ 'Image Make': 'Marque', 'Image Model': 'Modele', 'Image DateTime': 'Heure', 'EXIF Flash':'Flash', 'EXIF FocalLength': 'Focale', 'EXIF FNumber': 'Ouverture', 'EXIF ExposureTime' :'Vitesse', 'EXIF ISOSpeedRatings': 'Iso', 'EXIF ExposureBiasValue': 'Bias'}
self.x,self.y=self.taille()
self.taille()
def show(self,Xsize=600,Ysize=600): """return a pixbuf to shows the image in a Gtk window""" self.x,self.y=self.taille() pixbuf = gtk.gdk.pixbuf_new_from_file(self.fn) if self.x>Xsize: RX=1.0*Xsize/self.x else : RX=1 if self.y>Ysize: RY=1.0*Ysize/self.y else : RY=1 R=min(RY,RX) if R<1: nx=int(R*self.x) ny=int(R*self.y) scaled_buf=pixbuf.scale_simple(nx,ny,gtkInterpolation[self.config.Interpolation]) else : scaled_buf=pixbuf return scaled_buf
if self.x>Xsize: RX=1.0*Xsize/self.x else : RX=1 if self.y>Ysize: RY=1.0*Ysize/self.y else : RY=1 R=min(RY,RX)
R=min(float(Xsize)/self.x,float(Ysize)/self.y)
def show(self,Xsize=600,Ysize=600): """return a pixbuf to shows the image in a Gtk window""" self.x,self.y=self.taille() pixbuf = gtk.gdk.pixbuf_new_from_file(self.fn) if self.x>Xsize: RX=1.0*Xsize/self.x else : RX=1 if self.y>Ysize: RY=1.0*Ysize/self.y else : RY=1 R=min(RY,RX) if R<1: nx=int(R*self.x) ny=int(R*self.y) scaled_buf=pixbuf.scale_simple(nx,ny,gtkInterpolation[self.config.Interpolation]) else : scaled_buf=pixbuf return scaled_buf
config=Config()
def ContrastMask(self,outfile): """Ceci est un filtre de debouchage de photographies, aussi appel masque de contraste, il permet de rattrapper une photo trop contrast, un contre jour, ... crit par Jrme Kieffer, avec l'aide de la liste python@aful, en particulier A. Fayolles et F. Mantegazza avril 2006 necessite numarray et PIL.""" import ImageChops try: import numarray except: raise "This filter needs the numarray library available on http://www.stsci.edu/resources/software_hardware/numarray" config=Config() self.LoadPIL() x,y=self.f.size img_array = numarray.fromstring(self.f.tostring(),type="UInt8").astype("UInt16") img_array.shape = (x, y, 3) red, green, blue = img_array[:,:,0], img_array[:,:,1],img_array[:,:,2] desat_array = (numarray.minimum(numarray.minimum(red, green), blue) + numarray.maximum( numarray.maximum(red, green), blue))/2 inv_desat=255-desat_array k=Image.fromstring("L",(x,y),inv_desat.astype("UInt8").tostring()).convert("RGB") S=ImageChops.screen(self.f,k) M=ImageChops.multiply(self.f,k) F=ImageChops.add(ImageChops.multiply(self.f,S),ImageChops.multiply(ImageChops.invert(self.f),M)) F.save(os.path.join(config.DefaultRepository,outfile),quality=90,progressive=True,Optimize=True)
F.save(os.path.join(config.DefaultRepository,outfile),quality=90,progressive=True,Optimize=True)
F.save(os.path.join(self.config.DefaultRepository,outfile),quality=90,progressive=True,Optimize=True) os.chmod(os.path.join(self.config.DefaultRepository,outfile),self.config.DefaultFileMode)
def ContrastMask(self,outfile): """Ceci est un filtre de debouchage de photographies, aussi appel masque de contraste, il permet de rattrapper une photo trop contrast, un contre jour, ... crit par Jrme Kieffer, avec l'aide de la liste python@aful, en particulier A. Fayolles et F. Mantegazza avril 2006 necessite numarray et PIL.""" import ImageChops try: import numarray except: raise "This filter needs the numarray library available on http://www.stsci.edu/resources/software_hardware/numarray" config=Config() self.LoadPIL() x,y=self.f.size img_array = numarray.fromstring(self.f.tostring(),type="UInt8").astype("UInt16") img_array.shape = (x, y, 3) red, green, blue = img_array[:,:,0], img_array[:,:,1],img_array[:,:,2] desat_array = (numarray.minimum(numarray.minimum(red, green), blue) + numarray.maximum( numarray.maximum(red, green), blue))/2 inv_desat=255-desat_array k=Image.fromstring("L",(x,y),inv_desat.astype("UInt8").tostring()).convert("RGB") S=ImageChops.screen(self.f,k) M=ImageChops.multiply(self.f,k) F=ImageChops.add(ImageChops.multiply(self.f,S),ImageChops.multiply(ImageChops.invert(self.f),M)) F.save(os.path.join(config.DefaultRepository,outfile),quality=90,progressive=True,Optimize=True)
self.startSignal.emit(self.__label, len(List))
self.startSignal.emit(self.__label, max(1,len(List)))
def start(self,List): """ Lance les calculs """ self.startSignal.emit(self.__label, len(List))
if (os.path.isdir(src)) and (os.path.split(src)[1] in [scaled,thumb]):
if (os.path.isdir(src)) and (os.path.split(src)[1] in [config.ScaledImages["Suffix"],config.Thumbnails["Suffix"]]):
def start(self,List): """ Lance les calculs """ self.startSignal.emit(self.__label, len(List))
class ModelProcessSelected: """Implemantation MVC de la procedure ProcessSelected""" def __init__(self): """ """ self.__label = "Un moment..." self.startSignal = Signal() self.refreshSignal = Signal() self.finishSignal = Signal() def start(self,List): """ Lance les calculs """ self.startSignal.emit(self.__label, len(List)) config=Config() self.refreshSignal.emit(-1,"copie des fichiers existants") if not os.path.isdir(config.SelectedDirectory): mkdir(config.SelectedDirectory) for day in os.listdir(config.SelectedDirectory): for File in os.listdir(os.path.join(config.SelectedDirectory,day)): if File.find(config.PagePrefix)==0: if os.path.isdir(os.path.join(config.SelectedDirectory,day,File)): for ImageFile in os.listdir(os.path.join(config.SelectedDirectory,day,File)): src=os.path.join(config.SelectedDirectory,day,File,ImageFile) dst=os.path.join(config.SelectedDirectory,day,ImageFile) if os.path.isfile(src) and not os.path.exists(dst): shutil.move(src,dst) if (os.path.isdir(src)) and (os.path.split(src)[1] in [scaled,thumb]): shutil.rmtree(src) for File in List: dest=os.path.join(config.SelectedDirectory,File) src=os.path.join(config.DefaultRepository,File) destdir=os.path.dirname(dest) if not os.path.isdir(destdir): makedir(destdir) if not os.path.exists(dest): print "copie de %s "%(File) shutil.copy(src,dest) os.chmod(dest,config.DefaultFileMode) else : print "%s existe dja"%(dest) dirs=os.listdir(config.SelectedDirectory) dirs.sort() GlobalCount=0 for day in dirs: pathday=os.path.join(config.SelectedDirectory,day) files=[] for i in os.listdir(pathday): if i[-4:]==".jpg":files.append(i) files.sort() if len(files)>config.NbrPerPage: pages=1+(len(files)-1)/config.NbrPerPage for i in range(1, pages+1): folder=os.path.join(pathday,config.PagePrefix+str(i)) if not os.path.isdir(folder): mkdir(folder) for j in range(len(files)): i=1+(j)/config.NbrPerPage filename=os.path.join(pathday,PagePrefix+str(i),files[j]) self.refreshSignal.emit(GlobalCount,files[j]) GlobalCount+=1 shutil.move(os.path.join(pathday,files[j]),filename) ScaleImage(filename) else: for j in files: self.refreshSignal.emit(GlobalCount,j) GlobalCount+=1 ScaleImage(os.path.join(pathday,j)) self.finishSignal.emit()
see aspn.activestate.com """ def __init__(self, f): self.f = f.im_func self.c = weakref.ref(f.im_self) def __call__(self, *args, **kwargs): if self.c() == None: return self.f(self.c(), *args, **kwargs)
# def start(self):
class ModelRangeTout: """Implemantation MVC de la procedure RangeTout moves all the JPEG files to a directory named from their day and with the name according to the time""" def __init__(self): """ """ self.__label = "Rangement photo" self.startSignal = Signal() self.refreshSignal = Signal() self.finishSignal = Signal() def start(self,RootDir): """ Lance les calculs """ config=Config() AllJpegs=FindFile(RootDir) AllFilesToProcess=[] AllreadyDone=[] NewFiles=[] for i in AllJpegs: if i.find(config.TrashDirectory)==0: continue if i.find(config.SelectedDirectory)==0: continue try: a=int(i[:4]) m=int(i[5:7]) j=int(i[8:10]) if (a>=0000) and (m<=12) and (j<=31) and (i[4] in ["-","_","."]) and (i[7] in ["-","_"]): AllreadyDone.append(i) else: AllFilesToProcess.append(i) except : AllFilesToProcess.append(i) AllFilesToProcess.sort() NumFiles=len(AllFilesToProcess) self.startSignal.emit(self.__label,NumFiles) for h in range(NumFiles): i=AllFilesToProcess[h] self.refreshSignal.emit(h,i) data=photo(i).exif() try: datei,heurei=data["Heure"].split() date=re.sub(":","-",datei) heurej=re.sub(":","h",heurei,1) model=data["Modele"].split(",")[-1] heure=latin1_to_ascii("%s-%s.jpg"%(re.sub(":","m",heurej,1),re.sub("/","",re.sub(" ","_",model)))) except: date=time.strftime("%Y-%m-%d",time.gmtime(os.path.getctime(os.path.join(RootDir,i)))) heure=latin1_to_ascii("%s-%s.jpg"%(time.strftime("%Hh%Mm%S",time.gmtime(os.path.getctime(os.path.join(RootDir,i)))),re.sub("/","-",re.sub(" ","_",os.path.splitext(i)[0])))) if not (os.path.isdir(os.path.join(RootDir,date))) : mkdir(os.path.join(RootDir,date)) imagefile=os.path.join(RootDir,date,heure) ToProcess=os.path.join(date,heure) if os.path.isfile(imagefile): print "Problme ... %s existe dja "%i s=0 for j in os.listdir(os.path.join(RootDir,date)): if j.find(heure[:-4])==0:s+=1 ToProcess=os.path.join(date,heure[:-4]+"-%s.jpg"%s) imagefile=os.path.join(RootDir,ToProcess) shutil.move(os.path.join(RootDir,i),imagefile) if config.AutoRotate : photo(imagefile).autorotate() AllreadyDone.append(ToProcess) NewFiles.append(ToProcess) AllreadyDone.sort() self.finishSignal.emit() if len(NewFiles)>0: FirstImage=min(NewFiles) return AllreadyDone,AllreadyDone.index(FirstImage) else: return AllreadyDone,0 class Controler: """ Implmentation du contrleur de la vue utilisant la console""" def __init__(self, model, view): self.__view = view model.startSignal.connect(self.__startCallback) model.refreshSignal.connect(self.__refreshCallback) model.finishSignal.connect(self.__stopCallback) def __startCallback(self, label, nbVal): """ Callback pour le signal de dbut de progressbar.""" self.__view.creatProgressBar(label, nbVal) def __refreshCallback(self, i,filename): """ Mise jour de la progressbar.""" self.__view.updateProgressBar(i,filename) def __stopCallback(self): """ Callback pour le signal de fin de splashscreen.""" self.__view.finish() class ControlerX: """ Implmentation du contrleur. C'est lui qui lie les modle et la(les) vue(s).""" def __init__(self, model, viewx): self.__viewx = viewx model.startSignal.connect(self.__startCallback) model.refreshSignal.connect(self.__refreshCallback) model.finishSignal.connect(self.__stopCallback) def __startCallback(self, label, nbVal): """ Callback pour le signal de dbut de progressbar.""" self.__viewx.creatProgressBar(label, nbVal) def __refreshCallback(self, i,filename): """ Mise jour de la progressbar. """ self.__viewx.updateProgressBar(i,filename) def __stopCallback(self): """ ferme la fenetre. Callback pour le signal de fin de splashscreen.""" self.__viewx.finish() class View: """ Implmentation de la vue. Utilisation de la console. """ def __init__(self): """ On initialise la vue.""" self.__nbVal = None def creatProgressBar(self, label, nbVal): """ Cration de la progressbar. """ self.__nbVal = nbVal print label def updateProgressBar(self,h,filename): """ Mise jour de la progressbar """ print "%5.1f %% processing ... %s"%(100.0*(h+1)/self.__nbVal,filename) def finish(self): """nothin in text mode""" pass class ViewX: """ Implmentation de la vue comme un splashscren """ def __init__(self): """ On initialise la vue. Ici, on ne fait rien, car la progressbar sera cre au moment o on en aura besoin. Dans un cas rel, on initialise les widgets de l'interface graphique """ self.__nbVal = None def creatProgressBar(self, label, nbVal): """ Cration de la progressbar. """ self.xml=gtk.glade.XML(unifiedglade,root="splash") self.xml.get_widget("image").set_from_pixbuf(gtk.gdk.pixbuf_new_from_file(os.path.join(installdir,"Splash.png"))) self.pb=self.xml.get_widget("progress") self.xml.get_widget("splash").set_title(label) self.xml.get_widget("splash").show() while gtk.events_pending():gtk.main_iteration() self.__nbVal = nbVal def updateProgressBar(self,h,filename): """ Mise jour de la progressbar Dans le cas d'un toolkit, c'est ici qu'il faudra appeler le traitement des vnements. set the progress-bar to the given value with the given name @param h: current number of the file @type val: integer or float @param name: name of the current element @type name: string @return: None""" self.pb.set_fraction(float(h+1)/self.__nbVal) self.pb.set_text(filename) while gtk.events_pending():gtk.main_iteration() def finish(self): """destroys the interface of the splash screen""" self.xml.get_widget("splash").destroy() while gtk.events_pending():gtk.main_iteration() del self.xml gc.collect() def RangeTout(repository): """moves all the JPEG files to a directory named from their day and with the name according to the time This is a MVC implementation""" model = ModelRangeTout() view = View() ctrl = Controler(model, view) viewx = ViewX() ctrlx = ControlerX(model, viewx) return model.start(repository) def ProcessSelected(SelectedFiles): """This procedure uses the MVC implementation of processSelected It makes a copy of all selected photos and scales them copy all the selected files to "selected" subdirectory, 20 per page """ print "execution %s"%SelectedFiles model = ModelProcessSelected() view = View() ctrl = Controler(model, view) viewx = ViewX() ctrlx = ControlerX(model, viewx) model.start(SelectedFiles) class Config: """this class is a Borg : always returns the same values regardless to the instance of the object""" __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state def default(self): self.ScreenSize=600 self.NbrPerPage=20 self.PagePrefix="page" self.TrashDirectory="Trash" self.SelectedDirectory="Selected" self.Selected_save=".selected-photos" self.Extensions=[".jpg", ".jpeg",".jpe",".jfif"] self.AutoRotate=False self.DefaultMode="664" self.DefaultRepository=os.getcwd() self.Interpolation=1 self.DefaultFileMode=int(self.DefaultMode,8) self.DefaultDirMode=self.DefaultFileMode+3145 self.Thumbnails={ "Size":160, "Suffix": "thumb", "Interpolation":1, "Progressive":False, "Optimize":False, "ExifExtraction":True, "Quality": 75 } self.ScaledImages={ "Size":800, "Suffix": "scaled", "Interpolation":2, "Progressive":False, "Optimize":False, "ExifExtraction":False, "Quality": 75 } def load(self,filenames): """retrieves the the default options, if the filenames does not exist, uses the default instead type filenames: list of filename """ import ConfigParser config = ConfigParser.ConfigParser() self.default() files=[] for i in filenames: if os.path.isfile(i):files.append(i) if len(files)==0: print "No configuration file found. Falling back on defaults" return config.read(files) for i in config.items("Selector"): j=i[0] if j=="ScreenSize".lower():self.ScreenSize=int(i[1]) elif j=="Interpolation".lower():self.Interpolation=int(i[1]) elif j=="PagePrefix".lower():self.PagePrefix=i[1] elif j=="NbrPerPage".lower():self.NbrPerPage=int(i[1]) elif j=="TrashDirectory".lower():self.TrashDirectory=i[1] elif j=="SelectedDirectory".lower():self.SelectedDirectory=i[1] elif j=="Selected_save".lower():self.Selected_save=i[1] elif j=="AutoRotate".lower():self.AutoRotate=config.getboolean("Selector","AutoRotate") elif j=="DefaultFileMode".lower(): self.DefaultFileMode=int(i[1],8) self.DefaultDirMode=self.DefaultFileMode+3145 elif j=="Extensions".lower(): self.Extensions=i[1].split() elif j=="DefaultRepository".lower():self.DefaultRepository=i[1] else: print "unknown key "+j for k in ["ScaledImages","Thumbnails"]: try: dico=eval(k) except: dico={} for i in config.items(k): j=i[0] if j=="Size".lower():dico["Size"]=int(i[1]) elif j=="Suffix".lower():dico["Suffix"]=i[1] elif j=="Interpolation".lower():dico["Interpolation"]=int(i[1]) elif j=="Progressive".lower():dico["Progressive"]=config.getboolean(k,"Progressive") elif j=="Optimize".lower():dico["Optimize"]=config.getboolean(k,"Optimize") elif j=="ExifExtraction".lower():dico["ExifExtraction"]=config.getboolean(k,"ExifExtraction") elif j=="Quality".lower():dico["Quality"]=int(i[1]) exec("self.%s=dico"%k) def PrintConfig(self): print " print "Size on the images on the Screen:%s"%self.ScreenSize print "Downsampling quality [0..3]:\t %s"%self.Interpolation print "Page prefix:\t\t\t %s"%self.PagePrefix print "Number of images per page:\t %s"%self.NbrPerPage print "Trash directory:\t\t %s"%self.TrashDirectory print "Selected directory:\t\t %s"%self.SelectedDirectory print "Selected images file:\t\t %s"%self.Selected_save print "Use Exif for Auto-Rotate:\t %s"%self.AutoRotate print "Default mode for files (octal):\t %o"%self.DefaultFileMode print "JPEG extensions:\t\t %s"%self.Extensions print "Default photo repository:\t %s"%self.DefaultRepository print "**** Scaled images configuration ****" print "Size:\t\t\t\t %s"%self.ScaledImages["Size"] print "Suffix:\t\t\t\t %s"%self.ScaledImages["Suffix"] print "Interpolation Quality:\t\t %s"%self.ScaledImages["Interpolation"] print "Progressive JPEG:\t\t %s"%self.ScaledImages["Progressive"] print "Optimized JPEG:\t\t\t %s"%self.ScaledImages["Optimize"] print "JPEG Quality:\t\t\t %s %%"%self.ScaledImages["Quality"] print "Allow Exif extraction:\t\t %s"%self.ScaledImages["ExifExtraction"] print "**** Thumbnail images configuration ****" print "Size:\t\t\t\t %s"%self.Thumbnails["Size"] print "Suffix:\t\t\t\t %s"%self.Thumbnails["Suffix"] print "Interpolation Quality:\t\t %s"%self.Thumbnails["Interpolation"] print "Progressive JPEG:\t\t %s"%self.Thumbnails["Progressive"] print "Optimized JPEG:\t\t\t %s"%self.Thumbnails["Optimize"] print "JPEG Quality:\t\t\t %s %%"%self.Thumbnails["Quality"] print "Allow Exif extraction:\t\t %s"%self.Thumbnails["ExifExtraction"] def SaveConfig(self,filename): """saves the default options""" txt="[Selector]\n" txt+=" txt+=" txt+=" txt+=" txt+=" txt+=" txt+=" txt+=" txt+=" txt+=" for i in self.Extensions: txt+=i+" " txt+="\n\n" txt+=" for i in ["ScaledImages","Thumbnails"]: txt+="[%s]\n"%i j=eval("self.%s"%i) txt+=" txt+=" txt+=" txt+=" txt+=" txt+=" txt+=" w=open(filename,"w") w.write(txt) w.close() class photo: """class photo that does all the operations available on photos""" def __init__(self,filename): self.config=Config() self.filename=filename self.fn=os.path.join(self.config.DefaultRepository,self.filename) if not os.path.isfile(self.fn): print "Erreur, le fichier %s n'existe pas"%self.fn def LoadPIL(self): """Load the image""" self.f=Image.open(self.fn) def larg(self): """width-height of a jpeg file""" x,y=self.taille() return x-y def taille(self): """width and height of a jpeg file""" self.LoadPIL() self.x,self.y=self.f.size return self.x,self.y def SaveThumb(self,Thumbname,Size=160,Interpolation=1,Quality=75,Progressive=False,Optimize=False,ExifExtraction=False): """save a thumbnail of the given name, with the given size and the interpollation mathode (quality) resampling filters : NONE = 0 NEAREST = 0 ANTIALIAS = 1 LINEAR = BILINEAR = 2 CUBIC = BICUBIC = 3 """ if os.path.isfile(Thumbname): print "sorry, file %s exists"%Thumbname else: RawExif,comment=EXIF.process_file(open(self.fn,'rb'),0) if RawExif.has_key("JPEGThumbnail") and ExifExtraction: w=open(Thumbname,"wb") w.write(RawExif["JPEGThumbnail"]) w.close() else: self.LoadPIL() self.f.thumbnail((Size,Size),Interpolation) self.f.save(Thumbname,quality=Quality,progressive=Progressive,optimize=Optimize) os.chmod(Thumbname,self.config.DefaultFileMode) def Rotate(self,angle=0): """does a looseless rotation of the given jpeg file""" if os.name == 'nt' and self.f!=None: del self.f if angle==90: os.system('JPEGMEM=%i %s -ip -9 "%s"'%(self.x*self.y/100,exiftran,self.fn)) elif angle==270: os.system('JPEGMEM=%i %s -ip -2 "%s"'%(self.x*self.y/100,exiftran,self.fn)) elif angle==180: os.system('JPEGMEM=%i %s -ip -1 "%s"'%(self.x*self.y/100,exiftran,self.fn)) else: print "Erreur ! il n'est pas possible de faire une rotation de ce type sans perte de donne." def Trash(self): """Send the file to the trash folder""" td=os.path.dirname(os.path.join(Trashdir,self.filename)) tf=os.path.join(Trashdir,self.filename) if not os.path.isdir(td): makedir(td) shutil.move(self.fn,os.path.join(Trashdir,self.filename)) def exif(self): """return exif data + title from the photo""" clef={ 'Image Make': 'Marque', 'Image Model': 'Modele', 'Image DateTime': 'Heure', 'EXIF Flash':'Flash', 'EXIF FocalLength': 'Focale', 'EXIF FNumber': 'Ouverture', 'EXIF ExposureTime' :'Vitesse', 'EXIF ISOSpeedRatings': 'Iso', 'EXIF ExposureBiasValue': 'Bias'} data={} data["Taille"]="%s ko"%(os.path.getsize(self.fn)/1024) RawExif,comment=EXIF.process_file(open(self.fn,'rb'),0) if comment: data["Titre"]=comment else: data["Titre"]="" x,y=self.taille() data["Resolution"]="%s x %s "%(x,y) for i in clef: try: data[clef[i]]=str(RawExif[i].printable).strip() except: data[clef[i]]="" return data def show(self,Xsize=600,Ysize=600): """return a pixbuf to shows the image in a Gtk window""" self.x,self.y=self.taille() pixbuf = gtk.gdk.pixbuf_new_from_file(self.fn) if self.x>Xsize: RX=1.0*Xsize/self.x else : RX=1 if self.y>Ysize: RY=1.0*Ysize/self.y else : RY=1 R=min(RY,RX) if R<1: nx=int(R*self.x) ny=int(R*self.y) scaled_buf=pixbuf.scale_simple(nx,ny,gtkInterpolation[self.config.Interpolation]) else : scaled_buf=pixbuf return scaled_buf def name(self,titre): """write the title of the photo inside the description field, in the JPEG header""" if os.name == 'nt' and self.f!=None: del self.f os.system('%s -ipc "%s" "%s"'%(exiftran,titre,self.fn)) def autorotate(self): """does autorotate the image according to the EXIF tag""" if os.name == 'nt' and self.f!=None: del self.f self.taille() os.system('JPEGMEM=%i %s -aip "%s"'%(self.x*self.y/100,exiftran,self.fn)) def makedir(filen): """creates the tree structure for the file""" dire=os.path.dirname(filen) if os.path.isdir(dire): mkdir(filen) else: makedir(dire) mkdir(filen) def mkdir(filename): """create an empty directory with the given rights""" config=Config() os.mkdir(filename) os.chmod(filename,config.DefaultDirMode) def FindFile(RootDir): """returns a list of the files with the given suffix in the given dir files=os.system('find "%s" -iname "*.%s"'%(RootDir,suffix)).readlines() """ files=[] config=Config() for i in config.Extensions: files+=parser().FindExts(RootDir,i) good=[] l=len(RootDir)+1 for i in files: good.append(i.strip()[l:]) return good def ScaleImage(filename): """common processing for one image : create a subfolder "scaled" and "thumb" : """ print "Gnration des vignettes pour %s "%filename config=Config() rootdir=os.path.dirname(filename) scaledir=os.path.join(rootdir,config.ScaledImages["Suffix"]) thumbdir=os.path.join(rootdir,config.Thumbnails["Suffix"]) if not os.path.isdir(scaledir) : mkdir(scaledir) if not os.path.isdir(thumbdir) : mkdir(thumbdir) Img=photo(filename) Param=config.ScaledImages.copy() Param.pop("Suffix") Param["Thumbname"]=os.path.join(scaledir,os.path.basename(filename))[:-4]+"--%s.jpg"%config.ScaledImages["Suffix"] Img.SaveThumb(**Param) Param=config.Thumbnails.copy() Param.pop("Suffix") Param["Thumbname"]=os.path.join(thumbdir,os.path.basename(filename))[:-4]+"--%s.jpg"%config.Thumbnails["Suffix"] Img.SaveThumb(**Param) def latin1_to_ascii (unicrap): """This takes a UNICODE string and replaces Latin-1 characters with something equivalent in 7-bit ASCII. It returns a plain ASCII string. This function makes a best effort to convert Latin-1 characters into ASCII equivalents. It does not just strip out the Latin-1 characters. All characters in the standard 7-bit ASCII range are preserved. In the 8th bit range all the Latin-1 accented letters are converted to unaccented equivalents. Most symbol characters are converted to something meaningful. Anything not converted is deleted. """ xlate={0xc0:'A', 0xc1:'A', 0xc2:'A', 0xc3:'A', 0xc4:'A', 0xc5:'A', 0xc6:'Ae', 0xc7:'C', 0xc8:'E', 0xc9:'E', 0xca:'E', 0xcb:'E', 0xcc:'I', 0xcd:'I', 0xce:'I', 0xcf:'I', 0xd0:'Th', 0xd1:'N', 0xd2:'O', 0xd3:'O', 0xd4:'O', 0xd5:'O', 0xd6:'O', 0xd8:'O', 0xd9:'U', 0xda:'U', 0xdb:'U', 0xdc:'U', 0xdd:'Y', 0xde:'th', 0xdf:'ss', 0xe0:'a', 0xe1:'a', 0xe2:'a', 0xe3:'a', 0xe4:'a', 0xe5:'a', 0xe6:'ae', 0xe7:'c', 0xe8:'e', 0xe9:'e', 0xea:'e', 0xeb:'e', 0xec:'i', 0xed:'i', 0xee:'i', 0xef:'i', 0xf0:'th', 0xf1:'n', 0xf2:'o', 0xf3:'o', 0xf4:'o', 0xf5:'o', 0xf6:'o', 0xf8:'o', 0xf9:'u', 0xfa:'u', 0xfb:'u', 0xfc:'u', 0xfd:'y', 0xfe:'th', 0xff:'y', 0xa1:'!', 0xa2:'{cent}', 0xa3:'{pound}', 0xa4:'{currency}', 0xa5:'{yen}', 0xa6:'|', 0xa7:'{section}', 0xa8:'{umlaut}', 0xa9:'{C}', 0xaa:'{^a}', 0xab:'<<', 0xac:'{not}', 0xad:'-', 0xae:'{R}', 0xaf:'_', 0xb0:'{degrees}', 0xb1:'{+/-}', 0xb2:'{^2}', 0xb3:'{^3}', 0xb4:"'", 0xb5:'{micro}', 0xb6:'{paragraph}', 0xb7:'*', 0xb8:'{cedilla}', 0xb9:'{^1}', 0xba:'{^o}', 0xbb:'>>', 0xbc:'{1/4}', 0xbd:'{1/2}', 0xbe:'{3/4}', 0xbf:'?', 0xd7:'*', 0xf7:'/' } r=[] for i in unicrap: if xlate.has_key(ord(i)): r.append(xlate[ord(i)]) elif ord(i) >= 0x80: pass else: r.append(str(i)) return "".join(r) class parser: """this class searches all the jpeg files""" def __init__(self): self.imagelist=[] def OneDir(self,curent): """ append all the imagesfiles to the list, then goes recursively to the subdirectories""" ls=os.listdir(curent) subdirs=[] for i in ls: a=os.path.join(curent,i) if os.path.isdir(a): self.OneDir(a) if os.path.isfile(a): if i[(-len(self.suffix)):].lower()==self.suffix: self.imagelist.append(os.path.join(curent,i)) def FindExts(self,root,suffix): self.root=root self.suffix=suffix self.OneDir(self.root) return self.imagelist if __name__ == "__main__": config=Config() config.load(ConfFile) config.DefaultRepository=os.path.abspath(sys.argv[1]) print config.DefaultRepository RangeTout(sys.argv[1])
def start(self,List): """ Lance les calculs """ self.startSignal.emit(self.__label, len(List))
def runcmd(args):
def runcmd(args, mode = Commands):
def runcmd(args): args = [ commands.mkarg(arg) for arg in args ] cmd = " ".join(args) # t = time.time() # print("Executing '%s'." % cmd) (exitstatus, output) = commands.getstatusoutput(cmd) if exitstatus != 0: raise SVKError(cmd, exitstatus >> 8, output) # print("'%s' executed in %s" % (cmd, time.time() - t)) return output
output = None
def runcmd(args): args = [ commands.mkarg(arg) for arg in args ] cmd = " ".join(args) # t = time.time() # print("Executing '%s'." % cmd) (exitstatus, output) = commands.getstatusoutput(cmd) if exitstatus != 0: raise SVKError(cmd, exitstatus >> 8, output) # print("'%s' executed in %s" % (cmd, time.time() - t)) return output
(exitstatus, output) = commands.getstatusoutput(cmd)
if mode == Commands: (exitstatus, output) = commands.getstatusoutput(cmd) exitstatus >>= 8 elif mode == System: exitstatus = os.system(cmd)
def runcmd(args): args = [ commands.mkarg(arg) for arg in args ] cmd = " ".join(args) # t = time.time() # print("Executing '%s'." % cmd) (exitstatus, output) = commands.getstatusoutput(cmd) if exitstatus != 0: raise SVKError(cmd, exitstatus >> 8, output) # print("'%s' executed in %s" % (cmd, time.time() - t)) return output
raise SVKError(cmd, exitstatus >> 8, output)
raise SVKError(cmd, exitstatus, output)
def runcmd(args): args = [ commands.mkarg(arg) for arg in args ] cmd = " ".join(args) # t = time.time() # print("Executing '%s'." % cmd) (exitstatus, output) = commands.getstatusoutput(cmd) if exitstatus != 0: raise SVKError(cmd, exitstatus >> 8, output) # print("'%s' executed in %s" % (cmd, time.time() - t)) return output
def getexternals(path): svnpath = findsvnpath(finddepotpath(path))
def findcopypath(path): info = runcmd([Config.svk, 'info', path]) infodict = {} for line in info.splitlines(): (key, value) = line.split(": ") infodict[key] = value return '/'+infodict['Copied From'].split(', ')[0] def getexternals(path, depotpath): if not depotpath: depotpath = finddepotpath(path) svnpath = findsvnpath(depotpath) if not svnpath: return
def getexternals(path): svnpath = findsvnpath(finddepotpath(path)) def findexternals(arg, dirname, fnames): import re args = [ Config.svn, 'propget', 'svn:externals', re.sub("^%s" % path, svnpath, dirname) ] try: dirext = runcmd(args) except SVKError: return if dirext == '': return import re for line in re.split('[\n\r]*', dirext): if line == '': continue (dest, src) = line.split() arg.append((os.path.join(dirname, dest), src)) externals = [] os.path.walk(path, findexternals, externals) return externals
def handleexternals(path, handler):
def handleexternals(path, handler, depotpath):
def handleexternals(path, handler): extcache = [] toclist = gettocfiles(path) for toc in toclist: tocdir = os.path.dirname(toc) extdestdir = os.path.dirname(tocdir) externals = getexternals(path) for ext,upstream in externals: if upstream in extcache: continue mipath = None for url in mi.byvalue.keys(): i = upstream.replace('svn.wowace.com', 'dev.wowace.com') i = i.replace('www.wowace.com/svn/ace', 'dev.wowace.com/wowace') i = i.replace('www.wowace.com/svn/wowace', 'dev.wowace.com/wowace') # print('i is "%s", url is "%s"' % (i, url)) if i.startswith(url): mipath = mi.byvalue[url] rest = i[len(url)+1:] if rest.endswith('/'): rest = rest[:-1] break if not mipath: raise Exception("Unable to checkout %s, as %s is not yet mirrored." % (path, upstream)) extstandalone = None for st in standalones.keys(): if rest.startswith(st): extstandalone = standalones[st] if not extstandalone: print("Error: the standalone lib translation table does not have an") print("entry for '%s'." % rest) return if not extstandalone in extcache: rest = extstandalone extdest = os.path.join(extdestdir, os.path.basename(extstandalone)) handler(os.path.join(mipath, rest), extdest) extcache.append(extstandalone)
externals = getexternals(path)
externals = getexternals(tocdir, tocdir.replace(path, depotpath)) if not externals: continue
def handleexternals(path, handler): extcache = [] toclist = gettocfiles(path) for toc in toclist: tocdir = os.path.dirname(toc) extdestdir = os.path.dirname(tocdir) externals = getexternals(path) for ext,upstream in externals: if upstream in extcache: continue mipath = None for url in mi.byvalue.keys(): i = upstream.replace('svn.wowace.com', 'dev.wowace.com') i = i.replace('www.wowace.com/svn/ace', 'dev.wowace.com/wowace') i = i.replace('www.wowace.com/svn/wowace', 'dev.wowace.com/wowace') # print('i is "%s", url is "%s"' % (i, url)) if i.startswith(url): mipath = mi.byvalue[url] rest = i[len(url)+1:] if rest.endswith('/'): rest = rest[:-1] break if not mipath: raise Exception("Unable to checkout %s, as %s is not yet mirrored." % (path, upstream)) extstandalone = None for st in standalones.keys(): if rest.startswith(st): extstandalone = standalones[st] if not extstandalone: print("Error: the standalone lib translation table does not have an") print("entry for '%s'." % rest) return if not extstandalone in extcache: rest = extstandalone extdest = os.path.join(extdestdir, os.path.basename(extstandalone)) handler(os.path.join(mipath, rest), extdest) extcache.append(extstandalone)
return getlastpath('Copied From')
return getlastpath(path, 'Copied From')
def findcopypath(path): return getlastpath('Copied From')
return getlastpath('Merged From')
return getlastpath(path, 'Merged From')
def getlastmergepath(path): return getlastpath('Merged From')
import types
import types, re
def getsvkinfo(path): if not infos.get(path): import types info = runcmd([Config.svk, 'info', path]) infodict = {} for line in info.splitlines(): fields = line.split(": ") if len(fields) != 2: sys.__stderr__.write("Unexpected number of fields in line `%s', skipping." % line) continue key = fields[1] value = fields[2] val = infodict.get(key) if val: if type(val) == types.ListType: val.append(value) else: infodict[key] = [val, value] else: infodict[key] = value infos[path] = infodict return infos[path]
fields = line.split(": ") if len(fields) != 2: sys.__stderr__.write("Unexpected number of fields in line `%s', skipping." % line) continue key = fields[1] value = fields[2]
m = re.match('([^:]+): (.*)$', line) key = m.group(1) value = m.group(2)
def getsvkinfo(path): if not infos.get(path): import types info = runcmd([Config.svk, 'info', path]) infodict = {} for line in info.splitlines(): fields = line.split(": ") if len(fields) != 2: sys.__stderr__.write("Unexpected number of fields in line `%s', skipping." % line) continue key = fields[1] value = fields[2] val = infodict.get(key) if val: if type(val) == types.ListType: val.append(value) else: infodict[key] = [val, value] else: infodict[key] = value infos[path] = infodict return infos[path]
path = "notes/active/"
def __init__(self): path = "notes/active/" for note in os.listdir(path): if os.path.isfile(os.path.join(path,note)): self.noteList.append(self.loadNote(note))
if os.path.isfile(os.path.join(path,note)): self.noteList.append(self.loadNote(note))
filepath = os.path.join(path,note) if os.path.isfile(filepath): self.loadNote(filepath)
def __init__(self): path = "notes/active/" for note in os.listdir(path): if os.path.isfile(os.path.join(path,note)): self.noteList.append(self.loadNote(note))
note = cPickle.load(open("notes/active/%s" % file,"rb")) note.text = decompress(note.text)
note = cPickle.load(open(file,"rb")) note.setFilepath(file) note.setText(decompress(note.getText())) if note not in self.noteList: self.noteList.append(note)
def loadNote(self,file): note = cPickle.load(open("notes/active/%s" % file,"rb")) note.text = decompress(note.text) return note
if note not in self.noteList: self.noteList.append(note)
def saveNote(self,note): if note not in self.noteList: self.noteList.append(note)
note.text = compress(note.text)
self.removeNote(note) if note.getText() != "": note.setFilepath("") note.setText(compress(note.getText()))
def saveNote(self,note): if note not in self.noteList: self.noteList.append(note)
cFile = StringIO() cPickle.dump(note,cFile,-1) nFile = file("notes/active/%s" % md5.new(cFile.getvalue()).hexdigest(),"wb") nFile.write(cFile.getvalue()) nFile.close() cFile.close()
cFile = StringIO() cPickle.dump(note,cFile,-1)
def saveNote(self,note): if note not in self.noteList: self.noteList.append(note)
note.text = decompress(note.text)
filepath = os.path.join(path,md5.new(cFile.getvalue()).hexdigest()) nFile = file(filepath,"wb") nFile.write(cFile.getvalue()) nFile.close() cFile.close() note = self.loadNote(filepath)
def saveNote(self,note): if note not in self.noteList: self.noteList.append(note)
note.setText(decompress(note.getText()))
note.setText(unicode(decompress(note.getText()),'utf-8'))
def loadNote(self,file): note = cPickle.load(open(file,"rb")) note.setFilepath(file) note.setText(decompress(note.getText()))
note.setText(compress(note.getText()))
note.setText(compress(note.getText().encode('utf-8')))
def saveNote(self,note):
os._exit()
os._exit(0)
def run(self, result=None): if result is None: result = self.defaultTestResult() c2pread, c2pwrite = os.pipe() # fixme - error -> result # now fork pid = os.fork() if pid == 0: # Child # Close parent's pipe ends os.close(c2pread) # Dup fds for child os.dup2(c2pwrite, 1) # Close pipe fds. os.close(c2pwrite)
self.text.LoadFile(filename)
self.text.SetValue(open(filename).read())
def Open(self, filename): self.filename = filename self.text.LoadFile(filename)
recent.Append(ID_RECENT_FILES+i, f)
recent.Append(ID_RECENT_FILES+i, os.path.basename(f))
def InitMenu(self): menu = (('&File', (('&New', wx.ID_NEW, self.OnNew), ('&Open', wx.ID_OPEN, self.OnOpen), ('&Save', wx.ID_SAVE, self.OnSave), ('Save as...', wx.ID_SAVEAS, self.OnSaveAs), None, ('&Close', wx.ID_CLOSE, self.OnClose), ('Close all', wx.ID_CLOSE_ALL, self.OnCloseAll), ('E&xit', wx.ID_EXIT, self.OnExit))), ('&Edit', (('Undo', wx.ID_UNDO, self.OnUndo), ('Redo', wx.ID_REDO, self.OnRedo), None, ('Cut', wx.ID_CUT, self.OnCut), ('Copy', wx.ID_COPY, self.OnCopy), ('Paste', wx.ID_PASTE, self.OnPaste), None, ('Goto...', ID_GOTO, self.OnGoto), ('Search...', ID_SEARCH, self.OnSearch), ('Replace...', ID_REPLACE, self.OnReplace)))) mbar = wx.MenuBar() self._populate_menubar(mbar, menu) recent = wx.Menu() for i, f in enumerate(self.recent[::-1]): recent.Append(ID_RECENT_FILES+i, f) wx.EVT_MENU(self, ID_RECENT_FILES+i, self.OnOpenRecent) mbar.GetMenu(0).AppendSeparator() mbar.GetMenu(0).AppendMenu(ID_RECENT, '&Recent', recent) self.SetMenuBar(mbar)
self.Load(self.recent[evt.GetId()-ID_RECENT_FILES])
self.Load(self.recent[ID_RECENT_FILES-evt.GetId()-1])
def OnOpenRecent(self, evt): self.Load(self.recent[evt.GetId()-ID_RECENT_FILES])
if filename in self.recent: self.recent.remove(filename) self.recent.append(filename)
absname = os.path.abspath(filename) if absname in self.recent: self.recent.remove(absname) self.recent.append(absname)
def Load(self, filename): SrcFrame.create(self, filename) if filename in self.recent: self.recent.remove(filename) self.recent.append(filename)
pass
sel = self.book.GetSelection() if sel != -1: if self.book.GetPage(sel).text.CanRedo(): self.book.GetPage(sel).text.Redo() else: print 'No Redo available'
def OnRedo(self, evt): pass
self.clip = self.book.GetPage(sel).text.Copy(True)
self.clip = self.book.GetPage(sel).text.Cut()
def OnCut(self, evt): sel = self.book.GetSelection() if sel != -1: self.clip = self.book.GetPage(sel).text.Copy(True)
self.clip = self.book.GetPage(sel).text.Paste(self.clip)
self.clip = self.book.GetPage(sel).text.Paste()
def OnPaste(self, evt): sel = self.book.GetSelection() if sel != -1: self.clip = self.book.GetPage(sel).text.Paste(self.clip)
self.book.SetSelection(0)
if self.book.GetPageCount() > 0: self.book.SetSelection(0)
def ClosePage(self, index): if self.book.GetPage(index).text.IsModified(): return False else: success = self.book.DeletePage(index) self.book.SetSelection(0) return success
if s.is_dirty():
if self.__stores[s].is_dirty():
def is_dirty(self): for s in self.__stores: if s.is_dirty(): return 1 return 0
self.samenext.is_sensitive(1)
self.sameButton.set_sensitive(1)
def savenext(self, obj): try: self.save(obj) except NotValid: self.error("Data not valid") return UI.save_previous(self, item) self.samenext.is_sensitive(1) self.next(obj) self.saveable(self.stores.is_dirty())
self.next(obj)
self.savenext(obj)
def samenext(self, obj): item = UI.get_previous(self) self.title.entry.set_text(item.get_title(1)) self.__textview_set(self.desc, item.get_description(1)) self.next(obj)