Ejemplo n.º 1
0
 def __init__(self, root, mv, title="select a set:",
              command=None, mode="single", cwcfg=None):
     self.mv = mv
     pmvsets = self.getPmvSets()
     ListChooser.__init__(self, root, mode=mode, title=title, entries=pmvsets,
                 command=command, cwcfg=cwcfg)
     self.widget.configure(exportselection = False)
Ejemplo n.º 2
0
 def __init__(self,
              root,
              mv,
              title="select a set:",
              command=None,
              mode="single",
              cwcfg=None):
     self.mv = mv
     pmvsets = self.getPmvSets()
     ListChooser.__init__(self,
                          root,
                          mode=mode,
                          title=title,
                          entries=pmvsets,
                          command=command,
                          cwcfg=cwcfg)
     self.widget.configure(exportselection=False)
Ejemplo n.º 3
0
 def showChooser(self, entries):
     if self.cFlag == 1:
         self.palChooser.clear()
         list(map(self.palChooser.add, entries))
         self.root.deiconify()
     else:
         self.root = tkinter.Toplevel()
         self.chooserFrame = tkinter.Frame(self.root)
         self.palChooser = ListChooser(
             self.chooserFrame,
             mode='extended',
             title='Customized colors groups',
             entries=entries,
             command=self.addCustomCol,
         )
         self.cFlag = 1
         dismissChooser = tkinter.Button(self.chooserFrame,
                                         text='Dismiss',
                                         command=self.root.withdraw)
         self.palChooser.pack()
         dismissChooser.pack()
         self.chooserFrame.pack()
Ejemplo n.º 4
0
 def __init__(self, master, title = '', text = '',
              entries = (('',None),('',None)) , cancel = None,
              mode = 'single', list_width = None, list_height=None,
              list_font = None, list_command = None):
     
     assert mode in ['single', 'browse', 'multiple', 'extended' ]
     self.root = Tkinter.Toplevel(master)
     if title:
         self.root.title(title)
         self.root.iconname(title)
     self.entry = None
     self.entries = map(lambda x: x[0], entries)
     self.frame = Tkinter.Frame(self.root)
     self.frame.pack()
     self.root.bind('<Return>', self.return_event)
     list_cfg = {}
     if list_height:
         list_cfg['height']=list_height
     if list_width:
         list_cfg['width']=list_width
     
     self.listchooser = ListChooser(self.frame,
                                    title=text,
                                    entries = entries,
                                    lbwcfg=list_cfg,
                                    command=list_command)
     self.listchooser.pack(fill = Tkinter.BOTH, expand=1, padx=5, pady=5)
     ok_button = Tkinter.Button(self.frame, text="OK",
                    command=(lambda self=self, num=0: self.done(num)))
     ok_button.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH, expand=1)
     if cancel :
         cancel_button = Tkinter.Button(self.frame, text="Cancel",
                    command=(lambda self=self, num=1: self.done(num)))
         cancel_button.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH,
                            expand=1)
     if list_font:
         self.set_newfont(list_font)
     self.root.protocol('WM_DELETE_WINDOW', self.wm_delete_window)
 def showChooser(self, entries):
     if self.cFlag == 1:
         self.palChooser.clear()
         map(self.palChooser.add, entries)
         self.root.deiconify()
     else:
         self.root = Tkinter.Toplevel()
         self.chooserFrame = Tkinter.Frame(self.root)
         self.palChooser = ListChooser(self.chooserFrame, mode = 'extended',
                                      title='Customized colors groups',
                                       entries = entries,
                                       command=self.addCustomCol,)
         self.cFlag=1
         dismissChooser = Tkinter.Button(self.chooserFrame,
                                         text='Dismiss',
                                         command=self.root.withdraw)
         self.palChooser.pack()
         dismissChooser.pack()
         self.chooserFrame.pack()
Ejemplo n.º 6
0
class ListChooserDialog:
    """A dialog widget consisting of a ListChooser, an 'OK' button and
    an optional 'Cancel' button."""

    def __init__(self, master, title = '', text = '',
                 entries = (('',None),('',None)) , cancel = None,
                 mode = 'single', list_width = None, list_height=None,
                 list_font = None, list_command = None):
        
        assert mode in ['single', 'browse', 'multiple', 'extended' ]
        self.root = Tkinter.Toplevel(master)
        if title:
            self.root.title(title)
            self.root.iconname(title)
        self.entry = None
        self.entries = map(lambda x: x[0], entries)
        self.frame = Tkinter.Frame(self.root)
        self.frame.pack()
        self.root.bind('<Return>', self.return_event)
        list_cfg = {}
        if list_height:
            list_cfg['height']=list_height
        if list_width:
            list_cfg['width']=list_width
        
        self.listchooser = ListChooser(self.frame,
                                       title=text,
                                       entries = entries,
                                       lbwcfg=list_cfg,
                                       command=list_command)
        self.listchooser.pack(fill = Tkinter.BOTH, expand=1, padx=5, pady=5)
        ok_button = Tkinter.Button(self.frame, text="OK",
                       command=(lambda self=self, num=0: self.done(num)))
        ok_button.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH, expand=1)
        if cancel :
            cancel_button = Tkinter.Button(self.frame, text="Cancel",
                       command=(lambda self=self, num=1: self.done(num)))
            cancel_button.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH,
                               expand=1)
        if list_font:
            self.set_newfont(list_font)
        self.root.protocol('WM_DELETE_WINDOW', self.wm_delete_window)

    def go(self):
        self.root.grab_set()
        self.root.mainloop()
        self.root.destroy()
        return self.entry

    def return_event(self, event):
        if self.default is None:
            self.root.bell()
        else:
            self.done(self.default)

    def wm_delete_window(self):
        if self.cancel is None:
            self.root.bell()
        else:
            self.done(self.cancel)

    def choseEntry(self, entry):
        self.entry = entry
        
    def done(self, num):
        if num == 0:
            self.entry = self.listchooser.get()
        elif num == 1:
            self.entry = []
        self.root.quit()

    def setentry(self, index):
        ent = self.entries[index]
        self.listchooser.set(ent)

    def set_newfont(self, newfont):
        self.changefont(self.root, newfont)

    def changefont(self, wid, newfont):
        try:
            wid.config(font=newfont)
        except :
            pass
        if len(wid.children)==0: return
        for item in wid.children.values():
            self.changefont(item, newfont)
Ejemplo n.º 7
0
class ColorChooser(Chooser):

    colors = [
        '#FF8284', '#ffff84', '#84ff84', '#00ff84', '#84ffff', '#0082ff',
        '#ff82c6', '#ff82ff', '#ff0000', '#ffff00', '#84ff00', '#00ff42',
        '#00ffff', '#0082c6', '#8482c6', '#ff00ff', '#844142', '#ff8242',
        '#00ff00', '#008284', '#004184', '#8482ff', '#840042', '#ff0084',
        '#840000', '#ff8200', '#008200', '#008242', '#0000ff', '#0000a5',
        '#840084', '#8400ff', '#420000', '#844100', '#004100', '#004142',
        '#000084', '#000042', '#420042', '#420084', '#000000', '#848200',
        '#848242', '#848284', '#428284', '#c6c3c6', '#6b0c94', '#ffffff',
        '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF',
        '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF',
        '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF',
        '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF'
    ]

    def __new__(cls,
                master=None,
                title='Chooser',
                commands=None,
                immediate=0,
                exitFunction=None):

        #the following code was added to avoid having multiple copies of ColorChoosers
        global colorChoosersDict
        if title in colorChoosersDict:
            try:
                colorChoosersDict[title].master.destroy()
            except:
                pass

        self = object.__new__(cls)
        self.exitFunc = exitFunction
        self.mapping = {}
        self.currentTag = None
        self.rcPath = getResourceFolder()
        self.customColorsPath = os.path.join(self.rcPath, 'customColors')
        if os.path.exists(self.customColorsPath):
            customColors = open(self.customColorsPath).read().strip()
            customCols = customColors.split()
            self.colors[48:48 + len(customCols)] = customCols

        Chooser.__init__(self,
                         master=master,
                         title=title,
                         commands=commands,
                         immediate=immediate,
                         exitFunction=exitFunction)

        if self.ownmaster:
            ## create dismiss button
            if exitFunction:
                cb = exitFunction
            else:
                cb = self.master.destroy
            self.dismissb = tkinter.Button(self.master,
                                           text='DISMISS',
                                           command=cb)
            self.dismissb.pack(side='bottom', expand=1, fill='x')

        try:
            self.master.protocol('WM_DELETE_WINDOW', self.exit)
        except:
            pass

        colorChoosersDict[title] = self
        return self

    def __init__(self,
                 master=None,
                 title='Chooser',
                 commands=None,
                 immediate=0,
                 exitFunction=None):
        pass

    def createChooser(self):
        self.ccFrame = tkinter.Frame(self.mainFrame)
        self.menuBar.forget()

        ##         self.menuBar.addmenuitem('File', 'command', 'Load custom',
        ##                                  command = self.load,
        ##                                  label='Load')

        ##         self.menuBar.addmenuitem('File', 'command', 'Save Colors',
        ##                                  command = self.save_cb,
        ##                                  label='Save')

        ##         self.menuBar.addmenuitem('File', 'separator')

        ##         self.menuBar.addmenuitem('File', 'command', 'Exit',
        ##                                  command=self.exit,
        ##                                  label='Exit')

        ##         self.menuBar.addmenu('Edit', 'editing commands')

        ##         self.menuBar.addmenuitem('Edit', 'command','Add New Color',
        ##                                  command = self.addColor,
        ##                                  label='Add New Color')
        ##         self.add = 0

        ##         self.menuBar.addmenuitem('Edit', 'command','Edit Custom Color',
        ##                                  command = self.editColor,
        ##                                  label='Edit Selected Color')
        self.edit = 0

        ##         self.menuBar.addmenuitem('Edit', 'command','Hide Color Editor',
        ##                                  command = self.hideCE,
        ##                                  label='Hide Color Editor')
        # Here we are creating the part of the widget that will contain the
        # chips.
        # ccFrame is the left part of the widget
        self.ccFrame.pack(side='left', expand=1, fill='both')
        self.addButton = tkinter.Button(self.ccFrame,
                                        text='Add to custom',
                                        command=self.addToCustom_cb)
        self.addHidden = 1

        # The chips frame will contain the color chips which are RadioSelect
        # and it is a scrolledFrame.
        chipsSFrame = Pmw.Group(self.ccFrame, tag_text='Basic colors:')
        #chipsSFrame = Pmw.ScrolledFrame(self.ccFrame, usehullsize=1,
        #                                hull_width=130,
        #                                hull_height=200,
        #                                hscrollmode = 'none')
        chipsSFrame.pack(padx=5, pady=3)  #, fill = 'both', expand = 1)

        # Create the RadioSelect empty
        self.chipsFrame = chipsSFrame.interior()

        self.colorVar = colorVar = tkinter.IntVar(0)
        colors = self.colors
        for i in range(6):
            for j in range(8):
                val = i * 8 + j
                col = colors[val]
                b = tkinter.Radiobutton(self.chipsFrame,
                                        text="",
                                        variable=colorVar,
                                        value=val,
                                        bg=col,
                                        activebackground=col,
                                        fg=col,
                                        activeforeground=col,
                                        indicatoron=0,
                                        selectcolor=col,
                                        width=2,
                                        height=1,
                                        command=self.selectColor)
                b.grid(row=i, column=j)

        customFrame = Pmw.Group(self.ccFrame, tag_text='Custom colors')
        self.customchipsFrame = customFrame.interior()
        self.custombuttons = []
        for i in range(3):
            for j in range(8):
                val = 48 + i * 8 + j
                col = colors[val]
                b = tkinter.Radiobutton(self.customchipsFrame,
                                        text="",
                                        variable=colorVar,
                                        value=val,
                                        bg=col,
                                        activebackground=col,
                                        fg=col,
                                        activeforeground=col,
                                        indicatoron=0,
                                        selectcolor=col,
                                        width=2,
                                        height=1,
                                        command=self.selectColor)
                b.grid(row=i, column=j)
                self.custombuttons.append(b)

        customFrame.pack(padx=5, pady=3)  #, fill = 'both', expand = 1)

        #self.colorChips=Pmw.RadioSelect(self.chipsFrame,
        #                                label_text='Default Colors',
        #                                labelpos='nw', orient='vertical',
        #                                buttontype='radiobutton',
        #                                command = self.colButton_cb)

        #self.mod = {}
        #execfile(self.customFilename, self.mod)
        #self.cFlag=0
        #self.addCustomCol(paletteName = self.colorsName)
        #self.doubleClick = False
        #self.editColor()
        #self.ce.pack(side = 'right', fill='both', expand=1)
        self.ce.immediate = 1
        self.ce.cw.immediate = 1
        self.currentEditingCB = None

    def selectColor(self, event=None):
        colNum = self.colorVar.get()

        hcol = self.colors[colNum]
        rgb = int(hcol[1:3], 16), int(hcol[3:5], 16), int(hcol[5:7], 16)
        col = [x / 255. for x in rgb]

        if colNum > 47:  # custom color
            self.ce.pack(side='right', fill='both', expand=1)
            if self.currentEditingCB:
                self.ce.cbManager.RemoveCallback(self.currentEditingCB)
            cb = CallbackFunction(self.editCustom, custColNum=colNum - 48)
            self.ce.cbManager.AddCallback(cb)
            self.ce.set(col, trigger=0)
            self.currentEditingCB = cb
        else:
            self.ce.pack_forget()

        self.cbManager.CallCallbacks(col)

    def editCustom(self, col, custColNum=0):
        hexcol = ToHEX(col)
        self.custombuttons[custColNum].configure(bg=hexcol,
                                                 activebackground=hexcol,
                                                 fg=hexcol,
                                                 activeforeground=hexcol,
                                                 selectcolor=hexcol)
        self.colors[48 + custColNum] = hexcol
        self.cbManager.CallCallbacks(col)
        try:
            outFile = open(self.customColorsPath, 'w')
        except Exception as inst:
            print(inst)
            print("Can't save custom colors in ", self.customColorsPath)
            return
        outFile.write(' '.join(self.colors[48:]))

    ## def load(self):
    ##     ftypes = [ ('Python files', '*.py') ]
    ##     filename = fileOpenAsk(self.master, types=ftypes,
    ##                            title='Load custom colors' )
    ##     # Open the module
    ##     if filename is None: return
    ##     self.customFilename = filename
    ##     self.mod = {}
    ##     execfile( self.customFilename, self.mod)
    ##     self.mod.keys()
    ##     colName = filter(lambda x: x[:2]!='__',self.mod.keys())
    ##     entries = map(lambda x: (x, None), colName)
    ##     # From the module display the available colorPalette.
    ##     self.showChooser(entries)

    def showChooser(self, entries):
        if self.cFlag == 1:
            self.palChooser.clear()
            list(map(self.palChooser.add, entries))
            self.root.deiconify()
        else:
            self.root = tkinter.Toplevel()
            self.chooserFrame = tkinter.Frame(self.root)
            self.palChooser = ListChooser(
                self.chooserFrame,
                mode='extended',
                title='Customized colors groups',
                entries=entries,
                command=self.addCustomCol,
            )
            self.cFlag = 1
            dismissChooser = tkinter.Button(self.chooserFrame,
                                            text='Dismiss',
                                            command=self.root.withdraw)
            self.palChooser.pack()
            dismissChooser.pack()
            self.chooserFrame.pack()

    ## def hideCE(self):
    ##     if self.hidden == 0:
    ##         self.ce.pack_forget()
    ##         self.hidden=1
    ##     if self.addHidden == 0:
    ##         self.addButton.pack_forget()
    ##         self.addHidden=1
    ##     self.add =0
    ##     self.edit=0

    ## def addCustomCol(self, event=None, paletteName=None):
    ##     if paletteName is None:
    ##         paletteName = self.palChooser.get()[0]
    ##         self.colorsName = paletteName
    ##     # first clean up what is there:
    ##     if not self.mod.has_key(paletteName):
    ##         self.colDict={}
    ##         return
    ##     else:
    ##         self.colDict = self.mod[paletteName]
    ##     if len(self.colorChips._buttonList)!=0:
    ##         self.colorChips.deleteall()

    ##     self.colorChips.configure(label_text=paletteName)
    ##     items = self.colDict.items()
    ##     items.sort()
    ##     for name, value in items:
    ##         fg = col = ToHEX(value)
    ##         try:
    ##             int(name)
    ##         except:
    ##             fg = 'black'
    ##         self.colorChips.add(name, bg = col,
    ##                             activebackground=col,
    ##                             fg = fg, activeforeground = col,
    ##                             indicatoron=0,selectcolor=col,
    ##                             width=10,height=1,
    ##                             value = name)
    ##     self.colorChips.pack(fill='x', expand=1)
    ##     self.ce.cbManager.AddCallback(self.editChip)

    ##     if hasattr(self, 'chooserFrame'):
    ##         self.chooserFrame.master.withdraw()

    ## def save_cb(self, fileName = None, paletteName=None):
    ##     """Save the color palette """
    ##     if paletteName is None or fileName is None:
    ##         if hasattr(self, 'saveHidden'):
    ##             if self.saveHidden == 1:
    ##                 self.root.deiconify()
    ##                 self.saveHidden = 0
    ##         else:
    ##             self.root = Tkinter.Toplevel()
    ##             self.saveFrame = Tkinter.Frame(self.root, )
    ##             groupFrame = Tkinter.Frame(self.saveFrame)
    ##             self.groupEntry = Pmw.EntryField(groupFrame,
    ##                                              label_text='Group name:',
    ##                                              labelpos='w',
    ##                                              value=self.colorsName)
    ##             label = Tkinter.Label(groupFrame, text="\t\t",
    ##                                   )
    ##             self.groupEntry.pack(side='left')
    ##             label.pack(side='right', fill='x', expand=1)
    ##             groupFrame.pack(fill='x', expand=1)

    ##             fileFrame = Tkinter.Frame(self.saveFrame)

    ##             self.fileEntry = Pmw.EntryField(fileFrame,
    ##                                             label_text='Python File name:',
    ##                                             labelpos='w',
    ##                                             value=self.customFilename)

    ##             browseBut = Tkinter.Button(fileFrame, text='Browse',
    ##                                        command=self.browse)
    ##             self.fileEntry.pack(side='left')
    ##             browseBut.pack(side='right', fill='x', expand=1)
    ##             fileFrame.pack(fill='x', expand=1)

    ##             buttonFrame = Tkinter.Frame(self.saveFrame)
    ##             ok = Tkinter.Button(buttonFrame, text='OK', command=self.ok)
    ##             cancel = Tkinter.Button(buttonFrame, text='Cancel',
    ##                                     command=self.cancel)
    ##             ok.pack(side='left', fill='x',expand=1)
    ##             cancel.pack(side='right', fill='x', expand=1)
    ##             buttonFrame.pack(side='bottom', fill='both', expand=1)
    ##             self.saveFrame.pack(fill='both', expand=1)

    ##             self.saveHidden = 0

    def ok(self):
        filename = self.fileEntry.get()
        groupname = self.groupEntry.get()
        if not groupname:
            print('ERROR')
        self.save(filename, groupname)
        self.root.withdraw()

    def save(self, filename, groupname):
        if filename is None: return
        if not os.path.isfile(filename):
            f = open(filename, 'w')
            s = groupname + '=' + repr(self.colDict)
            f.write(s)
            f.write('\n')
            f.close()
        else:
            mod = {}
            exec(compile(open(filename, "rb").read(), filename, 'exec'), mod)
            colName = [x for x in dir(list(mod.keys())) if x[:2] != '__']
            if groupname in colName:
                f = open(filename, 'w')
                for name in colName:
                    if name == groupname:
                        s = groupname + '=' + repr(self.colDict)
                    else:
                        dict = getattr(self.mod, name)
                        s = name + '=' + repr(dict)
            else:
                f = open(filename, 'w')
                f.write('\n')
                s = groupname + '=' + repr(self.colDict)
            f.write(s)
            f.write('\n')
            f.close()

    def cancel(self):
        self.root.withdraw()
        self.saveHidden = 1

    def browse(self):
        ftypes = [('Python files', '*.py')]

        filename = fileSaveAsk(self.master,
                               types=ftypes,
                               title='Save custom colors')
        if filename:
            self.fileEntry.setentry(filename)

    def hide(self):
        if hasattr(self.masterFrame.master, 'withdraw'):
            try:
                self.masterFrame.master.withdraw()
            except:
                pass

    ## def exit(self):
    ##     self.hideCE()
    ##     if self.exitFunc is None:
    ##         if hasattr(self.masterFrame.master,'withdraw'):
    ##             self.masterFrame.master.withdraw()
    ##     else:
    ##         self.exitFunc()

    ## def editColor(self):
    ##     if self.edit == 1:
    ##         return
    ##     self.edit = 1
    ##     if self.hidden == 1:
    ##         self.ce.pack(side = 'right', fill='both', expand=1)
    ##         self.hidden = 0
    ##     else:
    ##         if self.add == 0:
    ##             self.ce.pack_forget()
    ##             self.hidden=1
    ##     if self.addHidden == 0:
    ##         self.addButton.pack_forget()
    ##         self.addHidden=1
    ##     self.ce.immediate=1
    ##     self.add = 0

    def addColor(self):
        if self.add == 1: return
        if self.hidden:
            self.ce.pack(side='right', fill='both', expand=1)
            self.hidden = 0
        else:
            if self.edit == 0:
                self.ce.pack_forget()
                self.hidden = 1
        if self.addHidden:
            self.addButton.pack(side='bottom', fill='x', expand=1)
            self.addHidden = 0
        self.ce.immediate = 0
        self.add = 1
        self.edit = 0

    #####################################################################
    #####     CALLBACKS
    ####################################################################
    def editChip(self, col):
        hexcol = ToHEX(col)
        chipName = self.colorChips.getcurselection()
        if chipName is None: return
        chip = self.colorChips.button(chipName)
        chip.configure(bg=hexcol,
                       fg=hexcol,
                       activebackground=hexcol,
                       activeforeground=hexcol,
                       selectcolor=hexcol)
        self.colDict[chipName] = col

    def colButton_cb(self, tag):
        #this is needed to self.colorChips._buttonList working
        if tag in list(self.mapping.keys()):
            tag = self.mapping[tag]

        col = self.colDict[tag]
        self.ce.set(col)
        if self.edit == 0 or self.add == 0:
            self.cbManager.CallCallbacks(col)

        if self.doubleClick:
            if self.currentTag != tag:
                self.currentTag = tag
                return
            self.doubleClick = False
            dialog = Pmw.PromptDialog(
                self.master,
                title='Color Name Dialog',
                label_text='Enter text to label this color:',
                entryfield_labelpos='n',
                buttons=('OK', 'Cancel'))
            result = dialog.activate()
            if result == 'OK':
                txt = dialog.get()
                fg = 'black'
                if not txt:
                    txt = str(len(self.colDict) + 1)
                    fg = col
                self.colorChips.button(
                    self.colorChips.index(
                        self.colorChips.selection)).configure(text=txt,
                                                              fg=fg,
                                                              value=txt)
                color = self.colDict.pop(tag)
                self.colDict[txt] = color
                self.mapping[tag] = txt
                self.save(self.customFilename, self.colorsName)

        else:
            self.doubleClick = True
            self.master.after(1000, self.setDoubleClick)

    def setDoubleClick(self):
        self.doubleClick = False

    def addToCustom_cb(self):
        rgbcol = self.ce.get()
        newKey = str(len(self.colDict) + 1)
        while newKey in self.colDict:
            newKey = str(int(newKey) + 1)
        self.colDict[newKey] = rgbcol
        col = ToHEX(rgbcol)
        self.colorChips.add(newKey,
                            bg=col,
                            activebackground=col,
                            fg=col,
                            activeforeground=col,
                            indicatoron=0,
                            selectcolor=col,
                            width=10,
                            height=1,
                            value=newKey)
        try:
            self.save(self.customFilename, self.colorsName)
        except Exception as inst:
            print(inst)
class ColorChooser(Chooser):
    def __init__(self, master=None, title = 'Chooser', commands = None,
                 immediate=0, exitFunction=None, colorsFile=None,
                 colorsName=None):
        
        self.exitFunc = exitFunction
        self.mapping = {}
        self.currentTag = None
        if colorsFile is None or colorsName is None:
            path = getResourceFolder()
            if not path:
                path = __import__('mglutil').__path__
            if not os.path.exists(os.path.join(path,'defaultColors.py')):
                   import shutil
                   shutil.copy(os.path.join(__import__('mglutil').__path__[0],'gui/BasicWidgets/Tk/defaultColors.py'),
                               os.path.join(path,'defaultColors.py'))
            self.customFilename = os.path.join(path,'defaultColors.py')
            self.colorsName = 'defaultColor'

        else:
            self.customFilename = colorsFile
            self.colorsName = colorsName
            
        Chooser.__init__(self, master=master, title=title, commands = commands,
                         immediate=immediate, exitFunction=exitFunction)
        try:
            self.master.protocol('WM_DELETE_WINDOW', self.exit)
        except:
            pass 

    def createChooser(self):
        self.ccFrame = Tkinter.Frame(self.mainFrame)
        

        self.menuBar.addmenuitem('File', 'command', 'Load custom',
                                 command = self.load,
                                 label='Load')

        self.menuBar.addmenuitem('File', 'command', 'Save Colors',
                                 command = self.save_cb,
                                 label='Save')

        self.menuBar.addmenuitem('File', 'separator')

        self.menuBar.addmenuitem('File', 'command', 'Exit',
                                 command=self.exit,
                                 label='Exit')
        
        self.menuBar.addmenu('Edit', 'editing commands')

        self.menuBar.addmenuitem('Edit', 'command','Add New Color',
                                 command = self.addColor,
                                 label='Add New Color')
        self.add = 0

        self.menuBar.addmenuitem('Edit', 'command','Edit Custom Color',
                                 command = self.editColor,
                                 label='Edit Selected Color')
        self.edit = 0

        self.menuBar.addmenuitem('Edit', 'command','Hide Color Editor',
                                 command = self.hideCE,
                                 label='Hide Color Editor')
        # Here we are creating the part of the widget that will contain the
        # chips.
        # ccFrame is the left part of the widget
        self.ccFrame.pack(side='left',expand=1, fill='both')
        self.addButton = Tkinter.Button(self.ccFrame, text='Add to custom',
                                        command=self.addToCustom_cb)
        self.addHidden = 1

        # The chips frame will contain the color chips which are RadioSelect
        # and it is a scrolledFrame.
        chipsSFrame = Pmw.ScrolledFrame(self.ccFrame, usehullsize=1,
                                        hull_width=130,
                                        hull_height=200,
                                        hscrollmode = 'none')
        chipsSFrame.pack(padx = 5, pady = 3, fill = 'both', expand = 1)
        
        # Create the RadioSelect empty
        self.chipsFrame = chipsSFrame.interior()
        
        self.colorChips=Pmw.RadioSelect(self.chipsFrame,
                                        label_text='Default Colors',
                                        labelpos='nw', orient='vertical',
                                        buttontype='radiobutton',
                                        command = self.colButton_cb)

        self.mod = {}
        execfile(self.customFilename, self.mod)
        self.cFlag=0
        self.addCustomCol(paletteName = self.colorsName)
        self.doubleClick = False
        
                
    def load(self):
        ftypes = [ ('Python files', '*.py') ]
        filename = fileOpenAsk(self.master, types=ftypes,
                               title='Load custom colors' )
        # Open the module
        if filename is None: return
        self.customFilename = filename
        self.mod = {}
        execfile( self.customFilename, self.mod)
        self.mod.keys()
        colName = filter(lambda x: x[:2]!='__',self.mod.keys())
        entries = map(lambda x: (x, None), colName)
        # From the module display the available colorPalette.
        self.showChooser(entries)
                                 
    def showChooser(self, entries):
        if self.cFlag == 1:
            self.palChooser.clear()
            map(self.palChooser.add, entries)
            self.root.deiconify()
        else:
            self.root = Tkinter.Toplevel()
            self.chooserFrame = Tkinter.Frame(self.root)
            self.palChooser = ListChooser(self.chooserFrame, mode = 'extended',
                                         title='Customized colors groups',
                                          entries = entries,
                                          command=self.addCustomCol,)
            self.cFlag=1
            dismissChooser = Tkinter.Button(self.chooserFrame,
                                            text='Dismiss',
                                            command=self.root.withdraw)
            self.palChooser.pack()
            dismissChooser.pack()
            self.chooserFrame.pack()
            
    def hideCE(self):
        if self.hidden == 0:
            self.ce.pack_forget()
            self.hidden=1
        if self.addHidden == 0:
            self.addButton.pack_forget()
            self.addHidden=1
        self.add =0
        self.edit=0
        

    def addCustomCol(self, event=None, paletteName=None):
        if paletteName is None:
            paletteName = self.palChooser.get()[0]
            self.colorsName = paletteName
        # first clean up what is there:
        if not self.mod.has_key(paletteName):
            self.colDict={}
            return
        else:
            self.colDict = self.mod[paletteName]
        if len(self.colorChips._buttonList)!=0:
            self.colorChips.deleteall()

        self.colorChips.configure(label_text=paletteName)
        items = self.colDict.items()
        items.sort()
        for name, value in items:
            fg = col = ToHEX(value)
            try:
                int(name)
            except:
                fg = 'black'
            self.colorChips.add(name, bg = col,
                                activebackground=col,
                                fg = fg, activeforeground = col,
                                indicatoron=0,selectcolor=col,
                                width=10,height=1,
                                value = name)
        self.colorChips.pack(fill='x', expand=1)
        self.ce.cbManager.AddCallback(self.editChip)
        
        if hasattr(self, 'chooserFrame'):
            self.chooserFrame.master.withdraw()

    def save_cb(self, fileName = None, paletteName=None):
        """Save the color palette """
        if paletteName is None or fileName is None:
            if hasattr(self, 'saveHidden'):
                if self.saveHidden == 1:
                    self.root.deiconify()
                    self.saveHidden = 0
            else:
                self.root = Tkinter.Toplevel()
                self.saveFrame = Tkinter.Frame(self.root, )
                groupFrame = Tkinter.Frame(self.saveFrame)
                self.groupEntry = Pmw.EntryField(groupFrame,
                                                 label_text='Group name:',
                                                 labelpos='w',
                                                 value=self.colorsName)
                label = Tkinter.Label(groupFrame, text="\t\t",
                                      )
                self.groupEntry.pack(side='left')
                label.pack(side='right', fill='x', expand=1)
                groupFrame.pack(fill='x', expand=1)

                fileFrame = Tkinter.Frame(self.saveFrame)

                self.fileEntry = Pmw.EntryField(fileFrame, 
                                                label_text='Python File name:',
                                                labelpos='w',
                                                value=self.customFilename)

                browseBut = Tkinter.Button(fileFrame, text='Browse',
                                           command=self.browse)
                self.fileEntry.pack(side='left')
                browseBut.pack(side='right', fill='x', expand=1)
                fileFrame.pack(fill='x', expand=1)

                buttonFrame = Tkinter.Frame(self.saveFrame)
                ok = Tkinter.Button(buttonFrame, text='OK', command=self.ok)
                cancel = Tkinter.Button(buttonFrame, text='Cancel',
                                        command=self.cancel)
                ok.pack(side='left', fill='x',expand=1)
                cancel.pack(side='right', fill='x', expand=1)
                buttonFrame.pack(side='bottom', fill='both', expand=1)
                self.saveFrame.pack(fill='both', expand=1)
                
                self.saveHidden = 0

    def ok(self):
        filename= self.fileEntry.get()
        groupname = self.groupEntry.get()
        if not groupname:
            print 'ERROR'
        self.save(filename, groupname)
        self.root.withdraw()
        
    def save(self, filename, groupname):
        if filename is None: return
        if not os.path.isfile(filename):
            f = open(filename, 'w')
            s = groupname+'='+repr(self.colDict)
            f.write(s)
            f.write('\n')
            f.close()
        else:
            mod = {}
            execfile(filename, mod)
            colName = filter(lambda x: x[:2]!='__',dir(mod.keys()))
            if groupname in colName:
                f = open(filename, 'w')
                for name in colName:
                    if name == groupname:
                        s = groupname+'='+repr(self.colDict)
                    else:
                        dict = getattr(self.mod,name)
                        s = name+'='+repr(dict)
            else:
                f = open(filename, 'w')
                f.write('\n')
                s = groupname+'='+repr(self.colDict)
            f.write(s)
            f.write('\n')
            f.close()
                
    def cancel(self):
        self.root.withdraw()
        self.saveHidden=1

    def browse(self):
        ftypes = [ ('Python files', '*.py') ]

        filename = fileSaveAsk(self.master,  types=ftypes,
                               title='Save custom colors')
        if filename:
            self.fileEntry.setentry(filename)

    def hide(self):
        if hasattr(self.masterFrame.master,'withdraw'):
            self.masterFrame.master.withdraw()
        
    def exit(self):
        self.hideCE()
        if self.exitFunc is None:
            if hasattr(self.masterFrame.master,'withdraw'):
                self.masterFrame.master.withdraw()
        else:
            self.exitFunc()

    def editColor(self):
        if self.edit == 1:
            return
        self.edit = 1
        if self.hidden == 1:
            self.ce.pack(side = 'right', fill='both', expand=1)
            self.hidden = 0
        else:
            if self.add == 0:
                self.ce.pack_forget()
                self.hidden=1
        if self.addHidden == 0:
            self.addButton.pack_forget()
            self.addHidden=1
        self.ce.immediate=1
        self.add = 0

    def addColor(self):
        if self.add ==1: return
        if self.hidden:
            self.ce.pack(side = 'right', fill='both', expand=1)
            self.hidden=0
        else:
            if self.edit == 0:
                self.ce.pack_forget()
                self.hidden=1
        if self.addHidden:
            self.addButton.pack(side = 'bottom', fill='x', expand=1)
            self.addHidden=0
        self.ce.immediate=0
        self.add = 1
        self.edit = 0

        
    #####################################################################
    #####     CALLBACKS
    ####################################################################
    def editChip(self, col):
        hexcol = ToHEX(col)
        chipName = self.colorChips.getcurselection()
        if chipName is None: return
        chip = self.colorChips.button(chipName)
        chip.configure(bg=hexcol, fg=hexcol, activebackground=hexcol,
                       activeforeground=hexcol, selectcolor=hexcol)
        self.colDict[chipName]=col
            
    def colButton_cb(self, tag):
        #this is needed to self.colorChips._buttonList working
        if tag in self.mapping.keys():
            tag = self.mapping[tag]
        
        col = self.colDict[tag]
        self.ce.set(col)
        if self.edit == 0 or self.add==0:
            self.cbManager.CallCallbacks(col)
            
        if self.doubleClick:
            if self.currentTag != tag:
                self.currentTag = tag 
                return
            self.doubleClick = False
            dialog = Pmw.PromptDialog(self.master, 
            title = 'Color Name Dialog',
            label_text = 'Enter text to label this color:',
            entryfield_labelpos = 'n',
            buttons = ('OK', 'Cancel'))
            result = dialog.activate()      
            if result == 'OK':
                txt = dialog.get() 
                fg='black' 
                if not txt: 
                    txt = str(len(self.colDict)+1)
                    fg = col
                self.colorChips.button(self.colorChips.index(
                                                             self.colorChips.selection
                                                             )).configure(text=txt,
                                                                          fg=fg,
                                                                          value=txt)
                color = self.colDict.pop(tag)
                self.colDict[txt] = color
                self.mapping[tag] = txt
                self.save(self.customFilename, self.colorsName)
                
        else:
            self.doubleClick = True
            self.master.after(1000, self.setDoubleClick)
    
    def setDoubleClick(self):
        self.doubleClick = False
        
    def addToCustom_cb(self):
        rgbcol = self.ce.get()
        newKey = str(len(self.colDict)+1)
        while newKey in self.colDict:
            newKey = str(int(newKey)+1)
        self.colDict[newKey]=rgbcol
        col = ToHEX(rgbcol)
        self.colorChips.add(newKey, bg = col,
                            activebackground=col,
                            fg = col, activeforeground = col,
                            indicatoron=0,selectcolor=col,
                            width=10,height=1, value = newKey)
        try:
            self.save(self.customFilename, self.colorsName)
        except Exception, inst:
            print inst