forked from enthought/mayavi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrapper_gen.py
1890 lines (1616 loc) · 75.8 KB
/
wrapper_gen.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 module generates the tvtk (Traited VTK) wrapper classes for
VTK classes.
"""
# Author: Prabhu Ramachandran
# Copyright (c) 2004-2020, Enthought, Inc.
# License: BSD Style.
import re
import sys
import vtk
import textwrap
import keyword
import copy
from itertools import chain
# Local imports (these are relative imports because the package is not
# installed when these modules are imported).
from .common import get_tvtk_name, camel2enthought, vtk_major_version
from . import vtk_parser
from . import indenter
from . import special_gen
try:
import faulthandler
except ImportError:
pass
else:
faulthandler.enable()
def get_trait_def(value, **kwargs):
""" Return the appropriate trait type, reformatted string and
the associated traits meta data for a given `value`
If a sequence is given, traits.Array is returned instead of
traits.Tuple or traits.List
Parameters
----------
value
can be anything
kwargs : dict
keyword arguments for the trait definition
Returns
-------
tuple : (str, str, str)
(trait_type, value, keyword_arguments)
Raises
------
TypeError
if this function cannot find an appropriate Trait type for `value`
Example
-------
>>> get_trait_def([100., 200.], enter_set=True, auto_set=False)
('traits.Array', '', 'auto_set=False, enter_set=True, shape=(2,), dtype=float, value=[100.0, 200.0], cols=2')
>>> get_trait_def(100, enter_set=True, auto_set=False)
('traits.Int', '100', 'auto_set=False, enter_set=True')
>>> get_trait_def(u'something', enter_set=True, auto_set=False)
('traits.Unicode', "u'something'", 'auto_set=False, enter_set=True')
>>> get_trait_def(True, enter_set=True, auto_set=False)
('traits.Bool', 'True', 'auto_set=False, enter_set=True')
"""
kwargs_code = ', '.join('{0}={1}'.format(key, value)
for key, value in kwargs.items())
type_ = type(value)
number_map = {int: 'traits.Int',
float: 'traits.Float'}
if type_ in number_map:
return number_map[type_], str(value), kwargs_code
elif type_ is str:
if value == '\x00':
value = ''
return 'traits.String', '{!r}'.format(value), kwargs_code
elif type_ in (tuple, list):
shape = (len(value),)
dtypes = set(type(element) for element in value)
dtype = dtypes.pop().__name__ if len(dtypes) == 1 else None
if dtype == 'int' and sys.platform.startswith('win'):
dtype = 'int64'
elif dtype == 'long':
dtype = 'int64'
dtype = '"{}"'.format(dtype) if dtype is not None else 'None'
cols = len(value)
if kwargs_code:
kwargs_code += ', '
kwargs_code += ('shape={shape}, dtype={dtype}, '
'value={value!r}, cols={cols}').format(
shape=shape, dtype=dtype,
value=value, cols=min(3, cols))
return 'traits.Array', '', kwargs_code
elif type_ is bool:
return 'traits.Bool', str(value), kwargs_code
else:
raise TypeError("Could not understand type: {}".format(type_))
def patch_default(vtk_get_meth, vtk_set_meth, default):
"""Patch the initial default value for an attribute of
a VTK class that does not initialise it properly.
Parameters
----------
vtk_get_meth : Method for getting the position attribute
vtk_set_meth : Method for setting the position attribute
default : initial default value
Returns
-------
default
If patching fails, the initial default is returned
Examples
--------
>>> import vtk
>>> vtk.vtkVersion.GetVTKVersion()
'6.3.0'
>>> obj = vtk.vtkXOpenGLRenderWindow()
>>> obj.GetPosition()
'_000000000351c458_p_void'
>>> patch_default(vtk.vtkXOpenGLRenderWindow.GetPosition,
vtk.vtkXOpenGLRenderWindow.SetPosition,
'_000000000351c458_p_void')
(0, 0)
"""
# We will attempt to guess the default by looking into the
# arguments of the Set method
# SetPosition(int, int) has a signature of ("int", "int")
# SetPosition(int position[2]) has a signature of (["int", "int"],)
# Some method even has a signature of (["int", "int"], "vtkInformation")
arg_formats = []
# Collect the signatures of the get method
# We only use the arguments
all_sigs = vtk_parser.VTKMethodParser.get_method_signature(vtk_get_meth)
# Collect the signatures of the set method
all_sigs.extend(
vtk_parser.VTKMethodParser.get_method_signature(vtk_set_meth))
for sig in all_sigs:
if sig[1] is None:
continue
if len(sig[1]) == 1:
# This unpacks tuple of something e.g. (('int', 'int', 'int'))
arg_formats.append(tuple(chain.from_iterable(sig[1])))
arg_formats.append(tuple(sig[1]))
default_mappings = {
'int' : 0,
'float': 0.0,
'string': ''
}
for arg_format in arg_formats:
try:
all_same_type = len(set(arg_format)) == 1
except TypeError: # Unhashable
continue
if all_same_type and arg_format[0] in default_mappings:
# All types in `arg_format` are the same and they are
# in the mapping (e.g. arg_format = ('int', 'int')
default = default_mappings[arg_format[0]]
if len(arg_format) > 1:
return (default,)*len(arg_format)
else:
return default
else:
return default
######################################################################
# `WrapperGenerator` class.
######################################################################
class WrapperGenerator:
"""Generates the wrapper code for all the TVTK classes.
"""
def __init__(self):
self.indent = indenter.Indent()
self.parser = vtk_parser.VTKMethodParser()
self.special = special_gen.SpecialGenerator(self.indent)
self.dm = indenter.VTKDocMassager()
#################################################################
# `WrapperGenerator` interface.
#################################################################
def get_tree(self):
"""Returns the parser's class tree."""
return self.parser.get_tree()
def generate_code(self, node, out):
"""Generates the code for the given node in the parse tree
along with an opened file-like object.
Parameters
----------
- node
A node in the ClassTree.
- out : file-like object.
Must support a `write` method. Code is written to it.
"""
self.indent.reset()
self._write_prelims(node, out)
# Write the class decl and __init__
self._gen_class_init(node, out)
# Write the other methods.
self._gen_methods(node, out)
# Write any special code if available.
self.special.generate_code(node, out)
out.write('\n')
#################################################################
# Non-public interface.
#################################################################
def _write_prelims(self, node, out):
"""Write preliminary information given the node in the class
tree, `node`, and output file-like object, `out`.
"""
prelim = """
# Automatically generated code: EDIT AT YOUR OWN RISK
from traits import api as traits
from traitsui.item import Item, spring
from traitsui.group import HGroup
from traitsui.view import View
from tvtk import vtk_module as vtk
from tvtk import tvtk_base
from tvtk.tvtk_base_handler import TVTKBaseHandler
from tvtk import messenger
from tvtk.tvtk_base import deref_vtk
from tvtk import array_handler
from tvtk.array_handler import deref_array
from tvtk.tvtk_classes.tvtk_helper import wrap_vtk
nan = float('nan')
def InstanceEditor(*args, **kw):
from traitsui.editors.api import InstanceEditor as Editor
return Editor(view_name="handler.view")
try:
long
except NameError:
# Silly workaround for Python3.
long = int
inf = float('inf')
"""
out.write(self.indent.format(prelim))
def _gen_class_init(self, node, out):
indent = self.indent
klass = self.get_tree().get_class(node.name)
vtk_class_name = klass.__name__
class_name = self._get_class_name(klass)
if node.level == 0 or node.name == 'vtkObjectBase':
base_name = 'tvtk_base.TVTKBase'
else:
base_name = self._get_class_name(klass.__bases__)[0]
if base_name != 'object':
# Import the base class.
base_fname = camel2enthought(base_name)
_imp = "from tvtk.tvtk_classes.%(base_fname)s import %(base_name)s"%locals()
out.write(indent.format(_imp))
out.write('\n\n')
# Write the class declaration.
cdef = """
class %(class_name)s(%(base_name)s):
"""%locals()
out.write(indent.format(cdef))
self.dm.write_class_doc(klass.__doc__, out, indent)
indent.incr()
# Write __init__
decl = """
def __init__(self, obj=None, update=True, **traits):
tvtk_base.TVTKBase.__init__(self, vtk.%(vtk_class_name)s, obj, update, **traits)
"""%locals()
out.write(indent.format(decl))
if 'vtk3DWidget' in [x.name for x in node.get_ancestors()]:
# In this case we also update the traits on the
# EndInteractionEvent. Note that we don't need to change
decl = '''
def setup_observers(self):
"""Setup the observers for the object."""
super(%(class_name)s, self).setup_observers()
tvtk_base._object_cache.setup_observers(self._vtk_obj,
'EndInteractionEvent',
self.update_traits)
'''%locals()
out.write(indent.format(decl))
def _gen_methods(self, node, out):
klass = self.get_tree().get_class(node.name)
self.parser.parse(klass)
if klass.__name__ == 'vtkCamera':
# 'vtkCamera.Roll' has conflicting signatures --
# Get/SetRoll() plus an additional Roll() method. So we
# wrap all of them as methods and not as traits.
p = self.parser
p.get_set_meths.pop('Roll')
p.other_meths.extend(['GetRoll', 'SetRoll'])
# ----------------------------------------
# Generate the code.
# The return values are editable traits.
toggle, toggle_allow_failure = self._gen_toggle_methods(klass, out)
state = self._gen_state_methods(klass, out)
# The first return value contains updateable traits
# the second return value contains dubious traits that
# are initialised by VTK on init
get_set, allow_update_failure = self._gen_get_set_methods(klass, out)
allow_update_failure.update(toggle_allow_failure)
# These do not produce editable traits.
self._gen_get_methods(klass, out)
self._gen_other_methods(klass, out)
# ----------------------------------------
# Now write out the _updateable_traits_ and View related code.
# Store the data in the node after updating from parents.
# Note that this data is generated and stored at run
# time. This is the reason why the wrapper code for the
# classes are generated in the reverse order of their depth in
# the inheritance tree.
data = {'toggle':toggle, 'state':state, 'get_set':get_set,
'allow_update_failure': allow_update_failure}
if node.level != 0 and node.parents[0].name != 'object':
pd = node.parents[0].data
for i in data.keys():
data[i].update(pd[i])
node.data = data
# ----------------------------------------
# Write out the updateable traits, this is used by
# the `update_traits` method.
ut = {}
for i in (data['toggle'], data['state'], data['get_set']):
ut.update(i)
junk = textwrap.fill(repr(tuple(ut.items())))
code = "\n_updateable_traits_ = \\" + "\n%s\n\n"%junk
out.write(self.indent.format(code))
# ----------------------------------------
# Write out the allow_update_failure traits, this is used by
# the `update_traits` method.
junk = textwrap.fill(repr(tuple(data['allow_update_failure'])))
code = "\n_allow_update_failure_ = \\" + "\n%s\n\n"%junk
out.write(self.indent.format(code))
# ----------------------------------------
# Write out the full_traits_view and the more compact
# traits_view
# First copy the data over (we're going to edit it and don't
# want the node's version to be changed).
d = copy.deepcopy(data)
# Add support for property trait delegation.
#Commented out because of problems.
#self._generate_delegates(node, d, out)
toggle, state, get_set = d['toggle'], d['state'], d['get_set']
# Remove unwanted stuff.
def _safe_remove(d, keys):
for key in keys:
try:
del d[key]
except KeyError:
pass
# No point having these in the GUI.
_safe_remove(get_set, ['reference_count', 'progress'])
class_name = get_tvtk_name(node.name)
title = 'Edit %s properties'%class_name
# Write the full_traits_view.
# The full traits view displays all of the relevant traits in a table
# editor. For this, we first write out the _full_traitnames_list: this
# is used by the TVTKBaseHandler to build a TableEditor for all of
# the (relevant) traits in the tvtk object.
t_g = sorted(toggle.keys())
s_g = sorted(state.keys())
gs_g = sorted(get_set.keys())
junk = textwrap.fill("(%s)" % (t_g + s_g + gs_g))
code = "\n_full_traitnames_list_ = \\" + "\n%s\n\n"%junk
out.write(self.indent.format(code))
# Start the trait_view() method.
code = "\ndef trait_view(self, name=None, view_element=None):"
out.write(self.indent.format(code))
self.indent.incr()
code = "\nif view_element is not None or name not in (None, '', 'traits_view', 'full_traits_view', 'view'):"
out.write(self.indent.format(code))
self.indent.incr()
code = "\nreturn super(%s, self).trait_view(name, view_element)" % class_name
out.write(self.indent.format(code))
self.indent.decr()
# Now write the full traits view.
code = "\nif name == 'full_traits_view':"
out.write(self.indent.format(code))
self.indent.incr()
item_contents = (
'Item("handler._full_traits_list",show_label=False)')
junk = 'View((%s),'% item_contents
code = "\nfull_traits_view = \\" + \
"\n%s\ntitle=\'%s\', scrollable=True, resizable=True,"\
"\nhandler=TVTKBaseHandler,"\
"\nbuttons=['OK', 'Cancel'])"\
"\nreturn full_traits_view"%(junk, title)
out.write(self.indent.format(code))
self.indent.decr()
# Next, we write a compact traits_view (which we call 'view'), which
# removes some generally unused items.
code = "\nelif name == 'view':"
out.write(self.indent.format(code))
self.indent.incr()
_safe_remove(get_set, ['progress_text'])
_safe_remove(toggle, ['abort_execute', 'release_data_flag',
'dragable', 'pickable',
'debug', 'global_warning_display'])
t_g = sorted(toggle.keys())
s_g = sorted(state.keys())
gs_g = sorted(get_set.keys())
junk = textwrap.fill('View((%s, %s, %s),'%(t_g, s_g, gs_g))
code = "\nview = \\" + \
"\n%s\ntitle=\'%s\', scrollable=True, resizable=True,"\
"\nhandler=TVTKBaseHandler,"\
"\nbuttons=['OK', 'Cancel'])"\
"\nreturn view"%(junk, title)
out.write(self.indent.format(code))
self.indent.decr()
# Finally, we write the default traits_view which includes a field
# for specifying the view type (basic or advanced) and the
# corresponding view (basic->view and advanced->full_traits_view)
code = "\nelif name in (None, 'traits_view'):"
out.write(self.indent.format(code))
self.indent.incr()
viewtype_contents = (
'HGroup(spring, "handler.view_type", ' +\
'show_border=True)')
view_contents = (
'\nItem("handler.info.object", ' +\
'editor = InstanceEditor(view_name="handler.view"), ' +\
'style = "custom", show_label=False)')
junk = 'View((%s, %s),'% (viewtype_contents, view_contents)
code = "\ntraits_view = \\" + \
"\n%s\ntitle=\'%s\', scrollable=True, resizable=True,"\
"\nhandler=TVTKBaseHandler,"\
"\nbuttons=['OK', 'Cancel'])"\
"\nreturn traits_view\n\n"%(junk, title)
out.write(self.indent.format(code))
self.indent.decr()
self.indent.decr()
def _generate_delegates(self, node, n_data, out):
"""This method generates delegates for specific classes. It
modifies the n_data dictionary."""
prop_name = {'vtkActor': 'vtkProperty',
'vtkActor2D': 'vtkProperty2D',
'vtkVolume': 'vtkVolumeProperty'}
if node.name in prop_name:
prop_node = self.get_tree().get_node(prop_name[node.name])
prop_data = prop_node.data
# Update the data of the node so the view includes the
# property traits.
code = ''
for key in n_data:
props = prop_data[key]
n_data[key].update(props)
# Write the delegates.
for p in props:
code += '%s = tvtk_base.vtk_property_delegate\n'%p
code += '\n'
out.write(self.indent.format(code))
def _gen_toggle_methods(self, klass, out):
meths = self.parser.get_toggle_methods()
updateable_traits = {}
allow_update_failure = set()
for m in meths:
name = self._reform_name(m)
#-----------------------------------------------------------
# Some traits have special API or the VTK API is broken that
# we need to handle them separately.
# Warning: Be critical about whether the case is special
# enthough to be added to the `special_traits` mapping
# -----------------------------------------------------------
if self._is_special(klass, m):
updateable, can_fail = self._get_special_updateable_failable(
klass, m)
if not updateable:
# We cannot update this trait
del updateable_traits[name]
elif can_fail:
# We will update this trait but updating can fail
allow_update_failure.add(name)
self._write_special_trait(klass, out, m)
continue
updateable_traits[name] = 'Get' + m
t_def = 'tvtk_base.false_bool_trait'
if meths[m]:
t_def = 'tvtk_base.true_bool_trait'
try:
vtk_set_meth = getattr(klass, 'Set' + m)
except AttributeError:
# Broken VTK API (4.2) where sometimes GetProp and
# PropOn/Off exist but no SetProp method is available.
vtk_get_meth = getattr(klass, 'Get' + m)
self._write_trait(out, name, t_def, vtk_get_meth,
mapped=True, broken_bool=True)
else:
self._write_trait(out, name, t_def, vtk_set_meth,
mapped=True)
return updateable_traits, allow_update_failure
def _gen_state_methods(self, klass, out):
parser = self.parser
indent = self.indent
meths = parser.get_state_methods()
updateable_traits = {}
for m in meths:
name = self._reform_name(m)
updateable_traits[name] = 'Get' + m
d = {}
vtk_val = 0
for key, val in meths[m]:
d[self._reform_name(key)] = val
if isinstance(val, vtk.vtkObjectBase):
vtk_val = 1
# Setting the default value of the traits of these classes
# Else they are not instantiable
if klass.__name__ == 'vtkCellQuality' \
and m == 'QualityMeasure':
vtk_val = 1
elif klass.__name__ == 'vtkRenderView' \
and m == 'InteractionMode':
vtk_val = 1
elif klass.__name__ == 'vtkMatrixMathFilter' \
and m == 'Operation':
vtk_val = 1
elif klass.__name__ == 'vtkResliceImageViewer' \
and m == 'ResliceMode':
vtk_val = 'axis_aligned'
elif klass.__name__ == 'vtkThreshold' \
and m == 'PointsDataType':
vtk_val = 10
if (not hasattr(klass, 'Set' + m)):
# Sometimes (very rarely) the VTK method is
# inconsistent. For example in VTK-4.4
# vtkExtentTranslator::SetSplitMode does not exist.
# In this case wrap it specially.
vtk_val = 1
if vtk_val == 0 and m in ['DataScalarType', 'OutputScalarType',
'UpdateExtent']:
vtk_val = 2
# Sometimes, some methods have default values that are
# outside the specified choices. This is to special case
# these.
extra_val = None
if vtk_val == 0 and klass.__name__ == 'vtkGenericEnSightReader' \
and m == 'ByteOrder':
extra_val = 2
if vtk_val == 0 and klass.__name__ == 'vtkImageData' \
and m == 'ScalarType':
extra_val = list(range(0, 22))
if vtk_val == 0 and klass.__name__ == 'vtkImagePlaneWidget' \
and m == 'PlaneOrientation':
extra_val = 3
if (vtk_val == 0) and (klass.__name__ == 'vtkThreshold') \
and (m == 'AttributeMode'):
extra_val = -1
if (sys.platform == 'darwin') and (vtk_val == 0) \
and (klass.__name__ == 'vtkRenderWindow') \
and (m == 'StereoType'):
extra_val = 0
if not vtk_val:
default = self._reform_name(meths[m][0][0])
if extra_val is None:
t_def = """tvtk_base.RevPrefixMap(%(d)s, default_value='%(default)s')""" % locals()
elif hasattr(extra_val, '__iter__'):
extra_val = str(extra_val)[1:-1]
if (not hasattr(klass, 'Set' + m)):
# Sometimes (very rarely) the VTK method is
# inconsistent. For example in VTK-4.4
# vtkExtentTranslator::SetSplitMode does not exist.
# In this case wrap it specially.
vtk_val = 1
if vtk_val == 0 and m in ['DataScalarType', 'OutputScalarType',
'UpdateExtent']:
vtk_val = 2
# Sometimes, some methods have default values that are
# outside the specified choices. This is to special case
# these.
extra_val = None
if vtk_val == 0 and klass.__name__ == 'vtkGenericEnSightReader' \
and m == 'ByteOrder':
extra_val = 2
elif (vtk_val == 0 and
klass.__name__ == 'vtkPolyDataEdgeConnectivityFilter' and
m == 'RegionGrowing'):
extra_val = 0
elif vtk_val == 0 and klass.__name__ == 'vtkImageData' \
and m == 'ScalarType':
extra_val = list(range(0, 22))
elif vtk_val == 0 and klass.__name__ == 'vtkImagePlaneWidget' \
and m == 'PlaneOrientation':
extra_val = 3
elif (vtk_val == 0) and (klass.__name__ == 'vtkThreshold') \
and (m == 'AttributeMode'):
extra_val = -1
elif (sys.platform == 'darwin') and (vtk_val == 0) \
and (klass.__name__ == 'vtkRenderWindow') \
and (m == 'StereoType'):
extra_val = 0
if not vtk_val:
default = self._reform_name(meths[m][0][0])
if extra_val is None:
t_def = """tvtk_base.RevPrefixMap(%(d)s, default_value='%(default)s')""" % locals()
elif hasattr(extra_val, '__iter__'):
extra_val = str(extra_val)[1:-1]
t_def = """tvtk_base.RevPrefixMap(%(d)s, %(extra_val)s, default_value='%(default)s')""" % locals()
else:
t_def = """tvtk_base.RevPrefixMap(%(d)s, %(extra_val)s, default_value='%(default)s')""" % locals()
vtk_set_meth = getattr(klass, 'Set' + m)
self._write_trait(out, name, t_def, vtk_set_meth,
mapped=True)
else:
del updateable_traits[name]
vtk_meth = getattr(klass, 'Get' + m)
self._write_tvtk_method(klass, out, vtk_meth)
if vtk_val == 2:
vtk_meth = getattr(klass, 'Set' + m)
self._write_tvtk_method(klass, out, vtk_meth)
for key, val in meths[m][1:]:
x = self._reform_name(key)
vtk_meth = getattr(klass, 'Set%sTo%s'%(m, key))
decl = 'def set_%s_to_%s(self):'%(name, x)
body = 'self._vtk_obj.Set%(m)sTo%(key)s()\n'%locals()
self._write_generic_method(out, decl, vtk_meth, body)
return updateable_traits
def _gen_get_set_methods(self, klass, out):
parser = self.parser
meths = parser.get_get_set_methods()
updateable_traits = {}
allow_update_failure = set()
for vtk_attr_name in meths: # VTK Attribute name (e.g. PropColorValue)
# trait name
name = self._reform_name(vtk_attr_name)
updateable_traits[name] = 'Get' + vtk_attr_name
vtk_set_meth = getattr(klass, 'Set' + vtk_attr_name)
vtk_get_meth = getattr(klass, 'Get' + vtk_attr_name)
get_sig = parser.get_method_signature(vtk_get_meth)
set_sig = parser.get_method_signature(vtk_set_meth)
#- ----------------------------------------------------------
# Some traits have special API or the VTK API is broken that
# we need to handle them separately.
# Warning: Be critical about whether the case is special
# enthough to be added to the `special_traits` mapping
# -----------------------------------------------------------
if self._is_special(klass, vtk_attr_name):
updateable, can_fail = self._get_special_updateable_failable(
klass, vtk_attr_name)
if not updateable:
# We cannot update this trait
del updateable_traits[name]
elif can_fail:
# We will update this trait but updating can fail
allow_update_failure.add(name)
self._write_special_trait(klass, out, vtk_attr_name)
continue
# --------------------------------------------------------
# If it is an abstract class with no concrete subclass
# and if we can read the get method signature, we write
# the get and set methods and done
# --------------------------------------------------------
if not meths[vtk_attr_name] and get_sig[0][1]:
self._write_tvtk_method(klass, out, vtk_get_meth, get_sig)
self._write_tvtk_method(klass, out, vtk_set_meth)
continue
# -------------------------------
# Get default values
# -------------------------------
if meths[vtk_attr_name]:
default, rng = meths[vtk_attr_name]
else:
# In some rare cases, the vtk class is an abstract class
# that does not have a concrete subclass
# We patch the default using the get/set method
# while the below seems a hack, this is the best we could do
default, rng = (patch_default(vtk_get_meth, vtk_set_meth, None),
None)
# --------------------------------------------------------
# Has a specified range of valid values. Write and done
# --------------------------------------------------------
if rng:
self._write_trait_with_range(klass, out, vtk_attr_name)
continue
# ----------------------------------------------------------
# The VTK Get method for the attribute returns the address
# to a pointer, this is therefore, a VTK python bug
# ----------------------------------------------------------
if isinstance(default, str) and default.endswith('_p_void'):
try:
self._write_trait_with_default_undefined(klass, out,
vtk_attr_name)
except TypeError as exception:
# We could not write the trait
# we will let the next clause handle it
print('Warning:', str(exception))
default = None
else:
# Getting the trait value using the get method
# without argument will continue to return an address to
# a pointer, so there is no point in updating.
# However, some VTK Get methods have multiple signatures
# among which you could pass a numpy array of the right
# size and the Get method would populate the array with
# the value of the attribute
# e.g. x = numpy.empty(9); ImageConvolve.GetKernel3x3(x)
# FIXME: we could try harder in retrieving these values
# in TVTKBase.update_traits
del updateable_traits[name]
continue
# ------------------------------------------------------
# The default is None, depending on the get/set methods
# signature, we will either have the trait as a Property
# and write getter/setter or we would just write the
# VTK get and set methods
# -------------------------------------------------------
if default is None or isinstance(default, vtk.vtkObjectBase):
# Bunch of hacks to work around issues.
if len(get_sig) == 0:
get_sig = [([None], None)]
if len(set_sig) == 0:
set_sig = [([None], [None])]
get_sig = [([None], None)]
elif set_sig[0][1] is None or set_sig[0][1] == '':
set_sig[0] = list(set_sig[0])
set_sig[0][1] = [None]
if get_sig[0][0][0] == 'string' and get_sig[0][1] is None:
# If the get method really returns a string
# wrap it as such.
t_def = 'traits.Trait(None, None, '\
'traits.String(enter_set=True, auto_set=False))'
self._write_trait(out, name, t_def, vtk_set_meth,
mapped=False)
else:
if (get_sig[0][1] is None) and (len(set_sig[0][1]) == 1):
# Get needs no args and Set needs one arg
self._write_property(out, name, vtk_get_meth,
vtk_set_meth)
else: # Get has args or Set needs many args.
self._write_tvtk_method(klass, out, vtk_get_meth, get_sig)
self._write_tvtk_method(klass, out, vtk_set_meth, set_sig)
# We cannot update the trait
del updateable_traits[name]
# ---------------------------------------------------------
# This is a color, we want RGBEditor for the trait
# ---------------------------------------------------------
elif (isinstance(default, tuple) and len(default) == 3 and
(name.find('color') > -1 or name.find('bond_color') > -1 or
name.find('background') > -1)):
# This is a color
force = 'False'
# 'vtkProperty' and 'vtkLight' are special because if you change
# one color the GetColor changes value so we must force an
# update.
if klass.__name__ in ['vtkProperty', 'vtkLight']:
force = 'True'
t_def = 'tvtk_base.vtk_color_trait({default})'.format(default=default)
self._write_trait(out, name, t_def, vtk_set_meth,
mapped=False, force_update=force)
# ------------------------------------------------------
# Try to get the trait type using the default
# ------------------------------------------------------
else:
try:
# That would give the trait definition as
# {trait_type}({default}, {kwargs})
trait_type, default, kwargs = get_trait_def(default,
enter_set=True,
auto_set=False)
except TypeError:
# ------------------------------------------
# Nothing works, print what we ignore
# ------------------------------------------
print("%s:"%klass.__name__, end=' ')
print("Ignoring method: Get/Set%s"%vtk_attr_name)
print("default: %s, range: None"%default)
del updateable_traits[name]
else:
if default:
t_def = '{0}({1}, {2})'.format(trait_type, default,
kwargs)
else:
t_def = '{0}({1})'.format(trait_type, kwargs)
self._write_trait(out, name, t_def, vtk_set_meth,
mapped=False)
return updateable_traits, allow_update_failure
def _gen_get_methods(self, klass, out):
parser = self.parser
meths = parser.get_get_methods()
for m in meths:
vtk_get_meth = getattr(klass, m)
if m == 'GetOutput': # GetOutput is special.
self._write_get_output_method(klass, out, set=False)
elif m == 'GetInput': # GetInput is special.
self._write_pure_get_input_method(klass, out)
elif m == 'GetOutputPort':
# This method sometimes prints warnings so we handle
# it specially.GetInput is special.
self._write_pure_get_output_port_method(klass, out)
else:
name = self._reform_name(m[3:])
sig = parser.get_method_signature(vtk_get_meth)
write_prop = False
write_getter = True
if len(sig) == 1 and sig[0][1] is None:
write_prop = True
# No need for a getter in this case.
write_getter = False
elif len(sig) > 1:
for i in sig:
if i[1] is None:
# There is a getter which takes no args too, so
# expose that as a property.
write_prop = True
break
if write_prop:
self._write_property(out, name, vtk_get_meth, None)
if write_getter:
self._write_tvtk_method(klass, out, vtk_get_meth, sig)
def _gen_other_methods(self, klass, out):
parser = self.parser
meths = parser.get_other_methods()
for m in meths:
vtk_meth = getattr(klass, m)
self._write_tvtk_method(klass, out, vtk_meth)
#################################################################
# Private utility methods.
#################################################################
def _reform_name(self, name, method=False):
"""Converts a VTK name to an Enthought style one. If `method`
is True it does not touch names that are all upper case."""
if name == 'TeX':
# Special case for some of the names. TeX occurs in the
# vtkGL2PSExporter class.
return 'tex'
if name.isupper() and method:
# All upper case names should remain the same since they
# are usually special methods.
return name
res = camel2enthought(name)
if keyword.iskeyword(res):
return res + '_'
else:
return res
def _get_class_name(self, klasses):
"""Returns renamed VTK classes as per TVTK naming style."""
ret = []
if type(klasses) in (list, tuple):
return [get_tvtk_name(x.__name__) \
for x in klasses]
else:
return get_tvtk_name(klasses.__name__)
def _find_type(self, val):
"""Given `val` which is extracted from the method call
signature, this returns the type of the value. Right now this
is in ['vtk', 'array', 'basic']. 'vtk' refers to a VTK type,
'array' to a vtkDataArray/vtkCellArray/vtkPoints/vtkIdList,
'basic' refers to a non-VTK, basic Python type.
"""
_arr_types = ['Array', 'vtkPoints', 'vtkIdList']
s = repr(val)
if s.find('vtk') > -1:
for i in _arr_types:
if s.find(i) > -1:
return 'array'
return 'vtk'
else:
return 'basic'
def _find_arg_type(self, sig):
"""Given a method signature `sig`, this finds the argument
types. It uses the `_find_type` method to obtain its result.
If no arguments are present in *all* of the signatures, then
it returns `None`.
"""
if len(sig) == 1:
if sig[0][1] is None:
return None
args = [s[1] for s in sig]
return self._find_type(args)
def _find_return_type(self, sig):
"""Given a method signature `sig`, this finds the return
types.
"""
rets = [s[0] for s in sig]
return self._find_type(rets)
def _find_sig_type(self, sig):