Beispiel #1
0
class DialogSpineSetting(wx.Dialog):
    def __init__(self, parent, id, title='',
                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
                 value_in=None,  choices=['normal', 'strange']):
        wx.Dialog.__init__(self, parent, id, title, style=style)

        s1 = {"style": wx.CB_READONLY,
              "choices": choices}
        s2 = {"style": wx.CB_READONLY,
              "choices": ['outward', 'axes', 'data']}
        s3 = {"style": wx.TE_PROCESS_ENTER,
              "choices": ["0.0", "1.0"]}

        vbox = wx.BoxSizer(wx.VERTICAL)
        self.l0 = [["label",  s1["choices"][0], 4, s1, ], ]
        self.elp0 = EditListPanel(self, self.l0)
        self.nb = wx.Notebook(self)
        self.l2 = [
            ["loc. ref",  s2["choices"][0], 104, s2, ],
            ["loc. value",  s3["choices"][0],  4, s3, ],
            ["face", 'k', 206, {}],
            ["edge",   'k', 206, {}],
            ["width",    1.0, 107, {}],
            ["style",   'solid', 10, {}],
            ["alpha",   1.0, 105, {}], ]
        i = 0
        self.elp1 = EditListPanel(self.nb, self.l2)
        self.nb.AddPage(self.elp1, 'spine1')
        self.elp2 = EditListPanel(self.nb, self.l2)
        self.nb.AddPage(self.elp2, 'spine2')

        vbox.Add(self.elp0, 0, wx.EXPAND | wx.ALL, 1)
        vbox.Add(self.nb, 1, wx.EXPAND | wx.ALL, 10)
        sizer = self.CreateButtonSizer(wx.OK | wx.CANCEL)
        if sizer is not None:
            vbox.Add(sizer, 0, wx.EXPAND | wx.ALIGN_CENTER | wx.ALL, 10)
        self.SetSizer(vbox)
        if 'label' in value_in:
            self.elp0.SetValue([value_in['label']])
            self.elp1.SetValue(dict2elp(self.l2, value_in['spine1']))
            self.elp2.SetValue(dict2elp(self.l2, value_in['spine2']))
        self.Layout()
        wx.CallAfter(self._myRefresh)

        self.Bind(EDITLIST_CHANGED, self.onELP_Changed)
        self.Bind(EDITLIST_CHANGED, self.onELP_Changed)

    def GetValue(self):
        ret = elp2dic(self.l0, self.elp0.GetValue())
        ret['spine1'] = elp2dic(self.l2, self.elp1.GetValue())
        ret['spine2'] = elp2dic(self.l2, self.elp2.GetValue())
        return ret

    def onELP_Changed(self, evt):
        value = evt.elp.GetValue()
        if evt.widget_idx == 6:  # alpha
            if value[6] is None:
                return
            v2 = [x for x in value[2]]
            v2[-1] = value[6]
            v3 = [x for x in value[3]]
            v3[-1] = value[6]
            value[2] = v2
            value[3] = v3
            evt.elp.SetValue(value)

        elif evt.widget_idx == 2:  # face
            if not any(value[2]):
                value[6] = None
            evt.elp.SetValue(value)
        elif evt.widget_idx == 3:  # edge
            if not any(value[3]):
                value[6] = None
            evt.elp.SetValue(value)
        pass

    def _myRefresh(self):
        win = self.GetTopLevelParent()
#        win.SetSizeHints(win)
        win.Fit()
        win.Layout()
class dlg_jobsubmission(wx.Dialog):
    def __init__(self,
                 parent,
                 id=wx.ID_ANY,
                 title='',
                 value=None,
                 queues=None):

        if queues is None:
            queues = def_queues

        wx.Dialog.__init__(self,
                           parent,
                           wx.ID_ANY,
                           title,
                           style=wx.STAY_ON_TOP | wx.DEFAULT_DIALOG_STYLE)

        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)

        self.SetSizer(vbox)
        vbox.Add(hbox2, 1, wx.EXPAND | wx.ALL, 1)

        q_names = [x['name'] for x in queues['queues']]
        dp_setting = {"style": wx.CB_DROPDOWN, "choices": q_names}
        ll[4] = ["Queue", q_names[0], 4, dp_setting]
        self.elp = EditListPanel(self, ll)

        hbox2.Add(self.elp, 1,
                  wx.EXPAND | wx.ALIGN_CENTER | wx.RIGHT | wx.LEFT, 1)
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        button = wx.Button(self, wx.ID_ANY, "Cancel")
        button2 = wx.Button(self, wx.ID_ANY, "Submit")

        hbox.Add(button, 0, wx.EXPAND)
        hbox.AddStretchSpacer()
        hbox.Add(button2, 0, wx.EXPAND)
        vbox.Add(hbox, 0, wx.EXPAND | wx.ALL, 5)

        button.Bind(wx.EVT_BUTTON, self.onCancel)
        button2.Bind(wx.EVT_BUTTON, self.onSubmit)
        if value is not None:
            v, names = get_defaults()
            for k, n in enumerate(names):
                if n in value: v[k] = value[n]
            if not value[4] in q_names:
                value[4] = q_names[0]
            self.elp.SetValue(value)
        size = self.GetSize()
        self.SetSizeHints(minH=-1, minW=size.GetWidth())
        self.Show()
        self.Layout()
        self.Fit()
        self.CenterOnScreen()
        #wx.CallAfter(self.Fit)
        self.value = self.elp.GetValue()

    def onCancel(self, evt):
        self.value = self.elp.GetValue()
        self.EndModal(wx.ID_CANCEL)

    def onSubmit(self, evt):
        self.value = self.elp.GetValue()
        self.EndModal(wx.ID_OK)
Beispiel #3
0
class DlgMdsSessionData(DialogWithWindowList):
    # class DlgMdsSessionData(FrameWithWindowList):
    def __init__(self, parent, data=None, figmds=None, cb=None, noapply=False):
        if data is None:
            return
        if figmds is None:
            return
        self._rvars = tuple()
        self.cb = cb
        self.figmds = weakref.ref(figmds, self.onLinkDead)

        style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
        super(DlgMdsSessionData, self).__init__(parent, wx.ID_ANY, style=style,
                                                title=self.figmds().get_full_path())
#        FrameWithWindowList.__init__(self, parent, wx.ID_ANY,
#                          title = self.figmds().get_full_path())

        if bitmaps is None:
            from ifigure.utils.cbook import make_bitmap_list
            from ifigure.ifigure_config import icondir as path
            path1 = os.path.join(path, '16x16', 'variable.png')
            path2 = os.path.join(path, '16x16', 'script.png')
            globals()['bitmaps'] = make_bitmap_list([path1, path2])


#        self.nb_big = wx.Notebook(self)
        panel1 = wx.Panel(self)

        # panel1
        elpl = [['Experiment', figmds.getvar('experiment'), 200, None],
                ['Def Node', figmds.getvar('default_node'), 200, None],
                ['Title', figmds.getvar('title'), 200, None]]

        self.elp = EditListPanel(panel1, elpl)
        self.nb = Notebook(panel1)
        self.bt_var = wx.BitmapButton(
            panel1, wx.ID_ANY, bitmaps[0])  # 'Add Variable...')
        self.bt_script = wx.BitmapButton(
            panel1, wx.ID_ANY, bitmaps[1])  # 'Add Script...')
        self.cb_local = wx.StaticText(
            panel1, wx.ID_ANY, 'Note: Script runs in main thread')
#        p = PythonSTC(self.nb, -1)
#        self.nb.AddPage(p, 'Untitiled')
        sizer = wx.BoxSizer(wx.VERTICAL)
        bsizer2 = wx.BoxSizer(wx.HORIZONTAL)
        bsizer1 = wx.BoxSizer(wx.HORIZONTAL)
        bsizer0 = wx.BoxSizer(wx.VERTICAL)

        bsizer1.Add(self.elp, 1, wx.EXPAND | wx.ALL, 3)
        bsizer1.Add(bsizer0, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 1)
        bsizer0.Add(self.bt_var, 0, wx.ALL, 0)
        bsizer0.Add(self.bt_script, 0, wx.ALL, 0)
        bsizer2.Add(self.cb_local, 1, wx.ALL, 3)

        sizer.Add(bsizer1, 0, wx.EXPAND | wx.ALL, 1)
        sizer.Add(self.nb, 1, wx.EXPAND | wx.ALL, 0)
        sizer.Add(bsizer2, 0, wx.EXPAND | wx.ALL, 1)
        panel1.SetSizer(sizer)

#        self.bt_var = wx.Button(panel1, wx.ID_ANY, 'Add Variable...')
#       self.bt_script = wx.Button(panel1, wx.ID_ANY, 'Add Script...')
#        self.cb_local = wx.CheckBox(self, wx.ID_ANY, 'Run script in main thread')

        bt_apply = wx.Button(self, wx.ID_ANY, 'Apply')
        bt_save = wx.Button(self, wx.ID_ANY, 'Save')
#        bt_reset  = wx.Button(self, wx.ID_ANY, 'Reset')
#        bt_cancel = wx.Button(self, wx.ID_ANY, 'Cancel')
#        bsizer0.Add(self.bt_var, 1, wx.ALL, 3)
#        bsizer0.Add(self.bt_script, 1, wx.ALL, 3)
#        bsizer1.Add(self.cb_local, 1, wx.ALL, 3)

        # big_panel
        self.SetSizer(wx.BoxSizer(wx.VERTICAL))
        self.GetSizer().Add(panel1, 1, wx.EXPAND)
        from ifigure.utils.wx3to4 import GridSizer
        bsizer = GridSizer(1, 5)
        bsizer.AddStretchSpacer()
        self.GetSizer().Add(bsizer, 0, wx.EXPAND | wx.ALL, 1)
        bsizer.Add(bt_save, 1, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 3)
        bsizer.AddStretchSpacer()
        bsizer.Add(bt_apply, 1, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 3)
        bsizer.AddStretchSpacer()
#        bsizer.Add(bt_reset, 1, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 3)
#        bsizer.Add(bt_cancel, 1, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 3)
        self.Bind(wx.EVT_BUTTON, self.onAddVar, self.bt_var)
        self.Bind(wx.EVT_BUTTON, self.onAddScript, self.bt_script)
        self.Bind(wx.EVT_BUTTON, self.onSave, bt_save)
#        self.Bind(wx.EVT_BUTTON, self.onCancel, bt_cancel)
        self.Bind(wx.EVT_BUTTON, self.onApply, bt_apply)
#        self.Bind(wx.EVT_BUTTON, self.onReset, bt_reset)
        if noapply:
            bt_apply.Hide()
#        self.Bind(wx.EVT_CHECKBOX, self.onHit, cb_local)
        hasscript, lc, script = self.read_script()
        if hasscript:
            self.bt_script.Enable(False)
        self.cb_local.SetLabel(self._lcstr(lc, hasscript))
        self.data2pages(data)
        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.onClosePage, self.nb)
        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGED,
                  self.onPageChanging, self.nb)
#        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.onPageChange, self.nb)
#        wx.CallLater(1000, self.onPageChange, None)
        # self.append_help_menu()
        self.SetSize((650, 600))
        # self.SetMenuBar(self.menuBar)
        self.Layout()
        self.Show()
        self.Raise()
        # self.set_accelerator_table()
        self.nb.SetSelection(0)
        wx.GetApp().add_palette(self)
        self.Bind(wx.EVT_CLOSE, self.onClose)
        
    def onClose(self, evt):
        wx.GetApp().rm_palette(self)
        self.Destroy()
        evt.Skip()

    def onPageChanging(self, evt):
        ipage = self.nb.GetSelection()
        evt.Skip()

    def onApply(self, evt=None):
        self.onSave(self)
        fig_mds = self.figmds()
        fig_axes = fig_mds.get_figaxes()
        proj = fig_mds.get_root_parent()
        scope = proj.app.find_bookviewer(fig_mds.get_figbook())
        if scope is not None:
            scope._handle_apply_abort(allshot=True, figaxes=[fig_axes])
        if evt is not None:
            evt.Skip()

    def onOk(self, evt):
        # do something to convert texts to data
        # send action to figmds
        data, script = self.pages2data()
        self.update_figmds(data, script)
        self.data = None
        self.Destroy()

    def onCancel(self, evt):
        self.data = None
        self.Destroy()
#        if self.cb is not None:
#            self.cb()

    def onSave(self, evt=None):
        data, script = self.pages2data()
        self.update_figmds(data, script)
        ipage = self.nb.GetSelection()
        for x in range(self.nb.GetPageCount()):
            p = self.nb.GetPage(x)
            name = str(self.nb.GetPageText(x))
            if name.startswith('*'):
                name = name[1:]
            self.nb.SetPageText(x, name)
            p.SetSavePoint()

        if self.nb.GetPageCount() > ipage:
            self.nb.SetSelection(ipage)

        for x in range(self.nb.GetPageCount()):
            p = self.nb.GetPage(x)
            p.SetSavePoint()
        self.onModified(None)
#        for x in range(self.nb.GetPageCount()):
#            p=self.nb.GetPage(x)
#            self.Bind(wx.stc.EVT_STC_MODIFIED, self.onModified, p)

    def onReset(self, evt):
        fmds = self.figmds()
        if fmds is None:
            self.Destroy()
#            if self.cb is not None:
#                self.cb()
            return
#        self.Freeze()
#        self.deleteallpages()
        self.data2pages(fmds.getvar('mdsvars'))
#        self.Thaw()

    def onAddVar(self, evt):
        dlg = TextEntryDialog(self.GetTopLevelParent(),
                              "Enter the name of variable", "Add variable", "")
        if dlg.ShowModal() == wx.ID_OK:
            #            self.Freeze()
            new_name = str(dlg.GetValue())
            data, script = self.pages2data()
            if new_name in data:
                return
#            len(data.keys())
            for i in range(self.nb.GetPageCount()):
                self.nb.GetPage(i).set_syntax('none')

            p = self._new_stc(self.nb, '', syntax='none')
            self.nb.InsertPage(len(data), p, new_name, True)
            self.Bind(wx.stc.EVT_STC_MODIFIED, self.onModified, p)
#            data[new_name] = ''
#            self.data2pages(data)
        dlg.Destroy()

    def SetStatusText(self, *args, **kargs):
        pass

    def onOpenFile(self, *args, **kargs):
        pass

    def onSaveFile(self, *args, **kargs):
        # this is called from stc
        self.onApply()

    def onAddScript(self, evt=None):
        hasscript, lc, script = self.read_script()
        if hasscript:
            return

#        self.Freeze()
        data, script = self.pages2data()
        data['script.py'] = ''

        self.data2pages(data)
#        self.bt_script.Enable(False)
#        self.cb_local.SetLabel(self._lcstr(lc, True))
#        self.Thaw()
        evt.Skip()

    def _lcstr(self, value, hasscript):
        if not hasscript:
            return "note : no addtionanl python script after MDS session"
        if value:
            return "note : script runs in main thread"
        else:
            return "note : script runs in subprocess"

#    def onPageChange(self, evt=None):
#        ipage = self.nb.GetSelection()
#        label  = self.nb.GetPageText(ipage)
#        self._selected_page = label

    def onClosePage(self, evt):
        #        print("onClose")
        ipage = self.nb.GetSelection()
        label = str(self.nb.GetPageText(ipage))
        if label.startswith('*'):
            label = label[1:]
        mods = [self.nb.GetPage(x).GetModify()
                for x in range(self.nb.GetPageCount())]
        del mods[ipage]
        if str(label) in self._rvars:
            ret = dialog.message(self,
                                 '"'+label+'"' +
                                 " cannot deleted for current plot type\n(Leave it empty, if you don't need it)",
                                 'Error',
                                 0)
            evt.Veto()
            return
        npage = self.nb.GetPageCount()
        if npage == 1 or npage == 0:
            ret = dialog.message(self,
                                 '"'+label+'"' + " cannot deleted since this is the last page.",
                                 'Error',
                                 0)
            evt.Veto()
            return
        else:
            ret = dialog.message(self,
                                 'Do you want to delete "'+label+'"',
                                 'Error',
                                 2)
            if ret != 'ok':
                evt.Veto()
                return

#        if label == 'script.py' or label == '*script.py':
#            fmds = self.figmds()
#            if fmds is not None:
#              if (fmds.has_owndir() and
#                  fmds.hasvar('path')):
#                  fname = os.path.join(fmds.owndir(), fmds.getvar('path'))
#                  if os.path.exists(fname):
#                      os.remove(fname)
#                      fmds.delvar('pathmode')
#                      fmds.delvar('path')
        self.data = None
#        print label
        if str(label) == 'script.py':
            self.bt_script.Enable(True)

        wx.CallAfter(self._set_save_point, mods)

    def _set_save_point(self, mods):
        # print 'xxx', mods
        for x in range(self.nb.GetPageCount()):
            p = self.nb.GetPage(x)
            txt = self.nb.GetPageText(x)
            if not mods[x]:
                self.nb.GetPage(x).SetSavePoint()
                if txt.startswith('*'):
                    self.nb.SetPageText(x, txt[1:])
            else:
                if not txt.startswith('*'):
                    self.nb.SetPageText(x, '*' + txt)

    def update_figmds(self, data, script):
        fmds = self.figmds()
        var = self.elp.GetValue()
        fmds.setvar('experiment', str(var[0]))
        fmds.setvar('default_node', str(var[1]))
        fmds.setvar('title', str(var[2]))
        d = OrderedDict()
        for key in data:
            name = key
            if key.startswith('*'):
                name = key[1:]
            d[name] = data[key]
        fmds.applyDlgData(d)
        if script != '':
            if not fmds.has_owndir():
                fmds.mk_owndir()
            filename = 'mdsscript.py'
            fmds.setvar('pathmode', 'owndir')
            fmds.setvar('path', filename)
            fname = os.path.join(fmds.owndir(),
                                 fmds.getvar('path'))
            from ifigure.mdsplus.fig_mds import write_scriptfile
            write_scriptfile(fname, script)
        else:
            if (fmds.has_owndir() and
                    fmds.hasvar('path')):
                fname = os.path.join(fmds.owndir(), fmds.getvar('path'))
                if os.path.exists(fname):
                    os.remove(fname)
                    fmds.delvar('pathmode')
                    fmds.delvar('path')

#        fmds._script_local = self.cb_local.GetValue()
#        print self.GetParent()
        self.GetParent().property_editor.update_panel()
        # should change varviewer here too

    def checkscripttab(self):
        data = OrderedDict()
        for ipage in range(self.nb.GetPageCount()):
            name = str(self.nb.GetPageText(ipage))
            if name.startswith('*'):
                name = name[1:]
            p = self.nb.GetPage(ipage)
            data[name] = str(p.GetText())

        return 'script.py' in data

    def pages2data(self):
        data = OrderedDict()
        for ipage in range(self.nb.GetPageCount()):
            name = str(self.nb.GetPageText(ipage)).strip()
            if name.startswith('*'):
                name = name[1:]
            p = self.nb.GetPage(ipage)
            data[name] = str(p.GetText()).strip()
            p.SetSavePoint()
        script = ''
        if 'script.py' in data:
            script = data['script.py']
            del data['script.py']
        return data, script

    def data2pages(self, data):
        fmds = self.figmds()

        hasscript, lc,  script = self.read_script()
        if 'script.py' in data:
            script = data['script.py']
            hasscript = True
            del data['script.py']

        # set button
        self.cb_local.SetLabel(self._lcstr(lc, hasscript))

        # prepare pages
        npage = len([key for key in data])
        if hasscript:
            npage = npage + 1
        while self.nb.GetPageCount() != npage:
            if self.nb.GetPageCount() > npage:
                self.nb.DeletePage(self.nb.GetPageCount()-1)
            elif self.nb.GetPageCount() < npage:
                title = 'tmp_key' + str(self.nb.GetPageCount())
                p = self._new_stc(self.nb, '', syntax='python')
                title = '{:>3s}'.format(title)
                self.nb.AddPage(p, title, True)
                self.Bind(wx.stc.EVT_STC_MODIFIED, self.onModified, p)

        for ipage, key in enumerate(data):
            self.nb.SetPageText(ipage, key)
            p = self.nb.GetPage(ipage)
            if ipage == len(data)-1 and hasscript:
                pass
            else:
                p.set_syntax('none')
            self._set_stc_txt(p, data[key])

        if hasscript:
            self.nb.SetPageText(npage-1, 'script.py')
            p = self.nb.GetPage(npage-1)
            self._set_stc_txt(p, script)
            p.set_syntax('python')
            self.bt_script.Enable(False)
        else:
            self.bt_script.Enable(True)

    def read_script(self):
        from ifigure.mdsplus.fig_mds import read_scriptfile
        fmds = self.figmds()
        lc = fmds.get_script_local()
        if fmds is None:
            return
        if (fmds.has_owndir() and
                fmds.hasvar('path')):
            fname = os.path.join(fmds.owndir(), fmds.getvar('path'))
            txt = read_scriptfile(fname)
            return True,  lc, txt
        return False, lc,  ''

    def get_filelist(self):
        return self.file_list

    def onModified(self, e=None):
        ipage = self.nb.GetSelection()
#        print 'onModified', ipage
        txt = self.nb.GetPageText(ipage)
        p = self.nb.GetPage(ipage)
#        print [self.nb.GetPage(x).GetModify() for x in range(self.nb.GetPageCount())]
        # print p.GetModify()
        if not txt.startswith('*') and p.GetModify():
            self.nb.SetPageText(ipage, '*'+txt)
        if txt.startswith('*') and not p.GetModify():
            self.nb.SetPageText(ipage, txt[1:])

    def onLinkDead(self, obj):
        #        if self.cb is not None:
        #            self.cb()
        try:
            self.Destroy()
        except:
            pass

    def _new_stc(self, parent, txt, syntax='none'):
        p = PythonSTC(parent, -1, syntax=syntax)
        self._set_stc_txt(p, txt)
        p.EmptyUndoBuffer()
        p.Colourise(0, -1)
        # line numbers in the margin
        p.SetMarginType(1, stc.STC_MARGIN_NUMBER)
        #p.SetMarginWidth(1, 25)
        p.set_syntax(syntax)
        return p

    def _set_stc_txt(self, p, txt):
        #        mod = p.GetModify()
        try:
            p.SetText(txt)
#            if not mod: p.SetSavePoint()
        except UnicodeDecodeError:
            p.SetText(unicode(txt, errors='ignore'))
#            if not mod: p.SetSavePoint()
        pass
Beispiel #4
0
class DlgMdsSession(DialogWithWindowList):
    def __init__(self, parent, data=None, figmds=None, cb=None, noapply=False):
        if data is None: return
        if figmds is None: return
        self._rvars = tuple()
        self._var_mask = [x for x in figmds._var_mask]
        self.cb = cb
        self.figmds = weakref.ref(figmds, self.onLinkDead)

        style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
        super(DlgMdsSession,
              self).__init__(parent,
                             wx.ID_ANY,
                             style=style,
                             title=self.figmds().get_full_path())
        #FrameWithWindowList.__init__(self, parent, wx.ID_ANY,
        #                  title = self.figmds().get_full_path())
        if bitmaps is None:
            from ifigure.utils.cbook import make_bitmap_list
            from ifigure.ifigure_config import icondir as path
            path1 = os.path.join(path, '16x16', 'variable.png')
            path2 = os.path.join(path, '16x16', 'script.png')
            globals()['bitmaps'] = make_bitmap_list([path1, path2])

        self.nb_big = wx.Notebook(self)
        panel1 = wx.Panel(self.nb_big)
        panel2 = wx.Panel(self.nb_big)

        ### panel1
        elpl = [['Experiment',
                 figmds.getvar('experiment'), 200, None],
                ['Def Node',
                 figmds.getvar('default_node'), 200, None],
                ['Title', figmds.getvar('title'), 200, None]]

        self.elp = EditListPanel(panel1, elpl)
        self.nb = Notebook(panel1)
        #        p = PythonSTC(self.nb, -1)
        #        self.nb.AddPage(p, 'Untitiled')
        self.bt_var = wx.BitmapButton(panel1, wx.ID_ANY,
                                      bitmaps[0])  # 'Add Variable...')
        self.bt_script = wx.BitmapButton(panel1, wx.ID_ANY,
                                         bitmaps[1])  # 'Add Script...')
        #        self.cb_local = wx.CheckBox(self, wx.ID_ANY, 'Run script in main thread')
        self.cb_local = wx.StaticText(panel1, wx.ID_ANY,
                                      'Note: Script runs in main thread')
        self.rb_mask = wx.CheckBox(panel1, wx.ID_ANY, 'Ignore this variable')
        sizer = wx.BoxSizer(wx.VERTICAL)
        bsizer2 = wx.BoxSizer(wx.HORIZONTAL)
        bsizer1 = wx.BoxSizer(wx.HORIZONTAL)
        bsizer0 = wx.BoxSizer(wx.VERTICAL)

        bsizer1.Add(self.elp, 1, wx.EXPAND | wx.ALL, 3)
        bsizer1.Add(bsizer0, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 1)
        bsizer0.Add(self.bt_var, 0, wx.ALL, 0)
        bsizer0.Add(self.bt_script, 0, wx.ALL, 0)
        bsizer2.Add(self.cb_local, 1, wx.ALL, 3)

        sizer.Add(bsizer1, 0, wx.EXPAND | wx.ALL, 1)
        sizer.Add(self.nb, 1, wx.EXPAND | wx.ALL, 0)
        sizer.Add(self.rb_mask, 0, wx.ALL, 1)
        sizer.Add(bsizer2, 0, wx.EXPAND | wx.ALL, 1)
        panel1.SetSizer(sizer)

        ### panel2
        panel2.SetSizer(wx.BoxSizer(wx.VERTICAL))
        s = {
            "style":
            wx.CB_READONLY,
            "choices": [
                "timetrace", "stepplot", "plot", "contour", "image", "axline",
                "axspan", "surface"
            ]
        }
        elp2 = [
            [None, 'timetrace', 31, s],
            [None, ((False, (-1, 1)), (False, (-1, 1))), 32, None],
            ["update", '', 0, {}],
        ]
        self.elp2 = EditListPanel(panel2, elp2)
        self.elp2.Bind(EDITLIST_CHANGED, self.onEL_Changed)
        self.bt = wx.Button(panel2, wx.ID_ANY, 'Format...')
        panel2.GetSizer().Add(self.elp2, 1, wx.EXPAND)
        panel2.GetSizer().Add(self.bt, 0, wx.ALL | wx.ALIGN_RIGHT, 5)
        self.bt.Bind(wx.EVT_BUTTON, self.onFormat)

        ### big_panel
        self.nb_big.AddPage(panel1, 'Signal')
        self.nb_big.AddPage(panel2, 'Setting')
        self.SetSizer(wx.BoxSizer(wx.VERTICAL))
        self.GetSizer().Add(self.nb_big, 1, wx.EXPAND)
        bt_apply = wx.Button(self, wx.ID_ANY, 'Apply')
        bt_save = wx.Button(self, wx.ID_ANY, 'Save')

        bsizer = GridSizer(1, 5)
        bsizer.AddStretchSpacer()
        self.GetSizer().Add(bsizer, 0, wx.EXPAND | wx.ALL, 1)
        bsizer.Add(bt_save, 1, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 3)
        bsizer.AddStretchSpacer()
        bsizer.Add(bt_apply, 1, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 3)
        bsizer.AddStretchSpacer()
        #        bsizer.Add(bt_reset, 1, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 3)
        #        bsizer.Add(bt_cancel, 1, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 3)
        self.Bind(wx.EVT_BUTTON, self.onAddVar, self.bt_var)
        self.Bind(wx.EVT_BUTTON, self.onAddScript, self.bt_script)
        self.Bind(wx.EVT_BUTTON, self.onSave, bt_save)
        #        self.Bind(wx.EVT_BUTTON, self.onCancel, bt_cancel)
        self.Bind(wx.EVT_BUTTON, self.onApply, bt_apply)
        #        self.Bind(wx.EVT_BUTTON, self.onReset, bt_reset)
        if noapply: bt_apply.Hide()
        #        self.Bind(wx.EVT_CHECKBOX, self.onHit, cb_local)
        hasscript, lc, script = self.read_script()
        if hasscript: self.bt_script.Enable(False)
        self.cb_local.SetLabel(self._lcstr(lc, hasscript))
        self.data2pages(data)
        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.onClosePage, self.nb)
        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.onPageChanging,
                  self.nb)
        self.Bind(wx.EVT_CHECKBOX, self.onMaskHit, self.rb_mask)
        #        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.onPageChange, self.nb)
        #        wx.CallLater(1000, self.onPageChange, None)
        self.set_panel2(figmds)

        #self.append_help_menu()
        #self.append_help2_menu(self.helpmenu)
        #self.SetMenuBar(self.menuBar)
        self.Bind(wx.EVT_CLOSE, self.onClose)
        self.SetSize((650, 600))
        self.Layout()
        self.SetSize((650, 700))
        self.Show()
        self.Raise()
        #self.set_accelerator_table()
        self.nb.SetSelection(0)
        self.set_mask_button()
        wx.GetApp().add_palette(self)

    def onClose(self, evt):
        wx.GetApp().rm_palette(self)
        self.Destroy()
        evt.Skip()

    def onFormat(self, evt):
        from ifigure.mto.fig_plot import FigPlot
        from ifigure.mto.fig_contour import FigContour
        from ifigure.mto.fig_image import FigImage
        from ifigure.mto.fig_surface import FigSurface
        from ifigure.mto.fig_axline import FigAxline
        from ifigure.mto.fig_axspan import FigAxspan
        from ifigure.mto.fig_text import FigText

        from ifigure.utils.edit_list import EditListDialog
        from ifigure.widgets.artist_widgets import listparam
        figtype = self.elp2.GetValue()[0]
        if (figtype == 'plot' or figtype == 'timetrace'
                or figtype == 'stepplot'):
            s = {"style": wx.CB_READONLY, "choices": ["line", "dot", "both"]}
            l = [
                [None, 'format plot', 2, None],
                ["mode", 'line', 4, s],
            ]
        elif figtype == 'contour':
            l = [
                [None, 'format contour', 2, None],
                listparam['contour_nlevel2'][:4],
            ]
        else:
            l = None
        if l is None: return
        dia = EditListDialog(
            self,
            wx.ID_ANY,
            '',
            l,
            nobutton=False,
            pos=self.GetScreenPosition(),
        )
        val = dia.ShowModal()
        value = dia.GetValue()
        dia.Destroy()
        if val != wx.ID_OK: return

        fig_mds = self.figmds()
        if figtype in ('plot', 'timetrace', 'stepplot'):
            figplots = [
                child for name, child in fig_mds.get_children()
                if isinstance(child, FigPlot)
            ]
            artists = []
            for p in figplots:
                artists.extend(p._artists)

            opt = fig_mds.getvar('plot_options')[figtype]
            if str(value[1]) == 'line':
                opt = (('', ), opt[1].copy())
                for a in artists:
                    a.set_marker(None)
                    a.set_linestyle('-')
            elif str(value[1]) == 'dot':
                opt = (('s', ), opt[1].copy())
                for a in artists:
                    a.set_marker('s')
                    a.set_linestyle('None')
                    a.set_markersize(3)
                    a.set_markerfacecolor(a.get_color())
                    a.set_markeredgecolor(a.get_color())
            elif str(value[1]) == 'both':
                opt = (('-o', ), opt[1].copy())
                for a in artists:
                    a.set_marker('o')
                    a.set_linestyle('-')
                    a.set_markersize(3)
                    a.set_markerfacecolor(a.get_color())
                    a.set_markeredgecolor(a.get_color())

            fig_mds.getvar('plot_options')[figtype] = opt

            for k, child in enumerate(figplots):
                child.setvar('s', opt[0][0])
#                col = fig_mds._color_order[k % len(fig_mds._color_order)]
#                opt[1]['color'] = col
#                opt[1]['markerfacecolor'] = col
#                opt[1]['markeredgecolor'] = col
#                for key in opt[1]:
#                     child.getvar('kywds')[key] = opt[1][key]
        elif figtype == 'contour':
            #            print(value[1])
            for name, child in fig_mds.get_children():
                if isinstance(child, FigContour):
                    child.set_contour_nlevel2(value[1])
            if value[1][0]:
                opt = ((value[1][1][0][1], ), {})
            else:
                opt = ((int(value[1][2][0]), ), {})
            fig_mds.getvar('plot_options')[figtype] = opt

            figplots = [
                child for name, child in fig_mds.get_children()
                if isinstance(child, FigContour)
            ]
            for child in figplots:
                child.setvar('n', opt[0][0])
        else:
            return
        fig_mds.get_figaxes().set_bmp_update(False)
        import ifigure.events
        ifigure.events.SendPVDrawRequest(fig_mds.get_figbook(),
                                         wait_idle=True,
                                         refresh_hl=False)

    def onMaskHit(self, evt):
        ipage = self.nb.GetSelection()
        txt = self.nb.GetPageText(ipage)
        txt = ''.join(txt.split('*'))
        if self.rb_mask.GetValue():
            self._var_mask.append(txt)
        else:
            self._var_mask = [x for x in self._var_mask if x != txt]
        evt.Skip()

    def onPageChanging(self, evt):
        ipage = self.nb.GetSelection()
        self.set_mask_button()
        evt.Skip()

    def set_mask_button(self):
        ipage = self.nb.GetSelection()
        txt = self.nb.GetPageText(ipage)
        txt = ''.join(txt.split('*'))
        self.rb_mask.SetValue(txt in self._var_mask)

    def set_panel2(self, figmds):
        value = [
            figmds.get_mdsfiguretype(None),
            figmds.get_mdsrange(None),
            figmds.get_mdsevent(None)
        ]
        self.elp2.SetValue(value)

    def onApply(self, evt=None):
        self.onSave(self)
        fig_mds = self.figmds()
        fig_axes = fig_mds.get_figaxes()
        proj = fig_mds.get_root_parent()
        scope = proj.app.find_bookviewer(fig_mds.get_figbook())
        if scope is not None:
            scope._handle_apply_abort(allshot=True, figaxes=[fig_axes])
        if evt is not None: evt.Skip()

    def onOk(self, evt):
        # do something to convert texts to data
        # send action to figmds
        data, script = self.pages2data()
        self.update_figmds(data, script)
        v = self.elp2.GetValue()
        self.data = None
        self.Destroy()
        if self.cb is not None:
            self.cb(v)

    def onCancel(self, evt):
        self.data = None
        self.Destroy()
#        if self.cb is not None:
#            self.cb()

    def onSave(self, evt=None):
        data, script = self.pages2data()
        self.update_figmds(data, script)
        ipage = self.nb.GetSelection()
        for x in range(self.nb.GetPageCount()):
            p = self.nb.GetPage(x)
            #            name = str(self.nb.GetPageText(x))
            #            if name.startswith('*'): name = name[1:]
            p.SetSavePoint()
            self.nb.SetPageTextModifiedMark(x, False)

        v = self.elp2.GetValue()
        if self.cb is not None:
            self.cb(v)
        if self.nb.GetPageCount() > ipage:
            self.nb.SetSelection(ipage)

        for x in range(self.nb.GetPageCount()):
            p = self.nb.GetPage(x)
            p.SetSavePoint()
        self.onModified(None)
#        for x in range(self.nb.GetPageCount()):
#            p=self.nb.GetPage(x)
#            self.Bind(wx.stc.EVT_STC_MODIFIED, self.onModified, p)

    def onReset(self, evt):
        fmds = self.figmds()
        if fmds is None:
            self.Destroy()
            #            if self.cb is not None:
            #                self.cb()
            return
#        self.Freeze()
#        self.deleteallpages()
        self.data2pages(fmds.getvar('mdsvars'))
#        self.Thaw()

    def onAddVar(self, evt):
        dlg = TextEntryDialog(self.GetTopLevelParent(),
                              "Enter the name of variable", "Add variable", "")
        if dlg.ShowModal() == wx.ID_OK:
            #            self.Freeze()
            new_name = str(dlg.GetValue())
            data, script = self.pages2data()
            if new_name in data.keys():
                dlg.Destroy()
                return
#            len(data.keys())
            for i in range(self.nb.GetPageCount()):

                label = str(self.nb.GetPageText(i))
                if label.startswith('*'): label = label[1:]
                if label == 'script.py':
                    self.nb.GetPage(i).set_syntax('python')
                else:
                    self.nb.GetPage(i).set_syntax('none')
            p = self._new_stc(self.nb, '', syntax='none')
            self.nb.InsertPage(len(data.keys()), p, new_name, True)
            self.Bind(wx.stc.EVT_STC_MODIFIED, self.onModified, p)
#            data[new_name] = ''
#            self.data2pages(data)
        dlg.Destroy()

    def SetStatusText(self, *args, **kargs):
        pass

    def onOpenFile(self, *args, **kargs):
        pass

    def onSaveFile(self, *args, **kargs):
        ## this is called from stc
        self.onApply()

    def onAddScript(self, evt=None):
        hasscript, lc, script = self.read_script()
        if hasscript: return

        #        self.Freeze()
        data, script = self.pages2data()
        data['script.py'] = '\n'

        self.data2pages(data)
        #        self.bt_script.Enable(False)
        #        self.cb_local.SetLabel(self._lcstr(lc, True))
        #        self.Thaw()
        evt.Skip()

    def _lcstr(self, value, hasscript):
        if not hasscript:
            return "note : no addtionanl python script after MDS session"
        if value:
            return "note : script runs in main thread"
        else:
            return "note : script runs in subprocess"

#    def onPageChange(self, evt=None):
#        ipage = self.nb.GetSelection()
#        label  = self.nb.GetPageText(ipage)
#        self._selected_page = label

    def onClosePage(self, evt):
        print 'onClose'
        ipage = self.nb.GetSelection()
        label = str(self.nb.GetPageText(ipage))
        if label.startswith('*'): label = label[1:]
        mods = [
            self.nb.GetPage(x).GetModify()
            for x in range(self.nb.GetPageCount())
        ]
        del mods[ipage]
        if str(label) in self._rvars:
            ret = dialog.message(
                self, '"' + label + '"' +
                " cannot be deleted for current plot type\n(Leave it empty, if you don't need it)",
                'Error', 0)
            evt.Veto()
            return
        npage = self.nb.GetPageCount()
        if npage == 1 or npage == 0:
            ret = dialog.message(
                None, '"' + label + '"' +
                " cannot be deleted since this is the last page.", 'Error', 0)
            evt.Veto()
            return
        else:
            ret = dialog.message(self, 'Do you want to delete "' + label + '"',
                                 'Error', 2)
            if ret != 'ok':
                evt.Veto()
                return

        self.data = None
        if str(label) == 'script.py':
            self.bt_script.Enable(True)

        if self.cb is not None:
            v = self.elp2.GetValue()
            self.cb(v)
        wx.CallAfter(self._set_save_point, mods)

    def _set_save_point(self, mods):
        #print 'xxx', mods
        for x in range(self.nb.GetPageCount()):
            #            p = self.nb.GetPage(x)
            #            txt = self.nb.GetPageText(x)
            self.nb.SetPageTextModifiedMark(x, mods[x])
#            if not mods[x]:
#               self.nb.GetPage(x).SetSavePoint()
#               if txt.startswith('*'):
#                  self.nb.SetPageText(x, txt[1:])
#            else:
#               if not txt.startswith('*'):
#                  self.nb.SetPageText(x,'*'+ txt)

    def update_figmds(self, data, script):
        fmds = self.figmds()
        fmds._var_mask = [x for x in self._var_mask]
        var = self.elp.GetValue()
        fmds.setvar('experiment', str(var[0]))
        fmds.setvar('default_node', str(var[1]))
        fmds.setvar('title', str(var[2]))
        d = OrderedDict()
        for key in data:
            name = key
            if key.startswith('*'): name = key[1:]
            d[name] = data[key]
        fmds.applyDlgData(d)

        if script != '':
            fmds.write_script(script)
        else:
            fmds.remove_script()

#        fmds._script_local = self.cb_local.GetValue()
#        print self.GetParent()
        self.GetParent().property_editor.update_panel()
        ## should change varviewer here too

    def checkscripttab(self):
        data = OrderedDict()
        for ipage in range(self.nb.GetPageCount()):
            name = str(self.nb.GetPageText(ipage))
            if name.startswith('*'): name = name[1:]
            p = self.nb.GetPage(ipage)
            data[name] = str(p.GetText())

        return 'script.py' in data

    def pages2data(self):
        data = OrderedDict()
        for ipage in range(self.nb.GetPageCount()):
            name = str(self.nb.GetPageText(ipage))
            if name.startswith('*'): name = name[1:]
            p = self.nb.GetPage(ipage)
            data[name] = str(p.GetText()).strip()
            p.SetSavePoint()
        script = ''
        if 'script.py' in data:
            script = data['script.py']
            del data['script.py']
        return data, script

    def data2pages(self, data):
        fmds = self.figmds()

        hasscript, lc, script = self.read_script()
        if 'script.py' in data:
            script = data['script.py']
            hasscript = True
            del data['script.py']

        ## set button
        self.cb_local.SetLabel(self._lcstr(lc, hasscript))

        ## prepare pages
        npage = len([key for key in data])
        if hasscript: npage = npage + 1
        while self.nb.GetPageCount() != npage:
            if self.nb.GetPageCount() > npage:
                self.nb.DeletePage(self.nb.GetPageCount() - 1)
            elif self.nb.GetPageCount() < npage:
                title = 'tmp_key' + str(self.nb.GetPageCount())
                p = self._new_stc(self.nb, '', syntax='python')
                title = '{:>3s}'.format(title)
                self.nb.AddPage(p, title, select=True)
                self.Bind(wx.stc.EVT_STC_MODIFIED, self.onModified, p)

        for ipage, key in enumerate(data):
            self.nb.SetPageText(ipage, key)
            p = self.nb.GetPage(ipage)
            if ipage == len(data) - 1 and hasscript:
                pass
            else:
                p.set_syntax('none')
            self._set_stc_txt(p, data[key])

        if hasscript:
            fmds = self.figmds()
            fname = os.path.join(fmds.owndir(), 'mdsscript.py')
            self.nb.SetSelection(npage - 1)
            self.nb.SetPageText(npage - 1, 'script.py', doc_name=fname)
            p = self.nb.GetPage(npage - 1)
            p.set_syntax('python')
            self._set_stc_txt(p, script)
            self.bt_script.Enable(False)
        else:
            self.bt_script.Enable(True)

    def read_script(self):
        from ifigure.mdsplus.fig_mds import read_scriptfile
        fmds = self.figmds()
        lc = fmds.get_script_local()
        if fmds is None: return
        if (fmds.has_owndir() and fmds.hasvar('path')):
            fname = os.path.join(fmds.owndir(), fmds.getvar('path'))
            txt = read_scriptfile(fname)
            return True, lc, txt
        return False, lc, ''

    def get_filelist(self):
        return self.file_list

    def onModified(self, e=None):
        ipage = self.nb.GetSelection()
        p = self.nb.GetPage(ipage)
        self.nb.SetPageTextModifiedMark(ipage, p.GetModify())

    def onLinkDead(self, obj):
        #        if self.cb is not None:
        #            self.cb()
        try:
            self.Destroy()
        except:
            pass

    def onEL_Changed(self, evt):
        from ifigure.mdsplus.fig_mds import required_variables
        print evt.widget_idx
        if evt.widget_idx == 0:
            plot_type = str(evt.elp.GetValue()[0])
            v = required_variables[plot_type]
            self.set_required_variables(v)

    def set_required_variables(self, variables):
        self._rvars = variables
        data, script = self.pages2data()
        chk = self.checkscripttab()
        for x in self._rvars:
            if not x in data:
                p = self._new_stc(self.nb, '', syntax='none')
                title = '{:>3s}'.format(x)
                if script == '':
                    self.nb.AddPage(p, title, select=True)
                else:
                    self.nb.InsertPage(self._rvars.index(x),
                                       p,
                                       title,
                                       select=True)
                self.Bind(wx.stc.EVT_STC_MODIFIED, self.onModified, p)

#        if chk: data['script.py'] = script
#        self.data2pages(data)
#        self.nb.SetSelection(0)

    def _new_stc(self, parent, txt, syntax='none'):
        p = PythonSTC(parent, -1, syntax=syntax)

        #self._set_stc_txt(p, txt)
        p.EmptyUndoBuffer()
        p.Colourise(0, -1)
        # line numbers in the margin
        p.SetMarginType(1, stc.STC_MARGIN_NUMBER)
        #        p.SetMarginWidth(1, 25)
        p.set_syntax(syntax)
        return p

    def _set_stc_txt(self, p, txt):
        #        mod = p.GetModify()
        try:
            p.SetText(txt)
#            if not mod: p.SetSavePoint()
        except UnicodeDecodeError:
            p.SetText(unicode(txt, errors='ignore'))
#            if not mod: p.SetSavePoint()
        pass
class ProjTreeViewer(wx.Panel):
    def __init__(self, parent=None):
        """Constructor"""

        super(ProjTreeViewer, self).__init__(parent)
        self._drag_start = False
        self.panel = None

        #        sizer=wx.BoxSizer(wx.VERTICAL)
        #        self.SetSizer(sizer)
        #        self.splitter=wx.SplitterWindow(self)
        #        sizer.Add(self.splitter, 1, wx.EXPAND)
        #        self.nb = aui.AuiNotebook(self, style=aui.AUI_NB_TAB_SPLIT|
        #                                              aui.AUI_NB_TAB_MOVE|
        #                                              aui.AUI_NB_SCROLL_BUTTONS)

        ### make tree ###
        self.tree = wx.TreeCtrl(self, wx.ID_ANY, wx.DefaultPosition, (-1, -1),
                                wx.TR_HAS_BUTTONS)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.tree, 1, wx.EXPAND)
        self.SetSizer(sizer)
        #        self.nb.AddPage(self.tree, 'Project Tree')
        self.tree.parent = self
        self.dt1 = ProjViewerDropTarget(self)
        self.tree.SetDropTarget(self.dt1)

        im = ImageFiles()
        self.tree.SetIndent(8)
        self.tree.SetImageList(im.get_imagelist())

        self.Bind(wx.EVT_TREE_ITEM_EXPANDING, self.OnExpandItem)
        self.Bind(wx.EVT_TREE_ITEM_COLLAPSING, self.OnCollapseItem)
        self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnItemRightClick)
        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged)
        self.Bind(wx.EVT_TREE_SEL_CHANGING, self.OnSelChanging)
        self.Bind(wx.EVT_TREE_BEGIN_DRAG, self.OnBeginDrag)
        self.Bind(wx.EVT_TREE_END_DRAG, self.OnEndDrag)
        self.Bind(wx.EVT_MENU, self.OnMenu)
        self.Bind(wx.EVT_TREE_KEY_DOWN, self.OnKeyDown)
        self.tree.GetTopLevelParent().Bind(wx.EVT_MOUSE_CAPTURE_LOST,
                                           lambda x: None)

    def init_sash_pos(self):
        return
        #self.splitter.SetSashPosition(200)

    def get_proj(self):
        app = self.GetTopLevelParent()
        return app.proj

    def update_widget(self):
        sel = self.tree.GetSelection()
        if sel is not None:
            sdict = self.tree.GetPyData(sel)
        else:
            sdict = None

        proj = self.get_proj()
        if proj is None:
            self.tree.DeleteAllItems()
            return
        if sdict is None: sdict = proj  ## default select proj

        croot = self.tree.GetRootItem()
        if self.tree.GetPyData(croot) is None:
            self.tree.DeleteAllItems()
            croot = self.tree.AddRoot(proj.name)
            self.tree.SetPyData(croot, self.get_proj())

        #
        #  remove item from tree viewer
        #
        while self.remove_item_from_tree():
            pass
        #
        #  add item to tree viewer
        #
        while self.add_item_to_tree():
            pass
        #
        #  refresh tree name...
        #
        for item in self.walk_treectrl(croot):
            treedict = self.tree.GetPyData(item)
            name = treedict.name
            if treedict.status != '':
                label = name + ' (' + treedict.status + ')'
            else:
                label = name
            self.tree.SetItemText(item, label)

        self.varviewer.fill_list(sdict)
        return

    def walk_treectrl(self, item):
        yield item
        (child, cookie) = self.tree.GetFirstChild(item)
        while child.IsOk():
            for x in self.walk_treectrl(child):
                yield x
            (child, cookie) = self.tree.GetNextChild(item, cookie)

    def OnButton(self, e):
        pass

    def OnKeyDown(self, e):
        "map delete to selcting delete in pull down"
        if e.GetKeyCode() == 8:
            item = self.tree.GetSelection()
            dictobj = self.tree.GetPyData(item)
            dictobj.onDelete(e)

            if isinstance(dictobj, FigObj):
                self.GetTopLevelParent().draw()
            else:
                self.update_widget()

    def OnExpandItem(self, e):
        #        print "change visible (expand)"
        item = e.GetItem()
        dictobj = self.tree.GetPyData(item)
        if dictobj is None:
            return
        for name, child in dictobj.get_children():
            child.set_visible(True)

    def OnCollapseItem(self, e):
        #        print "change visible (collapse)"
        item = e.GetItem()
        dictobj = self.tree.GetPyData(item)
        if dictobj is None:
            return
        for name, child in dictobj.get_children():
            child.set_visible(False)

    def OnItemRightClick(self, e):
        item = e.GetItem()
        dictobj = self.tree.GetPyData(item)
        if dictobj is None:
            return
        menus = dictobj.tree_viewer_menu()
        if menus is None:
            return None

        m = ProjTreeViewerPopUp(self, dictobj)
        self.PopupMenu(m, e.GetPoint())
        m.Destroy()

    def OnSelChanged(self, e):
        item = e.GetItem()
        dictobj = self.tree.GetPyData(item)
        if dictobj is None:
            return
        self.varviewer.fill_list(dictobj)
        if isinstance(dictobj, FigObj):
            if len(dictobj._artists) != 0:
                sel = [weakref.ref(dictobj._artists[0])]
                ifigure.events.SendSelectionEvent(dictobj, self, sel)

    def OnSelChanging(self, e):
        if self._drag_start:
            self._drag_start = False
            e.Veto()

    def OnMenu(self, e):
        self.update_widget()

    def OnBeginDrag(self, e):
        item = e.GetItem()
        dictobj = self.tree.GetPyData(item)
        #        self.dragItem = e.GetItem()
        app = self.tree.GetTopLevelParent()
        app._text_clip = dictobj.get_full_path()
        text = unicode(dictobj.get_full_path())
        tdo = wx.TextDataObject(text)
        tds = wx.DropSource(self.tree)
        tds.SetData(tdo)
        tds.DoDragDrop(True)
        #        self.tree.Unselect()
        self._drag_start = True
        e.Skip()

    def OnEndDrag(self, e):
        print("OnEndDrag")
        #        self.tree.Unselect()
        Write2Main(e, "ev")
        if not e.GetItem().IsOk():
            return
        # Make sure this memeber exists.
        try:
            old = self.dragItem
        except:
            return

        # Get the other IDs that are involved
        new = e.GetItem()
        parent = self.GetItemParent(new)
        if not parent.IsOk():
            return
        text = self.GetItemText(old)
#        self.Delete(old)
#        self.InsertItem(parent, new, text)

    def OpenPanel(self, list, obj=None, callback=None):
        if self.panel is not None:
            self.ClosePanel()
        self.panel = wx.Panel(self, wx.ID_ANY)
        vbox = wx.BoxSizer(wx.VERTICAL)
        self.panel.SetSizer(vbox)
        self.elp = EditListPanel(self.panel, list)
        vbox.Add(self.elp, 0, wx.EXPAND | wx.ALIGN_CENTER | wx.RIGHT | wx.LEFT,
                 1)
        button = wx.Button(self.panel, wx.ID_ANY, "Apply")
        vbox.Add(button, 0, wx.ALIGN_RIGHT | wx.ALIGN_TOP)
        button.Bind(wx.EVT_BUTTON, self.onPanelApply)
        #        vbox.SetSizeHints(self)
        #        elp.GetSizer().SetSizeHints(self)

        sizer = self.GetSizer()
        sizer.Add(self.panel, 1, wx.EXPAND)
        self.GetTopLevelParent()._force_layout()
        self.callback = callback
        self.callback_obj = weakref.proxy(obj, self.onPanelClean)

    def onPanelApply(self, e):
        if self.callback_obj is not None:
            m = getattr(self.callback_obj, self.callback)
            m(self.elp.GetValue())
            self.ClosePanel()
        else:
            self.ClosePanel()

    def onPanelClean(self, ref):
        if self.panel is not None:
            self.ClosePanel()
            print('panel clean')

    def ClosePanel(self):
        self.GetSizer().Remove(self.panel)
        self.panel.Destroy()
        self.GetTopLevelParent()._force_layout()
        self.panel = None

    def onTD_Selection(self, evt):
        if len(evt.selections) < 2:
            croot = self.tree.GetRootItem()
            t0 = evt.GetTreeDict()
            print(t0)
            for item in self.walk_treectrl(croot):
                if t0 == self.tree.GetPyData(item): break

            # unbind temprorary to avoid change of event generation
            self.Unbind(wx.EVT_TREE_SEL_CHANGED)
            self.tree.SelectItem(item)
            dictobj = self.tree.GetPyData(item)
            if dictobj is not None:
                self.varviewer.fill_list(dictobj)
            self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged)

    def remove_item_from_tree(self):
        croot = self.tree.GetRootItem()
        for item in self.walk_treectrl(croot):
            treedict = self.tree.GetPyData(item)
            print(treedict.get_full_path())
            print(self.item_path(item))
            if treedict is None:
                #rm_list.append(item)
                self.tree.Delete(item)
                return True
            if (treedict.get_full_path() != self.item_path(item)):
                self.tree.Delete(item)
                return True

            if (treedict.get_parent() is None
                    and treedict is not self.get_proj()):
                self.tree.Delete(item)
                return True

        return False

    def item_path(self, item):
        path = []
        p = item
        croot = self.tree.GetRootItem()
        while p != croot:
            path = [self.tree.GetItemText(p)] + path
            p = self.tree.GetItemParent(p)
        path = [self.tree.GetItemText(p)] + path
        return '.'.join(path)

    def add_item_to_tree(self):
        croot = self.tree.GetRootItem()
        oge = self.walk_treectrl(croot)
        nge = self.get_proj().walk_tree()

        ntd = self.get_proj()
        otd = ntd
        ntd2 = ntd
        otd2 = ntd
        oitem = croot
        while True:
            try:
                ntd2 = nge.next()
                try:
                    oitem2 = oge.next()
                    otd2 = self.tree.GetPyData(oitem2)
                except Exception:
                    otd2 = None

                if ntd2 is not otd2:
                    #              if otd2 is not None: print otd2.get_full_

                    if ntd2.get_parent() is ntd:
                        #                 print "adding first child", ntd2.get_full_path()
                        self.fill_sub_tree(oitem,
                                           ntd2,
                                           sel_dict=None,
                                           first=True)
                        break

                    pitem = self.tree.GetItemParent(oitem)
                    while (self.tree.GetPyData(pitem)
                           is not ntd2.get_parent()):
                        oitem = pitem
                        pitem = self.tree.GetItemParent(pitem)

#              print "adding sibling", ntd2.get_full_path()
#              print "next to", self.tree.GetPyData(oitem).get_full_path()
                    self.fill_sub_tree(pitem, ntd2, sel_dict=None, sib=oitem)
                    break
                ntd = ntd2
                otd = otd2
                oitem = oitem2
            except StopIteration:
                return False

        return True

    def fill_sub_tree(self,
                      pitem,
                      treedict,
                      sel_dict=None,
                      sib=None,
                      first=False):

        name = treedict.name
        if treedict.status != '':
            label = name + ' (' + treedict.status + ')'
        else:
            label = name
        img = treedict.classimage()
        if sib is None:
            if first is True:
                parent2 = self.tree.InsertItemBefore(pitem, 0, label, img)
            else:
                parent2 = self.tree.AppendItem(pitem, label, img)
        else:
            parent2 = self.tree.InsertItem(pitem, sib, label, img)
        if treedict is sel_dict:
            self.tree.SelectItem(parent2)
        if treedict.is_suppress():
            self.tree.SetItemTextColour(parent2, wx.NamedColour('Grey'))
        if treedict.can_have_child():
            self.tree.SetItemHasChildren(parent2)

        self.tree.SetPyData(parent2, treedict)
        if treedict.isTreeLink():
            l = treedict.get_linkobj()
            if l is not None:
                tx = l.name
            else:
                tx = 'None'
            self.tree.SetItemText(parent2, '-> ' + name + '(' + tx + ')')
        else:
            for n2, child in treedict.get_children():
                self.fill_sub_tree(parent2, child, sel_dict=sel_dict)
        # self.tree.Expand(parent2)

        if treedict.is_visible():
            self.tree.Expand(pitem)
Beispiel #6
0
class FileHelperDialog(wx.Dialog):
    def __init__(self, parent, id=-1, title="File Action Setting"):

        p = SP().set_rule('file',
                          {'name': '', 'ext': '', 'action': '',
                           'action_txt': '', 'use': False})
        self.var = p.read_setting(pref)

        wx.Dialog.__init__(self, parent, id, title,
                           style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)

        self.mainSizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.mainSizer)

        self.cb = wx.ComboBox(self, wx.ID_ANY,
                              size=(-1, -1),
                              style=wx.CB_READONLY,
                              choices=[x['name'] for x in self.var['file']])
        self.mainSizer.Add(self.cb, 0, wx.ALL, 3)

        l = [["rule",   '', 200, None],
             ["action", '', 235, {'nlines': 3}],
             ["note", '', 0, None],
             [None, False, 3,  {'text': 'Use'}], ]

        self.elp = EditListPanel(self, l, edge=0, call_sendevent=self)
        self.elp.GetSizer().AddGrowableRow(1)

        self.mainSizer.Add(self.elp, 1, wx.ALL | wx.EXPAND, 2)

        self.buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.bnew = wx.Button(self, label="New...", id=wx.ID_ANY)
        self.bdel = wx.Button(self, label="Delete...", id=wx.ID_ANY)
        self.bok = wx.Button(self, label="OK", id=wx.ID_OK)

        self.buttonSizer.Add(self.bnew, 0, wx.ALL, 7)
        self.buttonSizer.Add(self.bdel, 0, wx.ALL, 7)
        self.buttonSizer.AddStretchSpacer(1)
        self.buttonSizer.Add(self.bok, 0, wx.ALL, 7)
        self.mainSizer.Add(self.buttonSizer, 0, wx.ALL | wx.EXPAND, 0)
        self.Bind(wx.EVT_BUTTON, self.onOk, id=wx.ID_OK)
        self.Bind(wx.EVT_BUTTON, self.onNew, self.bnew)
        self.Bind(wx.EVT_BUTTON, self.onDel, self.bdel)
        self.cb.Bind(wx.EVT_COMBOBOX, self.onCBHit)
        wx.CallAfter(self.Layout)

        self.set_panels_2_index0()

    def send_event(self, elp, evt0):
        for v in self.var['file']:
            if v['name'] == str(self.cb.GetValue()):
                value = self.elp.GetValue()
                v['ext'] = value[0]
                v['action'] = value[1]
                v['action_txt'] = value[2]
                v['use'] = value[3]
                break

    def set_elp(self):
        vv = self.var['file']
        for v in vv:
            if v['name'] == str(self.cb.GetValue()):
                self.elp.SetValue((str(v['ext']),
                                   str(v['action']),
                                   str(v['action_txt']), v['use']))
                break

    def update_cb(self):
        names = self.get_names()
        self.cb.Clear()
        for x in names:
            self.cb.Append(x)

    def get_names(self):
        names = [x['name'] for x in self.var['file']]
        return names

    def onCBHit(self, evt):
        for v in self.var['file']:
            if v['name'] == self._cb_value:
                value = self.elp.GetValue()
                v['ext'] = value[0]
                v['action'] = value[1]
                v['action_txt'] = value[2]
                v['use'] = value[3]
        self.set_elp()
        self._cb_value = str(self.cb.GetValue())

    def onOk(self, evt):
        for v in self.var['file']:
            if v['name'] == self._cb_value:
                value = self.elp.GetValue()
                v['ext'] = value[0]
                v['action'] = value[1]
                v['action_txt'] = value[2]
                v['use'] = value[3]
        if self.IsModal():
            self.EndModal(wx.ID_OK)
        else:
            self.Destroy()

    def onDel(self, evt):
        vv = self.var['file']
        self.var['file'] = [v for v in vv if v['name']
                            != str(self.cb.GetValue())]
        self.set_panels_2_index0()

    def set_panels_2_index0(self):
        names = self.get_names()
        self.update_cb()
        self.cb.SetValue(names[0])
        self._cb_value = names[0]
        self.set_elp()

    def onNew(self, evt):
        ret, new_name = dialog.textentry(self,
                                         "Enter the name of file type",
                                         "Add New FileType", '')
        if not ret:
            return
        if not new_name in self.get_names():
            v = {'name': new_name, 'ext': '*.*',
                 'action': '', 'action_txt': '', 'use': True}
        self.var['file'].append(v)
        self.update_cb()
        self.cb.SetValue(new_name)
        self._cb_value = new_name
        self.set_elp()
Beispiel #7
0
class dlg_jobsubmission(wx.Dialog):
    def __init__(self,
                 parent,
                 id=wx.ID_ANY,
                 title='',
                 value=None,
                 queues=None):

        if queues is None:
            queues = def_queues

        wx.Dialog.__init__(self,
                           parent,
                           wx.ID_ANY,
                           title,
                           style=wx.STAY_ON_TOP | wx.DEFAULT_DIALOG_STYLE
                           | wx.RESIZE_BORDER)

        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)

        self.SetSizer(vbox)
        vbox.Add(hbox2, 1, wx.EXPAND | wx.ALL, 1)

        q_names = [x['name'] for x in queues['queues']]
        dp_setting = {"style": wx.CB_DROPDOWN, "choices": q_names}

        if "keywords" in queues:
            log_keywords = queues["keywords"]
        else:
            log_keywords = ["production", "debug"]
        ll = elp_setting(log_keywords)
        ll[4] = ["Queue", q_names[0], 4, dp_setting]
        self.elp = EditListPanel(self, ll)

        hbox2.Add(self.elp, 1, wx.EXPAND | wx.RIGHT | wx.LEFT, 1)
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        button = wx.Button(self, wx.ID_ANY, "Cancel")
        button2 = wx.Button(self, wx.ID_ANY, "Submit")

        hbox.Add(button, 0, wx.EXPAND)
        hbox.AddStretchSpacer()
        hbox.Add(button2, 0, wx.EXPAND)
        vbox.Add(hbox, 0, wx.EXPAND | wx.ALL, 5)

        button.Bind(wx.EVT_BUTTON, self.onCancel)
        button2.Bind(wx.EVT_BUTTON, self.onSubmit)
        if value is not None:
            v, names = get_defaults()
            for k, n in enumerate(names):
                if n in value: v[k] = value[n]
            if not value[4] in q_names:
                value[4] = q_names[0]

            value7 = [False] * len(log_keywords)
            for name, v in value[7]:
                if name in log_keywords:
                    value7[log_keywords.index(name)] = v
            value[7] = value7

            self.elp.SetValue(value)

        #self.SetSizeHints(minH=-1, minW=size.GetWidth())
        self.SetSizeHints(minH=-1, minW=300)

        self.Layout()
        self.Fit()
        size = self.GetSize()
        width = max(len(value[5]) * 12, 550)
        width = min(width, 1200)
        self.SetSize((width, size.GetHeight()))
        self.CenterOnScreen()

        self.Show()
        #wx.CallAfter(self.Fit)
        self.value = self.elp.GetValue()

    def onCancel(self, evt):
        self.value = self.elp.GetValue()
        self.EndModal(wx.ID_CANCEL)

    def onSubmit(self, evt):
        self.value = self.elp.GetValue()

        if (self.value[6].strip() == ''
                or not any([x[1] for x in self.value[7]])):

            from ifigure.widgets.dialog import message
            message(
                self,
                title="Error",
                message="Enter job description and select at least one keyword"
            )
            return

        self.EndModal(wx.ID_OK)
Beispiel #8
0
class DlgPlotExpr(SimpleFramePlus):
    def __init__(self,
                 parent,
                 id=wx.ID_ANY,
                 title='Plot Expression',
                 **kwargs):

        iattr = kwargs.pop("iattr", [])

        style = (wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.RESIZE_BORDER
                 | wx.FRAME_FLOAT_ON_PARENT | wx.FRAME_TOOL_WINDOW)
        super(DlgPlotExpr, self).__init__(parent,
                                          id,
                                          title,
                                          style=style,
                                          **kwargs)

        self.parent = parent
        choices = list(parent.model.param.getvar('mfem_model')['Phys'])
        if len(choices) == 0:
            choices = ['No Physics is defined!']

        ll = [
            ['Expression', '', 0, {}],
            ['Index', ','.join(iattr), 0, {}],
            [None, 'Index: Domain (1D/2D) and Boundary (3D)', 2, {}],
            [
                'NameSpace', choices[0], 4, {
                    'style': wx.CB_READONLY,
                    'choices': choices
                }
            ],
            [None, ' ' * 50, 2, {}],
        ]
        self.elp = EditListPanel(self, ll)
        button = wx.Button(self, wx.ID_ANY, "Apply")

        box = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(box)
        box.Add(self.elp, 1, wx.EXPAND | wx.ALL, 1)

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.AddStretchSpacer()
        hbox.Add(button, 0, wx.ALL, 5)
        box.Add(hbox, 0, wx.EXPAND | wx.ALL, 1)

        button.Bind(wx.EVT_BUTTON, self.onApply)
        self.Show()
        self.Layout()
        self.Fit()

    def onApply(self, evt):
        value = self.elp.GetValue()
        self._doPlotExpr(value)
        evt.Skip()

    def _doPlotExpr(self, value):
        model = self.parent.model.param.getvar('mfem_model')
        if model is None: return

        expr = str(value[0])
        phys = str(value[3])
        use_2dplot = model['Phys'][phys].dim == 1

        from petram.utils import eval_expr
        try:
            engine = self.parent.engine
            d = eval_expr(model, engine, expr, value[1], phys=phys)
        except:
            dialog.showtraceback(parent=self,
                                 txt='Failed to evauate expression',
                                 title='Error',
                                 traceback=traceback.format_exc())
            return

        from ifigure.interactive import figure
        v = figure()
        v.update(False)
        v.suptitle(expr)
        if use_2dplot:
            for k in d.keys():
                v.plot(d[k][0][:, 0, 0].flatten(), d[k][1][:, 0].flatten())
            v.update(True)
        else:
            from petram.pi.dlg_plot_sol import setup_figure
            setup_figure(v, self.GetParent())
            for k in d.keys():
                v.solid(d[k][0], cz=True, cdata=d[k][1])
            v.update(True)
            v.view('noclip')
            v.lighting(light=0.5)