Custom probes

A local probe can share the terminal writer and event loop with core probes. Each probe owns its query choices. Each record owns its replies. This current-source example measures how far a space moves the cursor. It batches that measurement with the core ambiguous-width measurement.

Define a local module

The constructor captures TERM by value from the supplied environment. The explicit space_width field selects the measurement. For TERM=dumb, this example leaves the measurement unknown. The writer method sends the selected query, then optional DA1. The caller owns the flush.

Use Probe::new(env) to capture the environment and select useful domain queries. Keep cursor measurements explicit because they change screen content.

The selected query order is: space measurement, then optional DA1. The measurement writes CR, a space, CPR, CR, and ECH 1. It erases the first cell and leaves the cursor at column zero. Use a blank row with room for the space and the cursor advance.

rust
mod local {
    use std::io::{self, Write};
    use uncurses::ansi::ctrl::REQUEST_PRIMARY_DA;
    use uncurses::event::Event;
    use uncurses::terminal::Env;

    pub struct Probe {
        pub space_width: bool,
        term: Option<String>,
    }

    #[derive(Default)]
    pub struct Capabilities {
        pub space_width: Option<u16>,
        pending: bool,
    }

    impl Probe {
        pub fn new(env: &dyn Env) -> Self {
            Self { space_width: false, term: env.get("TERM") }
        }

        pub fn query_capabilities<W: Write>(
            &self,
            writer: &mut W,
            terminator: bool,
        ) -> io::Result<Capabilities> {
            let pending = self.space_width && self.term.as_deref() != Some("dumb");
            if pending {
                writer.write_all(b"\r \x1b[6n\r\x1b[X")?;
            }
            if terminator {
                writer.write_all(REQUEST_PRIMARY_DA)?;
            }
            Ok(Capabilities { pending, ..Capabilities::default() })
        }

        pub fn measures_space(&self) -> bool {
            self.space_width && self.term.as_deref() != Some("dumb")
        }
    }

    impl Capabilities {
        pub fn record(&mut self, event: &Event) {
            match event {
                Event::CursorPosition { position, .. } if self.pending => {
                    self.space_width = Some(position.x);
                    self.pending = false;
                }
                Event::PrimaryDeviceAttributes(_) => self.pending = false,
                _ => {}
            }
        }
    }
}

The record accepts only cursor replies that the application assigns to it. DA1 closes a pending measurement. Collection completion stays in the application. The optional value preserves the distinction between an answer and silence.

Write both probes and route replies

Append this fragment after the module above to make a complete application. Core writes its cursor request first. The local probe writes its request second. The application collects cursor replies before it assigns them in request order. The application checks the geometry before it selects either measurement.

rust
use std::io::Write;
use std::time::{Duration, Instant};
use uncurses::event::{Event, KeyCode};
use uncurses::program::{Probe, Program};

fn main() -> std::io::Result<()> {
    let mut program = Program::stdio()?;
    let result: std::io::Result<Option<u16>> = (|| {
        program.init()?;
        let mut core_probe = Probe::new(program.env());
        let mut local_probe = local::Probe::new(program.env());
        let enough_columns = program.screen().size().width >= 3;
        core_probe.eaw_width = enough_columns;
        local_probe.space_width = enough_columns;
        let core_cursor = core_probe.eaw_width;
        let cursor_count = usize::from(core_cursor)
            + usize::from(local_probe.measures_space());
        let (mut core_caps, mut local_caps) = {
            let screen = program.screen_mut();
            let core = core_probe.query_capabilities(screen, false)?;
            let local = local_probe.query_capabilities(screen, true)?;
            if cursor_count > 0 {
                screen.invalidate();
                screen.invalidate_tracked_cursor();
            }
            screen.flush()?;
            (core, local)
        };

        let mut cursor_replies = Vec::new();
        let mut terminator = None;
        let mut keys = Vec::new();
        let deadline = Instant::now() + Duration::from_millis(300);
        'startup: while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
            if !program.poll_event(Some(remaining))? {
                break;
            }
            while let Some(event) = program.try_read_event()? {
                match &event {
                    Event::PrimaryDeviceAttributes(_) => {
                        terminator = Some(event);
                        break 'startup;
                    }
                    Event::CursorPosition { .. } => cursor_replies.push(event),
                    Event::KeyPress(key)
                        if cursor_replies.len() < cursor_count && key.code == KeyCode::F(3) => {}
                    Event::KeyPress(_) | Event::KeyRelease(_) => keys.push(event),
                    _ => {
                        core_caps.record(&event);
                        local_caps.record(&event);
                    }
                }
            }
        }
        if cursor_replies.len() == cursor_count {
            for (index, event) in cursor_replies.iter().enumerate() {
                if core_cursor && index == 0 {
                    core_caps.record(event);
                } else {
                    local_caps.record(event);
                }
            }
        }
        if let Some(event) = terminator {
            core_caps.record(&event);
            local_caps.record(&event);
        }
        for event in keys.into_iter().rev() {
            program.unread_event(event);
        }
        program.apply_defaults(&core_caps)?;
        Ok(local_caps.space_width)
    })();
    let finish = program.finish();
    let width = result?;
    finish?;
    println!("Space width: {width:?}");
    Ok(())
}

Run this application before the first frame, on a blank row. It preserves ordinary keys for the next input loop. An application with paste or mouse input also retains or processes those events. The row-1 CPR ambiguity can suppress a real modified F3 during the cursor wait.

The assignment assumes each request receives one reply in order. The example assigns measurements only when the final count matches the number of requests. It then broadcasts DA1 before it applies the results. An incomplete or extra set leaves both measurements unknown. Missing, late, or stray CPR has no request identity. Treat measurements as unknown whenever that assumption fails. A timeout stops collection but leaves terminal requests active. DA1 gives this application a startup boundary; multiplexers can deliver identified replies later. Continue to record those identified replies in the appropriate domain record.

For domain extensions, use the same structure with typed events. For example, uncurses_glyph::Probe::new(env) captures its environment and enables the support query. Its query method returns uncurses_glyph::Capabilities. That record exposes support() -> Option<&GlyphSupport>. The Glyph probe applies Apple Terminal APC safety rules. Give a domain manager its own record and keep runtime state separately.

For Kitty drag and drop, write the query through uncurses::ansi::drag_drop and collect the typed replies in an application record. That record can share this startup loop with the core and Glyph records.

See Querying the terminal for general startup policy. The executable probe_batch example shows the same composition pattern. Run it with -- --replay for deterministic output through an in-memory writer.

Edit this page

Search documentation

Type to search the documentation.