annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/idlelib/config_key.py @ 69:33d812a61356

planemo upload commit 2e9511a184a1ca667c7be0c6321a36dc4e3d116d
author jpayne
date Tue, 18 Mar 2025 17:55:14 -0400
parents
children
rev   line source
jpayne@69 1 """
jpayne@69 2 Dialog for building Tkinter accelerator key bindings
jpayne@69 3 """
jpayne@69 4 from tkinter import Toplevel, Listbox, Text, StringVar, TclError
jpayne@69 5 from tkinter.ttk import Frame, Button, Checkbutton, Entry, Label, Scrollbar
jpayne@69 6 from tkinter import messagebox
jpayne@69 7 import string
jpayne@69 8 import sys
jpayne@69 9
jpayne@69 10
jpayne@69 11 FUNCTION_KEYS = ('F1', 'F2' ,'F3' ,'F4' ,'F5' ,'F6',
jpayne@69 12 'F7', 'F8' ,'F9' ,'F10' ,'F11' ,'F12')
jpayne@69 13 ALPHANUM_KEYS = tuple(string.ascii_lowercase + string.digits)
jpayne@69 14 PUNCTUATION_KEYS = tuple('~!@#%^&*()_-+={}[]|;:,.<>/?')
jpayne@69 15 WHITESPACE_KEYS = ('Tab', 'Space', 'Return')
jpayne@69 16 EDIT_KEYS = ('BackSpace', 'Delete', 'Insert')
jpayne@69 17 MOVE_KEYS = ('Home', 'End', 'Page Up', 'Page Down', 'Left Arrow',
jpayne@69 18 'Right Arrow', 'Up Arrow', 'Down Arrow')
jpayne@69 19 AVAILABLE_KEYS = (ALPHANUM_KEYS + PUNCTUATION_KEYS + FUNCTION_KEYS +
jpayne@69 20 WHITESPACE_KEYS + EDIT_KEYS + MOVE_KEYS)
jpayne@69 21
jpayne@69 22
jpayne@69 23 def translate_key(key, modifiers):
jpayne@69 24 "Translate from keycap symbol to the Tkinter keysym."
jpayne@69 25 mapping = {'Space':'space',
jpayne@69 26 '~':'asciitilde', '!':'exclam', '@':'at', '#':'numbersign',
jpayne@69 27 '%':'percent', '^':'asciicircum', '&':'ampersand',
jpayne@69 28 '*':'asterisk', '(':'parenleft', ')':'parenright',
jpayne@69 29 '_':'underscore', '-':'minus', '+':'plus', '=':'equal',
jpayne@69 30 '{':'braceleft', '}':'braceright',
jpayne@69 31 '[':'bracketleft', ']':'bracketright', '|':'bar',
jpayne@69 32 ';':'semicolon', ':':'colon', ',':'comma', '.':'period',
jpayne@69 33 '<':'less', '>':'greater', '/':'slash', '?':'question',
jpayne@69 34 'Page Up':'Prior', 'Page Down':'Next',
jpayne@69 35 'Left Arrow':'Left', 'Right Arrow':'Right',
jpayne@69 36 'Up Arrow':'Up', 'Down Arrow': 'Down', 'Tab':'Tab'}
jpayne@69 37 key = mapping.get(key, key)
jpayne@69 38 if 'Shift' in modifiers and key in string.ascii_lowercase:
jpayne@69 39 key = key.upper()
jpayne@69 40 return f'Key-{key}'
jpayne@69 41
jpayne@69 42
jpayne@69 43 class GetKeysDialog(Toplevel):
jpayne@69 44
jpayne@69 45 # Dialog title for invalid key sequence
jpayne@69 46 keyerror_title = 'Key Sequence Error'
jpayne@69 47
jpayne@69 48 def __init__(self, parent, title, action, current_key_sequences,
jpayne@69 49 *, _htest=False, _utest=False):
jpayne@69 50 """
jpayne@69 51 parent - parent of this dialog
jpayne@69 52 title - string which is the title of the popup dialog
jpayne@69 53 action - string, the name of the virtual event these keys will be
jpayne@69 54 mapped to
jpayne@69 55 current_key_sequences - list, a list of all key sequence lists
jpayne@69 56 currently mapped to virtual events, for overlap checking
jpayne@69 57 _htest - bool, change box location when running htest
jpayne@69 58 _utest - bool, do not wait when running unittest
jpayne@69 59 """
jpayne@69 60 Toplevel.__init__(self, parent)
jpayne@69 61 self.withdraw() # Hide while setting geometry.
jpayne@69 62 self.configure(borderwidth=5)
jpayne@69 63 self.resizable(height=False, width=False)
jpayne@69 64 self.title(title)
jpayne@69 65 self.transient(parent)
jpayne@69 66 self.grab_set()
jpayne@69 67 self.protocol("WM_DELETE_WINDOW", self.cancel)
jpayne@69 68 self.parent = parent
jpayne@69 69 self.action = action
jpayne@69 70 self.current_key_sequences = current_key_sequences
jpayne@69 71 self.result = ''
jpayne@69 72 self.key_string = StringVar(self)
jpayne@69 73 self.key_string.set('')
jpayne@69 74 # Set self.modifiers, self.modifier_label.
jpayne@69 75 self.set_modifiers_for_platform()
jpayne@69 76 self.modifier_vars = []
jpayne@69 77 for modifier in self.modifiers:
jpayne@69 78 variable = StringVar(self)
jpayne@69 79 variable.set('')
jpayne@69 80 self.modifier_vars.append(variable)
jpayne@69 81 self.advanced = False
jpayne@69 82 self.create_widgets()
jpayne@69 83 self.update_idletasks()
jpayne@69 84 self.geometry(
jpayne@69 85 "+%d+%d" % (
jpayne@69 86 parent.winfo_rootx() +
jpayne@69 87 (parent.winfo_width()/2 - self.winfo_reqwidth()/2),
jpayne@69 88 parent.winfo_rooty() +
jpayne@69 89 ((parent.winfo_height()/2 - self.winfo_reqheight()/2)
jpayne@69 90 if not _htest else 150)
jpayne@69 91 ) ) # Center dialog over parent (or below htest box).
jpayne@69 92 if not _utest:
jpayne@69 93 self.deiconify() # Geometry set, unhide.
jpayne@69 94 self.wait_window()
jpayne@69 95
jpayne@69 96 def showerror(self, *args, **kwargs):
jpayne@69 97 # Make testing easier. Replace in #30751.
jpayne@69 98 messagebox.showerror(*args, **kwargs)
jpayne@69 99
jpayne@69 100 def create_widgets(self):
jpayne@69 101 self.frame = frame = Frame(self, borderwidth=2, relief='sunken')
jpayne@69 102 frame.pack(side='top', expand=True, fill='both')
jpayne@69 103
jpayne@69 104 frame_buttons = Frame(self)
jpayne@69 105 frame_buttons.pack(side='bottom', fill='x')
jpayne@69 106
jpayne@69 107 self.button_ok = Button(frame_buttons, text='OK',
jpayne@69 108 width=8, command=self.ok)
jpayne@69 109 self.button_ok.grid(row=0, column=0, padx=5, pady=5)
jpayne@69 110 self.button_cancel = Button(frame_buttons, text='Cancel',
jpayne@69 111 width=8, command=self.cancel)
jpayne@69 112 self.button_cancel.grid(row=0, column=1, padx=5, pady=5)
jpayne@69 113
jpayne@69 114 # Basic entry key sequence.
jpayne@69 115 self.frame_keyseq_basic = Frame(frame, name='keyseq_basic')
jpayne@69 116 self.frame_keyseq_basic.grid(row=0, column=0, sticky='nsew',
jpayne@69 117 padx=5, pady=5)
jpayne@69 118 basic_title = Label(self.frame_keyseq_basic,
jpayne@69 119 text=f"New keys for '{self.action}' :")
jpayne@69 120 basic_title.pack(anchor='w')
jpayne@69 121
jpayne@69 122 basic_keys = Label(self.frame_keyseq_basic, justify='left',
jpayne@69 123 textvariable=self.key_string, relief='groove',
jpayne@69 124 borderwidth=2)
jpayne@69 125 basic_keys.pack(ipadx=5, ipady=5, fill='x')
jpayne@69 126
jpayne@69 127 # Basic entry controls.
jpayne@69 128 self.frame_controls_basic = Frame(frame)
jpayne@69 129 self.frame_controls_basic.grid(row=1, column=0, sticky='nsew', padx=5)
jpayne@69 130
jpayne@69 131 # Basic entry modifiers.
jpayne@69 132 self.modifier_checkbuttons = {}
jpayne@69 133 column = 0
jpayne@69 134 for modifier, variable in zip(self.modifiers, self.modifier_vars):
jpayne@69 135 label = self.modifier_label.get(modifier, modifier)
jpayne@69 136 check = Checkbutton(self.frame_controls_basic,
jpayne@69 137 command=self.build_key_string, text=label,
jpayne@69 138 variable=variable, onvalue=modifier, offvalue='')
jpayne@69 139 check.grid(row=0, column=column, padx=2, sticky='w')
jpayne@69 140 self.modifier_checkbuttons[modifier] = check
jpayne@69 141 column += 1
jpayne@69 142
jpayne@69 143 # Basic entry help text.
jpayne@69 144 help_basic = Label(self.frame_controls_basic, justify='left',
jpayne@69 145 text="Select the desired modifier keys\n"+
jpayne@69 146 "above, and the final key from the\n"+
jpayne@69 147 "list on the right.\n\n" +
jpayne@69 148 "Use upper case Symbols when using\n" +
jpayne@69 149 "the Shift modifier. (Letters will be\n" +
jpayne@69 150 "converted automatically.)")
jpayne@69 151 help_basic.grid(row=1, column=0, columnspan=4, padx=2, sticky='w')
jpayne@69 152
jpayne@69 153 # Basic entry key list.
jpayne@69 154 self.list_keys_final = Listbox(self.frame_controls_basic, width=15,
jpayne@69 155 height=10, selectmode='single')
jpayne@69 156 self.list_keys_final.insert('end', *AVAILABLE_KEYS)
jpayne@69 157 self.list_keys_final.bind('<ButtonRelease-1>', self.final_key_selected)
jpayne@69 158 self.list_keys_final.grid(row=0, column=4, rowspan=4, sticky='ns')
jpayne@69 159 scroll_keys_final = Scrollbar(self.frame_controls_basic,
jpayne@69 160 orient='vertical',
jpayne@69 161 command=self.list_keys_final.yview)
jpayne@69 162 self.list_keys_final.config(yscrollcommand=scroll_keys_final.set)
jpayne@69 163 scroll_keys_final.grid(row=0, column=5, rowspan=4, sticky='ns')
jpayne@69 164 self.button_clear = Button(self.frame_controls_basic,
jpayne@69 165 text='Clear Keys',
jpayne@69 166 command=self.clear_key_seq)
jpayne@69 167 self.button_clear.grid(row=2, column=0, columnspan=4)
jpayne@69 168
jpayne@69 169 # Advanced entry key sequence.
jpayne@69 170 self.frame_keyseq_advanced = Frame(frame, name='keyseq_advanced')
jpayne@69 171 self.frame_keyseq_advanced.grid(row=0, column=0, sticky='nsew',
jpayne@69 172 padx=5, pady=5)
jpayne@69 173 advanced_title = Label(self.frame_keyseq_advanced, justify='left',
jpayne@69 174 text=f"Enter new binding(s) for '{self.action}' :\n" +
jpayne@69 175 "(These bindings will not be checked for validity!)")
jpayne@69 176 advanced_title.pack(anchor='w')
jpayne@69 177 self.advanced_keys = Entry(self.frame_keyseq_advanced,
jpayne@69 178 textvariable=self.key_string)
jpayne@69 179 self.advanced_keys.pack(fill='x')
jpayne@69 180
jpayne@69 181 # Advanced entry help text.
jpayne@69 182 self.frame_help_advanced = Frame(frame)
jpayne@69 183 self.frame_help_advanced.grid(row=1, column=0, sticky='nsew', padx=5)
jpayne@69 184 help_advanced = Label(self.frame_help_advanced, justify='left',
jpayne@69 185 text="Key bindings are specified using Tkinter keysyms as\n"+
jpayne@69 186 "in these samples: <Control-f>, <Shift-F2>, <F12>,\n"
jpayne@69 187 "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n"
jpayne@69 188 "Upper case is used when the Shift modifier is present!\n\n" +
jpayne@69 189 "'Emacs style' multi-keystroke bindings are specified as\n" +
jpayne@69 190 "follows: <Control-x><Control-y>, where the first key\n" +
jpayne@69 191 "is the 'do-nothing' keybinding.\n\n" +
jpayne@69 192 "Multiple separate bindings for one action should be\n"+
jpayne@69 193 "separated by a space, eg., <Alt-v> <Meta-v>." )
jpayne@69 194 help_advanced.grid(row=0, column=0, sticky='nsew')
jpayne@69 195
jpayne@69 196 # Switch between basic and advanced.
jpayne@69 197 self.button_level = Button(frame, command=self.toggle_level,
jpayne@69 198 text='<< Basic Key Binding Entry')
jpayne@69 199 self.button_level.grid(row=2, column=0, stick='ew', padx=5, pady=5)
jpayne@69 200 self.toggle_level()
jpayne@69 201
jpayne@69 202 def set_modifiers_for_platform(self):
jpayne@69 203 """Determine list of names of key modifiers for this platform.
jpayne@69 204
jpayne@69 205 The names are used to build Tk bindings -- it doesn't matter if the
jpayne@69 206 keyboard has these keys; it matters if Tk understands them. The
jpayne@69 207 order is also important: key binding equality depends on it, so
jpayne@69 208 config-keys.def must use the same ordering.
jpayne@69 209 """
jpayne@69 210 if sys.platform == "darwin":
jpayne@69 211 self.modifiers = ['Shift', 'Control', 'Option', 'Command']
jpayne@69 212 else:
jpayne@69 213 self.modifiers = ['Control', 'Alt', 'Shift']
jpayne@69 214 self.modifier_label = {'Control': 'Ctrl'} # Short name.
jpayne@69 215
jpayne@69 216 def toggle_level(self):
jpayne@69 217 "Toggle between basic and advanced keys."
jpayne@69 218 if self.button_level.cget('text').startswith('Advanced'):
jpayne@69 219 self.clear_key_seq()
jpayne@69 220 self.button_level.config(text='<< Basic Key Binding Entry')
jpayne@69 221 self.frame_keyseq_advanced.lift()
jpayne@69 222 self.frame_help_advanced.lift()
jpayne@69 223 self.advanced_keys.focus_set()
jpayne@69 224 self.advanced = True
jpayne@69 225 else:
jpayne@69 226 self.clear_key_seq()
jpayne@69 227 self.button_level.config(text='Advanced Key Binding Entry >>')
jpayne@69 228 self.frame_keyseq_basic.lift()
jpayne@69 229 self.frame_controls_basic.lift()
jpayne@69 230 self.advanced = False
jpayne@69 231
jpayne@69 232 def final_key_selected(self, event=None):
jpayne@69 233 "Handler for clicking on key in basic settings list."
jpayne@69 234 self.build_key_string()
jpayne@69 235
jpayne@69 236 def build_key_string(self):
jpayne@69 237 "Create formatted string of modifiers plus the key."
jpayne@69 238 keylist = modifiers = self.get_modifiers()
jpayne@69 239 final_key = self.list_keys_final.get('anchor')
jpayne@69 240 if final_key:
jpayne@69 241 final_key = translate_key(final_key, modifiers)
jpayne@69 242 keylist.append(final_key)
jpayne@69 243 self.key_string.set(f"<{'-'.join(keylist)}>")
jpayne@69 244
jpayne@69 245 def get_modifiers(self):
jpayne@69 246 "Return ordered list of modifiers that have been selected."
jpayne@69 247 mod_list = [variable.get() for variable in self.modifier_vars]
jpayne@69 248 return [mod for mod in mod_list if mod]
jpayne@69 249
jpayne@69 250 def clear_key_seq(self):
jpayne@69 251 "Clear modifiers and keys selection."
jpayne@69 252 self.list_keys_final.select_clear(0, 'end')
jpayne@69 253 self.list_keys_final.yview('moveto', '0.0')
jpayne@69 254 for variable in self.modifier_vars:
jpayne@69 255 variable.set('')
jpayne@69 256 self.key_string.set('')
jpayne@69 257
jpayne@69 258 def ok(self, event=None):
jpayne@69 259 keys = self.key_string.get().strip()
jpayne@69 260 if not keys:
jpayne@69 261 self.showerror(title=self.keyerror_title, parent=self,
jpayne@69 262 message="No key specified.")
jpayne@69 263 return
jpayne@69 264 if (self.advanced or self.keys_ok(keys)) and self.bind_ok(keys):
jpayne@69 265 self.result = keys
jpayne@69 266 self.grab_release()
jpayne@69 267 self.destroy()
jpayne@69 268
jpayne@69 269 def cancel(self, event=None):
jpayne@69 270 self.result = ''
jpayne@69 271 self.grab_release()
jpayne@69 272 self.destroy()
jpayne@69 273
jpayne@69 274 def keys_ok(self, keys):
jpayne@69 275 """Validity check on user's 'basic' keybinding selection.
jpayne@69 276
jpayne@69 277 Doesn't check the string produced by the advanced dialog because
jpayne@69 278 'modifiers' isn't set.
jpayne@69 279 """
jpayne@69 280 final_key = self.list_keys_final.get('anchor')
jpayne@69 281 modifiers = self.get_modifiers()
jpayne@69 282 title = self.keyerror_title
jpayne@69 283 key_sequences = [key for keylist in self.current_key_sequences
jpayne@69 284 for key in keylist]
jpayne@69 285 if not keys.endswith('>'):
jpayne@69 286 self.showerror(title, parent=self,
jpayne@69 287 message='Missing the final Key')
jpayne@69 288 elif (not modifiers
jpayne@69 289 and final_key not in FUNCTION_KEYS + MOVE_KEYS):
jpayne@69 290 self.showerror(title=title, parent=self,
jpayne@69 291 message='No modifier key(s) specified.')
jpayne@69 292 elif (modifiers == ['Shift']) \
jpayne@69 293 and (final_key not in
jpayne@69 294 FUNCTION_KEYS + MOVE_KEYS + ('Tab', 'Space')):
jpayne@69 295 msg = 'The shift modifier by itself may not be used with'\
jpayne@69 296 ' this key symbol.'
jpayne@69 297 self.showerror(title=title, parent=self, message=msg)
jpayne@69 298 elif keys in key_sequences:
jpayne@69 299 msg = 'This key combination is already in use.'
jpayne@69 300 self.showerror(title=title, parent=self, message=msg)
jpayne@69 301 else:
jpayne@69 302 return True
jpayne@69 303 return False
jpayne@69 304
jpayne@69 305 def bind_ok(self, keys):
jpayne@69 306 "Return True if Tcl accepts the new keys else show message."
jpayne@69 307 try:
jpayne@69 308 binding = self.bind(keys, lambda: None)
jpayne@69 309 except TclError as err:
jpayne@69 310 self.showerror(
jpayne@69 311 title=self.keyerror_title, parent=self,
jpayne@69 312 message=(f'The entered key sequence is not accepted.\n\n'
jpayne@69 313 f'Error: {err}'))
jpayne@69 314 return False
jpayne@69 315 else:
jpayne@69 316 self.unbind(keys, binding)
jpayne@69 317 return True
jpayne@69 318
jpayne@69 319
jpayne@69 320 if __name__ == '__main__':
jpayne@69 321 from unittest import main
jpayne@69 322 main('idlelib.idle_test.test_config_key', verbosity=2, exit=False)
jpayne@69 323
jpayne@69 324 from idlelib.idle_test.htest import run
jpayne@69 325 run(GetKeysDialog)