Skip to main content

matchmaker/preview/
view.rs

1use ratatui::text::{Line, Text};
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::sync::{Arc, Mutex};
4
5use super::AppendOnly;
6
7// Images?
8#[derive(Debug)]
9pub struct Preview {
10    lines: AppendOnly<Line<'static>>,
11    string: Arc<Mutex<Option<Text<'static>>>>,
12    /// Overrides lines when present
13    changed: Arc<AtomicBool>,
14}
15
16impl Preview {
17    pub fn results(&self) -> Text<'_> {
18        if let Some(s) = self.string.lock().unwrap().as_ref() {
19            s.clone()
20        } else {
21            let output = self.lines.read().unwrap(); // acquire read lock
22            Text::from_iter(output.iter().map(|(_, line)| line.clone()))
23        }
24    }
25
26    pub fn len(&self) -> usize {
27        if let Some(s) = self.string.lock().unwrap().as_ref() {
28            s.height()
29        } else {
30            let output = self.lines.read().unwrap();
31            output.iter().count()
32        }
33    }
34
35    pub fn is_empty(&self) -> bool {
36        if let Some(s) = self.string.lock().unwrap().as_ref() {
37            s.height() == 0
38        } else {
39            let output = self.lines.read().unwrap();
40            output.iter().next().is_none()
41        }
42    }
43
44    pub fn changed(&self) -> bool {
45        self.changed.swap(false, Ordering::Relaxed)
46    }
47
48    pub fn new(
49        lines: AppendOnly<Line<'static>>,
50        string: Arc<Mutex<Option<Text<'static>>>>,
51        changed: Arc<AtomicBool>,
52    ) -> Self {
53        Self {
54            lines,
55            string,
56            changed,
57        }
58    }
59}