| 1 |
# |
| 2 |
# Allows GTK 3 python applications to exit when CTRL-C is raised |
| 3 |
# From https://bugzilla.gnome.org/show_bug.cgi?id=622084 |
| 4 |
# |
| 5 |
# Author: Simon Feltman |
| 6 |
# License: Presume same as pygobject |
| 7 |
# |
| 8 |
|
| 9 |
|
| 10 |
import sys |
| 11 |
import signal |
| 12 |
from typing import ClassVar, List |
| 13 |
|
| 14 |
from gi.repository import GLib |
| 15 |
|
| 16 |
|
| 17 |
class InterruptibleLoopContext: |
| 18 |
""" |
| 19 |
Context Manager for GLib/Gtk based loops. |
| 20 |
|
| 21 |
Usage of this context manager will install a single GLib unix signal handler |
| 22 |
and allow for multiple context managers to be nested using this single handler. |
| 23 |
""" |
| 24 |
|
| 25 |
#: Global stack context loops. This is added to per InterruptibleLoopContext |
| 26 |
#: instance and allows for context nesting using the same GLib signal handler. |
| 27 |
_loop_contexts: ClassVar[List['InterruptibleLoopContext']] = [] |
| 28 |
|
| 29 |
#: Single source id for the unix signal handler. |
| 30 |
_signal_source_id = None |
| 31 |
|
| 32 |
@classmethod |
| 33 |
def _glib_sigint_handler(cls, user_data): |
| 34 |
context = cls._loop_contexts[-1] |
| 35 |
context._quit_by_sigint = True |
| 36 |
context._loop_exit_func() |
| 37 |
|
| 38 |
# keep the handler around until we explicitly remove it |
| 39 |
return True |
| 40 |
|
| 41 |
def __init__(self, loop_exit_func): |
| 42 |
self._loop_exit_func = loop_exit_func |
| 43 |
self._quit_by_sigint = False |
| 44 |
|
| 45 |
def __enter__(self): |
| 46 |
# Only use unix_signal_add if this is not win32 and there has |
| 47 |
# not already been one. |
| 48 |
if sys.platform != 'win32' and not InterruptibleLoopContext._loop_contexts: |
| 49 |
# Add a glib signal handler |
| 50 |
source_id = GLib.unix_signal_add( |
| 51 |
GLib.PRIORITY_DEFAULT, signal.SIGINT, self._glib_sigint_handler, None |
| 52 |
) |
| 53 |
InterruptibleLoopContext._signal_source_id = source_id |
| 54 |
|
| 55 |
InterruptibleLoopContext._loop_contexts.append(self) |
| 56 |
|
| 57 |
def __exit__(self, exc_type, exc_value, traceback): |
| 58 |
context = InterruptibleLoopContext._loop_contexts.pop() |
| 59 |
assert self == context |
| 60 |
|
| 61 |
# if the context stack is empty and we have a GLib signal source, |
| 62 |
# remove the source from GLib and clear out the variable. |
| 63 |
if ( |
| 64 |
not InterruptibleLoopContext._loop_contexts |
| 65 |
and InterruptibleLoopContext._signal_source_id is not None |
| 66 |
): |
| 67 |
GLib.source_remove(InterruptibleLoopContext._signal_source_id) |
| 68 |
InterruptibleLoopContext._signal_source_id = None |
| 69 |
|
| 70 |
if self._quit_by_sigint: |
| 71 |
# caught by _glib_sigint_handler() |
| 72 |
raise KeyboardInterrupt |