Debian Codegraph @

cpython27/Lib/idlelib/keybindingDialog.py

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