def __init__(self, avl=None, **traits): """Initializes the object. """ super(AVLTreeBrowser, self).__init__(**traits) self.ui = None self.view = None if avl: self.avl = avl menu = Menu(Action(name='Refresh', action='editor.update_editor'), Action(name='Expand all', action='editor.expand_all')) self.menu = menu self._root_object_changed(self.root_object) nodes = self.tree_generator.get_nodes(menu) self.tree_editor = TreeEditor(nodes=nodes, orientation='vertical', hide_root=True, on_dclick=self._on_dclick, selected='selected') self.view = View(Group(Item(name='_root', editor=self.tree_editor, resizable=True), show_labels=False, show_border=False, orientation='vertical'), title='pyAVL', help=False, resizable=True, undo=False, revert=False, width=.3, height=.3, handler=self.avlhandler, toolbar=ToolBar(*self.avlhandler.toolbar_actions) )
def configure(self): """Pops up the GUI control widget.""" if self.ui is None: self._show_glyphs() view = View(Group(Item(name='light_mode'), Item(name='number_of_lights'), label='LightManager'), Group(Item(name='lights', style='custom'), label='Lights', selected=True, show_labels=False), resizable=True, buttons=['OK'], handler=CloseHandler()) self.ui = view.ui(self) else: try: self.ui.control.Raise() except AttributeError: pass
class ChannelNamesEditor(HasTraits): """ChannelNamesEditor Used to edit the channel-names of EEG files.""" # THE trait-attribute to change channel_names = List(Str) view = View( Item( 'channel_names@', #show_label = False, editor=ListEditor(style="text")), title='Editing channel-names', width=0.5, height=0.6, resizable=True, buttons=[OKButton, CancelButton, RevertButton, UndoButton])
class HTMLEditorDemo(HasTraits): """ Defines the main HTMLEditor demo class. """ # Define a HTML trait to view html_trait = HTML("""<html><body><p>A HTMLEditor displaying</p> <p>two paragraphs of text.</p></body></html>""") # Demo view view = View(Group(Item('html_trait', style='simple', label='Simple'), show_labels=False), title='HTMLEditor', buttons=['OK'], width=800, height=600, resizable=True)
class AVLTreeView(HasTraits): avl = Instance(AVL) traits_view = View( Item( name = 'avl', editor = AVL_tree_editor, show_label = False ), title = 'pyAVL', buttons = [ 'OK' ], resizable = True, style = 'custom', width = .3, height = .3 )
class Camera(HasTraits): start_stop_capture = Button() display = Instance(TextDisplay) capture_thread = Instance(CaptureThread) view = View(Item('start_stop_capture', show_label=False)) def _start_stop_capture_fired(self): if self.capture_thread and self.capture_thread.isAlive(): self.capture_thread.wants_abort = True else: self.capture_thread = CaptureThread() self.capture_thread.wants_abort = False self.capture_thread.display = self.display self.capture_thread.start()
class ListDemo2(HasTraits): filter_types = List(Str, value=["低通", "高通", "带通", "带阻"]) items = List(Str) view = View( HGroup( Item("filter_types", label="候选"), Item("items", style="custom", editor=CheckListEditor(name="filter_types")), show_labels=False ), resizable=True, width = 300, height = 180, title="动态修改候选值" )
class ListDemo(HasTraits): items = List(Str) view = View( HSplit( Item("items", style="custom", show_label=False), Item("items", style="custom", editor=CheckListEditor(values=filter_types, cols=4)), Item("items", editor=SetEditor(values=filter_types)), show_labels=False ), resizable=True, width = 600, title="简单列表编辑器演示" )
class ShowArray ( HasTraits ): data = Array view = View( Item( 'data', show_label = False, style = 'readonly', editor = TabularEditor( adapter = ArrayAdapter() ) ), title = 'Array Viewer', width = 0.3, height = 0.8, resizable = True )
class Test(HasTraits): figure = Instance(Figure, ()) view = View(Item('figure', editor=MPLFigureEditor(), show_label=False), width=600, height=450, resizable=True) def __init__(self): super(Test, self).__init__() axes = self.figure.add_subplot(111) t = linspace(0, 2*pi, 200) axes.plot(sin(t)*(1+0.5*cos(11*t)), cos(t)*(1+0.5*cos(11*t)))
class SampleClass(HasTraits): """ This Sample class is used to demonstrate the InstanceEditor demo. """ # The actual attributes don't matter here; we just need an assortment # to demonstrate the InstanceEditor's capabilities.: name = Str occupation = Str age = Range(21, 65) registered_voter = Bool # The InstanceEditor uses whatever view is defined for the class. The # default view lists the fields alphabetically, so it's best to define one # explicitly: view = View('name', 'occupation', 'age', 'registered_voter')
class Expression(HasTraits): _vars = Instance(Variables) _expr = ExpressionString('') _data_array_cache = None _data_array_cache_index = Int(0) view = View( Item('_expr', show_label=False, editor=TextEditor(enter_set=True, auto_set=False))) def __init__(self, variables, expr, **kwargs): HasTraits.__init__(self, **kwargs) self._vars = variables self.set_expr(expr) def set_expr(self, expr): if self._expr != expr: self._expr = expr def __expr_changed(self): self.clear_cache() def clear_cache(self): self._data_array_cache = numpy.array([]) self._data_array_cache_index = 0 def get_curr_value(self): return self._vars._eval_expr(self._expr) def get_array(self, first=0, last=None): first, last = self._vars.bound_array(first, last) if last > self._data_array_cache_index: #print "Cache miss of", (last - self._data_array_cache_index) new_data = self._vars._get_array(self._expr, self._data_array_cache_index, last) new_shape = list(new_data.shape) new_shape[ 0] = -1 # -1 lets the first index resize appropriately for the data length self._data_array_cache = numpy.append(self._data_array_cache, new_data) self._data_array_cache.shape = new_shape self._data_array_cache_index = last return self._data_array_cache[first:last]
class Plot_i(HasTraits): plot = Instance(Plot) color = ColorTrait('blue') marker = marker_trait marker_size = Int(4) line_width = Int(4) traits_view = View(Group(Tabbed(Group( \ Group(Item('color', label="Color"), \ Item('marker', label="Marker"), \ orientation = 'vertical'), \ Group( \ Item('marker_size', label= "Size"), \ Item('line_width', label = 'Linewidth'), \ orientation = 'vertical'), \ dock = 'tab', orientation = 'vertical')), \ Item('plot', editor=ComponentEditor(), show_label=False), orientation = 'horizontal'), \ width=800, height=600, resizable=True, title="Chaco Plot") def __init__(self,X,Y): super(Plot_i, self).__init__() self.load_data(X,Y) self.start() def load_data(self,X,Y) : self.X = X self.Y = Y plotdata = ArrayPlotData(x = X, y = Y) plot = Plot(plotdata) self.renderer_line = plot.plot(('x','y'),type = 'line', color = "blue")[0] self.renderer_scat = plot.plot(('x','y'),type = 'scatter', color = "blue")[0] self.plot = plot def start(self): self.configure_traits() def _color_changed(self): self.renderer_line.color = self.color self.renderer_scat.color = self.color def _marker_changed(self): self.renderer_scat.marker = self.marker def _marker_size_changed(self): self.renderer_scat.marker_size = self.marker_size def _line_width_changed(self): self.renderer_line.line_width = self.line_width
class LassoDemoPlot(HasTraits): plot = Instance(HPlotContainer) data = Instance(ArrayPlotData) traits_view = View(Item('plot', editor=ComponentEditor(), show_label=False), width=600, height=320, resizable=True, title="Lasso Tool Demo") def __init__(self, **traits): super(LassoDemoPlot, self).__init__(**traits) x = np.random.random(N) y = np.random.random(N) x2 = np.array([]) y2 = np.array([]) data = ArrayPlotData(x=x, y=y, x2=x2, y2=y2) plot1 = Plot(data, padding=10) scatter_plot1 = plot1.plot(("x", "y"), type="scatter", marker="circle", color="blue")[0] self.lasso = LassoSelection(scatter_plot1, incremental_select=True, selection_datasource=scatter_plot1.index) self.lasso.on_trait_change(self._selection_changed, 'selection_changed') scatter_plot1.tools.append(self.lasso) scatter_plot1.overlays.append( LassoOverlay(scatter_plot1, lasso_selection=self.lasso)) plot2 = Plot(data, padding=10) plot2.index_range = plot1.index_range plot2.value_range = plot1.value_range plot2.plot(("x2", "y2"), type="scatter", marker="circle", color="red") self.plot = HPlotContainer(plot1, plot2) self.plot2 = plot2 self.data = data def _selection_changed(self): index = np.array(self.lasso.selection_datasource.metadata["selection"], dtype=np.bool) self.data["x2"] = self.data["x"][index] self.data["y2"] = self.data["y"][index]
class CorrelationData(HasTraits): """Holds correlation data """ cr_plot = Instance(Plot, ()) corr_plot = Instance(Plot, ()) plotdata = Instance(ArrayPlotData) count_rate = Array correlation = Array correlation_avg = Array index = Int traits_view = View(Item('cr_plot', editor=ComponentEditor(), show_label=False), Item('corr_plot', editor=ComponentEditor(), show_label=False), width=400, height=800, resizable=True) def _plotdata_default(self): x = linspace(-14, 14, 100) y = x * 0 return ArrayPlotData(time=x, cr=y, lag=x, corr=y, avg=y) def __init__(self, **kw): super(CorrelationData, self).__init__(**kw) plot = Plot(self.plotdata) plot2 = Plot(self.plotdata) plot.plot(("time", "cr"), type="line", color="blue") plot2.plot(("lag", "corr"), type="line", color="green") plot2.plot(("lag", "avg"), type="line", color="red") plot2.index_scale = 'log' self.cr_plot = plot self.corr_plot = plot2 def _count_rate_changed(self, data): self.plotdata.set_data('time', data[:, 0]) self.plotdata.set_data('cr', data[:, 1]) def _correlation_changed(self, data): self.plotdata.set_data('lag', data[:, 0]) self.plotdata.set_data('corr', data[:, 1]) def _correlation_avg_changed(self, data): self.plotdata.set_data('lag', data[:, 0]) self.plotdata.set_data('avg', data[:, 1])
class CSVGrapher(HasTraits): """ 主界面包括绘图列表,数据源,文件选择器和添加绘图按钮 """ graph_list = List(Instance(Graph)) # 绘图列表 data_source = Instance(DataSource) # 数据源 csv_file_name = File(filter=[u"*.csv"]) # 文件选择 add_graph_button = Button(u"添加绘图") # 添加绘图按钮 view = View( # 整个窗口分为上下两个部分 VGroup( # 上部分横向放置控件,因此用HGroup HGroup( # 文件选择控件 Item("csv_file_name", label=u"选择CSV文件", width=400), # 添加绘图按钮 Item("add_graph_button", show_label=False) ), # 下部分是绘图列表,采用ListEditor编辑器显示 Item("graph_list", style="custom", show_label=False, editor=ListEditor( use_notebook=True, # 是用多标签页格式显示 deletable=True, # 可以删除标签页 dock_style="tab", # 标签dock样式 page_name=".name") # 标题页的文本使用Graph对象的name属性 ) ), resizable = True, height = 0.8, width = 0.8, title = u"CSV数据绘图器" ) def _csv_file_name_changed(self): """ 打开新文件时的处理,根据文件创建一个DataSource """ self.data_source = DataSource() self.data_source.load_csv(self.csv_file_name) del self.graph_list[:] def _add_graph_button_changed(self): """ 添加绘图按钮的事件处理 """ if self.data_source != None: self.graph_list.append( Graph(data_source = self.data_source) )
def default_traits_view(self): view = View(HGroup( VGroup('renormalized', Item('data_fig', style='custom', show_label=False), 'cr_fig', 'corr_fig'), Item('usable_data', style='custom', show_label=False, editor=CheckListEditor(values=list( map(str, self.possible_usable_data)), cols=1)), ), height=800, width=800, handler=DLS_DataHandler) return view
class WorldFrame(Frame): #Nothing to be seen here e = eye(4) variables = Instance(Variables) def evalT(self): return self.e def __init__(self, variables): self.variables = variables self.name = "WorldFrame" #self.parent=None #self.T=T traits_view = View(Item(label="The world is immutable"), title='WorldFrame')
class DataUnits(HasTraits): data_units = List(Instance(DataUnit)) def transfer_units(self,sif,xindex): for du in self.data_units: du.value = sif.__dict__[du.sname][xindex] view = View( Group( Item('data_units',editor = utable_editor), show_labels = False, ), resizable = True, width = 200, height = 400, )
class FileEditorDemo(HasTraits): """ Defines the main FileEditor demo class. """ # Define a File trait to view: file_name = File # Display specification (one Item per editor style): file_group = Group(Item('file_name', style='simple', label='Simple'), Item('_'), Item('file_name', style='custom', label='Custom'), Item('_'), Item('file_name', style='text', label='Text'), Item('_'), Item('file_name', style='readonly', label='ReadOnly')) # Demo view: view = View(file_group, title='FileEditor', buttons=['OK'], resizable=True)
class Text(Primitive): text = DelegatesTo('source') traits_view = View(Item(name='parent', label='Frame'), Item(name='T', label='Matrix4x4', style='custom'), Item(name='text'), Item(name='properties', editor=InstanceEditor(), label='Render properties'), title='Text properties') def __init__(self, *args, **kwargs): Primitive.__init__(self, **kwargs) self.source = tvtk.VectorText() self.mapper = tvtk.PolyDataMapper(input=self.source.get_output()) self.actor = tvtk.Actor(mapper=self.mapper) self.handle_arguments(*args, **kwargs)
class Employee(HasTraits): # Define the traits: name = Str dept = Str email = Str # Define the view: view = View( VGroup( VGroup( Item('name', show_label=False, editor=ImageEditor(image=ImageResource( 'info', search_path=search_path)))), VGroup(Item('name'), Item('dept'), Item('email'))))
def default_traits_view(self): view = View(VGroup( HGroup( Item("current_map", label="颜色映射", editor=EnumEditor(name="object.color_maps")), Item("reverse_map", label="反转颜色"), Item("position", label="位置", style="readonly"), ), Item("plot", show_label=False, editor=ComponentEditor()), ), resizable=True, width=550, height=300, title="Mandelbrot观察器") return view
class NullDecoder(DataDecoder): """ Doesn't do anything, just prints what it received to the console. """ name = Str('Null Decoder') view = View(Item( label= "The null decoder just prints the data \nit receives to the console for testing." ), title='Null decoder') def decode(self, data): print data return None
class ListEditorDemo(HasTraits): """ Defines the main ListEditor demo class. """ # Define a List trait to display: play_list = List(Str, ["The Merchant of Venice", "Hamlet", "MacBeth"]) # Items are used to define display, one per editor style: list_group = Group( Item('play_list', style='simple', label='Simple', height=75), Item('_'), Item('play_list', style='custom', label='Custom'), Item('_'), Item('play_list', style='text', label='Text'), Item('_'), Item('play_list', style='readonly', label='ReadOnly')) # Demo view: view = View(list_group, title='ListEditor', buttons=['OK'], resizable=True)
class StarDesign(HasTraits): box = Instance(StarComponent) view = View( HGroup(Item("object.box.edges", label=u"顶角数"), Item("object.box.star_color", label=u"颜色")), Item("box", editor=ComponentEditor(),show_label=False), resizable=True, width = 600, height = 400, title = u"星空设计" ) def __init__(self, **traits): super(StarDesign, self).__init__(**traits) self.box = StarComponent()
class CompoundEditorDemo(HasTraits): """ This class specifies the details of the CompoundEditor demo. """ # To demonstrate any given Trait editor, an appropriate Trait is required. compound_trait = Trait(1, Range(1, 6), 'a', 'b', 'c', 'd', 'e', 'f') # Display specification (one Item per editor style) comp_group = Group( Item('compound_trait', style='simple', label='Simple'), Item('_'), Item('compound_trait', style='custom', label='Custom'), Item('_'), Item('compound_trait', style='text', label='Text'), Item('_'), Item('compound_trait', style='readonly', label='ReadOnly')) # Demo view view1 = View(comp_group, title='CompoundEditor', buttons=['OK'])
class TimeEditorDemo(HasTraits): """ Demo class. """ time = Time(datetime.time(12, 0, 0)) view = View( Item('time', label='Simple Editor'), Item( 'time', label='Readonly Editor', style='readonly', # Show 24-hour mode instead of default 12 hour. editor=TimeEditor(strftime='%H:%M:%S')), resizable=True) def _time_changed(self): """ Print each time the time value is changed in the editor. """ print self.time
class PointsTask(BaseViewerTask): points = DelegatesTo('viewer') selected_point = Instance(Point) traits_view = View( #VGroup( Item('points', show_label=False, editor=table_editor), ) def startup(self): pass def _selected_point_changed(self): if self.selected_point is not None: slice_selector = self.viewer.slice_selector if slice_selector is not None: slice_selector.set_slices(*self.selected_point.coordinates)
class EnumEditorDemo(HasTraits): """ Defines the main EnumEditor demo class. """ # Define an Enum trait to view: name_list = Enum('A-495', 'A-498', 'R-1226', 'TS-17', 'TS-18') # Items are used to define the display, one Item per editor style: enum_group = Group(Item('name_list', style='simple', label='Simple'), Item('_'), Item('name_list', style='custom', label='Custom'), Item('_'), Item('name_list', style='text', label='Text'), Item('_'), Item('name_list', style='readonly', label='ReadOnly')) # Demo view: view = View(enum_group, title='EnumEditor', buttons=['OK'], resizable=True)
class FigureInspectorData(FigureInspector): """See :class:`Figure`. In adition.. defines a filename attribute.. ta load images from file """ filename = File() traits_view = View('filename', Group(Item('container', editor=ComponentEditor(size=size, bgcolor=bg_color), show_label=False), orientation="vertical"), resizable=True) def _filename_changed(self, new): image = ImageData.fromfile(new) self.plot_image(image._data)
class ListItem(HasTraits): """ Class used to represent an item in a list with traits UI. """ column_number = Int name = Str my_name = Str parent = Instance(HasTraits) view = View( HGroup( Item('name', style='readonly', show_label=False, resizable=False), Item('my_name', style='simple', show_label=False, editor=TextEditor(auto_set=False, enter_set=True), springy=True), ))
def __init__(self, renwin=None, **traits): """Initializes the object. Parameters ---------- - renwin: `Scene` instance. Defaults to None. This may be passed in addition to the renwins attribute which can be a list of scenes. """ super(PipelineBrowser, self).__init__(**traits) self.ui = None self.view = None if renwin: self.renwins.append(renwin) self._root_object_changed(self.root_object) menu = Menu( Action(name="Refresh", action="editor.update_editor"), Action(name="Expand all", action="editor.expand_all") ) self.menu = menu nodes = self.tree_generator.get_nodes(menu) self.tree_editor = TreeEditor( nodes=nodes, editable=False, orientation="vertical", hide_root=True, on_dclick=self._on_dclick ) self.view = View( Group( Item(name="_root", editor=self.tree_editor, resizable=True), show_labels=False, show_border=False, orientation="vertical", ), title="Pipeline browser", help=False, resizable=True, undo=False, revert=False, width=0.3, height=0.3, )
html_editor = HTMLEditor() else: from enthought.traits.ui.api import HTMLEditor html_editor = HTMLEditor(format_text=False) # Local imports import rest_html from python_function_info import PythonFunctionInfo html_view = View( Item('_html', show_label=False, editor=html_editor, springy= True, resizable=True, ), id='help_view', resizable=True, buttons=NoButtons, ) class HtmlInfoUI(HasTraits): """ Model for the a window to display Html in an application. This widget has the following APIs: set_text(text): display raw text. set_html(text): display html formatted text. set_function_help(function_name, module_name):
class AVLTreeBrowser(HasTraits): # The tree generator to use. tree_generator = Trait(SimpleTreeGenerator(), Instance(TreeGenerator)) # The TVTK render window(s) associated with this browser. avl = Instance(AVL) avlhandler = Instance(AVLHandler, AVLHandler()) # The root object to view in the pipeline. If None (default), the # root object is the render_window of the Scene instance passed at # object instantiation time. root_object = List() selected = Any # Private traits. # The root of the tree to display. _root = Any ########################################################################### # `object` interface. ########################################################################### def __init__(self, avl=None, **traits): """Initializes the object. """ super(AVLTreeBrowser, self).__init__(**traits) self.ui = None self.view = None if avl: self.avl = avl menu = Menu(Action(name='Refresh', action='editor.update_editor'), Action(name='Expand all', action='editor.expand_all')) self.menu = menu self._root_object_changed(self.root_object) nodes = self.tree_generator.get_nodes(menu) self.tree_editor = TreeEditor(nodes=nodes, orientation='vertical', hide_root=True, on_dclick=self._on_dclick, selected='selected') self.view = View(Group(Item(name='_root', editor=self.tree_editor, resizable=True), show_labels=False, show_border=False, orientation='vertical'), title='pyAVL', help=False, resizable=True, undo=False, revert=False, width=.3, height=.3, handler=self.avlhandler, toolbar=ToolBar(*self.avlhandler.toolbar_actions) ) ########################################################################### # `PipelineBrowser` interface. ########################################################################### def show(self, parent=None): """Show the tree view if not already show. If optional `parent` widget is passed, the tree is displayed inside the passed parent widget.""" # If UI already exists, raise it and return. if self.ui and self.ui.control: try: self.ui.control.Raise() except AttributeError: pass else: return else: # No active ui, create one. if parent: self.ui = self.view.ui(self, parent=parent, kind='subpanel') else: self.ui = self.view.ui(self, parent=parent) #@on_trait_change('avl?.[(case?.geometry?.[bodies?,surfaces?.sections?])?,run_cases?]') #@on_trait_change('avl.case.geometry.refresh_geometry_view') # this doesn't work, self.ui is None def update(self): """Update the tree view.""" # This is a hack. logger.info('updating tree view') if self.ui and self.ui.control: try: ed = self.ui._editors[0] ed.update_editor() self.ui.control.Refresh() except (AttributeError, IndexError): pass # Another name for update. refresh = update ########################################################################### # Non-public interface. ########################################################################### def _make_default_root(self): tree_gen = self.tree_generator objs = [self.avl] node = TreeCollectionNode(object=objs, name="Root", tree_generator=tree_gen) return node #@on_trait_change('avl?,avl?.case?,avl?.case?.geometry?,avl?.run_cases?[],avl?.case?.geometry?.surfaces?[],avl?.case?.geometry?.surfaces?.sections?[],avl?.case?.geometry?.bodies?[]') @on_trait_change('avl?,avl.case?,avl.case.geometry.refresh_geometry_view') def recreate_tree(self): self._tree_generator_changed(self.tree_generator) def _tree_generator_changed(self, tree_gen): """Traits event handler.""" if self._root: root_obj = self._root.object else: root_obj = self.root_object if root_obj: ro = root_obj if not hasattr(root_obj, '__len__'): ro = [root_obj] self._root = TreeCollectionNode(object=ro, name="Root", tree_generator=tree_gen) else: self._root = self._make_default_root() if hasattr(self, 'tree_editor'): self.tree_editor.nodes = tree_gen.get_nodes(self.menu) self.update() #@on_trait_change('avl.[(case.geometry.[bodies,surfaces.sections]),run_cases]') @on_trait_change('avl.case.geometry.bodies_items,avl.case.geometry.surfaces.sections_items') def refresh(self): self.update() def _root_object_changed(self, root_obj): """Trait handler called when the root object is assigned to.""" logger.info('in _root_object_changed') tg = self.tree_generator if root_obj: self._root = TreeCollectionNode(object=root_obj, name="Root", tree_generator=tg) else: self._root = self._make_default_root() self.root_object = self._root.object self.update() def _root_object_items_changed(self, list_event): """Trait handler called when the items of the list change.""" self._root_object_changed(self.root_object) def _on_dclick(self, obj): """Callback that is called when nodes are double-clicked.""" if hasattr(obj, 'object') and hasattr(obj.object, 'edit_traits'): object = obj.object view = object.trait_view() view.handler = UICloseHandler(browser=self) #object.on_trait_change(self.render) ui = object.edit_traits(view=view)
class PipelineBrowser(HasTraits): # The tree generator to use. tree_generator = Trait(FullTreeGenerator(), Instance(TreeGenerator)) # The TVTK render window(s) associated with this browser. renwins = List # The root object to view in the pipeline. If None (default), the # root object is the render_window of the Scene instance passed at # object instantiation time. root_object = List(TVTKBase) # Private traits. # The root of the tree to display. _root = Any ########################################################################### # `object` interface. ########################################################################### def __init__(self, renwin=None, **traits): """Initializes the object. Parameters ---------- - renwin: `Scene` instance. Defaults to None. This may be passed in addition to the renwins attribute which can be a list of scenes. """ super(PipelineBrowser, self).__init__(**traits) self.ui = None self.view = None if renwin: self.renwins.append(renwin) self._root_object_changed(self.root_object) menu = Menu(Action(name='Refresh', action='editor.update_editor'), Action(name='Expand all', action='editor.expand_all')) self.menu = menu nodes = self.tree_generator.get_nodes(menu) self.tree_editor = TreeEditor(nodes=nodes, editable=False, orientation='vertical', hide_root=True, on_dclick=self._on_dclick) self.view = View(Group(Item(name='_root', editor=self.tree_editor, resizable=True), show_labels=False, show_border=False, orientation='vertical'), title='Pipeline browser', help=False, resizable=True, undo=False, revert=False, width=.3, height=.3) ########################################################################### # `PipelineBrowser` interface. ########################################################################### def show(self, parent=None): """Show the tree view if not already show. If optional `parent` widget is passed, the tree is displayed inside the passed parent widget.""" # If UI already exists, raise it and return. if self.ui and self.ui.control: try: self.ui.control.Raise() except AttributeError: pass else: return else: # No active ui, create one. if parent: self.ui = self.view.ui(self, parent=parent, kind='subpanel') else: self.ui = self.view.ui(self, parent=parent) def update(self): """Update the tree view.""" # This is a hack. if self.ui and self.ui.control: try: ed = self.ui._editors[0] ed.update_editor() self.ui.control.Refresh() except (AttributeError, IndexError): pass # Another name for update. refresh = update def render(self): """Calls render on all render windows associated with this browser.""" for rw in self.renwins: rw.render() ########################################################################### # Non-public interface. ########################################################################### def _make_default_root(self): tree_gen = self.tree_generator objs = [x.render_window for x in self.renwins] node = TVTKCollectionNode(object=objs, name="Root", tree_generator=tree_gen) return node def _tree_generator_changed(self, tree_gen): """Traits event handler.""" if self._root: root_obj = self._root.object else: root_obj = self.root_object if root_obj: ro = root_obj if not hasattr(root_obj, '__len__'): ro = [root_obj] self._root = TVTKCollectionNode(object=ro, name="Root", tree_generator=tree_gen) else: self._root = self._make_default_root() self.tree_editor.nodes = tree_gen.get_nodes(self.menu) self.update() def _root_object_changed(self, root_obj): """Trait handler called when the root object is assigned to.""" tg = self.tree_generator if root_obj: self._root = TVTKCollectionNode(object=root_obj, name="Root", tree_generator=tg) else: self._root = self._make_default_root() self.root_object = self._root.object self.update() def _root_object_items_changed(self, list_event): """Trait handler called when the items of the list change.""" self._root_object_changed(self.root_object) def _on_dclick(self, obj): """Callback that is called when nodes are double-clicked.""" if hasattr(obj, 'object') and hasattr(obj.object, 'edit_traits'): object = obj.object view = object.trait_view() view.handler = UICloseHandler(browser=self) object.on_trait_change(self.render) ui = object.edit_traits(view=view)