home *** CD-ROM | disk | FTP | other *** search
/ PC World 2005 June / PCWorld_2005-06_cd.bin / software / vyzkuste / firewally / firewally.exe / framework-2.3.exe / keybindingDialog.py < prev    next >
Text File  |  2003-12-30  |  12KB  |  262 lines

  1. """
  2. dialog for building tkinter accelerator key bindings
  3. """
  4. from Tkinter import *
  5. import tkMessageBox
  6. import string, os
  7.  
  8. class GetKeysDialog(Toplevel):
  9.     def __init__(self,parent,title,action,currentKeySequences):
  10.         """
  11.         action - string, the name of the virtual event these keys will be
  12.                  mapped to
  13.         currentKeys - list, a list of all key sequence lists currently mapped
  14.                  to virtual events, for overlap checking
  15.         """
  16.         Toplevel.__init__(self, parent)
  17.         self.configure(borderwidth=5)
  18.         self.resizable(height=FALSE,width=FALSE)
  19.         self.title(title)
  20.         self.transient(parent)
  21.         self.grab_set()
  22.         self.protocol("WM_DELETE_WINDOW", self.Cancel)
  23.         self.parent = parent
  24.         self.action=action
  25.         self.currentKeySequences=currentKeySequences
  26.         self.result=''
  27.         self.keyString=StringVar(self)
  28.         self.keyString.set('')
  29.         self.SetModifiersForPlatform()
  30.         self.modifier_vars = []
  31.         for modifier in self.modifiers:
  32.             variable = StringVar(self)
  33.             variable.set('')
  34.             self.modifier_vars.append(variable)
  35.         self.CreateWidgets()
  36.         self.LoadFinalKeyList()
  37.         self.withdraw() #hide while setting geometry
  38.         self.update_idletasks()
  39.         self.geometry("+%d+%d" %
  40.             ((parent.winfo_rootx()+((parent.winfo_width()/2)
  41.                 -(self.winfo_reqwidth()/2)),
  42.               parent.winfo_rooty()+((parent.winfo_height()/2)
  43.                 -(self.winfo_reqheight()/2)) )) ) #centre dialog over parent
  44.         self.deiconify() #geometry set, unhide
  45.         self.wait_window()
  46.  
  47.     def CreateWidgets(self):
  48.         frameMain = Frame(self,borderwidth=2,relief=SUNKEN)
  49.         frameMain.pack(side=TOP,expand=TRUE,fill=BOTH)
  50.         frameButtons=Frame(self)
  51.         frameButtons.pack(side=BOTTOM,fill=X)
  52.         self.buttonOk = Button(frameButtons,text='Ok',
  53.                 width=8,command=self.Ok)
  54.         self.buttonOk.grid(row=0,column=0,padx=5,pady=5)
  55.         self.buttonCancel = Button(frameButtons,text='Cancel',
  56.                 width=8,command=self.Cancel)
  57.         self.buttonCancel.grid(row=0,column=1,padx=5,pady=5)
  58.         self.frameKeySeqBasic = Frame(frameMain)
  59.         self.frameKeySeqAdvanced = Frame(frameMain)
  60.         self.frameControlsBasic = Frame(frameMain)
  61.         self.frameHelpAdvanced = Frame(frameMain)
  62.         self.frameKeySeqAdvanced.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5)
  63.         self.frameKeySeqBasic.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5)
  64.         self.frameKeySeqBasic.lift()
  65.         self.frameHelpAdvanced.grid(row=1,column=0,sticky=NSEW,padx=5)
  66.         self.frameControlsBasic.grid(row=1,column=0,sticky=NSEW,padx=5)
  67.         self.frameControlsBasic.lift()
  68.         self.buttonLevel = Button(frameMain,command=self.ToggleLevel,
  69.                 text='Advanced Key Binding Entry >>')
  70.         self.buttonLevel.grid(row=2,column=0,stick=EW,padx=5,pady=5)
  71.         labelTitleBasic = Label(self.frameKeySeqBasic,
  72.                 text="New keys for  '"+self.action+"' :")
  73.         labelTitleBasic.pack(anchor=W)
  74.         labelKeysBasic = Label(self.frameKeySeqBasic,justify=LEFT,
  75.                 textvariable=self.keyString,relief=GROOVE,borderwidth=2)
  76.         labelKeysBasic.pack(ipadx=5,ipady=5,fill=X)
  77.         self.modifier_checkbuttons = {}
  78.         column = 0
  79.         for modifier, variable in zip(self.modifiers, self.modifier_vars):
  80.             label = self.modifier_label.get(modifier, modifier)
  81.             check=Checkbutton(self.frameControlsBasic,
  82.                 command=self.BuildKeyString,
  83.                 text=label,variable=variable,onvalue=modifier,offvalue='')
  84.             check.grid(row=0,column=column,padx=2,sticky=W)
  85.             self.modifier_checkbuttons[modifier] = check
  86.             column += 1
  87.         labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT,
  88.                 text="Select the desired modifier\n"+
  89.                      "keys above, and final key\n"+
  90.                      "from the list on the right.")
  91.         labelFnAdvice.grid(row=1,column=0,columnspan=4,padx=2,sticky=W)
  92.         self.listKeysFinal=Listbox(self.frameControlsBasic,width=15,height=10,
  93.                 selectmode=SINGLE)
  94.         self.listKeysFinal.bind('<ButtonRelease-1>',self.FinalKeySelected)
  95.         self.listKeysFinal.grid(row=0,column=4,rowspan=4,sticky=NS)
  96.         scrollKeysFinal=Scrollbar(self.frameControlsBasic,orient=VERTICAL,
  97.                 command=self.listKeysFinal.yview)
  98.         self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set)
  99.         scrollKeysFinal.grid(row=0,column=5,rowspan=4,sticky=NS)
  100.         self.buttonClear=Button(self.frameControlsBasic,
  101.                 text='Clear Keys',command=self.ClearKeySeq)
  102.         self.buttonClear.grid(row=2,column=0,columnspan=4)
  103.         labelTitleAdvanced = Label(self.frameKeySeqAdvanced,justify=LEFT,
  104.                 text="Enter new binding(s) for  '"+self.action+"' :\n"+
  105.                 "(will not be checked for validity)")
  106.         labelTitleAdvanced.pack(anchor=W)
  107.         self.entryKeysAdvanced=Entry(self.frameKeySeqAdvanced,
  108.                 textvariable=self.keyString)
  109.         self.entryKeysAdvanced.pack(fill=X)
  110.         labelHelpAdvanced=Label(self.frameHelpAdvanced,justify=LEFT,
  111.             text="Key bindings are specified using tkinter key id's as\n"+
  112.                  "in these samples: <Control-f>, <Shift-F2>, <F12>,\n"
  113.                  "<Control-space>, <Meta-less>, <Control-Alt-Shift-x>.\n\n"+
  114.                  "'Emacs style' multi-keystroke bindings are specified as\n"+
  115.                  "follows: <Control-x><Control-y> or <Meta-f><Meta-g>.\n\n"+
  116.                  "Multiple separate bindings for one action should be\n"+
  117.                  "separated by a space, eg., <Alt-v> <Meta-v>." )
  118.         labelHelpAdvanced.grid(row=0,column=0,sticky=NSEW)
  119.  
  120.     def SetModifiersForPlatform(self):
  121.         """Determine list of names of key modifiers for this platform.
  122.  
  123.         The names are used to build Tk bindings -- it doesn't matter if the
  124.         keyboard has these keys, it matters if Tk understands them. The
  125.         order is also important: key binding equality depends on it, so
  126.         config-keys.def must use the same ordering.
  127.         """
  128.         import sys
  129.         if sys.platform == 'darwin' and sys.executable.count('.app'):
  130.             self.modifiers = ['Shift', 'Control', 'Option', 'Command']
  131.         else:
  132.             self.modifiers = ['Control', 'Alt', 'Shift']
  133.         self.modifier_label = {'Control': 'Ctrl'}
  134.  
  135.     def ToggleLevel(self):
  136.         if  self.buttonLevel.cget('text')[:8]=='Advanced':
  137.             self.ClearKeySeq()
  138.             self.buttonLevel.config(text='<< Basic Key Binding Entry')
  139.             self.frameKeySeqAdvanced.lift()
  140.             self.frameHelpAdvanced.lift()
  141.             self.entryKeysAdvanced.focus_set()
  142.         else:
  143.             self.ClearKeySeq()
  144.             self.buttonLevel.config(text='Advanced Key Binding Entry >>')
  145.             self.frameKeySeqBasic.lift()
  146.             self.frameControlsBasic.lift()
  147.  
  148.     def FinalKeySelected(self,event):
  149.         self.BuildKeyString()
  150.  
  151.     def BuildKeyString(self):
  152.         keyList=[]
  153.         modifiers=self.GetModifiers()
  154.         finalKey=self.listKeysFinal.get(ANCHOR)
  155.         if modifiers: modifiers[0]='<'+modifiers[0]
  156.         keyList=keyList+modifiers
  157.         if finalKey:
  158.             if (not modifiers) and (finalKey not
  159.                     in self.alphanumKeys+self.punctuationKeys):
  160.                 finalKey='<'+self.TranslateKey(finalKey)
  161.             else:
  162.                 finalKey=self.TranslateKey(finalKey)
  163.             keyList.append(finalKey+'>')
  164.         keyStr=string.join(keyList,'-')
  165.         self.keyString.set(keyStr)
  166.  
  167.     def GetModifiers(self):
  168.         modList = [variable.get() for variable in self.modifier_vars]
  169.         return filter(None, modList)
  170.  
  171.     def ClearKeySeq(self):
  172.         self.listKeysFinal.select_clear(0,END)
  173.         self.listKeysFinal.yview(MOVETO, '0.0')
  174.         for variable in self.modifier_vars:
  175.             variable.set('')
  176.         self.keyString.set('')
  177.  
  178.     def LoadFinalKeyList(self):
  179.         #these tuples are also available for use in validity checks
  180.         self.functionKeys=('F1','F2','F2','F4','F5','F6','F7','F8','F9',
  181.                 'F10','F11','F12')
  182.         self.alphanumKeys=tuple(string.ascii_lowercase+string.digits)
  183.         self.punctuationKeys=tuple('~!@#%^&*()_-+={}[]|;:,.<>/?')
  184.         self.whitespaceKeys=('Tab','Space','Return')
  185.         self.editKeys=('BackSpace','Delete','Insert')
  186.         self.moveKeys=('Home','End','Page Up','Page Down','Left Arrow',
  187.                 'Right Arrow','Up Arrow','Down Arrow')
  188.         #make a tuple of most of the useful common 'final' keys
  189.         keys=(self.alphanumKeys+self.punctuationKeys+self.functionKeys+
  190.                 self.whitespaceKeys+self.editKeys+self.moveKeys)
  191.         self.listKeysFinal.insert(END, *keys)
  192.  
  193.     def TranslateKey(self,key):
  194.         #translate from key list value to tkinter key-id
  195.         translateDict={'~':'asciitilde','!':'exclam','@':'at','#':'numbersign',
  196.                 '%':'percent','^':'asciicircum','&':'ampersand','*':'asterisk',
  197.                 '(':'parenleft',')':'parenright','_':'underscore','-':'minus',
  198.                 '+':'plus','=':'equal','{':'braceleft','}':'braceright',
  199.                 '[':'bracketleft',']':'bracketright','|':'bar',';':'semicolon',
  200.                 ':':'colon',',':'comma','.':'period','<':'less','>':'greater',
  201.                 '/':'slash','?':'question','Page Up':'Prior','Page Down':'Next',
  202.                 'Left Arrow':'Left','Right Arrow':'Right','Up Arrow':'Up',
  203.                 'Down Arrow': 'Down'}
  204.         if key in translateDict.keys():
  205.             key=translateDict[key]
  206.         key='Key-'+key
  207.         return key
  208.  
  209.     def Ok(self, event=None):
  210.         if self.KeysOk():
  211.             self.result=self.keyString.get()
  212.             self.destroy()
  213.  
  214.     def Cancel(self, event=None):
  215.         self.result=''
  216.         self.destroy()
  217.  
  218.     def KeysOk(self):
  219.         #simple validity check
  220.         keysOk=1
  221.         keys=self.keyString.get()
  222.         keys.strip()
  223.         finalKey=self.listKeysFinal.get(ANCHOR)
  224.         modifiers=self.GetModifiers()
  225.         keySequence=keys.split()#make into a key sequence list for overlap check
  226.         if not keys: #no keys specified
  227.             tkMessageBox.showerror(title='Key Sequence Error',
  228.                     message='No keys specified.')
  229.             keysOk=0
  230.         elif not keys.endswith('>'): #no final key specified
  231.             tkMessageBox.showerror(title='Key Sequence Error',
  232.                     message='No final key specified.')
  233.             keysOk=0
  234.         elif (not modifiers) and (finalKey in
  235.                 self.alphanumKeys+self.punctuationKeys):
  236.             #modifier required
  237.             tkMessageBox.showerror(title='Key Sequence Error',
  238.                     message='No modifier key(s) specified.')
  239.             keysOk=0
  240.         elif (modifiers==['Shift']) and (finalKey not
  241.                 in self.functionKeys+('Tab',)):
  242.             #shift alone is only a useful modifier with a function key
  243.             tkMessageBox.showerror(title='Key Sequence Error',
  244.                     message='Shift alone is not a useful modifier '+
  245.                             'when used with this final key key.')
  246.             keysOk=0
  247.         elif keySequence in self.currentKeySequences: #keys combo already in use
  248.             tkMessageBox.showerror(title='Key Sequence Error',
  249.                     message='This key combination is already in use.')
  250.             keysOk=0
  251.         return keysOk
  252.  
  253. if __name__ == '__main__':
  254.     #test the dialog
  255.     root=Tk()
  256.     def run():
  257.         keySeq=''
  258.         dlg=GetKeysDialog(root,'Get Keys','find-again',[])
  259.         print dlg.result
  260.     Button(root,text='Dialog',command=run).pack()
  261.     root.mainloop()
  262.