config_key.py 14 KB

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