mnml-rs 0.2.13

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
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
//! Image rendering — protocol detection + encoders for terminals that
//! support inline images (Kitty graphics protocol, iTerm2 inline images).
//!
//! `Pane::Image` (defined in `src/pane.rs`) is the viewer pane: it caches
//! the file bytes + format on first load, and the renderer (`ui::image_view`)
//! reserves an area in the ratatui frame. After ratatui's draw completes,
//! `tui.rs` emits the protocol-specific escape directly to stdout to paint
//! the image *over* the reserved cells. This is the same two-phase trick
//! that crates like `ratatui-image` use — ratatui doesn't passthrough
//! escapes inside spans, so image draws have to happen after the regular
//! frame reconciliation.

pub mod iterm2;
pub mod kitty;
pub mod pane;
pub mod sixel;

pub use pane::ImagePane;

/// One pending image paint, captured by the renderer and consumed by
/// `tui.rs` after `terminal.draw()` to emit the protocol escape. The
/// renderer is responsible for ensuring the PNG bytes are ready
/// (i.e. calling [`ImageData::ensure_png_bytes`] for non-PNG sources);
/// the emitter just writes them out.
#[derive(Debug, Clone)]
pub struct PaintRequest {
    /// Pane that owns the image — for logging / debugging. The emitter
    /// doesn't look this up; it just writes the bytes.
    pub pane_id: crate::layout::PaneId,
    pub area: ratatui::layout::Rect,
    /// Encoded PNG payload (`Arc` so the same image across multiple
    /// frames doesn't reallocate; `MdPreview` and `ImagePane` both
    /// hold their own `Arc` and share it cheaply per frame).
    pub png_bytes: std::sync::Arc<Vec<u8>>,
}

use std::path::{Path, PathBuf};

/// Image protocols supported by the active terminal. Detected once at
/// `App::new` time from env vars; reads cheaply via `App.image_protocol`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageProtocol {
    /// Kitty graphics protocol (`\x1b_G...`) — Kitty, WezTerm, Ghostty,
    /// recent Konsole.
    Kitty,
    /// iTerm2 inline image protocol (`\x1b]1337;File=...`) — iTerm2,
    /// recent WezTerm (via OSC 1337).
    Iterm2,
    /// DEC sixel protocol (`\x1bP...q...\x1b\\`) — foot, mlterm,
    /// xterm with sixel support, Black Box, mintty. Lower fidelity
    /// than Kitty/iTerm2 (216-color web-safe palette) but covers
    /// every terminal that the modern two miss.
    Sixel,
    /// No support — the pane shows a metadata-only placeholder.
    None,
}

/// Detect the active terminal's image protocol support via env vars.
///
/// Order matters:
/// 1. Kitty wins when it's clearly present (`KITTY_WINDOW_ID` or
///    `TERM` contains kitty). It's the highest-fidelity option.
/// 2. WezTerm / Ghostty advertise Kitty support via `TERM_PROGRAM`.
/// 3. iTerm2 takes its own slot via `TERM_PROGRAM`.
/// 4. Sixel terminals (foot / mlterm) get detected last via
///    `TERM`. `MNML_IMAGE_PROTOCOL=sixel` is the explicit opt-in
///    for terminals that support sixel without advertising via env
///    (notably xterm-with-sixel, where users opt-in by build flag).
/// qa-feature 2026-07-02 — probe the controlling TTY for its cell pixel
/// dimensions via `TIOCGWINSZ`. Returns `Some((cell_w_px, cell_h_px))`
/// when the terminal reports non-zero pixel dims; `None` otherwise.
/// All modern terminals (Ghostty, Kitty, iTerm2, WezTerm, Alacritty,
/// Terminal.app, Foot, xterm) fill in the pixel fields — non-TTY stdout
/// or exotic setups return zeros / fail and we fall back to a rough
/// constant elsewhere.
///
/// Zero external deps — declares the `winsize` struct + `ioctl` signature
/// inline with `TIOCGWINSZ` values hard-coded per OS (macOS/BSD:
/// 0x40087468, Linux: 0x5413).
#[cfg(unix)]
pub fn probe_cell_pixel_size() -> Option<(u16, u16)> {
    use std::os::unix::io::AsRawFd;

    #[repr(C)]
    struct WinSize {
        ws_row: u16,
        ws_col: u16,
        ws_xpixel: u16,
        ws_ypixel: u16,
    }

    #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))]
    const TIOCGWINSZ: u64 = 0x40087468;
    #[cfg(target_os = "linux")]
    const TIOCGWINSZ: u64 = 0x5413;
    #[cfg(not(any(
        target_os = "macos",
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "linux",
    )))]
    const TIOCGWINSZ: u64 = 0x5413; // best-effort fallback

    unsafe extern "C" {
        fn ioctl(fd: i32, req: u64, arg: *mut WinSize) -> i32;
    }

    let fd = std::io::stdout().as_raw_fd();
    let mut ws = WinSize {
        ws_row: 0,
        ws_col: 0,
        ws_xpixel: 0,
        ws_ypixel: 0,
    };
    let ret = unsafe { ioctl(fd, TIOCGWINSZ, &mut ws) };
    if ret != 0 || ws.ws_row == 0 || ws.ws_col == 0 || ws.ws_xpixel == 0 || ws.ws_ypixel == 0 {
        return None;
    }
    let cell_w = ws.ws_xpixel / ws.ws_col;
    let cell_h = ws.ws_ypixel / ws.ws_row;
    if cell_w == 0 || cell_h == 0 {
        return None;
    }
    Some((cell_w, cell_h))
}

#[cfg(not(unix))]
pub fn probe_cell_pixel_size() -> Option<(u16, u16)> {
    None
}

pub fn detect_protocol() -> ImageProtocol {
    // Explicit user override beats everything — for testing, for
    // terminals whose env doesn't advertise, and for users who'd
    // rather force iTerm2 over Kitty (e.g. on WezTerm).
    if let Ok(forced) = std::env::var("MNML_IMAGE_PROTOCOL") {
        match forced.to_ascii_lowercase().as_str() {
            "kitty" => return ImageProtocol::Kitty,
            "iterm2" | "iterm" => return ImageProtocol::Iterm2,
            "sixel" => return ImageProtocol::Sixel,
            "none" | "off" => return ImageProtocol::None,
            _ => {} // Unknown value — fall through to env detection.
        }
    }
    if std::env::var_os("KITTY_WINDOW_ID").is_some() {
        return ImageProtocol::Kitty;
    }
    if let Ok(term) = std::env::var("TERM")
        && term.to_lowercase().contains("kitty")
    {
        return ImageProtocol::Kitty;
    }
    if let Ok(tp) = std::env::var("TERM_PROGRAM") {
        let l = tp.to_lowercase();
        if l.contains("wezterm") || l == "ghostty" {
            return ImageProtocol::Kitty;
        }
        if l.contains("iterm") {
            return ImageProtocol::Iterm2;
        }
        if l.contains("black box") || l == "blackbox" {
            return ImageProtocol::Sixel;
        }
    }
    // Terminals that advertise sixel via `TERM` (the DEC convention).
    // `foot` and `mlterm` are the common ones; xterm with sixel
    // typically still reports `xterm-256color`, so users have to set
    // `MNML_IMAGE_PROTOCOL=sixel` explicitly for it.
    if let Ok(term) = std::env::var("TERM") {
        let t = term.to_lowercase();
        if t == "foot" || t.starts_with("foot-") || t.starts_with("mlterm") {
            return ImageProtocol::Sixel;
        }
    }
    ImageProtocol::None
}

/// One file's worth of cached image data — the raw bytes plus a detected
/// format. Kept compact since PNG/JPEG files are typically a few hundred KB.
///
/// `png_bytes` is a cache of the PNG-transcoded payload for non-PNG sources.
/// Set lazily on first use via [`ImageData::ensure_png_bytes`]; transmission
/// pulls from this slot so the heavy decode only happens once per file.
#[derive(Debug, Clone)]
pub struct ImageData {
    pub path: PathBuf,
    pub bytes: Vec<u8>,
    pub format: ImageFormat,
    /// PNG-encoded payload for transmission. For PNG sources this points at
    /// `bytes` (zero-copy through `Arc`). For other formats it's lazily
    /// populated by decoding `bytes` then re-encoding as PNG.
    pub png_bytes: Option<std::sync::Arc<Vec<u8>>>,
    /// `(width, height)` in pixels — set once a decode has happened.
    /// `None` until first access.
    pub pixel_size: Option<(u32, u32)>,
}

impl ImageData {
    /// Return the PNG-encoded payload, decoding + re-encoding the source if
    /// necessary. PNG sources zero-copy through `Arc<Vec<u8>>`. Returns
    /// `Err` when the source can't be decoded (corrupt / unsupported).
    pub fn ensure_png_bytes(&mut self) -> Result<std::sync::Arc<Vec<u8>>, String> {
        if let Some(arc) = self.png_bytes.as_ref() {
            return Ok(arc.clone());
        }
        let arc = if matches!(self.format, ImageFormat::Png) {
            // PNG → reuse the bytes verbatim. Also fill pixel_size while
            // we're here (cheap — just parse the IHDR chunk).
            if self.pixel_size.is_none() {
                self.pixel_size = parse_png_size(&self.bytes);
            }
            std::sync::Arc::new(self.bytes.clone())
        } else {
            let img = image::load_from_memory(&self.bytes)
                .map_err(|e| format!("decode {}: {e}", format_label(self.format)))?;
            self.pixel_size = Some((img.width(), img.height()));
            let mut out: Vec<u8> = Vec::with_capacity(self.bytes.len());
            img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
                .map_err(|e| format!("encode PNG: {e}"))?;
            std::sync::Arc::new(out)
        };
        self.png_bytes = Some(arc.clone());
        Ok(arc)
    }
}

fn format_label(f: ImageFormat) -> &'static str {
    match f {
        ImageFormat::Png => "PNG",
        ImageFormat::Jpeg => "JPEG",
        ImageFormat::Gif => "GIF",
        ImageFormat::Webp => "WebP",
        ImageFormat::Bmp => "BMP",
        ImageFormat::Other => "image",
    }
}

/// Parse a PNG file's IHDR chunk for `(width, height)`. Returns None on a
/// non-PNG or truncated file. Cheap — reads only the first 24 bytes.
fn parse_png_size(bytes: &[u8]) -> Option<(u32, u32)> {
    // PNG magic (8 bytes) + IHDR length (4) + "IHDR" (4) + width (4) + height (4)
    if bytes.len() < 24 {
        return None;
    }
    if &bytes[0..8] != b"\x89PNG\r\n\x1a\n" {
        return None;
    }
    if &bytes[12..16] != b"IHDR" {
        return None;
    }
    let w = u32::from_be_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]);
    let h = u32::from_be_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]);
    Some((w, h))
}

/// Image formats recognized by the loader. Detection is by file extension
/// (cheap; supports common cases without dragging in a full image crate).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageFormat {
    Png,
    Jpeg,
    Gif,
    Webp,
    Bmp,
    /// Unknown — kitty/iterm2 may still render it, but we can't promise.
    Other,
}

impl ImageFormat {
    /// Guess from file extension. Case-insensitive.
    pub fn from_path(path: &Path) -> Self {
        let ext = path
            .extension()
            .and_then(|s| s.to_str())
            .map(str::to_ascii_lowercase);
        match ext.as_deref() {
            Some("png") => ImageFormat::Png,
            Some("jpg") | Some("jpeg") => ImageFormat::Jpeg,
            Some("gif") => ImageFormat::Gif,
            Some("webp") => ImageFormat::Webp,
            Some("bmp") => ImageFormat::Bmp,
            _ => ImageFormat::Other,
        }
    }
}

/// Load an image file into memory. Refuses files past `MAX_BYTES` so a stray
/// click on a multi-GB raw file doesn't OOM the IDE.
pub fn load(path: &Path) -> Result<ImageData, String> {
    const MAX_BYTES: u64 = 50 * 1024 * 1024; // 50 MB
    let meta = std::fs::metadata(path).map_err(|e| format!("stat: {e}"))?;
    if meta.len() > MAX_BYTES {
        return Err(format!(
            "file too large ({} MB > 50 MB cap)",
            meta.len() / 1_048_576
        ));
    }
    let bytes = std::fs::read(path).map_err(|e| format!("read: {e}"))?;
    Ok(ImageData {
        path: path.to_path_buf(),
        bytes,
        format: ImageFormat::from_path(path),
        png_bytes: None,
        pixel_size: None,
    })
}

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

    #[test]
    fn format_from_path_picks_known_extensions() {
        assert_eq!(ImageFormat::from_path(Path::new("a.png")), ImageFormat::Png);
        assert_eq!(
            ImageFormat::from_path(Path::new("a.JPG")),
            ImageFormat::Jpeg
        );
        assert_eq!(
            ImageFormat::from_path(Path::new("a.jpeg")),
            ImageFormat::Jpeg
        );
        assert_eq!(ImageFormat::from_path(Path::new("a.gif")), ImageFormat::Gif);
        assert_eq!(
            ImageFormat::from_path(Path::new("a.webp")),
            ImageFormat::Webp
        );
        assert_eq!(ImageFormat::from_path(Path::new("a.bmp")), ImageFormat::Bmp);
        assert_eq!(
            ImageFormat::from_path(Path::new("a.tif")),
            ImageFormat::Other
        );
        assert_eq!(
            ImageFormat::from_path(Path::new("noext")),
            ImageFormat::Other
        );
    }

    /// Build an in-memory image of `format`, then verify
    /// `ensure_png_bytes` decodes + re-encodes it as a valid PNG.
    /// Round-trip coverage that the `image` crate features pulled in
    /// (jpeg / gif / webp / bmp) actually decode at runtime — without
    /// this, a feature-flag regression in `Cargo.toml` would silently
    /// strand non-PNG sources.
    fn round_trip(format: image::ImageFormat, our_format: ImageFormat) {
        // 2×2 solid-red RGB image — the smallest meaningful payload.
        let raw = image::RgbImage::from_pixel(2, 2, image::Rgb([255, 0, 0]));
        let mut encoded = Vec::new();
        image::DynamicImage::ImageRgb8(raw)
            .write_to(&mut std::io::Cursor::new(&mut encoded), format)
            .expect("encode test fixture");
        let mut data = ImageData {
            path: PathBuf::from("x"),
            bytes: encoded,
            format: our_format,
            png_bytes: None,
            pixel_size: None,
        };
        let png = data.ensure_png_bytes().expect("decode + reencode");
        // PNG magic bytes confirm we got real PNG out.
        assert_eq!(&png[0..8], b"\x89PNG\r\n\x1a\n", "{our_format:?} → PNG");
        // Pixel size populated.
        assert_eq!(data.pixel_size, Some((2, 2)));
    }

    #[test]
    fn jpeg_decodes_and_reencodes_to_png() {
        round_trip(image::ImageFormat::Jpeg, ImageFormat::Jpeg);
    }

    #[test]
    fn gif_decodes_and_reencodes_to_png() {
        round_trip(image::ImageFormat::Gif, ImageFormat::Gif);
    }

    #[test]
    fn webp_decodes_and_reencodes_to_png() {
        // image 0.25's WebP encoder is lossless by default; round-trip
        // is byte-exact.
        round_trip(image::ImageFormat::WebP, ImageFormat::Webp);
    }

    #[test]
    fn bmp_decodes_and_reencodes_to_png() {
        round_trip(image::ImageFormat::Bmp, ImageFormat::Bmp);
    }

    #[test]
    fn png_source_zero_copies_through_ensure_png_bytes() {
        // PNG sources should hit the fast path that reuses self.bytes
        // verbatim (no decode → re-encode round trip).
        let raw = image::RgbImage::from_pixel(2, 2, image::Rgb([0, 255, 0]));
        let mut encoded = Vec::new();
        image::DynamicImage::ImageRgb8(raw)
            .write_to(
                &mut std::io::Cursor::new(&mut encoded),
                image::ImageFormat::Png,
            )
            .unwrap();
        let mut data = ImageData {
            path: PathBuf::from("x"),
            bytes: encoded.clone(),
            format: ImageFormat::Png,
            png_bytes: None,
            pixel_size: None,
        };
        let png = data.ensure_png_bytes().unwrap();
        assert_eq!(&*png, &encoded, "PNG source should be reused verbatim");
        assert_eq!(data.pixel_size, Some((2, 2)));
    }
}