blob: 3b1ddbafeca110dd45975c68b4517a8d1aaf0327 [file] [log] [blame]
Steven M. Gavaedb60a72002-01-12 09:48:02 +00001"""
2dialog for building tkinter accelerator key bindings
3"""
4from Tkinter import *
5import tkMessageBox
6import string, os
7
Steven M. Gavafacfc092002-01-19 00:29:54 +00008class GetKeysDialog(Toplevel):
Steven M. Gava68d73362002-01-19 01:30:56 +00009 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 """
Steven M. Gavaedb60a72002-01-12 09:48:02 +000016 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
Steven M. Gava68d73362002-01-19 01:30:56 +000025 self.currentKeySequences=currentKeySequences
Steven M. Gavafacfc092002-01-19 00:29:54 +000026 self.result=''
Steven M. Gavaedb60a72002-01-12 09:48:02 +000027 self.keyString=StringVar(self)
28 self.keyString.set('')
29 self.keyCtrl=StringVar(self)
30 self.keyCtrl.set('')
31 self.keyAlt=StringVar(self)
32 self.keyAlt.set('')
Steven M. Gavaedb60a72002-01-12 09:48:02 +000033 self.keyShift=StringVar(self)
34 self.keyShift.set('')
Steven M. Gavaedb60a72002-01-12 09:48:02 +000035 self.CreateWidgets()
36 self.LoadFinalKeyList()
Steven M. Gavaedb60a72002-01-12 09:48:02 +000037 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 checkCtrl=Checkbutton(self.frameControlsBasic,
78 command=self.BuildKeyString,
79 text='Ctrl',variable=self.keyCtrl,onvalue='Control',offvalue='')
80 checkCtrl.grid(row=0,column=0,padx=2,sticky=W)
81 checkAlt=Checkbutton(self.frameControlsBasic,
82 command=self.BuildKeyString,
83 text='Alt',variable=self.keyAlt,onvalue='Alt',offvalue='')
84 checkAlt.grid(row=0,column=1,padx=2,sticky=W)
Steven M. Gavaedb60a72002-01-12 09:48:02 +000085 checkShift=Checkbutton(self.frameControlsBasic,
86 command=self.BuildKeyString,
87 text='Shift',variable=self.keyShift,onvalue='Shift',offvalue='')
88 checkShift.grid(row=0,column=3,padx=2,sticky=W)
89 labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT,
90 text="Select the desired modifier\n"+
91 "keys above, and final key\n"+
Steven M. Gavaedb60a72002-01-12 09:48:02 +000092 "from the list on the right.")
93 labelFnAdvice.grid(row=1,column=0,columnspan=4,padx=2,sticky=W)
94 self.listKeysFinal=Listbox(self.frameControlsBasic,width=15,height=10,
95 selectmode=SINGLE)
Steven M. Gavaedb60a72002-01-12 09:48:02 +000096 self.listKeysFinal.bind('<ButtonRelease-1>',self.FinalKeySelected)
97 self.listKeysFinal.grid(row=0,column=4,rowspan=4,sticky=NS)
98 scrollKeysFinal=Scrollbar(self.frameControlsBasic,orient=VERTICAL,
99 command=self.listKeysFinal.yview)
100 self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set)
101 scrollKeysFinal.grid(row=0,column=5,rowspan=4,sticky=NS)
Steven M. Gavafacfc092002-01-19 00:29:54 +0000102 self.buttonClear=Button(self.frameControlsBasic,
103 text='Clear Keys',command=self.ClearKeySeq)
104 self.buttonClear.grid(row=2,column=0,columnspan=4)
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000105 labelTitleAdvanced = Label(self.frameKeySeqAdvanced,justify=LEFT,
106 text="Enter new binding(s) for '"+self.action+"' :\n"+
107 "(will not be checked for validity)")
108 labelTitleAdvanced.pack(anchor=W)
109 self.entryKeysAdvanced=Entry(self.frameKeySeqAdvanced,
110 textvariable=self.keyString)
111 self.entryKeysAdvanced.pack(fill=X)
112 labelHelpAdvanced=Label(self.frameHelpAdvanced,justify=LEFT,
113 text="Key bindings are specified using tkinter key id's as\n"+
114 "in these samples: <Control-f>, <Shift-F2>, <F12>,\n"
115 "<Control-space>, <Meta-less>, <Control-Alt-Shift-x>.\n\n"+
116 "'Emacs style' multi-keystroke bindings are specified as\n"+
117 "follows: <Control-x><Control-y> or <Meta-f><Meta-g>.\n\n"+
118 "Multiple separate bindings for one action should be\n"+
119 "separated by a space, eg., <Alt-v> <Meta-v>." )
120 labelHelpAdvanced.grid(row=0,column=0,sticky=NSEW)
121
122 def ToggleLevel(self):
123 if self.buttonLevel.cget('text')[:8]=='Advanced':
Steven M. Gavafacfc092002-01-19 00:29:54 +0000124 self.ClearKeySeq()
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000125 self.buttonLevel.config(text='<< Basic Key Binding Entry')
126 self.frameKeySeqAdvanced.lift()
127 self.frameHelpAdvanced.lift()
128 self.entryKeysAdvanced.focus_set()
129 else:
Steven M. Gavafacfc092002-01-19 00:29:54 +0000130 self.ClearKeySeq()
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000131 self.buttonLevel.config(text='Advanced Key Binding Entry >>')
132 self.frameKeySeqBasic.lift()
133 self.frameControlsBasic.lift()
134
135 def FinalKeySelected(self,event):
136 self.BuildKeyString()
137
138 def BuildKeyString(self):
139 keyList=[]
Steven M. Gavafacfc092002-01-19 00:29:54 +0000140 modifiers=self.GetModifiers()
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000141 finalKey=self.listKeysFinal.get(ANCHOR)
142 if modifiers: modifiers[0]='<'+modifiers[0]
143 keyList=keyList+modifiers
144 if finalKey:
145 if (not modifiers) and (finalKey in self.functionKeys):
Steven M. Gavac628a062002-01-19 10:33:21 +0000146 finalKey='<'+self.TranslateKey(finalKey)
147 else:
148 finalKey=self.TranslateKey(finalKey)
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000149 keyList.append(finalKey+'>')
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000150 keyStr=string.join(keyList,'-')
151 self.keyString.set(keyStr)
152
Steven M. Gavafacfc092002-01-19 00:29:54 +0000153 def GetModifiers(self):
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000154 modList=[]
Steven M. Gavafacfc092002-01-19 00:29:54 +0000155 ctrl=self.keyCtrl.get()
156 alt=self.keyAlt.get()
157 shift=self.keyShift.get()
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000158 if ctrl: modList.append(ctrl)
159 if alt: modList.append(alt)
160 if shift: modList.append(shift)
161 return modList
162
Steven M. Gavafacfc092002-01-19 00:29:54 +0000163 def ClearKeySeq(self):
164 self.listKeysFinal.select_clear(0,END)
165 self.listKeysFinal.yview(MOVETO, '0.0')
166 self.keyCtrl.set('')
167 self.keyAlt.set(''),
168 self.keyShift.set('')
169 self.keyString.set('')
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000170
171 def LoadFinalKeyList(self):
Steven M. Gavafacfc092002-01-19 00:29:54 +0000172 #these tuples are also available for use in validity checks
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000173 self.functionKeys=('F1','F2','F2','F4','F5','F6','F7','F8','F9',
174 'F10','F11','F12')
Steven M. Gavafacfc092002-01-19 00:29:54 +0000175 self.alphanumKeys=tuple(string.ascii_lowercase+string.digits)
Steven M. Gavac628a062002-01-19 10:33:21 +0000176 self.punctuationKeys=tuple('~!@#%^&*()_-+={}[]|;:,.<>/?')
177 self.whitespaceKeys=('Tab','Space','Return')
178 self.editKeys=('BackSpace','Delete','Insert')
179 self.moveKeys=('Home','End','Page Up','Page Down','Left Arrow',
180 'Right Arrow','Up Arrow','Down Arrow')
Steven M. Gavafacfc092002-01-19 00:29:54 +0000181 #make a tuple of most of the useful common 'final' keys
Steven M. Gavac628a062002-01-19 10:33:21 +0000182 keys=(self.alphanumKeys+self.punctuationKeys+self.functionKeys+
183 self.whitespaceKeys+self.editKeys+self.moveKeys)
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000184 apply(self.listKeysFinal.insert,
185 (END,)+keys)
186
Steven M. Gavac628a062002-01-19 10:33:21 +0000187 def TranslateKey(self,key):
188 #translate from key list value to tkinter key-id
189 translateDict={'~':'asciitilde','!':'exclam','@':'at','#':'numbersign',
190 '%':'percent','^':'asciicircum','&':'ampersand','*':'asterisk',
191 '(':'parenleft',')':'parenright','_':'underscore','-':'minus',
192 '+':'plus','=':'equal','{':'braceleft','}':'braceright',
193 '[':'bracketleft',']':'bracketright','|':'bar',';':'semicolon',
194 ':':'colon',',':'comma','.':'period','<':'less','>':'greater',
195 '/':'slash','?':'question','Page Up':'Prior','Page Down':'Next',
196 'Left Arrow':'Left','Right Arrow':'Right','Up Arrow':'Up',
197 'Down Arrow': 'Down'}
198 if key in translateDict.keys():
199 key=translateDict[key]
200 key='Key-'+key
201 return key
202
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000203 def Ok(self, event=None):
204 if self.KeysOk():
Steven M. Gavafacfc092002-01-19 00:29:54 +0000205 self.result=self.keyString.get()
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000206 self.destroy()
Steven M. Gavafacfc092002-01-19 00:29:54 +0000207
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000208 def Cancel(self, event=None):
Steven M. Gavafacfc092002-01-19 00:29:54 +0000209 self.result=''
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000210 self.destroy()
211
Steven M. Gava68d73362002-01-19 01:30:56 +0000212 def KeysOk(self):
213 #simple validity check
214 keysOk=1
215 keys=self.keyString.get()
216 keys.strip()
217 finalKey=self.listKeysFinal.get(ANCHOR)
218 modifiers=self.GetModifiers()
219 keySequence=keys.split()#make into a key sequence list for overlap check
220 if not keys: #no keys specified
221 tkMessageBox.showerror(title='Key Sequence Error',
222 message='No keys specified.')
223 keysOk=0
224 elif not keys.endswith('>'): #no final key specified
225 tkMessageBox.showerror(title='Key Sequence Error',
226 message='No final key specified.')
227 keysOk=0
228 elif (not modifiers) and (finalKey not in self.functionKeys):
229 #modifier required if not a function key
230 tkMessageBox.showerror(title='Key Sequence Error',
231 message='No modifier key(s) specified.')
232 keysOk=0
233 elif (modifiers==['Shift']) and (finalKey not in self.functionKeys):
234 #shift alone is only a useful modifier with a function key
235 tkMessageBox.showerror(title='Key Sequence Error',
236 message='Shift alone is only a useful modifier '+
237 'when used with a function key.')
238 keysOk=0
239 elif keySequence in self.currentKeySequences: #keys combo already in use
240 tkMessageBox.showerror(title='Key Sequence Error',
241 message='This key combination is already in use.')
242 keysOk=0
243 return keysOk
244
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000245if __name__ == '__main__':
246 #test the dialog
247 root=Tk()
248 def run():
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000249 keySeq=''
Steven M. Gava68d73362002-01-19 01:30:56 +0000250 dlg=GetKeysDialog(root,'Get Keys','find-again',[])
Steven M. Gavafacfc092002-01-19 00:29:54 +0000251 print dlg.result
Steven M. Gavaedb60a72002-01-12 09:48:02 +0000252 Button(root,text='Dialog',command=run).pack()
253 root.mainloop()