def __init__ ( self, parent = None, **traits ):
        super( MFnChacoEditorToolbar, self ).__init__( **traits )
        factory = self.editor.factory

        actions = [ self.save_data, self.save_fig ]
        toolbar = ToolBar( image_size      = ( 16, 16 ),
                           show_tool_names = False,
                           show_divider    = False,
                           *actions )
        self.control = toolbar.create_tool_bar( parent, self )
        self.control.SetBackgroundColour( parent.GetBackgroundColour() )

        # fixme: Why do we have to explictly set the size of the toolbar?
        #        Is there some method that needs to be called to do the
        #        layout?
        self.control.SetSize( wx.Size( 23 * len( actions ), 16 ) )
Exemplo n.º 2
0
 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()
     )
Exemplo n.º 3
0
    def __init__(self, avl=None, **traits):
        """Initializes the object.
        """
        super(AVLTreeBrowser, self).__init__(**traits)
        self.ui = None
        self.view = None
        if avl:
            self.avl = avl

        menu = Menu(Action(name='Refresh', action='editor.update_editor'),
                    Action(name='Expand all', action='editor.expand_all'))
        self.menu = menu

        self._root_object_changed(self.root_object)

        nodes = self.tree_generator.get_nodes(menu)

        self.tree_editor = TreeEditor(nodes=nodes,
                                      orientation='vertical',
                                      hide_root=True,
                                      on_dclick=self._on_dclick,
                                      selected='selected')
        self.view = View(Group(Item(name='_root',
                                    editor=self.tree_editor,
                                    resizable=True),
                               show_labels=False,
                               show_border=False,
                               orientation='vertical'),
                         title='pyAVL',
                         help=False,
                         resizable=True,
                         undo=False,
                         revert=False,
                         width=.3,
                         height=.3,
                         handler=self.avlhandler,
                         toolbar=ToolBar(*self.avlhandler.toolbar_actions))
Exemplo n.º 4
0
 def _toolbar_default(self):
     toolbar = ToolBar(*self.actions)
     toolbar.image_size = (16, 16)
     toolbar.show_tool_names = False
     toolbar.show_divider = False
     return toolbar
Exemplo n.º 5
0
help_menu = Menu(
    "|",  #help_action, "_",
    about_action,
    name="&Help")

menubar = MenuBar(file_menu, edit_menu, view_menu, graph_menu, help_menu)

#------------------------------------------------------------------------------
#  Godot "ToolBar" instance:
#------------------------------------------------------------------------------

toolbar = ToolBar(
    "|",  #close_action, "_",
    new_action,
    open_action,
    save_action,
    save_as_action,
    "_",
    undo_action,
    redo_action,
    "_",
    node_action,
    edge_action,
    configure_graph_action,
    configure_nodes_action,
    configure_edges_action,
    show_tool_names=False,  #show_divider=False
)

# EOF -------------------------------------------------------------------------
Exemplo n.º 6
0
class tcWindow(HasTraits):
    project = tcProject
    plot = tcPlot

    def __init__(self, project):
        self.project = project
        self.plot = create_timechart_container(project)
        self.plot_range_tools = self.plot.range_tools
        self.plot_range_tools.on_trait_change(self._selection_time_changed,
                                              "time")
        self.trait_view().title = self.get_title()

    def get_title(self):
        if self.project.filename == "dummy":
            return "PyTimechart: Please Open a File"
        return "PyTimechart:" + self.project.filename

    # Create an action that exits the application.
    status = Str("Welcome to PyTimechart")
    traits_view = View(
        HSplit(
            VSplit(
                Item('project',
                     show_label=False,
                     editor=InstanceEditor(view='process_view'),
                     style='custom',
                     width=150),
                #                Item('plot_range_tools', show_label = False, editor=InstanceEditor(view = 'selection_view'), style='custom',width=150,height=100)
            ),
            Item('plot', show_label=False, editor=ComponentEditor()),
        ),
        toolbar=ToolBar(*_create_toolbar_actions(),
                        image_size=(24, 24),
                        show_tool_names=False),
        menubar=MenuBar(*_create_menubar_actions()),
        statusbar=[
            StatusItem(name='status'),
        ],
        resizable=True,
        width=1280,
        height=1024,
        handler=tcActionHandler())

    def _on_open_trace_file(self):
        if open_file(None) and self.project.filename == "dummy":
            self._ui.dispose()

    def _on_view_properties(self):
        self.plot.options.edit_traits()

    def _on_exit(self, n=None):
        self.close()
        sys.exit(0)

    def close(self, n=None):
        pass

    def _on_about(self):
        aboutBox().edit_traits()

    def _on_doc(self):
        browse_doc()

    def _selection_time_changed(self):
        self.status = "selection time:%s" % (self.plot_range_tools.time)
Exemplo n.º 7
0
class ControlTab(HasTraits):
    """ This object is the core of the traitsUI interface. Its view is
        the right panel of the application, and it hosts the method for
        interaction between the objects and the GUI.
    """
    move_step = Enum(1,0.2,0.5,1,2,5,10)
    scale_step = Enum(10,1,5,10,20,50,100)
    channels = List()
    ch_editor = CheckListEditor(values=[],cols=2)
    num_channels = Int(0)
    patient_name = Str()
    select_all = Button("all")
    select_none = Button("none")
    select_good = Button("good (db)")
    mlcount = Int(0)
    mrcount = Int(0)
    mucount = Int(0)
    mdcount = Int(0)
    #_sls = [0,1100,5] #StartLengthStride
    #acquisition_thread = Instance(AcquisitionThread)
    
    move_left = Action(name = "Left",
                        action = "_trigger_move_left",
                        toolip = "Move to the left",
                        image = ImageResource("images/left_32.png")
                        )
    move_right = Action(name = "Right",
                        action = "_trigger_move_right",
                        toolip = "Move to the right",
                        image = ImageResource("images/right_32.png")
                        )
    scale_up = Action(name = "Scale up",
                        action = "_trigger_scale_up",
                        toolip = "Move to the right",
                        image = ImageResource("images/up_32.png")
                        )
    scale_down = Action(name = "Scale down",
                        action = "_trigger_scale_down",
                        toolip = "Move to the right",
                        image = ImageResource("images/down_32.png")
                        )
                        
    toolbar = ToolBar(move_left, move_right,scale_up,scale_down)
    
    
    traits_view = View(VGroup(
                  #Item('do_plot', show_label=False ),
                    VGroup(
                      Item('move_step',label="Move by:"),
                      Item('scale_step',label="Scale by"),
                    ),
                    VGroup(
                      Group(
                          Item('channels',
                               show_label=False,
                               style='custom',
                               editor=ch_editor,
                               #springy=True,
                               #height=-500,
                          ),
                          scrollable=True,
                          springy=True,
                      ),
                      HGroup(
                        spring,
                        Item('select_all',show_label=False),
                        Item('select_none',show_label=False),
                        Item('select_good',show_label=False),
                        spring,
                      ),
                      label = "Choose channels",
                      #height=300,
                    ),
                  #Item('results_string',show_label=False, 
                  #                      springy=True, style='custom' ),
                  #springy=True,
                  #scrollable=True,
                  #height=-500,
                  dock='tab',
                  springy=True
                  #scrollable=True
                  ),
               toolbar=toolbar,
               scrollable=True
               #height=-500,
               )
               #key_bindings=key_bindings,
               #handler=ControlHandler,
               
    def _trigger_move_left(self):
        #print "Trigger Left"
        self.mlcount+=1
    def _trigger_move_right(self):
        self.mrcount+=1
        #print "Trigger Right"
    def _trigger_scale_up(self):
        self.mucount+=1
    def _trigger_scale_down(self):
        self.mdcount+=1

    def _select_none_fired(self):
        self.channels = []
 
    def _select_all_fired(self):
        self.channels = range(self.num_channels)

    def _select_good_fired(self):
        try:
            gc = schlaf_ged.get_good_channels(self.patient_name)
            print "Got", gc, "from database"
            self.channels = gc
        except ValueError, ve:
            #Zeige Fehlermeldung
            print ve
            print self.patient_name
            try:
                short_patient_name = self.patient_name.split("_")[0]
                gc = schlaf_ged.get_good_channels(short_patient_name)
                print "Got", gc, "from database"
                self.channels = gc
            except ValueError,ve:
                print ve
                print short_patient_name
                message = Message(message="Cannot find good channels for subject %s" % self.patient_name)
                message.edit_traits()
Exemplo n.º 8
0
 def _toolbar_default(self):
     toolbar = ToolBar(*self.actions)
     toolbar.image_size = (16, 16)
     toolbar.show_tool_names = False
     toolbar.show_divider = False
     return toolbar
Exemplo n.º 9
0
class RunCase(HasTraits):
    patterns = {'name':re.compile(r"""Operation of run case (?P<case_num>\d+)/(?P<num_cases>\d+):\s*(?P<case_name>.+?)\ *?\n"""),
                'constraint':re.compile(r"""(?P<cmd>[A-Z0-9]+)\s+(?P<pattern>.+?)\s+->\s+(?P<constraint>\S+)\s+=\s+(?P<val>[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)"""),
                'constraint_variable':re.compile(r"""(?P<sel>->)?\s*(?P<cmd>[A-Z0-9]+)\s+(?P<pattern>.+?)\s+=\s+(?P<val>[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)"""),
                'parameter':re.compile(r"""(?P<cmd>[A-Z]+)\s+(?P<pattern>.+?)\s+=\s+(?P<val>[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)(\ +(?P<unit>\S+))?"""),
                'var':re.compile(r"""(?P<name>\S+?)\s*?=\s*?(?P<value>[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)"""),
                'float':re.compile(r'(?P<value>[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)'),
                'mode' :re.compile(r"""mode (\d+?):\s*?(?P<real>[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)\s+(?P<imag>[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)"""),
                'modeveccomp': re.compile(r"""(?P<name>[a-z]+?)(\s*?):\s*(?P<real>[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)\s+(?P<imag>[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)""")
                }
    number = Int
    name = String
    runoutput = Instance(RunOutput, RunOutput())# Dict(String, Float, {})
    #not to be used separately apart from modal gui
    #trim_runcase = Instance(TrimCase, TrimCase())
    set_trim_case_action = Action(name='Set Trim Condition', action='set_trimcase', \
                tooltip='Set the runcase conditions for horizontal(+banked) or looping trim condition')
    parameter_view = Property(List(Parameter), depends_on='parameters[]')
    constraint_view = Property(List(Constraint), depends_on='constraints[]')
    @cached_property
    def _get_parameter_view(self):
        return sorted(self.parameters.values(), key=lambda x:x.name.upper())
    @cached_property
    def _get_constraint_view(self):
        return sorted(self.constraints.values(), key=lambda x:x.name.upper())
    
    traits_view = View(Group(Item('number', style='readonly'),
                             Item('name')),
                       Group(Item('parameter_view', editor=Parameter.editor, show_label=False), label='Parameters'),
                       Group(Item('constraint_view', editor=Constraint.editor, show_label=False), label='Constraints'),
                        Item(), # so that groups are not tabbed
                        toolbar=ToolBar(set_trim_case_action)
                       )
    
    # name, value
    parameters = Dict(String, Instance(Parameter), {})
    # pattern:name ; Predefined parameters to have good names
    parameter_names = Dict(String, String, {})
    
    
    
    # constraints are corresponding to to the params in constraint_names
    # constrained : constraint_name, value
    constraints = Dict(String, Instance(Constraint), {})
    
    # pattern:name
    constraint_names = Dict(String, String, {'lpha':'alpha', 'eta':'beta',
                            'oll  rate':'roll rate', 'itch rate':'pitch rate',
                            'aw   rate':'yaw rate'})
    
    constraint_variables = Dict(String, Instance(ConstraintVariable), {})
    
    constraint_variable_names = Dict(String, String, {'CL': 'lift coeff',
                                             'CY': 'side force coeff',
                                             'Cl roll mom': 'roll coeff',
                                             'Cm pitchmom': 'pitch coeff',
                                             'Cn yaw  mom': 'yaw coeff',
                                             'alpha': 'alpha',
                                             'beta': 'beta',
                                             'pb/2V': 'roll rate',
                                             'qc/2V': 'pitch rate',
                                             'rb/2V': 'yaw rate'})
    
    trimcase = Instance(TrimCase, TrimCase())
    
    def set_trimcase(self, info=None):
        #print self
        self.trimcase = TrimCase(runcase=self)
        self.trimcase.update_parameters_from_avl()
        self.trimcase.edit_traits()
        self.get_parameters_info_from_avl(self.avl)
    
    @on_trait_change('trimcase.parameter_view.value,trimcase.type')
    def on_trimcase_changed(self, object, name, old, new):
        #print object, name, old, new
        print 'trimcase_changed'
        if name == 'value':
            self.update_trim_case(self.trimcase, object)
            self.trimcase.update_parameters_from_avl()
        elif name == 'type':
            self.trimcase.update_parameters_from_avl()
    
    # send changed value of trimcase to avl, parameter is Parameter instance
    def update_trim_case(self, trimcase, parameter):
        #print 'update_trim_case'
        self.get_parameters_info_from_avl(self.avl)
        self.avl.sendline('oper')
        self.avl.sendline(trimcase.type_)
        self.avl.expect(AVL.patterns['/oper/m'])
        #print self.parameters.keys()
        #for p, v in trimcase.parameters.iteritems():
        self.avl.sendline('%s %f' % (parameter.cmd, parameter.value))
        AVL.goto_state(self.avl)
    
    @on_trait_change('constraints.value,constraints.constraint_name')
    def update_constraints(self):
        print 'constraints changed'
        #self.avl.sendline('oper')
        #self.avl.sendline()
        #self.avl.expect(AVL.patterns['/'])
        for name, constraint in self.constraints.iteritems():
            ccmd = constraint.cmd
            vcmd = self.constraint_variables[constraint.constraint_name].cmd
            val = constraint.value
            self.avl.sendline('oper')
            self.avl.expect(AVL.patterns['/oper'])
            self.avl.sendline('%s %s %f' % (ccmd, vcmd, val))
            self.avl.expect(AVL.patterns['/oper'])
        AVL.goto_state(self.avl)
    
    @on_trait_change('parameters.value')
    def update_parameters(self):
        print 'parameters changed'
        self.avl.sendline('oper')
        self.avl.sendline('m')
        self.avl.expect(AVL.patterns['/oper/m'])
        #print self.parameters.keys()
        try:
            tmpv = self.parameters['velocity'].value
            if tmpv < 0.00001:
                tmpv = 1.0
        except KeyError:
            tmpv = 1.0
        self.avl.sendline('V %f' % tmpv)
        for p, v in self.parameters.iteritems():
            cmd = self.parameters[p].cmd
            if cmd != 'V':
                self.avl.sendline('%s %f' % (cmd, v.value))
        AVL.goto_state(self.avl)
    
    #returns pattern:cmd
    @classmethod
    def get_constraint_variables_from_avl(cls, avl, case_num=1):
        avl.sendline('oper')
        avl.expect(AVL.patterns['/oper'])
        avl.sendline(str(case_num))
        avl.expect(AVL.patterns['/oper'])
        avl.sendline('a')
        avl.expect(AVL.patterns['/oper/a'])
        if avl.match.groups('case_num') != str(case_num):
            #raise Exception('could not get case information for case num %d' % case_num)
            pass
        lines = avl.before.splitlines()
        lines = [line.strip() for line in lines]
        i1 = lines.index('- - - - - - - - - - - - - - - - -')
        i2 = lines.index('', i1 + 1)
        constraint_lines = lines[i1 + 1:i2]
        groups = [re.search(RunCase.patterns['constraint_variable'], line).groupdict() for line in constraint_lines]
        params = {}
        for group in groups:
            params[group['pattern']] = group['cmd']
        avl.sendline()
        AVL.goto_state(avl)
        return params
    
    # return pattern:cmd,con_pattern,value
    @classmethod
    def get_constraints_from_avl(cls, avl, case_num=1):
        avl.sendline('oper')
        avl.expect(AVL.patterns['/oper'])
        avl.sendline(str(case_num))
        avl.expect(AVL.patterns['/oper'])
        if avl.match.groups('case_num') != str(case_num):
            #raise Exception('could not get case information for case num %d' % case_num)
            pass
        lines = avl.before.splitlines()
        lines = [line.strip() for line in lines]
        i1 = lines.index('------------      ------------------------')
        i2 = lines.index('------------      ------------------------', i1 + 1)
        constraint_lines = lines[i1 + 1:i2]
        groups = [re.match(RunCase.patterns['constraint'], line).groupdict() for line in constraint_lines]
        params = {}
        for group in groups:
            params[group['pattern']] = (group['cmd'], group['constraint'], group['val'])
        AVL.goto_state(avl)
        return params
    
    @classmethod
    def get_case_from_avl(cls, avl, case_num=1):
        # TODO: parse constraints and parameters from avl
        avl.sendline('oper')
        avl.expect(AVL.patterns['/oper'])
        avl.sendline(str(case_num))
        avl.expect(AVL.patterns['/oper'])
        match = re.search((RunCase.patterns['name']), avl.before)
        name = match.group('case_name').strip()
        AVL.goto_state(avl)
        runcase = RunCase(name=name, number=case_num)
        runcase.avl = avl
        
        constraint_vars = RunCase.get_constraint_variables_from_avl(avl, case_num)
        for constraint_var in constraint_vars:
            if constraint_var not in runcase.constraint_variable_names:
                runcase.constraint_variable_names[constraint_var] = constraint_var
            constraint_name = runcase.constraint_variable_names[constraint_var]
            runcase.constraint_variables[constraint_name] = ConstraintVariable(
                                name=constraint_name, pattern=constraint_var,
                                cmd=constraint_vars[constraint_var])
        
        constraints = RunCase.get_constraints_from_avl(avl, case_num)
        rc_constraints = {}
        for constraint_pattern, constraint_info in constraints.iteritems():
            if constraint_pattern not in runcase.constraint_names:
                runcase.constraint_names[constraint_pattern] = constraint_pattern
            constraint_name = runcase.constraint_names[constraint_pattern]
            rc_constraints[constraint_name] = Constraint(name=constraint_name,
                                pattern=constraint_pattern, cmd=constraint_info[0],
                                constraint_name=runcase.constraint_variable_names[constraint_info[1]],
                                value=float(constraint_info[2]), runcase=runcase)
        runcase.constraints.update(rc_constraints)
        RunCase.get_parameters_info_from_avl(runcase, avl)
        AVL.goto_state(avl)
        return runcase
        
    def get_parameters_info_from_avl(self, avl):
        avl.sendline('oper')
        avl.expect(AVL.patterns['/oper'])
        avl.sendline('m')
        avl.expect(AVL.patterns['/oper/m'])
        avl.sendline()
        lines = avl.before.splitlines()
        lines = [line.strip() for line in lines if len(line.strip()) > 0]
        l2 = [line.startswith('Parameters') for line in lines]
        i1 = l2.index(True)
        i2 = - 1
        constraint_lines = lines[i1 + 1:i2]
        groups = [re.search(RunCase.patterns['parameter'], line).groupdict() for line in constraint_lines]
        params = {}
        AVL.goto_state(avl)
        #params.update(self.parameters)
        for group in groups:
            pattern = group['pattern']
            name = self.parameter_names.get(pattern, pattern)
            unit = group.get('unit', '')
            unit = unit if unit is not None else ''
            params[name] = Parameter(name=name, pattern=pattern, cmd=group['cmd'], unit=unit, value=float(group['val']))
        #self.parameters[name] = float(group['val'])
        AVL.goto_state(avl)
        self.parameters.update(params)
        #self.parameters = params
        
    def get_run_output(self):
        self.avl.sendline('oper')
        self.avl.expect(AVL.patterns['/oper'])
        self.avl.sendline('x')
        self.avl.expect(AVL.patterns['/oper'])
        ret = {}
        #print self.avl.before
        i1 = re.search(r"""Run case:\s*?.*?\n""", self.avl.before).end()
        i2 = re.search(r"""---------------------------------------------------------------""", self.avl.before[i1:]).start()
        text = self.avl.before[i1:i1 + i2]
        AVL.goto_state(self.avl)
        for match in re.finditer(RunCase.patterns['var'], text):
            ret[match.group('name')] = float(match.group('value'))
        #self.output = ret
        AVL.goto_state(self.avl)
        return ret
    
    def get_modes(self):
        self.avl.sendline('mode')
        self.avl.expect(AVL.patterns['/mode'])
        self.avl.sendline('n')
        self.avl.expect(AVL.patterns['/mode'])
        if re.search(r'Eigenmodes not computed for run case', self.avl.before):
            print 'Error : \n', self.avl.before
            AVL.goto_state(avl)
            return
        ret = {}
        i1 = re.search(r"""Run case\s*?\d+?:.*?\n""", self.avl.before).end()
        i2 = re.search(r"""Run-case parameters for eigenmode analyses""", self.avl.before[i1:]).start()
        text = self.avl.before[i1 : i1 + i2]
        modes = []
        for mode_eval in re.finditer(RunCase.patterns['mode'], text):
            eigenvalue = float(mode_eval.group('real')) + 1j * float(mode_eval.group('imag'))
            mode = EigenMode(eigenvalue=eigenvalue)
            i = 0
            for match in re.finditer(RunCase.patterns['modeveccomp'], text[mode_eval.end():]):
                i += 1
                mode.eigenvector[mode.order.index(match.group('name'))] = float(mode_eval.group('real')) + 1j * float(mode_eval.group('imag'))
                if i > 11:
                    break
            modes.append(mode)
        AVL.goto_state(self.avl)
        return modes
    
    def get_system_matrix(self):
        self.avl.sendline('mode')
        self.avl.expect(AVL.patterns['/mode'])
        self.avl.sendline('n')
        self.avl.expect(AVL.patterns['/mode'])
        self.avl.sendline('s')
        self.avl.expect(AVL.patterns['/mode/s'])
        lines = [line for line in self.avl.before.splitlines()[3: - 1] if len(line) > 0]
        lines = [line.replace('**********', '      nan ') for line in lines]
        #print lines
        # fortran format to deceode
        # FORMAT(1X,12F10.4,3X,12G12.4)
        # 1 space, 12 floats of fixed width 10, 3 spaces 12 exponents of fixed width 12
        order = lines[0].replace('|', ' ').split()
        mat = numpy.empty((12, len(order)))
        for i, line in enumerate(lines[1:]):
            l1 = line[1:121]
            for j in xrange(12):
                mat[i, j] = float(l1[j * 10:(j + 1) * 10])
            l2 = line[124:]
            for j in xrange(len(l2) / 12):
                mat[i, 12 + j] = float(l2[j * 12:(j + 1) * 12])
        ret = EigenMatrix(order=order, matrix=mat)
        AVL.goto_state(self.avl)
        return ret
Exemplo n.º 10
0
class MarkerTab(HasTraits):
    """ Object used to display the results.
    """

    record_mark = Bool(False)
    name_new = Str("Mark")
    markers = List(Marker)
    update_marks = Int(0)
    active_row = Int(0)

    remove_f2 = Button("Remove")
    load_evt = Action(name="Load",
                      action="_load",
                      toolip="Load markers from EventTable",
                      image=ImageResource("images/load_32.png"))
    save_evt = Action(name="EventTable",
                      action="_save_to",
                      toolip="Save markers as EventTable",
                      image=ImageResource("images/save_32.png"))
    save_ascii = Action(name="ASCII",
                        action="_save_to_ascii",
                        toolip="Save markers as ASCII-file",
                        image=ImageResource("images/save_32.png"))
    toolbar = ToolBar(load_evt, save_evt, save_ascii)

    def __init__(self):
        HasTraits.__init__(self)
        #self.markers.append(Marker(t=10,name="Test10"))
        #self.markers.append(Marker(t=100,name="Test100"))

    #x = Float(50, label="X", desc="X position of the center")
    #y = Float(50, label="Y", desc="Y position of the center")

    def cmp_markers(self, x, y):
        return x.t - y.t

    def append(self, t, name=None, notify=True, do_sort=True):
        if name == None:
            name = str(self.name_new)
        self.markers.append(Marker(t=t, name=name))
        if do_sort:
            self.markers.sort(cmp=self.cmp_markers)
        if notify:
            self.update_marks += 1
        #self.goto_marker = self.markers[-1]

    def get_marks(self, start, stop):
        rv = []
        for m in self.markers:
            if m.t >= start and m.t <= stop:
                rv.append(m)
        return rv

    def _load(self):
        print "Load from EventTable"
        extension = "evt"
        wildcard = "EventTable|*.evt|VA MarkerFile|*.vmrk"
        fileDialog = FileDialog(action='open',
                                title='Load EventTable',
                                wildcard=wildcard)
        fileDialog.open()
        if fileDialog.path == '' or fileDialog.return_code == CANCEL:
            return False
        else:
            print "Opening", fileDialog.path
            #et = eegpy.load(str(fileDialog.path))
            et = eegpy.EventTable(str(fileDialog.path))
            for k in et.keys():
                for t in et[k]:
                    #print k,t
                    self.append(t, k, False, False)
            self.markers.sort(cmp=self.cmp_markers)

    def _save_to(self):
        print "Save to EventTable"
        extension = "evt"
        wildcard = "*.evt"
        fileDialog = FileDialog(action='save as',
                                title='Save As',
                                wildcard=wildcard)
        fileDialog.open()
        if fileDialog.path == '' or fileDialog.return_code == CANCEL:
            return False
        else:
            extLen = len(extension)
            if extLen and fileDialog.path[-extLen - 1:] != '.' + extension:
                fileDialog.path += '.' + extension
        #print "fc.fn:", fileDialog.path
        #TODO: Check if file exists and join EventTables
        et = EventTable()
        for m in self.markers:
            try:
                et.add_trigger(m.name, m.t)
            except ValueError, e:
                et.add_trigger_type(m.name, [m.t])
        try:
            et.save(fileDialog.path)
        except Exception, e:
            mb = Message(
                message="Error while writing EventTable to file.\n%s" % str(e))