jpayne@69: """ jpayne@69: Dialog for building Tkinter accelerator key bindings jpayne@69: """ jpayne@69: from tkinter import Toplevel, Listbox, Text, StringVar, TclError jpayne@69: from tkinter.ttk import Frame, Button, Checkbutton, Entry, Label, Scrollbar jpayne@69: from tkinter import messagebox jpayne@69: import string jpayne@69: import sys jpayne@69: jpayne@69: jpayne@69: FUNCTION_KEYS = ('F1', 'F2' ,'F3' ,'F4' ,'F5' ,'F6', jpayne@69: 'F7', 'F8' ,'F9' ,'F10' ,'F11' ,'F12') jpayne@69: ALPHANUM_KEYS = tuple(string.ascii_lowercase + string.digits) jpayne@69: PUNCTUATION_KEYS = tuple('~!@#%^&*()_-+={}[]|;:,.<>/?') jpayne@69: WHITESPACE_KEYS = ('Tab', 'Space', 'Return') jpayne@69: EDIT_KEYS = ('BackSpace', 'Delete', 'Insert') jpayne@69: MOVE_KEYS = ('Home', 'End', 'Page Up', 'Page Down', 'Left Arrow', jpayne@69: 'Right Arrow', 'Up Arrow', 'Down Arrow') jpayne@69: AVAILABLE_KEYS = (ALPHANUM_KEYS + PUNCTUATION_KEYS + FUNCTION_KEYS + jpayne@69: WHITESPACE_KEYS + EDIT_KEYS + MOVE_KEYS) jpayne@69: jpayne@69: jpayne@69: def translate_key(key, modifiers): jpayne@69: "Translate from keycap symbol to the Tkinter keysym." jpayne@69: mapping = {'Space':'space', jpayne@69: '~':'asciitilde', '!':'exclam', '@':'at', '#':'numbersign', jpayne@69: '%':'percent', '^':'asciicircum', '&':'ampersand', jpayne@69: '*':'asterisk', '(':'parenleft', ')':'parenright', jpayne@69: '_':'underscore', '-':'minus', '+':'plus', '=':'equal', jpayne@69: '{':'braceleft', '}':'braceright', jpayne@69: '[':'bracketleft', ']':'bracketright', '|':'bar', jpayne@69: ';':'semicolon', ':':'colon', ',':'comma', '.':'period', jpayne@69: '<':'less', '>':'greater', '/':'slash', '?':'question', jpayne@69: 'Page Up':'Prior', 'Page Down':'Next', jpayne@69: 'Left Arrow':'Left', 'Right Arrow':'Right', jpayne@69: 'Up Arrow':'Up', 'Down Arrow': 'Down', 'Tab':'Tab'} jpayne@69: key = mapping.get(key, key) jpayne@69: if 'Shift' in modifiers and key in string.ascii_lowercase: jpayne@69: key = key.upper() jpayne@69: return f'Key-{key}' jpayne@69: jpayne@69: jpayne@69: class GetKeysDialog(Toplevel): jpayne@69: jpayne@69: # Dialog title for invalid key sequence jpayne@69: keyerror_title = 'Key Sequence Error' jpayne@69: jpayne@69: def __init__(self, parent, title, action, current_key_sequences, jpayne@69: *, _htest=False, _utest=False): jpayne@69: """ jpayne@69: parent - parent of this dialog jpayne@69: title - string which is the title of the popup dialog jpayne@69: action - string, the name of the virtual event these keys will be jpayne@69: mapped to jpayne@69: current_key_sequences - list, a list of all key sequence lists jpayne@69: currently mapped to virtual events, for overlap checking jpayne@69: _htest - bool, change box location when running htest jpayne@69: _utest - bool, do not wait when running unittest jpayne@69: """ jpayne@69: Toplevel.__init__(self, parent) jpayne@69: self.withdraw() # Hide while setting geometry. jpayne@69: self.configure(borderwidth=5) jpayne@69: self.resizable(height=False, width=False) jpayne@69: self.title(title) jpayne@69: self.transient(parent) jpayne@69: self.grab_set() jpayne@69: self.protocol("WM_DELETE_WINDOW", self.cancel) jpayne@69: self.parent = parent jpayne@69: self.action = action jpayne@69: self.current_key_sequences = current_key_sequences jpayne@69: self.result = '' jpayne@69: self.key_string = StringVar(self) jpayne@69: self.key_string.set('') jpayne@69: # Set self.modifiers, self.modifier_label. jpayne@69: self.set_modifiers_for_platform() jpayne@69: self.modifier_vars = [] jpayne@69: for modifier in self.modifiers: jpayne@69: variable = StringVar(self) jpayne@69: variable.set('') jpayne@69: self.modifier_vars.append(variable) jpayne@69: self.advanced = False jpayne@69: self.create_widgets() jpayne@69: self.update_idletasks() jpayne@69: self.geometry( jpayne@69: "+%d+%d" % ( jpayne@69: parent.winfo_rootx() + jpayne@69: (parent.winfo_width()/2 - self.winfo_reqwidth()/2), jpayne@69: parent.winfo_rooty() + jpayne@69: ((parent.winfo_height()/2 - self.winfo_reqheight()/2) jpayne@69: if not _htest else 150) jpayne@69: ) ) # Center dialog over parent (or below htest box). jpayne@69: if not _utest: jpayne@69: self.deiconify() # Geometry set, unhide. jpayne@69: self.wait_window() jpayne@69: jpayne@69: def showerror(self, *args, **kwargs): jpayne@69: # Make testing easier. Replace in #30751. jpayne@69: messagebox.showerror(*args, **kwargs) jpayne@69: jpayne@69: def create_widgets(self): jpayne@69: self.frame = frame = Frame(self, borderwidth=2, relief='sunken') jpayne@69: frame.pack(side='top', expand=True, fill='both') jpayne@69: jpayne@69: frame_buttons = Frame(self) jpayne@69: frame_buttons.pack(side='bottom', fill='x') jpayne@69: jpayne@69: self.button_ok = Button(frame_buttons, text='OK', jpayne@69: width=8, command=self.ok) jpayne@69: self.button_ok.grid(row=0, column=0, padx=5, pady=5) jpayne@69: self.button_cancel = Button(frame_buttons, text='Cancel', jpayne@69: width=8, command=self.cancel) jpayne@69: self.button_cancel.grid(row=0, column=1, padx=5, pady=5) jpayne@69: jpayne@69: # Basic entry key sequence. jpayne@69: self.frame_keyseq_basic = Frame(frame, name='keyseq_basic') jpayne@69: self.frame_keyseq_basic.grid(row=0, column=0, sticky='nsew', jpayne@69: padx=5, pady=5) jpayne@69: basic_title = Label(self.frame_keyseq_basic, jpayne@69: text=f"New keys for '{self.action}' :") jpayne@69: basic_title.pack(anchor='w') jpayne@69: jpayne@69: basic_keys = Label(self.frame_keyseq_basic, justify='left', jpayne@69: textvariable=self.key_string, relief='groove', jpayne@69: borderwidth=2) jpayne@69: basic_keys.pack(ipadx=5, ipady=5, fill='x') jpayne@69: jpayne@69: # Basic entry controls. jpayne@69: self.frame_controls_basic = Frame(frame) jpayne@69: self.frame_controls_basic.grid(row=1, column=0, sticky='nsew', padx=5) jpayne@69: jpayne@69: # Basic entry modifiers. jpayne@69: self.modifier_checkbuttons = {} jpayne@69: column = 0 jpayne@69: for modifier, variable in zip(self.modifiers, self.modifier_vars): jpayne@69: label = self.modifier_label.get(modifier, modifier) jpayne@69: check = Checkbutton(self.frame_controls_basic, jpayne@69: command=self.build_key_string, text=label, jpayne@69: variable=variable, onvalue=modifier, offvalue='') jpayne@69: check.grid(row=0, column=column, padx=2, sticky='w') jpayne@69: self.modifier_checkbuttons[modifier] = check jpayne@69: column += 1 jpayne@69: jpayne@69: # Basic entry help text. jpayne@69: help_basic = Label(self.frame_controls_basic, justify='left', jpayne@69: text="Select the desired modifier keys\n"+ jpayne@69: "above, and the final key from the\n"+ jpayne@69: "list on the right.\n\n" + jpayne@69: "Use upper case Symbols when using\n" + jpayne@69: "the Shift modifier. (Letters will be\n" + jpayne@69: "converted automatically.)") jpayne@69: help_basic.grid(row=1, column=0, columnspan=4, padx=2, sticky='w') jpayne@69: jpayne@69: # Basic entry key list. jpayne@69: self.list_keys_final = Listbox(self.frame_controls_basic, width=15, jpayne@69: height=10, selectmode='single') jpayne@69: self.list_keys_final.insert('end', *AVAILABLE_KEYS) jpayne@69: self.list_keys_final.bind('', self.final_key_selected) jpayne@69: self.list_keys_final.grid(row=0, column=4, rowspan=4, sticky='ns') jpayne@69: scroll_keys_final = Scrollbar(self.frame_controls_basic, jpayne@69: orient='vertical', jpayne@69: command=self.list_keys_final.yview) jpayne@69: self.list_keys_final.config(yscrollcommand=scroll_keys_final.set) jpayne@69: scroll_keys_final.grid(row=0, column=5, rowspan=4, sticky='ns') jpayne@69: self.button_clear = Button(self.frame_controls_basic, jpayne@69: text='Clear Keys', jpayne@69: command=self.clear_key_seq) jpayne@69: self.button_clear.grid(row=2, column=0, columnspan=4) jpayne@69: jpayne@69: # Advanced entry key sequence. jpayne@69: self.frame_keyseq_advanced = Frame(frame, name='keyseq_advanced') jpayne@69: self.frame_keyseq_advanced.grid(row=0, column=0, sticky='nsew', jpayne@69: padx=5, pady=5) jpayne@69: advanced_title = Label(self.frame_keyseq_advanced, justify='left', jpayne@69: text=f"Enter new binding(s) for '{self.action}' :\n" + jpayne@69: "(These bindings will not be checked for validity!)") jpayne@69: advanced_title.pack(anchor='w') jpayne@69: self.advanced_keys = Entry(self.frame_keyseq_advanced, jpayne@69: textvariable=self.key_string) jpayne@69: self.advanced_keys.pack(fill='x') jpayne@69: jpayne@69: # Advanced entry help text. jpayne@69: self.frame_help_advanced = Frame(frame) jpayne@69: self.frame_help_advanced.grid(row=1, column=0, sticky='nsew', padx=5) jpayne@69: help_advanced = Label(self.frame_help_advanced, justify='left', jpayne@69: text="Key bindings are specified using Tkinter keysyms as\n"+ jpayne@69: "in these samples: , , ,\n" jpayne@69: ", , .\n" jpayne@69: "Upper case is used when the Shift modifier is present!\n\n" + jpayne@69: "'Emacs style' multi-keystroke bindings are specified as\n" + jpayne@69: "follows: , where the first key\n" + jpayne@69: "is the 'do-nothing' keybinding.\n\n" + jpayne@69: "Multiple separate bindings for one action should be\n"+ jpayne@69: "separated by a space, eg., ." ) jpayne@69: help_advanced.grid(row=0, column=0, sticky='nsew') jpayne@69: jpayne@69: # Switch between basic and advanced. jpayne@69: self.button_level = Button(frame, command=self.toggle_level, jpayne@69: text='<< Basic Key Binding Entry') jpayne@69: self.button_level.grid(row=2, column=0, stick='ew', padx=5, pady=5) jpayne@69: self.toggle_level() jpayne@69: jpayne@69: def set_modifiers_for_platform(self): jpayne@69: """Determine list of names of key modifiers for this platform. jpayne@69: jpayne@69: The names are used to build Tk bindings -- it doesn't matter if the jpayne@69: keyboard has these keys; it matters if Tk understands them. The jpayne@69: order is also important: key binding equality depends on it, so jpayne@69: config-keys.def must use the same ordering. jpayne@69: """ jpayne@69: if sys.platform == "darwin": jpayne@69: self.modifiers = ['Shift', 'Control', 'Option', 'Command'] jpayne@69: else: jpayne@69: self.modifiers = ['Control', 'Alt', 'Shift'] jpayne@69: self.modifier_label = {'Control': 'Ctrl'} # Short name. jpayne@69: jpayne@69: def toggle_level(self): jpayne@69: "Toggle between basic and advanced keys." jpayne@69: if self.button_level.cget('text').startswith('Advanced'): jpayne@69: self.clear_key_seq() jpayne@69: self.button_level.config(text='<< Basic Key Binding Entry') jpayne@69: self.frame_keyseq_advanced.lift() jpayne@69: self.frame_help_advanced.lift() jpayne@69: self.advanced_keys.focus_set() jpayne@69: self.advanced = True jpayne@69: else: jpayne@69: self.clear_key_seq() jpayne@69: self.button_level.config(text='Advanced Key Binding Entry >>') jpayne@69: self.frame_keyseq_basic.lift() jpayne@69: self.frame_controls_basic.lift() jpayne@69: self.advanced = False jpayne@69: jpayne@69: def final_key_selected(self, event=None): jpayne@69: "Handler for clicking on key in basic settings list." jpayne@69: self.build_key_string() jpayne@69: jpayne@69: def build_key_string(self): jpayne@69: "Create formatted string of modifiers plus the key." jpayne@69: keylist = modifiers = self.get_modifiers() jpayne@69: final_key = self.list_keys_final.get('anchor') jpayne@69: if final_key: jpayne@69: final_key = translate_key(final_key, modifiers) jpayne@69: keylist.append(final_key) jpayne@69: self.key_string.set(f"<{'-'.join(keylist)}>") jpayne@69: jpayne@69: def get_modifiers(self): jpayne@69: "Return ordered list of modifiers that have been selected." jpayne@69: mod_list = [variable.get() for variable in self.modifier_vars] jpayne@69: return [mod for mod in mod_list if mod] jpayne@69: jpayne@69: def clear_key_seq(self): jpayne@69: "Clear modifiers and keys selection." jpayne@69: self.list_keys_final.select_clear(0, 'end') jpayne@69: self.list_keys_final.yview('moveto', '0.0') jpayne@69: for variable in self.modifier_vars: jpayne@69: variable.set('') jpayne@69: self.key_string.set('') jpayne@69: jpayne@69: def ok(self, event=None): jpayne@69: keys = self.key_string.get().strip() jpayne@69: if not keys: jpayne@69: self.showerror(title=self.keyerror_title, parent=self, jpayne@69: message="No key specified.") jpayne@69: return jpayne@69: if (self.advanced or self.keys_ok(keys)) and self.bind_ok(keys): jpayne@69: self.result = keys jpayne@69: self.grab_release() jpayne@69: self.destroy() jpayne@69: jpayne@69: def cancel(self, event=None): jpayne@69: self.result = '' jpayne@69: self.grab_release() jpayne@69: self.destroy() jpayne@69: jpayne@69: def keys_ok(self, keys): jpayne@69: """Validity check on user's 'basic' keybinding selection. jpayne@69: jpayne@69: Doesn't check the string produced by the advanced dialog because jpayne@69: 'modifiers' isn't set. jpayne@69: """ jpayne@69: final_key = self.list_keys_final.get('anchor') jpayne@69: modifiers = self.get_modifiers() jpayne@69: title = self.keyerror_title jpayne@69: key_sequences = [key for keylist in self.current_key_sequences jpayne@69: for key in keylist] jpayne@69: if not keys.endswith('>'): jpayne@69: self.showerror(title, parent=self, jpayne@69: message='Missing the final Key') jpayne@69: elif (not modifiers jpayne@69: and final_key not in FUNCTION_KEYS + MOVE_KEYS): jpayne@69: self.showerror(title=title, parent=self, jpayne@69: message='No modifier key(s) specified.') jpayne@69: elif (modifiers == ['Shift']) \ jpayne@69: and (final_key not in jpayne@69: FUNCTION_KEYS + MOVE_KEYS + ('Tab', 'Space')): jpayne@69: msg = 'The shift modifier by itself may not be used with'\ jpayne@69: ' this key symbol.' jpayne@69: self.showerror(title=title, parent=self, message=msg) jpayne@69: elif keys in key_sequences: jpayne@69: msg = 'This key combination is already in use.' jpayne@69: self.showerror(title=title, parent=self, message=msg) jpayne@69: else: jpayne@69: return True jpayne@69: return False jpayne@69: jpayne@69: def bind_ok(self, keys): jpayne@69: "Return True if Tcl accepts the new keys else show message." jpayne@69: try: jpayne@69: binding = self.bind(keys, lambda: None) jpayne@69: except TclError as err: jpayne@69: self.showerror( jpayne@69: title=self.keyerror_title, parent=self, jpayne@69: message=(f'The entered key sequence is not accepted.\n\n' jpayne@69: f'Error: {err}')) jpayne@69: return False jpayne@69: else: jpayne@69: self.unbind(keys, binding) jpayne@69: return True jpayne@69: jpayne@69: jpayne@69: if __name__ == '__main__': jpayne@69: from unittest import main jpayne@69: main('idlelib.idle_test.test_config_key', verbosity=2, exit=False) jpayne@69: jpayne@69: from idlelib.idle_test.htest import run jpayne@69: run(GetKeysDialog)