config_key.py 14 KB

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