class XYStageTraits( XYStage, HasTraits): x = Float(default_value=0., mode='text', auto_set=False, enter_set=True) y = Float(default_value=0., mode='text', auto_set=False, enter_set=True) actual_x = Float() actual_y = Float() def __init__(self): XYStage.__init__(self) HasTraits.__init__(self) self.x = self.actual_x = self.get_x() self.y = self.actual_y = self.get_y() self.on_trait_change(self.on_x_change, 'x') self.on_trait_change(self.on_y_change, 'y') def on_x_change(self, new): self.set_x(new) self.actual_x = self.get_x() def on_y_change(self, new): self.set_y(new) self.actual_y = self.get_y() traits_view = View(VGrid(Item('x'), Item('actual_x', style='readonly', show_label=False), Item('y'), Item('actual_y', style='readonly', show_label=False), ), )
class HeadViewController(HasTraits): """Set head views for Anterior-Left-Superior coordinate system. Parameters ---------- system : 'RAS' | 'ALS' | 'ARI' Coordinate system described as initials for directions associated with the x, y, and z axes. Relevant terms are: Anterior, Right, Left, Superior, Inferior. """ system = Enum("RAS", "ALS", "ARI", desc="Coordinate system: directions of " "the x, y, and z axis.") right = Button() front = Button() left = Button() top = Button() scale = Float(0.16) scene = Instance(MlabSceneModel) view = View( VGrid('0', 'top', '0', Item('scale', label='Scale', show_label=True), 'right', 'front', 'left', show_labels=False, columns=4)) @on_trait_change('scene.activated') def _init_view(self): self.scene.parallel_projection = True # apparently scene,activated happens several times if self.scene.renderer: self.sync_trait('scale', self.scene.camera, 'parallel_scale') # and apparently this does not happen by default: self.on_trait_change(self.scene.render, 'scale') @on_trait_change('top,left,right,front') def on_set_view(self, view, _): if self.scene is None: return system = self.system kwargs = None if system == 'ALS': if view == 'front': kwargs = dict(azimuth=0, elevation=90, roll=-90) elif view == 'left': kwargs = dict(azimuth=90, elevation=90, roll=180) elif view == 'right': kwargs = dict(azimuth=-90, elevation=90, roll=0) elif view == 'top': kwargs = dict(azimuth=0, elevation=0, roll=-90) elif system == 'RAS': if view == 'front': kwargs = dict(azimuth=90, elevation=90, roll=180) elif view == 'left': kwargs = dict(azimuth=180, elevation=90, roll=90) elif view == 'right': kwargs = dict(azimuth=0, elevation=90, roll=270) elif view == 'top': kwargs = dict(azimuth=90, elevation=0, roll=180) elif system == 'ARI': if view == 'front': kwargs = dict(azimuth=0, elevation=90, roll=90) elif view == 'left': kwargs = dict(azimuth=-90, elevation=90, roll=180) elif view == 'right': kwargs = dict(azimuth=90, elevation=90, roll=0) elif view == 'top': kwargs = dict(azimuth=0, elevation=180, roll=90) else: raise ValueError("Invalid system: %r" % system) if kwargs is None: raise ValueError("Invalid view: %r" % view) if not _testing_mode(): self.scene.mlab.view(distance=None, reset_roll=True, figure=self.scene.mayavi_scene, **kwargs)
class HeadViewController(HasTraits): """Set head views for the given coordinate system. Parameters ---------- system : 'RAS' | 'ALS' | 'ARI' Coordinate system described as initials for directions associated with the x, y, and z axes. Relevant terms are: Anterior, Right, Left, Superior, Inferior. """ system = Enum("RAS", "ALS", "ARI", desc="Coordinate system: directions of " "the x, y, and z axis.") right = Button() front = Button() left = Button() top = Button() interaction = Enum('Trackball', 'Terrain') scale = Float(0.16) scene = Instance(MlabSceneModel) view = View(VGrid('0', 'top', '0', Item('scale', label='Scale', show_label=True), 'right', 'front', 'left', 'interaction', show_labels=False, columns=4)) @on_trait_change('scene.activated') def _init_view(self): self.scene.parallel_projection = True self._trackball_interactor = None # apparently scene,activated happens several times if self.scene.renderer: self.sync_trait('scale', self.scene.camera, 'parallel_scale') # and apparently this does not happen by default: self.on_trait_change(self.scene.render, 'scale') @on_trait_change('interaction') def on_set_interaction(self, _, interaction): if self.scene is None: return if interaction == 'Terrain': # Ensure we're in the correct orientatino for the # InteractorStyleTerrain to have the correct "up" if self._trackball_interactor is None: self._trackball_interactor = \ self.scene.interactor.interactor_style self.on_set_view('front', '') self.scene.mlab.draw() self.scene.interactor.interactor_style = \ tvtk.InteractorStyleTerrain() self.on_set_view('front', '') self.scene.mlab.draw() else: # interaction == 'trackball' self.scene.interactor.interactor_style = self._trackball_interactor @on_trait_change('top,left,right,front') def on_set_view(self, view, _): if self.scene is None: return system = self.system kwargs = dict(ALS=dict(front=(0, 90, -90), left=(90, 90, 180), right=(-90, 90, 0), top=(0, 0, -90)), RAS=dict(front=(90., 90., 180), left=(180, 90, 90), right=(0., 90, 270), top=(90, 0, 180)), ARI=dict(front=(0, 90, 90), left=(-90, 90, 180), right=(90, 90, 0), top=(0, 180, 90))) if system not in kwargs: raise ValueError("Invalid system: %r" % system) if view not in kwargs[system]: raise ValueError("Invalid view: %r" % view) kwargs = dict(zip(('azimuth', 'elevation', 'roll'), kwargs[system][view])) with SilenceStdout(): self.scene.mlab.view(distance=None, reset_roll=True, figure=self.scene.mayavi_scene, **kwargs)
def trait_view(self, name=None, view_element=None): """ Use proxy views when the UI has to refresh """ # Static view if name != 'actual_view': filename = os.path.split(self.filename) settings = { 'buttons': [ Action(name='Back', action='show_file_dialog'), OKButton, CancelButton ], 'title': 'Importing Data as Context', 'width': 700, 'height': 600, 'resizable': True, 'close_result': False, 'handler': ConfigurableImportUIHandler, } return View( Item(name='_view_proxy', show_label=False, editor=InstanceEditor(view='actual_view'), style='custom'), **settings) # Dynamic view items = [] if has_geo and self.model: if isinstance(self.model, FileLogReaderUI): items = [ Tabbed( Group( Group( Item('object.model.log_reader_info', show_label=False, style='custom', height=375), ), '_', HGroup( Item('object.model.select_deselect_all', label='Select/deselect all'), '_', Item('object.model.lower_case'), ), label='Select Curves', ), Group( Item('object.model.text_view', style='custom', show_label=False), label='File View', ), ) ] else: items = [ Tabbed( Group(HGroup( Item('object.model.samples_per_trace', style='readonly', width=50), Item('object.model.trace_count', style='readonly', width=50), Item('object.model.sample_rate'), label='Header info', show_border=True, ), VGrid( HGroup( Item('object.model.inline_bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), Item('object.model.crossline_bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), ), HGroup( Item('object.model.x_location_bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), Item('object.model.y_location_bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), Item('object.model.xy_scale_bytes', label='XY Scale Bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), ), label='Byte offsets', show_border=True, ), HGroup( Item('object.model.data_type'), Item('object.model.byte_order', style='readonly'), label='Data format', show_border=True, ), label='File Format'), Group(Item('object.model.active_traceheader', style='custom', show_label=False), label='Trace Header'), ) ] # Insert file name at the begin; and save options in the end. items.insert( 0, Group(Item('filename', style='readonly', show_label=False), show_border=True, label='File')) items.append( Group( Item('save_choice', style='custom', show_label=False), show_border=True, label='Save new context as', )) return View(Group(*items))
Item('samples_per_trace', style='readonly', width=50), Item('trace_count', style='readonly', width=50), Item('sample_rate'), label='Header info', show_border=True, ), VGrid( HGroup( Item('inline_bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), Item('crossline_bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), ), HGroup( Item('x_location_bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), Item('y_location_bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), Item('xy_scale_bytes', label='XY Scale Bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), ), label='Byte offsets', show_border=True, ), HGroup( Item('data_type'), # FIXME: This is needed only when UI supports tabular view of # the header data. #Item('view_data_bytes', enabled_when = 'False'), Item('byte_order', style='readonly'),
class NewAccountView(ModelView): """ Account creation dialog example. """ #: Text explaining the dialog. explanation = Property(HTML, depends_on=['_password_suggestions', '+view_error']) #: The user's password entered a second time. password = Password #: The user's password strength. password_strength = Range(0, 4) #: Alert icon for username error. password_strength_icon = Property(Image, depends_on='password_strength') #: Alert icon for username error. username_icon = Image('@std:alert16') #: Alert icon for second password error. password_match_icon = Image('@std:alert16') # private traits --------------------------------------------------------- #: The suggestions for a stronger password. _password_suggestions = Unicode #: Whether there is anything entered for the username. _username_error = Bool(False, view_error=True) #: Whether the password is strong enough. _password_strength_error = Bool(False, view_error=True) #: Whether the two entered passwords match. _password_match_error = Bool(False, view_error=True) # ------------------------------------------------------------------------ # Handler interface # ------------------------------------------------------------------------ def init(self, info): """ Initialize the error state of the object. """ obj = info.object model = info.model # check for initial error states obj._check_username(model.username) obj._check_password_strength(model.password) obj._check_password_match(model.password) super(NewAccountView, self).init(info) def close(self, info, is_ok): """ Handles the user attempting to close the dialog. If it is via the OK dialog button, try to create an account before closing. If this fails, display an error message and veto the close by returning false. """ if is_ok: success, message = info.model.create_account() if not success: dlg = MessageDialog(message="Cannot create account", informative=message, severity='error') dlg.open() return False return True # UI change handlers ----------------------------------------------------- def model_username_changed(self, ui_info): """ Set error condition if the model's username is empty. """ if ui_info.initialized: ui_info.object._username_error = (ui_info.model.username == '') def model_password_changed(self, ui_info): """ Check the quality of the password that the user entered. """ if ui_info.initialized: obj = ui_info.object password = ui_info.model.password obj._check_password_strength(password) obj._check_password_match(password) def object_password_changed(self, ui_info): """ Check if the re-enteredpassword matches the original. """ if ui_info.initialized: obj = ui_info.object password = ui_info.model.password obj._check_password_match(password) # ------------------------------------------------------------------------ # private interface # ------------------------------------------------------------------------ def _check_username(self, username): """ Check whether the passwords match. """ self._username_error = (username == '') def _check_password_strength(self, password): """ Check the strength of the password This sets the password strength, suggestions for making a better password and an error state if the password is not strong enough. """ if password: password_check = test_strength(password) self.password_strength = password_check['score'] feedback = password_check.get('feedback', {}) if feedback.get('warnings'): warnings = '<em>{}</em> '.format(feedback['warnings']) else: warnings = '' suggestions = feedback.get('suggestions', []) self._password_suggestions = warnings + ' '.join(suggestions) else: self.password_strength = 0 self._password_suggestions = 'The password cannot be empty.' self._password_strength_error = (self.password_strength < 3) def _check_password_match(self, password): """ Check whether the passwords match. """ self._password_match_error = (not password or password != self.password) # Trait change handlers -------------------------------------------------- @on_trait_change("+view_error") def _view_error_updated(self, new_error): """ One of the error traits changed: update the error count. """ if self.info and self.info.ui: if new_error: self.info.ui.errors += 1 else: self.info.ui.errors -= 1 # Traits property handlers ----------------------------------------------- @cached_property def _get_password_strength_icon(self): """ Get the icon for password strength. """ return strength_map[self.password_strength] @cached_property def _get_explanation(self): """ Get the explanatory HTML. """ text = '' if self._username_error: text += 'The username cannot be empty. ' if self._password_match_error: text += 'The passwords must match. ' if self._password_suggestions: text += self._password_suggestions if not text: text = ("The username is valid, the password is strong and both " + "password fields match.") return explanation_template.format(css=css, text=text) # TraitsUI view ---------------------------------------------------------- view = View( VGroup( Item('explanation', show_label=False), VGrid( Item('model.username', tooltip='The username to use when logging in.', editor=TextEditor(invalid='_username_error')), Item( 'username_icon', editor=ImageEditor(), show_label=False, visible_when='_username_error', tooltip='User name must not be empty.', ), Item('model.password', tooltip='The password to use when logging in.', editor=TextEditor( invalid='_password_strength_error', password=True, )), Item( 'password_strength_icon', editor=ImageEditor(), show_label=False, ), Item('password', label='Re-enter Password:'******'Enter the password a second time.', editor=TextEditor( invalid='_password_match_error', password=True, )), Item( 'password_match_icon', editor=ImageEditor(), show_label=False, visible_when='_password_match_error', tooltip='Passwords must match.', ), columns=2, show_border=True, ), ), title='Create User Account', buttons=OKCancelButtons, width=480, height=280, )
class OpenfoamModel(HasStrictTraits): """ The model of Openfoam input parameters """ # Computational method parameters #: The input file used for OpenFoam. input_file = File(auto_set=True) #: The mode of computation used with Openfoam. mode = Enum('internal', 'io') #: The type of the mesh. mesh_type = Enum('block', 'quad') #: The directory where to put output files. output_path = Directory(os.path.abspath(os.path.curdir)) #: The duration of a step of computation. timestep = PositiveFloat(2.0e-4) #: The number of iterations in the simulation. num_iterations = PositiveInt(10) # Boundary conditions parameters #: The boundary conditions during the simulation boundary_conditions = Instance(BoundaryConditionsModel) # System parameters/ conditions #: The viscosity of the fluid. viscosity = PositiveFloat(1.0e-3) #: The density of the fluid. density = PositiveFloat(1000.0) #: The channel size. channel_size_x = PositiveFloat(1.0e-1) channel_size_y = PositiveFloat(1.0e-2) channel_size_z = PositiveFloat(2.0e-3) #: The number of elements in all channel-directions. num_grid_x = PositiveInt(400) num_grid_y = PositiveInt(40) num_grid_z = PositiveInt(1) valid = Bool(False) traits_view = View( VGroup( VGroup( Item(name='timestep', label='Timestep (s)'), Item(name='num_iterations', label='Number of iterations'), '_', Item(name='input_file'), '_', Item(name='mode'), '_', Item(name='mesh_type'), '_', Item(name='output_path'), label='Computational Method Parameters', show_border=True, ), VGroup(UItem(name='boundary_conditions', style='custom'), label='Boundary Conditions', show_border=True), VGrid( Label('Viscosity (Pa.s)'), UItem(name='viscosity'), Label('Density (kg/m^3)'), UItem(name='density'), Label('Channel size (m)'), HGroup( Item(name='channel_size_x', label='x'), Item(name='channel_size_y', label='y'), Item(name='channel_size_z', label='z'), ), Label('Number Of Elements'), HGroup( Item(name='num_grid_x', label='x'), Item(name='num_grid_y', label='y'), Item(name='num_grid_z', label='z'), ), label='System Parameters / Conditions', show_border=True, ), Spring(), )) @on_trait_change('input_file') def update_valid(self): self.valid = self.input_file != '' def _boundary_conditions_default(self): return BoundaryConditionsModel()