@@ -836,37 +836,38 @@ def _notify_change_observers(self):
836836
837837 def begin_typing (self , x ):
838838 self .capturekeystrokes = True
839- # Check for toolmanager handling the keypress
840- if self .ax .figure .canvas .manager .key_press_handler_id is not None :
841- # Disable command keys so that the user can type without
842- # command keys causing figure to be saved, etc.
843- self ._restore_keymap = ExitStack ()
839+ # Disable keypress shortcuts, which may otherwise cause the figure to
840+ # be saved, closed, etc., until the user stops typing. The way to
841+ # achieve this depends on whether toolmanager is in use.
842+ stack = ExitStack () # Register cleanup actions when user stops typing.
843+ self ._on_stop_typing = stack .close
844+ toolmanager = getattr (
845+ self .ax .figure .canvas .manager , "toolmanager" , None )
846+ if toolmanager is not None :
847+ # If using toolmanager, lock keypresses, and plan to release the
848+ # lock when typing stops.
849+ toolmanager .keypresslock (self )
850+ stack .push (toolmanager .keypresslock .release , self )
851+ else :
852+ # If not using toolmanager, disable all keypress-related rcParams.
844853 # Avoid spurious warnings if keymaps are getting deprecated.
845854 with cbook ._suppress_matplotlib_deprecation_warning ():
846- self ._restore_keymap .enter_context (
847- mpl .rc_context ({k : [] for k in mpl .rcParams
848- if k .startswith ('keymap.' )}))
849- else :
850- self .ax .figure .canvas .manager .toolmanager .keypresslock (self )
855+ stack .enter_context (mpl .rc_context (
856+ {k : [] for k in mpl .rcParams if k .startswith ("keymap." )}))
851857
852858 def stop_typing (self ):
853- notifysubmit = False
854- # Because _notify_submit_users might throw an error in the user's code,
855- # we only want to call it once we've already done our cleanup.
856859 if self .capturekeystrokes :
857- # Check for toolmanager handling the keypress
858- if self .ax .figure .canvas .manager .key_press_handler_id is not None :
859- # since the user is no longer typing,
860- # reactivate the standard command keys
861- self ._restore_keymap .close ()
862- else :
863- toolmanager = self .ax .figure .canvas .manager .toolmanager
864- toolmanager .keypresslock .release (self )
860+ self ._on_stop_typing ()
861+ self ._on_stop_typing = None
865862 notifysubmit = True
863+ else :
864+ notifysubmit = False
866865 self .capturekeystrokes = False
867866 self .cursor .set_visible (False )
868867 self .ax .figure .canvas .draw ()
869868 if notifysubmit :
869+ # Because _notify_submit_observers might throw an error in the
870+ # user's code, only call it once we've already done our cleanup.
870871 self ._notify_submit_observers ()
871872
872873 def position_cursor (self , x ):
0 commit comments