示例#1
0
class RC(traits.HasTraits):
   backend = traits.Trait(*backends)
   interactive  = flexible_false_trait
   toolbar      = traits.Trait('toolbar2', 'classic', None)
   timezone     = traits.Trait(*timezones)
   lines        = traits.Trait(LineRC())
   patch        = traits.Trait(PatchRC())
示例#2
0
 class font(TConfig):
     family = T.Trait('sans-serif', 'sans-serif', 'serif', 'cursive',
                      'fantasy', 'monospace')
     style = T.Trait('normal', 'normal', 'italic', 'oblique')
     variant = T.Trait('normal', 'normal', 'small-caps')
     weight = T.Trait('normal', 'normal', 'bold', 'bolder', 'lighter', 100,
                      200, 300, 400, 500, 600, 700, 800, 900)
     stretch = T.Trait('normal', 'ultra-condensed', 'extra-condensed',
                       'condensed', 'semi-condensed', 'normal',
                       'semi-expanded', 'expanded', 'extra-expanded',
                       'ultra-expanded', 'wider', 'narrower')
     size = T.Float(12.0)
     serif = T.ListStr([
         "Bitstream Vera Serif", "New Century Schoolbook",
         "Century Schoolbook L", "Utopia", "ITC Bookman", "Bookman",
         "Nimbus Roman No9 L", "Times New Roman", "Times", "Palatino",
         "Charter", "serif"
     ])
     sans_serif = T.ListStr([
         "Bitstream Vera Sans", "Lucida Grande", "Verdana", "Geneva",
         "Lucid", "Arial", "Helvetica", "Avant Garde", "sans-serif"
     ])
     cursive = T.ListStr(
         ["Apple Chancery", "Textile", "Zapf Chancery", "Sand", "cursive"])
     fantasy = T.ListStr([
         "Comic Sans MS", "Chicago", "Charcoal", "Impact", "Western",
         "fantasy"
     ])
     monospace = T.ListStr([
         "Bitstream Vera Sans Mono", "Andale Mono", "Nimbus Mono L",
         "Courier New", "Courier", "Fixed", "Terminal", "monospace"
     ])
示例#3
0
 class image(TConfig):
     aspect = T.Trait('equal', 'equal', 'auto', T.Float)
     interpolation = T.Trait('bilinear', 'bilinear', 'nearest', 'bicubic',
                             'spline16', 'spline36', 'hanning', 'hamming',
                             'hermite', 'kaiser', 'quadric', 'catrom',
                             'gaussian', 'bessel', 'mitchell', 'sinc',
                             'lanczos', 'blackman')
     cmap = T.Trait('jet', *mplT.colormaps)
     lut = T.Int(256)
     origin = T.Trait('upper', 'upper', 'lower')
示例#4
0
class LineRC(traits.HasTraits):
    linewidth = traits.Float(0.5)
    linestyle = traits.Trait(*linestyles)
    color = Color
    marker = traits.Trait(*linemarkers)
    markerfacecolor = Color
    markeredgecolor = Color
    markeredgewidth = traits.Float(0.5)
    markersize = traits.Float(6)
    antialiased = flexible_true_trait
    data_clipping = flexible_false_trait
示例#5
0
        class ps(TConfig):
            papersize = T.Trait('letter', 'auto', 'letter', 'legal', 'ledger',
                                'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7',
                                'A8', 'A9', 'A10', 'B0', 'B1', 'B2', 'B3',
                                'B4', 'B5', 'B6', 'B7', 'B8', 'B9', 'B10')
            useafm = T.false
            fonttype = T.Trait(3, 42)

            class distiller(TConfig):
                use = T.Trait(None, None, 'ghostscript', 'xpdf', False)
                resolution = T.Float(6000)
示例#6
0
    class yticks(TConfig):
        color = T.Trait('black', mplT.ColorHandler())
        labelsize = T.Trait('small', 'xx-small', 'x-small', 'small', 'medium',
                            'large', 'x-large', 'xx-large', T.Float)
        direction = T.Trait('in', 'out')

        class major(TConfig):
            size = T.Float(4)
            pad = T.Float(4)

        class minor(TConfig):
            size = T.Float(2)
            pad = T.Float(4)
示例#7
0
 class legend(TConfig):
     loc = T.Trait('upper right', 'best', 'upper right', 'upper left',
                   'lower left', 'lower right', 'right', 'center left',
                   'center right', 'lower center', 'upper center', 'center')
     isaxes = T.true
     numpoints = T.Int(3)
     fontsize = T.Trait('medium', 'xx-small', 'x-small', 'small', 'medium',
                        'large', 'x-large', 'xx-large', T.Float)
     pad = T.Float(0.2)
     markerscale = T.Float(1.0)
     labelsep = T.Float(0.01)
     handlelen = T.Float(0.05)
     handletextsep = T.Float(0.02)
     axespad = T.Float(0.02)
     shadow = T.false
示例#8
0
    class figure(TConfig):
        figsize = T.List(T.Float, [8, 6], maxlen=2, minlen=2)
        dpi = T.Float(80)
        facecolor = T.Trait('0.75', mplT.ColorHandler())
        edgecolor = T.Trait('white', mplT.ColorHandler())

        class subplot(TConfig):
            """The figure subplot parameters.  All dimensions are fraction
            of the figure width or height"""
            left = T.Float(0.125)
            right = T.Float(0.9)
            bottom = T.Float(0.1)
            top = T.Float(0.9)
            wspace = T.Float(0.2)
            hspace = T.Float(0.2)
示例#9
0
class Prop(tvtk_base.TVTKBase):
    def __init__(self, obj=None, update=1, **traits):
        tvtk_base.TVTKBase.__init__(self, vtk.vtkProperty, obj, update,
                                    **traits)

    edge_visibility = tvtk_base.false_bool_trait

    def _edge_visibility_changed(self, old_val, new_val):
        self._do_change(self._vtk_obj.SetEdgeVisibility, self.edge_visibility_)

    representation = traits.Trait(
        'surface',
        tvtk_base.TraitRevPrefixMap({
            'points': 0,
            'wireframe': 1,
            'surface': 2
        }))

    def _representation_changed(self, old_val, new_val):
        self._do_change(self._vtk_obj.SetRepresentation, self.representation_)

    opacity = traits.Trait(1.0, traits.Range(0.0, 1.0))

    def _opacity_changed(self, old_val, new_val):
        self._do_change(self._vtk_obj.SetOpacity, self.opacity)

    specular_color = tvtk_base.vtk_color_trait((1.0, 1.0, 1.0))

    def _specular_color_changed(self, old_val, new_val):
        self._do_change(self._vtk_obj.SetSpecularColor, self.specular_color, 1)

    diffuse_color = tvtk_base.vtk_color_trait((1.0, 1.0, 1.0))

    def _diffuse_color_changed(self, old_val, new_val):
        self._do_change(self._vtk_obj.SetDiffuseColor, self.diffuse_color, 1)

    color = tvtk_base.vtk_color_trait((1.0, 1.0, 1.0))

    def _color_changed(self, old_val, new_val):
        self._do_change(self._vtk_obj.SetColor, self.color)

    _updateable_traits_ = (('edge_visibility', 'GetEdgeVisibility'),
                           ('opacity', 'GetOpacity'), ('specular_color',
                                                       'GetSpecularColor'),
                           ('color', 'GetColor'), ('diffuse_color',
                                                   'GetDiffuseColor'),
                           ('representation', 'GetRepresentation'))
示例#10
0
    class text(TConfig):
        color = T.Trait('black', mplT.ColorHandler())
        usetex = T.false

        class latex(TConfig):
            unicode = T.false
            preamble = T.ListStr([])
            dvipnghack = T.false
示例#11
0
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)
示例#12
0
 class mathtext(TConfig):
     cal = T.Trait('cursive'       , mplT.FontconfigPatternHandler())
     rm  = T.Trait('serif'         , mplT.FontconfigPatternHandler())
     tt  = T.Trait('monospace'     , mplT.FontconfigPatternHandler())
     it  = T.Trait('serif:oblique' , mplT.FontconfigPatternHandler())
     bf  = T.Trait('serif:bold'    , mplT.FontconfigPatternHandler())
     sf  = T.Trait('sans'          , mplT.FontconfigPatternHandler())
     fontset = T.Trait('cm', 'cm', 'stix', 'stixsans', 'custom')
     default = T.Trait(*("rm cal it tt sf bf default bb frak circled scr regular".split()))
     fallback_to_cm = T.true
示例#13
0
 class mathtext(TConfig):
     cal = T.Trait('cursive', mplT.FontconfigPatternHandler())
     rm = T.Trait('serif', mplT.FontconfigPatternHandler())
     tt = T.Trait('monospace', mplT.FontconfigPatternHandler())
     it = T.Trait('serif:oblique', mplT.FontconfigPatternHandler())
     bf = T.Trait('serif:bold', mplT.FontconfigPatternHandler())
     sf = T.Trait('sans', mplT.FontconfigPatternHandler())
     fontset = T.Trait('cm', 'cm', 'stix', 'stixsans', 'custom')
     fallback_to_cm = T.true
示例#14
0
class SimpleConfig(TConfig):
    """Configuration for my application."""

    datafile = T.Str('data.txt')
    solver = T.Trait('Direct', 'Iterative')

    class Protocol(TConfig):
        """Specify the Protocol"""

        ptype = T.Trait('http', 'ftp', 'ssh')
        max_users = T.Int(1)
示例#15
0
 class legend(TConfig):
     isaxes = T.true
     numpoints = T.Int(3)
     fontsize = T.Trait('medium', 'xx-small', 'x-small', 'small', 'medium',
                        'large', 'x-large', 'xx-large', T.Float)
     pad = T.Float(0.2)
     markerscale = T.Float(1.0)
     labelsep = T.Float(0.01)
     handlelen = T.Float(0.05)
     handletextsep = T.Float(0.02)
     axespad = T.Float(0.02)
     shadow = T.false
示例#16
0
    class backend(TConfig):
        use = T.Trait('Agg', mplT.BackendHandler())
        fallback = T.Trait(True, mplT.BoolHandler())

        class cairo(TConfig):
            format = T.Trait('png', 'png', 'ps', 'pdf', 'svg')

        class tk(TConfig):
            """
            window_focus : Maintain shell focus for TkAgg
            pythoninspect: tk sets PYTHONINSPECT
            """

            window_focus = T.false
            pythoninspect = T.false

        class ps(TConfig):
            papersize = T.Trait('letter', 'auto', 'letter', 'legal', 'ledger',
                                'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7',
                                'A8', 'A9', 'A10',
                                'B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7',
                                'B8', 'B9', 'B10')
            useafm = T.false
            fonttype = T.Trait(3, 42)

            class distiller(TConfig):
                use = T.Trait(None, None, 'ghostscript', 'xpdf', False)
                resolution = T.Float(6000)

        class pdf(TConfig):
            compression = T.Range(0, 9, 6)
            fonttype = T.Trait(3, 42)
            inheritcolor = T.false
            use14corefonts = T.false

        class svg(TConfig):
            image_inline = T.true
            image_noscale = T.false
            embed_char_paths = T.true
示例#17
0
    class axes(TConfig):
        hold = T.Trait(True, mplT.BoolHandler())
        facecolor = T.Trait('white', mplT.ColorHandler())
        edgecolor = T.Trait('black', mplT.ColorHandler())
        linewidth = T.Float(1.0)
        grid = T.Trait(False, mplT.BoolHandler())
        polargrid = T.Trait(True, mplT.BoolHandler())
        titlesize = T.Trait('large', 'xx-small', 'x-small', 'small', 'medium',
                            'large', 'x-large', 'xx-large', T.Float)
        labelsize = T.Trait('medium', 'xx-small', 'x-small', 'small', 'medium',
                            'large', 'x-large', 'xx-large', T.Float)
        labelcolor = T.Trait('black', mplT.ColorHandler())
        axisbelow = T.false

        class formatter(TConfig):
            limits = T.List(T.Float, [-7, 7], minlen=2, maxlen=2)
示例#18
0
 class lines(TConfig):
     linewidth = T.Float(1.0)
     linestyle = T.Trait('-', '--', '-.', ':', 'steps', '', ' ', None)
     color = T.Trait('blue', mplT.ColorHandler())
     solid_joinstyle = T.Trait('round', 'miter', 'round', 'bevel')
     solid_capstyle = T.Trait('butt', 'butt', 'round', 'projecting')
     dash_joinstyle = T.Trait('round', 'miter', 'round', 'bevel')
     dash_capstyle = T.Trait('butt', 'butt', 'round', 'projecting')
     marker = T.Trait('None', 'None', 'o', '.', ',', '^', 'v', '<', '>',
                      's', '+', 'x', 'D', 'd', '1', '2', '3', '4', 'h', 'H',
                      'p', '|', '_')
     markeredgewidth = T.Float(0.5)
     markersize = T.Float(6)
     antialiased = T.true
示例#19
0
class DeviceTimer3State(traits.HasTraits):
    """encapsulate all (relevant) timer3 state on the device

    Making these variables a member of their own HasTraits class means
    that updates to the device can be treated in an atomic way.
    """
    # Timer/Counter3 state
    timer3_top = traits.Int(200)
    # The conversion from a clock select (CS) prescaler bit code.
    timer3_CS = traits.Trait(64, { 0.0:   0x00, # off
                                   1.0:   0x01,
                                   8.0:   0x02,
                                   64.0:  0x03,
                                   256.0: 0x04,
                                   1024.0:0x05})
    ocr3a = traits.Int
    ocr3b = traits.Int
    ocr3c = traits.Int
示例#20
0
class IPythonConfig(TConfig):
    """Class Docstring

    More

    And more...
    """

    m = T.Int(123)

    select = T.Trait('only', 'one', 'of', 'these')

    class InitOnly(TConfig):
        """
        The Read-only part of the configuration.

        More than one line of info...
        """
        n = T.Int
        x = T.Float

    class Protocol(TConfig):
        """Specify the Protocol

        More text...
        """
        include = T.Str
        ptype = T.Str

        class Handler(TConfig):
            """Specify the handler, a string.

            More..."""
            key = T.Str
            key2 = T.Str

    class Machine(TConfig):
        """Set the machine by ip address and port number."""
        ip = T.Str
        port = T.Int
示例#21
0
    class backend(TConfig):
        """Valid backends are: 'GTKAgg', 'GTKCairo', 'QtAgg', 'Qt4Agg',
        'TkAgg', 'Agg', 'Cairo', 'PS', 'PDF', 'SVG'"""
        use = T.Trait('TkAgg', BackendHandler())

        class cairo(TConfig):
            format = T.Trait('png', 'png', 'ps', 'pdf', 'svg')

        class tk(TConfig):
            """
            window_focus : Maintain shell focus for TkAgg
            pythoninspect: tk sets PYTHONINSPECT
            """

            window_focus = T.false
            pythoninspect = T.false

        class ps(TConfig):
            papersize = T.Trait('auto', 'letter', 'legal', 'ledger', 'A0',
                                'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8',
                                'A9', 'A10', 'B0', 'B1', 'B2', 'B3', 'B4',
                                'B5', 'B6', 'B7', 'B8', 'B9', 'B10')
            useafm = T.false
            fonttype = T.Trait(3, 42)

            class distiller(TConfig):
                use = T.Trait(None, 'ghostscript', 'xpdf')
                resolution = T.Float(6000)

        class pdf(TConfig):
            compression = T.Range(0, 9, 6)
            fonttype = T.Trait(3, 42)

        class svg(TConfig):
            image_inline = T.true
            image_noscale = T.false
            embed_chars = T.false
示例#22
0
    """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 GenerateProjectorCalibration(HasTraits):
    #width = traits.Int
    #height = traits.Int
    display_id = traits.String
    plot = Instance(Component)
    linedraw = Instance(LineSegmentTool)
    viewport_id = traits.String('viewport_0')
    display_mode = traits.Trait('white on black', 'black on white')
    client = traits.Any
    blit_compressed_image_proxy = traits.Any

    set_display_server_mode_proxy = traits.Any

    traits_view = View(
                    Group(
        Item('display_mode'),
        Item('viewport_id'),
                        Item('plot', editor=ComponentEditor(),
                             show_label=False),
                        orientation = "vertical"),
                    resizable=True,
                    )

    def __init__(self,*args,**kwargs):
        display_coords_filename = kwargs.pop('display_coords_filename')
        super( GenerateProjectorCalibration, self ).__init__(*args,**kwargs)

        fd = open(display_coords_filename,mode='r')
        data = pickle.load(fd)
        fd.close()

        self.param_name = 'virtual_display_config_json_string'
        self.fqdn = '/virtual_displays/'+self.display_id + '/' + self.viewport_id
        self.fqpn = self.fqdn + '/' + self.param_name
        self.client = dynamic_reconfigure.client.Client(self.fqdn)

        self._update_image()
        if 1:
            virtual_display_json_str = rospy.get_param(self.fqpn)
            this_virtual_display = json.loads( virtual_display_json_str )

        if 1:
            virtual_display_json_str = rospy.get_param(self.fqpn)
            this_virtual_display = json.loads( virtual_display_json_str )

            all_points_ok = True
            # error check
            for (x,y) in this_virtual_display['viewport']:
                if (x >= self.width) or (y >= self.height):
                    all_points_ok = False
                    break
            if all_points_ok:
                self.linedraw.points = this_virtual_display['viewport']
            # else:
            #     self.linedraw.points = []
            self._update_image()

    def _update_image(self):
        self._image = np.zeros( (self.height, self.width, 3), dtype=np.uint8)
        # draw polygon
        if len(self.linedraw.points)>=3:
            pts = [ (posint(y,self.height-1),posint(x,self.width-1)) for (x,y) in self.linedraw.points]
            mahotas.polygon.fill_polygon(pts, self._image[:,:,0])
            self._image[:,:,0] *= 255
            self._image[:,:,1] = self._image[:,:,0]
            self._image[:,:,2] = self._image[:,:,0]

        # draw red horizontal stripes
        for i in range(0,self.height,100):
            self._image[i:i+10,:,0] = 255

        # draw blue vertical stripes
        for i in range(0,self.width,100):
            self._image[:,i:i+10,2] = 255

        if hasattr(self,'_pd'):
            self._pd.set_data("imagedata", self._image)
        self.send_array()
        if len(self.linedraw.points) >= 3:
            self.update_ROS_params()

    def _plot_default(self):
        self._pd = ArrayPlotData()
        self._pd.set_data("imagedata", self._image)

        plot = Plot(self._pd, default_origin="top left")
        plot.x_axis.orientation = "top"
        img_plot = plot.img_plot("imagedata")[0]

        plot.bgcolor = "white"

        # Tweak some of the plot properties
        plot.title = "Click to add points, press Enter to clear selection"
        plot.padding = 50
        plot.line_width = 1

        # Attach some tools to the plot
        pan = PanTool(plot, drag_button="right", constrain_key="shift")
        plot.tools.append(pan)
        zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
        plot.overlays.append(zoom)

        return plot

    def _linedraw_default(self):
        linedraw = LineSegmentTool(self.plot,color=(0.5,0.5,0.9,1.0))
        self.plot.overlays.append(linedraw)
        linedraw.on_trait_change( self.points_changed, 'points[]')
        return linedraw

    def points_changed(self):
        self._update_image()

    @traits.on_trait_change('display_mode')
    def send_array(self):
        # create an array
        if self.display_mode.endswith(' on black'):
            bgcolor = (0,0,0,1)
        elif self.display_mode.endswith(' on white'):
            bgcolor = (1,1,1,1)

        if self.display_mode.startswith('black '):
            color = (0,0,0,1)
        elif self.display_mode.startswith('white '):
            color = (1,1,1,1)

        fname = tempfile.mktemp('.png')
        try:
            scipy.misc.imsave(fname, self._image )
            image = freemovr_engine.msg.FreemoVRCompressedImage()
            image.format = 'png'
            image.data = open(fname).read()
            self.blit_compressed_image_proxy(image)
        finally:
            os.unlink(fname)

    def get_viewport_verts(self):
        # convert to integers
        pts = [ (posint(x,self.width-1),posint(y,self.height-1)) for (x,y) in self.linedraw.points]
        # convert to list of lists for maximal json compatibility
        return [ list(x) for x in pts ]
示例#24
0
 class pdf(TConfig):
     compression = T.Range(0, 9, 6)
     fonttype = T.Trait(3, 42)
     inheritcolor = T.false
     use14corefonts = T.false
示例#25
0
 class distiller(TConfig):
     use = T.Trait(None, None, 'ghostscript', 'xpdf', False)
     resolution = T.Float(6000)
示例#26
0
 class cairo(TConfig):
     format = T.Trait('png', 'png', 'ps', 'pdf', 'svg')
示例#27
0
 class savefig(TConfig):
     dpi = T.Float(100)
     facecolor = T.Trait('white', mplT.ColorHandler())
     edgecolor = T.Trait('white', mplT.ColorHandler())
     orientation = T.Trait('portrait', 'portrait', 'landscape')
示例#28
0
 class contour(TConfig):
     negative_linestyle = T.Trait('dashed', 'dashed', 'solid')
示例#29
0
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
示例#30
0
 class verbose(TConfig):
     level = T.Trait('silent', 'silent', 'helpful', 'debug',
                     'debug-annoying')
     fileo = T.Trait('sys.stdout', 'sys.stdout', T.File)