def ChooseLayout(root, mech, edict):
    if mech.buttonInhibit:
        return
    mech.buttonInhibit = 1

    layout = clients.GetLayoutSelection(root, mech.pcode, edict)
    if not layout:
        mech.buttonInhibit = 0
        return
    pathp = edict['DATAPATH'] + '\\' + mech.client[
        'client.clientid'] + '\\' + mech.pcode + '\\'
    # reload stuff
    presets = load_preset_file(mech, edict, mech.pcode, layout)
    if presets == None:
        ##print 'preset failure',mech.pcode,layout
        clientgui.deselect(mech.edict)
        mech._set_study_info(root)
        mech.buttonInhibit = 0
        return
    pathn = pathp + 'STAGES.' + layout
    edict['layout'] = layout
    st, d, stitle = stages.load_stages_from_file(pathn, edict, presets)
    if len(st) == 0:  # problem with user version so load system version
        ##print 'load problem'
        md = Pmw.MessageDialog(
            root,
            message_text='Session plan bad. Do you want to load the default?',
            defaultbutton=0,
            title='Load default plan',
            buttons=['Yes', 'No'])
        ans = md.activate()
        if ans != 'Yes':
            clientgui.deselect(mech, edict)
            mech.set_topwarnings(root)
            mech.buttonInhibit = 0
            return
        shutil.copy2(
            edict['PROGRAMPATH'] + '\\Preferences\\' + mech.pcode +
            '\\stages.' + layout, pathn)
        st, d, stitle = stages.load_stages_from_file(pathn, edict, presets)

    write_layout_file(pathp, layout, mech)
    ##print pathn,st
    mech.st = st
    d['pcode'] = mech.pcode
    mech.userinfo = d
    mech.stitle = stitle
    mech.st_save_path = pathn
    try:
        mech.canvas.itemconfigure(mech.canvlayout,
                                  text=clients.GetLayoutTitle(layout))
    except:
        pass
    mech.set_topwarnings(root)
    mech.buttonInhibit = 0
def SelectCustomPlan(root, mech, edict, client=None, pro=None):
    # somehow select a client first?????

    if mech.buttonInhibit:
        return
    if client == None:
        clientgui.deselect(nmech, edict)
        mech._set_study_info(root)
        mech.buttonInhibit = 1
        client = clients.SelectClient(root, 0, edict)
        if client == None:
            mech.buttonInhibit = 0
            return
        proto = clients.SelectProtocol(root)
        if proto == None:
            mech.buttonInhibit = 0
            return
        ask = None
    else:
        client = mech.client
        proto = pro
        ask = mech.layout
    pathing = edict['DATAPATH'] + '\\' + client[
        'client.clientid'] + '\\' + proto
    pathn = _selectcustom(root, client, proto, pathing, mech, edict, ask=ask)
    if pathn:
        ####mech.title=stitle
        mech.st_save_path = pathn
        try:
            mech.canvas.itemconfigure(mech.canvlayout,
                                      text=clients.GetLayoutTitle(layout))
        except:
            pass
        mech.set_topwarnings(root)
    mech.buttonInhibit = 0

    # ask - Do you want a specific default plan
    md = Pmw.MessageDialog(
        root,
        message_text='Do you want to load a custom session plan',
        defaultbutton=0,
        title='Option to select a custom session plan',
        buttons=['Yes', 'No'])
    ans = md.activate()
    if ans != None and ans == 'Yes':
        # if yes
        _selectcustom(root, client, proto, pathing, mech, edict)

    clients.NewClientIndexNeeded(root, edict, 1)
    mech.buttonInhibit = 0
    mech._set_study_info(root)
    return proto
def EditDefaultSessionPlan(root, which, mech, edict):

    if mech.state != None:
        return  # one thing at a time popped up

    if mech.buttonInhibit:
        return
    mech.buttonInhibit = 1
    clientgui.deselect(mech, edict)
    mech._set_study_info(root)
    mech.stagesave = which
    #need the system path!!!!
    layout = clients.GetLayoutSelection(root, which, edict)
    if not layout:
        mech.buttonInhibit = 0
        return
    presets = load_preset_file(mech, edict, which,
                               layout)  # also reload sequence file
    if presets == None:
        ##print 'preset error'
        mech.buttonInhibit = 0
        return  # load error
    spath, stitle = select_stages_path(root, edict['PROGRAMPATH'], which,
                                       layout)
    if not spath:
        mech.buttonInhibit = 0
        return  # cancel
    mech.st_save_path = spath
    edict['layout'] = layout
    lst = stages.load_stages_from_file(spath, edict, presets, stitle=stitle)
    if len(lst) == 2 and len(lst[0]) == 0:
        xpath = '%s\\PREFERENCES\\%s\\STAGES.%s' % (edict['PROGRAMPATH'],
                                                    which, 'INI')
        lst = stages.load_stages_from_file(xpath, edict, presets)
        stitle = '?????'
    if len(lst) < 2:
        st = []
    else:
        st = lst[0]
    mech.buttonInhibit = 1  # don't let user punch buttons during reload

    stagesetup(root,
               st,
               mech,
               edict,
               reason=':' + stitle + ' : ' + which,
               stitle=stitle)
    mech.buttonInhibit = 0
def EditDefaultFilterSets(root, whichproto, mech, edict, recall=None):
    "Edit the 'preset' choices for each protocol"

    if mech.state != None:
        return  # one thing at a time popped up
    try:
        if root.top != None:
            return
    except:
        pass
    if mech.buttonInhibit:
        return
    clientgui.deselect(mech, edict)
    mech.buttonInhibit = 1
    mech._set_study_info(root)

    def _cpbutton(sd, result, *other, **kw):
        sd._answer = result
        if result == 'Select':
            return
        sd.deactivate()

    if recall:
        layout = recall
    else:
        layout = clients.GetLayoutSelection(root, whichproto, edict)
        if not layout:
            mech.buttonInhibit = 0
            return

    while 1:  # just so continue after delete reruns me
        # first reload the defaults again
        presets = load_preset_file(mech, edict, whichproto, layout)
        if presets == None:
            mech.buttonInhibit = 0
            return
        mech.tempsave = presets
        mech.layout = layout

        # make choice list of all the settings for the selected protocol
        clist = []
        klist = []
        keylist = presets.keys()
        keylist.sort()
        for k in keylist:
            parts = string.split(k, '.')
            if len(parts) != 2:
                continue
            kvalue = string.strip(parts[1])[1:-1]  #remove parens
            fbmode = stages.validatefeedbackmode(parts[0], edict)
            if not fbmode:
                #print 'invalid fb mode ',parts[0],edict['modelist']
                continue  # bad format
            klist.append(k)  # contains keys  mode.(sitelist,0)
            pieces = string.split(kvalue,
                                  ',')  # remove parens and find tuple parts
            if len(pieces) > 2:
                sites = string.join(pieces[0:-1], ',')
            else:
                sites = pieces[0]

            ln = '%s> %-12s: %s' % (fbmode, string.upper(sites), presets[k])
            # Note: old display_presets function was used here but did
            # nothing except set g.display_format=edict['streamformat']
            stages.set_display_format(edict)  # might not be needed

            clist.append(ln)

        dv = {}
        sd = PmwAdded.ScrolledFrameDialog(
            root,
            title='Choose preset for ' + whichproto + ' ' +
            clients.GetLayoutTitle(layout),
            buttons=['Done', 'Edit', 'New', 'Delete'])
        sd.configure(command=Command(_cpbutton, sd))
        sf = sd.component('scrolledframe').interior()
        sd.component('scrolledframe').configure(horizflex='expand')
        bcolor = ['light yellow', 'LightBlue1']
        which = 0
        ivar = IntVar()
        ivar.set(0)  # initial selection
        sd._ivar = ivar
        for inx in range(len(clist)):
            Radiobutton(sf,
                        text=clist[inx],
                        variable=ivar,
                        value=inx,
                        borderwidth=3,
                        relief='raised',
                        command=Command(_cpbutton, sd, 'Select'),
                        bg=bcolor[which],
                        anchor='w').pack(side=TOP, expand=1, fill='x')
            which = 1 - which

        gpos = '+0+%d' % 60
        sd.activate(geometry=gpos)
        result = sd._answer

        if result == None or result == 'Done':
            del sd
            break  # done/window closed
        inx = int(sd._ivar.get())
        del sd
        if inx < len(clist):
            item = clist[inx]

            if result == 'Edit' or result == 'Delete':
                val = item
                index = inx
                if result == 'Delete':
                    del mech.tempsave[klist[index]]
                    IniAid.WriteConfig(mech.tempsave)
                    continue
        if result != 'Edit' and result != 'New':
            break  # outa here
        # now build entire stage thingy and try to edit
        if result == 'New':
            # must get mode selection
            ans = stages.selectfeedbackmode(root, edict)
            if ans == None:
                break
            parts = [ans, '', None]
        else:
            if len(clist) == 0:
                continue  # nothing there???
            parts = val.split('>')
            parts.append(klist[index])
        tp = common_stage_prep_stuff(root,
                                     presetremove,
                                     mech,
                                     edict,
                                     reason=' : Presets ' + whichproto)
        # parts is tuple with ('mode','sites:ranges $comments',key,presets_dict)
        ###stages.presetsetup(tp,edict,parts,presets)
        stages.presetsetup(tp, edict, parts,
                           int(edict['SETTINGS']['ShowAdvancedSites']))
        mech.state = whichproto
        break
    mech.buttonInhibit = 0
def stageremove(root, mech, edict, flag):

    ##print flag
    try:
        if mech.buttonInhibit:
            return  # whoa...still busy
    except:
        print mech
        raise
    st = None
    edict['layout'] = mech.layout
    if flag < 0:
        if (edict['SETTINGS']['LICENSEKIND'][0] == 'R' and
                not mech.allow) or mech.forceremote:  ## or mech.hasaccess==0:
            tkMessageBox.showwarning(
                'EEGer Remote User',
                '\n\n\nChanges to remote-use sessions cannot be made here.\n\nThe session plan stored in the remote-use drive\nis the ONLY session plan used!\n\n\nPlease contact your supervisor for session plan changes.',
                parent=root)
            return
        if flag == -1:
            try:
                if root.top != None:
                    root.top.destroy()
                root.top = None
            except:
                root.top = None
            ChooseLayout(root, mech, edict)
            layout = mech.layout
            if not mech.client:
                clientgui.deselect(mech, edict)
                return
            pathp = edict['DATAPATH'] + '\\' + mech.client[
                'client.clientid'] + '\\' + mech.pcode + '\\'
            # reload stuff
            presets = load_preset_file(mech, edict, mech.pcode, layout)
            if presets == None:
                ##print 'preset failure',mech.pcode,layout
                clientgui.deselect(mech, edict)
                return
            SelectCustomPlan(root,
                             mech,
                             edict,
                             client=mech.client,
                             pro=mech.pcode)

            pathn = pathp + 'STAGES.' + layout
            st, d, stitle = stages.load_stages_from_file(pathn, edict, presets)
            if len(st
                   ) == 0:  # problem with user version so load system version
                ##print 'load problem'
                md = Pmw.MessageDialog(
                    root,
                    message_text=
                    'Session plan bad. Do you want to load the default?',
                    defaultbutton=0,
                    title='Load default plan',
                    buttons=['Yes', 'No'])
                ans = md.activate()
                if ans != 'Yes':
                    clientgui.deselect(mech, edict)
                    return
                shutil.copy2(
                    edict['PROGRAMPATH'] + '\\Preferences\\' + mech.pcode +
                    '\\stages.' + layout, pathn)
                st, d, stitle = stages.load_stages_from_file(
                    pathn, edict, presets)

            write_layout_file(pathp, layout, mech)
        elif flag < -1:
            #here for the special  selections calm=-2/balance=-3/focus=-4
            pass
        else:
            # here for choose session plan
            SelectCustomPlan(root,
                             mech,
                             edict,
                             client=mech.client,
                             pro=mech.pcode)
            layout = mech.layout
            pathp = edict['DATAPATH'] + '\\' + mech.client[
                'client.clientid'] + '\\' + mech.pcode + '\\'
            # reload stuff
            presets = load_preset_file(mech, edict, mech.pcode, layout)
            pathn = pathp + 'STAGES.' + layout
            st, d, stitle = stages.load_stages_from_file(pathn, edict, presets)
            #stages.gensetup(root,st,client=mech.client,stitle=stitle, loadit=0)

        ##print pathn,st
        if st:
            mech.st = st
            d['pcode'] = mech.pcode
            mech.userinfo = d
            mech.stitle = stitle
            mech.st_save_path = pathn
            try:
                mech.canvas.itemconfigure(mech.canvlayout,
                                          text=clients.GetLayoutTitle(layout))
            except:
                pass
            mech.state = None
            stagesetup(root, st, mech, edict)
            mech._set_study_info(root)  # in case session plan changed
        mech.set_topwarnings(root)
        return
    if flag == 1:
        if stages.saveOK(edict) == 0:
            ##print 'NOT OK'
            return  # unable to save due to error
        if (edict['SETTINGS']['LICENSEKIND'][0] == 'R' and
                not mech.allow) or mech.forceremote:  ## or mech.hasaccess==0:
            tkMessageBox.showwarning(
                'EEGer Remote User',
                '\n\n\nChanges to remote-use sessions cannot be made here.\n\nThe session plan stored in the remote-use drive\nis the ONLY session plan used!\n\n\nPlease contact your supervisor for session plan changes.',
                parent=root)
        # must somehow retrieve set of stages
        st = stages.getstagelist()
        mech.st = st
        if mech.stagesave:
            stitle = stages.get_stitle()
            save_default_stages(st, mech.stagesave, mech, edict, stitle=stitle)
        else:
            stitle = stages.get_stitle()
            #save them to floppy
            if mech.floppy:
                if not FloppyAid.Inserted('A:\\'):
                    # make them put it back in
                    Require_floppy()
                #if not os.access('A:\\stages.ini',os.W_OK):
                #Require_writeable()
                stages.write_stages_to_file('A:\\stages.ini',
                                            st,
                                            mech.userinfo,
                                            stitle=stitle)
                mech.floppy = 0
            else:
                stages.write_stages_to_file(mech.st_save_path,
                                            st,
                                            mech.userinfo,
                                            stitle=stitle)
    else:
        stitle = ''
        if mech.st_save_path:
            presets = load_preset_file(mech, edict, mech.pcode, mech.layout)
            if presets == None:
                clientgui.deselect(mech, edict)
                mech.set_topwarnings(root)
            else:
                mech.st, d, stitle = stages.load_stages_from_file(
                    mech.st_save_path, edict, presets)
    if stitle != mech.stitle:
        mech.stitle = stitle
        mech._set_study_info(root)  # in case session plan changed
    else:
        mech.stitle = stitle
    try:
        if root.top != None:
            root.top.destroy()
        root.top = None
    except:
        root.top = None
    mech.state = None