revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
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
//! Clipboard utilities for copy/paste operations
//!
//! Provides cross-platform clipboard access for TUI applications.
//!
//! # Example
//!
//! ```rust,ignore
//! use revue::utils::clipboard::{copy, paste, Clipboard};
//!
//! // Simple copy/paste
//! copy("Hello, World!").unwrap();
//! let text = paste().unwrap();
//!
//! // Using clipboard instance
//! let clipboard = Clipboard::new();
//! clipboard.set("Some text").unwrap();
//! let content = clipboard.get().unwrap();
//! ```

use super::lock::lock_or_recover;
use crate::constants::MAX_CLIPBOARD_SIZE;
use std::io::{self, Write};
use std::process::{Command, Stdio};
use std::sync::OnceLock;

/// Sanitize clipboard content by removing dangerous characters and ANSI escapes
fn sanitize_clipboard_content(content: &str) -> String {
    // First strip ANSI escape sequences to prevent terminal injection
    let stripped = crate::utils::ansi::strip_ansi(content);
    stripped
        .chars()
        .filter(|&c| {
            // Keep printable characters and common whitespace
            // Filter out null bytes, ESC (0x1B), and other control characters except:
            // - \t (tab), \n (newline), \r (carriage return)
            (c >= ' ' && c != '\x1b') || c == '\t' || c == '\n' || c == '\r'
        })
        .collect()
}

/// Clipboard error type
#[derive(Debug)]
pub enum ClipboardError {
    /// No clipboard tool available
    NoClipboardTool,
    /// I/O error
    Io(io::Error),
    /// Command failed
    CommandFailed(String),
    /// Invalid UTF-8 in clipboard content
    InvalidUtf8,
    /// Invalid input (e.g., too large)
    InvalidInput(String),
}

impl std::fmt::Display for ClipboardError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ClipboardError::NoClipboardTool => write!(f, "No clipboard tool available"),
            ClipboardError::Io(e) => write!(f, "I/O error: {}", e),
            ClipboardError::CommandFailed(msg) => write!(f, "Command failed: {}", msg),
            ClipboardError::InvalidUtf8 => write!(f, "Invalid UTF-8 in clipboard content"),
            ClipboardError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
        }
    }
}

impl std::error::Error for ClipboardError {}

impl From<io::Error> for ClipboardError {
    fn from(err: io::Error) -> Self {
        ClipboardError::Io(err)
    }
}

/// Result type for clipboard operations
pub type ClipboardResult<T> = Result<T, ClipboardError>;

/// Clipboard backend trait
pub trait ClipboardBackend {
    /// Copy text to clipboard
    fn set(&self, content: &str) -> ClipboardResult<()>;

    /// Get text from clipboard
    fn get(&self) -> ClipboardResult<String>;

    /// Check if clipboard contains text
    fn has_text(&self) -> ClipboardResult<bool>;

    /// Clear clipboard
    fn clear(&self) -> ClipboardResult<()>;
}

/// Cached clipboard command detection to avoid repeated subprocess spawning
static COPY_COMMAND_CACHE: OnceLock<Option<(&'static str, &'static [&'static str])>> =
    OnceLock::new();
static PASTE_COMMAND_CACHE: OnceLock<Option<(&'static str, &'static [&'static str])>> =
    OnceLock::new();

/// Platform-specific clipboard implementation
#[derive(Clone, Debug, Default)]
pub struct SystemClipboard;

impl SystemClipboard {
    /// Create new system clipboard instance
    pub fn new() -> Self {
        Self
    }

    /// Get the appropriate copy command for the platform (cached)
    fn copy_command() -> Option<(&'static str, &'static [&'static str])> {
        *COPY_COMMAND_CACHE.get_or_init(|| {
            #[cfg(target_os = "macos")]
            {
                Some(("pbcopy", &[]))
            }

            #[cfg(target_os = "linux")]
            {
                // Try xclip first, then xsel, then wl-copy
                // Use direct command execution instead of shell to avoid injection risk
                let check_cmd = |cmd: &str| -> bool {
                    // Most clipboard tools support --version or --help for availability check
                    // Try to execute the command directly without shell
                    Command::new(cmd)
                        .arg("--version")
                        .stdout(Stdio::null())
                        .stderr(Stdio::null())
                        .status()
                        .map(|s| s.success())
                        .unwrap_or(false)
                };

                if check_cmd("xclip") {
                    Some(("xclip", &["-selection", "clipboard"]))
                } else if check_cmd("xsel") {
                    Some(("xsel", &["--clipboard", "--input"]))
                } else if check_cmd("wl-copy") {
                    Some(("wl-copy", &[]))
                } else {
                    None
                }
            }

            #[cfg(target_os = "windows")]
            {
                Some(("clip", &[]))
            }

            #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
            {
                None
            }
        })
    }

    /// Get the appropriate paste command for the platform (cached)
    fn paste_command() -> Option<(&'static str, &'static [&'static str])> {
        *PASTE_COMMAND_CACHE.get_or_init(|| {
            #[cfg(target_os = "macos")]
            {
                Some(("pbpaste", &[]))
            }

            #[cfg(target_os = "linux")]
            {
                // Try xclip first, then xsel, then wl-paste
                // Use direct command execution instead of shell to avoid injection risk
                let check_cmd = |cmd: &str| -> bool {
                    // Most clipboard tools support --version or --help for availability check
                    // Try to execute the command directly without shell
                    Command::new(cmd)
                        .arg("--version")
                        .stdout(Stdio::null())
                        .stderr(Stdio::null())
                        .status()
                        .map(|s| s.success())
                        .unwrap_or(false)
                };

                if check_cmd("xclip") {
                    Some(("xclip", &["-selection", "clipboard", "-o"]))
                } else if check_cmd("xsel") {
                    Some(("xsel", &["--clipboard", "--output"]))
                } else if check_cmd("wl-paste") {
                    Some(("wl-paste", &[]))
                } else {
                    None
                }
            }

            #[cfg(target_os = "windows")]
            {
                // Windows paste is more complex, use PowerShell
                Some(("powershell", &["-Command", "Get-Clipboard"]))
            }

            #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
            {
                None
            }
        })
    }
}

impl ClipboardBackend for SystemClipboard {
    fn set(&self, content: &str) -> ClipboardResult<()> {
        // Validate size to prevent DoS
        if content.len() > MAX_CLIPBOARD_SIZE {
            return Err(ClipboardError::InvalidInput(format!(
                "Clipboard content too large ({} bytes, max {})",
                content.len(),
                MAX_CLIPBOARD_SIZE
            )));
        }

        // Sanitize content to remove dangerous control characters
        let sanitized = sanitize_clipboard_content(content);

        let (cmd, args) = Self::copy_command().ok_or(ClipboardError::NoClipboardTool)?;

        let mut child = Command::new(cmd)
            .args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()?;

        if let Some(mut stdin) = child.stdin.take() {
            stdin.write_all(sanitized.as_bytes())?;
        }

        let status = child.wait()?;
        if status.success() {
            Ok(())
        } else {
            Err(ClipboardError::CommandFailed(format!(
                "{} exited with status: {:?}",
                cmd,
                status.code()
            )))
        }
    }

    fn get(&self) -> ClipboardResult<String> {
        let (cmd, args) = Self::paste_command().ok_or(ClipboardError::NoClipboardTool)?;

        let output = Command::new(cmd)
            .args(args)
            .stdin(Stdio::null())
            .stderr(Stdio::null())
            .output()?;

        if output.status.success() {
            // Validate size to prevent DoS through large clipboard content
            if output.stdout.len() > MAX_CLIPBOARD_SIZE {
                return Err(ClipboardError::InvalidInput(format!(
                    "Clipboard content too large: {} bytes (max: {})",
                    output.stdout.len(),
                    MAX_CLIPBOARD_SIZE
                )));
            }
            String::from_utf8(output.stdout).map_err(|_| ClipboardError::InvalidUtf8)
        } else {
            Err(ClipboardError::CommandFailed(format!(
                "{} exited with status: {:?}",
                cmd,
                output.status.code()
            )))
        }
    }

    fn has_text(&self) -> ClipboardResult<bool> {
        match self.get() {
            Ok(content) => Ok(!content.is_empty()),
            Err(ClipboardError::NoClipboardTool) => Err(ClipboardError::NoClipboardTool),
            _ => Ok(false),
        }
    }

    fn clear(&self) -> ClipboardResult<()> {
        self.set("")
    }
}

/// In-memory clipboard for testing or sandboxed environments
#[derive(Clone, Debug, Default)]
pub struct MemoryClipboard {
    content: std::sync::Arc<std::sync::Mutex<String>>,
}

impl MemoryClipboard {
    /// Create new in-memory clipboard
    pub fn new() -> Self {
        Self {
            content: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
        }
    }
}

impl ClipboardBackend for MemoryClipboard {
    fn set(&self, content: &str) -> ClipboardResult<()> {
        let mut guard = lock_or_recover(&self.content);
        *guard = content.to_string();
        Ok(())
    }

    fn get(&self) -> ClipboardResult<String> {
        let guard = lock_or_recover(&self.content);
        Ok(guard.clone())
    }

    fn has_text(&self) -> ClipboardResult<bool> {
        let guard = lock_or_recover(&self.content);
        Ok(!guard.is_empty())
    }

    fn clear(&self) -> ClipboardResult<()> {
        let mut guard = lock_or_recover(&self.content);
        guard.clear();
        Ok(())
    }
}

/// Main clipboard type with pluggable backend
pub struct Clipboard {
    backend: Box<dyn ClipboardBackend + Send + Sync>,
}

impl Clipboard {
    /// Create clipboard with system backend
    pub fn new() -> Self {
        Self {
            backend: Box::new(SystemClipboard::new()),
        }
    }

    /// Create clipboard with custom backend
    pub fn with_backend<B: ClipboardBackend + Send + Sync + 'static>(backend: B) -> Self {
        Self {
            backend: Box::new(backend),
        }
    }

    /// Create in-memory clipboard (for testing)
    pub fn memory() -> Self {
        Self {
            backend: Box::new(MemoryClipboard::new()),
        }
    }

    /// Copy text to clipboard
    ///
    /// # Errors
    ///
    /// Returns `Err(ClipboardError)` if the clipboard backend cannot set the content.
    pub fn set(&self, content: &str) -> ClipboardResult<()> {
        self.backend.set(content)
    }

    /// Get text from clipboard
    ///
    /// # Errors
    ///
    /// Returns `Err(ClipboardError)` if the clipboard backend cannot access the content.
    pub fn get(&self) -> ClipboardResult<String> {
        self.backend.get()
    }

    /// Check if clipboard contains text
    ///
    /// # Errors
    ///
    /// Returns `Err(ClipboardError)` if the clipboard backend cannot be accessed.
    pub fn has_text(&self) -> ClipboardResult<bool> {
        self.backend.has_text()
    }

    /// Clear clipboard
    ///
    /// # Errors
    ///
    /// Returns `Err(ClipboardError)` if the clipboard backend cannot clear the content.
    pub fn clear(&self) -> ClipboardResult<()> {
        self.backend.clear()
    }
}

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

// Convenience functions using system clipboard

/// Copy text to system clipboard
///
/// # Errors
///
/// Returns `Err(ClipboardError)` if the system clipboard cannot be accessed or set.
pub fn copy(content: &str) -> ClipboardResult<()> {
    SystemClipboard::new().set(content)
}

/// Get text from system clipboard
///
/// # Errors
///
/// Returns `Err(ClipboardError)` if the system clipboard cannot be accessed.
pub fn paste() -> ClipboardResult<String> {
    SystemClipboard::new().get()
}

/// Check if system clipboard has text
///
/// # Errors
///
/// Returns `Err(ClipboardError)` if the system clipboard cannot be accessed.
pub fn has_text() -> ClipboardResult<bool> {
    SystemClipboard::new().has_text()
}

/// Clear system clipboard
///
/// # Errors
///
/// Returns `Err(ClipboardError)` if the system clipboard cannot be cleared.
pub fn clear() -> ClipboardResult<()> {
    SystemClipboard::new().clear()
}

/// Clipboard history manager
#[derive(Clone, Debug)]
pub struct ClipboardHistory {
    /// History entries
    entries: Vec<String>,
    /// Maximum history size
    max_size: usize,
}

impl ClipboardHistory {
    /// Create new clipboard history
    pub fn new(max_size: usize) -> Self {
        Self {
            entries: Vec::with_capacity(max_size),
            max_size,
        }
    }

    /// Add entry to history
    pub fn push(&mut self, content: String) {
        // Don't add duplicates at the top
        if self.entries.first() == Some(&content) {
            return;
        }

        // Remove if exists elsewhere (to move to top)
        self.entries.retain(|e| e != &content);

        // Add to front
        self.entries.insert(0, content);

        // Trim to max size
        self.entries.truncate(self.max_size);
    }

    /// Get entry at index (0 = most recent)
    pub fn get(&self, index: usize) -> Option<&str> {
        self.entries.get(index).map(|s| s.as_str())
    }

    /// Get most recent entry
    pub fn latest(&self) -> Option<&str> {
        self.get(0)
    }

    /// Get all entries
    pub fn entries(&self) -> &[String] {
        &self.entries
    }

    /// Get number of entries
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Check if history is empty
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Clear history
    pub fn clear(&mut self) {
        self.entries.clear();
    }
}

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