]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wx/tools/XRCed/xxx.py
collapsing tool panels
[wxWidgets.git] / wxPython / wx / tools / XRCed / xxx.py
1 # Name: xxx.py ('xxx' is easy to distinguish from 'wx' :) )
2 # Purpose: XML interface classes
3 # Author: Roman Rolinsky <rolinsky@mema.ucl.ac.be>
4 # Created: 22.08.2001
5 # RCS-ID: $Id$
6
7 from xml.dom import minidom
8 from globals import *
9 from params import *
10 import traceback, types
11
12 # Base class for interface parameter classes
13 class xxxNode:
14 def __init__(self, node):
15 self.node = node
16 def remove(self):
17 self.node.parentNode.removeChild(self.node)
18 self.node.unlink()
19
20 # Generic (text) parameter class
21 class xxxParam(xxxNode):
22 # Standard use: for text nodes
23 def __init__(self, node):
24 xxxNode.__init__(self, node)
25 if not node.hasChildNodes():
26 # If does not have child nodes, create empty text node
27 text = g.tree.dom.createTextNode('')
28 node.appendChild(text)
29 else:
30 text = node.childNodes[0] # first child must be text node
31 assert text.nodeType == minidom.Node.TEXT_NODE
32 # Append other text nodes if present and delete them
33 extraText = ''
34 for n in node.childNodes[1:]:
35 if n.nodeType == minidom.Node.TEXT_NODE:
36 extraText += n.data
37 node.removeChild(n)
38 n.unlink()
39 else: break
40 if extraText: text.data = text.data + extraText
41 # Use convertion from unicode to current encoding
42 self.textNode = text
43 # Value returns string
44 if wx.USE_UNICODE: # no conversion is needed
45 def value(self):
46 return self.textNode.data
47 def update(self, value):
48 self.textNode.data = value
49 else:
50 def value(self):
51 try:
52 return self.textNode.data.encode(g.currentEncoding)
53 except LookupError:
54 return self.textNode.data.encode()
55 def update(self, value):
56 try: # handle exception if encoding is wrong
57 self.textNode.data = unicode(value, g.currentEncoding)
58 except UnicodeDecodeError:
59 self.textNode.data = unicode(value)
60 #wx.LogMessage("Unicode error: set encoding in file\nglobals.py to something appropriate")
61
62 # Integer parameter
63 class xxxParamInt(xxxParam):
64 # Standard use: for text nodes
65 def __init__(self, node):
66 xxxParam.__init__(self, node)
67 # Value returns string
68 def value(self):
69 try:
70 return int(self.textNode.data)
71 except ValueError:
72 return -1 # invalid value
73 def update(self, value):
74 self.textNode.data = str(value)
75
76 # Content parameter
77 class xxxParamContent(xxxNode):
78 def __init__(self, node):
79 xxxNode.__init__(self, node)
80 data, l = [], [] # data is needed to quicker value retrieval
81 nodes = node.childNodes[:] # make a copy of the child list
82 for n in nodes:
83 if n.nodeType == minidom.Node.ELEMENT_NODE:
84 assert n.tagName == 'item', 'bad content content'
85 if not n.hasChildNodes():
86 # If does not have child nodes, create empty text node
87 text = g.tree.dom.createTextNode('')
88 node.appendChild(text)
89 else:
90 # !!! normalize?
91 text = n.childNodes[0] # first child must be text node
92 assert text.nodeType == minidom.Node.TEXT_NODE
93 l.append(text)
94 data.append(text.data)
95 else: # remove other
96 node.removeChild(n)
97 n.unlink()
98 self.l, self.data = l, data
99 def value(self):
100 return self.data
101 def update(self, value):
102 # If number if items is not the same, recreate children
103 if len(value) != len(self.l): # remove first if number of items has changed
104 childNodes = self.node.childNodes[:]
105 for n in childNodes:
106 self.node.removeChild(n)
107 l = []
108 for str in value:
109 itemElem = g.tree.dom.createElement('item')
110 itemText = g.tree.dom.createTextNode(str)
111 itemElem.appendChild(itemText)
112 self.node.appendChild(itemElem)
113 l.append(itemText)
114 self.l = l
115 else:
116 for i in range(len(value)):
117 self.l[i].data = value[i]
118 self.data = value
119
120 # Content parameter for checklist
121 class xxxParamContentCheckList(xxxNode):
122 def __init__(self, node):
123 xxxNode.__init__(self, node)
124 data, l = [], [] # data is needed to quicker value retrieval
125 nodes = node.childNodes[:] # make a copy of the child list
126 for n in nodes:
127 if n.nodeType == minidom.Node.ELEMENT_NODE:
128 assert n.tagName == 'item', 'bad content content'
129 checked = n.getAttribute('checked')
130 if not checked: checked = 0
131 if not n.hasChildNodes():
132 # If does not have child nodes, create empty text node
133 text = g.tree.dom.createTextNode('')
134 node.appendChild(text)
135 else:
136 # !!! normalize?
137 text = n.childNodes[0] # first child must be text node
138 assert text.nodeType == minidom.Node.TEXT_NODE
139 l.append((text, n))
140 data.append((str(text.data), int(checked)))
141 else: # remove other
142 node.removeChild(n)
143 n.unlink()
144 self.l, self.data = l, data
145 def value(self):
146 return self.data
147 def update(self, value):
148 # If number if items is not the same, recreate children
149 if len(value) != len(self.l): # remove first if number of items has changed
150 childNodes = self.node.childNodes[:]
151 for n in childNodes:
152 self.node.removeChild(n)
153 l = []
154 for s,ch in value:
155 itemElem = g.tree.dom.createElement('item')
156 # Add checked only if True
157 if ch: itemElem.setAttribute('checked', '1')
158 itemText = g.tree.dom.createTextNode(s)
159 itemElem.appendChild(itemText)
160 self.node.appendChild(itemElem)
161 l.append((itemText, itemElem))
162 self.l = l
163 else:
164 for i in range(len(value)):
165 self.l[i][0].data = value[i][0]
166 self.l[i][1].setAttribute('checked', str(value[i][1]))
167 self.data = value
168
169 # Bitmap parameter
170 class xxxParamBitmap(xxxParam):
171 def __init__(self, node):
172 xxxParam.__init__(self, node)
173 self.stock_id = node.getAttribute('stock_id')
174 def value(self):
175 return [self.stock_id, xxxParam.value(self)]
176 def update(self, value):
177 self.stock_id = value[0]
178 if self.stock_id:
179 self.node.setAttribute('stock_id', self.stock_id)
180 elif self.node.hasAttribute('stock_id'):
181 self.node.removeAttribute('stock_id')
182 xxxParam.update(self, value[1])
183
184 ################################################################################
185
186 # Classes to interface DOM objects
187 class xxxObject:
188 # Default behavior
189 hasChildren = False # has children elements?
190 hasStyle = True # almost everyone
191 hasName = True # has name attribute?
192 isSizer = hasChild = False
193 isElement = True
194 allParams = None # Some nodes have no parameters
195 # Style parameters (all optional)
196 styles = ['fg', 'bg', 'font', 'enabled', 'focused', 'hidden', 'tooltip']
197 # Special parameters
198 specials = []
199 # Bitmap tags
200 bitmapTags = ['bitmap', 'bitmap2', 'icon']
201 # Required paremeters: none by default
202 required = []
203 # Default parameters with default values
204 default = {}
205 # Parameter types
206 paramDict = {}
207 # Window styles and extended styles
208 winStyles = []
209 # Tree icon index
210 #image = -1
211 # Construct a new xxx object from DOM element
212 # parent is parent xxx object (or None if none), element is DOM element object
213 def __init__(self, parent, element, refElem=None):
214 self.parent = parent
215 self.node = element
216 self.refElem = refElem
217 self.undo = None
218 # Reference are dereferenced
219 if element.tagName == 'object_ref':
220 # Find original object
221 self.ref = element.getAttribute('ref')
222 if refElem:
223 self.className = self.refElem.getAttribute('class')
224 else:
225 self.className = 'xxxUnknown'
226 self.required = []
227 else:
228 # Get attributes
229 self.ref = None
230 self.className = element.getAttribute('class')
231 self.subclass = element.getAttribute('subclass')
232 if self.hasName: self.name = element.getAttribute('name')
233 # Set parameters (text element children)
234 self.params = {}
235 for n in element.childNodes[:]:
236 if n.nodeType == minidom.Node.ELEMENT_NODE:
237 tag = n.tagName
238 if tag in ['object', 'object_ref']:
239 continue # do nothing for object children here
240 elif tag not in self.allParams and tag not in self.styles:
241 print 'WARNING: unknown parameter for %s: %s' % \
242 (self.className, tag)
243 elif tag in self.specials:
244 self.special(tag, n)
245 elif tag == 'content':
246 if self.className == 'wxCheckListBox':
247 self.params[tag] = xxxParamContentCheckList(n)
248 else:
249 self.params[tag] = xxxParamContent(n)
250 elif tag == 'font': # has children
251 self.params[tag] = xxxParamFont(element, n)
252 elif tag in self.bitmapTags:
253 # Can have attributes
254 self.params[tag] = xxxParamBitmap(n)
255 else: # simple parameter
256 self.params[tag] = xxxParam(n)
257 elif n.nodeType == minidom.Node.TEXT_NODE and n.data.isspace():
258 # Remove empty text nodes
259 element.removeChild(n)
260 n.unlink()
261
262 # Check that all required params are set
263 for param in self.required:
264 if not self.params.has_key(param):
265 # If default is specified, set it
266 if self.default.has_key(param):
267 elem = g.tree.dom.createElement(param)
268 if param == 'content':
269 if self.className == 'wxCheckListBox':
270 self.params[param] = xxxParamContentCheckList(elem)
271 else:
272 self.params[param] = xxxParamContent(elem)
273 else:
274 self.params[param] = xxxParam(elem)
275 # Find place to put new element: first present element after param
276 found = False
277 paramStyles = self.allParams + self.styles
278 for p in paramStyles[paramStyles.index(param) + 1:]:
279 # Content params don't have same type
280 if self.params.has_key(p) and p != 'content':
281 found = True
282 break
283 if found:
284 nextTextElem = self.params[p].node
285 self.node.insertBefore(elem, nextTextElem)
286 else:
287 self.node.appendChild(elem)
288 else:
289 wx.LogWarning('Required parameter %s of %s missing' %
290 (param, self.className))
291 # Returns real tree object
292 def treeObject(self):
293 if self.hasChild: return self.child
294 return self
295 # Returns tree image index
296 def treeImage(self):
297 if self.hasChild: return self.child.treeImage()
298 return self.image
299 # Class name plus wx name
300 def treeName(self):
301 if self.hasChild: return self.child.treeName()
302 if self.subclass: className = self.subclass
303 else: className = self.className
304 if self.hasName and self.name: return className + ' "' + self.name + '"'
305 return className
306 # Class name or subclass
307 def panelName(self):
308 if self.subclass: name = self.subclass + '(' + self.className + ')'
309 name = self.className
310 if self.ref: name = 'ref: ' + self.ref + ', ' + name
311 return name
312 # Sets name of tree object
313 def setTreeName(self, name):
314 if self.hasChild: obj = self.child
315 else: obj = self
316 obj.name = name
317 obj.node.setAttribute('name', name)
318 # Set normal (text) params
319 def set(self, param, value):
320 try:
321 self.params[param].update(value)
322 except KeyError:
323 p = xxxParam(g.tree.dom.createElement(param))
324 p.update(value)
325 self.params[param] = p
326 # Special processing for growablecols-like parameters
327 # represented by several nodes
328 def special(self, tag, node):
329 if not self.params.has_key(tag):
330 # Create new multi-group
331 self.params[tag] = xxxParamMulti(node)
332 self.params[tag].append(xxxParamInt(node))
333 def setSpecial(self, param, value):
334 # Straightforward implementation: remove, add again
335 self.params[param].remove()
336 del self.params[param]
337 for i in value:
338 node = g.tree.dom.createElement(param)
339 text = g.tree.dom.createTextNode(str(i))
340 node.appendChild(text)
341 self.node.appendChild(node)
342 self.special(param, node)
343
344 # Imitation of FindResource/DoFindResource from xmlres.cpp
345 def DoFindResource(parent, name, classname, recursive):
346 for n in parent.childNodes:
347 if n.nodeType == minidom.Node.ELEMENT_NODE and \
348 n.tagName in ['object', 'object_ref'] and \
349 n.getAttribute('name') == name:
350 cls = n.getAttribute('class')
351 if not classname or cls == classname: return n
352 if not cls or n.tagName == 'object_ref':
353 refName = n.getAttribute('ref')
354 if not refName: continue
355 refNode = FindResource(refName)
356 if refName and refNode.getAttribute('class') == classname:
357 return n
358 if recursive:
359 for n in parent.childNodes:
360 if n.nodeType == minidom.Node.ELEMENT_NODE and \
361 n.tagName in ['object', 'object_ref']:
362 found = DoFindResource(n, name, classname, True)
363 if found: return found
364 def FindResource(name, classname='', recursive=True):
365 found = DoFindResource(g.tree.mainNode, name, classname, recursive)
366 if found: return found
367 wx.LogError('XRC resource "%s" not found!' % name)
368
369
370 ################################################################################
371
372 # This is a little special: it is both xxxObject and xxxNode
373 class xxxParamFont(xxxObject, xxxNode):
374 allParams = ['size', 'family', 'style', 'weight', 'underlined',
375 'face', 'encoding']
376 def __init__(self, parent, element):
377 xxxObject.__init__(self, parent, element)
378 xxxNode.__init__(self, element)
379 self.parentNode = parent # required to behave similar to DOM node
380 v = []
381 for p in self.allParams:
382 try:
383 v.append(str(self.params[p].value()))
384 except KeyError:
385 v.append('')
386 self.data = v
387 def update(self, value):
388 # `value' is a list of strings corresponding to all parameters
389 elem = self.node
390 # Remove old elements first
391 childNodes = elem.childNodes[:]
392 for node in childNodes: elem.removeChild(node)
393 i = 0
394 self.params.clear()
395 v = []
396 for param in self.allParams:
397 if value[i]:
398 fontElem = g.tree.dom.createElement(param)
399 textNode = g.tree.dom.createTextNode(value[i])
400 self.params[param] = textNode
401 fontElem.appendChild(textNode)
402 elem.appendChild(fontElem)
403 v.append(value[i])
404 i += 1
405 self.data = v
406 def value(self):
407 return self.data
408
409 ################################################################################
410
411 class xxxContainer(xxxObject):
412 hasChildren = True
413 exStyles = []
414
415 # Simulate normal parameter for encoding
416 class xxxEncoding:
417 def value(self):
418 return g.currentEncoding
419 def update(self, val):
420 g.currentEncoding = val
421
422 # Special class for root node
423 class xxxMainNode(xxxContainer):
424 allParams = ['encoding']
425 hasStyle = hasName = False
426 def __init__(self, dom):
427 xxxContainer.__init__(self, None, dom.documentElement)
428 self.className = 'XML tree'
429 # Reset required parameters after processing XML, because encoding is
430 # a little special
431 self.required = ['encoding']
432 self.params['encoding'] = xxxEncoding()
433
434 ################################################################################
435 # Top-level windwows
436
437 class xxxPanel(xxxContainer):
438 allParams = ['pos', 'size', 'style']
439 winStyles = ['wxNO_3D', 'wxTAB_TRAVERSAL']
440 styles = ['fg', 'bg', 'font', 'enabled', 'focused', 'hidden', 'exstyle',
441 'tooltip']
442
443 class xxxDialog(xxxContainer):
444 allParams = ['title', 'centered', 'pos', 'size', 'style']
445 paramDict = {'centered': ParamBool}
446 required = ['title']
447 default = {'title': ''}
448 winStyles = ['wxDEFAULT_DIALOG_STYLE', 'wxCAPTION',
449 'wxSTAY_ON_TOP', 'wxSYSTEM_MENU', 'wxTHICK_FRAME',
450 'wxRESIZE_BORDER', 'wxRESIZE_BOX', 'wxCLOSE_BOX',
451 'wxMAXIMIZE_BOX', 'wxMINIMIZE_BOX',
452 'wxDIALOG_MODAL', 'wxDIALOG_MODELESS', 'wxDIALOG_NO_PARENT'
453 'wxNO_3D', 'wxTAB_TRAVERSAL']
454 exStyles = ['wxWS_EX_VALIDATE_RECURSIVELY', 'wxDIALOG_EX_METAL']
455 styles = ['fg', 'bg', 'font', 'enabled', 'focused', 'hidden', 'exstyle',
456 'tooltip']
457
458 class xxxFrame(xxxContainer):
459 allParams = ['title', 'centered', 'pos', 'size', 'style']
460 paramDict = {'centered': ParamBool}
461 required = ['title']
462 default = {'title': ''}
463 winStyles = ['wxDEFAULT_FRAME_STYLE', 'wxDEFAULT_DIALOG_STYLE', 'wxCAPTION',
464 'wxSTAY_ON_TOP', 'wxSYSTEM_MENU', 'wxTHICK_FRAME',
465 'wxRESIZE_BORDER', 'wxRESIZE_BOX', 'wxCLOSE_BOX',
466 'wxMAXIMIZE_BOX', 'wxMINIMIZE_BOX',
467 'wxFRAME_NO_TASKBAR', 'wxFRAME_SHAPED', 'wxFRAME_TOOL_WINDOW',
468 'wxFRAME_FLOAT_ON_PARENT',
469 'wxNO_3D', 'wxTAB_TRAVERSAL']
470 exStyles = ['wxWS_EX_VALIDATE_RECURSIVELY', 'wxFRAME_EX_METAL']
471 styles = ['fg', 'bg', 'font', 'enabled', 'focused', 'hidden', 'exstyle',
472 'tooltip']
473
474 class xxxTool(xxxObject):
475 allParams = ['bitmap', 'bitmap2', 'radio', 'toggle', 'tooltip', 'longhelp', 'label']
476 required = ['bitmap']
477 paramDict = {'bitmap2': ParamBitmap, 'radio': ParamBool, 'toggle': ParamBool}
478 hasStyle = False
479
480 class xxxToolBar(xxxContainer):
481 allParams = ['bitmapsize', 'margins', 'packing', 'separation', 'dontattachtoframe',
482 'pos', 'size', 'style']
483 hasStyle = False
484 paramDict = {'bitmapsize': ParamPosSize, 'margins': ParamPosSize,
485 'packing': ParamUnit, 'separation': ParamUnit,
486 'dontattachtoframe': ParamBool, 'style': ParamNonGenericStyle}
487 winStyles = ['wxTB_FLAT', 'wxTB_DOCKABLE', 'wxTB_VERTICAL', 'wxTB_HORIZONTAL',
488 'wxTB_3DBUTTONS','wxTB_TEXT', 'wxTB_NOICONS', 'wxTB_NODIVIDER',
489 'wxTB_NOALIGN', 'wxTB_HORZ_LAYOUT', 'wxTB_HORZ_TEXT']
490
491 class xxxStatusBar(xxxObject):
492 hasStyle = False
493 allParams = ['fields', 'widths', 'styles', 'style']
494 paramDict = {'fields': ParamIntNN, 'widths': ParamText, 'styles': ParamText,
495 'style': ParamNonGenericStyle}
496 winStyles = ['wxST_SIZEGRIP']
497
498 class xxxWizard(xxxContainer):
499 allParams = ['title', 'bitmap', 'pos']
500 required = ['title']
501 default = {'title': ''}
502 winStyles = []
503 exStyles = ['wxWIZARD_EX_HELPBUTTON']
504 styles = ['fg', 'bg', 'font', 'exstyle']
505
506 class xxxWizardPage(xxxContainer):
507 allParams = ['bitmap']
508 winStyles = []
509 exStyles = []
510
511 class xxxWizardPageSimple(xxxContainer):
512 allParams = ['bitmap']
513 winStyles = []
514 exStyles = []
515
516 ################################################################################
517 # Bitmap, Icon
518
519 class xxxBitmap(xxxObject):
520 allParams = ['bitmap']
521 required = ['bitmap']
522
523 # Just like bitmap
524 class xxxIcon(xxxObject):
525 allParams = []
526
527 ################################################################################
528 # Controls
529
530 class xxxStaticText(xxxObject):
531 allParams = ['label', 'pos', 'size', 'style']
532 required = ['label']
533 default = {'label': ''}
534 winStyles = ['wxALIGN_LEFT', 'wxALIGN_RIGHT', 'wxALIGN_CENTRE', 'wxST_NO_AUTORESIZE']
535
536 class xxxStaticLine(xxxObject):
537 allParams = ['pos', 'size', 'style']
538 winStyles = ['wxLI_HORIZONTAL', 'wxLI_VERTICAL']
539
540 class xxxStaticBitmap(xxxObject):
541 allParams = ['bitmap', 'pos', 'size', 'style']
542 required = ['bitmap']
543
544 class xxxTextCtrl(xxxObject):
545 allParams = ['value', 'pos', 'size', 'style']
546 winStyles = ['wxTE_NO_VSCROLL',
547 'wxTE_AUTO_SCROLL',
548 'wxTE_PROCESS_ENTER',
549 'wxTE_PROCESS_TAB',
550 'wxTE_MULTILINE',
551 'wxTE_PASSWORD',
552 'wxTE_READONLY',
553 'wxHSCROLL',
554 'wxTE_RICH',
555 'wxTE_RICH2',
556 'wxTE_AUTO_URL',
557 'wxTE_NOHIDESEL',
558 'wxTE_LEFT',
559 'wxTE_CENTRE',
560 'wxTE_RIGHT',
561 'wxTE_DONTWRAP',
562 'wxTE_LINEWRAP',
563 'wxTE_WORDWRAP']
564 paramDict = {'value': ParamMultilineText}
565
566 class xxxChoice(xxxObject):
567 allParams = ['content', 'selection', 'pos', 'size', 'style']
568 required = ['content']
569 default = {'content': '[]'}
570 winStyles = ['wxCB_SORT']
571
572 class xxxSlider(xxxObject):
573 allParams = ['value', 'min', 'max', 'pos', 'size', 'style',
574 'tickfreq', 'pagesize', 'linesize', 'thumb', 'tick',
575 'selmin', 'selmax']
576 paramDict = {'value': ParamInt, 'tickfreq': ParamIntNN, 'pagesize': ParamIntNN,
577 'linesize': ParamIntNN, 'thumb': ParamUnit,
578 'tick': ParamInt, 'selmin': ParamInt, 'selmax': ParamInt}
579 required = ['value', 'min', 'max']
580 winStyles = ['wxSL_HORIZONTAL', 'wxSL_VERTICAL', 'wxSL_AUTOTICKS', 'wxSL_LABELS',
581 'wxSL_LEFT', 'wxSL_RIGHT', 'wxSL_TOP', 'wxSL_BOTTOM',
582 'wxSL_BOTH', 'wxSL_SELRANGE', 'wxSL_INVERSE']
583
584 class xxxGauge(xxxObject):
585 allParams = ['range', 'pos', 'size', 'style', 'value', 'shadow', 'bezel']
586 paramDict = {'range': ParamIntNN, 'value': ParamIntNN,
587 'shadow': ParamIntNN, 'bezel': ParamIntNN}
588 winStyles = ['wxGA_HORIZONTAL', 'wxGA_VERTICAL', 'wxGA_PROGRESSBAR', 'wxGA_SMOOTH']
589
590 class xxxScrollBar(xxxObject):
591 allParams = ['pos', 'size', 'style', 'value', 'thumbsize', 'range', 'pagesize']
592 paramDict = {'value': ParamIntNN, 'range': ParamIntNN, 'thumbsize': ParamIntNN,
593 'pagesize': ParamIntNN}
594 winStyles = ['wxSB_HORIZONTAL', 'wxSB_VERTICAL']
595
596 class xxxListCtrl(xxxObject):
597 allParams = ['pos', 'size', 'style']
598 winStyles = ['wxLC_LIST', 'wxLC_REPORT', 'wxLC_ICON', 'wxLC_SMALL_ICON',
599 'wxLC_ALIGN_TOP', 'wxLC_ALIGN_LEFT', 'wxLC_AUTOARRANGE',
600 'wxLC_USER_TEXT', 'wxLC_EDIT_LABELS', 'wxLC_NO_HEADER',
601 'wxLC_SINGLE_SEL', 'wxLC_SORT_ASCENDING', 'wxLC_SORT_DESCENDING',
602 'wxLC_VIRTUAL', 'wxLC_HRULES', 'wxLC_VRULES', 'wxLC_NO_SORT_HEADER']
603
604 class xxxTreeCtrl(xxxObject):
605 allParams = ['pos', 'size', 'style']
606 winStyles = ['wxTR_EDIT_LABELS',
607 'wxTR_NO_BUTTONS',
608 'wxTR_HAS_BUTTONS',
609 'wxTR_TWIST_BUTTONS',
610 'wxTR_NO_LINES',
611 'wxTR_FULL_ROW_HIGHLIGHT',
612 'wxTR_LINES_AT_ROOT',
613 'wxTR_HIDE_ROOT',
614 'wxTR_ROW_LINES',
615 'wxTR_HAS_VARIABLE_ROW_HEIGHT',
616 'wxTR_SINGLE',
617 'wxTR_MULTIPLE',
618 'wxTR_EXTENDED',
619 'wxTR_DEFAULT_STYLE']
620
621 class xxxHtmlWindow(xxxObject):
622 allParams = ['pos', 'size', 'style', 'borders', 'url', 'htmlcode']
623 paramDict = {'htmlcode':ParamMultilineText}
624 winStyles = ['wxHW_SCROLLBAR_NEVER', 'wxHW_SCROLLBAR_AUTO', 'wxHW_NO_SELECTION']
625
626 class xxxCalendarCtrl(xxxObject):
627 allParams = ['pos', 'size', 'style']
628 winStyles = ['wxCAL_SUNDAY_FIRST', 'wxCAL_MONDAY_FIRST', 'wxCAL_SHOW_HOLIDAYS',
629 'wxCAL_NO_YEAR_CHANGE', 'wxCAL_NO_MONTH_CHANGE',
630 'wxCAL_SEQUENTIAL_MONTH_SELECTION', 'wxCAL_SHOW_SURROUNDING_WEEKS']
631
632 class xxxNotebook(xxxContainer):
633 allParams = ['pos', 'size', 'style']
634 winStyles = ['wxNB_TOP', 'wxNB_LEFT', 'wxNB_RIGHT', 'wxNB_BOTTOM',
635 'wxNB_FIXEDWIDTH', 'wxNB_MULTILINE', 'wxNB_NOPAGETHEME', 'wxNB_FLAT']
636
637 class xxxChoicebook(xxxContainer):
638 allParams = ['pos', 'size', 'style']
639 winStyles = ['wxCHB_DEFAULT', 'wxCHB_LEFT', 'wxCHB_RIGHT', 'wxCHB_TOP', 'wxCHB_BOTTOM']
640
641 class xxxListbook(xxxContainer):
642 allParams = ['pos', 'size', 'style']
643 winStyles = ['wxLB_DEFAULT', 'wxLB_LEFT', 'wxLB_RIGHT', 'wxLB_TOP', 'wxLB_BOTTOM']
644
645 class xxxSplitterWindow(xxxContainer):
646 allParams = ['orientation', 'sashpos', 'minsize', 'pos', 'size', 'style']
647 paramDict = {'orientation': ParamOrientation, 'sashpos': ParamUnit, 'minsize': ParamUnit }
648 winStyles = ['wxSP_3D', 'wxSP_3DSASH', 'wxSP_3DBORDER',
649 'wxSP_FULLSASH', 'wxSP_NOBORDER', 'wxSP_PERMIT_UNSPLIT', 'wxSP_LIVE_UPDATE',
650 'wxSP_NO_XP_THEME' ]
651
652 class xxxGenericDirCtrl(xxxObject):
653 allParams = ['defaultfolder', 'filter', 'defaultfilter', 'pos', 'size', 'style']
654 paramDict = {'defaultfilter': ParamIntNN}
655 winStyles = ['wxDIRCTRL_DIR_ONLY', 'wxDIRCTRL_3D_INTERNAL', 'wxDIRCTRL_SELECT_FIRST',
656 'wxDIRCTRL_SHOW_FILTERS']
657
658 class xxxScrolledWindow(xxxContainer):
659 allParams = ['pos', 'size', 'style']
660 winStyles = ['wxHSCROLL', 'wxVSCROLL', 'wxNO_3D', 'wxTAB_TRAVERSAL']
661
662 class xxxDateCtrl(xxxObject):
663 allParams = ['pos', 'size', 'style', 'borders']
664 winStyles = ['wxDP_DEFAULT', 'wxDP_SPIN', 'wxDP_DROPDOWN',
665 'wxDP_ALLOWNONE', 'wxDP_SHOWCENTURY']
666
667 class xxxGrid(xxxObject):
668 allParams = ['pos', 'size', 'style']
669
670 class xxxFilePickerCtrl(xxxObject):
671 allParams = ['value', 'message', 'wildcard', 'pos', 'size', 'style']
672 winStyles = ['wxFLP_OPEN', 'wxFLP_SAVE', 'wxFLP_OVERWRITE_PROMPT',
673 'wxFLP_FILE_MUST_EXIST', 'wxFLP_CHANGE_DIR',
674 'wxFLP_DEFAULT_STYLE']
675
676
677 ################################################################################
678 # Buttons
679
680 class xxxButton(xxxObject):
681 allParams = ['label', 'default', 'pos', 'size', 'style']
682 paramDict = {'default': ParamBool}
683 required = ['label']
684 winStyles = ['wxBU_LEFT', 'wxBU_TOP', 'wxBU_RIGHT', 'wxBU_BOTTOM', 'wxBU_EXACTFIT',
685 'wxNO_BORDER']
686
687 class xxxBitmapButton(xxxObject):
688 allParams = ['bitmap', 'selected', 'focus', 'disabled', 'default',
689 'pos', 'size', 'style']
690 paramDict = {'selected': ParamBitmap, 'focus': ParamBitmap, 'disabled': ParamBitmap,
691 'default': ParamBool}
692 required = ['bitmap']
693 winStyles = ['wxBU_AUTODRAW', 'wxBU_LEFT', 'wxBU_RIGHT',
694 'wxBU_TOP', 'wxBU_BOTTOM']
695
696 class xxxRadioButton(xxxObject):
697 allParams = ['label', 'value', 'pos', 'size', 'style']
698 paramDict = {'value': ParamBool}
699 required = ['label']
700 winStyles = ['wxRB_GROUP', 'wxRB_SINGLE']
701
702 class xxxSpinButton(xxxObject):
703 allParams = ['value', 'min', 'max', 'pos', 'size', 'style']
704 paramDict = {'value': ParamInt}
705 winStyles = ['wxSP_HORIZONTAL', 'wxSP_VERTICAL', 'wxSP_ARROW_KEYS', 'wxSP_WRAP']
706
707 class xxxSpinCtrl(xxxObject):
708 allParams = ['value', 'min', 'max', 'pos', 'size', 'style']
709 paramDict = {'value': ParamInt}
710 winStyles = ['wxSP_HORIZONTAL', 'wxSP_VERTICAL', 'wxSP_ARROW_KEYS', 'wxSP_WRAP']
711
712 class xxxToggleButton(xxxObject):
713 allParams = ['label', 'checked', 'pos', 'size', 'style']
714 paramDict = {'checked': ParamBool}
715 required = ['label']
716
717 ################################################################################
718 # Boxes
719
720 class xxxStaticBox(xxxObject):
721 allParams = ['label', 'pos', 'size', 'style']
722 required = ['label']
723
724 class xxxRadioBox(xxxObject):
725 allParams = ['label', 'content', 'selection', 'dimension', 'pos', 'size', 'style']
726 paramDict = {'dimension': ParamIntNN}
727 required = ['label', 'content']
728 default = {'content': '[]'}
729 winStyles = ['wxRA_SPECIFY_ROWS', 'wxRA_SPECIFY_COLS', 'wxRA_HORIZONTAL',
730 'wxRA_VERTICAL']
731
732 class xxxCheckBox(xxxObject):
733 allParams = ['label', 'checked', 'pos', 'size', 'style']
734 paramDict = {'checked': ParamBool}
735 winStyles = ['wxCHK_2STATE', 'wxCHK_3STATE', 'wxCHK_ALLOW_3RD_STATE_FOR_USER',
736 'wxALIGN_RIGHT']
737 required = ['label']
738
739 class xxxComboBox(xxxObject):
740 allParams = ['content', 'selection', 'value', 'pos', 'size', 'style']
741 required = ['content']
742 default = {'content': '[]'}
743 winStyles = ['wxCB_SIMPLE', 'wxCB_SORT', 'wxCB_READONLY', 'wxCB_DROPDOWN']
744
745 class xxxListBox(xxxObject):
746 allParams = ['content', 'selection', 'pos', 'size', 'style']
747 required = ['content']
748 default = {'content': '[]'}
749 winStyles = ['wxLB_SINGLE', 'wxLB_MULTIPLE', 'wxLB_EXTENDED', 'wxLB_HSCROLL',
750 'wxLB_ALWAYS_SB', 'wxLB_NEEDED_SB', 'wxLB_SORT']
751
752 class xxxCheckList(xxxObject):
753 allParams = ['content', 'pos', 'size', 'style']
754 required = ['content']
755 default = {'content': '[]'}
756 winStyles = ['wxLB_SINGLE', 'wxLB_MULTIPLE', 'wxLB_EXTENDED', 'wxLB_HSCROLL',
757 'wxLB_ALWAYS_SB', 'wxLB_NEEDED_SB', 'wxLB_SORT']
758 paramDict = {'content': ParamContentCheckList}
759
760 ################################################################################
761 # Sizers
762
763 class xxxSizer(xxxContainer):
764 hasName = hasStyle = False
765 paramDict = {'orient': ParamOrient}
766 isSizer = True
767 itemTag = 'sizeritem' # different for some sizers
768
769 class xxxBoxSizer(xxxSizer):
770 allParams = ['orient']
771 required = ['orient']
772 default = {'orient': 'wxVERTICAL'}
773 # Tree icon depends on orientation
774 def treeImage(self):
775 if self.params['orient'].value() == 'wxHORIZONTAL': return self.imageH
776 else: return self.imageV
777
778 class xxxStaticBoxSizer(xxxBoxSizer):
779 allParams = ['label', 'orient']
780 required = ['label', 'orient']
781
782 class xxxGridSizer(xxxSizer):
783 allParams = ['cols', 'rows', 'vgap', 'hgap']
784 required = ['cols']
785 default = {'cols': '2', 'rows': '2'}
786
787 class xxxStdDialogButtonSizer(xxxSizer):
788 allParams = []
789 itemTag = 'button'
790
791 # For repeated parameters
792 class xxxParamMulti:
793 def __init__(self, node):
794 self.node = node
795 self.l, self.data = [], []
796 def append(self, param):
797 self.l.append(param)
798 self.data.append(param.value())
799 def value(self):
800 return self.data
801 def remove(self):
802 for param in self.l:
803 param.remove()
804 self.l, self.data = [], []
805
806 class xxxFlexGridSizer(xxxGridSizer):
807 specials = ['growablecols', 'growablerows']
808 allParams = ['cols', 'rows', 'vgap', 'hgap'] + specials
809 paramDict = {'growablecols': ParamIntList, 'growablerows': ParamIntList}
810
811 class xxxGridBagSizer(xxxSizer):
812 specials = ['growablecols', 'growablerows']
813 allParams = ['vgap', 'hgap'] + specials
814 paramDict = {'growablecols': ParamIntList, 'growablerows': ParamIntList}
815
816 # Container with only one child.
817 # Not shown in tree.
818 class xxxChildContainer(xxxObject):
819 hasName = hasStyle = False
820 hasChild = True
821 def __init__(self, parent, element, refElem=None):
822 xxxObject.__init__(self, parent, element, refElem)
823 # Must have one child with 'object' tag, but we don't check it
824 nodes = element.childNodes[:] # create copy
825 for node in nodes:
826 if node.nodeType == minidom.Node.ELEMENT_NODE:
827 if node.tagName in ['object', 'object_ref']:
828 # Create new xxx object for child node
829 self.child = MakeXXXFromDOM(self, node)
830 self.child.parent = parent
831 # Copy hasChildren and isSizer attributes
832 self.hasChildren = self.child.hasChildren
833 self.isSizer = self.child.isSizer
834 return # success
835 else:
836 element.removeChild(node)
837 node.unlink()
838 assert 0, 'no child found'
839 def resetChild(self, xxx):
840 '''Reset child info (for replacing with another class).'''
841 self.child = xxx
842 self.hasChildren = xxx.hasChildren
843 self.isSizer = xxx.isSizer
844
845 class xxxSizerItem(xxxChildContainer):
846 allParams = ['option', 'flag', 'border', 'minsize', 'ratio']
847 paramDict = {'option': ParamInt, 'minsize': ParamPosSize, 'ratio': ParamPosSize}
848 defaults_panel = {}
849 defaults_control = {}
850 def __init__(self, parent, element, refElem=None):
851 # For GridBag sizer items, extra parameters added
852 if isinstance(parent, xxxGridBagSizer):
853 self.allParams = self.allParams + ['cellpos', 'cellspan']
854 xxxChildContainer.__init__(self, parent, element, refElem)
855 # Remove pos parameter - not needed for sizeritems
856 if 'pos' in self.child.allParams:
857 self.child.allParams = self.child.allParams[:]
858 self.child.allParams.remove('pos')
859 # Set defaults for some children types
860 if isinstance(self.child, xxxContainer) and not self.child.isSizer:
861 for param,v in self.defaults_panel.items():
862 print param,v
863 self.set(param, v)
864 elif isinstance(self.child, xxxObject):
865 for param,v in self.defaults_control.items():
866 self.set(param, v)
867 def resetChild(self, xxx):
868 xxxChildContainer.resetChild(self, xxx)
869 # Remove pos parameter - not needed for sizeritems
870 if 'pos' in self.child.allParams:
871 self.child.allParams = self.child.allParams[:]
872 self.child.allParams.remove('pos')
873
874 class xxxSizerItemButton(xxxSizerItem):
875 allParams = []
876 paramDict = {}
877 def __init__(self, parent, element, refElem=None):
878 xxxChildContainer.__init__(self, parent, element, refElem=None)
879 # Remove pos parameter - not needed for sizeritems
880 if 'pos' in self.child.allParams:
881 self.child.allParams = self.child.allParams[:]
882 self.child.allParams.remove('pos')
883
884 class xxxPage(xxxChildContainer):
885 allParams = ['label', 'selected']
886 paramDict = {'selected': ParamBool}
887 required = ['label']
888 def __init__(self, parent, element, refElem=None):
889 xxxChildContainer.__init__(self, parent, element, refElem)
890 # pos and size dont matter for notebookpages
891 if 'pos' in self.child.allParams:
892 self.child.allParams = self.child.allParams[:]
893 self.child.allParams.remove('pos')
894 if 'size' in self.child.allParams:
895 self.child.allParams = self.child.allParams[:]
896 self.child.allParams.remove('size')
897
898 class xxxSpacer(xxxObject):
899 hasName = hasStyle = False
900 allParams = ['size', 'option', 'flag', 'border']
901 paramDict = {'option': ParamInt}
902 default = {'size': '0,0'}
903 def __init__(self, parent, element, refElem=None):
904 # For GridBag sizer items, extra parameters added
905 if isinstance(parent, xxxGridBagSizer):
906 self.allParams = self.allParams + ['cellpos', 'cellspan']
907 xxxObject.__init__(self, parent, element, refElem)
908
909 class xxxMenuBar(xxxContainer):
910 allParams = ['style']
911 paramDict = {'style': ParamNonGenericStyle} # no generic styles
912 winStyles = ['wxMB_DOCKABLE']
913
914 class xxxMenu(xxxContainer):
915 allParams = ['label', 'help', 'style']
916 default = {'label': ''}
917 paramDict = {'style': ParamNonGenericStyle} # no generic styles
918 winStyles = ['wxMENU_TEAROFF']
919
920 class xxxMenuItem(xxxObject):
921 allParams = ['label', 'bitmap', 'accel', 'help',
922 'checkable', 'radio', 'enabled', 'checked']
923 default = {'label': ''}
924 hasStyle = False
925
926 class xxxSeparator(xxxObject):
927 hasName = hasStyle = False
928
929 ################################################################################
930 # Unknown control
931
932 class xxxUnknown(xxxObject):
933 allParams = ['pos', 'size', 'style']
934 winStyles = ['wxNO_FULL_REPAINT_ON_RESIZE']
935
936 ################################################################################
937 # Comment
938
939 _handlers = [] # custom handler classes/funcs
940 def getHandlers():
941 return _handlers
942 def setHandlers(handlers):
943 global _handlers
944 _handlers = handlers
945 _CFuncPtr = None # ctypes function type
946
947 def register(hndlr):
948 """Register hndlr function or XmlResourceHandler class."""
949 if _CFuncPtr and isinstance(hndlr, _CFuncPtr):
950 _handlers.append(hndlr)
951 return
952 if not isinstance(hndlr, type):
953 wx.LogError('handler is not a type: %s' % hndlr)
954 elif not issubclass(hndlr, wx.xrc.XmlResourceHandler):
955 wx.LogError('handler is not a XmlResourceHandler: %s' % hndlr)
956 else:
957 _handlers.append(hndlr)
958
959 def load_dl(path, localname=''):
960 """Load shared/dynamic library into xxx namespace.
961
962 If path is not absolute or relative, try to find in the module's directory.
963 """
964 if not localname:
965 localname = os.path.basename(os.path.splitext(path)[0])
966 try:
967 import ctypes
968 global _CFuncPtr
969 _CFuncPtr = ctypes._CFuncPtr # use as a flag of loaded ctypes
970 #if not os.path.dirname(path) and os.path.isfile(path):
971
972 except ImportError:
973 wx.LogError('ctypes module not found')
974 globals()[localname] = None
975 return
976 try:
977 dl = ctypes.CDLL(path)
978 globals()[localname] = dl
979 # Register AddXmlHandlers() if exists
980 try:
981 register(dl.AddXmlHandlers)
982 except:
983 pass
984 except:
985 wx.LogError('error loading dynamic library: %s' % path)
986 print traceback.print_exc()
987
988 # Called when creating test window
989 def addHandlers():
990 for h in _handlers:
991 if _CFuncPtr and isinstance(h, _CFuncPtr):
992 try:
993 apply(h, ())
994 except:
995 wx.LogError('error calling DL func: "%s"' % h)
996 print traceback.print_exc()
997 else:
998 try:
999 xrc.XmlResource.Get().AddHandler(apply(h, ()))
1000 except:
1001 wx.LogError('error adding XmlHandler: "%s"' % h)
1002 print traceback.print_exc()
1003
1004 def custom(klassName, klass='unknown'):
1005 """Define custom control based on xrcClass.
1006
1007 klass: new object name
1008 xrcClass: name of an existing XRC object class or
1009 a class object defining class parameters.
1010 """
1011 if type(klass) is str:
1012 # Copy correct xxx class under new name
1013 kl = xxxDict[klass]
1014 xxxClass = types.ClassType('xxx' + klassName, kl.__bases__, kl.__dict__)
1015 else:
1016 xxxClass = klass
1017 # Register param IDs
1018 for param in klass.allParams + klass.paramDict.keys():
1019 if not paramIDs.has_key(param):
1020 paramIDs[param] = wx.NewId()
1021 # Insert in dictionaty
1022 xxxDict[klassName] = xxxClass
1023 # Add to menu
1024 g.pullDownMenu.addCustom(klassName)
1025
1026 class xxxParamComment(xxxParam):
1027 def __init__(self, node):
1028 xxxNode.__init__(self, node)
1029 self.textNode = node
1030 # Parse "pragma" comments
1031 if node.data and node.data[0] == '%':
1032 try:
1033 code = node.data[1:]
1034 exec code in globals()
1035 except:
1036 wx.LogError('exec error: "%s"' % code)
1037 print traceback.print_exc()
1038
1039 class xxxComment(xxxObject):
1040 hasStyle = hasName = False
1041 allParams = required = ['comment']
1042
1043 def __init__(self, parent, node):
1044 self.parent = parent
1045 self.node = node
1046 self.isElement = False
1047 self.undo = None
1048 self.className = 'comment'
1049 self.ref = self.subclass = None
1050 self.params = {'comment': xxxParamComment(node)}
1051
1052 def treeName(self):
1053 # Replace newlines by \n to avoid tree item resizing
1054 return self.params['comment'].value().replace('\n', r'\n')
1055
1056 ################################################################################
1057
1058 # Mapping of XRC names to xxx classes
1059 xxxDict = {
1060 'wxPanel': xxxPanel,
1061 'wxDialog': xxxDialog,
1062 'wxFrame': xxxFrame,
1063 'tool': xxxTool,
1064 'wxToolBar': xxxToolBar,
1065 'wxStatusBar': xxxStatusBar,
1066 'wxWizard': xxxWizard,
1067 'wxWizardPage': xxxWizardPage,
1068 'wxWizardPageSimple': xxxWizardPageSimple,
1069
1070 'wxBitmap': xxxBitmap,
1071 'wxIcon': xxxIcon,
1072
1073 'wxButton': xxxButton,
1074 'wxBitmapButton': xxxBitmapButton,
1075 'wxRadioButton': xxxRadioButton,
1076 'wxSpinButton': xxxSpinButton,
1077 'wxToggleButton' : xxxToggleButton,
1078
1079 'wxStaticBox': xxxStaticBox,
1080 'wxStaticBitmap': xxxStaticBitmap,
1081 'wxRadioBox': xxxRadioBox,
1082 'wxComboBox': xxxComboBox,
1083 'wxCheckBox': xxxCheckBox,
1084 'wxListBox': xxxListBox,
1085
1086 'wxStaticText': xxxStaticText,
1087 'wxStaticLine': xxxStaticLine,
1088 'wxTextCtrl': xxxTextCtrl,
1089 'wxChoice': xxxChoice,
1090 'wxSlider': xxxSlider,
1091 'wxGauge': xxxGauge,
1092 'wxScrollBar': xxxScrollBar,
1093 'wxTreeCtrl': xxxTreeCtrl,
1094 'wxListCtrl': xxxListCtrl,
1095 'wxCheckListBox': xxxCheckList,
1096 'notebookpage': xxxPage,
1097 'choicebookpage': xxxPage,
1098 'listbookpage': xxxPage,
1099 'wxNotebook': xxxNotebook,
1100 'wxChoicebook': xxxChoicebook,
1101 'wxListbook': xxxListbook,
1102 'wxSplitterWindow': xxxSplitterWindow,
1103 'wxHtmlWindow': xxxHtmlWindow,
1104 'wxCalendarCtrl': xxxCalendarCtrl,
1105 'wxGenericDirCtrl': xxxGenericDirCtrl,
1106 'wxSpinCtrl': xxxSpinCtrl,
1107 'wxScrolledWindow': xxxScrolledWindow,
1108 'wxGrid': xxxGrid,
1109 'wxFilePickerCtrl': xxxFilePickerCtrl,
1110 'wxDatePickerCtrl': xxxDateCtrl,
1111
1112 'wxBoxSizer': xxxBoxSizer,
1113 'wxStaticBoxSizer': xxxStaticBoxSizer,
1114 'wxGridSizer': xxxGridSizer,
1115 'wxFlexGridSizer': xxxFlexGridSizer,
1116 'wxGridBagSizer': xxxGridBagSizer,
1117 'wxStdDialogButtonSizer': xxxStdDialogButtonSizer,
1118 'sizeritem': xxxSizerItem, 'button': xxxSizerItemButton,
1119 'spacer': xxxSpacer,
1120
1121 'wxMenuBar': xxxMenuBar,
1122 'wxMenu': xxxMenu,
1123 'wxMenuItem': xxxMenuItem,
1124 'separator': xxxSeparator,
1125
1126 'unknown': xxxUnknown,
1127 'comment': xxxComment,
1128 }
1129
1130 # Create IDs for all parameters of all classes
1131 paramIDs = {'fg': wx.NewId(), 'bg': wx.NewId(), 'exstyle': wx.NewId(), 'font': wx.NewId(),
1132 'enabled': wx.NewId(), 'focused': wx.NewId(), 'hidden': wx.NewId(),
1133 'tooltip': wx.NewId(), 'encoding': wx.NewId(),
1134 'cellpos': wx.NewId(), 'cellspan': wx.NewId(),
1135 'text': wx.NewId()
1136 }
1137 for cl in xxxDict.values():
1138 if cl.allParams:
1139 for param in cl.allParams + cl.paramDict.keys():
1140 if not paramIDs.has_key(param):
1141 paramIDs[param] = wx.NewId()
1142
1143 ################################################################################
1144 # Helper functions
1145
1146 # Test for object elements
1147 def IsObject(node):
1148 return node.nodeType == minidom.Node.ELEMENT_NODE and \
1149 node.tagName in ['object', 'object_ref'] or \
1150 node.nodeType == minidom.Node.COMMENT_NODE
1151
1152 # Make XXX object from some DOM object, selecting correct class
1153 def MakeXXXFromDOM(parent, node):
1154 if node.nodeType == minidom.Node.COMMENT_NODE:
1155 return xxxComment(parent, node)
1156 if node.tagName == 'object_ref':
1157 ref = node.getAttribute('ref')
1158 refElem = FindResource(ref)
1159 if refElem: cls = refElem.getAttribute('class')
1160 else: return xxxUnknown(parent, node)
1161 else:
1162 refElem = None
1163 cls = node.getAttribute('class')
1164 try:
1165 klass = xxxDict[cls]
1166 except KeyError:
1167 # If we encounter a weird class, use unknown template
1168 print 'WARNING: unsupported class:', node.getAttribute('class')
1169 klass = xxxUnknown
1170 return klass(parent, node, refElem)
1171
1172 # Make empty DOM element
1173 def MakeEmptyDOM(className):
1174 elem = g.tree.dom.createElement('object')
1175 elem.setAttribute('class', className)
1176 # Set required and default parameters
1177 xxxClass = xxxDict[className]
1178 defaultNotRequired = filter(lambda x, l=xxxClass.required: x not in l,
1179 xxxClass.default.keys())
1180 for param in xxxClass.required + defaultNotRequired:
1181 textElem = g.tree.dom.createElement(param)
1182 try:
1183 textNode = g.tree.dom.createTextNode(xxxClass.default[param])
1184 except KeyError:
1185 textNode = g.tree.dom.createTextNode('')
1186 textElem.appendChild(textNode)
1187 elem.appendChild(textElem)
1188 return elem
1189
1190 # Make empty XXX object
1191 def MakeEmptyXXX(parent, className):
1192 # Make corresponding DOM object first
1193 elem = MakeEmptyDOM(className)
1194 # If parent is a sizer, we should create sizeritem object, except for spacers
1195 if parent:
1196 if parent.isSizer and className != 'spacer':
1197 sizerItemElem = MakeEmptyDOM(parent.itemTag)
1198 sizerItemElem.appendChild(elem)
1199 elem = sizerItemElem
1200 elif isinstance(parent, xxxNotebook):
1201 pageElem = MakeEmptyDOM('notebookpage')
1202 pageElem.appendChild(elem)
1203 elem = pageElem
1204 elif isinstance(parent, xxxChoicebook):
1205 pageElem = MakeEmptyDOM('choicebookpage')
1206 pageElem.appendChild(elem)
1207 elem = pageElem
1208 elif isinstance(parent, xxxListbook):
1209 pageElem = MakeEmptyDOM('listbookpage')
1210 pageElem.appendChild(elem)
1211 elem = pageElem
1212 # Now just make object
1213 return MakeXXXFromDOM(parent, elem)
1214
1215 # Make empty DOM element for reference
1216 def MakeEmptyRefDOM(ref):
1217 elem = g.tree.dom.createElement('object_ref')
1218 elem.setAttribute('ref', ref)
1219 return elem
1220
1221 # Make empty XXX object
1222 def MakeEmptyRefXXX(parent, ref):
1223 # Make corresponding DOM object first
1224 elem = MakeEmptyRefDOM(ref)
1225 # If parent is a sizer, we should create sizeritem object, except for spacers
1226 if parent:
1227 if parent.isSizer:
1228 sizerItemElem = MakeEmptyDOM(parent.itemTag)
1229 sizerItemElem.appendChild(elem)
1230 elem = sizerItemElem
1231 elif isinstance(parent, xxxNotebook):
1232 pageElem = MakeEmptyDOM('notebookpage')
1233 pageElem.appendChild(elem)
1234 elem = pageElem
1235 elif isinstance(parent, xxxChoicebook):
1236 pageElem = MakeEmptyDOM('choicebookpage')
1237 pageElem.appendChild(elem)
1238 elem = pageElem
1239 elif isinstance(parent, xxxListbook):
1240 pageElem = MakeEmptyDOM('listbookpage')
1241 pageElem.appendChild(elem)
1242 elem = pageElem
1243 # Now just make object
1244 xxx = MakeXXXFromDOM(parent, elem)
1245 # Label is not used for references
1246 xxx.allParams = xxx.allParams[:]
1247 #xxx.allParams.remove('label')
1248 return xxx
1249
1250 # Make empty comment node
1251 def MakeEmptyCommentDOM():
1252 node = g.tree.dom.createComment('')
1253 return node
1254
1255 # Make empty xxxComment
1256 def MakeEmptyCommentXXX(parent):
1257 node = MakeEmptyCommentDOM()
1258 # Now just make object
1259 xxx = MakeXXXFromDOM(parent, node)
1260 return xxx
1261