def setupArgs(self, ctrlName, params, dontEval, evalDct): """ Create a dictionary of parameters for the constructor of the control from a dictionary of string/source parameters. Catches design time parameter overrides. """ args = {} # Build dictionary of params for paramKey in params.keys(): value = params[paramKey] ## function references in the constructor #if len(value) >= 11 and value[:11] == 'self._init_': # continue # collItem = methodparse.CollectionInitParse(value) # self.addCollView(paramKey, collItem.method, False) if paramKey in dontEval: args[paramKey] = params[paramKey] else: try: args[paramKey] = PaletteMapping.evalCtrl(params[paramKey], evalDct) except AttributeError: args[paramKey] = PaletteMapping.evalCtrl(params[paramKey], {'self': self.controllerView.objectNamespace}) return args
def readCustomClasses(self, mod, cls): """ Read definition for Custom Classes Custom Classes can be defined as a class attribute named _custom_classes containing a dictionary defining wxPython classes and their custom equivalents, e.g. _custom_classes = {'wx.TreeCtrl': ['MyTreeCtrl', 'AdvancedTreeCtrl']} These custom classes will then be available to the Designer and will act as equivalent to the corresponding wxPython class, but will generate source for the custom definition. One implication is that you loose the constructor. Because Boa will generate the creation code for the object, the constructor signature has to be the same as the wxPython class. """ res = {} if cls.class_attributes.has_key('_custom_classes'): try: import PaletteMapping cls_attr = cls.class_attributes['_custom_classes'][0] attr_val = cls_attr.signature srcline = cls_attr.start # multiline parser ;) while 1: try: custClasses = PaletteMapping.evalCtrl(attr_val, preserveExc=True) assert type(custClasses) == type({}) break except SyntaxError, err: if err[0] == 'unexpected EOF while parsing': attr_val = attr_val + mod.source[srcline].strip() srcline = srcline + 1 else: raise except Exception, err: raise Exception, _('_custom_classes is not valid: ') + str(err) for wxClassName, customs in custClasses.items(): wxClass = PaletteMapping.evalCtrl(wxClassName) res[wxClassName] = wxClass for custom in customs: # to combine frame attrs with custom classes a phony # self object is created to resolve the class name # during frame creation if custom.startswith('self.'): if not 'self' in res: res['self'] = _your_frame_attrs_() setattr(res['self'], custom[5:], wxClass) else: res[custom] = wxClass
def readCustomClasses(self, mod, cls): """ Read definition for Custom Classes Custom Classes can be defined as a class attribute named _custom_classes containing a dictionary defining wxPython classes and their custom equivalents, e.g. _custom_classes = {'wx.TreeCtrl': ['MyTreeCtrl', 'AdvancedTreeCtrl']} These custom classes will then be available to the Designer and will act as equivalent to the corresponding wxPython class, but will generate source for the custom definition. One implication is that you loose the constructor. Because Boa will generate the creation code for the object, the constructor signature has to be the same as the wxPython class. """ res = {} if cls.class_attributes.has_key('_custom_classes'): try: import PaletteMapping cls_attr = cls.class_attributes['_custom_classes'][0] attr_val = cls_attr.signature srcline = cls_attr.start # multiline parser ;) while 1: try: custClasses = PaletteMapping.evalCtrl(attr_val, preserveExc=True) assert type(custClasses) == type({}) break except SyntaxError, err: if err[0] == 'unexpected EOF while parsing': attr_val = attr_val + mod.source[srcline].strip() srcline = srcline + 1 else: raise except Exception, err: raise Exception, _('_custom_classes is not valid: ')+str(err) for wxClassName, customs in custClasses.items(): wxClass = PaletteMapping.evalCtrl(wxClassName) res[wxClassName] = wxClass for custom in customs: # to combine frame attrs with custom classes a phony # self object is created to resolve the class name # during frame creation if custom.startswith('self.'): if not 'self' in res: res['self'] = _your_frame_attrs_() setattr(res['self'], custom[5:], wxClass) else: res[custom] = wxClass
def refreshCtrl(self): self.DeleteAllItems() if self.model.objectCollections.has_key(self.collectionMethod): objCol = self.model.objectCollections[self.collectionMethod] objCol.indexOnCtrlName() else: objCol = ObjCollection.ObjectCollection() creators = {} for ctrl in objCol.creators: if ctrl.comp_name: creators[ctrl.comp_name] = ctrl for name in self.objectOrder: idx = -1 ctrl = creators[name] className = ctrl.class_name try: ClassObj = PaletteMapping.evalCtrl(className) except NameError: if className in self.model.customClasses: ClassObj = self.model.customClasses[className] else: idx = self.il.Add(PaletteStore.bitmapForComponent(className, 'Component')) else: className = ClassObj.__name__ if idx == -1: idx = self.il.Add(PaletteStore.bitmapForComponent(ClassObj)) self.InsertImageStringItem(self.GetItemCount(), '%s : %s' % ( ctrl.comp_name, className), idx) self.opened = True
def initObjProps(self, props, name, creator, dependents, depLinks): """ Initialise property list by evaluating 1st parameter and calling prop's setter with it. Also associate companion name with prop parse objs """ # XXX creator not used if props.has_key(name): comp, ctrl = self.objects[name][0:2] # initialise live component's properies for prop in props[name]: prop.prop_name = comp.getPropNameFromSetter(prop.prop_setter) # Dependent properties if prop.prop_name in comp.dependentProps(): self.addDepLink(prop, name, dependents, depLinks) # Collection initialisers elif len(prop.params) and prop.params[0][:11] == 'self._init_': collItem = methodparse.CollectionInitParse(prop.params[0]) self.addCollView(name, collItem.method, False) # Check for custom evaluator elif comp.customPropEvaluators.has_key(prop.prop_name): args = comp.customPropEvaluators[prop.prop_name]( prop.params, self.getAllObjects()) # XXX This is a hack !!! # XXX argument list with more than one prop value are # XXX initialised thru the companion instead of the control if prop.prop_name in comp.initPropsThruCompanion: getattr(comp, prop.prop_setter)(*(args, )) else: getattr(ctrl, prop.prop_setter)(*args) # Check for pops which don't update the control elif prop.prop_name in comp.onlyPersistProps(): continue # Normal property, eval value and apply it else: try: value = PaletteMapping.evalCtrl( prop.params[0], self.model.specialAttrs) except AttributeError, name: value = PaletteMapping.evalCtrl( prop.params[0], {'self': self.controllerView.objectNamespace}) except: print _('Problem with: %s') % prop.asText() raise
def initObjProps(self, props, name, creator, dependents, depLinks): """ Initialise property list by evaluating 1st parameter and calling prop's setter with it. Also associate companion name with prop parse objs """ # XXX creator not used if props.has_key(name): comp, ctrl = self.objects[name][0:2] # initialise live component's properies for prop in props[name]: prop.prop_name = comp.getPropNameFromSetter(prop.prop_setter) # Dependent properties if prop.prop_name in comp.dependentProps(): self.addDepLink(prop, name, dependents, depLinks) # Collection initialisers elif len(prop.params) and prop.params[0][:11] == 'self._init_': collItem = methodparse.CollectionInitParse(prop.params[0]) self.addCollView(name, collItem.method, False) # Check for custom evaluator elif comp.customPropEvaluators.has_key(prop.prop_name): args = comp.customPropEvaluators[prop.prop_name](prop.params, self.getAllObjects()) # XXX This is a hack !!! # XXX argument list with more than one prop value are # XXX initialised thru the companion instead of the control if prop.prop_name in comp.initPropsThruCompanion: getattr(comp, prop.prop_setter)(*(args,)) else: getattr(ctrl, prop.prop_setter)(*args) # Check for pops which don't update the control elif prop.prop_name in comp.onlyPersistProps(): continue # Normal property, eval value and apply it else: try: value = PaletteMapping.evalCtrl(prop.params[0], self.model.specialAttrs) except AttributeError, name: value = PaletteMapping.evalCtrl(prop.params[0], {'self': self.controllerView.objectNamespace}) except: print _('Problem with: %s') % prop.asText() raise
def initObjCreator(self, constrPrs): # Assumes all design time ctrls are imported in global scope try: ctrlClass = PaletteMapping.evalCtrl(constrPrs.class_name, self.model.customClasses) except NameError: raise DesignerError, \ _('%s is not defined on the Palette.')%constrPrs.class_name try: ctrlCompnClass = PaletteMapping.compInfo[ctrlClass][1] except KeyError: raise DesignerError, \ _('%s is not defined on the Palette.')%ctrlClass.__name__ else: ctrlName = self.loadControl(ctrlClass, ctrlCompnClass, constrPrs.comp_name, constrPrs.params) ctrlCompn = self.objects[ctrlName][0] ctrlCompn.setConstr(constrPrs)
def refreshCtrl(self): self.DeleteAllItems() if self.model.objectCollections.has_key(self.collectionMethod): objCol = self.model.objectCollections[self.collectionMethod] objCol.indexOnCtrlName() else: objCol = ObjCollection.ObjectCollection() creators = {} for ctrl in objCol.creators: if ctrl.comp_name: creators[ctrl.comp_name] = ctrl for name in self.objectOrder: idx = -1 ctrl = creators[name] className = ctrl.class_name try: ClassObj = PaletteMapping.evalCtrl(className) except NameError: if className in self.model.customClasses: ClassObj = self.model.customClasses[className] else: idx = self.il.Add( PaletteStore.bitmapForComponent( className, 'Component')) else: className = ClassObj.__name__ if idx == -1: idx = self.il.Add(PaletteStore.bitmapForComponent(ClassObj)) self.InsertImageStringItem(self.GetItemCount(), '%s : %s' % (ctrl.comp_name, className), idx) self.opened = True
def eval(self, expr): import PaletteMapping return PaletteMapping.evalCtrl(expr, vars(Preferences))
class BaseFrameModel(ClassModel): """ Base class for all frame type models that can be opened in the Designer This class is responsible for parsing the _init_* methods generated by the Designer and maintaining other special values like window id declarations """ modelIdentifier = 'Frames' dialogLook = False Companion = BaseCompanions.DesignTimeCompanion def __init__(self, data, name, main, editor, saved, app=None): ClassModel.__init__(self, data, name, main, editor, saved, app) self.designerTool = None self.specialAttrs = {} self.defCreateClass = sourceconst.defCreateClass self.defClass = sourceconst.defClass self.defImport = sourceconst.defImport self.defWindowIds = sourceconst.defWindowIds self.defSrcVals = {} def renameMain(self, oldName, newName): """ Rename the main class of the module """ ClassModel.renameMain(self, oldName, newName) if self.getModule().functions.has_key('create'): self.getModule().replaceFunctionBody( 'create', [' return %s(parent)' % newName, '']) def renameCtrl(self, oldName, newName): # Currently DesignerView maintains ctrls pass def new(self, params): """ Create a new frame module """ paramLst = [] for param in params.keys(): paramLst.append(Preferences.cgKeywordArgFormat % { 'keyword': param, 'value': params[param] }) # XXX Refactor line wrappers to Utils and wrap this paramStr = 'self, ' + ', '.join(paramLst) srcValsDict = { 'modelIdent': self.modelIdentifier, 'main': self.main, 'idNames': Utils.windowIdentifier(self.main, ''), 'idIdent': sourceconst.init_ctrls, 'idCount': 1, 'defaultName': self.defaultName, 'params': paramStr } srcValsDict.update(self.defSrcVals) self.data = (sourceconst.defSig + self.defImport + \ self.defCreateClass + self.defWindowIds + \ self.defClass) % srcValsDict self.savedAs = False self.modified = True self.initModule() self.notify() def identifyCollectionMethods(self): """ Return a list of all _init_* methods in the class """ results = [] module = self.getModule() if module.classes.has_key(self.main): main = module.classes[self.main] for meth in main.methods.keys(): if len(meth) > len('_init_') and meth[:6] == '_init_': results.append(meth) return results def allObjects(self): views = ['Data', 'Designer'] order = [] objs = {} for view in views: order.extend(self.views[view].objectOrder) objs.update(self.views[view].objects) return order, objs def readDesignerMethod(self, meth, codeBody): """ Create a new ObjectCollection by parsing the given method body """ from Views import ObjCollection import methodparse # Collection method if ObjCollection.isInitCollMeth(meth): ctrlName = methodparse.ctrlNameFromMeth(meth) try: res = Utils.split_seq(codeBody, '', string.strip) inits, body, fins = res[:3] except ValueError: raise Exception, _( 'Collection body %s not in init, body, fin form') % meth allInitialisers, unmatched = methodparse.parseMixedBody(\ [methodparse.EventParse, methodparse.CollectionItemInitParse],body) creators = allInitialisers.get(methodparse.CollectionItemInitParse, []) collectionInits = [] properties = [] events = allInitialisers.get(methodparse.EventParse, []) methodparse.decorateParseItems(creators + events, ctrlName, self.main) # Normal method else: inits = [] fins = [] allInitialisers, unmatched = methodparse.parseMixedBody(\ [methodparse.ConstructorParse, methodparse.EventParse, methodparse.CollectionInitParse, methodparse.PropertyParse], codeBody) creators = allInitialisers.get(methodparse.ConstructorParse, []) collectionInits = allInitialisers.get( methodparse.CollectionInitParse, []) properties = allInitialisers.get(methodparse.PropertyParse, []) events = allInitialisers.get(methodparse.EventParse, []) newObjColl = ObjCollection.ObjectCollection() newObjColl.setup(creators, properties, events, collectionInits, inits, fins) if unmatched: wx.LogWarning(_('The following lines were not used by the Designer '\ 'and will be lost:\n')) for line in unmatched: wx.LogWarning(line) wx.LogWarning(_('\nThere were unprocessed lines in the source code of '\ 'method: %s\nIf this was unexpected, it is advised '\ 'that you cancel this Designer session and correct '\ 'the problem before continuing.')%meth) return newObjColl def readSpecialAttrs(self, mod, cls): """ Read special attributes from __init__ method. All instance attributes defined between the top of the __init__ method and the _init_ctrls() method call will be available to the Designer as valid names bound to properties. For an attribute to qualify, it has to have a simple deduceable type; Python builtin or wxPython objects. If for example the attribute is bound to a variable passed in as a parameter, you have to first initialise it to a literal of the same type. This value will be used at design time. e.g. def __init__(self, parent, myFrameCaption): self.frameCaption = 'Design time frame caption' self.frameCaption = myFrameCaption self._init_ctrls(parent) Now you may add this attribute as a parameter or property value in the source by hand. In the Inspector property values recognised as special attributes will display as bold values and cannot be edited (yet). """ initMeth = cls.methods['__init__'] # determine end of attrs and possible external attrs init startline = initMeth.start extAttrInitLine = -1 extAttrInitName = '' for idx in range(startline, initMeth.end): line = mod.source[idx].strip() if line.startswith('self._init_ctrls('): endline = idx break elif line.find('_AttrMixin.__init__(self') != -1: extAttrInitLine = idx extAttrInitName = line.split('.__init__')[0] else: raise Exception, 'self._init_ctrls not found in __init__' # build list of attrs attrs = [] def readAttrsFromSrc(attrs, attributes, source, startline, endline): for attr, blocks in attributes.items(): for block in blocks: if startline <= block.start <= endline and attr not in attrs: linePos = block.start - 1 line = source[linePos] val = line[line.find('=') + 1:].strip() # handle lines continued with , while val.endswith(','): linePos += 1 val += source[linePos].strip() attrs.append((attr, val)) if extAttrInitName: if not mod.from_imports_names.has_key(extAttrInitName): raise Exception, '%s.__init__ called, but not imported in the form: '\ 'from [ModuleName] import %s'%(extAttrInitName, extAttrInitName) # try to load external attrs extModName = mod.from_imports_names[extAttrInitName] extModFilename = os.path.join(os.path.dirname(self.filename), extModName + '.py') from Explorers.Explorer import openEx try: data = openEx(extModFilename).load() except Exception, error: raise Exception, 'Problem loading %s: File expected at: %s' % ( extModName, extModFilename) exModModel = ModuleModel(data, extModFilename, self.editor, 1) extModule = exModModel.getModule() extClass = extModule.classes[extAttrInitName] extMeth = extClass.methods['__init__'] readAttrsFromSrc(attrs, extClass.attributes, extModule.source, extMeth.start, extMeth.end) readAttrsFromSrc(attrs, cls.attributes, mod.source, startline, endline) import PaletteMapping # build a dictionary that can be passed to eval evalNS = _your_frame_attrs_() for attr, code in attrs: if hasattr(evalNS, attr): continue try: val = PaletteMapping.evalCtrl(code) except Exception, err: print str(err) continue else: setattr(evalNS, attr, val)