matchmaker/proc/
preview.rs

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