dustnet-client 0.2.0

Dustnet client library: transport, viewer, compositor, and AML/WASM runtime
Documentation
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use crate::color::{NamedColor, ResolvedColor};
use crate::compositor::layout::cell::CellStyle;
use std::io::{self, Write};

/// Physical fallback used when AML leaves either color unspecified.
///
/// Cells remain transparent inside the compositor; the fallback is applied
/// only while presenting the final frame so the host terminal's theme cannot
/// bleed through the client canvas.
pub const TERMINAL_DEFAULT_SGR: &str = "\x1b[38;2;255;255;255;48;2;0;0;0m";

/// `black` is presented as literal RGB, never as SGR 30/40.
///
/// SGR 30/40 name palette slot 0, which almost no terminal theme sets to
/// `#000000` — Solarized Dark puts `#073642` there, One Dark `#282c34`. An
/// absent color is already materialized as literal black (see
/// `TERMINAL_DEFAULT_SGR`), so honoring the palette for a *named* black would
/// make a region that says `bg=black` band against the region beside it that
/// says nothing at all. The two blacks must agree, and literal wins.
const BLACK_FG_SGR: &str = "38;2;0;0;0";
const BLACK_BG_SGR: &str = "48;2;0;0;0";

/// Generate the SGR (Select Graphic Rendition) escape sequence for a cell style.
///
/// Returns the full escape sequence including the ESC[ prefix and 'm' suffix.
/// Missing colors are materialized as bright white on black. This is a
/// presentation-only default: it does not change cell transparency or
/// compositing semantics.
pub fn style_to_sgr(style: &CellStyle) -> String {
    let mut params: Vec<String> = Vec::new();

    if style.bold {
        params.push("1".into());
    }
    if style.dim {
        params.push("2".into());
    }
    if style.italic {
        params.push("3".into());
    }
    if style.underline {
        params.push("4".into());
    }
    if style.blink {
        params.push("5".into());
    }
    if style.strikethrough {
        params.push("9".into());
    }

    match &style.fg {
        Some(fg) => match fg {
            ResolvedColor::Named(NamedColor::Black) => {
                params.push(BLACK_FG_SGR.into());
            }
            ResolvedColor::Named(n) => {
                params.push(n.fg_sgr().to_string());
            }
            ResolvedColor::Palette(idx) => {
                params.push(format!("38;5;{idx}"));
            }
            ResolvedColor::Rgb(r, g, b) => {
                params.push(format!("38;2;{r};{g};{b}"));
            }
        },
        None => params.push("38;2;255;255;255".into()),
    }

    match &style.bg {
        Some(bg) => match bg {
            ResolvedColor::Named(NamedColor::Black) => {
                params.push(BLACK_BG_SGR.into());
            }
            ResolvedColor::Named(n) => {
                params.push(n.bg_sgr().to_string());
            }
            ResolvedColor::Palette(idx) => {
                params.push(format!("48;5;{idx}"));
            }
            ResolvedColor::Rgb(r, g, b) => {
                params.push(format!("48;2;{r};{g};{b}"));
            }
        },
        None => params.push("48;2;0;0;0".into()),
    }

    format!("\x1b[{}m", params.join(";"))
}

/// Write an SGR sequence without allocating an intermediate `String`.
pub fn write_style_sgr(out: &mut impl Write, style: &CellStyle) -> io::Result<()> {
    out.write_all(b"\x1b[")?;
    let mut first = true;
    macro_rules! parameter {
        ($($arg:tt)*) => {{
            if !first {
                out.write_all(b";")?;
            }
            first = false;
            write!(out, $($arg)*)?;
        }};
    }

    if style.bold {
        parameter!("1");
    }
    if style.dim {
        parameter!("2");
    }
    if style.italic {
        parameter!("3");
    }
    if style.underline {
        parameter!("4");
    }
    if style.blink {
        parameter!("5");
    }
    if style.strikethrough {
        parameter!("9");
    }

    match &style.fg {
        Some(ResolvedColor::Named(NamedColor::Black)) => parameter!("{BLACK_FG_SGR}"),
        Some(ResolvedColor::Named(color)) => parameter!("{}", color.fg_sgr()),
        Some(ResolvedColor::Palette(index)) => parameter!("38;5;{index}"),
        Some(ResolvedColor::Rgb(red, green, blue)) => parameter!("38;2;{red};{green};{blue}"),
        None => parameter!("38;2;255;255;255"),
    }
    match &style.bg {
        Some(ResolvedColor::Named(NamedColor::Black)) => parameter!("{BLACK_BG_SGR}"),
        Some(ResolvedColor::Named(color)) => parameter!("{}", color.bg_sgr()),
        Some(ResolvedColor::Palette(index)) => parameter!("48;5;{index}"),
        Some(ResolvedColor::Rgb(red, green, blue)) => parameter!("48;2;{red};{green};{blue}"),
        None => parameter!("48;2;0;0;0"),
    }
    debug_assert!(!first);
    out.write_all(b"m")
}

/// Write a 1-based terminal cursor position without allocating.
pub fn write_cursor(out: &mut impl Write, row: u16, col: u16) -> io::Result<()> {
    write!(out, "\x1b[{};{}H", row + 1, col + 1)
}

/// SGR reset sequence.
pub const RESET: &str = "\x1b[0m";

/// Move cursor to (row, col). Both are 1-based in ANSI.
pub fn move_cursor(row: u16, col: u16) -> String {
    format!("\x1b[{};{}H", row + 1, col + 1)
}

/// Hide the cursor.
pub const HIDE_CURSOR: &str = "\x1b[?25l";

/// Show the cursor.
pub const SHOW_CURSOR: &str = "\x1b[?25h";

/// Switch to the alternate screen buffer.
pub const ENTER_ALT_SCREEN: &str = "\x1b[?1049h";

/// Switch back to the main screen buffer.
pub const LEAVE_ALT_SCREEN: &str = "\x1b[?1049l";

/// Clear the entire screen.
pub const CLEAR_SCREEN: &str = "\x1b[2J";

/// Move cursor to top-left.
pub const CURSOR_HOME: &str = "\x1b[H";

#[cfg(test)]
mod tests {
    use super::*;
    use crate::color::NamedColor;

    #[test]
    fn default_style_uses_physical_dark_canvas() {
        let style = CellStyle::default();
        assert_eq!(style_to_sgr(&style), TERMINAL_DEFAULT_SGR);
    }

    #[test]
    fn bold_only() {
        let style = CellStyle {
            bold: true,
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[1;38;2;255;255;255;48;2;0;0;0m");
    }

    #[test]
    fn dim_only() {
        let style = CellStyle {
            dim: true,
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[2;38;2;255;255;255;48;2;0;0;0m");
    }

    #[test]
    fn italic_only() {
        let style = CellStyle {
            italic: true,
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[3;38;2;255;255;255;48;2;0;0;0m");
    }

    #[test]
    fn underline_only() {
        let style = CellStyle {
            underline: true,
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[4;38;2;255;255;255;48;2;0;0;0m");
    }

    #[test]
    fn blink_only() {
        let style = CellStyle {
            blink: true,
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[5;38;2;255;255;255;48;2;0;0;0m");
    }

    #[test]
    fn strikethrough_only() {
        let style = CellStyle {
            strikethrough: true,
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[9;38;2;255;255;255;48;2;0;0;0m");
    }

    #[test]
    fn named_fg_color() {
        let style = CellStyle {
            fg: Some(ResolvedColor::Named(NamedColor::Red)),
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[31;48;2;0;0;0m");
    }

    #[test]
    fn named_bg_color() {
        let style = CellStyle {
            bg: Some(ResolvedColor::Named(NamedColor::Blue)),
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[38;2;255;255;255;44m");
    }

    #[test]
    fn bright_fg_color() {
        let style = CellStyle {
            fg: Some(ResolvedColor::Named(NamedColor::BrightCyan)),
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[96;48;2;0;0;0m");
    }

    #[test]
    fn palette_fg_color() {
        let style = CellStyle {
            fg: Some(ResolvedColor::Palette(196)),
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[38;5;196;48;2;0;0;0m");
    }

    #[test]
    fn palette_bg_color() {
        let style = CellStyle {
            bg: Some(ResolvedColor::Palette(42)),
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[38;2;255;255;255;48;5;42m");
    }

    #[test]
    fn rgb_fg_color() {
        let style = CellStyle {
            fg: Some(ResolvedColor::Rgb(255, 102, 0)),
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[38;2;255;102;0;48;2;0;0;0m");
    }

    #[test]
    fn rgb_bg_color() {
        let style = CellStyle {
            bg: Some(ResolvedColor::Rgb(0, 0, 128)),
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[38;2;255;255;255;48;2;0;0;128m");
    }

    #[test]
    fn combined_styles() {
        let style = CellStyle {
            fg: Some(ResolvedColor::Named(NamedColor::Red)),
            bg: Some(ResolvedColor::Named(NamedColor::Black)),
            bold: true,
            underline: true,
            ..Default::default()
        };
        let sgr = style_to_sgr(&style);
        assert!(sgr.starts_with("\x1b["));
        assert!(sgr.ends_with('m'));
        assert!(sgr.contains("1")); // bold
        assert!(sgr.contains("4")); // underline
        assert!(sgr.contains("31")); // red fg
        assert!(sgr.contains("48;2;0;0;0")); // black bg, literal not palette
        assert!(!sgr.contains(";40")); // never the theme-controlled slot 0
    }

    #[test]
    fn named_black_bg_is_literal_rgb_not_palette_slot_zero() {
        let style = CellStyle {
            bg: Some(ResolvedColor::Named(NamedColor::Black)),
            ..Default::default()
        };
        // Must be byte-identical to the absent-color default, so a cell that
        // names black cannot band against a cell that leaves it unspecified.
        assert_eq!(style_to_sgr(&style), TERMINAL_DEFAULT_SGR);
    }

    #[test]
    fn named_black_fg_is_literal_rgb() {
        let style = CellStyle {
            fg: Some(ResolvedColor::Named(NamedColor::Black)),
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[38;2;0;0;0;48;2;0;0;0m");
    }

    #[test]
    fn bright_black_still_uses_the_palette() {
        // Only `black` is materialized; `bright-black` remains an honest
        // palette reference so themes keep control of their greys.
        let style = CellStyle {
            fg: Some(ResolvedColor::Named(NamedColor::BrightBlack)),
            bg: Some(ResolvedColor::Named(NamedColor::BrightBlack)),
            ..Default::default()
        };
        assert_eq!(style_to_sgr(&style), "\x1b[90;100m");
    }

    #[test]
    fn streaming_and_allocating_agree_on_black() {
        for style in [
            CellStyle {
                bg: Some(ResolvedColor::Named(NamedColor::Black)),
                ..Default::default()
            },
            CellStyle {
                fg: Some(ResolvedColor::Named(NamedColor::Black)),
                bg: Some(ResolvedColor::Named(NamedColor::Black)),
                bold: true,
                ..Default::default()
            },
        ] {
            let mut direct = Vec::new();
            write_style_sgr(&mut direct, &style).unwrap();
            assert_eq!(direct, style_to_sgr(&style).as_bytes());
        }
    }

    #[test]
    fn all_styles_at_once() {
        let style = CellStyle {
            fg: Some(ResolvedColor::Rgb(255, 0, 0)),
            bg: Some(ResolvedColor::Rgb(0, 0, 255)),
            bold: true,
            dim: true,
            italic: true,
            underline: true,
            blink: true,
            strikethrough: true,
        };
        let sgr = style_to_sgr(&style);
        // Should contain all attributes
        assert!(sgr.contains("1")); // bold
        assert!(sgr.contains("2")); // dim
        assert!(sgr.contains("3")); // italic
        assert!(sgr.contains("4")); // underline
        assert!(sgr.contains("5")); // blink
        assert!(sgr.contains("9")); // strikethrough
        assert!(sgr.contains("38;2;255;0;0")); // fg
        assert!(sgr.contains("48;2;0;0;255")); // bg
        let mut direct = Vec::new();
        write_style_sgr(&mut direct, &style).unwrap();
        assert_eq!(direct, sgr.as_bytes());
    }

    #[test]
    fn move_cursor_values() {
        // (0,0) should produce ESC[1;1H (1-based)
        assert_eq!(move_cursor(0, 0), "\x1b[1;1H");
        assert_eq!(move_cursor(5, 10), "\x1b[6;11H");
        assert_eq!(move_cursor(23, 79), "\x1b[24;80H");
    }

    #[test]
    fn constants_are_valid_escape_sequences() {
        assert!(RESET.starts_with("\x1b["));
        assert!(HIDE_CURSOR.starts_with("\x1b["));
        assert!(SHOW_CURSOR.starts_with("\x1b["));
        assert!(ENTER_ALT_SCREEN.starts_with("\x1b["));
        assert!(LEAVE_ALT_SCREEN.starts_with("\x1b["));
        assert!(CLEAR_SCREEN.starts_with("\x1b["));
        assert!(CURSOR_HOME.starts_with("\x1b["));
    }
}