def default_traits_view(self): view = View( HSplit( VSplit( Item("object_class", editor=self.tree_editor, show_label=False, visible_when="object.show_tree"), Group( Item("search", label="搜索"), Item("search_result_str", show_label=False, editor=ListStrEditor(editable=False, selected_index="search_result_index")), label="Search"), ), Item("current_document", style="custom", show_label=False, editor=CodeEditor(lexer="null", search="top", line = "current_line", mark_lines="mark_lines", mark_color=0xff7777)), id = "tvtkdoc.hsplit" ), width = 700, height = 500, resizable = True, title = "TVTK文档浏览器", id = "tvtkdoc", handler = TVTKDocumentHandler(), ) return view
def _create_traits_ui_view(self): """ Create the traits UI view used by the editor. fixme: We create the view dynamically to allow the key bindings to be created dynamically (we don't use this just yet, but obviously plugins need to be able to contribute new bindings). """ view = View( Group(Item('text', editor=CodeEditor(key_bindings=self.key_bindings)), Item('runbut', label='Run script...', show_label=False), show_labels=False), id='enthought.envisage.editor.text_editor', handler=TextEditorHandler(), kind='live', resizable=True, width=1.0, height=1.0, #buttons = NoButtons, buttons=['OK'], ) return view
class TextView(HasTraits): text = Str save = Button() def __init__(self, text, title): self.text = text self.trait_view().title = title traits_view = View( Item('text', style="readonly", show_label=False, editor=CodeEditor()), HGroup(Item('save'), show_labels=False), resizable=True, width=1024, height=600, ) def _save_changed(self): from window import save_dialog fn = save_dialog() if fn: try: f = open(fn, "w") f.write(self.text) f.close() except: print "unable to write file..."
class RecorderWithUI(Recorder): """ This class represents a Recorder but with a simple user interface. """ # The code to display code = Code(editor=CodeEditor(line='current_line')) # Button to save script to file. save_script = Button('Save Script') # The current line to show, used by the editor. current_line = Int # The root object which is being recorded. root = Any ######################################## # Traits View. view = View(Group( HGroup( Item('recording', show_label=True), spring, Item('save_script', show_label=False), ), Group(Item('code', show_label=False)), ), width=600, height=360, id='enthought.scripting.recorder_with_ui', buttons=['Cancel'], resizable=True, handler=CloseHandler()) ###################################################################### # RecorderWithUI interface. ###################################################################### def on_ui_close(self): """Called from the CloseHandler when the UI is closed. This method basically stops the recording. """ from util import stop_recording from package_globals import get_recorder if get_recorder() is self: stop_recording(self.root, save=False) else: self.recording = False self.unregister(self.root) ###################################################################### # Non-public interface. ###################################################################### @on_trait_change('lines[]') def _update_code(self): self.code = self.get_code() self.current_line = len(self.lines) + 1 def _save_script_fired(self): self.ui_save()
def _createView(self): """Set up a view for the traits.""" # Figure out the ticks and ticklabels for the TAM. We want to put a tick on every # coincidence. The dimensions of the TAM image we're showing are N*numCoincidences # wide and tall. dim = self.subTAM.shape[0] tickWidth = dim / self._numCoincidences ticks = numpy.arange(tickWidth / 2, dim, tickWidth, dtype='float') tickLabels = [str(x) for x in range(self._numCoincidences)] self._plotEditor = PlotEditor(colorbar=True, xTicks=ticks, xTickLabels=tickLabels, yTicks=ticks, yTickLabels=tickLabels) self.traits_view = View(HGroup( Group( Group(Item( 'topology', show_label=False, label="Topology", ), Item('normalized', show_label=True), Item('magnifyActivity', show_label=True), Item('threshold', show_label=True), orientation='horizontal', show_left=False), Group( Item( 'subTAM', style='custom', show_label=False, editor=PlotEditor(colorbar=True, xTicks=ticks, xTickLabels=tickLabels, yTicks=ticks, yTickLabels=tickLabels), width=-self.plotSize[0], height=-self.plotSize[0] + self.toolbarSize, ), Item( 'output', style='readonly', show_label=False, editor=CodeEditor(), ), ), ), ), title='LocalTAM')
class TestCode(HasPrivateTraits): code = Code status = Str view = View([ Item('code', style='custom', resizable=True, editor=CodeEditor(key_bindings=key_bindings)), 'status~', '|<>' ], id='enthought.traits.ui.tests.test_code_editor.TestCode', title='Sample Code Editor', width=0.4, height=0.4, resizable=True, buttons=NoButtons, handler=CodeHandler())
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 ConsoleLogger(HasTraits): ## Title of logger object title = "Output" ## Contents of the actual logging window data = Str ## Whether this logger is currently active is_active = false ## Class variable containing which logger is currently active; cannot ## have more than one active logger simultaneously. NOTE: we assume ## that this variable is only accessed within the UI thread. active_logger = None ## Default view traits_view = View( Item( 'data~', editor=CodeEditor(foldable=False, search='top', auto_scroll=False, mark_color=0xFFFFFF), #editor=TextEditor(multi_line=True), show_label=False), handler=LoggerHandler()) ## Unwrapped (non-autoflush) python stdout and stderr orig_stdout = None orig_stderr = None def _data_changed(self): editor = self.traits()['data'].get_editor() def activate_stdouterr_redirect(self, streams_to_watch={}): """Redirect standard output and error to be sent to the log pane instead of the console. """ ## If we already have an active logger, raise if ConsoleLogger.active_logger is not None: raise RuntimeError, "Trying to activate redirection for a ConsoleLogger " +\ "while it is already active for a different one" ConsoleLogger.active_logger = self ## If redirection is already active, don't insist global _raw_stdout, _raw_stderr if _raw_stdout is not None or _raw_stderr is not None: return ## Ensure that any pending writes are expelled before redirection ## (Python only) sys.stdout.flush() sys.stderr.flush() ## Redirect standard output and standard error to display to the ## log pane area. Keep around old stdout/stderr in order to ## display debugging messages. They are called, respectively, ## raw_stdout and raw_stderr (Python file objects); make them ## global for ease of debugging. if _raw_stdout is None: old_stdout_fd = os.dup(sys.stdout.fileno()) _raw_stdout = os.fdopen(old_stdout_fd, 'w') if _raw_stderr is None: old_stderr_fd = os.dup(sys.stderr.fileno()) _raw_stderr = os.fdopen(old_stderr_fd, 'w') # print >>sys.stderr, "Original stderr" # print >>_raw_stderr, "Redirected stderr" # sys.stderr.flush() # _raw_stderr.flush() (self.stdout_read, self.stdout_write) = os.pipe() (self.stderr_read, self.stderr_write) = os.pipe() os.dup2(self.stdout_write, sys.stdout.fileno()) os.dup2(self.stderr_write, sys.stderr.fileno()) out_flags = fcntl.fcntl(self.stdout_read, fcntl.F_GETFL) err_flags = fcntl.fcntl(self.stderr_read, fcntl.F_GETFL) fcntl.fcntl(self.stdout_read, fcntl.F_SETFL, out_flags | os.O_NONBLOCK) fcntl.fcntl(self.stderr_read, fcntl.F_SETFL, err_flags | os.O_NONBLOCK) streams_to_watch.update({ self.stdout_read: 'stdout', self.stderr_read: 'stderr' }) ## We're going to create a thread whose purpose is to indefinitely ## wait (using 'select') on the stdout/stderr file descriptors. ## When text arrives read it and update the log window. class _ListenerThread(threading.Thread): def run(inner_self): listen_fds = streams_to_watch.keys() eof = False while not eof and self.is_active: # Note: traits are thread-safe ready = select(listen_fds, [], []) for fd in listen_fds: if fd in ready[0]: chunk = os.read(fd, 65536) if chunk == '': eof = True self.data += chunk if eof: break select([], [], [], .1) # Give a little time for buffers to fill listener = _ListenerThread() listener.setDaemon( True) # Allow quitting Python even if thread running self.is_active = True listener.start() ## Ensure that all Python-level prints are auto-flushing class AutoFlush(object): def __init__(self, stream): self.stream = stream def write(self, text): self.stream.write(text) self.stream.flush() def writelines(self, lines): self.stream.writelines(lines) self.stream.flush() def flush(self): self.stream.flush() self.orig_stdout = sys.stdout self.orig_stderr = sys.stderr sys.stdout = AutoFlush(sys.stdout) sys.stderr = AutoFlush(sys.stderr) def desactivate_stdout_err_redirect(self): """Bring back redirected file descriptors to their original state and relinquish control as the active logger. """ global _raw_stdout, _raw_stderr if ConsoleLogger.active_logger == self: ## Wait a little bit to ensure that the last data printed to ## stdout/stderr has had time to be processed by the logging ## thread sys.stdout.flush() sys.stderr.flush() time.sleep(0.1) if _raw_stdout is not None and self.orig_stdout is not None: os.dup2(_raw_stdout.fileno(), self.orig_stdout.fileno()) sys.stdout = self.orig_stdout _raw_stdout = None self.orig_stdout = None if _raw_stderr is not None and self.orig_stderr is not None: os.dup2(_raw_stderr.fileno(), self.orig_stderr.fileno()) sys.stderr = self.orig_stderr _raw_stderr = None self.orig_stderr = None ConsoleLogger.active_logger = None self.is_active = False
class LiveSearch ( HasTraits ): # The currenty root directory being searched: root = Directory( getcwd(), entries = 10 ) # Should sub directories be included in the search: recursive = Bool( True ) # The file types to include in the search: file_type = Enum( 'Python', 'C', 'C++', 'Java', 'Ruby' ) # The current search string: search = Str # Is the search case sensitive? case_sensitive = Bool( False ) # The live search table filter: filter = Property # Instance( TableFilter ) # The current list of source files being searched: source_files = Property # List( SourceFile ) # The currently selected source file: selected = Any # Instance( SourceFile ) # The contents of the currently selected source file: selected_contents = Property # List( Str ) # The currently selected match: selected_match = Int # The text line corresponding to the selected match: selected_line = Property # Int # The full name of the currently selected source file: selected_full_name = Property # File # The list of marked lines for the currently selected file: mark_lines = Property # List( Int ) # Summary of current number of files and matches: summary = Property # Str #-- Traits UI Views -------------------------------------------------------- view = View( VGroup( HGroup( Item( 'root', id = 'root', label = 'Path', width = 0.5 ), Item( 'recursive' ), Item( 'file_type', label = 'Type' ), Item( 'search', id = 'search', width = 0.5, editor = HistoryEditor( auto_set = True ) ), Item( 'case_sensitive' ) ), VSplit( VGroup( Item( 'summary', editor = TitleEditor() ), Item( 'source_files', id = 'source_files', editor = table_editor ), dock = 'horizontal', show_labels = False ), VGroup( HGroup( Item( 'selected_full_name', editor = TitleEditor(), springy = True ), Item( 'selected_full_name', editor = DNDEditor(), tooltip = 'Drag this file' ), show_labels = False ), Item( 'selected_contents', style = 'readonly', editor = CodeEditor( mark_lines = 'mark_lines', line = 'selected_line', selected_line = 'selected_line' ) ), dock = 'horizontal', show_labels = False ), id = 'splitter' ) ), title = 'Live File Search', id = 'enthought.examples.demo.Advanced.' 'Table_editor_with_live_search_and_cell_editor.LiveSearch', width = 0.75, height = 0.67, resizable = True ) #-- Property Implementations ----------------------------------------------- @property_depends_on( 'search, case_sensitive' ) def _get_filter ( self ): if len( self.search ) == 0: return lambda x: True return lambda x: len( x.matches ) > 0 @property_depends_on( 'root, recursive, file_type' ) def _get_source_files ( self ): root = self.root if root == '': root = getcwd() file_types = FileTypes[ self.file_type ] if self.recursive: result = [] for dir_path, dir_names, file_names in walk( root ): for file_name in file_names: if splitext( file_name )[1] in file_types: result.append( SourceFile( live_search = self, full_name = join( dir_path, file_name ) ) ) return result return [ SourceFile( live_search = self, full_name = join( root, file_name ) ) for file_name in listdir( root ) if splitext( file_name )[1] in file_types ] @property_depends_on( 'selected' ) def _get_selected_contents ( self ): if self.selected is None: return '' return ''.join( self.selected.contents ) @property_depends_on( 'selected' ) def _get_mark_lines ( self ): if self.selected is None: return [] return [ int( match.split( ':', 1 )[0] ) for match in self.selected.matches ] @property_depends_on( 'selected, selected_match' ) def _get_selected_line ( self ): selected = self.selected if (selected is None) or (len( selected.matches ) == 0): return 1 return int( selected.matches[ self.selected_match - 1 ].split( ':', 1 )[0] ) @property_depends_on( 'selected' ) def _get_selected_full_name ( self ): if self.selected is None: return '' return self.selected.full_name @property_depends_on( 'source_files, search, case_sensitive' ) def _get_summary ( self ): source_files = self.source_files search = self.search if search == '': return 'A total of %d files.' % len( source_files ) files = 0 matches = 0 for source_file in source_files: n = len( source_file.matches ) if n > 0: files += 1 matches += n return 'A total of %d files with %d files containing %d matches.' % ( len( source_files ), files, matches ) #-- Traits Event Handlers -------------------------------------------------- def _selected_changed ( self ): self.selected_match = 1 def _source_files_changed ( self ): if len( self.source_files ) > 0: self.selected = self.source_files[0] else: self.selected = None
def get_drag_value ( self, object ): return object.full_name table_editor = TableEditor( columns = [ MatchesColumn1( name = 'matches', label = '#', editable = False, width = 0.05, horizontal_alignment = 'center' ), MatchesColumn2( name = 'matches', width = 0.35, format_func = lambda x: (x + [ '' ])[0].strip(), editor = CodeEditor( line = 'object.live_search.selected_match', selected_line = 'object.live_search.selected_match' ), style = 'readonly', edit_width = 0.95, edit_height = 0.33 ), FileColumn( name = 'base_name', label = 'Name', width = 0.30, editable = False ), ObjectColumn( name = 'ext_path', label = 'Path', width = 0.30, editable = False ), ], filter_name = 'filter', auto_size = False,
class LoggerView(TraitsUIView): """ The Workbench View showing the list of log items. """ id = Str('enthought.logger.plugin.view.logger_view.LoggerView') name = Str('Logger') service = Instance(LoggerService) log_records = List(Instance(logging.LogRecord)) formatted_records = Property(Str, depends_on='log_records') activated = Instance(logging.LogRecord) activated_text = Property(Str, depends_on='activated') reset_button = Button("Reset Logs") show_button = Button("Complete Text Log") copy_button = Button("Copy Log to Clipboard") code_editor = CodeEditor(lexer='null', show_line_numbers=False) log_records_editor = TabularEditor(adapter=LogRecordAdapter(), editable=False, activated='activated') trait_view = View( Group(Item('log_records', editor=log_records_editor), Group(Item('reset_button'), spring, Item('show_button'), Item('copy_button'), orientation='horizontal', show_labels=False), show_labels=False)) ########################################################################### # LogQueueHandler view interface ########################################################################### def update(self, force=False): """ Update 'log_records' if our handler has new records or 'force' is set. """ service = self.service if service.handler.has_new_records() or force: self.log_records = [ rec for rec in service.handler.get() if rec.levelno >= service.preferences.level_ ] ########################################################################### # Private interface ########################################################################### @on_trait_change('service.preferences.level_') def _update_log_records(self): self.service.handler._view = self self.update(force=True) def _reset_button_fired(self): self.service.handler.reset() self.log_records = [] def _show_button_fired(self): self.edit_traits(view=View(Item('formatted_records', editor=self.code_editor, style='readonly', show_label=False), width=800, height=600, resizable=True, buttons=['OK'], title='Complete Text Log')) def _copy_button_fired(self): clipboard.text_data = self.formatted_records @cached_property def _get_formatted_records(self): return '\n'.join([ self.service.handler.formatter.format(record) for record in self.log_records ]) def _activated_changed(self): if self.activated is None: return msg = self.activated.getMessage() if self.service.preferences.enable_agent: dialog = QualityAgentView(msg=msg, service=self.service) dialog.open() else: self.edit_traits(view=View(Item('activated_text', editor=self.code_editor, style='readonly', show_label=False), width=800, height=600, resizable=True, buttons=['OK'], title='Log Message Detail')) @cached_property def _get_activated_text(self): if self.activated is None: return '' else: return self.activated.getMessage()