5151_application = None
5252
5353
54+ def _shutdown_application (app ):
55+ # The application might prematurely shut down if Ctrl-C'd out of IPython,
56+ # so close all windows.
57+ for win in app .get_windows ():
58+ win .destroy ()
59+ # The PyGObject wrapper incorrectly thinks that None is not allowed, or we
60+ # would call this:
61+ # Gio.Application.set_default(None)
62+ # Instead, we set this property and ignore default applications with it:
63+ app ._created_by_matplotlib = True
64+ global _application
65+ _application = None
66+
67+
5468def _create_application ():
5569 global _application
5670
5771 if _application is None :
5872 app = Gio .Application .get_default ()
59- if app is None :
73+ if app is None or getattr ( app , '_created_by_matplotlib' ) :
6074 # display_is_valid returns False only if on Linux and neither X11
6175 # nor Wayland display can be opened.
6276 if not mpl ._c_internal_utils .display_is_valid ():
@@ -66,6 +80,7 @@ def _create_application():
6680 # The activate signal must be connected, but we don't care for
6781 # handling it, since we don't do any remote processing.
6882 _application .connect ('activate' , lambda * args , ** kwargs : None )
83+ _application .connect ('shutdown' , _shutdown_application )
6984 _application .register ()
7085 cbook ._setup_new_guiapp ()
7186 else :
@@ -851,6 +866,8 @@ def mainloop():
851866 if _application is None :
852867 return
853868
854- _application .run () # Quits when all added windows close.
855- # Running after quit is undefined, so create a new one next time.
856- _application = None
869+ try :
870+ _application .run () # Quits when all added windows close.
871+ finally :
872+ # Running after quit is undefined, so create a new one next time.
873+ _application = None
0 commit comments