rura 1.6.0

Interactive TUI pipeline editor built for rapid iteration
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
use crate::config::ThemeConfig;
use crate::content_widget::{ContentLine, ContentWidget, Position};
use crate::shell::cmd_runner::CmdResult;
use crate::shell::output::Output;
use crate::theme::Theme;
use itertools::Itertools;
use log::debug;
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Direction, Layout, Rect, Size};
use ratatui::prelude::Color::Red;
use ratatui::prelude::{Style, Widget};
use ratatui::widgets::{Block, Paragraph};
use similar::TextDiff;
use similar::{Algorithm, ChangeTag};
use std::cell::Cell;
use std::sync::Arc;
use std::time::Duration;

pub struct OutputWidget {
    content: ContentWidget<String>,
    diff: ContentWidget<(ChangeTag, String)>,
    error_output_opt: Option<(Vec<String>, Option<i32>)>,
    theme: Theme,
    error_pane_placement: ErrorPanePlacement,
    cmd_result: CmdResult,
    pub content_mode: ContentMode,
    diff_base: Option<usize>,
    diff_ready: bool,
}

impl ContentLine for String {
    fn string(&self) -> String {
        self.into()
    }

    fn style(&self, _theme: &Theme) -> Style {
        Style::default()
    }
}

impl ContentLine for (ChangeTag, String) {
    fn string(&self) -> String {
        self.clone().1
    }

    fn style(&self, theme: &Theme) -> Style {
        match self.0 {
            ChangeTag::Equal => theme.diff_equal,
            ChangeTag::Insert => theme.diff_addition,
            ChangeTag::Delete => theme.diff_deletion,
        }
    }
}

impl OutputWidget {
    pub fn new(theme_config: &ThemeConfig, error_pane_placement: ErrorPanePlacement) -> Self {
        Self {
            content: ContentWidget {
                offset: Position::default(),
                lines: vec![],
                wrap: false,
                highlight_positions: vec![],
                highlight_index: 0,
                theme: Theme::from_config(theme_config),
                output_content_area_size: Cell::new(Size::default()),
            },
            diff: ContentWidget {
                offset: Position::default(),
                lines: vec![],
                wrap: false,
                highlight_positions: vec![],
                highlight_index: 0,
                theme: Theme::from_config(theme_config),
                output_content_area_size: Cell::new(Size::default()),
            },
            error_output_opt: None,
            theme: Theme::from_config(theme_config),
            error_pane_placement,
            cmd_result: CmdResult {
                stdin: Arc::from("".as_bytes()),
                outputs: vec![],
            },
            content_mode: ContentMode::Normal,
            diff_base: None,
            diff_ready: false,
        }
    }

    pub fn toggle_diff(&mut self) {
        match self.content_mode {
            ContentMode::Normal => {
                self.content_mode = ContentMode::Diff;
                self.diff()
            }
            ContentMode::Diff => self.content_mode = ContentMode::Normal,
        }
    }

    pub fn diff_base(&self) -> Option<usize> {
        self.diff_base
    }

    pub fn diff(&mut self) {
        let now = std::time::Instant::now();
        if self.diff_ready {
            return;
        }
        let ok_bytes = self.cmd_result.ok_bytes();
        let last_bytes = ok_bytes.last().unwrap_or(&self.cmd_result.stdin);
        let stdin_bytes = if let Some(base) = self.diff_base {
            if let Some(b) = self.cmd_result.outputs.get(base) {
                if let Output::Ok(b) = b {
                    b.as_ref()
                } else {
                    return;
                }
            } else {
                return;
            }
        } else {
            self.cmd_result.stdin.as_ref()
        };

        let old = String::from_utf8_lossy(&stdin_bytes);
        let new = String::from_utf8_lossy(&last_bytes);

        let text_diff: TextDiff<str> = TextDiff::configure()
            .algorithm(Algorithm::Patience)
            .timeout(Duration::from_millis(5000))
            .diff_lines(&old, &new);

        debug!("Diff took {}ms", now.elapsed().as_millis());

        let old_lines = old.lines().collect_vec();
        let new_lines = new.lines().collect_vec();

        let lines: Vec<(ChangeTag, String)> = text_diff
            .ops()
            .into_iter()
            .flat_map(|op| {
                op.iter_slices(&old_lines, &new_lines)
                    .flat_map(|(tag, slice)| slice.iter().map(move |&s| (tag, s.to_string())))
            })
            .collect_vec();

        self.diff_ready = true;
        self.diff.with_content(lines);
    }

    pub fn highlight_info(&self) -> (usize, usize) {
        match self.content_mode {
            ContentMode::Normal => self.content.highlight_info(),
            ContentMode::Diff => self.diff.highlight_info(),
        }
    }

    pub fn set_diff_base(&mut self, base: Option<usize>) {
        self.diff_base = base;
        self.content_mode = ContentMode::Diff;
        self.diff_ready = false;
        self.diff();
    }

    pub fn clear_highlight(&mut self) {
        match self.content_mode {
            ContentMode::Normal => self.content.clear_highlight(),
            ContentMode::Diff => self.diff.clear_highlight(),
        }
    }

    pub fn highlight_next(&mut self) {
        match self.content_mode {
            ContentMode::Normal => self.content.highlight_next(),
            ContentMode::Diff => self.diff.highlight_next(),
        }
    }

    pub fn highlight_prev(&mut self) {
        match self.content_mode {
            ContentMode::Normal => self.content.highlight_prev(),
            ContentMode::Diff => self.diff.highlight_prev(),
        }
    }

    pub fn highlight(&mut self, search_str: &str, case_sensitive: bool, regex: bool) {
        match self.content_mode {
            ContentMode::Normal => self.content.highlight(search_str, case_sensitive, regex),
            ContentMode::Diff => self.diff.highlight(search_str, case_sensitive, regex),
        }
    }

    pub fn output_len(&self) -> usize {
        match self.content_mode {
            ContentMode::Normal => self.content.output_len(),
            ContentMode::Diff => self.diff.output_len(),
        }
    }

    pub fn handle_command_result(&mut self, result: CmdResult) {
        self.cmd_result = result;

        debug!("handle_command_result: {:?}", self.cmd_result.outputs.len());

        match self.cmd_result.outputs.last() {
            Some(Output::Ok(bytes)) => {
                let str = String::from_utf8_lossy(&bytes);
                let lines = str.lines().map(|a| a.into()).collect_vec();
                self.content.with_content(lines);

                self.error_output_opt = None;
            }
            Some(Output::Err(bytes, code)) => {
                let str = String::from_utf8_lossy(&bytes);
                let lines = str.lines().map(|a| a.into()).collect_vec();

                self.error_output_opt = Some((lines, *code));
            }
            None => {
                let str = String::from_utf8_lossy(&self.cmd_result.stdin);
                let lines = str.lines().map(|a| a.into()).collect_vec();
                self.content.with_content(lines);

                self.error_output_opt = None;
            }
        }
        self.diff_ready = false;

        match self.content_mode {
            ContentMode::Normal => {}
            ContentMode::Diff => self.diff(),
        }

        self.clear_highlight();
    }

    pub fn scroll_down(&mut self) {
        match self.content_mode {
            ContentMode::Normal => self.content.scroll_down(),
            ContentMode::Diff => self.diff.scroll_down(),
        }
    }

    pub fn scroll_page_down(&mut self) {
        match self.content_mode {
            ContentMode::Normal => self.content.scroll_page_down(),
            ContentMode::Diff => self.diff.scroll_page_down(),
        }
    }

    pub fn scroll_up(&mut self) {
        match self.content_mode {
            ContentMode::Normal => self.content.scroll_up(),
            ContentMode::Diff => self.diff.scroll_up(),
        }
    }

    pub fn scroll_page_up(&mut self) {
        match self.content_mode {
            ContentMode::Normal => self.content.scroll_page_up(),
            ContentMode::Diff => self.diff.scroll_page_up(),
        }
    }

    pub fn scroll_left(&mut self) {
        match self.content_mode {
            ContentMode::Normal => self.content.scroll_left(),
            ContentMode::Diff => self.diff.scroll_left(),
        }
    }

    pub fn scroll_page_left(&mut self) {
        match self.content_mode {
            ContentMode::Normal => self.content.scroll_page_left(),
            ContentMode::Diff => self.diff.scroll_page_left(),
        }
    }

    pub fn scroll_right(&mut self) {
        match self.content_mode {
            ContentMode::Normal => self.content.scroll_right(),
            ContentMode::Diff => self.diff.scroll_right(),
        }
    }

    pub fn scroll_page_right(&mut self) {
        match self.content_mode {
            ContentMode::Normal => self.content.scroll_page_right(),
            ContentMode::Diff => self.diff.scroll_page_right(),
        }
    }

    pub fn toggle_wrap(&mut self) {
        match self.content_mode {
            ContentMode::Normal => self.content.wrap = !self.content.wrap,
            ContentMode::Diff => self.diff.wrap = !self.diff.wrap,
        }
    }

    pub fn layout(&self, area: Rect) -> [Rect; 2] {
        let error_output_lines = self
            .error_output_opt
            .as_ref()
            .map(|e| e.0.len() + 2)
            .unwrap_or(0);

        let (output_area, errors_area) = match self.error_pane_placement {
            ErrorPanePlacement::Top => {
                let layout = Layout::default()
                    .direction(Direction::Vertical)
                    .constraints(vec![
                        Constraint::Length(error_output_lines.min(10) as u16),
                        Constraint::Fill(1),
                    ])
                    .split(area);

                (layout[1], layout[0])
            }
            ErrorPanePlacement::Bottom => {
                let layout = Layout::default()
                    .direction(Direction::Vertical)
                    .constraints(vec![
                        Constraint::Fill(1),
                        Constraint::Length(error_output_lines.min(10) as u16),
                    ])
                    .split(area);

                (layout[0], layout[1])
            }
        };

        [output_area, errors_area]
    }
}

impl Widget for &OutputWidget {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let _theme = &self.theme;

        let [output_content_area, errors_area] = self.layout(area);

        if let Some(err_output) = &self.error_output_opt {
            let block = Block::bordered()
                .title(format!(" Error: {} ", err_output.1.unwrap_or(0)))
                .border_style(Style::default().fg(Red));
            let err_output_par = Paragraph::new(err_output.0.join("\n")).block(block);

            err_output_par.render(errors_area, buf);
        }

        match self.content_mode {
            ContentMode::Normal => self.content.render(output_content_area, buf),
            ContentMode::Diff => self.diff.render(output_content_area, buf),
        }
    }
}

pub enum ContentMode {
    Normal,
    Diff,
}

pub enum ErrorPanePlacement {
    Top,
    Bottom,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::shell::output::Output;
    use insta::assert_snapshot;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;
    use std::sync::Arc;

    struct TestTerminal(Terminal<TestBackend>);

    impl Default for TestTerminal {
        fn default() -> Self {
            TestTerminal(Terminal::new(TestBackend::new(100, 30)).unwrap())
        }
    }

    impl Default for OutputWidget {
        fn default() -> Self {
            let theme_config = ThemeConfig::default();

            OutputWidget::new(&theme_config, ErrorPanePlacement::Top)
        }
    }

    fn result(output: Output) -> CmdResult {
        CmdResult {
            stdin: Arc::from("".as_bytes()),
            outputs: vec![output],
        }
    }

    #[test]
    fn errors_pane_top() {
        let mut terminal = TestTerminal::default().0;

        let mut widget = OutputWidget::default();
        widget.error_pane_placement = ErrorPanePlacement::Top;

        widget.handle_command_result(result(Output::ok_str("out1\nout2\nout3")));
        widget.handle_command_result(result(Output::err_str("errors1\nerrors2\nerrors3")));

        terminal
            .draw(|frame| widget.render(frame.area(), frame.buffer_mut()))
            .unwrap();

        assert_snapshot!(terminal.backend());
    }

    #[test]
    fn errors_pane_bottom() {
        let mut terminal = TestTerminal::default().0;

        let mut widget = OutputWidget::default();
        widget.error_pane_placement = ErrorPanePlacement::Bottom;

        widget.handle_command_result(result(Output::ok_str("out1\nout2\nout3")));
        widget.handle_command_result(result(Output::err_str("errors1\nerrors2\nerrors3")));

        terminal
            .draw(|frame| widget.render(frame.area(), frame.buffer_mut()))
            .unwrap();

        assert_snapshot!(terminal.backend());
    }

    #[test]
    fn highlighting_in_diff_mode() {
        let mut widget = OutputWidget::default();
        let stdin = Arc::from("line1\nline2\nline3".as_bytes());
        let output = Output::ok_str("line1\nline2 modified\nline3");
        widget.handle_command_result(CmdResult {
            stdin,
            outputs: vec![output],
        });

        widget.toggle_diff(); // Switch to diff mode
        assert!(matches!(widget.content_mode, ContentMode::Diff));

        widget.highlight("modified", false, false);
        let info = widget.highlight_info();
        assert_eq!(info.1, 1); // 1 match found

        // Test output_len
        assert_eq!(widget.output_len(), 4);

        // Test clear_highlight
        widget.clear_highlight();
        assert_eq!(widget.highlight_info().1, 0);
    }
}