-
Notifications
You must be signed in to change notification settings - Fork 4
/
dom.py
executable file
·5195 lines (3950 loc) · 150 KB
/
dom.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import os
import re
import sys
import time
import glob
import base64
import ctypes
import struct
import random
import logging
import traceback
from Peach import Transformers
from Peach.Engine.common import *
from Peach.Engine.engine import Engine
from Peach.publisher import PublisherBuffer
import Peach
PeachModule = Peach
from copy import deepcopy
import cPickle as pickle
from lxml import etree
class Empty(object):
pass
def new_instancemethod(function, instance):
"""
bind 'method' to 'instance.method_name'
"""
instance_method_type = type(getattr(instance, "__init__"))
return instance_method_type(function, instance, type(instance))
class Element(object):
"""
Element in our template tree.
"""
#: For generating unknown element names
__CurNameNum = 0
def __init__(self, name = None, parent = None):
#: Name of Element, cannot include "."s
self._name = name
if not self._name:
self._name = Element.getUniqueName()
#: Parent of Element
self.parent = parent
#: If element has children
self.hasChildren = False
#: Type of this element
self.elementType = None
#: Fullname cache
self.fullName = None
#: The reference that made us, or None
self.ref = None
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if self.parent is not None and self.parent.get(self._name) == self:
del self.parent._childrenHash[self._name]
delattr(self.parent.children, self._name)
self.parent._childrenHash[value] = self
setattr(self.parent.children, value, self)
self._name = value
def toXml(self, parent):
pass
def __deepcopy__(self, memo):
"""
Copying objects in our DOM is a crazy business. Here we
try and help out as much as we can.
"""
# Copy procedures
#
# - Only copy children array (_children)
# - Remove array and re-add children via append
# - Set our __deepcopy__ attributes
# - Fixup our toXml functions
parent = self.parent
self.parent = None
# Only copy _children array
if isinstance(self, ElementWithChildren):
# Save other children collections
_childrenHash = self._childrenHash
children = self.children
# Null out children except for array
self._childrenHash = None
self.children = None
if self.elementType == 'block' or self.elementType == 'namespace':
toXml = self.toXml
self.toXml = None
## Perform actual copy
e = pickle.loads(pickle.dumps(self, -1))
## Remove attributes
if e.elementType == 'block':
e.toXml = toXml
self.toXml = toXml
self.parent = parent
if isinstance(self, ElementWithChildren):
# Set back other children collections
self._childrenHash = _childrenHash
self.children = children
# Fixup ElementWithChildren types
# We need to try and keep things in order
# and not have to many duplicated elements
children = e._children
e._children = []
e._childrenHash = {}
e.children = PeachModule.Engine.engine.Empty()
for c in children:
e.append(c)
# Fixup DataElements
if isinstance(e, DataElement):
for r in e.relations:
r.parent = e
if e.placement is not None:
e.placement.parent = e
for h in e.hints:
h.parent = e
if e.transformer is not None:
e.transformer.parent = e
return e
def getElementsByType(self, type, ret=None):
"""
Will return an array all elements of a specific type
in the tree starting with us.
TODO: optimize
"""
if ret is None:
ret = []
if isinstance(self, type):
ret.append(self)
return ret
@staticmethod
def getUniqueName():
"""
Provide a unique default name for elements.
Note: Some graphs can get very large (500K nodes)
at which point this name can eat up alot of memeory. So
lets keep it simple/small.
"""
name = "Named_%d" % Element.__CurNameNum
Element.__CurNameNum += 1
return name
def getRoot(self):
"""
Get the root of this DOM tree
"""
stack = {self}
root = self
while root.parent is not None:
if root.parent in stack:
raise Exception("Error: getRoot found a recursive relationship! EEk!")
root = root.parent
stack.add(root)
return root
def printDomMap(self, level = 0):
"""
Print out a map of the dom.
"""
print("%s- %s [%s](%s)" % ((" "*level), self.name, self.elementType, str(self)[-9:]))
def toXmlDom(self, parent, dict):
"""
Convert to an XML DOM object tree for use in xpath queries.
"""
owner = parent.getroottree()
if owner is None:
owner = parent
# Only use ref if name is not available!
if getattr(self, 'ref', None) is not None and self.name.startswith('Named_'):
ref = self.ref.replace(":", "_")
node = etree.Element(ref)
else:
try:
name = self.name.replace(":", "_")
node = etree.Element(name)
except Exception:
print("name:", self.name)
raise
node.set("elementType", self.elementType)
node.set("name", self.name)
if getattr(self, 'ref', None) is not None:
self._setXmlAttribute(node, "ref", self.ref)
self._setXmlAttribute(node, "fullName", self.getFullname())
dict[node] = self
dict[self] = node
parent.append(node)
return node
def toXmlDomLight(self, parent, dict):
"""
Convert to an XML DOM object tree for use in xpath queries.
Does not include values (Default or otherwise)
"""
owner = parent.getroottree()
if owner is None:
owner = parent
node = etree.Element(self.name)
node.set("elementType", self.elementType)
node.set("name", self.name)
if getattr(self, 'ref', None) is not None:
self._setXmlAttribute(node, "ref", self.ref)
self._setXmlAttribute(node, "fullName", self.getFullname())
dict[node] = self
dict[self] = node
parent.append(node)
return node
@staticmethod
def _setXmlAttribute(node, key, value):
"""
Set an XML attribute with handling for UnicodeDecodeError.
"""
try:
node.set(key, str(value))
value = str(node.get(key))
except UnicodeEncodeError:
node.set("%s-Encoded" % key, "base64")
node.set(key, base64.b64encode(str(value)))
except UnicodeDecodeError:
node.set("%s-Encoded" % key, "base64")
node.set(key, base64.b64encode(str(value)))
@staticmethod
def _getXmlAttribute(node, key):
"""
Get an XML attribute with handling for UnicodeDecodeError.
"""
if node.get(key) is None:
return None
if node.get("%s-Encoded" % key) is not None:
value = node.get(key)
value = base64.b64decode(value)
else:
value = str(node.get(key))
return value
def updateFromXmlDom(self, node, dict):
"""
Update our object based on an XML DOM object.
All we are taking for now is defaultValue.
"""
if node.get('defaultValue') is not None:
self.defaultValue = self._getXmlAttribute(node, "defaultValue")
if node.get('currentValue') is not None:
self.currentValue = self._getXmlAttribute(node, "currentValue")
if node.get('value') is not None:
self.value = self._getXmlAttribute(node, "value")
def compareTree(self, node1, node2):
"""
This method will compare two ElementWithChildren
object tree's.
"""
if node1.name != node2.name:
raise Exception("node1.name(%s) != node2.name(%s)" %(node1.name, node2.name))
if node1.elementType != node2.elementType:
raise Exception("Element types don't match [%s != %s]" % (node1.elementType, node2.elementType))
if not isinstance(node1, DataElement):
return True
if len(node1) != len(node2):
raise Exception("Lengths do not match %d != %d" % (len(node1), len(node2)))
if len(node1._childrenHash) > len(node1._children):
raise Exception("Node 1 length of hash > list")
if len(node2._childrenHash) > len(node2._children):
print("node1.name", node1.name)
print("node2.name", node2.name)
print("len(node1)", len(node1))
print("len(node2)", len(node2))
print("len(node1._childrenHash)", len(node1._childrenHash))
print("len(node2._childrenHash)", len(node2._childrenHash))
for c in node1._childrenHash.keys():
print("node1 hash key:", c)
for c in node2._childrenHash.keys():
print("node2 hash key:", c)
raise Exception("Node 2 length of hash > list")
for key, value in node1._childrenHash.iteritems():
if value not in node1._children:
raise Exception("Error: %s not found in node1 list" % key)
for key, value in node2._childrenHash.iteritems():
if value not in node2._children:
raise Exception("Error: %s not found in node2 list" % key)
for a, b in zip(node1, node2):
if not self.compareTree(a, b):
return False
return True
def copy(self, parent):
# We need to remove realParents before we can perform
# the copy and then replace then.
if isinstance(self, DataElement):
if hasattr(self, 'realParent'):
selfRealParent = self.realParent
self.realParent = object()
for child in self.getAllChildDataElements():
if getattr(child, 'realParent', None) is not None:
child.parent = child.realParent
child.realParent = object()
# Perform actual copy
newSelf = deepcopy(self)
newSelf.parent = parent
self._FixParents(newSelf, parent)
if isinstance(self, DataElement):
if hasattr(self, 'realParent'):
self.realParent = selfRealParent
for child in self.getAllChildDataElements():
if getattr(child, 'realParent', None) is not None:
child.realParent = child.parent
for child in newSelf.getAllChildDataElements():
if getattr(child, 'realParent', None) is not None:
child.realParent = child.parent
# Not sure if we realy want todo this.
if self.parent is None and parent is None and hasattr(self, 'realParent'):
newSelf.realParent = self.realParent
return newSelf
def _FixParents(self, start = None, parent = None):
"""
Walk down from start and fix parent settings on children
"""
if start is None:
start = self
if parent is not None:
start.parent = parent
if hasattr(start, 'fixup') and getattr(start, 'fixup') is not None:
start.fixup.parent = start
if isinstance(start, ElementWithChildren):
for child in start._children:
self._FixParents(child, start)
def getFullname(self):
if self.fullName is not None:
return self.fullName
name = self.name
node = self
while node.parent is not None:
# We need to handle namespaces here!!!
# TODO
node = node.parent
name = "%s.%s" % (node.name, name)
return name
def nextSibling(self):
"""
Get the next sibling or return None
"""
if self.parent is None:
return None
# First determin our position in parents children
ourIndex = self.parent._children.index(self)
# Check for next child
if len(self.parent._children) <= (ourIndex+1):
return None
#sys.stderr.write("nextSibling: %d:%d\n" % (len(self.parent), (ourIndex+1)))
return self.parent._children[ourIndex+1]
def previousSibling(self):
"""
Get the prior sibling or return None
"""
if self.parent is None:
return None
# First determin our position in parents children
ourIndex = self.parent._children.index(self)
# Check for next child
if ourIndex == 0:
return None
return self.parent._children[ourIndex-1]
def _setAttribute(self, node, name, value, default = None):
"""
Set an attribute on an XML Element. We only set the
attribute in the following cases:
1. We have no attached xml node or self.ref == None
2. We have a node, and the node has that attribute
3. The value is not None
"""
# Simplify the XML by not adding defaults
if value == default or value is None:
return
node.set(name, str(value))
GuidRegex = re.compile('^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
def _xmlHadChild(self, child):
"""
Verify that we should serialize child node. Checks
to see if we have an attached xml node and that xml
node has the child. If we don't have an attached
xml node then say we should add child.
"""
return True
class ElementWithChildren(Element):
"""
Contains functions that cause Element to act as a
hash table and array for children. Also children can
be accessed by name via self.children.name.
"""
def __init__(self, name = None, parent = None):
Element.__init__(self, name, parent)
self._children = [] #: List of children (in order)
self._childrenHash = {} #: Dictionary of children (by name)
self.children = Empty() #: Children object, has children as attributes by name
self.hasChildren = True
def getByName(self, name):
"""
Internal helper method, not for use!
"""
names = name.split(".")
node = self.getRoot()
if node.name != names[0]:
return None
obj = node
for i in range(1, len(names)):
if not obj.has_key(names[i]):
return None
obj = obj[names[i]]
return obj
def getElementsByType(self, type, ret = None):
"""
Will return array of a specific type
in the tree starting with us.
"""
if ret is None:
ret = []
if isinstance(self, type):
ret.append(self)
for child in self:
if isinstance(child, ElementWithChildren):
child.getElementsByType(type, ret)
return ret
def printDomMap(self, level = 0):
"""
Print out a map of the dom.
"""
print("")
print(" "*level) + "+ %s [%s](%s)" % (self.name, self.elementType, str(self)[-9:])
for child in self:
if isinstance(child, Element):
child.printDomMap(level+1)
if child.parent != self:
raise Exception("Error: printDomMap: %s.parent != self : %s:%s " % (child.name, child.name, repr(child.parent)))
def verifyDomMap(self):
"""
Verify parent child relationship across DOM Tree
"""
for child in self:
if isinstance(child, Element):
if child.parent != self:
raise Exception("Error: verifyDomMap: %s.parent != self : %s:%s " % (child.name, child.name, repr(child.parent)))
if isinstance(child, ElementWithChildren):
child.verifyDomMap()
def toXmlDom(self, parent, dict):
"""
Convert to an XML DOM boject tree for use in xpath queries.
"""
node = Element.toXmlDom(self, parent, dict)
for child in self._children:
if hasattr(child, 'toXmlDom'):
child.toXmlDom(node, dict)
return node
def toXmlDomLight(self, parent, dict):
"""
Convert to an XML DOM boject tree for use in xpath queries.
Note: toXmlDomLight and toXmlDom are the same now
"""
node = Element.toXmlDomLight(self, parent, dict)
for child in self._children:
if hasattr(child, 'toXmlDomLight'):
child.toXmlDomLight(node, dict)
return node
def updateFromXmlDom(self, node, dict):
"""
Update our object based on an XML DOM object.
All we are taking for now is defaultValue.
"""
Element.updateFromXmlDom(self, node, dict)
if node.hasChildNodes():
for child in node.iterchildren():
dict[child].updateFromXmlDom(child, dict)
def append(self, obj):
# If we have the key we need to replace it
if self._childrenHash.has_key(obj.name):
self[obj.name] = obj
obj.parent = self
return
# Otherwise add it at the end
self._children.append(obj)
self._childrenHash[obj.name] = obj
setattr(self.children, obj.name, obj)
# Reset parent relationship
obj.parent = self
def index(self, obj):
return self._children.index(obj)
def insert(self, index, obj):
if obj in self._children:
raise Exception("object already child of element")
# Update parent
obj.parent = self
self._children.insert(index, obj)
if obj.name is not None:
#print "inserting ",obj.name
self._childrenHash[obj.name] = obj
setattr(self.children, obj.name, obj)
def firstChild(self):
if len(self._children) >= 1:
return self._children[0]
return None
def lastChild(self):
if len(self._children) >= 1:
return self._children[-1]
return None
def has_key(self, name):
return self._childrenHash.has_key(name)
# Container emulation methods ############################
# Note: We have both a dictionary and an ordered list
# that we must keep upto date. This allows us
# to access children by index or by key
# So saying: elem[0] is valid as is elem['Name']
def __len__(self):
return self._children.__len__()
def get(self, key, default=None):
try:
return self.__getitem__(key)
except (KeyError, IndexError):
return default
def __getitem__(self, key):
if type(key) == int:
return self._children.__getitem__(key)
return self._childrenHash.__getitem__(key)
def __setitem__(self, key, value):
if type(key) == int:
oldObj = self._children[key]
if oldObj.name is not None:
del self._childrenHash[oldObj.name]
#delattr(self.children, oldObj.name)
if value.name is not None:
self._childrenHash[value.name] = value
setattr(self.children, value.name, value)
return self._children.__setitem__(key, value)
else:
if key in self._childrenHash:
# Existing item
inx = self._children.index( self._childrenHash[key] )
self._children[inx] = value
self._childrenHash[key] = value
setattr(self.children, value.name, value)
else:
self._children.append(value)
self._childrenHash[key] = value
setattr(self.children, value.name, value)
def __delitem__(self, key):
if type(key) == int:
obj = self._children[key]
if obj.name is not None:
del self._childrenHash[obj.name]
delattr(self.children, obj.name)
return self._children.__delitem__(key)
obj = self._childrenHash[key]
try:
self._children.remove(obj)
except:
pass
try:
del self._childrenHash[key]
except:
pass
if hasattr(self.children, key):
delattr(self.children, key)
def __iter__(self):
return self._children.__iter__()
def __contains__(self, item):
return self._children.__contains__(item)
class Mutatable(ElementWithChildren):
"""
To mark a DOM object as mutatable(fuzzable) or not
"""
def __init__(self, name = None, parent = None, isMutable = True):
ElementWithChildren.__init__(self, name, parent)
#: Can this object be changed by the mutators?
self.isMutable = isMutable
def setMutable(self, value):
"""
Update this element and all childrens isMutable.
"""
for child in self:
if isinstance(child, Mutatable):
child.setMutable(value)
self.isMutable = value
class DataElement(Mutatable):
"""
Data elements compose the Data Model. This is the base
class for String, Number, Block, Template, etc.
When iterating over the Peach DOM if an element
isinstance(obj, DataElement) it is part of a data model.
"""
def __init__(self, name = None, parent = None):
ElementWithChildren.__init__(self, name, parent)
if name is not None and (name.find(".") > -1 or name.find(":") > -1):
raise PeachException("Name '%s' contains characters not allowed in names such as period (.) or collen (:)" % name)
#: Is this a ctypes pointer to something? (Defaults to False)
self.isPointer = False
#: What is out pointer depth? (e.g. void** p is 2), (Defaults to 1)
self.pointerDepth = 1
#: Optional constraint used during data cracking, python expression
self.constraint = None
#: Should element be mutated?
self.isMutable = True
#: Does data model have an offset relation?
self.modelHasOffsetRelation = None
#: Cache of relation, list of full data names (String) of each relation from here down. cache is build post incoming.
self.relationCache = None
#: Key is full data name of "of" element (string), value is list of relation full data names (String). cache is bulid post incoming.
self.relationOfCache = None
#: Event that occurs prior to parsing the next array element.
self.onArrayNext = None
#: Transformers to apply
self.transformer = None
#: Fixup if any
self.fixup = None
#: Placement if any
self.placement = None
#: Relations this element has
self.relations = ArraySetParent(self)
#: Mutator Hints
self.hints = ArraySetParent(self)
#: Fixed occurs
self.occurs = None
#: Minimum occurences
self._minOccurs = 1
#: Maximum occurences
self._maxOccurs = 1
self.generatedOccurs = 1
#: Default value to use
self._defaultValue = None
#: Mutated value prior to packing and transformers
self._currentValue = None
#: Mutated value after everything but transformers
self._finalValue = None
#: Current value
self._value = None
#: Expression used by data cracker to determin
#: if element should be included in cracking.
self.when = None
self._inInternalValue = False #: Used to prevent recursion
# Attributes for elements part of an array
self.array = None #: Name of array. The origional name of the data element.
self.arrayPosition = None #: Our position in the array.
self.arrayMinOccurs = None #: The min occurences in the array
self.arrayMaxOccurs = None #: The max occurences in the array
#: Position in data stream item was parsed at
self._pos = None
self._possiblePos = None
#: Parse rating for element
self.rating = None
#: Is this element a static token?
self.isStatic = False
#: A StringBuffer used to determin offset relations
self.relationStringBuffer = None
#: Fullname in data model
self.fullNameDataModel = None
def get_DefaultValue(self):
return self._defaultValue
def set_DefaultValue(self, value):
self._defaultValue = value
#self._currentValue = None
self._value = None
self._finalValue = None
defaultValue = property(get_DefaultValue, set_DefaultValue, None)
def get_CurrentValue(self):
return self._currentValue
def set_CurrentValue(self, value):
self._currentValue = value
self._value = None
self._finalValue = None
currentValue = property(get_CurrentValue, set_CurrentValue, None)
def get_Value(self):
return self._value
def set_Value(self, value):
self._value = value
self._finalValue = None
value = property(get_Value, set_Value, None)
def get_FinalValue(self):
return self._finalValue
def set_FinalValue(self, value):
self._finalValue = value
finalValue = property(get_FinalValue, set_FinalValue, None)
@property
def pos(self):
"""
Getter for pos property. If we have a string buffer
associated with the root node, use that for the correct
position.
"""
obj = self
while obj.parent is not None and (not hasattr(obj, "relationStringBuffer") or obj.relationStringBuffer is None):
obj = obj.parent
if hasattr(obj, "relationStringBuffer") and obj.relationStringBuffer is not None:
value = obj.relationStringBuffer.getPosition(self.getFullnameInDataModel())
if value is not None:
return value
else:
return 0
return self._pos
@pos.setter
def pos(self, value):
"""
Setter for pos property
"""
self._pos = value
return self._pos
def get_possiblePos(self):
"""
Getter for pos property. If we have a string buffer
associated with the root node, use that for the correct
position.
"""
obj = self
while obj.parent is not None and (not hasattr(obj, "relationStringBuffer") or obj.relationStringBuffer is None):
obj = obj.parent
if hasattr(obj, "relationStringBuffer") and obj.relationStringBuffer is not None:
value = obj.relationStringBuffer.getPosition(self.getFullnameInDataModel())
if value is not None:
return value
##BUG: Leave this commented out else we introduce a bug in the data cracker
## that was run into with opentype.xml used in eot.xml.
##else:
## print "get_possiblePos: relationStringBuffer was of no use to us!"
## return 0
return self._possiblePos
def set_possiblePos(self, value):
"""
Setter for pos property
"""
self._possiblePos = value
return self._possiblePos
possiblePos = property(get_possiblePos, set_possiblePos, None)
def getElementsByType(self, type, ret = None):
"""
Will return an array all elements of a specific type
in the tree starting with us.
"""
if ret is None:
ret = []
if isinstance(self, type):
ret.append(self)
elif self.fixup is not None:
for child in self.fixup:
if isinstance(child, ElementWithChildren):
child.getElementsByType(type, ret)
for child in self:
if isinstance(child, ElementWithChildren):
child.getElementsByType(type, ret)
return ret
def clone(self, obj):
if obj is None:
raise Exception("Generic clone needs object instance!")
obj.name = self.name
obj.parent = self.parent
obj.hasChildren = self.hasChildren
obj.elementType = self.elementType
obj.fullName = self.fullName
obj.ref = self.ref
obj.generatedOccurs = self.generatedOccurs
obj.isPointer = self.isPointer
obj.pointerDepth = self.pointerDepth
obj.constraint = self.constraint