1# This file is part of ranger, the console file manager.
2# License: GNU GPL version 3, see the file "AUTHORS" for details.
3
4"""Interrupt Signal handler for curses
5
6This module can catch interrupt signals which would otherwise
7rise a KeyboardInterrupt exception and handle it by pushing
8a Ctrl+C (ASCII value 3) to the curses getch stack.
9"""
10
11from __future__ import (absolute_import, division, print_function)
12
13import curses
14import signal
15
16_do_catch_interrupt = True  # pylint: disable=invalid-name
17
18
19def catch_interrupt(boolean=True):
20    """Should interrupts be caught and simulate a ^C press in curses?"""
21    global _do_catch_interrupt  # pylint: disable=global-statement,invalid-name
22    old_value = _do_catch_interrupt
23    _do_catch_interrupt = bool(boolean)
24    return old_value
25
26# The handler which will be used in signal.signal()
27
28
29def _interrupt_handler(signum, frame):
30    # if a keyboard-interrupt occurs...
31    if _do_catch_interrupt:
32        # push a Ctrl+C (ascii value 3) to the curses getch stack
33        curses.ungetch(3)
34    else:
35        # use the default handler
36        signal.default_int_handler(signum, frame)
37
38
39def install_interrupt_handler():
40    """Install the custom interrupt_handler"""
41    signal.signal(signal.SIGINT, _interrupt_handler)
42
43
44def restore_interrupt_handler():
45    """Restore the default_int_handler"""
46    signal.signal(signal.SIGINT, signal.default_int_handler)
47