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
//! Background task runner with result polling
//!
//! Spawn background tasks and poll for results in the tick loop.

use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver, Sender};
use std::thread::{self, JoinHandle};

/// Unique task identifier
pub type TaskId = &'static str;

/// Task result with ID
#[derive(Debug)]
pub struct TaskResult<T> {
    /// Task identifier
    pub id: TaskId,
    /// Task result (success or error message)
    pub result: Result<T, String>,
}

/// Internal task message
struct TaskMessage<T> {
    id: TaskId,
    result: Result<T, String>,
}

/// Background task runner
///
/// # Example
///
/// ```ignore
/// let mut tasks: TaskRunner<MountResult> = TaskRunner::new();
///
/// // Spawn a background task
/// tasks.spawn("mount_host", || {
///     mount_sshfs("myhost")
/// });
///
/// // In tick handler
/// while let Some(result) = tasks.poll() {
///     match result.id {
///         "mount_host" => handle_mount(result.result),
///         _ => {}
///     }
/// }
/// ```
pub struct TaskRunner<T: Send + 'static> {
    rx: Receiver<TaskMessage<T>>,
    tx: Sender<TaskMessage<T>>,
    pending: HashMap<TaskId, ()>,
    handles: Vec<JoinHandle<()>>,
}

impl<T: Send + 'static> TaskRunner<T> {
    /// Create a new task runner
    pub fn new() -> Self {
        let (tx, rx) = mpsc::channel();
        Self {
            rx,
            tx,
            pending: HashMap::new(),
            handles: Vec::new(),
        }
    }

    /// Spawn a background task
    ///
    /// The task function runs in a separate thread and results are
    /// collected via `poll()`.
    pub fn spawn<F>(&mut self, id: TaskId, task: F)
    where
        F: FnOnce() -> T + Send + 'static,
    {
        if self.pending.contains_key(id) {
            return; // Task with this ID already running
        }

        self.pending.insert(id, ());
        let tx = self.tx.clone();

        let handle = thread::spawn(move || {
            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(task));
            let msg = match result {
                Ok(value) => TaskMessage {
                    id,
                    result: Ok(value),
                },
                Err(e) => TaskMessage {
                    id,
                    result: Err(format!("Task panicked: {:?}", e)),
                },
            };
            let _ = tx.send(msg);
        });

        self.handles.push(handle);
    }

    /// Spawn a task that returns Result
    pub fn spawn_result<F, E>(&mut self, id: TaskId, task: F)
    where
        F: FnOnce() -> Result<T, E> + Send + 'static,
        E: std::fmt::Display,
    {
        if self.pending.contains_key(id) {
            return;
        }

        self.pending.insert(id, ());
        let tx = self.tx.clone();

        let handle = thread::spawn(move || {
            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(task));
            let msg = match result {
                Ok(Ok(value)) => TaskMessage {
                    id,
                    result: Ok(value),
                },
                Ok(Err(e)) => TaskMessage {
                    id,
                    result: Err(e.to_string()),
                },
                Err(e) => TaskMessage {
                    id,
                    result: Err(format!("Task panicked: {:?}", e)),
                },
            };
            let _ = tx.send(msg);
        });

        self.handles.push(handle);
    }

    /// Poll for completed task results. Call this in your tick handler.
    pub fn poll(&mut self) -> Option<TaskResult<T>> {
        match self.rx.try_recv() {
            Ok(msg) => {
                self.pending.remove(msg.id);
                Some(TaskResult {
                    id: msg.id,
                    result: msg.result,
                })
            }
            Err(_) => None,
        }
    }

    /// Check if a specific task is running
    pub fn is_running(&self, id: TaskId) -> bool {
        self.pending.contains_key(id)
    }

    /// Check if any tasks are running
    pub fn has_pending(&self) -> bool {
        !self.pending.is_empty()
    }

    /// Get count of pending tasks
    pub fn pending_count(&self) -> usize {
        self.pending.len()
    }

    /// Cancel tracking of a task (doesn't stop the thread)
    pub fn cancel(&mut self, id: TaskId) {
        self.pending.remove(id);
    }

    /// Clean up completed thread handles
    pub fn cleanup(&mut self) {
        self.handles.retain(|h| !h.is_finished());
    }
}

impl<T: Send + 'static> Default for TaskRunner<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Send + 'static> Drop for TaskRunner<T> {
    fn drop(&mut self) {
        // Wait for all threads to complete
        for handle in self.handles.drain(..) {
            let _ = handle.join();
        }
    }
}

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

    #[test]
    fn test_spawn_and_poll() {
        let mut runner: TaskRunner<i32> = TaskRunner::new();

        runner.spawn("add", || 1 + 1);

        assert!(runner.is_running("add"));

        // Wait for completion
        std::thread::sleep(Duration::from_millis(50));

        let result = runner.poll();
        assert!(result.is_some());
        let result = result.unwrap();
        assert_eq!(result.id, "add");
        assert_eq!(result.result, Ok(2));

        assert!(!runner.is_running("add"));
    }

    #[test]
    fn test_multiple_tasks() {
        let mut runner: TaskRunner<i32> = TaskRunner::new();

        runner.spawn("task1", || 10);
        runner.spawn("task2", || 20);

        assert_eq!(runner.pending_count(), 2);

        std::thread::sleep(Duration::from_millis(50));

        let mut results = Vec::new();
        while let Some(r) = runner.poll() {
            results.push(r);
        }

        assert_eq!(results.len(), 2);
        assert_eq!(runner.pending_count(), 0);
    }

    #[test]
    fn test_default() {
        let runner: TaskRunner<i32> = TaskRunner::default();
        assert!(!runner.has_pending());
        assert_eq!(runner.pending_count(), 0);
    }

    #[test]
    fn test_has_pending() {
        let mut runner: TaskRunner<i32> = TaskRunner::new();
        assert!(!runner.has_pending());

        runner.spawn("task", || 42);
        assert!(runner.has_pending());

        std::thread::sleep(Duration::from_millis(50));
        runner.poll();
        assert!(!runner.has_pending());
    }

    #[test]
    fn test_cancel() {
        let mut runner: TaskRunner<i32> = TaskRunner::new();

        runner.spawn("slow_task", || {
            std::thread::sleep(Duration::from_millis(500));
            42
        });

        assert!(runner.is_running("slow_task"));
        runner.cancel("slow_task");
        assert!(!runner.is_running("slow_task"));
        assert_eq!(runner.pending_count(), 0);
    }

    #[test]
    fn test_duplicate_task_id_rejected() {
        let mut runner: TaskRunner<i32> = TaskRunner::new();

        runner.spawn("same_id", || {
            std::thread::sleep(Duration::from_millis(10));
            1
        });

        // This should be ignored since task with same ID is running
        runner.spawn("same_id", || 2);

        // Still only 1 pending
        assert_eq!(runner.pending_count(), 1);

        // Poll with timeout instead of fixed sleep
        let mut result = None;
        for _ in 0..100 {
            if let Some(r) = runner.poll() {
                result = Some(r);
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }

        assert!(result.is_some());
        // Should get result from first task
        assert_eq!(result.unwrap().result, Ok(1));
    }

    #[test]
    fn test_spawn_result_ok() {
        let mut runner: TaskRunner<i32> = TaskRunner::new();

        runner.spawn_result("ok_task", || -> Result<i32, &str> { Ok(100) });

        std::thread::sleep(Duration::from_millis(50));

        let result = runner.poll().unwrap();
        assert_eq!(result.id, "ok_task");
        assert_eq!(result.result, Ok(100));
    }

    #[test]
    fn test_spawn_result_err() {
        let mut runner: TaskRunner<i32> = TaskRunner::new();

        runner.spawn_result("err_task", || -> Result<i32, &str> { Err("failed") });

        std::thread::sleep(Duration::from_millis(50));

        let result = runner.poll().unwrap();
        assert_eq!(result.id, "err_task");
        assert!(result.result.is_err());
        assert_eq!(result.result.unwrap_err(), "failed");
    }

    #[test]
    fn test_spawn_result_duplicate_rejected() {
        let mut runner: TaskRunner<i32> = TaskRunner::new();

        runner.spawn_result("dup", || -> Result<i32, &str> {
            std::thread::sleep(Duration::from_millis(100));
            Ok(1)
        });

        runner.spawn_result("dup", || -> Result<i32, &str> { Ok(2) });

        assert_eq!(runner.pending_count(), 1);
    }

    #[test]
    fn test_cleanup() {
        let mut runner: TaskRunner<i32> = TaskRunner::new();

        runner.spawn("fast", || 1);
        std::thread::sleep(Duration::from_millis(50));

        // Poll to get result
        runner.poll();

        // Cleanup should remove finished handles
        runner.cleanup();
        // No assertion needed - just verify it doesn't panic
    }

    #[test]
    fn test_poll_empty() {
        let mut runner: TaskRunner<i32> = TaskRunner::new();
        assert!(runner.poll().is_none());
    }

    #[test]
    fn test_is_running_nonexistent() {
        let runner: TaskRunner<i32> = TaskRunner::new();
        assert!(!runner.is_running("nonexistent"));
    }

    #[test]
    fn test_cancel_nonexistent() {
        let mut runner: TaskRunner<i32> = TaskRunner::new();
        // Should not panic
        runner.cancel("nonexistent");
        assert_eq!(runner.pending_count(), 0);
    }

    #[test]
    fn test_task_result_debug() {
        let result = TaskResult {
            id: "test",
            result: Ok(42),
        };
        let debug = format!("{:?}", result);
        assert!(debug.contains("test"));
        assert!(debug.contains("42"));
    }

    #[test]
    fn test_task_with_string_result() {
        let mut runner: TaskRunner<String> = TaskRunner::new();

        runner.spawn("string_task", || "hello".to_string());

        std::thread::sleep(Duration::from_millis(50));

        let result = runner.poll().unwrap();
        assert_eq!(result.result, Ok("hello".to_string()));
    }

    #[test]
    fn test_task_with_vec_result() {
        let mut runner: TaskRunner<Vec<i32>> = TaskRunner::new();

        runner.spawn("vec_task", || vec![1, 2, 3]);

        std::thread::sleep(Duration::from_millis(50));

        let result = runner.poll().unwrap();
        assert_eq!(result.result, Ok(vec![1, 2, 3]));
    }

    #[test]
    fn test_panic_handling() {
        let mut runner: TaskRunner<i32> = TaskRunner::new();

        runner.spawn("panic_task", || {
            panic!("intentional panic");
        });

        std::thread::sleep(Duration::from_millis(50));

        let result = runner.poll().unwrap();
        assert_eq!(result.id, "panic_task");
        assert!(result.result.is_err());
        assert!(result.result.unwrap_err().contains("panicked"));
    }

    #[test]
    fn test_spawn_result_panic_handling() {
        let mut runner: TaskRunner<i32> = TaskRunner::new();

        runner.spawn_result("panic_result", || -> Result<i32, &str> {
            panic!("panic in result task");
        });

        std::thread::sleep(Duration::from_millis(50));

        let result = runner.poll().unwrap();
        assert!(result.result.is_err());
        assert!(result.result.unwrap_err().contains("panicked"));
    }
}