tui-lipan 0.2.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
#[cfg(all(
    feature = "clipboard",
    feature = "clipboard-images",
    not(target_arch = "wasm32")
))]
use std::io::Cursor;

use std::path::PathBuf;

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>,
}

/// Clipboard content classification used by performable terminal paste shortcuts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClipboardPasteContent {
    /// Plain text that the terminal host can paste directly.
    Text(String),
    /// A file list, image, or another richer format that the child should inspect itself.
    Rich,
    /// No known text or rich format was available. This may also represent an empty clipboard.
    Unavailable,
}

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>;

    /// Classify content for a terminal's performable paste shortcut.
    ///
    /// Providers with richer format support should prefer files/images over a text fallback. The
    /// default keeps custom providers source-compatible and treats text read failures as genuine
    /// provider failures rather than guessing that the clipboard contains another format.
    fn read_terminal_paste(&mut self) -> Result<ClipboardPasteContent, ClipboardError> {
        self.read_clipboard_text().map(ClipboardPasteContent::Text)
    }

    /// 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,
        ))
    }

    /// Read a file list from the system clipboard.
    ///
    /// Returns an empty vector when the clipboard holds no file list, which is
    /// distinct from the provider being unable to read one at all.
    fn read_clipboard_files(&mut self) -> Result<Vec<PathBuf>, ClipboardError> {
        Err(ClipboardError::unsupported(
            ClipboardOperation::ReadFileClipboard,
        ))
    }

    /// Write a file list to the system clipboard.
    ///
    /// Paths are expected to be absolute and to exist; callers going through
    /// [`ClipboardHandle::copy_files`](crate::ClipboardHandle::copy_files)
    /// get that guaranteed for them.
    fn write_clipboard_files(&mut self, _paths: &[PathBuf]) -> Result<(), ClipboardError> {
        Err(ClipboardError::unsupported(
            ClipboardOperation::WriteFileClipboard,
        ))
    }

    /// Returns true when the provider can exchange file lists.
    fn supports_file_clipboard(&self) -> bool {
        false
    }
}

/// 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_terminal_paste(&mut self) -> Result<ClipboardPasteContent, ClipboardError> {
        let clipboard = self.ensure_clipboard(ClipboardOperation::ReadClipboard)?;
        match clipboard.get().file_list() {
            Ok(files) if !files.is_empty() => return Ok(ClipboardPasteContent::Rich),
            Ok(_) | Err(arboard::Error::ContentNotAvailable) => {}
            Err(err) => {
                return Err(ClipboardError::provider(
                    ClipboardOperation::ReadClipboard,
                    err.to_string(),
                ));
            }
        }

        #[cfg(feature = "clipboard-images")]
        {
            let probe_image_data = true;
            #[cfg(target_os = "linux")]
            let probe_image_data = match wayland_clipboard_has_png()? {
                Some(true) => return Ok(ClipboardPasteContent::Rich),
                Some(false) => false,
                None => probe_image_data,
            };

            if probe_image_data {
                // arboard has no cross-platform format-presence API. X11, macOS, and Windows must
                // currently decode the advertised image to confirm it; Wayland uses the MIME list
                // above and avoids reading the payload.
                let clipboard = self.ensure_clipboard(ClipboardOperation::ReadImageClipboard)?;
                match clipboard.get().image() {
                    Ok(_) => return Ok(ClipboardPasteContent::Rich),
                    Err(arboard::Error::ContentNotAvailable) => {}
                    Err(err) => {
                        return Err(ClipboardError::provider(
                            ClipboardOperation::ReadImageClipboard,
                            err.to_string(),
                        ));
                    }
                }
            }
        }

        let clipboard = self.ensure_clipboard(ClipboardOperation::ReadClipboard)?;
        match clipboard.get().text() {
            Ok(text) => Ok(ClipboardPasteContent::Text(text)),
            Err(arboard::Error::ContentNotAvailable) => Ok(ClipboardPasteContent::Unavailable),
            Err(err) => Err(ClipboardError::provider(
                ClipboardOperation::ReadClipboard,
                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")
    }

    fn read_clipboard_files(&mut self) -> Result<Vec<PathBuf>, ClipboardError> {
        let clipboard = self.ensure_clipboard(ClipboardOperation::ReadFileClipboard)?;
        match clipboard.get().file_list() {
            Ok(paths) => Ok(paths),
            // An absent file list is an empty result, not a failure.
            Err(arboard::Error::ContentNotAvailable) => Ok(Vec::new()),
            Err(err) => Err(ClipboardError::provider(
                ClipboardOperation::ReadFileClipboard,
                err.to_string(),
            )),
        }
    }

    fn write_clipboard_files(&mut self, paths: &[PathBuf]) -> Result<(), ClipboardError> {
        let clipboard = self.ensure_clipboard(ClipboardOperation::WriteFileClipboard)?;
        clipboard.set().file_list(paths).map_err(|err| {
            ClipboardError::provider(ClipboardOperation::WriteFileClipboard, err.to_string())
        })
    }

    fn supports_file_clipboard(&self) -> bool {
        true
    }

    #[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(
    feature = "clipboard",
    feature = "clipboard-images",
    target_os = "linux"
))]
fn wayland_clipboard_has_png() -> Result<Option<bool>, ClipboardError> {
    use wl_clipboard_rs::paste::{ClipboardType, Error, Seat, get_mime_types};

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

    match get_mime_types(ClipboardType::Regular, Seat::Unspecified) {
        Ok(types) => Ok(Some(types.contains(ImageFormat::Png.mime_type()))),
        Err(Error::ClipboardEmpty | Error::NoMimeType) => Ok(Some(false)),
        Err(
            Error::NoSeats
            | Error::SocketOpenError(_)
            | Error::WaylandConnection(_)
            | Error::MissingProtocol { .. }
            | Error::PrimarySelectionUnsupported
            | Error::SeatNotFound,
        ) => Ok(None),
        Err(err) => Err(ClipboardError::provider(
            ClipboardOperation::ReadImageClipboard,
            err.to_string(),
        )),
    }
}

#[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
    }
}