tui-lipan 0.1.0

Opinionated, component-based TUI framework for Rust - declarative components, reconciliation, layout engine, focus, overlays, and rich widgets on top of ratatui.
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
419
420
421
422
423
424
425
426
#[cfg(all(
    feature = "clipboard",
    feature = "clipboard-images",
    not(target_arch = "wasm32")
))]
use std::io::Cursor;

use crate::clipboard::error::{ClipboardError, ClipboardOperation};

/// Supported image formats for clipboard operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageFormat {
    /// PNG format (lossless, larger file size).
    Png,
    /// JPEG format (lossy, smaller file size).
    Jpeg,
}

impl ImageFormat {
    /// Returns the MIME type for this image format.
    pub const fn mime_type(&self) -> &'static str {
        match self {
            Self::Png => "image/png",
            Self::Jpeg => "image/jpeg",
        }
    }
}

/// Image content read from or written to the clipboard.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImageContent {
    /// Base64-encoded image data.
    pub data: String,
    /// MIME type of the image (e.g., "image/png", "image/jpeg").
    pub mime: &'static str,
    /// Optional source filename for attachments created from local files.
    pub filename: Option<String>,
}

impl ImageContent {
    /// Creates new image content from raw bytes, encoding as base64.
    pub fn from_bytes(bytes: &[u8], format: ImageFormat) -> Self {
        use base64::{Engine as _, engine::general_purpose};
        Self {
            data: general_purpose::STANDARD.encode(bytes),
            mime: format.mime_type(),
            filename: None,
        }
    }

    /// Returns this image content with source filename metadata attached.
    pub fn with_filename(mut self, filename: impl Into<String>) -> Self {
        self.filename = Some(filename.into());
        self
    }

    /// Decodes the base64 data back to raw bytes.
    pub fn to_bytes(&self) -> Result<Vec<u8>, base64::DecodeError> {
        use base64::{Engine as _, engine::general_purpose};
        general_purpose::STANDARD.decode(&self.data)
    }
}

/// Abstraction over clipboard backends.
pub trait ClipboardProvider {
    /// Read text from the system clipboard.
    fn read_clipboard_text(&mut self) -> Result<String, ClipboardError>;
    /// Write text to the system clipboard.
    fn write_clipboard_text(&mut self, text: &str) -> Result<(), ClipboardError>;

    /// Update any provider-side cache used to satisfy sync clipboard reads.
    fn set_clipboard_text_cache(&mut self, _text: String) {}

    /// Read text from the primary selection, if supported.
    fn read_primary_selection_text(&mut self) -> Result<String, ClipboardError> {
        Err(ClipboardError::unsupported(
            ClipboardOperation::ReadPrimarySelection,
        ))
    }

    /// Write text to the primary selection, if supported.
    fn write_primary_selection_text(&mut self, _text: &str) -> Result<(), ClipboardError> {
        Err(ClipboardError::unsupported(
            ClipboardOperation::WritePrimarySelection,
        ))
    }

    /// Returns true when primary selection is supported.
    fn supports_primary_selection(&self) -> bool {
        false
    }

    /// Read an image from the system clipboard.
    /// Returns the image as base64-encoded data.
    fn read_clipboard_image(&mut self) -> Result<ImageContent, ClipboardError> {
        Err(ClipboardError::unsupported(
            ClipboardOperation::ReadImageClipboard,
        ))
    }

    /// Write an image to the system clipboard.
    /// Accepts base64-encoded image data.
    fn write_clipboard_image(&mut self, _content: &ImageContent) -> Result<(), ClipboardError> {
        Err(ClipboardError::unsupported(
            ClipboardOperation::WriteImageClipboard,
        ))
    }
}

/// Clipboard provider that reports all operations as unsupported.
///
/// Used as the default when the `clipboard` feature is disabled.
#[cfg(not(feature = "clipboard"))]
pub(crate) struct NoOpClipboardProvider;

#[cfg(not(feature = "clipboard"))]
impl ClipboardProvider for NoOpClipboardProvider {
    fn read_clipboard_text(&mut self) -> Result<String, ClipboardError> {
        Err(ClipboardError::unsupported(
            ClipboardOperation::ReadClipboard,
        ))
    }

    fn write_clipboard_text(&mut self, _text: &str) -> Result<(), ClipboardError> {
        Err(ClipboardError::unsupported(
            ClipboardOperation::WriteClipboard,
        ))
    }
}

/// Arboard-backed system clipboard provider.
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
pub(crate) struct SystemClipboardProvider {
    clipboard: Option<arboard::Clipboard>,
}

#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
impl SystemClipboardProvider {
    pub fn new() -> Self {
        Self { clipboard: None }
    }

    fn ensure_clipboard(
        &mut self,
        operation: ClipboardOperation,
    ) -> Result<&mut arboard::Clipboard, ClipboardError> {
        if self.clipboard.is_none() {
            self.clipboard = Some(
                arboard::Clipboard::new()
                    .map_err(|err| ClipboardError::provider(operation, err.to_string()))?,
            );
        }

        self.clipboard
            .as_mut()
            .ok_or_else(|| ClipboardError::provider(operation, "init"))
    }
}

#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
impl Default for SystemClipboardProvider {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
impl ClipboardProvider for SystemClipboardProvider {
    fn read_clipboard_text(&mut self) -> Result<String, ClipboardError> {
        let clipboard = self.ensure_clipboard(ClipboardOperation::ReadClipboard)?;
        clipboard.get_text().map_err(|err| {
            ClipboardError::provider(ClipboardOperation::ReadClipboard, err.to_string())
        })
    }

    fn write_clipboard_text(&mut self, text: &str) -> Result<(), ClipboardError> {
        let clipboard = self.ensure_clipboard(ClipboardOperation::WriteClipboard)?;
        clipboard.set_text(text.to_string()).map_err(|err| {
            ClipboardError::provider(ClipboardOperation::WriteClipboard, err.to_string())
        })
    }

    fn read_primary_selection_text(&mut self) -> Result<String, ClipboardError> {
        #[cfg(target_os = "linux")]
        {
            use arboard::{GetExtLinux, LinuxClipboardKind};
            let clipboard = self.ensure_clipboard(ClipboardOperation::ReadPrimarySelection)?;
            clipboard
                .get()
                .clipboard(LinuxClipboardKind::Primary)
                .text()
                .map_err(|err| {
                    ClipboardError::provider(
                        ClipboardOperation::ReadPrimarySelection,
                        err.to_string(),
                    )
                })
        }

        #[cfg(not(target_os = "linux"))]
        {
            Err(ClipboardError::unsupported(
                ClipboardOperation::ReadPrimarySelection,
            ))
        }
    }

    fn write_primary_selection_text(&mut self, _text: &str) -> Result<(), ClipboardError> {
        #[cfg(target_os = "linux")]
        {
            use arboard::{LinuxClipboardKind, SetExtLinux};
            let clipboard = self.ensure_clipboard(ClipboardOperation::WritePrimarySelection)?;
            clipboard
                .set()
                .clipboard(LinuxClipboardKind::Primary)
                .text(_text.to_string())
                .map_err(|err| {
                    ClipboardError::provider(
                        ClipboardOperation::WritePrimarySelection,
                        err.to_string(),
                    )
                })
        }

        #[cfg(not(target_os = "linux"))]
        {
            Err(ClipboardError::unsupported(
                ClipboardOperation::WritePrimarySelection,
            ))
        }
    }

    fn supports_primary_selection(&self) -> bool {
        cfg!(target_os = "linux")
    }

    #[cfg(feature = "clipboard-images")]
    fn read_clipboard_image(&mut self) -> Result<ImageContent, ClipboardError> {
        #[cfg(target_os = "linux")]
        if let Some(content) = read_wayland_png_clipboard()? {
            return Ok(content);
        }

        let clipboard = self.ensure_clipboard(ClipboardOperation::ReadImageClipboard)?;

        let image_data = clipboard.get_image().map_err(|err| {
            ClipboardError::provider(ClipboardOperation::ReadImageClipboard, err.to_string())
        })?;

        let width = image_data.width;
        let height = image_data.height;
        let rgba_bytes = image_data.bytes.into_owned();

        let mut png_buffer = Cursor::new(Vec::new());
        {
            let image_buffer = image::ImageBuffer::<image::Rgba<u8>, Vec<u8>>::from_raw(
                width as u32,
                height as u32,
                rgba_bytes,
            )
            .ok_or_else(|| {
                ClipboardError::provider(
                    ClipboardOperation::ReadImageClipboard,
                    "invalid image buffer dimensions",
                )
            })?;

            image_buffer
                .write_to(&mut png_buffer, image::ImageFormat::Png)
                .map_err(|err| {
                    ClipboardError::provider(
                        ClipboardOperation::ReadImageClipboard,
                        format!("PNG encode error: {}", err),
                    )
                })?;
        }

        Ok(ImageContent::from_bytes(
            png_buffer.into_inner().as_slice(),
            ImageFormat::Png,
        ))
    }

    #[cfg(feature = "clipboard-images")]
    fn write_clipboard_image(&mut self, content: &ImageContent) -> Result<(), ClipboardError> {
        let clipboard = self.ensure_clipboard(ClipboardOperation::WriteImageClipboard)?;

        let bytes = content.to_bytes().map_err(|err| {
            ClipboardError::provider(
                ClipboardOperation::WriteImageClipboard,
                format!("base64 decode error: {}", err),
            )
        })?;

        let img = image::load_from_memory(&bytes).map_err(|err| {
            ClipboardError::provider(
                ClipboardOperation::WriteImageClipboard,
                format!("image decode error: {}", err),
            )
        })?;

        let rgba = img.to_rgba8();
        let width = rgba.width() as usize;
        let height = rgba.height() as usize;
        let pixels: Vec<u8> = rgba.into_raw();

        clipboard
            .set_image(arboard::ImageData {
                width,
                height,
                bytes: std::borrow::Cow::Owned(pixels),
            })
            .map_err(|err| {
                ClipboardError::provider(ClipboardOperation::WriteImageClipboard, err.to_string())
            })
    }
}

#[cfg(all(
    feature = "clipboard",
    feature = "clipboard-images",
    target_os = "linux"
))]
fn read_wayland_png_clipboard() -> Result<Option<ImageContent>, ClipboardError> {
    use std::io::Read as _;

    use wl_clipboard_rs::paste::{ClipboardType, Error, MimeType, Seat, get_contents};

    if std::env::var_os("WAYLAND_DISPLAY").is_none() {
        return Ok(None);
    }

    let (mut reader, _) = match get_contents(
        ClipboardType::Regular,
        Seat::Unspecified,
        MimeType::Specific(ImageFormat::Png.mime_type()),
    ) {
        Ok(result) => result,
        Err(
            Error::NoSeats
            | Error::ClipboardEmpty
            | Error::NoMimeType
            | Error::SocketOpenError(_)
            | Error::WaylandConnection(_)
            | Error::MissingProtocol { .. }
            | Error::PrimarySelectionUnsupported
            | Error::SeatNotFound,
        ) => return Ok(None),
        Err(err) => {
            return Err(ClipboardError::provider(
                ClipboardOperation::ReadImageClipboard,
                err.to_string(),
            ));
        }
    };

    let mut bytes = Vec::new();
    reader.read_to_end(&mut bytes).map_err(|err| {
        ClipboardError::provider(ClipboardOperation::ReadImageClipboard, err.to_string())
    })?;

    if bytes.is_empty() {
        return Ok(None);
    }

    Ok(Some(ImageContent::from_bytes(&bytes, ImageFormat::Png)))
}

#[cfg(all(target_arch = "wasm32", feature = "web"))]
#[derive(Default)]
pub(crate) struct WebClipboardProvider {
    cache: std::rc::Rc<std::cell::RefCell<Option<String>>>,
}

#[cfg(all(target_arch = "wasm32", feature = "web"))]
impl WebClipboardProvider {
    pub fn new() -> Self {
        Self::default()
    }
}

#[cfg(all(target_arch = "wasm32", feature = "web"))]
impl ClipboardProvider for WebClipboardProvider {
    fn read_clipboard_text(&mut self) -> Result<String, ClipboardError> {
        if let Some(cached) = self.cache.borrow().clone() {
            return Ok(cached);
        }

        Err(ClipboardError::provider(
            ClipboardOperation::ReadClipboard,
            "web clipboard read requires a primed cache from a paste gesture",
        ))
    }

    fn write_clipboard_text(&mut self, text: &str) -> Result<(), ClipboardError> {
        let window = web_sys::window().ok_or_else(|| {
            ClipboardError::provider(ClipboardOperation::WriteClipboard, "window is unavailable")
        })?;
        let navigator = window.navigator();
        let clipboard = navigator.clipboard();
        let promise = clipboard.write_text(text);

        let cache = std::rc::Rc::clone(&self.cache);
        let text = text.to_string();
        let fut = wasm_bindgen_futures::JsFuture::from(promise);
        wasm_bindgen_futures::spawn_local(async move {
            match fut.await {
                Ok(_) => {
                    *cache.borrow_mut() = Some(text);
                }
                Err(err) => {
                    web_sys::console::warn_1(&err);
                }
            }
        });
        Ok(())
    }

    fn set_clipboard_text_cache(&mut self, text: String) {
        *self.cache.borrow_mut() = Some(text);
    }

    fn supports_primary_selection(&self) -> bool {
        false
    }
}