This file is indexed.

/usr/share/pyshared/tvtk/tvtk_base.py is in mayavi2 4.1.0-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
"""Commonly used code by tvtk objects.

"""
# Author: Prabhu Ramachandran <prabhu_r@users.sf.net>
# Copyright (c) 2004-2008,  Enthought, Inc.
# License: BSD Style.

import types
import sys
import weakref
import os
import logging

import vtk

from traits import api as traits
from traitsui.api import BooleanEditor, RGBColorEditor, FileEditor
import messenger

# Setup a logger for this module.
logger = logging.getLogger(__name__)

######################################################################
# The TVTK object cache.
######################################################################

class TVTKObjectCache(weakref.WeakValueDictionary):
    def __init__(self, *args, **kw):
        self._observer_data = {}
        weakref.WeakValueDictionary.__init__(self, *args, **kw)
        def remove(wr, selfref=weakref.ref(self)):
            self = selfref()
            if self is not None:
                self.teardown_observers(wr.key)
                del self.data[wr.key]
        self._remove = remove

    def setup_observers(self, vtk_obj, event, method):
        """Setup the observer for the VTK object's event.

        Parameters
        ----------

        vtk_obj -- The VTK object for which the `event` is
        observed.

        event -- The VTK event to watch.

        method -- The method to be called back when `event` is
        fired on the VTK object.

        """

        # Setup the observer so the traits are updated even if the
        # wrapped VTK object changes.
        if hasattr(vtk_obj, 'AddObserver'):
            # Some classes like vtkInformation* derive from
            # tvtk.ObjectBase which don't support Add/RemoveObserver.
            messenger.connect(vtk_obj, event, method)
            ob_id = vtk_obj.AddObserver(event, messenger.send)
            key = vtk_obj.__this__
            od = self._observer_data
            if key in od:
                od[key].append((vtk_obj, ob_id))
            else:
                od[key] = [(vtk_obj, ob_id)]

    def teardown_observers(self, key):
        """Given the key of the VTK object (vtk_obj.__this__), this
        removes the observer for the ModifiedEvent and also disconnects
        the messenger.
        """
        od = self._observer_data
        if key not in od:
            return

        for vtk_obj, ob_id in od[key]:
            try:
                # The disconnection sometimes fails at exit.
                vtk_obj.RemoveObserver(ob_id)
            except AttributeError:
                pass
        try:
            messenger.disconnect(vtk_obj)
        except AttributeError:
            pass
        del od[key]


# The TVTK object cache (`_object_cache`).  This caches all the TVTK
# instances using weakrefs.  When a VTK object is wrapped via the
# `wrap_vtk` function this cache is checked.  The key is the VTK
# object's address.  The value of the dict is the TVTK wrapper object.
# If the VTK object address exists in the cache, it is returned by
# `wrap_vtk`.  `wrap_vtk` is defined in `tvtk_helper.py` which is
# stored in the ZIP file.

_dummy = None
# This makes the cache work even when the module is reloaded.
for name in ['tvtk_base', 'tvtk.tvtk_base']:
    if sys.modules.has_key(name):
        mod = sys.modules[name]
        if hasattr(mod, '_object_cache'):
            _dummy = mod._object_cache
        del mod
        break

if _dummy is not None:
    _object_cache = _dummy
else:
    _object_cache = TVTKObjectCache()
del _dummy


def get_tvtk_object_from_cache(vtk_obj):
    """Returns the cached TVTK object given a VTK object."""
    return _object_cache.get(vtk_obj.__this__)


######################################################################
# Special traits used by the tvtk objects.
######################################################################

true_bool_trait = traits.Trait('true',
                               {'true':  1, 't': 1, 'yes': 1,
                                'y': 1, 'on': 1, 1: 1, 'false': 0,
                                'f': 0, 'no':  0, 'n': 0,
                                'off': 0, 0: 0},
                               editor=BooleanEditor)

false_bool_trait = traits.Trait('false', true_bool_trait)


class TraitRevPrefixMap(traits.TraitPrefixMap):
    """A reverse mapped TraitPrefixMap.  This handler allows for
    something like the following::

      >>> class A(HasTraits):
      ...     a = Trait('ab', TraitRevPrefixMap({'ab':1, 'cd':2}))
      ...
      >>> a = A()
      >>> a.a = 'c'
      >>> print a.a
      'cd'
      >>> a.a = 1
      >>> print a.a
      'ab'

    That is, you can set the trait to the value itself.  If multiple
    keys map to the same value, one of the valid keys will be used.

    """
    def __init__(self, map):
        traits.TraitPrefixMap.__init__(self, map)
        self._rmap = {}
        for key, value in map.items():
            self._rmap[value] = key

    def validate(self, object, name, value):
        try:
            if self._rmap.has_key(value):
                value = self._rmap[value]
            if not self._map.has_key( value ):
                match = None
                n     = len( value )
                for key in self.map.keys():
                    if value == key[:n]:
                        if match is not None:
                           match = None
                           break
                        match = key
                if match is None:
                    self.error( object, name, value )
                self._map[ value ] = match
            return self._map[ value ]
        except:
            self.error( object, name, value )

    def info(self):
        keys = [repr(x) for x in self._rmap.keys()]
        keys.sort()
        msg = ' or '.join(keys)
        return traits.TraitPrefixMap.info(self) + ' or ' + msg


def vtk_color_trait(default, **metadata):
    Range = traits.Range
    if default[0] == -1.0:
        # Occurs for the vtkTextProperty's color trait.  Need to work
        # around.
        return traits.Trait(default, traits.Tuple(*default),
                            traits.Tuple(Range(0.0, 1.0),
                                         Range(0.0, 1.0),
                                         Range(0.0, 1.0),
                                         editor=RGBColorEditor),
                            **metadata)
    else:
        return traits.Trait(traits.Tuple(Range(0.0, 1.0, default[0]),
                                         Range(0.0, 1.0, default[1]),
                                         Range(0.0, 1.0, default[2])),
                            editor=RGBColorEditor, **metadata)


# Special cases for the FileName and FilePrefix
vtk_file_name = traits.Trait(None, None, traits.Str, types.UnicodeType,
                             editor=FileEditor)
vtk_file_prefix = traits.Trait(None, None, traits.Str, types.UnicodeType,
                               editor=(FileEditor, {'truncate_ext': True}))

# The Property class traits are delegated in the Actors.
vtk_property_delegate = traits.Delegate('property', modify=True)


######################################################################
# Utility functions.
######################################################################
def deref_vtk(obj):
    """Dereferences the VTK object from the object if possible."""
    if isinstance(obj, TVTKBase):
        return obj._vtk_obj
    else:
        return obj


######################################################################
# 'TVTKBase' class (base class for all tvtk classes):
######################################################################
class TVTKBase(traits.HasStrictTraits):
    """The base class for all TVTK objects.  This class encapsulates
    key functionality common to all the TVTK classes.

    TVTK classes provide a trait wrapped VTK object.  They also
    primitively picklable.  Only the basic state of the object itself
    is pickled.  References to other VTK objects are NOT pickled.

    """

    # This is just a dummy integer (MUST be > 1) that indicates that
    # we are updating the traits and there is no need to change the
    # underlying VTK object.
    DOING_UPDATE = 10

    ########################################
    # Private traits.

    # This trait is only used internally and should not activate any
    # notifications when set which is why we use `Python`.
    _in_set = traits.Python

    # The wrapped VTK object.
    _vtk_obj = traits.Trait(None, None, vtk.vtkObjectBase())

    # Stores the names of the traits that need to be updated.
    _updateable_traits_ = traits.Tuple

    # List of trait names that are to be included in the full traits view of this object.
    _full_traitnames_list_ = traits.List

    #################################################################
    # `object` interface.
    #################################################################
    def __init__(self, klass, obj=None, update=True, **traits):
        """Object initialization.

        Parameters
        ----------

        - klass: `vtkObjectBase`

          A VTK class to wrap.  If `obj` is passed, its class must be
          the same as `klass` or a subclass of it.

        - obj: `vtkObjectBase` (default: None)

          An optional VTK object.  If passed the passed object is
          wrapped.  This defaults to `None` where a new VTK instance
          of class, `klass` is created.

        - update: `bool` (default: True)

          If True (default), the traits of the class are automatically
          updated based on the state of the wrapped VTK object.  If
          False, no updation is performed.  This is particularly
          useful when the object is being unpickled.

        - traits: `dict`

          A dictionary having the names of the traits as its keys.
          This allows a user to set the traits of the object while
          creating the object.

        """
        # Initialize the Python attribute.
        self._in_set = 0
        if obj:
            assert obj.IsA(klass.__name__)
            self._vtk_obj = obj
        else:
            self._vtk_obj = klass()

        # print "INIT", self.__class__.__name__, repr(self._vtk_obj)

        # Call the Super class to update the traits.
        # Inhibit any updates at this point since we update in the end
        # anyway.
        self._in_set = 1
        super(TVTKBase, self).__init__(**traits)
        self._in_set = 0

        # Update the traits based on the values of the VTK object.
        if update:
            self.update_traits()

        # Setup observers for the modified event.
        self.setup_observers()

        _object_cache[self._vtk_obj.__this__] = self

    def __getinitargs__(self):
        """This is merely a placeholder so that subclasses can
        override this if needed.  This is called by `__setstate__`
        because `traits.HasTrait` is a newstyle class.

        """
        # You usually don't want to call update when calling __init__
        # from __setstate__
        return (None, 0)

    def __getstate__(self):
        """Support for primitive pickling.  Only the basic state is
        pickled.
        """
        self.update_traits()
        d = self.__dict__.copy()
        for i in ['_vtk_obj', '_in_set', 'reference_count',
                  'global_warning_display', '__sync_trait__']:
            d.pop(i, None)
        return d

    def __setstate__(self, dict):
        """Support for primitive pickling.  Only the basic state is
        pickled.
        """
        # This is a newstyle class so we need to call init here.
        if self._vtk_obj is None:
            self.__init__(*self.__getinitargs__())
        self._in_set = 1
        for i in dict:
            # Not enough to update the dict because the vtk object
            # needs to be updated.
            try:
                setattr(self, i, dict[i])
            except traits.TraitError, msg:
                print "WARNING:",
                print msg
        self._in_set = 0

    def __str__(self):
        """Return a nice string representation of the object.

        This merely returns the result of str on the underlying VTK
        object.
        """
        return str(self._vtk_obj)

    #################################################################
    # `HasTraits` interface.
    #################################################################

    def class_trait_view_elements ( cls ):
        """ Returns the ViewElements object associated with the class.

        The returned object can be used to access all the view elements
        associated with the class.

        Overridden here to search through a particular directory for substitute
        views to use for this tvtk object. The view should be declared in a
        file named <class name>_view. We execute this file and replace any
        currently defined view elements with view elements declared in this
        file (that have the same name).

        """

        # FIXME: This can be enhanced to search for new views also (in addition
        # to replacing current views).

        view_elements = super(TVTKBase, cls).class_trait_view_elements()
        # Get the names of all the currently defined view elements.
        names = view_elements.filter_by()
        baseDir = os.path.dirname(os.path.abspath(__file__))
        viewDir = os.path.join(baseDir, 'view')
        try:
            module_name = cls.__module__.split('.')[-1]
            view_filename = os.path.join(viewDir,
                                         module_name + '_view.py')
            result = {}
            execfile(view_filename, {}, result)
            for name in names:
                if name in result:
                    view_elements.content[ name ] = result[name]
        except Exception, e:
            pass
        return view_elements

    class_trait_view_elements = classmethod( class_trait_view_elements )

    #################################################################
    # `TVTKBase` interface.
    #################################################################
    def setup_observers(self):
        """Add an observer for the ModifiedEvent so the traits are kept
        up-to-date with the wrapped VTK object and do it in a way that
        avoids reference cycles."""
        _object_cache.setup_observers(self._vtk_obj,
                                      'ModifiedEvent',
                                      self.update_traits)

    def teardown_observers(self):
        """Remove the observer for the Modified event."""
        _object_cache.teardown_observers(self._vtk_obj.__this__)

    def update_traits(self, obj=None, event=None):
        """Updates all the 'updateable' traits of the object.

        The method works by getting the current value from the wrapped
        VTK object.  `self._updateable_traits_` stores a tuple of
        tuples containing the trait name followed by the name of the
        get method to use on the wrapped VTK object.

        The `obj` and `event` parameters may be ignored and are not
        used in the function.  They exist only for compatibility with
        the VTK observer callback functions.

        """
        if self._in_set:
            return
        if not hasattr(self, '_updateable_traits_'):
            return

        self._in_set = self.DOING_UPDATE
        vtk_obj = self._vtk_obj

        # Save the warning state and turn it off!
        warn = vtk.vtkObject.GetGlobalWarningDisplay()
        vtk.vtkObject.GlobalWarningDisplayOff()

        for name, getter in self._updateable_traits_:
            try:
                val = getattr(vtk_obj, getter)()
            except (AttributeError, TypeError):
                pass
            else:
                if name == 'global_warning_display':
                    setattr(self, name, warn)
                else:
                    setattr(self, name, val)
        # Reset the warning state.
        vtk.vtkObject.SetGlobalWarningDisplay(warn)
        self._in_set = 0

    #################################################################
    # Non-public interface.
    #################################################################
    def _do_change(self, method, val, force_update=False):
        """This is called by the various traits when they change in
        order to update the underlying VTK object.

        Parameters
        ----------

        - method: `method`

          The method to invoke on the VTK object when called.

        - val: `Any`

          Argument to the method.

        - force_update: `bool` (default: False)

          If True, `update_traits` is always called at the end.

        """
        if self._in_set == self.DOING_UPDATE:
            return
        vtk_obj = self._vtk_obj
        self._in_set += 1
        mtime = self._wrapped_mtime(vtk_obj) + 1
        try:
            method(val)
        except TypeError:
            if hasattr(val, '__len__'):
                method(*val)
            else:
                raise
        self._in_set -= 1
        if force_update or self._wrapped_mtime(vtk_obj) > mtime:
            self.update_traits()


    def _wrap_call(self, vtk_method, *args):
        """This method allows us to safely call a VTK method without
        calling `update_traits` during the call.  This method is
        therefore used to wrap any 'Set' call on a VTK object.

        The method returns the output of the vtk_method call.

        Parameters
        ----------

        - vtk_method: `method`

          The method to invoke safely.

        - args: `Any`

          Argument to be passed to the method.

        """
        vtk_obj = self._vtk_obj
        self._in_set += 1
        mtime = self._wrapped_mtime(vtk_obj) + 1
        ret = vtk_method(*args)
        self._in_set -= 1
        if self._wrapped_mtime(vtk_obj) > mtime:
            self.update_traits()
        return ret

    def _wrapped_mtime(self, vtk_obj):
        """A simple wrapper for the mtime so tvtk can be used for
        `vtk.vtkObjectBase` subclasses that neither have an
        `AddObserver` or a `GetMTime` method.
        """
        try:
            return vtk_obj.GetMTime()
        except AttributeError:
            return 0