rpi-tui 0.4.0

Terminal User Interface for pi-rust
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
417
418
//! Image component for terminal display.
//!
//! Displays images using Kitty or iTerm2 protocols.

use std::any::Any;
use std::sync::Mutex;

use super::component::Component;
use super::terminal_image::{
    allocate_image_id, get_capabilities, get_image_dimensions, render_image, ImageProtocol,
    ImageRenderOptions,
};
use crate::utils::visible_width;

/// Image theme.
#[derive(Debug, Clone)]
pub struct ImageTheme {
    /// Placeholder background color (ANSI escape).
    pub placeholder_bg: &'static str,
    /// Placeholder border color (ANSI escape).
    pub border_color: &'static str,
    /// Alt text color function.
    pub alt_text_color: fn(&str) -> String,
}

impl Default for ImageTheme {
    fn default() -> Self {
        Self {
            placeholder_bg: "\x1b[48;5;238m", // Dark gray background
            border_color: "\x1b[38;5;244m",   // Gray border
            alt_text_color: |s| format!("\x1b[38;5;250m{}\x1b[0m", s),
        }
    }
}

/// Image options.
#[derive(Debug, Clone)]
pub struct ImageOptions {
    /// Width in cells (None = auto).
    pub width: Option<u16>,
    /// Height in cells (None = auto).
    pub height: Option<u16>,
    /// Preserve aspect ratio.
    pub preserve_aspect: bool,
    /// Alt text for fallback.
    pub alt_text: Option<String>,
    /// Title for the image.
    pub title: Option<String>,
}

impl Default for ImageOptions {
    fn default() -> Self {
        Self {
            width: None,
            height: None,
            preserve_aspect: true,
            alt_text: None,
            title: None,
        }
    }
}

/// Image component.
pub struct Image {
    data: Mutex<Option<Vec<u8>>>,
    url: Mutex<Option<String>>,
    options: ImageOptions,
    theme: ImageTheme,
    image_id: Mutex<Option<u32>>,
    cached_render: Mutex<Option<(usize, String)>>,
    inline_visible: Mutex<bool>,
}

impl Image {
    /// Create a new empty image.
    pub fn new() -> Self {
        Self {
            data: Mutex::new(None),
            url: Mutex::new(None),
            options: ImageOptions::default(),
            theme: ImageTheme::default(),
            image_id: Mutex::new(None),
            cached_render: Mutex::new(None),
            inline_visible: Mutex::new(true),
        }
    }

    /// Create an image from data.
    pub fn from_data(data: Vec<u8>, options: ImageOptions) -> Self {
        let id = allocate_image_id();
        Self {
            data: Mutex::new(Some(data)),
            url: Mutex::new(None),
            options,
            theme: ImageTheme::default(),
            image_id: Mutex::new(Some(id)),
            cached_render: Mutex::new(None),
            inline_visible: Mutex::new(true),
        }
    }

    /// Create an image from a URL.
    pub fn from_url(url: &str, options: ImageOptions) -> Self {
        Self {
            data: Mutex::new(None),
            url: Mutex::new(Some(url.to_string())),
            options,
            theme: ImageTheme::default(),
            image_id: Mutex::new(None),
            cached_render: Mutex::new(None),
            inline_visible: Mutex::new(true),
        }
    }

    /// Set image data.
    pub fn set_data(&self, data: Vec<u8>) {
        if let Ok(mut d) = self.data.lock() {
            *d = Some(data);
        }
        if let Ok(mut id) = self.image_id.lock() {
            *id = Some(allocate_image_id());
        }
        if let Ok(mut cached) = self.cached_render.lock() {
            *cached = None;
        }
    }

    /// Set image URL.
    pub fn set_url(&self, url: &str) {
        if let Ok(mut u) = self.url.lock() {
            *u = Some(url.to_string());
        }
        if let Ok(mut cached) = self.cached_render.lock() {
            *cached = None;
        }
    }

    /// Set options.
    pub fn set_options(&mut self, options: ImageOptions) {
        self.options = options;
        if let Ok(mut cached) = self.cached_render.lock() {
            *cached = None;
        }
    }

    /// Set alt text.
    pub fn set_alt_text(&mut self, alt_text: &str) {
        self.options.alt_text = Some(alt_text.to_string());
    }

    /// Set theme.
    pub fn set_theme(&mut self, theme: ImageTheme) {
        self.theme = theme;
        if let Ok(mut cached) = self.cached_render.lock() {
            *cached = None;
        }
    }

    /// Check if image is loaded.
    pub fn is_loaded(&self) -> bool {
        self.data.lock().map(|d| d.is_some()).unwrap_or(false)
            || self.url.lock().map(|u| u.is_some()).unwrap_or(false)
    }

    /// Get image dimensions if available.
    pub fn get_dimensions(&self) -> Option<(u32, u32)> {
        let data = self.data.lock().ok()?;
        let d = data.as_ref()?;
        let dims = get_image_dimensions(d)?;
        Some((dims.width, dims.height))
    }

    /// Render the image.
    fn render_image(&self, width: usize) -> String {
        if width == 0 {
            return String::new();
        }
        if !*self.inline_visible.lock().unwrap() {
            return crate::utils::truncate_to_width("[Image]", width, "");
        }
        let caps = get_capabilities();

        // Check if we have cached render
        if let Ok(cached) = self.cached_render.lock() {
            if let Some((cached_width, rendered)) = cached.as_ref() {
                if *cached_width == width {
                    return rendered.clone();
                }
            }
        }

        // Calculate dimensions
        let (img_width, img_height) = if let Some((w, h)) = self.get_dimensions() {
            // Calculate cell dimensions
            let cell_dims = super::terminal_image::get_cell_dimensions();
            let cell_width = self
                .options
                .width
                .unwrap_or_else(|| {
                    ((w as f32 / cell_dims.width.max(1) as f32).ceil() as u16).min(60)
                })
                .min(width.saturating_sub(2).max(1).min(u16::MAX as usize) as u16)
                .max(1);
            let cell_height = self
                .options
                .height
                .unwrap_or_else(|| {
                    ((h as f64 / w.max(1) as f64) * cell_width as f64 * cell_dims.width as f64
                        / cell_dims.height.max(1) as f64)
                        .ceil() as u16
                })
                .max(1);
            let max_height = self
                .options
                .height
                .unwrap_or_else(|| {
                    (cell_width as f64 * cell_dims.width as f64 / cell_dims.height.max(1) as f64)
                        .ceil() as u16
                })
                .max(1);
            if self.options.preserve_aspect && cell_height > max_height {
                (
                    ((cell_width as f64 * max_height as f64 / cell_height as f64).floor() as u16)
                        .max(1),
                    max_height,
                )
            } else {
                (cell_width, cell_height)
            }
        } else {
            (
                self.options.width.unwrap_or(width as u16),
                self.options.height.unwrap_or(5),
            )
        };

        // Render based on protocol
        let result = if caps.protocol == ImageProtocol::None {
            // Fallback: render placeholder
            crate::utils::truncate_to_width(
                self.options.alt_text.as_deref().unwrap_or("[Image]"),
                width,
                "",
            )
        } else if let Ok(data) = self.data.lock() {
            if let Some(ref img_data) = *data {
                let id = self.image_id.lock().ok().and_then(|id| *id);
                let options = ImageRenderOptions {
                    width: Some(img_width),
                    height: Some(img_height),
                    preserve_aspect: self.options.preserve_aspect,
                    x: 0,
                    y: 0,
                    z_index: None,
                    id,
                };
                // Keep cursor position stable and reserve the image's rows in
                // the retained layout so following text cannot overlap it.
                let sequence = render_image(img_data, &options);
                let rows = img_height.saturating_sub(1) as usize;
                if caps.protocol == ImageProtocol::Kitty {
                    format!("{sequence}{}", "\n".repeat(rows))
                } else {
                    let up = if rows > 0 {
                        format!("\x1b[{rows}A")
                    } else {
                        String::new()
                    };
                    format!("{}{up}{sequence}", "\n".repeat(rows))
                }
            } else {
                self.render_placeholder(img_width as usize, img_height as usize, width)
            }
        } else {
            self.render_placeholder(img_width as usize, img_height as usize, width)
        };

        // Cache the result
        if let Ok(mut cached) = self.cached_render.lock() {
            *cached = Some((width, result.clone()));
        }

        result
    }

    /// Hide terminal graphics while retaining an attachment placeholder.
    pub fn set_inline_visible(&self, visible: bool) {
        let mut current = self.inline_visible.lock().unwrap();
        if *current == visible {
            return;
        }
        *current = visible;
        *self.cached_render.lock().unwrap() = None;
    }

    /// Render a placeholder when image can't be displayed.
    fn render_placeholder(&self, img_width: usize, img_height: usize, max_width: usize) -> String {
        let width = img_width.min(max_width);
        let height = img_height.max(3);

        let border_h = "─".repeat(width.saturating_sub(2));
        let inner_width = width.saturating_sub(2);

        let mut lines = Vec::new();

        // Top border
        lines.push(format!("{}â•­{}â•®\x1b[0m", self.theme.border_color, border_h));

        // Content
        let alt_text = self.options.alt_text.as_deref().unwrap_or("[Image]");
        let title = self.options.title.as_deref().unwrap_or("");

        // Calculate content lines
        let content_height = height.saturating_sub(2);
        let alt_text_line = (self.theme.alt_text_color)(alt_text);
        let title_line = if !title.is_empty() {
            Some((self.theme.alt_text_color)(title))
        } else {
            None
        };

        for i in 0..content_height {
            let content = if i == 0 {
                if let Some(ref t) = title_line {
                    t.clone()
                } else {
                    alt_text_line.clone()
                }
            } else if i == 1 && title_line.is_some() {
                alt_text_line.clone()
            } else {
                " ".repeat(inner_width)
            };

            let content_padded = if visible_width(&content) < inner_width {
                format!(
                    "{}{}",
                    content,
                    " ".repeat(inner_width - visible_width(&content))
                )
            } else {
                crate::utils::truncate_to_width(&content, inner_width, "")
            };

            lines.push(format!(
                "{}│{}{}\x1b[0m│\x1b[0m",
                self.theme.border_color, self.theme.placeholder_bg, content_padded
            ));
        }

        // Bottom border
        lines.push(format!("{}╰{}╯\x1b[0m", self.theme.border_color, border_h));

        lines.join("\n")
    }
}

impl Default for Image {
    fn default() -> Self {
        Self::new()
    }
}

impl Component for Image {
    fn render(&self, width: usize) -> Vec<String> {
        let rendered = self.render_image(width);
        rendered.split('\n').map(|s| s.to_string()).collect()
    }

    fn invalidate(&self) {
        if let Ok(mut cached) = self.cached_render.lock() {
            *cached = None;
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

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

    #[test]
    fn image_visibility_retains_placeholder_and_resizing_rebuilds_layout() {
        let image = Image::new();
        image.set_inline_visible(false);
        assert_eq!(image.render(80), vec!["[Image]"]);
        assert_eq!(image.render(3), vec!["[Im"]);
        assert_eq!(image.render(0), vec![""]);
        image.set_inline_visible(true);
        let wide = image.render(80);
        let narrow = image.render(3);
        assert_ne!(wide, narrow);
        assert!(narrow.iter().all(|line| visible_width(line) <= 3));
    }

    #[test]
    fn test_image_new() {
        let image = Image::new();
        assert!(!image.is_loaded());
    }

    #[test]
    fn test_image_from_data() {
        let data = vec![0x89, 0x50, 0x4E, 0x47]; // PNG header start
        let image = Image::from_data(data, ImageOptions::default());
        assert!(image.is_loaded());
    }

    #[test]
    fn test_image_placeholder() {
        let image = Image::new();
        let lines = image.render(20);
        assert!(!lines.is_empty());
    }
}