class BaseConsolePreferences(BasePreferencesHelper): fontsize = Enum(6, 8, 10, 11, 12, 14, 16, 18, 22, 24, 36) textcolor = Color('green') bgcolor = Color('black') preview = Str('Pychron is python + geochronology')
class ThemedSliderEditor(BasicEditorFactory): # The editor class to be created: klass = _ThemedSliderEditor # The low end of the slider range: low = Float # The high end of the slider range: high = Float # The smallest allowed increment: increment = Float # Should the current value be displayed as text? show_value = Bool(True) # The alignment of the text within the slider: alignment = Alignment('center') # The color to use for the slider bar: slider_color = Color(0xC0C0C0) # The background color for the slider: bg_color = Color('white') # The color of the slider tip: tip_color = Color(0xFF7300) # The color to use for the value text: text_color = Color('black')
class DisplayEditor(EditorFactory): """A custom LED editor for float, int, str values. It changes color when alarm trait is activated. Colors can be defined. Examples -------- >>> from traitsui.api import * >>> from traits.api import * >>> editor = DisplayEditor( alarm_name = 'alarm', color = 'green', alarm_color = 'red') >>> class Test(HasTraits): ... alarm = Bool(False) ... value = Float(101.) ... view = View('alarm',Item('value', editor = editor, width = 300, height = 50)) >>> t = Test() >>> ok = t.configure_traits() # %(skip)s """ # klass = _DisplayEditor #: trait name for alarm bool, which triggers an alarm color for display alarm_name = Str() #: normal color of the display color = Color('green') #: alarm color of the display alarm_color = Color('red')
class CustomLabel(UItem): editor = Instance(CustomLabelEditor, ()) size = Int(12) size_name = Str color = Color('black') color_name = Str bgcolor = Color('transparent') bgcolor_name = Str use_color_background = Bool(False) weight = Str('normal') # top_padding = Int(5) # bottom_padding = Int(5) # left_padding = Int(5) # right_padding = Int(5) def _size_name_changed(self): self.editor.text_size = self.size_name def _color_name_changed(self): self.editor.color = self.color_name def _bgcolor_name_changed(self): self.editor.bgcolor = self.bgcolor_name
class ExplanationPane(TraitsDockPane): id = 'pychron.experiment.explanation' name = 'Explanation' measurement = Color(MEASUREMENT_COLOR) extraction = Color(EXTRACTION_COLOR) success = Color(SUCCESS_COLOR) skip = Color(SKIP_COLOR) canceled = Color(CANCELED_COLOR) truncated = Color(TRUNCATED_COLOR) failed = Color(FAILED_COLOR) not_executable = Color(NOT_EXECUTABLE_COLOR) end_after = Color(END_AFTER_COLOR) def set_colors(self, cd): for k, v in cd.iteritems(): if hasattr(self, k): setattr(self, k, v) def traits_view(self): v = View( VGroup( HGroup(Label('Extraction'), spring, UReadonly('extraction', )), HGroup(Label('Measurement'), spring, UReadonly('measurement', )), HGroup(Label('Skip'), spring, UReadonly('skip', )), HGroup(Label('Success'), spring, UReadonly('success', )), HGroup(Label('Truncated'), spring, UReadonly('truncated', )), HGroup(Label('Canceled'), spring, UReadonly('canceled', )), HGroup(Label('Failed'), spring, UReadonly('failed', )), HGroup(Label('Not Executable'), spring, UReadonly('not_executable', )), HGroup(Label('End After'), spring, UReadonly('end_after', )))) return v
class FusionsLaserPreferences(LaserPreferences): use_video = Bool(False) video_output_mode = Enum('MPEG', 'Raw') ffmpeg_path = File video_identifier = Str use_video_server = Bool(False) video_server_port = Int(1084) video_server_quality = Range(1, 75, 75) show_grids = Bool(True) show_laser_position = Bool(True) show_desired_position = Bool(True) show_map = Bool(False) crosshairs_kind = Enum('BeamRadius', 'UserRadius', 'MaskRadius') crosshairs_color = Color('maroon') crosshairs_radius = Range(0.0, 4.0, 1.0) desired_position_color = Color('green') calibration_style = Enum('Tray', 'Free') scaling = Range(1.0, 2.0, 1) use_autocenter = Bool(False) render_with_markup = Bool(False) crosshairs_offsetx = Float(0) crosshairs_offsety = Float(0) crosshairs_offset_color = Color('blue') show_patterning = Bool(True) video_directory = Directory use_video_archiver = Bool(True) video_archive_months = Range(0, 12, 1) video_archive_hours = Range(0, 23, 0) video_archive_days = Range(0, 31, 7) # recording_zoom = Range(0, 100.0, 0.0) record_patterning = Bool(False) record_brightness = Bool(True) # record_lasing_video = Bool(False) # record_lasing_power = Bool(False) use_calibrated_power = Bool(True) show_bounds_rect = Bool(True) def _get_value(self, name, value): if 'color' in name: value = value.split('(')[1] value = value[:-1] value = map(float, value.split(',')) value = ','.join(map(lambda x: str(int(x * 255)), value)) else: value = super(LaserPreferences, self)._get_value(name, value) return value
class ArrayAdapter(TabularAdapter): bg_color = Color(0xFFFFFF) width = 75 index_text = Property() obj_names = List() def _get_index_text(self, name): return unicode(self.obj_names[self.row]) def get_format(self, object, trait, row, column): if isinstance(self.content, (_np.float64, float)): return '%.2f' return self._result_for('get_format', object, trait, row, column) def get_bg_color(self, object, trait, row, column=0): if len(object.subs) < 1 and len(object.rsubs) < 1: return None else: colcat = object.subs.keys() rowcat = object.rsubs.keys() if column > 0: ci = column - 1 else: ci = 0 cn = object.matcat.columns[ci][1:] rn = object.matcat.index[row][1:] if cn in colcat or rn in rowcat: col = QtGui.QColor(255, 71, 71) else: col = None return col
class DisplayModel(HasTraits): # messages = List # max_messages = Int(300) # message = Tuple clear_event = Event refresh = Event font_size = Int(12) bgcolor = Color('white') # message = Queue def __init__(self, *args, **kw): super(DisplayModel, self).__init__(*args, **kw) self.qmessage = Queue() def add_text(self, txt, color, force=False, **kw): ''' if txt,color same as previous txt,color than message only added if force=True ''' # ms = self.messages[-self.max_messages:] # ms.append((txt, color)) # self.message = (txt, color, force) self.qmessage.put((txt, color, force)) invoke_in_main_thread(self.trait_set, refresh=True)
class ReportAdapter(TabularAdapter): """ The tabular adapter interfaces between the tabular editor and the data being displayed. For more details, please refer to the traitsUI user guide. """ # List of (Column labels, Column ID). columns = [('Name', 'name'), ('Age', 'age'), ('Address', 'address'), ('Spouse', 'spouse')] row_label_name = 'surname' # Interfacing between the model and the view: make some of the cell # attributes a property whose behavior is then controlled by the get # (and optionally set methods). The cell is identified by its column # ID (age, spouse). # Font fails with wx in OSX; see traitsui issue #13: # font = 'Courier 10' age_alignment = Constant('right') MarriedPerson_age_image = Property MarriedPerson_bg_color = Color(0xE0E0FF) MarriedPerson_spouse_text = Property Person_spouse_text = Constant('') def _get_MarriedPerson_age_image(self): if self.item.age < 18: return '@icons:red_ball' return None def _get_MarriedPerson_spouse_text(self): return self.item.partner.name
class Indicator(QPrimitive): hline_length = 0.1 vline_length = 0.1 use_simple_render = Bool(True) spot_size = Int(8) spot_color = Color('yellow') def __init__(self, x, y, *args, **kw): super(Indicator, self).__init__(x, y, *args, **kw) w = self.hline_length self.hline = Line(Point(x - w, y, **kw), Point(x + w, y, **kw), **kw) h = self.vline_length self.vline = Line(Point(x, y - h, **kw), Point(x, y + h, **kw), **kw) def _render(self, gc, *args, **kw): with gc: if self.spot_color: sc = self._convert_color(self.spot_color) gc.set_fill_color(sc) gc.set_stroke_color(sc) x, y = self.get_xy() # if self.use_simple_render: # render a simple square at the current location # gc = args[0] l = self.spot_size hl = l / 2. x, y = x - hl, y - hl gc.rect(x, y, l, l) gc.draw_path()
class EmailPreferences(BasePreferencesHelper): server_username = Str server_password = Password server_host = Str server_port = Int preferences_path = 'pychron.email' _test_connection_button = Button _status = Str('Not Tested') _status_color = Color('orange') @on_trait_change('server+') def _server_trait_changed(self): self._status = 'Not Tested' self._status_color = 'orange' def __test_connection_button_fired(self): from pychron.social.email.emailer import Emailer em = Emailer() em.trait_set(server_host=self.server_host, server_port=self.server_port, server_username=self.server_username, server_password=self.server_password) if em.connect(warn=False): self._status = 'Connected' self._status_color = 'green' else: self._status = 'Failed' self._status_color = 'red'
class Label(QPrimitive): text = String use_border = True bgcolor = Color('white') hjustify = 'left' vjustify = 'bottom' soffset_x = Float soffset_y = Float label_offsety = Float def _text_changed(self): self.request_redraw() def _get_text(self): return self.text def _render(self, gc): ox, oy = self.get_xy() loffset = 3 x, y = ox + loffset, oy + loffset lines = self._get_text().split('\n') gc.set_stroke_color(self._convert_color(self.default_color)) offset = 0 mw = -1 sh = 0 for li in lines: w, h, _, _ = gc.get_full_text_extent(li) mw = max(mw, w + 6) sh += h with gc: if self.vjustify == 'center': gc.translate_ctm(0, -sh / 2.0) gc.translate_ctm(0, self.label_offsety) gc.set_stroke_color((0, 0, 0)) if self.use_border: gc.set_fill_color(self._convert_color(self.bgcolor)) gc.set_line_width(2) gc.rect(ox + offset + self.soffset_x, oy + offset + self.soffset_y, mw, 5 + sh) gc.draw_path() c = self.text_color if self.text_color else self.default_color gc.set_fill_color(self._convert_color(c)) gc.set_font(self.gfont) for i, li in enumerate(lines[::-1]): w, h, _, _ = gc.get_full_text_extent(li) x += self.soffset_x if self.hjustify == 'center': x -= w / 2. gc.set_text_position(x, y + self.soffset_y + i * h) gc.show_text(li) def _get_group(self): g = Item('text', style='custom') return g
class SimpleAdapter(ReadOnlyTabularAdapter): columns = [('Name', 'name'), ('Value', 'value')] font = Font('12') SectionHeading_bg_color = Color(0xE0E0E0) SectionHeading_font = Font('14 bold') SectionHeading_name_text = Property Setting_name_text = Property name_width = Float(175) def get_text(self, object, name, row, column): # Not interested in Name column if 0 == column: return super(SimpleAdapter, self).get_text(object, name, row, column) settings_list = getattr(object, 'settings_list') setting = settings_list[row] digits = getattr(setting, 'digits', None) if digits: return '%.{}f'.format(digits) % float(setting.value) return super(SimpleAdapter, self).get_text(object, name, row, column) def _get_SectionHeading_name_text(self): return self.item.name.replace('_', ' ') def _get_Setting_name_text(self): return self.item.name.replace('_', ' ')
class MyModel(HasTraits): n_meridional = Range(0, 30, 6) n_longitudinal = Range(0, 30, 11) n_tube_radius = Range(0.01, 0.04, 0.025) s_colormap = Str('Spectral') background_color = Color(0x7B7B7B) s_representation = Str('surface') # points,wireframe,surface # 场景模型实例 scene = Instance(MlabSceneModel, ()) # 管线实例 plot = Instance(PipelineBase) #当场景被激活,或者参数发生改变,更新图形 @on_trait_change( 'n_meridional,n_longitudinal,n_tube_radius,s_colormap,background_color,s_representation,scene.activated' ) def update_plot(self): x, y, z, t = curve(self.n_meridional, self.n_longitudinal) if self.plot is None: #如果plot未绘制则生成plot3d self.plot = self.scene.mlab.plot3d(x, y, z, t, tube_radius=self.n_tube_radius, colormap=self.s_colormap) else: #如果数据有变化,将数据更新即重新赋值 self.plot.mlab_source.set(x=x, y=y, z=z, scalars=t, colormap=self.s_colormap) s = mlab.gcf() #设置scens 的背景色 s.scene.background = self.background_color.getRgbF()[0:3] #设置colormap module_manager = s.children[0].children[0].children[0].children[ 0] #获得所属对象 module_manager.scalar_lut_manager.lut_mode = self.s_colormap #设置表现方式 surface = module_manager.children[0] #在module_manager获得下级所属对象 surface.actor.property.representation = self.s_representation # 建立视图布局 view = View(Item('scene', editor=SceneEditor(scene_class=MayaviScene), height=250, width=300, show_label=False), Group('_', 'n_meridional', 'n_longitudinal', 'background_color', 's_colormap', 's_representation'), resizable=True, title="hongjy1 test")
class ArrayAdapter(TabularAdapter): bg_color = Color(0xFFFFFF) vidth = 200 index_text = Property() # index_bg_color = Color(0xE0E0E0) obj_names = List() def _get_index_text(self, name): return self.obj_names[self.row]
class AddLabelsWindow(Handler): model = Any #clumsily old a reference to the model object annotation = Str label = File add_annot_button = Button('Add annotation') add_label_button = Button('Add label file') annot_borders = Bool annot_opacity = Range(0., 1., 1.) annot_hemi = Enum('both', 'lh', 'rh') label_borders = Bool label_opacity = Range(0., 1., 1.) label_color = Color('blue') remove_labels_action = Action(name='Remove all labels', action='do_remove') def _add_annot_button_fired(self): self.model.add_annotation(self.annotation, border=self.annot_borders, hemi=self.annot_hemi, opacity=self.annot_opacity) def _add_label_button_fired(self): self.model.add_label(self.label, border=self.label_borders, opacity=self.label_opacity, color=self.label_color) def do_remove(self, info): self.model.remove_labels() traits_view = View( HSplit( VGroup( Item('annotation'), Item('annot_borders', label='show border only'), Item('annot_opacity', label='opacity'), Item('annot_hemi', label='hemi'), Item('add_annot_button', show_label=False), ), VGroup( Item('label'), Item('label_borders', label='show_border_only'), Item('label_opacity', label='opacity'), Item('label_color', label='color'), Item('add_label_button', show_label=False), ), ), buttons=[remove_labels_action, OKButton], kind='livemodal', title='Dial 1-800-COLLECT and save a buck or two', )
class DataFrameWithOutputsAdapter(DataFrameAdapter): """ Custom adapter to colorize the column outputs of a dataframe. """ #: Color to use as background for the output columns/rows output_color = Color("lightgrey") #: Name of attribute of the object we are editing. # We can't pass the DF itself because it might get reallocated during the # life of the edited object df_attr_name = Str #: Number of columns/rows that contain outputs to be colorized num_outputs = Int
class LSArrayAdapter (TabularAdapter): columns = Property def _get_columns(self): # print 'GETTING COLUMNS', self.object.columns, self.object, self.object.__class__ columns = self.object.columns return [ (name, idx) for idx, name in enumerate(columns) ] font = 'Courier 10' alignment = 'right' format = '%5.4f' # '%g' even_bg_color = Color(0xE0E0FF) width = Float(80)
class ConnectionMixin(HasTraits): test_connection_button = Button # _test_connection_button = Button _connected_label = String('Not Tested') _connected_color = Color('orange') _adapter_klass = 'pychron.database.core.database_adapter.DatabaseAdapter' _names = List _test_func = None def _reset_connection_label(self, d): def func(): self._connected_label = 'Not Tested' self._connected_color = 'orange' if d: do_later(func) else: func() def _get_connection_dict(self): raise NotImplementedError def _get_adapter(self): args = self._adapter_klass.split('.') mod, klass = '.'.join(args[:-1]), args[-1] mod = __import__(mod, fromlist=[klass]) return getattr(mod, klass) def _test_connection(self, kw): klass = self._get_adapter() db = klass(**kw) self._connected_label = '' if self._test_func: db.test_func = self._test_func return db.connect(warn=False) def _test_connection_button_fired(self): kw = self._get_connection_dict() self._connected_label = 'Not Connected' self._connected_color = 'red' if kw is not None: c = self._test_connection(kw) if c: self._connected_color = 'green' self._connected_label = 'Connected' else: warning(None, 'Please select a connection to test')
class Label(QPrimitive): text = String use_border = True bgcolor = Color('white') ox = Float oy = Float hjustify = 'left' def _text_changed(self): self.request_redraw() def _get_text(self): return self.text def _render_(self, gc): ox, oy = self.get_xy() loffset = 3 x, y = ox + loffset, oy + loffset lines = self._get_text().split('\n') gc.set_stroke_color((0, 0, 0)) if self.use_border: gc.set_fill_color(self._convert_color(self.bgcolor)) gc.set_line_width(2) offset = 5 mw = -1 sh = 10 for li in lines: w, h, _, _ = gc.get_full_text_extent(li) mw = max(mw, w + 2 * offset + loffset) sh += h gc.rect(ox - offset + self.ox, oy - offset + self.oy, mw, sh + loffset) gc.draw_path() gc.set_fill_color((0, 0, 0)) gc.set_font(self.gfont) for i, li in enumerate(lines[::-1]): w, h, _, _ = gc.get_full_text_extent(li) x += self.ox if self.hjustify == 'center': x -= w / 2. gc.set_text_position(x, y + self.oy + i * h) gc.show_text(li) def _get_group(self): g = Item('text', style='custom') return g
class Object(HasPrivateTraits): """Represent a 3d object in a mayavi scene.""" points = Array(float, shape=(None, 3)) trans = Array() name = Str scene = Instance(MlabSceneModel, ()) src = Instance(VTKDataSource) color = Color() rgbcolor = Property(depends_on='color') point_scale = Float(10, label='Point Scale') opacity = Range(low=0., high=1., value=1.) visible = Bool(True) @cached_property def _get_rgbcolor(self): if hasattr(self.color, 'Get'): # wx color = tuple(v / 255. for v in self.color.Get()) else: color = self.color.getRgbF()[:3] return color @on_trait_change('trans,points') def _update_points(self): """Update the location of the plotted points""" if not hasattr(self.src, 'data'): return trans = self.trans if np.any(trans): if trans.ndim == 0 or trans.shape == (3, ) or trans.shape == (1, 3): pts = self.points * trans elif trans.shape == (3, 3): pts = np.dot(self.points, trans.T) elif trans.shape == (4, 4): pts = apply_trans(trans, self.points) else: err = ("trans must be a scalar, a length 3 sequence, or an " "array of shape (1,3), (3, 3) or (4, 4). " "Got %s" % str(trans)) error(None, err, "Display Error") raise ValueError(err) else: pts = self.points self.src.data.points = pts return True
class SimpleChangeAdapter(ReadOnlyTabularAdapter): columns = [('Name', 'name'), ('Current Value', 'value'), ('Recommended Value', 'rec_value')] font = Font('12') SectionHeading_bg_color = Color(0xE0E0E0) SectionHeading_font = Font('14 bold') SectionHeading_name_text = Property Setting_name_text = Property name_width = Float(175) def _get_SectionHeading_name_text(self): return self.item.name.replace('_', ' ') def _get_Setting_name_text(self): return self.item.name.replace('_', ' ')
class ScrubberEditor(BasicEditorFactory): # The editor class to be instantiated: klass = Property # The low end of the scrubber range: low = Float # The high end of the scrubber range: high = Float # The normal increment (default: auto-calculate): increment = Float # The alignment of the text within the scrubber: alignment = Alignment('center') # The background color for the scrubber: color = Color(None) # The hover mode background color for the scrubber: hover_color = Color(None) # The active mode background color for the scrubber: active_color = Color(None) # The scrubber border color: border_color = Color(None) # The color to use for the value text: text_color = Color('black') def _get_klass(self): """ Returns the toolkit-specific editor class to be instantiated. """ return toolkit_object('scrubber_editor:_ScrubberEditor')
class ConnectionPane(TraitsDockPane): name = 'Connection' id = 'pychron.sys_mon.connection' conn_spec = Instance(ConnectionSpec) connection_status = Str connection_color = Color('red') def traits_view(self): v = View(VGroup(UItem('conn_spec', style='custom'), UItem('_'), CustomLabel('connection_status', color_name='connection_color'))) return v
class Demo(HasTraits): a = Str('asdfsdf') foo = Button color = Color('blue') bgcolor = Color('green') cnt = 0 size = Int(12) def _foo_fired(self): self.a = 'fffff {}'.format(random.random()) if self.cnt % 2 == 0: self.color = 'red' self.bgcolor = 'blue' else: self.bgcolor = 'red' self.color = 'blue' self.cnt += 1 def traits_view(self): v = View( UItem('size'), 'foo', CustomLabel( 'a', # color='blue', size=24, size_name='size', top_padding=10, left_padding=10, color_name='color', bgcolor_name='bgcolor'), resizable=True, width=400, height=100) return v
class SimpleAdapter(TabularAdapter): columns = [('Name', 'name'), ('Value', 'value')] font = Font('12') can_edit = Bool(False) SectionHeading_bg_color = Color(0xE0E0E0) SectionHeading_font = Font('14 bold') SectionHeading_name_text = Property Setting_name_text = Property name_width = Float(175) def _get_SectionHeading_name_text(self): return self.item.name.replace('_', ' ') def _get_Setting_name_text(self): return self.item.name.replace('_', ' ')
class ConnectionMixin(HasTraits): test_connection_button = Button # _test_connection_button = Button _connected_label = String('Not Tested') _connected_color = Color('orange') _adapter_klass = 'pychron.database.core.database_adapter.DatabaseAdapter' _names = List # def __init__(self, *args, **kw): # super(ConnectionMixin, self).__init__(*args, **kw) # # self.names = show_databases() # def _reset_connection_label(self, d): def func(): self._connected_label = 'Not Tested' self._connected_color = 'orange' if d: do_later(func) else: func() def _get_connection_dict(self): raise NotImplementedError def _get_adapter(self): args = self._adapter_klass.split('.') mod, klass = '.'.join(args[:-1]), args[-1] mod = __import__(mod, fromlist=[klass]) return getattr(mod, klass) def _test_connection_button_fired(self): kw = self._get_connection_dict() klass = self._get_adapter() db = klass(**kw) self._connected_label = '' c = db.connect(warn=False) if c: self._connected_color = 'green' self._connected_label = 'Connected' else: self._connected_label = 'Not Connected' self._connected_color = 'red'
class DatasetUI(HasTraits): name = Str('') color = Color(allow_none=True) active = Bool(True) highlighted = Bool(False) marker_size = Float(1.0) line_width = Float(1.0) dataset = Instance(object) traits_view = View( Item('name'), Item('color'), Item('active'), Item('highlighted'), Item('marker_size'), Item('line_width'), )
class ReportAdapter(TabularAdapter): columns = [('Name', 'name'), ('Age', 'age'), ('Address', 'address'), ('Spouse', 'spouse')] font = 'Courier 10' age_alignment = Constant('right') MarriedPerson_age_image = Property MarriedPerson_bg_color = Color(0xE0E0FF) MarriedPerson_spouse_text = Property Person_spouse_text = Constant('') def _get_MarriedPerson_age_image(self): if self.item.age < 18: return 'red_flag' return None def _get_MarriedPerson_spouse_text(self): return self.item.partner.name
class ConnectionPane(TraitsDockPane): name = 'Connection' id = 'pychron.sys_mon.connection' conn_spec = Instance(ConnectionSpec, ()) connection_status = Str connection_color = Color('red') def traits_view(self): v = View(VGroup(VGroup(Item('object.conn_spec.host'), Item('object.conn_spec.port'), Item('object.conn_spec.system_name', label='Name'), label='Parameters'), UItem('_'), CustomLabel('connection_status', color_name='connection_color'))) return v