Skip to main content

matchmaker/preview/
previewer.rs

1use ansi_to_tui::IntoText;
2use cba::broc::{CommandExt, EnvVars};
3use futures::FutureExt;
4use log::{debug, error, warn};
5use ratatui::text::{Line, Text};
6use std::io::BufReader;
7use std::process::{Child, Command, Stdio};
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::{Arc, Mutex};
10use std::thread;
11use std::time::{Duration, Instant};
12use tokio::sync::watch::{Receiver, Sender, channel};
13use tokio::task::JoinHandle;
14
15use super::AppendOnly;
16use crate::config::PreviewerConfig;
17use crate::event::EventSender;
18use crate::message::Event;
19use crate::preview::Preview;
20
21#[derive(Debug, Default, strum_macros::Display, Clone)]
22pub enum PreviewMessage {
23    Run(String, EnvVars),
24    Set(Text<'static>),
25    Unset,
26    #[default]
27    Stop,
28    Pause,
29    Unpause,
30}
31
32#[derive(Debug)]
33pub struct Previewer {
34    /// The reciever for for [`PreviewMessage`]'s.
35    rx: Receiver<PreviewMessage>,
36    /// storage for preview command output
37    lines: AppendOnly<Line<'static>>,
38    /// storage for preview string override
39    string: Arc<Mutex<Option<Text<'static>>>>,
40    /// Flag which is set to true whenever the state changes
41    /// and which the viewer can toggle after receiving the current state
42    changed: Arc<AtomicBool>,
43
44    paused: bool,
45    /// Maintain a queue of child processes to improve cleanup reliability
46    procs: Vec<Child>,
47    /// The currently executing child process
48    current: Option<(Child, JoinHandle<bool>)>,
49    pub config: PreviewerConfig,
50    /// Event loop controller
51    // We only use it to send [`ControlEvent::Event`]
52    event_controller_tx: Option<EventSender>,
53}
54
55impl Previewer {
56    pub fn new(config: PreviewerConfig) -> (Self, Sender<PreviewMessage>) {
57        let (tx, rx) = channel(PreviewMessage::Stop);
58
59        let new = Self {
60            rx,
61            lines: AppendOnly::new(),
62            string: Default::default(),
63            changed: Default::default(),
64            paused: false,
65
66            procs: Vec::new(),
67            current: None,
68            config,
69            event_controller_tx: None,
70        };
71
72        (new, tx)
73    }
74
75    pub fn view(&self) -> Preview {
76        Preview::new(
77            self.lines.clone(),
78            self.string.clone(),
79            self.changed.clone(),
80        )
81    }
82
83    pub fn set_string(&self, s: Text<'static>) {
84        if let Ok(mut guard) = self.string.lock() {
85            *guard = Some(s);
86            self.changed.store(true, Ordering::Release);
87        }
88    }
89
90    pub fn clear_string(&self) {
91        if let Ok(mut guard) = self.string.lock() {
92            *guard = None;
93            self.changed.store(true, Ordering::Release);
94        }
95    }
96
97    pub fn has_string(&self) -> bool {
98        let guard = self.string.lock();
99        guard.is_ok_and(|s| s.is_some())
100    }
101
102    pub async fn run(mut self) -> Result<(), Vec<Child>> {
103        while self.rx.changed().await.is_ok() {
104            if !self.procs.is_empty() {
105                debug!("procs: {:?}", self.procs);
106            }
107
108            {
109                let m = &*self.rx.borrow();
110                match m {
111                    PreviewMessage::Pause => {
112                        self.paused = true;
113                        continue;
114                    }
115                    PreviewMessage::Unpause => {
116                        self.paused = false;
117                        continue;
118                    }
119                    _ if self.paused => {
120                        continue;
121                    }
122                    PreviewMessage::Set(s) => {
123                        self.set_string(s.clone());
124                        // don't kill the underlying
125                        continue;
126                    }
127                    PreviewMessage::Unset => {
128                        self.clear_string();
129                        continue;
130                    }
131                    _ => {}
132                }
133            }
134
135            self.dispatch_kill();
136            self.clear_string();
137            self.lines.clear();
138
139            match &*self.rx.borrow() {
140                PreviewMessage::Run(cmd, variables) => {
141                    if let Some(mut child) = Command::from_script(cmd)
142                        .envs(variables.iter().cloned())
143                        .stdout(Stdio::piped())
144                        .stdin(Stdio::null())
145                        .stderr(Stdio::null())
146                        .detach()
147                        ._spawn()
148                    {
149                        if let Some(stdout) = child.stdout.take() {
150                            self.changed.store(true, Ordering::Relaxed);
151
152                            let lines = self.lines.clone();
153                            let guard = self.lines.read();
154                            let cmd = cmd.clone();
155
156                            // false => needs refresh (i.e. invalid utf-8)
157                            let handle = tokio::spawn(async move {
158                                let mut reader = BufReader::new(stdout);
159                                let mut leftover = Vec::new();
160                                let mut buf = [0u8; 8192];
161
162                                while let Ok(n) = std::io::Read::read(&mut reader, &mut buf) {
163                                    if n == 0 {
164                                        break;
165                                    }
166
167                                    leftover.extend_from_slice(&buf[..n]);
168
169                                    let valid_up_to = match std::str::from_utf8(&leftover) {
170                                        Ok(_) => leftover.len(),
171                                        Err(e) => e.valid_up_to(),
172                                    };
173
174                                    let split_at = leftover[..valid_up_to]
175                                        .iter()
176                                        .rposition(|&b| b == b'\n' || b == b'\r')
177                                        .map(|pos| pos + 1)
178                                        .unwrap_or(valid_up_to);
179
180                                    let (valid_bytes, rest) = leftover.split_at(split_at);
181
182                                    match valid_bytes.into_text() {
183                                        Ok(text) => {
184                                            for line in text {
185                                                // re-check before pushing
186                                                if lines.is_expired(&guard) {
187                                                    return true;
188                                                }
189                                                guard.push(line);
190                                            }
191                                        }
192                                        Err(e) => {
193                                            if self.config.try_lossy {
194                                                for bytes in valid_bytes.split(|b| *b == b'\n') {
195                                                    if lines.is_expired(&guard) {
196                                                        return true;
197                                                    }
198                                                    let line =
199                                                        String::from_utf8_lossy(bytes).into_owned();
200                                                    guard.push(Line::from(line));
201                                                }
202                                            } else {
203                                                error!("Error displaying {cmd}: {:?}", e);
204                                                return false;
205                                            }
206                                        }
207                                    }
208
209                                    leftover = rest.to_vec();
210                                }
211
212                                if !leftover.is_empty() && !lines.is_expired(&guard) {
213                                    match leftover.into_text() {
214                                        Ok(text) => {
215                                            for line in text {
216                                                if lines.is_expired(&guard) {
217                                                    return true;
218                                                }
219                                                guard.push(line);
220                                            }
221                                        }
222                                        Err(e) => {
223                                            if self.config.try_lossy {
224                                                for bytes in leftover.split(|b| *b == b'\n') {
225                                                    if lines.is_expired(&guard) {
226                                                        return true;
227                                                    }
228                                                    let line =
229                                                        String::from_utf8_lossy(bytes).into_owned();
230                                                    guard.push(Line::from(line));
231                                                }
232                                            } else {
233                                                error!("Error displaying {cmd}: {:?}", e);
234                                                return false;
235                                            }
236                                        }
237                                    }
238                                }
239
240                                true
241                            });
242                            self.current = Some((child, handle))
243                        } else {
244                            error!("Failed to get stdout of preview command: {cmd}")
245                        }
246                    }
247                }
248                PreviewMessage::Stop => {}
249                _ => unreachable!(),
250            }
251
252            self.prune_procs();
253        }
254
255        let ret = self.cleanup_procs();
256        if ret.is_empty() { Ok(()) } else { Err(ret) }
257    }
258
259    fn dispatch_kill(&mut self) {
260        if let Some((mut child, old)) = self.current.take() {
261            let _ = child.kill();
262            self.procs.push(child);
263            let mut old = Box::pin(old); // pin it to heap
264
265            match old.as_mut().now_or_never() {
266                Some(Ok(result)) => {
267                    if !result {
268                        self.send(Event::Refresh)
269                    }
270                }
271                None => {
272                    old.abort(); // still works because `AbortHandle` is separate
273                }
274                _ => {}
275            }
276        }
277    }
278
279    fn send(&self, event: Event) {
280        if let Some(ref tx) = self.event_controller_tx {
281            let _ = tx.send(event);
282        }
283    }
284
285    pub fn connect_controller(&mut self, event_controller_tx: EventSender) {
286        self.event_controller_tx = Some(event_controller_tx)
287    }
288
289    // todo: This would be cleaner with tokio::Child, but does that merit a conversion? I'm not sure if its worth it for the previewer to yield control while waiting for output cuz we are multithreaded anyways
290    // also, maybe don't want this delaying exit?
291    fn cleanup_procs(mut self) -> Vec<Child> {
292        let total_timeout = Duration::from_secs(1);
293        let start = Instant::now();
294
295        self.procs.retain_mut(|child| {
296            loop {
297                match child.try_wait() {
298                    Ok(Some(_)) => return false,
299                    Ok(None) => {
300                        if start.elapsed() >= total_timeout {
301                            error!("Child failed to exit in time: {:?}", child);
302                            return true;
303                        } else {
304                            thread::sleep(Duration::from_millis(10));
305                        }
306                    }
307                    Err(e) => {
308                        error!("Error waiting on child: {e}");
309                        return true;
310                    }
311                }
312            }
313        });
314
315        self.procs
316    }
317
318    fn prune_procs(&mut self) {
319        self.procs.retain_mut(|child| match child.try_wait() {
320            Ok(None) => true,
321            Ok(Some(_)) => false,
322            Err(e) => {
323                warn!("Error waiting on child: {e}");
324                true
325            }
326        });
327    }
328}
329
330// ---------- NON ANSI VARIANT
331// let reader = BufReader::new(stdout);
332// if self.config.try_lossy {
333// for line_result in reader.split(b'\n') {
334//     match line_result {
335//         Ok(bytes) => {
336//             let line =
337//             String::from_utf8_lossy(&bytes).into_owned();
338//             lines.push(Line::from(line));
339//         }
340//         Err(e) => error!("Failed to read line: {:?}", e),
341//     }
342// }
343// } else {
344//     for line_result in reader.lines() {
345//         match line_result {
346//             Ok(line) => lines.push(Line::from(line)),
347//             Err(e) => {
348//                 // todo: don't know why that even with an explicit ratatui clear, garbage sometimes stays on the screen
349//                 error!("Error displaying {cmd}: {:?}", e);
350//                 break;
351//             }
352//         }
353//     }
354// }
355
356// trait Resettable: Default {
357//     fn reset(&mut self) {}
358// }
359// impl<T> Resettable for AppendOnly<T> {
360//     fn reset(&mut self) {
361//         self.clear();
362//     }
363// }
364
365// use std::ops::{Deref, DerefMut};
366
367// #[derive(Debug)]
368// struct Queue<V: Resettable> {
369//     entries: Vec<(String, V)>,
370//     order: Vec<usize>, // indices ordered by recency (0 = most recent)
371// }
372
373// impl<V: Resettable> Queue<V> {
374//     pub fn new(len: usize) -> Self {
375//         Self {
376//             entries: (0..len)
377//             .map(|_| (String::default(), V::default()))
378//             .collect(),
379//             order: vec![len; len],
380//         }
381//     }
382
383//     fn find_key_pos(&self, key: &str) -> Option<(usize, usize)> {
384//         for (order_idx, &entries_idx) in self.order.iter().enumerate() {
385//             if order_idx == self.entries.len() {
386//                 return None
387//             }
388//             if self.entries[entries_idx].0 == key {
389//                 return Some((order_idx, entries_idx));
390//             }
391//         }
392//         None
393//     }
394
395//     /// Try to get a key; if found, move it to the top.
396//     /// If not found, replace the oldest, clear its vec, set new key.
397//     pub fn try_get(&mut self, key: &str) -> bool {
398//         let n = self.entries.len();
399
400//         if !key.is_empty() && let Some((order_idx, idx)) = self.find_key_pos(key) {
401//             self.order.copy_within(0..order_idx, 1);
402//             self.order[0] = idx;
403//             true
404//         } else {
405//             let order_idx = (0..n)
406//             .rfind(|&i| self.order[i] < n)
407//             .map(|i| i + 1)
408//             .unwrap_or(0);
409
410//             let idx = if self.order[order_idx] < self.entries.len() {
411//                 order_idx
412//             } else {
413//                 *self.order.last().unwrap()
414//             };
415
416//             // shift and insert at front
417//             self.order.copy_within(0..order_idx, 1);
418//             self.order[0] = idx;
419
420//             // reset and assign new key
421//             let (ref mut k, ref mut v) = self.entries[idx];
422//             *k = key.to_owned();
423//             v.reset();
424
425//             false
426//         }
427//     }
428// }
429
430// impl<V: Resettable> Deref for Queue<V> {
431//     type Target = V;
432//     fn deref(&self) -> &Self::Target {
433//         &self.entries[self.order[0]].1
434//     }
435// }
436
437// impl<V: Resettable> DerefMut for Queue<V> {
438//     fn deref_mut(&mut self) -> &mut Self::Target {
439//         &mut self.entries[self.order[0]].1
440//     }
441// }
442
443// impl<V: Resettable> Default for Queue<V> {
444//     fn default() -> Self {
445//         Self::new(1)
446//     }
447// }