Skip to main content

uncurses/ansi/
program_status.rs

1//! Program status reports and feature detection through OSC 7501.
2//!
3//! Each report replaces one terminal record. An absent ID selects the root.
4//! A clear report removes its record and descendants; clearing the root
5//! removes all records. Screen switches leave records intact. Done and error
6//! records survive process exit and the next shell prompt.
7//!
8//! Writers use `ESC ] 7501 ; pairs ESC \`. Messages and titles are standard
9//! base64 of UTF-8. Unsupported terminals ignore these sequences.
10//!
11//! See the [protocol specification](https://www.superlogical.com/rex/docs/build/program-status).
12
13use std::io::{self, Write};
14
15use base64::Engine as _;
16use base64::engine::general_purpose::STANDARD;
17
18/// Query OSC 7501 support. The reply starts with `?` and may list accepted
19/// states and kinds.
20pub const REQUEST_PROGRAM_STATUS: &[u8] = b"\x1b]7501;?\x1b\\";
21
22/// State of a program or one of its tasks.
23///
24/// Standard names are associated constants. Use [`Self::new`] for a name
25/// advertised by a protocol extension. The writer validates names before
26/// output; construction does not establish terminal support.
27///
28/// State and kind names are distinct types:
29///
30/// ```compile_fail
31/// use uncurses::ansi::program_status::{ProgramStatus, ProgramStatusKind};
32///
33/// let report = ProgramStatus::new(ProgramStatusKind::AUTH);
34/// ```
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub struct ProgramStatusState<'a>(&'a str);
37
38impl<'a> ProgramStatusState<'a> {
39    /// At rest, ready for the user's next instruction.
40    pub const IDLE: Self = Self("idle");
41    /// Work is in progress.
42    pub const WORKING: Self = Self("working");
43    /// Work finished and its result is ready.
44    pub const DONE: Self = Self("done");
45    /// Work requires user input before it can continue.
46    pub const BLOCKED: Self = Self("blocked");
47    /// Work failed and stopped.
48    pub const ERROR: Self = Self("error");
49    /// Remove the addressed record and all descendants.
50    pub const CLEAR: Self = Self("clear");
51
52    /// Borrow a state name without validation.
53    ///
54    /// Check the terminal's accepted states before use. The writer accepts
55    /// nonempty values from `[A-Za-z0-9_.,+/=-]` within the sequence limit.
56    pub const fn new(name: &'a str) -> Self {
57        Self(name)
58    }
59
60    /// Return the state name used on the wire.
61    pub const fn as_str(self) -> &'a str {
62        self.0
63    }
64}
65
66/// What a blocked program needs from the user.
67///
68/// Standard names are associated constants. Use [`Self::new`] for a name
69/// advertised by a protocol extension. The writer validates names before
70/// output; construction does not establish terminal support.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
72pub struct ProgramStatusKind<'a>(&'a str);
73
74impl<'a> ProgramStatusKind<'a> {
75    /// Approval for an action.
76    pub const PERMISSION: Self = Self("permission");
77    /// An answer to a question.
78    pub const QUESTION: Self = Self("question");
79    /// Authentication, such as a login or credential.
80    pub const AUTH: Self = Self("auth");
81
82    /// Borrow a kind name without validation.
83    ///
84    /// Check the terminal's accepted kinds before use. The writer accepts
85    /// nonempty values from `[A-Za-z0-9_.,+/=-]` within the sequence limit.
86    pub const fn new(name: &'a str) -> Self {
87        Self(name)
88    }
89
90    /// Return the kind name used on the wire.
91    pub const fn as_str(self) -> &'a str {
92        self.0
93    }
94}
95
96/// A complete OSC 7501 report, with borrowed text.
97///
98/// Each report replaces its record, so include every field that should
99/// remain present. An absent `app` inherits from the nearest ancestor with
100/// one. Text and identifiers are validated by [`write_program_status`]
101/// before any output. Callers supply plain UTF-8, not base64.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct ProgramStatus<'a> {
104    /// Required record state.
105    pub state: ProgramStatusState<'a>,
106    /// Optional record path. At most 128 bytes and eight slash-separated
107    /// segments, each 1-32 bytes from `[A-Za-z0-9_.+-]`. `None` selects root.
108    pub id: Option<&'a str>,
109    /// Reason for blocking. Terminals use this only with state `blocked`.
110    pub kind: Option<ProgramStatusKind<'a>>,
111    /// Percentage, from 0 to 100. Terminals use this only with state `working`
112    /// or `blocked`. `None` means indeterminate progress.
113    pub progress: Option<u8>,
114    /// Program name: 1-32 bytes from `[A-Za-z0-9_.+-]`.
115    pub app: Option<&'a str>,
116    /// Human-readable record label, at most 192 UTF-8 bytes.
117    /// C0, DEL, and C1 control characters are rejected.
118    pub title: Option<&'a str>,
119    /// Human-readable status message, at most 2048 UTF-8 bytes.
120    /// C0, DEL, and C1 control characters are rejected.
121    pub message: Option<&'a str>,
122}
123
124impl<'a> ProgramStatus<'a> {
125    /// Create a root report with the specified state and no optional fields.
126    pub fn new(state: ProgramStatusState<'a>) -> Self {
127        Self {
128            state,
129            id: None,
130            kind: None,
131            progress: None,
132            app: None,
133            title: None,
134            message: None,
135        }
136    }
137}
138
139pub(crate) fn valid_value(value: &str) -> bool {
140    value
141        .bytes()
142        .all(|b| b.is_ascii_alphanumeric() || b"_.,+/=-".contains(&b))
143}
144
145fn valid_segment(value: &str) -> bool {
146    (1..=32).contains(&value.len())
147        && value
148            .bytes()
149            .all(|b| b.is_ascii_alphanumeric() || b"_.+-".contains(&b))
150}
151
152fn validate_text(value: Option<&str>, limit: usize, field: &str) -> io::Result<()> {
153    if value.is_some_and(|s| s.len() > limit || s.chars().any(char::is_control)) {
154        return Err(io::Error::new(
155            io::ErrorKind::InvalidInput,
156            format!(
157                "program status {field} exceeds {limit} UTF-8 bytes or contains a control character"
158            ),
159        ));
160    }
161    Ok(())
162}
163
164/// Write one complete program status report without flushing.
165///
166/// All fields are validated before any bytes are written. Invalid IDs,
167/// state names, kind names, app names, text, or percentages return
168/// [`io::ErrorKind::InvalidInput`]. State and kind names must be nonempty
169/// values from `[A-Za-z0-9_.,+/=-]`.
170/// Text limits count UTF-8 bytes before base64 encoding. The complete
171/// encoded sequence, including its framing, must fit within 4096 bytes.
172///
173/// A terminal may apply lower limits or ignore OSC 7501 entirely. This
174/// function reports write errors, not terminal acceptance.
175///
176/// ```
177/// use uncurses::ansi::program_status::{
178///     ProgramStatus, ProgramStatusState, write_program_status,
179/// };
180///
181/// let mut report = ProgramStatus::new(ProgramStatusState::WORKING);
182/// report.app = Some("cargo");
183/// report.message = Some("Build");
184/// let mut bytes = Vec::new();
185/// write_program_status(&mut bytes, &report).unwrap();
186/// assert_eq!(bytes, b"\x1b]7501;state=working:app=cargo:msg=QnVpbGQ=\x1b\\");
187/// ```
188pub fn write_program_status<W: Write>(w: &mut W, report: &ProgramStatus<'_>) -> io::Result<()> {
189    for (field, value) in [
190        ("state", Some(report.state.as_str())),
191        ("kind", report.kind.map(ProgramStatusKind::as_str)),
192    ] {
193        if value.is_some_and(|name| name.is_empty() || name.len() > 4096 || !valid_value(name)) {
194            return Err(io::Error::new(
195                io::ErrorKind::InvalidInput,
196                format!("invalid program status {field} name"),
197            ));
198        }
199    }
200    if report.id.is_some_and(|id| {
201        id.len() > 128 || id.split('/').count() > 8 || !id.split('/').all(valid_segment)
202    }) {
203        return Err(io::Error::new(
204            io::ErrorKind::InvalidInput,
205            "invalid program status id",
206        ));
207    }
208    if report.app.is_some_and(|app| !valid_segment(app)) {
209        return Err(io::Error::new(
210            io::ErrorKind::InvalidInput,
211            "invalid program status app",
212        ));
213    }
214    if report.progress.is_some_and(|progress| progress > 100) {
215        return Err(io::Error::new(
216            io::ErrorKind::InvalidInput,
217            "program status progress exceeds 100",
218        ));
219    }
220    validate_text(report.title, 192, "title")?;
221    validate_text(report.message, 2048, "message")?;
222
223    let mut sequence = String::from("\x1b]7501;state=");
224    sequence.push_str(report.state.as_str());
225    if let Some(id) = report.id {
226        sequence.push_str(":id=");
227        sequence.push_str(id);
228    }
229    if let Some(kind) = report.kind {
230        sequence.push_str(":kind=");
231        sequence.push_str(kind.as_str());
232    }
233    if let Some(progress) = report.progress {
234        sequence.push_str(":progress=");
235        sequence.push_str(&progress.to_string());
236    }
237    if let Some(app) = report.app {
238        sequence.push_str(":app=");
239        sequence.push_str(app);
240    }
241    if let Some(title) = report.title {
242        sequence.push_str(":title=");
243        STANDARD.encode_string(title, &mut sequence);
244    }
245    if let Some(message) = report.message {
246        sequence.push_str(":msg=");
247        STANDARD.encode_string(message, &mut sequence);
248    }
249    sequence.push_str("\x1b\\");
250    if sequence.len() > 4096 {
251        return Err(io::Error::new(
252            io::ErrorKind::InvalidInput,
253            "program status sequence exceeds 4096 bytes",
254        ));
255    }
256    w.write_all(sequence.as_bytes())
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    #[test]
264    fn program_status_states_and_clear_records() {
265        for (state, value) in [
266            (ProgramStatusState::IDLE, "idle"),
267            (ProgramStatusState::WORKING, "working"),
268            (ProgramStatusState::DONE, "done"),
269            (ProgramStatusState::BLOCKED, "blocked"),
270            (ProgramStatusState::ERROR, "error"),
271            (ProgramStatusState::CLEAR, "clear"),
272        ] {
273            let mut report = ProgramStatus::new(state);
274            for id in [None, Some("build/test")] {
275                report.id = id;
276                let mut bytes = Vec::new();
277                write_program_status(&mut bytes, &report).unwrap();
278                let suffix = if id.is_some() { ":id=build/test" } else { "" };
279                assert_eq!(
280                    bytes,
281                    format!("\x1b]7501;state={value}{suffix}\x1b\\").as_bytes()
282                );
283            }
284        }
285    }
286
287    #[test]
288    fn program_status_encodes_all_fields_and_blocked_kinds() {
289        for (kind, value) in [
290            (ProgramStatusKind::PERMISSION, "permission"),
291            (ProgramStatusKind::QUESTION, "question"),
292            (ProgramStatusKind::AUTH, "auth"),
293        ] {
294            let report = ProgramStatus {
295                state: ProgramStatusState::BLOCKED,
296                id: Some("build/test"),
297                kind: Some(kind),
298                progress: Some(42),
299                app: Some("cargo"),
300                title: Some("Test"),
301                message: Some("Ready \u{2713}: yes?"),
302            };
303            let original = report.clone();
304            let mut bytes = Vec::new();
305            write_program_status(&mut bytes, &report).unwrap();
306            assert_eq!(
307                bytes,
308                format!("\x1b]7501;state=blocked:id=build/test:kind={value}:progress=42:app=cargo:title=VGVzdA==:msg=UmVhZHkg4pyTOiB5ZXM/\x1b\\").as_bytes(),
309            );
310            assert_eq!(report, original);
311        }
312    }
313
314    fn invalid(report: &ProgramStatus<'_>) {
315        let mut bytes = Vec::new();
316        let error = write_program_status(&mut bytes, report).unwrap_err();
317        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
318        assert!(bytes.is_empty(), "invalid reports must emit nothing");
319    }
320
321    #[test]
322    fn program_status_accepts_borrowed_extension_names() {
323        let state_name = String::from("paused");
324        let kind_name = String::from("confirm");
325        let mut report = ProgramStatus::new(ProgramStatusState::new(&state_name));
326        let mut bytes = Vec::new();
327        write_program_status(&mut bytes, &report).unwrap();
328        assert_eq!(bytes, b"\x1b]7501;state=paused\x1b\\");
329        assert_eq!(report.state.as_str(), state_name);
330
331        report.state = ProgramStatusState::BLOCKED;
332        report.kind = Some(ProgramStatusKind::new(&kind_name));
333        let original = report.clone();
334        bytes.clear();
335        write_program_status(&mut bytes, &report).unwrap();
336        assert_eq!(bytes, b"\x1b]7501;state=blocked:kind=confirm\x1b\\");
337        assert_eq!(report.kind.unwrap().as_str(), kind_name);
338        assert_eq!(report, original);
339
340        report.state = ProgramStatusState::new("AZaz09_.,+/=-");
341        report.kind = Some(ProgramStatusKind::new("AZaz09_.,+/=-"));
342        bytes.clear();
343        write_program_status(&mut bytes, &report).unwrap();
344        assert_eq!(
345            bytes,
346            b"\x1b]7501;state=AZaz09_.,+/=-:kind=AZaz09_.,+/=-\x1b\\"
347        );
348    }
349
350    #[test]
351    fn program_status_preserves_commas_in_report_values() {
352        for name in [",", ",paused", "paused,", "paused,done"] {
353            let mut report = ProgramStatus::new(ProgramStatusState::new(name));
354            let mut bytes = Vec::new();
355            write_program_status(&mut bytes, &report).unwrap();
356            assert_eq!(bytes, format!("\x1b]7501;state={name}\x1b\\").as_bytes());
357
358            report.state = ProgramStatusState::BLOCKED;
359            report.kind = Some(ProgramStatusKind::new(name));
360            bytes.clear();
361            write_program_status(&mut bytes, &report).unwrap();
362            assert_eq!(
363                bytes,
364                format!("\x1b]7501;state=blocked:kind={name}\x1b\\").as_bytes()
365            );
366        }
367    }
368
369    #[test]
370    fn program_status_rejects_invalid_extension_names_before_output() {
371        for name in ["", "a:b", "a;b", "a b", "\x1b\\", "\u{e9}", "\u{9c}"] {
372            invalid(&ProgramStatus::new(ProgramStatusState::new(name)));
373            let mut report = ProgramStatus::new(ProgramStatusState::BLOCKED);
374            report.kind = Some(ProgramStatusKind::new(name));
375            invalid(&report);
376        }
377        for code in (0..=0x1f).chain(0x7f..=0x9f) {
378            let name = format!("a{}b", char::from_u32(code).unwrap());
379            invalid(&ProgramStatus::new(ProgramStatusState::new(&name)));
380            let mut report = ProgramStatus::new(ProgramStatusState::BLOCKED);
381            report.kind = Some(ProgramStatusKind::new(&name));
382            invalid(&report);
383        }
384    }
385
386    #[test]
387    fn program_status_extension_names_respect_complete_sequence_limit() {
388        for (kind, overhead) in [
389            (false, b"\x1b]7501;state=\x1b\\".len()),
390            (true, b"\x1b]7501;state=blocked:kind=\x1b\\".len()),
391        ] {
392            for extra in [0, 1, overhead + 1] {
393                let name = "a".repeat(4096 - overhead + extra);
394                let mut report = ProgramStatus::new(if kind {
395                    ProgramStatusState::BLOCKED
396                } else {
397                    ProgramStatusState::new(&name)
398                });
399                if kind {
400                    report.kind = Some(ProgramStatusKind::new(&name));
401                }
402                if extra == 0 {
403                    let mut bytes = Vec::new();
404                    write_program_status(&mut bytes, &report).unwrap();
405                    assert_eq!(bytes.len(), 4096);
406                    report.title = Some("x");
407                    invalid(&report);
408                } else {
409                    invalid(&report);
410                }
411            }
412        }
413
414        let name = "a".repeat(2100);
415        let mut report = ProgramStatus::new(ProgramStatusState::new(&name));
416        report.kind = Some(ProgramStatusKind::new(&name));
417        invalid(&report);
418    }
419
420    #[test]
421    fn program_status_rejects_invalid_ids_apps_and_progress() {
422        let mut report = ProgramStatus::new(ProgramStatusState::WORKING);
423        for id in ["", "/a", "a/", "a//b", "a:b", "a;b", "a=b", "a b", "\u{e9}"] {
424            report.id = Some(id);
425            invalid(&report);
426        }
427        let segment = "a".repeat(33);
428        let levels = ["a"; 9].join("/");
429        let long_id = vec!["a".repeat(25); 5].join("/");
430        for id in [&segment, &levels, &long_id] {
431            report.id = Some(id);
432            invalid(&report);
433        }
434        report.id = None;
435        for app in ["", "a/b", "a b", "a:b", "a=b", "\u{e9}", &segment] {
436            report.app = Some(app);
437            invalid(&report);
438        }
439        report.app = None;
440        for progress in [101, 255] {
441            report.progress = Some(progress);
442            invalid(&report);
443        }
444    }
445
446    #[test]
447    fn program_status_rejects_controls_and_text_over_limits() {
448        for code in (0..=0x1f).chain(0x7f..=0x9f) {
449            let text = format!("before{}after", char::from_u32(code).unwrap());
450            let mut report = ProgramStatus::new(ProgramStatusState::DONE);
451            report.title = Some(&text);
452            invalid(&report);
453            report.title = None;
454            report.message = Some(&text);
455            invalid(&report);
456            report.message = None;
457        }
458        for title in ["a".repeat(193), "\u{e9}".repeat(97)] {
459            let mut report = ProgramStatus::new(ProgramStatusState::DONE);
460            report.title = Some(&title);
461            invalid(&report);
462        }
463        for message in ["a".repeat(2049), "\u{e9}".repeat(1025)] {
464            let mut report = ProgramStatus::new(ProgramStatusState::DONE);
465            report.message = Some(&message);
466            invalid(&report);
467        }
468    }
469
470    #[test]
471    fn program_status_accepts_limits_and_empty_text() {
472        let id = format!(
473            "{}/{}/{}/{}",
474            "a".repeat(32),
475            "b".repeat(32),
476            "c".repeat(32),
477            "d".repeat(29)
478        );
479        assert_eq!(id.len(), 128);
480        let app = "a".repeat(32);
481        let title = "\u{e9}".repeat(96);
482        let message = "\u{e9}".repeat(1024);
483        let mut report = ProgramStatus {
484            state: ProgramStatusState::BLOCKED,
485            id: Some(&id),
486            kind: Some(ProgramStatusKind::PERMISSION),
487            progress: Some(100),
488            app: Some(&app),
489            title: Some(&title),
490            message: Some(&message),
491        };
492        let mut bytes = Vec::new();
493        write_program_status(&mut bytes, &report).unwrap();
494        assert!(bytes.len() < 4096);
495        let sequence = String::from_utf8(bytes).unwrap();
496        assert_eq!(
497            sequence
498                .split(":title=")
499                .nth(1)
500                .unwrap()
501                .split(':')
502                .next()
503                .unwrap()
504                .len(),
505            256
506        );
507        assert_eq!(
508            sequence
509                .split(":msg=")
510                .nth(1)
511                .unwrap()
512                .trim_end_matches("\x1b\\")
513                .len(),
514            2732
515        );
516
517        report.id = Some("a/b/c/d/e/f/g/h");
518        report.app = Some("AZaz09_.+-");
519        report.title = Some("");
520        report.message = Some("");
521        report.progress = Some(0);
522        let mut bytes = Vec::new();
523        write_program_status(&mut bytes, &report).unwrap();
524        assert!(bytes.ends_with(b":title=:msg=\x1b\\"));
525    }
526
527    #[test]
528    fn program_status_propagates_write_errors() {
529        let mut empty = [];
530        let error = write_program_status(
531            &mut empty.as_mut_slice(),
532            &ProgramStatus::new(ProgramStatusState::IDLE),
533        )
534        .unwrap_err();
535        assert_eq!(error.kind(), io::ErrorKind::WriteZero);
536    }
537}