class CodeEditorDemo(HasTraits): """ Defines the CodeEditor demo class. """ run = ToolbarButton() def _run_fired(self): import imagect.api.util as iu iu.console.execute(self.code_sample) toolbar = Group(Item("run", show_label=False)) # Define a trait to view: code_sample = Code("""%matplotlib import imagect.api.util as iu from matplotlib import pyplot as plt import numpy as np X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) plt.plot(X, C) plt.plot(X, S) plt.show() """) # Display specification: code_group = Group( Item('code_sample', style='custom', label='Custom', show_label=False), ) # Demo view: view = View(VGroup(toolbar, code_group), title='CodeEditor', buttons=['OK'])
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='apptools.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()
class PythonBrowser(HasPrivateTraits): dir = Directory() files = List(FileInfo) file_info = Instance(FileInfo) code = Code() view = View(HSplit(Item('dir', style='custom'), VSplit(Item('files', editor=tabular_editor), Item('code', style='readonly'), show_labels=False), show_labels=False), resizable=True, width=0.75, height=0.75) #-- Event Handlers ------------------------------------------------------- def _dir_changed(self, dir): self.files = [ FileInfo(file_name=join(dir, name)) for name in listdir(dir) if ((splitext(name)[1] == '.py') and isfile(join(dir, name))) ] def _file_info_changed(self, file_info): fh = None try: fh = open(file_info.file_name, 'rb') self.code = fh.read() except: pass if fh is not None: fh.close()
class TestHTML(HasPrivateTraits): # ------------------------------------------------------------------------- # Trait definitions: # ------------------------------------------------------------------------- # Text string to display as HTML: html = Code(sample) # ------------------------------------------------------------------------- # Traits view definitions: # ------------------------------------------------------------------------- view = View( Group( [Item('html#@', editor=HTMLEditor(format_text=True)), '|<>'], ['{Enter formatted text and/or HTML below:}@', 'html#@', '|<>'], '|<>', layout='split', ), title='HTML Editor Test', resizable=True, width=0.4, height=0.6, )
class ScriptedComponent(Component): """ An Enable component that draws its mainlayer from a script """ #: kiva drawing code for mainlayer draw_script = Code(default_script) #: any errors which occur error = Str #: how long did the last draw take last_draw_time = Float(0.0) fps_display = Property(Str, observe="last_draw_time") #: compiled code _draw_code = Any def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): """ Try running the compiled code with the graphics context as `gc` """ with gc: try: self.error = "" start_time = time.time() exec(self._draw_code, {}, {"gc": gc}) self.last_draw_time = time.time() - start_time except Exception as exc: self.error = str(exc) def _compile_script(self): """ Try compiling the script to bytecode """ try: self.error = "" return compile(self.draw_script, "<script>", "exec") except SyntaxError as exc: self.error = str(exc) return None def _draw_script_changed(self): code = self._compile_script() if code is not None: self._draw_code = code self.request_redraw() def __draw_code_default(self): code = self._compile_script() if code is None: code = compile("", "<script>", "exec") return code def _get_fps_display(self): if self.last_draw_time == 0.0: return "" draw_time_ms = self.last_draw_time * 1000.0 draw_fps = 1000.0 / draw_time_ms return "{:.2f}ms ({:.2f} fps)".format(draw_time_ms, draw_fps)
class CodeView(HasTraits): """Defines a sub-view whose size we wish to explicitly control.""" n = Int(123) code = Code() view = View( # This HGroup keeps 'n' from over-widening, by implicitly placing # a spring to the right of the item. HGroup(Item('n')), UItem('code'), resizable=True, )
class HPCWriterModel(BaseNotificationListenerModel): #: Header to include in all HPC submission scripts header = Code(desc="Header to include in all HPC submission scripts") #: Prefix to include at beginning of all HPC submission files prefix = Unicode( "hpc_sub_script", desc="Prefix to include at beginning of all HPC submission files") #: Whether or not to perform a dry run - i.e, generate but do not #: write bash files dry_run = Bool(True)
class DemoError(HasPrivateTraits): # ------------------------------------------------------------------------- # Trait definitions: # ------------------------------------------------------------------------- #: The error message text: msg = Code() # ------------------------------------------------------------------------- # Traits view definitions: # ------------------------------------------------------------------------- traits_view = View( VGroup( Heading("Error in source file"), Item("msg", style="custom", show_label=False), ))
class CodeEditorDemo(HasTraits): """ This class specifies the details of the CodeEditor demo. """ # To demonstrate any given Trait editor, an appropriate Trait is required. code_sample = Code('import sys\n\nsys.print("hello world!")') # Display specification code_group = Group(Item('code_sample', style='simple', label='Simple'), Item('_'), Item('code_sample', style='custom', label='Custom'), Item('_'), Item('code_sample', style='text', label='Text'), Item('_'), Item('code_sample', style='readonly', label='ReadOnly')) # Demo view view1 = View(code_group, title='CodeEditor', width=350, buttons=['OK'])
class oriEditor(HasTraits): file_Path = File ori_Code = Code() ori_Save = Button(label='Save') buttons_group = Group(Item(name = 'file_Path', style = 'simple',show_label = False, width = 0.3 ),\ Item(name = 'ori_Save', show_label = False), orientation = 'horizontal') traits_view = View(Group(Item(name = 'ori_Code',show_label = False, height =300, width = 650),\ buttons_group)) def _ori_Save_fired(self, filename, code): f = open(self.file_Path, 'w') f.write(self.ori_Code) f.close() def __init__(self, file_path): self.file_Path = file_path self.ori_Code = get_code(file_path)
class CodeEditorDemo(HasTraits): """ Defines the CodeEditor demo class. """ # Define a trait to view: code_sample = Code('import sys\n\nsys.print("hello world!")') # Display specification: code_group = Group(Item('code_sample', style='simple', label='Simple'), Item('_'), Item('code_sample', style='custom', label='Custom'), Item('_'), Item('code_sample', style='text', label='Text'), Item('_'), Item('code_sample', style='readonly', label='ReadOnly')) # Demo view: view = View(code_group, title='CodeEditor', buttons=['OK'])
class TestCode(HasPrivateTraits): code = Code() status = Str() view = View( [Item('code', style='custom', resizable=True, editor=CodeEditor(key_bindings=key_bindings)), 'status~', '|<>'], id='traitsui.tests.test_code_editor.TestCode', title='Sample Code Editor', width=0.4, height=0.4, resizable=True, handler=CodeHandler())
class KBCodeExample(HasPrivateTraits): code = Code() status = Str() kb = Button(label='Edit Key Bindings') view = View(Group( Item('code', style='custom', resizable=True), Item('status', style='readonly'), 'kb', orientation='vertical', show_labels=False, ), id='KBCodeExample', key_bindings=key_bindings, title='Code Editor With Key Bindings', resizable=True, handler=CodeHandler()) def _kb_fired(self, event): key_bindings.edit_traits()
class ExpressionContextDemo(HasTraits): code = Code() execute = Button() plots = Instance(PlotComponent) value_expression = Str('') index_expression = Str('') view_expression = Button() data_context = Instance(DataContext) expression_context = Instance(ExpressionContext) traits_view = View('code', 'execute', Item('plots', editor=ComponentEditor()), 'value_expression', 'index_expression', Item('view_expression', show_label=False), resizable=True) def __init__(self): self.data_context = DataContext() self.expression_context = ExpressionContext(self.data_context) self.plots = VPlotContainer() return def _view_expression_fired(self): context_adapter = PlotDataContextAdapter( context=self.expression_context) plot = Plot(context_adapter) plot.plot((self.index_expression, self.value_expression)) self.plots.add(plot) self.plots.request_redraw() return def _execute_fired(self): exec(self.code, {}, self.data_context) return
class FunctionPlotter(HasTraits): figure = Instance(Figure, ()) #❶ code = Code() #❷ points = List(Instance(Point), []) #❸ draw_button = Button("Plot") view = View( VSplit( Item("figure", editor=MPLFigureEditor(toolbar=True), show_label=False), #❶ HSplit( VGroup( Item("code", style="custom"), #❷ HGroup(Item("draw_button", show_label=False), ), show_labels=False), Item("points", editor=point_table_editor, show_label=False) #❸ )), width=800, height=600, title="Function Plotter", resizable=True) ###2### ###3### def __init__(self, **kw): super(FunctionPlotter, self).__init__(**kw) self.figure.canvas_events = [ #❶ ("button_press_event", self.memory_location), ("button_release_event", self.update_location) ] self.button_press_status = None #保存鼠标按键按下时的状态 self.lines = [] #保存所有曲线 self.functions = [] #保存所有的曲线函数 self.env = {} #代码的执行环境 self.axe = self.figure.add_subplot(1, 1, 1) self.axe.callbacks.connect('xlim_changed', self.update_data) #❷ self.axe.set_xlim(0, 1) self.axe.set_ylim(0, 1) self.points_line, = self.axe.plot([], [], "kx", ms=8, zorder=1000) #数据点 ###3### ###6### def update_data(self, axe): xmin, xmax = axe.get_xlim() x = np.linspace(xmin, xmax, 500) for line, func in zip(self.lines, self.functions): y = func(x) line.set_data(x, y) self.update_figure() ###6### ###4### def memory_location(self, evt): if evt.button in (1, 3): self.button_press_status = time.clock(), evt.x, evt.y else: self.button_press_status = None def update_location(self, evt): if evt.button in (1, 3) and self.button_press_status is not None: last_clock, last_x, last_y = self.button_press_status if time.clock() - last_clock > 0.5: #❶ return if ((evt.x - last_x)**2 + (evt.y - last_y)**2)**0.5 > 4: #❷ return if evt.button == 1: if evt.xdata is not None and evt.ydata is not None: point = Point(x=evt.xdata, y=evt.ydata) #❸ self.points.append(point) elif evt.button == 3: if self.points: self.points.pop() #❹ ###4### ###5### @on_trait_change("points[]") def _points_changed(self, obj, name, new): for point in new: point.on_trait_change(self.update_points, name="x, y") #❶ self.update_points() def update_points(self): #❷ arr = np.array([(point.x, point.y) for point in self.points]) if arr.shape[0] > 0: self.points_line.set_data(arr[:, 0], arr[:, 1]) else: self.points_line.set_data([], []) self.update_figure() def update_figure(self): #❸ if self.figure.canvas is not None: #❹ self.figure.canvas.draw_idle() ###5### ###7### def _draw_button_fired(self): self.plot_lines() def plot_lines(self): xmin, xmax = self.axe.get_xlim() #❶ x = np.linspace(xmin, xmax, 500) self.env = { "points": np.array([(point.x, point.y) for point in self.points]) } #❷ exec self.code in self.env results = [] for line in self.lines: line.remove() self.axe.set_color_cycle(None) #重置颜色循环 self.functions = [] self.lines = [] for name, value in self.env.items(): #❸ if name.startswith("_"): #忽略以_开头的名字 continue if callable(value): try: y = value(x) if y.shape != x.shape: #输出数组应该与输入数组的形状一致 raise ValueError( "the return shape is not the same as x") except Exception as ex: import traceback print "failed when call function {}\n".format(name) traceback.print_exc() continue results.append((name, y)) self.functions.append(value) for (name, y), function in zip(results, self.functions): #如果函数有plot_parameters属性,则用其作为plot()的参数 kw = getattr(function, "plot_parameters", {}) #❹ label = kw.get("label", name) line, = self.axe.plot(x, y, label=label, **kw) self.lines.append(line) points = self.env.get("points", None) #❺ if points is not None: self.points = [ Point(x=x, y=y) for x, y in np.asarray(points).tolist() ] self.axe.legend() self.update_figure()
class DemoFileBase(DemoTreeNodeObject): #: Parent of this file: parent = Any() #: Name of file system path to this file: path = Property(depends_on='parent.path,name') #: Name of the file: name = Str() #: UI form of the 'name': nice_name = Property() #: Files don't allow children: allows_children = Bool(False) #: Description of what the demo does: description = HTML() #: The base URL for links: base_url = Property(depends_on='path') #: The css file for this node. css_filename = Str("default.css") #: Log of all print messages displayed: log = Code() _nice_name = Str() def init(self): self.log = "" # ------------------------------------------------------------------------- # Implementation of the 'path' property: # ------------------------------------------------------------------------- def _get_path(self): return join(self.parent.path, self.name) def _get_base_url(self): if isdir(self.path): base_dir = self.path else: base_dir = dirname(self.path) return base_dir # ------------------------------------------------------------------------- # Implementation of the 'nice_name' property: # ------------------------------------------------------------------------- def _get_nice_name(self): if not self._nice_name: name, ext = splitext(self.name) self._nice_name = user_name_for(name) return self._nice_name def _set_nice_name(self, value): old = self.nice_name self._nice_name = value self.trait_property_changed("nice_name", old, value) # ------------------------------------------------------------------------- # Returns whether or not the object has children: # ------------------------------------------------------------------------- def has_children(self): """ Returns whether or not the object has children. """ return False def get_children(self): """ Gets the demo file's children. """ return []
class DemoFile(DemoFileBase): #: Source code for the demo: source = Code() #: Demo object whose traits UI is to be displayed: demo = Instance(HasTraits) #: Local namespace for executed code: locals = Dict(Str, Any) def init(self): super(DemoFile, self).init() description, source = parse_source(self.path) self.description = publish_html_str(description, self.css_filename) self.source = source self.run_code() def run_code(self): """ Runs the code associated with this demo file. """ try: # Get the execution context dictionary: locals = self.parent.init_dic locals["__name__"] = "___main___" locals["__file__"] = self.path sys.modules["__main__"].__file__ = self.path exec(self.source, locals, locals) demo = self._get_object("modal_popup", locals) if demo is not None: demo = ModalDemoButton(demo=demo) else: demo = self._get_object("popup", locals) if demo is not None: demo = DemoButton(demo=demo) else: demo = self._get_object("demo", locals) except Exception: traceback.print_exc() else: self.demo = demo self.locals = locals # ------------------------------------------------------------------------- # Get a specified object from the execution dictionary: # ------------------------------------------------------------------------- def _get_object(self, name, dic): object = dic.get(name) or dic.get(name.capitalize()) if object is not None: if isinstance(type(object), type): try: object = object() except Exception: pass if isinstance(object, HasTraits): return object return None
class CodeEditingTest(HasTraits): block_code_editor = Instance(wx.Control, allow_none=False) code = Code("""from blockcanvas.debug.my_operator import add, mul from numpy import arange x = arange(0,10,.1) c1 = mul(a,a) x1 = mul(x,x) t1 = mul(c1,x1) t2 = mul(b, x) t3 = add(t1,t2) y = add(t3,c) """) text_index = Int(0) random_seed = Int(0) random_generator = Instance(Random) permute_lines = Bool(True) random_backspace = Bool(True) clear_first = Bool(False) num_runs = Int(1) finish_callback = Any traits_view = View( Item('code'), Item('random_seed'), Item('num_runs'), Item('random_backspace'), Item('num_runs'), Item('permute_lines'), Item('clear_first'), buttons=['OK'], resizable=True, ) def interactive_test(self): self.configure_test() self.run_test() return def run_test(self): self.random_generator = Random() self.random_generator.seed(self.random_seed) if self.permute_lines: codelines = self.code.split('\n') shuffle(codelines) self.code = '\n'.join(codelines) # Should have a more realistic markov process here if self.clear_first: self.clear_editor() timerid = wx.NewId() self.timer = wx.Timer(self.block_code_editor, timerid) self.block_code_editor.Bind(wx.EVT_TIMER, self.test_step, id=timerid) self.text_index = 0 self.test_step(None) def test_step(self, event): if self.text_index < len(self.code): if random() > 0.8 or not self.random_backspace: self.text_index -= 1 self.block_code_editor.CmdKeyExecute(STC_CMD_DELETEBACK) else: self.block_code_editor.AddText(self.code[self.text_index]) self.text_index += 1 self.timer.Start(50.0, wx.TIMER_ONE_SHOT) else: if self.finish_callback is not None: self.finish_callback() def configure_test(self): self.edit_traits(kind='modal') return def __init__(self, **kwtraits): super(CodeEditingTest, self).__init__(**kwtraits) from blockcanvas.block_display.code_block_ui import editor_control self.block_code_editor = editor_control() self.random_seed = int(random() * 1000000) return def insert_text(self, text, at_once=False): """Insert text into the code editor. This can be done character by charager, or all at once if at_once is True""" if at_once: self.block_code_editor.AddText(text) else: for char in text: self.block_code_editor.AddText(char) return def clear_editor(self): """Removes all of the text all at once from the editor. this is equivalent for almost all purposes to the user selecting all and hitting backspace""" self.block_code_editor.ClearAll() def goto_line(self, linenum): self.block_code_editor.GotoLine(linenum) return def enter_basic_code(self): self.insert_text(self.basic_code)