Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(linux): harden the evdev click reader (EINTR, hotplug, device loss, double-click)

Benjamin Freeman4ce923726372
diff --git a/electron/native/pipewire-capture/src/input.rs b/electron/native/pipewire-capture/src/input.rs
index 7de31e390..dd47ef73e 100644
--- a/electron/native/pipewire-capture/src/input.rs
+++ b/electron/native/pipewire-capture/src/input.rs
@@ -13,19 +13,32 @@
//! SCOPE AND PRIVACY. A pointer node can also deliver keystrokes on a combined
//! keyboard+mouse device. This reader inspects ONLY `EV_KEY` events whose code is
//! `BTN_LEFT`, and only their press edge; it never reads, stores, or forwards any
-//! other key code, and it only ever opens devices that advertise `BTN_LEFT` in
-//! the first place. Set `OPENSCREEN_DISABLE_CLICK_CAPTURE=1` to turn it off
-//! entirely even where the permission exists.
-
+//! other key code. Enumerating the devices does briefly open each readable
+//! `/dev/input/event*` node to inspect its capability bits, but any node that
+//! does not advertise `BTN_LEFT` is dropped immediately, without a single event
+//! ever being read from it — only `BTN_LEFT` devices get a reader. Set
+//! `OPENSCREEN_DISABLE_CLICK_CAPTURE=1` to turn it off entirely even where the
+//! permission exists.
+
+use std::collections::HashSet;
+use std::io::ErrorKind;
+use std::path::PathBuf;
use std::sync::mpsc::Sender;
use std::thread;
+use std::time::Duration;
use evdev::{Device, EventType, KeyCode};
+use crate::events::timestamp_ms;
use crate::Message;
const DISABLE_ENV: &str = "OPENSCREEN_DISABLE_CLICK_CAPTURE";
+/// How often the hotplug watcher re-scans `/dev/input` for pointer devices that
+/// appeared after startup. A few seconds is imperceptible for a device the user
+/// just plugged in and costs a cheap directory walk.
+const RESCAN_INTERVAL: Duration = Duration::from_secs(3);
+
/// True when this evdev event is the press edge of the left mouse button.
///
/// Extracted as a pure function so the decision is unit-testable without a real
@@ -53,30 +66,52 @@ pub enum ClickCapture {
Active,
}
-/// Opens every readable pointer device that reports `BTN_LEFT` and spawns a
-/// reader thread per device.
+/// Opens every readable pointer device that reports `BTN_LEFT`, spawns a reader
+/// thread per device, and leaves a daemon thread re-scanning for devices plugged
+/// in later.
///
/// Never fails: an unreadable node (the common case, when the user is not in the
/// `input` group) is skipped by `evdev::enumerate`, and no readable node at all
-/// simply means every sample stays `"move"`, exactly as before this existed.
+/// simply means every sample stays `"move"`, exactly as before this existed. The
+/// returned value reflects the INITIAL scan only — a device attached afterwards
+/// is adopted by the watcher without changing it.
pub fn spawn_readers(sender: &Sender<Message>) -> ClickCapture {
if std::env::var_os(DISABLE_ENV).is_some() {
return ClickCapture::Disabled;
}
- let mut opened = 0usize;
- for (_path, device) in evdev::enumerate() {
- if !device_reports_left_button(&device) {
+ // Paths already given a reader. Only ever grows, so a device is never
+ // double-read; the one case it misses is a device that unplugs and returns
+ // on the SAME node path — a replug usually lands on a fresh `eventNN`, which
+ // is not in the set and so is picked up.
+ let mut opened: HashSet<PathBuf> = HashSet::new();
+ scan_once(sender, &mut opened);
+ let result = if opened.is_empty() {
+ ClickCapture::NoDevice
+ } else {
+ ClickCapture::Active
+ };
+ // Hotplug: the one-shot scan above cannot see a mouse attached mid-recording,
+ // so a daemon thread re-scans and starts readers for nodes it has not seen.
+ // Detached, like the reader threads — it ends when the process does.
+ let watch_sender = sender.clone();
+ thread::spawn(move || loop {
+ thread::sleep(RESCAN_INTERVAL);
+ scan_once(&watch_sender, &mut opened);
+ });
+ result
+}
+
+/// Spawns a reader for every `BTN_LEFT` device not already in `opened`, recording
+/// each newly opened node's path. Shared by the initial scan and the watcher.
+fn scan_once(sender: &Sender<Message>, opened: &mut HashSet<PathBuf>) {
+ for (path, device) in evdev::enumerate() {
+ if opened.contains(&path) || !device_reports_left_button(&device) {
continue;
}
- opened += 1;
+ opened.insert(path);
let forward = sender.clone();
thread::spawn(move || read_device(device, forward));
}
- if opened > 0 {
- ClickCapture::Active
- } else {
- ClickCapture::NoDevice
- }
}
/// A touchpad advertises `BTN_LEFT` for a physical clickpad press, so it passes
@@ -93,17 +128,27 @@ fn device_reports_left_button(device: &Device) -> bool {
}
/// Blocks reading `device`, forwarding one `PointerButton` message per left-button
-/// press. Returns when the device errors (e.g. unplugged) or the loop's channel
-/// has closed, so the thread cannot outlive the recording it serves.
+/// press, each stamped with the press time so a click is not backdated to the
+/// next cursor sample. Returns when the device fails terminally (e.g. unplugged)
+/// or the loop's channel has closed, so the thread cannot outlive the recording
+/// it serves. A transient `EINTR` is retried, not mistaken for an unplug.
fn read_device(mut device: Device, sender: Sender<Message>) {
loop {
let events = match device.fetch_events() {
Ok(events) => events,
- Err(_) => return,
+ // A signal interrupted the blocking read — not a device failure.
+ Err(err) if err.kind() == ErrorKind::Interrupted => continue,
+ // A real error, typically the device unplugging. Report it rather
+ // than ending silently, so click capture going quiet mid-recording
+ // is answerable from the log; the watcher re-adopts it on a replug.
+ Err(err) => {
+ let _ = sender.send(Message::PointerDeviceLost(err.to_string()));
+ return;
+ }
};
for event in events {
if is_left_button_press(event.event_type(), event.code(), event.value())
- && sender.send(Message::PointerButton).is_err()
+ && sender.send(Message::PointerButton(timestamp_ms())).is_err()
{
return;
}
diff --git a/electron/native/pipewire-capture/src/main.rs b/electron/native/pipewire-capture/src/main.rs
index 9b18071f0..51ce8e5b4 100644
--- a/electron/native/pipewire-capture/src/main.rs
+++ b/electron/native/pipewire-capture/src/main.rs
@@ -219,10 +219,16 @@ struct AudioSourceConfig {
enum Message {
Portal(Box<Result<portal::PortalStream, portal::PortalError>>),
Stream(StreamEvent),
- /// A left mouse-button press observed on evdev — the next cursor sample is
- /// tagged `"click"`. See [`input`] for why this is the only way to see a
- /// button on Wayland, and for its permission and privacy model.
- PointerButton,
+ /// A left mouse-button press observed on evdev, carrying the press time in
+ /// milliseconds so the emitted click sample is stamped when it happened
+ /// rather than at the next throttled sample. See [`input`] for why this is
+ /// the only way to see a button on Wayland, and for its permission and
+ /// privacy model.
+ PointerButton(u64),
+ /// A pointer reader thread stopped on a device error (typically an unplug);
+ /// the string is the OS error. Surfaced as a warning so click capture going
+ /// quiet mid-recording is not silent.
+ PointerDeviceLost(String),
/// Arm a deferred session: connect to PipeWire and start encoding.
Record,
Pause,
@@ -602,8 +608,6 @@ fn run<W: Write>(
let mut cursor: Option<CursorState> = None;
let mut known_assets: HashSet<String> = HashSet::new();
let mut pending_asset: Option<CursorAsset> = None;
- // Set by a `PointerButton` message, consumed by the next emitted sample.
- let mut pending_click = false;
// The pw_stream has reached `streaming`, i.e. mutter has actually started
// handing us frames. Presses are ignored until then: before it, the only
// thing on screen is the portal's own picker, and the click that dismisses
@@ -672,17 +676,38 @@ fn run<W: Write>(
match receiver.recv_timeout(config.tick) {
Ok(Message::Stop) => break,
- // Latched, not emitted here: a bare press carries no position, so it
- // waits for the next sample (which does) to become a `"click"`.
- // Dropped before the stream is live (see `streaming`): a press that
- // lands while the picker is still up is the click on its "Share"
- // button, not content, and must not tag the first real sample.
- Ok(Message::PointerButton) => {
+ // Emit a click sample straight away at the current cursor position,
+ // stamped with the press time the reader captured: immediate so it is
+ // not backdated to the next throttled sample, and one sample per press
+ // so a rapid double-click reads as two clicks rather than collapsing
+ // into one. Dropped before the stream is live (see `streaming`): a
+ // press while the picker is still up is the click on its "Share"
+ // button, not content.
+ Ok(Message::PointerButton(press_ms)) => {
if streaming {
- pending_click = true;
+ emit_sample(
+ emitter,
+ &cursor,
+ size,
+ &mut pending_asset,
+ Some(press_ms),
+ );
}
}
+ // A reader lost its device (typically an unplug). Report it — if it
+ // was the only pointer, clicks stop until one is (re)connected, which
+ // the input watcher will pick up.
+ Ok(Message::PointerDeviceLost(reason)) => {
+ let _ = emitter.emit(&Event::Warning {
+ code: "click-capture-device-lost".to_owned(),
+ message: format!(
+ "a pointer device stopped delivering clicks ({reason}); if it was the \
+ only one, clicks are not captured until a device is reconnected"
+ ),
+ });
+ }
+
Ok(Message::Pause) => {
paused = true;
if let Some(capture) = capture.as_mut() {
@@ -1181,14 +1206,14 @@ fn run<W: Write>(
// A new sprite ships immediately; positions respect the sample
// interval so a 120fps compositor cannot flood stdout.
if asset_is_new || last_emit.elapsed() >= config.sample_interval {
- emit_sample(emitter, &cursor, size, &mut pending_asset, &mut pending_click);
+ emit_sample(emitter, &cursor, size, &mut pending_asset, None);
last_emit = Instant::now();
}
}
Err(RecvTimeoutError::Timeout) => {
if cursor.is_some() && last_emit.elapsed() >= config.sample_interval {
- emit_sample(emitter, &cursor, size, &mut pending_asset, &mut pending_click);
+ emit_sample(emitter, &cursor, size, &mut pending_asset, None);
last_emit = Instant::now();
}
// The heartbeat that keeps the output at a constant frame rate
@@ -1277,30 +1302,30 @@ fn finish_capture<W: Write>(
}
}
+/// Emits one cursor sample at the current position. `click` is `Some(press_ms)`
+/// for a left-button press — the sample is then tagged `"click"` and stamped with
+/// that press time — or `None` for an ordinary throttled position sample stamped
+/// now. Either way a pending new sprite rides out on it.
fn emit_sample<W: Write>(
emitter: &mut Emitter<W>,
cursor: &Option<CursorState>,
size: Option<(i32, i32)>,
pending_asset: &mut Option<CursorAsset>,
- pending_click: &mut bool,
+ click: Option<u64>,
) {
let (Some(state), Some((width, height))) = (cursor, size) else {
return;
};
let visible = state.x >= 0 && state.y >= 0 && state.x < width && state.y < height;
- // A click observed since the last sample rides out on this one, cleared only
- // when a sample is actually emitted — at the sample cadence the cursor has not
- // moved enough for the position to be wrong. Presses before the stream is live
- // are never latched (see the `PointerButton` arm), so this cannot carry the
- // portal picker's own "Share" click into the recording.
- let interaction_type = if *pending_click {
- *pending_click = false;
- Some("click".to_owned())
- } else {
- None
+ // A click carries its own press time so the bounce lands when the button went
+ // down, not up to a sample interval later; the position is the latest known,
+ // which at the sample cadence has not moved enough to be wrong.
+ let (timestamp, interaction_type) = match click {
+ Some(press_ms) => (press_ms, Some("click".to_owned())),
+ None => (timestamp_ms(), None),
};
let _ = emitter.emit(&Event::CursorSample {
- timestamp_ms: timestamp_ms(),
+ timestamp_ms: timestamp,
x: state.x,
y: state.y,
width,