def init_gui_menu(): odmenu = Menu(name='Odors') for odname in bv.odors.odors.keys(): odmenu.append(Action(name=odname, action='_show_%s' % odname)) viewmenu = Menu(name='View') viewmenu.append(Action(name='Set as Vincis view', action='_setview')) return MenuBar(odmenu, viewmenu), MenuHandler()
def _quick_drag_menu ( self, object ): """ Displays the quick drag menu for a specified drag object. """ # Get all the features it could be dropped on: feature_lists = [] if isinstance( object, IFeatureTool ): msg = 'Apply to' for dc in self.dock_control.dock_controls: if (dc.visible and (object.feature_can_drop_on( dc.object ) or object.feature_can_drop_on_dock_control( dc ))): from feature_tool import FeatureTool feature_lists.append( [ FeatureTool( dock_control = dc ) ] ) else: msg = 'Send to' for dc in self.dock_control.dock_controls: if dc.visible: allowed = [ f for f in dc.features if (f.feature_name != '') and f.can_drop( object ) ] if len( allowed ) > 0: feature_lists.append( allowed ) # If there are any compatible features: if len( feature_lists ) > 0: # Create the pop-up menu: features = [] actions = [] for list in feature_lists: if len( list ) > 1: sub_actions = [] for feature in list: sub_actions.append( Action( name = '%s Feature' % feature.feature_name, action = "self._drop_on(%d)" % len( features ) ) ) features.append( feature ) actions.append( Menu( name = '%s the %s' % ( msg, feature.dock_control.name ), *sub_actions ) ) else: actions.append( Action( name = '%s %s' % ( msg, list[0].dock_control.name ), action = "self._drop_on(%d)" % len( features ) ) ) features.append( list[0] ) # Display the pop-up menu: self._object = object self._features = features self.popup_menu( Menu( name = 'popup', *actions ) ) self._object = self._features = None
class AVLHandler(Handler): ''' Handler for all gui events ''' toolbar_actions = List(Action, [ Action(name="Load Case", action="load_case", toolip="Load an AVL case from file"), Action(name="Save Case", action="save_case", toolip="Save AVL case to file"), Action(name="Run...", action="run_config", toolip="Recalculate the results"), ]) #def object_runcases_changed(self, uiinfo): # print uiinfo.object, 'runcase name changed' def run_config(self, info): print 'running...' runcase = info.object.avl.run_cases[0] runcaseconfig = RunConfig(runcase=runcase) out = runcaseconfig.configure_traits(kind='livemodal') if not out: return output = runcaseconfig.run() runcase.runoutput.variable_names = output.variable_names runcase.runoutput.variable_values = output.variable_values runcase.runoutput.eigenmodes = output.eigenmodes runcase.runoutput.eigenmatrix = output.eigenmatrix def load_case(self, info): avl = info.object.avl filename = get_file_from_user(cwd=avl.case_filename, filter=['AVL case files (*.avl)|*.avl']) if filename: avl.load_case_from_file(filename) logger.info('loading case from file : %s' % str(filename)) avl.reload_case = True # NOTE: it also reloads the case into avl def save_case(self, info): case = info.object.avl.case filename = get_file_from_user(cwd=case.case_filename, filter=['AVL case files (*.avl)|*.avl']) if filename: f = open(filename, 'w') case.write_input_file(f) f.flush() f.close() logger.info('saving case to file : %s' % str(filename)) info.object.avl.load_case_from_file(filename) logger.info('reloading case into avl : %s' % str(filename))
def __init__(self, all_roles, **traits): """Initialise the object.""" buttons = [Action(name="Search"), Action(name="Save"), CancelButton] roles_editor = SetEditor(values=all_roles.values(), left_column_title="Available Roles", right_column_title="Assigned Roles") roles_group = Group(Item(name='roles', editor=roles_editor), label='Roles', show_border=True, show_labels=False) super(_AssignmentView, self).__init__(Item(name='user_name'), Item(name='description', style='readonly'), roles_group, buttons=buttons, **traits)
def initOdorsDisp(fname, fig, bulb): odorlbl, glomval = OdorsInput(fname) try: from enthought.traits.ui.menu import Action, MenuBar, Menu, Separator # create odor list except: from traitsui.menu import Action, MenuBar, Menu, Separator # create odor list menu = Menu(name='Odors') for i, name in enumerate(odorlbl): menu.append(Action(name=name, action='_show%g' % i)) #menu.append(Separator()) menu1 = Menu(name='View') menu1.append(Action(name='Set View as Vinci\'s', action='_setview')) menu1.append(Action(name='Clean gloms', action='_clean')) return MenuBar(menu, menu1), OdorHandler(fig, bulb, glomval)
class Flip(SingletonHasTraits): flippen = Button(desc="flip the mirror", label="flip mirror") def __init__(self, TriggerChannels): self._trigger_task = DOTask(TriggerChannels) SingletonHasTraits.__init__(self) def _flippen_changed(self): self._change_mirror() def _change_mirror(self): self._trigger_task.Write(numpy.array((1, ), dtype=numpy.uint8)) time.sleep(0.001) self._trigger_task.Write(numpy.array((0, ), dtype=numpy.uint8)) view = View(Item('flippen', show_label=False), menubar=MenuBar( Menu(Action(action='_on_close', name='Quit'), name='File')), title='Flip mirror', width=100, height=100, buttons=[], resizable=True, handler=CloseHandler)
def _buttons_default(self): """Return the view's buttons.""" # Create an action that will search the database. buttons = [Action(name="Search")] buttons.extend(OKCancelButtons) return buttons
def _add_viewer_actions_menu_default(self): actions = [] for viewer_plugin in find_viewer_plugins(): actions += [Action( name = viewer_plugin.__name__, action = 'handler.add_viewer(editor,object,"%s")' % viewer_plugin.__name__ )] return Menu(name = 'Add', *actions)
def _build_source_actions(self): actions = [] a = Action(name='Open File ...', action='object.menu_helper.open_file_action', tooltip='Open a supported data file') actions.append(a) for src in registry.sources: if len(src.extensions) == 0: # The method that creates the source. setattr(self, src.id, lambda self=self, md=src, select=True: self._create_source(md, select)) a = Action(name=src.menu_name, action='object.menu_helper.'+src.id, tooltip=src.tooltip) actions.append(a) return actions
def traits_view(self): """ Default traits view for this class. """ help_action = Action(name='Info', action='preferences_help') buttons = ['OK', 'Cancel'] if self.show_apply: buttons = ['Apply'] + buttons if self.show_help: buttons = [help_action] + buttons # A tree editor for preferences nodes. tree_editor = TreeEditor(nodes=[ TreeNode( node_for=[PreferencesNode], auto_open=False, children='children', label='name', rename=False, copy=False, delete=False, insert=False, menu=None, ), ], on_select=self._selection_changed, editable=False, hide_root=True, selected='selected_node', show_icons=False) view = View( HSplit( Item( name='root', editor=tree_editor, show_label=False, width=250, ), Item( name='selected_page', #editor = WidgetEditor(), show_label=False, width=450, style='custom', ), ), buttons=buttons, handler=PreferencesManagerHandler(model=self), resizable=True, title='Preferences', width=.3, height=.3, kind='modal') self.selected_page = self.pages[0] return view
def __init__(self, **traits): """Initialise the object.""" buttons = [Action(name="Search"), Action(name="Add"), Action(name="Modify"), Action(name="Delete"), CancelButton] all_perms = get_permissions_manager().policy_manager.permissions.values() perms_editor = SetEditor(values=all_perms, left_column_title="Available Permissions", right_column_title="Assigned Permissions") perms_group = Group(Item(name='permissions', editor=perms_editor), label='Permissions', show_border=True, show_labels=False) super(_RoleView, self).__init__(Item(name='name'), Item(name='description'), perms_group, buttons=buttons, **traits)
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)
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))
class AffectsAverageColumn(ObjectColumn): # The context menu for the column: menu = Menu(Action(name='Add', action='column.add( object )'), Action(name='Sub', action='column.sub( object )')) # Right-align numeric values (override): horizontal_alignment = 'center' # Column width (override): width = 0.09 # Don't allow the data to be edited directly: editable = False def add(self, object): """ Increment the affected player statistic. """ setattr(object, self.name, getattr(object, self.name) + 1) def sub(self, object): """ Decrement the affected player statistic. """ setattr(object, self.name, getattr(object, self.name) - 1)
def _build_filter_actions(self): actions = [] for fil in registry.filters: # The method that creates the object. setattr(self, fil.id, lambda self=self, md=fil, select=True: self._create_object(md, select)) # The method that checks if the menu can be activated or # not. setattr(self, 'check_' + fil.id, lambda self=self, md=fil: self.check_active(md)) a = Action(name=fil.menu_name, action='object.menu_helper.' + fil.id, enabled_when='object.menu_helper.check_%s()'%fil.id, tooltip=fil.tooltip) actions.append(a) return actions
def _build_module_actions(self): actions = [] for mod in registry.modules: # The method that creates the module. setattr(self, mod.id, lambda self=self, md=mod, select=True: self._create_object(md, select)) # The method that checks if the menu can be activated or # not. setattr(self, 'check_' + mod.id, lambda self=self, md=mod: self.check_active(md)) a = Action(name=mod.menu_name, action='object.menu_helper.' + mod.id, enabled_when='object.menu_helper.check_%s()'%mod.id, tooltip=mod.tooltip) actions.append(a) return actions
def _actions_default(self): """ Append a preferences action to the toolbar: this view of the engine is meant to be a powerful view giving access to all of Mayavi's functionality. """ preferences_action = \ Action( image=ImageResource('preferences.png', search_path=self._image_path), tooltip="Modify Mayavi's preferences", checked=False, defined_when='True', perform=preference_manager_view.dialog_view, ) actions = super(EngineRichView, self)._actions_default() actions.extend((Separator(), preferences_action)) return actions
def _buildAction(desc): global actions_doc from window import tcActionHandler if len(desc) == 0: return Separator() exec("tcActionHandler.%s = lambda self,i:self.chooseAction(i,'_on_%s')"%(desc["name"],desc["name"])) style = desc["name"].startswith("toggle") and "toggle" or "push" default = False if "default" in desc: default = desc["default"] desc["tooltip"] = desc["tooltip"].strip() action = Action(name=desc["name"].replace("_"," "), action=desc["name"], tooltip=desc["tooltip"], image=ImageResource(desc["name"]), style=style, checked=default) tcActionHandler.actions[desc["name"]] = action if not actions_doc is None: actions_doc += "\n**%s**:\n"%(desc["name"].replace("_"," ").strip()) actions_doc += "\n.. image:: images/%s.png\n\n"%(desc["name"]) actions_doc += desc["tooltip"] +"\n" return action
def traits_view(self): file_menu = Menu( ActionGroup( Action(id="open", name=u"打开", action="open_file"), Action(id="save", name=u"保存", action="save_file"), ), ActionGroup( Action(id="exit_app", name=u"退出", action="exit_app"), ), name = u"文件" ) about_menu = Menu( Action(id="about", name=u"关于", action="about_dialog"), name = u"帮助" ) tool_bar = ToolBar( Action( image = ImageResource("folder_page.png", search_path = ["img"]), tooltip = u"打开文档", action = "open_file" ), Action( image = ImageResource("disk.png", search_path = ["img"]), tooltip = u"保存文档", action = "save_file" ), ) return View( Item("text", style="custom", show_label=False, editor=CodeEditor(line="current_line")), menubar = MenuBar(file_menu, about_menu), toolbar = tool_bar, statusbar = ["status_info"], resizable = True, width = 500, height = 300, title = u"程序编辑器", handler = MenuDemoHandler() )
class PlotOMaticHandler(Controller): # ------------ Menu related -------------------- exit_action = Action(name='&Exit', action='exit') save_session_action = Action(name='&Open Session', action='open_session', accelerator='Ctrl+O') open_session_action = Action(name='&Save Session', action='save_session', accelerator='Ctrl+S') file_menu = Menu(exit_action, Separator(), save_session_action, open_session_action, name='&File') def exit(self, uii): print 'Exit called, really should implement this' def save_session(self, uii): filename = save_file( wildcard= 'Plot-o-matic session (*.plot_session)|*.plot_session|All files (*)|*', file_name='my_session.plot_session', message='Save session') if filename != '': print "Saving session as '%s'" % filename session = uii.object.get_config() fp = open(filename, 'w') yaml.safe_dump(session, fp, default_flow_style=False) fp.close() def open_session(self, uii): filename = open_file( wildcard= 'Plot-o-matic session (*.plot_session)|*.plot_session|All files (*)|*', file_name='my_session.plot_session', message='Open session') if filename != '': print "Opening session '%s'" % filename fp = open(filename, 'r') session = yaml.load(fp) fp.close() uii.object.set_config(session) clear_data_action = Action(name='&Clear Data', action='clear_data', accelerator='Ctrl+W') save_data_action = Action(name='&Save Data Set', action='save_data', accelerator='Ctrl+Shift+S') open_data_action = Action(name='&Open Data Set', action='open_data', accelerator='Ctrl+Shift+O') data_menu = Menu(clear_data_action, Separator(), save_data_action, open_data_action, name='&Data') def clear_data(self, uii): uii.object.variables.clear() def save_data(self, uii): filename = save_file( wildcard= 'Plot-o-matic data set (*.plot_data)|*.plot_data|All files (*)|*', file_name='my_data.plot_data', message='Save data set') if filename != '': uii.object.variables.save_data_set(filename) print "Saved data set '%s'" % filename def open_data(self, uii): filename = open_file( wildcard= 'Plot-o-matic data set (*.plot_data)|*.plot_data|All files (*)|*', file_name='my_data.plot_data', message='Open data set') if filename != '': uii.object.variables.open_data_set(filename) print "Opened data set '%s'" % filename # ------------ Tree related -------------------- remove_io_driver_action = Action( name='Remove', action='handler.remove_io_driver(editor,object)') add_io_driver_actions_menu = Instance(Menu) remove_decoder_action = Action( name='Remove', action='handler.remove_decoder(editor,object)') add_decoder_actions_menu = Instance(Menu) remove_viewer_action = Action( name='Remove', action='handler.remove_viewer(editor,object)') add_viewer_actions_menu = Instance(Menu) refresh_tree_action = Action(name='Refresh', action='handler.refresh_tree(editor)') def refresh_tree(self, editor): editor.update_editor() def _add_io_driver_actions_menu_default(self): actions = [] for io_driver_plugin in find_io_driver_plugins(): actions += [ Action(name=io_driver_plugin.__name__, action='handler.add_io_driver(editor,object,"%s")' % io_driver_plugin.__name__) ] return Menu(name='Add', *actions) def remove_io_driver(self, editor, io_driver_object): io_driver_list = editor._menu_parent_object io_driver_list._remove_io_driver(io_driver_object) editor.update_editor() def add_io_driver(self, editor, io_driver_list, new_io_driver_name): new_io_driver = get_io_driver_plugin_by_name(new_io_driver_name)() io_driver_list._add_io_driver(new_io_driver) editor.update_editor() def _add_decoder_actions_menu_default(self): actions = [] for decoder_plugin in find_decoder_plugins(): actions += [ Action(name=decoder_plugin.__name__, action='handler.add_decoder(editor,object,"%s")' % decoder_plugin.__name__) ] return Menu(name='Add', *actions) def remove_decoder(self, editor, decoder_object): parent_io_driver = editor._menu_parent_object parent_io_driver._remove_decoder(decoder_object) editor.update_editor() def add_decoder(self, editor, io_driver, decoder_name): io_driver_list = editor._menu_parent_object new_decoder = get_decoder_plugin_by_name(decoder_name)() io_driver._add_decoder(new_decoder) editor.update_editor() def _add_viewer_actions_menu_default(self): actions = [] for viewer_plugin in find_viewer_plugins(): actions += [ Action(name=viewer_plugin.__name__, action='handler.add_viewer(editor,object,"%s")' % viewer_plugin.__name__) ] return Menu(name='Add', *actions) def remove_viewer(self, editor, viewer_object): viewers = editor._menu_parent_object.viewers_instance viewers._remove_viewer(viewer_object) editor.update_editor() def add_viewer(self, editor, object, viewer_name): new_viewer = get_viewer_plugin_by_name(viewer_name)() object.viewers_instance._add_viewer(new_viewer) editor.update_editor()
def __init__(self, *args, **kargs): super(StonerPlot, self).__init__(*args, **kargs) self.data = numpy.zeros((2, 2)) acols = [(self.column_headers[i], i) for i in range(len(self.column_headers))] acols[:0] = [("index", "index")] self.adapter = ArrayAdapter() self.adapter.columns = acols self.plotgroup = Group(HGroup( VGroup( Item('xc', label='X Column', editor=CheckListEditor(name='column_headers')), Item('xm', label="X Scale")), VGroup( Item('yc', label='Y Column', editor=CheckListEditor(name='column_headers')), Item('ym', label="Y scale")), Item('p_type', label='Plot Type')), HGroup( Item('color', label="Colour", style="simple", width=75, visible_when='"scatter" in p_type'), Item('line_color', label="Line Colour", style="simple", visible_when='outline_width>0', width=75), Item('marker', label="Marker", visible_when='"scatter" in p_type'), Item('line_style', label='Line Style', visible_when="'line' in p_type"), Item('marker_size', label="Marker Size", visible_when='"scatter" in p_type'), Item('outline_width', label="Line Width")), Item('plot', editor=ComponentEditor(), show_label=False), label="Plot", orientation="vertical") self.datagroup = HGroup(Item( 'data', show_label=False, style='readonly', editor=TabularEditor(adapter=self.adapter)), Item('metadata', editor=ValueEditor(), show_label=False, width=0.25), label="Data") self.tabs = Tabbed(self.plotgroup, self.datagroup, orientation="horizontal") self.menubar = MenuBar( Menu( Action(name='E&xit', accelerator="Ctrl+Q", tooltip="E&xit", action='_on_close'), Separator(), Action(name="&Open", accelerator="Ctrl+O", tooltip="&Open Data File", action="load"), # these callbacks Action(name="&Close", accelerator="Ctrl+W", tooltip="&Close Plot", action="close_plot"), # these callbacks name="File")) self._paint()
class TableFilter ( HasPrivateTraits ): """ Filter for items displayed in a table. """ #--------------------------------------------------------------------------- # Trait definitions: #--------------------------------------------------------------------------- # UI name of this filter (so the user can identify it in the UI) name = Str( 'Default filter' ) # Default name that can be automatically overridden _name = Str( 'Default filter' ) # A user-readable description of what kind of object satisfies the filter desc = Str( 'All items' ) # A callable function that returns whether the passed object is allowed # by the filter allowed = Callable( lambda object: True ) # Is the filter a template (i.e., non-deletable, non-editable)? template = false #--------------------------------------------------------------------------- # Class constants: #--------------------------------------------------------------------------- # Traits that are ignored by the _anytrait_changed() handler ignored_traits = [ '_name', 'template', 'desc' ] #--------------------------------------------------------------------------- # Traits view definitions: #--------------------------------------------------------------------------- traits_view = View( 'name{Filter name}', '_', Include( 'filter_view' ), title = 'Edit Filter', width = 0.2, buttons = [ 'OK', 'Cancel', Action( name = 'Help', action = 'show_help', defined_when = "ui.view_elements.content['filter_view']" ".help_id != ''" ) ] ) searchable_view = View( [ [ Include( 'search_view' ), '|[]' ], [ 'handler.status~', '|[]<>' ], [ 'handler.find_next`Find the next matching item`', 'handler.find_previous`Find the previous matching item`', 'handler.select`Select all matching items`', 'handler.OK`Exit search`', '-<>' ], '|<>' ], title = 'Search for', kind = 'livemodal', undo = False, revert = False, ok = False, cancel = False, help = False, width = 0.25 ) search_view = Group( Include( 'filter_view' ) ) filter_view = Group() #--------------------------------------------------------------------------- # Returns whether a specified object meets the filter/search criteria: # (Should normally be overridden) #--------------------------------------------------------------------------- def filter ( self, object ): """ Returns whether a specified object meets the filter or search criteria. """ return self.allowed( object ) #--------------------------------------------------------------------------- # Returns a user readable description of what kind of object will # satisfy the filter: # (Should normally be overridden): #--------------------------------------------------------------------------- def description ( self ): """ Returns a user-readable description of what kind of object satisfies the filter. """ return self.desc #--------------------------------------------------------------------------- # Edits the contents of the filter: #--------------------------------------------------------------------------- def edit ( self, object ): """ Edits the contents of the filter. The ''object'' parameter is a sample object for the table that the filter will be applied to. It is supplied in case the filter needs to extract data or metadata from the object. If the table is empty, the ''object'' argument is None. """ return self.edit_traits( kind = 'livemodal' ) #--------------------------------------------------------------------------- # 'object' interface: #--------------------------------------------------------------------------- def __str__ ( self ): return self.name #--------------------------------------------------------------------------- # Event handlers: #--------------------------------------------------------------------------- def _anytrait_changed ( self, name, old, new ): if ((name not in self.ignored_traits) and ((self.name == self._name) or (self.name == ''))): self.name = self._name = self.description()
Separator(), DeleteAction, Separator(), RenameAction, Separator(), CopyAction, CutAction, PasteAction ), view = View( [ 'name', '|<' ] ), add = [ Employee ] ), TreeNode( node_for = [ Employee ], auto_open = True, label = 'name', menu = Menu( NewAction, Separator(), Action( name = 'Default title', action = 'object.default_title' ), Action( name = 'Department', action = 'handler.employee_department(editor,object)' ), Separator(), CopyAction, CutAction, PasteAction, Separator(), DeleteAction, Separator(), RenameAction ), view = View( [ 'name', 'title', 'phone', '|<' ] ) ) ] ) #-------------------------------------------------------------------------------
def _actions_default(self): add_scene = Action( image=ImageResource("add_scene.png", search_path=self._image_path), tooltip="Create a new scene", defined_when="True", enabled_when="True", perform=self._perform_new_scene, ) add_source = Action( image=ImageResource("add_source.png", search_path=self._image_path), tooltip="Add a data source", defined_when="True", enabled_when="len(scenes) > 0", perform=self._perform_add_source, ) add_module = Action( image=ImageResource("add_module.png", search_path=self._image_path), tooltip="Add a visualization module", defined_when="True", # isinstance doesn't work in enabled_when enabled_when="current_selection is not None and" '( hasattr(current_selection, "output_info")' "or current_selection.__class__.__name__ ==" '"ModuleFilterAdderNode")', perform=self._perform_add_module, ) add_filter = Action( image=ImageResource("add_filter.png", search_path=self._image_path), tooltip="Add a processing filter", defined_when="True", enabled_when="current_selection is not None and" '( ( hasattr(current_selection, "output_info")' ' and not current_selection.type in (" module", ' ' " module manager"))' "or current_selection.__class__.__name__ ==" '"ModuleFilterAdderNode")', perform=self._perform_add_filter, ) help = Action( image=ImageResource("help-action.png", search_path=self._image_path), tooltip="Help on the Mayavi pipeline", defined_when="True", enabled_when="True", perform=open_help_index, ) tvtk_docs = Action( image=ImageResource("reader.png", search_path=self._image_path), tooltip="Search the VTK class browser", defined_when="True", enabled_when="True", perform=open_tvtk_docs, ) record = Action( image=ImageResource("record.png", search_path=self._image_path), tooltip="Start/Stop script recording", style="toggle", checked=False, defined_when="True", enabled_when="engine is not None", perform=self._perform_record, ) # Check the record icon if the engine already has a recorder # set. if self.engine is not None and self.engine.recorder is not None: record.checked = True return [tvtk_docs, Separator(), add_scene, add_source, add_module, add_filter, Separator(), help, record]
def _actions_default(self): add_scene = \ Action( image=ImageResource('add_scene.png', search_path=self._image_path), tooltip="Create a new scene", defined_when='True', enabled_when='True', perform=self._perform_new_scene, ) add_source = \ Action( image=ImageResource('add_source.png', search_path=self._image_path), tooltip="Add a data source", defined_when='True', enabled_when='len(scenes) > 0', perform=self._perform_add_source, ) add_module = \ Action( image=ImageResource('add_module.png', search_path=self._image_path), tooltip="Add a visualization module", defined_when='True', # isinstance doesn't work in enabled_when enabled_when=\ 'current_selection is not None and' '( hasattr(current_selection, "output_info")' 'or current_selection.__class__.__name__ ==' '"ModuleFilterAdderNode")', perform=self._perform_add_module, ) add_filter = \ Action( image=ImageResource('add_filter.png', search_path=self._image_path), tooltip="Add a processing filter", defined_when='True', enabled_when=\ 'current_selection is not None and' '( ( hasattr(current_selection, "output_info")' ' and not current_selection.type in (" module", ' ' " module manager"))' 'or current_selection.__class__.__name__ ==' '"ModuleFilterAdderNode")', perform=self._perform_add_filter, ) help = \ Action( image=ImageResource('help-action.png', search_path=self._image_path), tooltip="Help on the Mayavi pipeline", defined_when='True', enabled_when='True', perform=open_help_index, ) tvtk_docs = \ Action( image=ImageResource('reader.png', search_path=self._image_path), tooltip="Search the VTK class browser", defined_when='True', enabled_when='True', perform=open_tvtk_docs, ) record = \ Action( image=ImageResource('record.png', search_path=self._image_path), tooltip="Start/Stop script recording", style='toggle', checked=False, defined_when='True', enabled_when='engine is not None', perform=self._perform_record, ) # Check the record icon if the engine already has a recorder # set. if self.engine is not None and self.engine.recorder is not None: record.checked = True return [ tvtk_docs, Separator(), add_scene, add_source, add_module, add_filter, Separator(), help, record ]
from enthought.mayavi.preferences.api import preference_manager from enthought.mayavi.core.common import get_engine # Setup a logger for this module. logger = logging.getLogger(__name__) # Subdirectory that the Base class will check for possible external views. UI_DIR_NAME = ['ui'] #------------------------------------------------------------------------------- # The core tree node menu actions: #------------------------------------------------------------------------------- NewAction = 'NewAction' CopyAction = Action(name = 'Copy', action = 'editor._menu_copy_node', enabled_when = 'editor._is_copyable(object)' ) CutAction = Action(name = 'Cut', action = 'editor._menu_cut_node', enabled_when = 'editor._is_cutable(object)' ) PasteAction = Action(name = 'Paste', action = 'editor._menu_paste_node', enabled_when = 'editor._is_pasteable(object)' ) DeleteAction = Action(name = 'Delete', action = 'editor._menu_delete_node', enabled_when = 'editor._is_deletable(object)' ) RenameAction = Action(name = 'Rename', action = 'editor._menu_rename_node', enabled_when = 'editor._is_renameable(object)' ) standard_menu_actions = [Separator(), CutAction, CopyAction, PasteAction, Separator(),
class ViewChooser(HasTraits): """ Allow the user to choose a view. This implementation shows views in a tree grouped by category. """ # The window that contains the views to choose from. window = Instance('enthought.pyface.workbench.api.WorkbenchWindow') # The currently selected tree item (at any point in time this might be # either None, a view category, or a view). selected = Any # The selected view (None if the selected item is not a view). view = Instance(IView) #### Traits UI views ###################################################### traits_ui_view = View( Item(name='window', editor=TreeEditor(nodes=[ WorkbenchWindowTreeNode( auto_open=True, label='=Views', rename=False, copy=False, delete=False, insert=False, menu=None, ), TreeNode( node_for=[Category], auto_open=True, children='views', label='name', rename=False, copy=False, delete=False, insert=False, menu=None, ), IViewTreeNode( auto_open=False, label='name', rename=False, copy=False, delete=False, insert=False, menu=None, ) ], editable=False, hide_root=True, selected='selected', show_icons=True), show_label=False), buttons=[Action(name='OK', enabled_when='view is not None'), 'Cancel'], resizable=True, style='custom', title='Show View', width=.2, height=.4) ########################################################################### # 'ViewChooser' interface. ########################################################################### def _selected_changed(self, old, new): """ Static trait change handler. """ # If the assignment fails then the selected object does *not* implement # the 'IView' interface. try: self.view = new except TraitError: self.view = None return
#------------------------------------------------------------------------------ # Imports: #------------------------------------------------------------------------------ from os.path import join, dirname from enthought.pyface.api import ImageResource from enthought.traits.ui.menu import MenuBar, ToolBar, Menu, Action #------------------------------------------------------------------------------ # File actions: #------------------------------------------------------------------------------ new_action = Action(name="&New", accelerator="Ctrl+N", action="new_model", image=ImageResource("new"), tooltip="New (Ctrl+N)") open_action = Action(name="&Open", accelerator="Ctrl+O", action="open_file", image=ImageResource("open"), tooltip="Open (Ctrl+O)") save_action = Action(name="&Save", accelerator="Ctrl+S", action="save", image=ImageResource("save"), tooltip="Save (Ctrl+S)")
RTImage.add_class_trait('rtplan', Instance(RTPlan)) RTDose.add_class_trait('rtplan', Instance(RTPlan)) RTImage.add_class_trait('rttreatmentrecord', Instance(RTTreatmentRecord)) RTPlan.add_class_trait('rttreatmentrecord', Instance(RTTreatmentRecord)) SOPInstance.add_class_trait('series', Instance(Series)) Series.add_class_trait('study', Instance(Study)) Study.add_class_trait('patient', Instance(Patient)) Beam.add_class_trait('plan', Instance(RTPlan)) ControlPoint.add_class_trait('beam', Instance(Beam)) # View for objects that aren't edited no_view = View() # Actions used by tree editor context menu def_title_action = Action(name='Default title', action='object.default') import sys root = Root(patientlist=PatientList()) for fn in sys.argv[1:]: try: dicom.read_file(fn) root.filenames.append(fn) print "added %s" % (fn, ) except: continue print "\n".join(root.filenames) patient_action = Action(name='Patient', action='handler.dump_patient(editor,object)')
class MainWindow(HasTraits): parameter_file_collections = Instance(ParameterFileCollectionList) parameter_files = Instance(ParameterFileCollection) plot_frame_tabs = List(Instance(DataObject)) open_parameterfile = Button shell = PythonValue def _shell_default(self): return globals() notebook_editor = ListEditor(editor=InstanceEditor(editable=True), use_notebook=True) traits_view = View( VSplit( HSplit( VGroup( Item( 'parameter_file_collections', width=120.0, height=500.0, show_label=False, editor=TreeEditor( editable=False, nodes=[ TreeNode( node_for=[ParameterFileCollectionList], children='parameter_file_collections', label="=Data Collections"), TreeNode(node_for=[ParameterFileCollection], children='parameter_files', label="name", view=View()), TreeNode(node_for=[ParameterFile], children='data_objects', label="name", menu=Menu( Action(name='Slice', action='object.do_slice'), Action(name='Project', action='object.do_proj'), Action(name='VTK', action='object.do_vtk')), view=View()), TreeNode(node_for=[DataObject], children='', label="name"), ], show_icons=False), ), Item('open_parameterfile', show_label=False)), Item('plot_frame_tabs', style='custom', editor=notebook_editor, show_label=False, height=500.0, width=500.0), ), HGroup( #Item('shell', editor=ShellEditor(share=True), #show_label=False, height=120.0), ), ), resizable=True, width=800.0, height=660.0, title="reason v2 [prototype]") def _open_parameterfile_fired(self): print "OPENING" def _parameter_file_collections_default(self): return ParameterFileCollectionList()
class ControlTab(HasTraits): """ This object is the core of the traitsUI interface. Its view is the right panel of the application, and it hosts the method for interaction between the objects and the GUI. """ move_step = Enum(1,0.2,0.5,1,2,5,10) scale_step = Enum(10,1,5,10,20,50,100) channels = List() ch_editor = CheckListEditor(values=[],cols=2) num_channels = Int(0) patient_name = Str() select_all = Button("all") select_none = Button("none") select_good = Button("good (db)") mlcount = Int(0) mrcount = Int(0) mucount = Int(0) mdcount = Int(0) #_sls = [0,1100,5] #StartLengthStride #acquisition_thread = Instance(AcquisitionThread) move_left = Action(name = "Left", action = "_trigger_move_left", toolip = "Move to the left", image = ImageResource("images/left_32.png") ) move_right = Action(name = "Right", action = "_trigger_move_right", toolip = "Move to the right", image = ImageResource("images/right_32.png") ) scale_up = Action(name = "Scale up", action = "_trigger_scale_up", toolip = "Move to the right", image = ImageResource("images/up_32.png") ) scale_down = Action(name = "Scale down", action = "_trigger_scale_down", toolip = "Move to the right", image = ImageResource("images/down_32.png") ) toolbar = ToolBar(move_left, move_right,scale_up,scale_down) traits_view = View(VGroup( #Item('do_plot', show_label=False ), VGroup( Item('move_step',label="Move by:"), Item('scale_step',label="Scale by"), ), VGroup( Group( Item('channels', show_label=False, style='custom', editor=ch_editor, #springy=True, #height=-500, ), scrollable=True, springy=True, ), HGroup( spring, Item('select_all',show_label=False), Item('select_none',show_label=False), Item('select_good',show_label=False), spring, ), label = "Choose channels", #height=300, ), #Item('results_string',show_label=False, # springy=True, style='custom' ), #springy=True, #scrollable=True, #height=-500, dock='tab', springy=True #scrollable=True ), toolbar=toolbar, scrollable=True #height=-500, ) #key_bindings=key_bindings, #handler=ControlHandler, def _trigger_move_left(self): #print "Trigger Left" self.mlcount+=1 def _trigger_move_right(self): self.mrcount+=1 #print "Trigger Right" def _trigger_scale_up(self): self.mucount+=1 def _trigger_scale_down(self): self.mdcount+=1 def _select_none_fired(self): self.channels = [] def _select_all_fired(self): self.channels = range(self.num_channels) def _select_good_fired(self): try: gc = schlaf_ged.get_good_channels(self.patient_name) print "Got", gc, "from database" self.channels = gc except ValueError, ve: #Zeige Fehlermeldung print ve print self.patient_name try: short_patient_name = self.patient_name.split("_")[0] gc = schlaf_ged.get_good_channels(short_patient_name) print "Got", gc, "from database" self.channels = gc except ValueError,ve: print ve print short_patient_name message = Message(message="Cannot find good channels for subject %s" % self.patient_name) message.edit_traits()