aboutsummaryrefslogtreecommitdiffstats
path: root/src/ctrlc.rs
blob: 9bf53fa127e308f575e526c03ca9a246e74526db (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use crate::Session;
use libc::c_int;
use nix::sys::signal::*;
use std::{sync::*, time::Instant};

static SESSION: Mutex<Option<Arc<Mutex<Session>>>> = Mutex::new(None);

fn handle() {
    let Ok(mut se) = SESSION.lock() else { return };
    let Some(se) = se.as_mut() else { return };
    let Ok(mut se) = se.lock() else { return };
    se.ctrlc.last_press = Instant::now();
}

extern "C" fn c_handle(_signal: c_int) {
    // cannot propagate panic into C-land
    let _ = std::panic::catch_unwind(|| {
        if let Err(e) = std::panic::catch_unwind(handle) {
            eprintln!("{e:?}"); // might panic
        }
    });
}

pub struct CtrlC {
    last_press: Instant,
}

impl Default for CtrlC {
    fn default() -> Self {
        Self {
            last_press: Instant::now(),
        }
    }
}

struct Teardown;
impl Drop for Teardown {
    fn drop(&mut self) {
        teardown();
    }
}

fn teardown() {
    unsafe {
        let _ = signal(Signal::SIGINT, SigHandler::SigDfl);
    }
    if let Ok(mut se) = SESSION.lock() {
        *se = None;
    }
}

#[must_use]
pub fn setup(session: Arc<Mutex<Session>>) -> impl Drop {
    *SESSION.lock().unwrap() = Some(session);
    unsafe {
        signal(Signal::SIGINT, SigHandler::Handler(c_handle))
            .expect("failed to set ctrl+c signal handler");
    }
    Teardown
}

pub fn pressed_since(session: &Session, instant: Instant) -> bool {
    session.ctrlc.last_press > instant
}