keybindingDialog.py 12 KB

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