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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/* Copyright (C) 2023 Purism SPC
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

use mio;
use std::ffi::OsString;
use std::io;
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use udev;

struct Notify {
    var: Condvar,
    m: Mutex<()>,
}

impl Notify {
    fn new() -> Arc<Self> {
        Arc::new(Self {
            var: Condvar::new(),
            m: Mutex::new(()),
        })
    }
    
    fn notify(n: Arc<Self>) {
        let Notify { var, .. } = &*n;
        var.notify_all()
    }
    
    fn wait(n: Arc<Self>) {
        let Notify { var, m } = &*n;
        let m = m.lock().unwrap();
        let _ignore_poisoned = var.wait(m);
    }
}

#[derive(Debug)]
pub enum EventKind {
    Added,
    Removed,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Device {
    pub system_path: OsString,
    pub device_path: OsString,
    pub device_node: Option<OsString>,
}

impl Device {
    /// Just a demo. I'm not sure what property is meant to be stable.
    pub fn stable_id(&self) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        self.device_path.hash(&mut hasher);
        hasher.finish()
    }
}

impl From<udev::Device> for Device {
    fn from(d: udev::Device) -> Self {
        Self {
            system_path: d.syspath().into(),
            device_path: d.devpath().into(),
            device_node: d.devnode().map(OsString::from),
        }
    }
}

#[derive(Debug)]
pub struct Event {
    pub device: Device,
    pub kind: EventKind,
}

const WAKE_TOKEN: mio::Token = mio::Token(10);

pub struct Watcher {
    waker: Arc<mio::Waker>,
    thread: Option<thread::JoinHandle<Result<(), io::Error>>>,
}

impl Watcher {
    /// Spawns a new watcher executing f on each event
    pub fn spawn(f: (impl FnMut(Event) + Send + 'static)) -> Result<Self, io::Error> {
        let poll = mio::Poll::new()?;
        let initialized = Notify::new();
        let waker = Arc::new(mio::Waker::new(poll.registry(), WAKE_TOKEN)?);
        let initialized_inner = initialized.clone();
        let thread = Some(thread::spawn(move || 
            watch(poll, initialized_inner, f)
        ));
        
        Notify::wait(initialized);
        Ok(Self {
            waker,
            thread,
        })
    }
    
    /// Tries to stop the watcher and waits for its result.
    /// Call this to make sure that the watcher actually stops - dropping it doesn't wait and doesn't ensure that it's really stopped.
    /// Consecutive calls return Ok(()).
    pub fn stop(mut self) -> Result<Result<(), io::Error>, (Self, io::Error)> {
        match self.waker.wake() {
            Ok(()) => Ok({
                if let Some(thread) = self.thread.take() {
                    thread.join().unwrap()
                } else {
                    Ok(())
                }
            }),
            Err(e) => Err((self, e)),
        }
    }

}

impl Drop for Watcher {
    fn drop(&mut self) {
        let _ = self.waker.wake();
        // The thread may get cleaned up or it may not.
        // Either way, we did all we can, and we don't want to wait.
    }
}

fn watch(
    mut poll: mio::Poll,
    initialized: Arc<Notify>,
    mut f: impl FnMut(Event),
) -> io::Result<()> {
    let mut socket = udev::MonitorBuilder::new()?
        .match_subsystem("media")?
        .match_subsystem("video4linux")?
        .listen()?;

    let mut events = mio::Events::with_capacity(16);
    poll.registry().register(
        &mut socket,
        mio::Token(0),
        mio::Interest::READABLE | mio::Interest::WRITABLE,
    )?;

    let mut e = udev::Enumerator::new()?;
    e.match_subsystem("media")?;
    e.match_subsystem("video4linux")?;
    e.match_is_initialized()?;
    for device in e.scan_devices()? {
        f(Event { device: device.into(), kind: EventKind::Added });
    }
    Notify::notify(initialized);
    
    loop {
        poll.poll(&mut events, None)?;
        let stop_message = events.iter().find(
            |ev| ev.is_readable() && ev.token() == WAKE_TOKEN
        );
        if stop_message.is_some() {
            break;
        }

        for ev in socket.iter() {
            let kind = match ev.event_type() {
                udev::EventType::Add => Some(EventKind::Added),
                udev::EventType::Remove => Some(EventKind::Removed),
                _ => None,
            };
            if let Some(kind) = kind {
                f(Event { device: ev.device().into(), kind })
            }
        }
    }
    Ok(())
}