def normal_key_pressed(self, event): """ Handles a key-press when the tool is in the 'normal' state. Saves an image of the plot if the keys pressed are Control and S. """ if self.component is None: return if event.character == "s" and event.control_down: if self.filenameview.configure_traits(view=View( Item('filename', editor=FileEditor(entries=0, filter=[ 'PNG file (*.png)|*.png', 'GIF file (*.gif)|*.gif', 'JPG file (*.jpg)|*.jpg', 'JPEG file (*.jpeg)|*.jpeg', 'PDF file (*.pdf)|*.pdf' ])), buttons=['OK', 'Cancel']), kind='modal'): if os.path.splitext(self.filename)[-1] == ".pdf": self._save_pdf() else: self._save_raster() event.handled = True return
class HistoryDemo(HasTraits): name = Str file = File directory = Directory view = View(Item('name', id='name', editor=HistoryEditor(entries=5)), Item('file', id='file1', editor=FileEditor(entries=10)), Item('file', id='file2', editor=FileEditor(entries=10, filter=[ 'All files (*.*)|*.*', 'Python files (*.py)|*.py' ])), Item('directory', id='directory', editor=DirectoryEditor(entries=10)), title='History Editor Demo', id='enthought.test.history_demo.HistoryDemo', width=0.33, resizable=True)
def get_file_from_user(cwd='', filter=['All (*)|*'], entries=0): filename = FileName(filename=cwd) f = filename.configure_traits(view=View(Item('filename', editor=FileEditor( entries=entries, filter=filter)), buttons=['OK', 'Cancel'], width=500, height=200), kind='modal') if f: return filename.filename else: return None
class PLOT3DReader(Source): """A PLOT3D file reader. This reader does not support a timeseries of files. """ # The version of this class. Used for persistence. __version__ = 0 # XYZ file name xyz_file_name = Str('', desc='the XYZ file') # The (optional) Q file. q_file_name = Str('', desc='the Q file') # The active scalar name. scalars_name = Trait('density', TraitPrefixMap({ 'density': 100, 'pressure': 110, 'temperature': 120, 'enthalpy': 130, 'internal energy': 140, 'kinetic energy': 144, 'velocity magnitude': 153, 'stagnation energy': 163, 'entropy': 170, 'swirl': 184 }), desc='scalar data attribute to show') # The active vector name. vectors_name = Trait('momentum', TraitPrefixMap({ 'velocity': 200, 'vorticity': 201, 'momentum': 202, 'pressure gradient': 210 }), desc='vector data attribute to show') # The VTK data file reader. reader = Instance(tvtk.PLOT3DReader, args=(), allow_none=False, record=True) # Information about what this object can produce. output_info = PipelineInfo(datasets=['structured_grid']) ######################################## # View related code. update_reader = Button('Update Reader') # Our view. view = View(Group( Item('xyz_file_name', editor=FileEditor()), Item('q_file_name', editor=FileEditor()), Item(name='scalars_name', enabled_when='len(object.q_file_name) > 0'), Item(name='vectors_name', enabled_when='len(object.q_file_name)>0'), Item(name='update_reader'), label='Reader', ), Group(Item(name='reader', style='custom', resizable=True), show_labels=False, label='PLOT3DReader'), resizable=True) ######################################## # Private traits. # The current file paths. This is not meant to be touched by the # user. xyz_file_path = Instance(FilePath, args=(), desc='the current XYZ file path') q_file_path = Instance(FilePath, args=(), desc='the current Q file path') ###################################################################### # `object` interface ###################################################################### def __get_pure_state__(self): d = super(PLOT3DReader, self).__get_pure_state__() # These traits are dynamically created. for name in ('scalars_name', 'vectors_name', 'xyz_file_name', 'q_file_name'): d.pop(name, None) return d def __set_pure_state__(self, state): xyz_fn = state.xyz_file_path.abs_pth q_fn = state.q_file_path.abs_pth if not isfile(xyz_fn): msg = 'Could not find file at %s\n' % xyz_fn msg += 'Please move the file there and try again.' raise IOError, msg # Setup the reader state. set_state(self, state, first=['reader'], ignore=['*']) # Initialize the files. self.initialize(xyz_fn, q_fn, configure=False) # Now set the remaining state without touching the children. set_state(self, state, ignore=['children', 'xyz_file_path', 'q_file_path']) # Setup the children. handle_children_state(self.children, state.children) # Setup the children's state. set_state(self, state, first=['children'], ignore=['*']) ###################################################################### # `FileDataSource` interface ###################################################################### def initialize(self, xyz_file_name, q_file_name='', configure=True): """Given an xyz filename and a Q filename which may or may not be part of a time series, this initializes the list of files. This method need not be called to initialize the data. If configure is True, it pops up a UI to configure the PLOT3DReader. """ if len(q_file_name) == 0: base = splitext(xyz_file_name)[0] qf = base + '.q' if exists(qf): q_file_name = qf if configure: # First set properties of the reader. This is useful when # the data format has atypical defaults. Automatic # detection can be disastrous sometimes due to VTK related # problems. self.reader.edit_traits(kind='livemodal') self.xyz_file_name = xyz_file_name if len(q_file_name) > 0: self.q_file_name = q_file_name def update(self): if len(self.xyz_file_path.get()) == 0: return self.reader.update() self.render() ###################################################################### # Non-public interface ###################################################################### def _xyz_file_name_changed(self, value): if len(value) == 0: return else: self.reader.xyz_file_name = value self.xyz_file_path.set(value) self._update_reader_output() def _q_file_name_changed(self, value): if len(value) == 0: return else: self.reader.q_file_name = value self.q_file_path.set(value) self._update_reader_output() def _update_reader_output(self): r = self.reader r.update() if r.error_code != 0: try: self.reader.i_blanking = True except AttributeError: pass else: r.update() # Try reading file. if r.error_code != 0: # No output so the file might be an ASCII file. try: # Turn off IBlanking. r.set(i_blanking=False, binary_file=False) except AttributeError: pass else: r.update() # Try again this time as ascii and with blanking. if r.error_code != 0: # No output so the file might be an ASCII file. try: # Turn on IBlanking. r.i_blanking = True except AttributeError: pass else: r.update() # If there still is an error, ask the user. if r.error_code != 0: r.edit_traits(kind='livemodal') r.update() # If there still is an error, ask the user to retry. if r.error_code != 0: msg = 'Unable to read file properly. '\ 'Please check the settings of the reader '\ 'on the UI and press the "Update Reader" button '\ 'when done and try again!' error(msg) return # Now setup the outputs by resetting self.outputs. Changing # the outputs automatically fires a pipeline_changed event. try: n = r.number_of_output_ports except AttributeError: # for VTK >= 4.5 n = r.number_of_outputs outputs = [] for i in range(n): outputs.append(r.get_output(i)) self.outputs = outputs # Fire data_changed just in case the outputs are not # really changed. This can happen if the dataset is of # the same type as before. self.data_changed = True # Change our name on the tree view self.name = self._get_name() def _scalars_name_changed(self, value): self.reader.scalar_function_number = self.scalars_name_ self.reader.modified() self.update() self.data_changed = True def _vectors_name_changed(self, value): self.reader.vector_function_number = self.vectors_name_ self.reader.modified() self.update() self.data_changed = True def _update_reader_fired(self): self.reader.modified() self._update_reader_output() self.pipeline_changed = True def _get_name(self): """ Gets the name to display on the tree view. """ xyz_fname = basename(self.xyz_file_path.get()) q_fname = basename(self.q_file_path.get()) if len(self.q_file_name) > 0: ret = "PLOT3D:%s, %s" % (xyz_fname, q_fname) else: ret = "PLOT3D:%s" % (xyz_fname) if '[Hidden]' in self.name: ret += ' [Hidden]' return ret
class FileDataSource(Source): # The version of this class. Used for persistence. __version__ = 0 # The list of file names for the timeseries. file_list = List(Str, desc='a list of files belonging to a time series') # The current time step (starts with 0). This trait is a dummy # and is dynamically changed when the `file_list` trait changes. # This is done so the timestep bounds are linked to the number of # the files in the file list. timestep = Range(value=0, low='_min_timestep', high='_max_timestep', enter_set=True, auto_set=False, desc='the current time step') base_file_name = Str('', desc="the base name of the file", enter_set=True, auto_set=False, editor=FileEditor()) # A timestep view group that may be included by subclasses. time_step_group = Group( Item(name='file_path', style='readonly'), Item(name='timestep', defined_when='len(object.file_list) > 1')) ################################################## # Private traits. ################################################## # The current file name. This is not meant to be touched by the # user. file_path = Instance(FilePath, (), desc='the current file name') _min_timestep = Int(0) _max_timestep = Int(0) ###################################################################### # `object` interface ###################################################################### def __get_pure_state__(self): d = super(FileDataSource, self).__get_pure_state__() # These are obtained dynamically, so don't pickle them. for x in ['file_list', 'timestep']: d.pop(x, None) return d def __set_pure_state__(self, state): # Use the saved path to initialize the file_list and timestep. fname = state.file_path.abs_pth if not isfile(fname): msg = 'Could not find file at %s\n' % fname msg += 'Please move the file there and try again.' raise IOError, msg self.initialize(fname) # Now set the remaining state without touching the children. set_state(self, state, ignore=['children', 'file_path']) # Setup the children. handle_children_state(self.children, state.children) # Setup the children's state. set_state(self, state, first=['children'], ignore=['*']) ###################################################################### # `FileDataSource` interface ###################################################################### def initialize(self, base_file_name): """Given a single filename which may or may not be part of a time series, this initializes the list of files. This method need not be called to initialize the data. """ self.base_file_name = base_file_name ###################################################################### # Non-public interface ###################################################################### def _file_list_changed(self, value): # Change the range of the timestep suitably to reflect new list. n_files = len(self.file_list) timestep = min(self.timestep, n_files) self._max_timestep = max(n_files - 1, 0) if self.timestep == timestep: self._timestep_changed(timestep) else: self.timestep = timestep def _file_list_items_changed(self, list_event): self._file_list_changed(self.file_list) def _timestep_changed(self, value): file_list = self.file_list if len(file_list) > 0: self.file_path = FilePath(file_list[value]) else: self.file_path = FilePath('') def _base_file_name_changed(self, value): self.file_list = get_file_list(value) if len(self.file_list) == 0: self.file_list = [value] try: self.timestep = self.file_list.index(value) except ValueError: self.timestep = 0
class Person ( HasTraits ): #--------------------------------------------------------------------------- # Trait definitions: #--------------------------------------------------------------------------- name = Str( 'David Morrill' ) age = Int( 39 ) sex = Trait( 'Male', 'Female' ) coolness = Range( 0.0, 10.0, 10.0 ) number = Trait( 1, Range( 1, 6 ), 'one', 'two', 'three', 'four', 'five', 'six' ) human = Bool( True ) employer = Trait( Employer( company = 'Enthought, Inc.', boss = 'eric' ) ) eye_color = RGBAColor set = List( editor = CheckListEditor( values = [ 'one', 'two', 'three', 'four' ], cols = 4 ) ) font = KivaFont street = Str city = Str state = Str zip = Int( 78663 ) password = Str books = List( Str, [ 'East of Eden', 'The Grapes of Wrath', 'Of Mice and Men' ] ) call = Event( 0, editor = ButtonEditor( label = 'Click to call' ) ) info = Str( editor = FileEditor() ) location = Str( editor = DirectoryEditor() ) origin = Trait( editor = ImageEnumEditor( values = origin_values, suffix = '_origin', cols = 4, klass = Employer ), *origin_values ) nm = Item( 'name', enabled_when = 'object.age >= 21' ) pw = Item( 'password', defined_when = 'object.zip == 78664' ) view = View( ( ( nm, 'age', 'coolness', '_', 'eye_color', 'eye_color@', 'eye_color*', 'eye_color~', '_', 'font', 'font@', 'font*', 'font~', '_', 'set', 'set@', 'set*', 'set~', '_', 'sex', 'sex@', 'sex*', 'sex~', '_', 'human', 'human@', 'human*', 'human~', '_', 'number', 'number@', 'number*', 'number~', '_', 'books', '_', 'books@', '_', 'books*', '_', 'books~', '_', 'info', 'location', 'origin', 'origin@', 'call', 'employer', 'employer[]@', 'employer*', 'employer~', pw, '|<[Person:]' ), ( ' ', 'street', 'city', 'state', 'zip', '|<[Address:]' ), ( nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, '|<[Names:]' ), '|' ), title = 'Traits 2 User Interface Test', handler = PersonHandler(), buttons = [ 'Apply', 'Revert', 'Undo', 'OK' ], height = 0.5 ) wizard = View( ( '|p1:', 'name', 'age', 'sex' ), ( '|p2:', 'street', 'city', 'state', 'zip' ), ( '|p3:', 'eye_color', 'origin', 'human' ), handler = WizardHandler() )
class VRMLImporter(Source): __version__ = 0 # The file name. file_name = Str('', enter_set=True, auto_set=False, desc='the VRML file name') # The VRML importer. reader = Instance(tvtk.VRMLImporter, args=(), allow_none=False, record=True) output_info = PipelineInfo(datasets=['none']) ############### # Private traits. # Our file path used for persistence _file_path = Instance(FilePath, args=()) # Our View. view = View(Item(name='file_name', editor=FileEditor())) ###################################################################### # `object` interface ###################################################################### def __get_pure_state__(self): d = super(VRMLImporter, self).__get_pure_state__() # These traits are dynamically created. for name in ('reader', 'file_name'): d.pop(name) return d def __set_pure_state__(self, state): # The reader has its own file_name which needs to be fixed. fname = state._file_path.abs_pth # Now call the parent class to setup everything. self.initialize(fname) # Setup the rest of the state. set_state(self, state, ignore=['_file_path']) def initialize(self, file_name): self.file_name = file_name ###################################################################### # `PipelineBase` interface. ###################################################################### def add_actors(self): """Adds `self.actors` to the scene. """ if not self._actors_added: self.reader.render_window = self.scene.render_window self._update_reader() self._actors_added = True if not self.visible: self._visible_changed(self.visible) self.scene.render() def remove_actors(self): """Removes `self.actors` from the scene. """ if self._actors_added: self.scene.remove_actors(self.actors) self._actors_added = False self.scene.render() ###################################################################### # Non-public interface ###################################################################### def _file_name_changed(self, value): reader = self.reader reader.file_name = value self._file_path.set(value) self._update_reader() self.render() name = "VRML file (%s)" % basename(self.file_name) if '[Hidden]' in self.name: name += ' [Hidden]' self.name = name def _update_reader(self): reader = self.reader if self.scene is None or reader.file_name is None \ or len(reader.file_name) == 0: return actors1 = [x for x in self.scene.renderer.actors] reader.read() self.scene.render() actors2 = [x for x in self.scene.renderer.actors] self.actors = [x for x in actors2 if x not in actors1] # If these are the first actors on scene reset the view. if len(actors1) == 0: self.scene.reset_zoom() def _scene_changed(self, old, new): if self._actors_added: old.remove_actors(self.actors) reader = self.reader reader.render_window = new.render_window self._update_reader() def _actors_changed(self, old, new): if self._actors_added: self.scene.remove_actors(old) # The actors are added automatically when the importer # does a read. self.scene.render() def _actors_items_changed(self, list_event): if self._actors_added: self.scene.remove_actors(list_event.removed) # The actors are added automatically when the importer # does a read. self.scene.render() def _visible_changed(self, value): if value: if not self._actors_added: self.scene.add_actors(self.actors) self._actors_added = True super(VRMLImporter, self)._visible_changed(value)