cnf 0.6.1

Distribution-agnostic 'command not found'-handler
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: (C) 2023 Andreas Hartmann <hartan@7x.de>
// This file is part of cnf, available at <https://gitlab.com/hartang/rust/cnf>

//! # Custom tree widget for [`ratatui`]
use std::{cell::RefCell, error::Error, rc::Rc, sync::Arc};

use ratatui::{
    style::{Color, Modifier, Style},
    text::{Span, Spans},
};

use cnf_lib::prelude::*;

/// When scrolling the treeview up/down, how many lines to leave until the border above/below
/// respectively. If there isn't enough space, the "scroll border" can be reduced to 0, too.
const DEFAULT_SCROLL_BORDER: usize = 2;

/// Common trait for displaying TUI tree elements
trait UiTreeNode<'a> {
    /// Value to display for collapsed tree node.
    ///
    /// A single [`Spans`] is represents a single line of output. Multiline output is represented
    /// by a vector with multiple spans inside it.
    fn value_collapsed(&self) -> Vec<Spans<'a>>;

    /// Value to display for expanded tree node.
    ///
    /// Defaults to `value_collapsed` if unspecified. See [`UiTreeNode::value_collapsed()`] for
    /// additional documentation.
    fn value_expanded(&self) -> Vec<Spans<'a>> {
        self.value_collapsed()
    }

    /// Get the unique ID of this tree node.
    fn get_id(&self) -> u64;

    /// Get the IDs of all visible children of this tree node.
    ///
    /// If the node is collapsed, returns a vector with only the nodes ID.
    fn enumerate(&self) -> Vec<u64>;

    /// Collapse the node with the given index.
    fn collapse(&mut self, id: u64);

    /// Exnapd the node with the given index.
    fn expand(&mut self, id: u64);

    /// Get the candidate with the given ID, if any.
    fn get_candidate(&self, id: u64) -> Option<(Rc<Query>, usize)>;
}

/// TUI tree node information structure
#[derive(Debug)]
struct NodeInfo {
    /// True of this node is currently expanded, false otherwise
    expanded: bool,
    /// Tree-unique ID of this node
    id: u64,
}

/// Represents a candidate of a Query in the TUI tree.
#[derive(Debug)]
struct CandidateNode {
    /// Query Result and index, to retrieve results on request
    value: (Rc<Query>, usize),
    /// Node metadata
    info: NodeInfo,
}

impl<'a> UiTreeNode<'a> for CandidateNode {
    fn value_collapsed(&self) -> Vec<Spans<'a>> {
        let query = self.value.0.clone();
        let index = self.value.1;
        let value = query.results.as_ref().unwrap().get(index).unwrap();

        let needs_install = if value.actions.install.is_some() {
            "needs install"
        } else {
            "installed"
        };
        vec![
            if value.version.is_empty() {
                Span::raw(format!("    + {}, {}", value.package, needs_install))
            } else {
                Span::raw(format!(
                    "    + {} @ {}, {}",
                    value.package, value.version, needs_install
                ))
            }
            .into(),
        ]
    }

    fn value_expanded(&self) -> Vec<Spans<'a>> {
        macro_rules! write_format {
            ($string:expr, $var:expr) => {
                Span::raw(format!(
                    "        {:<14}: {}\n",
                    $string,
                    if $var.is_empty() { "n/a" } else { $var }
                ))
            };
        }

        let query = self.value.0.clone();
        let index = self.value.1;
        let value = query.results.as_ref().unwrap().get(index).unwrap();

        vec![
            Spans::from(vec![
                Span::raw("    - "),
                Span::styled(
                    format!("Package: {}\n", &value.package),
                    Style::default().add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
                ),
            ]),
            write_format!("Description", &value.description).into(),
            write_format!("Version", &value.version).into(),
            write_format!("Origin", &value.origin).into(),
            write_format!(
                "Needs install",
                if value.actions.install.is_some() {
                    "yes"
                } else {
                    "no"
                }
            )
            .into(),
        ]
    }

    fn get_id(&self) -> u64 {
        self.info.id
    }

    fn enumerate(&self) -> Vec<u64> {
        vec![self.info.id]
    }

    fn collapse(&mut self, id: u64) {
        if id == self.info.id {
            self.info.expanded = false;
        }
    }

    fn expand(&mut self, id: u64) {
        if id == self.info.id {
            self.info.expanded = true;
        }
    }

    fn get_candidate(&self, id: u64) -> Option<(Rc<Query>, usize)> {
        if id == self.info.id {
            Some((self.value.0.clone(), self.value.1))
        } else {
            None
        }
    }
}

/// Represents a provider in the TUI tree.
#[derive(Debug)]
struct ProviderNode {
    /// Provider this node represents
    value: Rc<Query>,
    /// Child values (candidates) of this node (provider)
    children: Vec<CandidateNode>,
    /// Node metadata
    info: NodeInfo,
}

impl<'a> UiTreeNode<'a> for ProviderNode {
    fn value_collapsed(&self) -> Vec<Spans<'a>> {
        let provider = &self.value.provider;
        let mut span_vec = match &self.value.results {
            Ok(results) => vec![
                Span::raw("["),
                Span::styled("✔", Style::default().fg(Color::Green)),
                Span::raw(format!("] {} - {} results found", provider, results.len())),
            ],
            Err(error) => {
                if matches!(error, ProviderError::Requirements(_)) {
                    vec![
                        Span::raw("["),
                        Span::styled("-", Style::default().add_modifier(Modifier::DIM)),
                        Span::raw("] "),
                        Span::raw(format!("{} - {}", provider, error)),
                    ]
                } else {
                    vec![
                        Span::raw("["),
                        Span::styled("✘", Style::default().fg(Color::Red)),
                        Span::raw(format!("] {} - {}", provider, error)),
                    ]
                }
            }
        };
        let mut spans = vec![Span::raw("  + ")];
        spans.append(&mut span_vec);
        vec![Spans::from(spans)]
    }

    fn value_expanded(&self) -> Vec<Spans<'a>> {
        let provider = &self.value.provider;
        let span_prefix = Span::raw("  - [");
        match &self.value.results {
            Ok(results) => vec![Spans::from(vec![
                span_prefix,
                Span::styled("✔", Style::default().fg(Color::Green)),
                Span::raw(format!("] {} - {} results found", provider, results.len())),
            ])],
            Err(error) => {
                if matches!(error, ProviderError::Requirements(_)) {
                    vec![Spans::from(vec![
                        span_prefix,
                        Span::styled("-", Style::default().add_modifier(Modifier::DIM)),
                        Span::raw("] "),
                        Span::raw(format!("{} - {}", provider, error)),
                    ])]
                } else {
                    let mut output = vec![Spans::from(vec![
                        span_prefix,
                        Span::styled("✘", Style::default().fg(Color::Red)),
                        Span::raw(format!("] {} - {}", provider, error)),
                    ])];

                    let mut source_err: Option<&(dyn Error + 'static)> = error.source();
                    while let Some(error) = source_err {
                        let line = Spans::from(vec![
                            Span::styled("     '->", Style::default().fg(Color::Red)),
                            Span::styled(
                                " caused by: ",
                                Style::default().add_modifier(Modifier::ITALIC),
                            ),
                            Span::raw(error.to_string()),
                        ]);
                        output.push(line);

                        source_err = error.source();
                    }

                    output
                }
            }
        }
    }

    fn get_id(&self) -> u64 {
        self.info.id
    }

    fn enumerate(&self) -> Vec<u64> {
        let mut ret = vec![self.info.id];
        if self.info.expanded {
            let mut ids = self
                .children
                .iter()
                .flat_map(|child| child.enumerate())
                .collect::<Vec<u64>>();
            ret.append(&mut ids);
        }
        ret
    }

    fn collapse(&mut self, id: u64) {
        if id == self.info.id {
            self.info.expanded = false;
        } else {
            self.children
                .iter_mut()
                .for_each(|child| child.collapse(id));
        }
    }

    fn expand(&mut self, id: u64) {
        if id == self.info.id {
            self.info.expanded = true;
        } else {
            self.children.iter_mut().for_each(|child| child.expand(id));
        }
    }

    fn get_candidate(&self, id: u64) -> Option<(Rc<Query>, usize)> {
        if (id == self.info.id) && (self.children.len() == 1) {
            // Shortcut: If we have only a single result, provide that directly
            self.children
                .first()
                .and_then(|child| child.get_candidate(child.get_id()))
        } else {
            let mut candidates = self
                .children
                .iter()
                .filter_map(|child| child.get_candidate(id))
                .collect::<Vec<_>>();
            candidates.pop()
        }
    }
}

/// Represents an environment in the TUI tree.
#[derive(Debug)]
struct EnvNode {
    /// The environment represented by this node
    value: Arc<Environment>,
    /// The providers/results found in this environment
    children: RefCell<Vec<ProviderNode>>,
    /// Node metadata
    info: NodeInfo,
}

impl<'a> UiTreeNode<'a> for EnvNode {
    fn value_collapsed(&self) -> Vec<Spans<'a>> {
        vec![Spans::from(vec![
            Span::raw("+ "),
            Span::raw(format!("In {}", self.value)),
        ])]
    }

    fn value_expanded(&self) -> Vec<Spans<'a>> {
        vec![Spans::from(vec![
            Span::raw("- "),
            Span::raw(format!("In {}", self.value)),
        ])]
    }

    fn get_id(&self) -> u64 {
        self.info.id
    }

    fn enumerate(&self) -> Vec<u64> {
        let mut ret = vec![self.info.id];
        if self.info.expanded {
            let mut ids = self
                .children
                .borrow()
                .iter()
                .flat_map(|child| child.enumerate())
                .collect::<Vec<u64>>();
            ret.append(&mut ids);
        }
        ret
    }

    fn collapse(&mut self, id: u64) {
        if id == self.info.id {
            self.info.expanded = false;
        } else {
            self.children
                .borrow_mut()
                .iter_mut()
                .for_each(|child| child.collapse(id));
        }
    }

    fn expand(&mut self, id: u64) {
        if id == self.info.id {
            self.info.expanded = true;
        } else {
            self.children
                .borrow_mut()
                .iter_mut()
                .for_each(|child| child.expand(id));
        }
    }

    fn get_candidate(&self, id: u64) -> Option<(Rc<Query>, usize)> {
        let mut candidates = self
            .children
            .borrow()
            .iter()
            .filter_map(|child| child.get_candidate(id))
            .collect::<Vec<_>>();
        candidates.pop()
    }
}

/// TUI tree root element.
#[derive(Debug, Default)]
pub(crate) struct UiTree {
    /// ID to assign to the next added tree node
    next_id: RefCell<u64>,
    /// Children of this tree
    children: Vec<EnvNode>,
    /// State information for the UI
    ui: UiState,
}

#[derive(Debug, Default)]
struct UiState {
    select_id: u64,
    last_viewport_scroll: usize,
}

impl UiTree {
    /// Recursively convert all visible children into [`Spans`].
    pub(crate) fn to_spans<'a>(&self) -> Vec<Vec<Spans<'a>>> {
        let mut spans = vec![];
        for env_node in &self.children {
            if env_node.info.expanded {
                spans.push(env_node.value_expanded());
                for provider_node in &*env_node.children.borrow() {
                    if provider_node.info.expanded {
                        spans.push(provider_node.value_expanded());
                        for query_node in &provider_node.children {
                            if query_node.info.expanded {
                                spans.push(query_node.value_expanded());
                            } else {
                                spans.push(query_node.value_collapsed());
                            }
                        }
                    } else {
                        spans.push(provider_node.value_collapsed());
                    }
                }
            } else {
                spans.push(env_node.value_collapsed());
            }
        }
        spans
    }

    /// Create an empty UI tree.
    pub(crate) fn new() -> Self {
        Default::default()
    }

    /// Collect the IDs of all visible nodes, in display order (top to bottom).
    pub(crate) fn enumerate(&self) -> Vec<u64> {
        self.children
            .iter()
            .flat_map(|child| child.enumerate())
            .collect::<Vec<_>>()
    }

    /// Advance selection to next visible entry.
    pub(crate) fn selection_plus(&mut self) {
        let ids = self.enumerate();
        let next = ids
            .iter()
            .skip_while(|id| **id != self.ui.select_id)
            .nth(1)
            .unwrap_or(&self.ui.select_id);
        self.ui.select_id = *next;
    }

    /// Advance selection to previous visible entry.
    pub(crate) fn selection_minus(&mut self) {
        let ids = self.enumerate();
        let mut last_id = ids.first().copied();
        for id in self.enumerate() {
            if id == self.ui.select_id {
                break;
            } else {
                last_id = Some(id);
            }
        }
        if let Some(id) = last_id {
            self.ui.select_id = id;
        }
    }

    /// Collapse the selected nodes UI representation.
    pub(crate) fn collapse_node(&mut self) {
        self.children
            .iter_mut()
            .for_each(|child| child.collapse(self.ui.select_id));
    }

    /// Expand the selected nodes UI representation.
    pub(crate) fn expand_node(&mut self) {
        self.children
            .iter_mut()
            .for_each(|child| child.expand(self.ui.select_id));
    }

    /// Create new [`NodeInfo`] struct with increase node ID.
    fn next_node_info(&self) -> NodeInfo {
        let id = self.next_id.replace_with(|&mut old| old + 1);
        NodeInfo {
            expanded: false,
            id,
        }
    }

    /// Add new env if it doesn't exist yet.
    pub(crate) fn add_env(&mut self, env: Arc<Environment>) {
        if !self.children.iter().any(|child| child.value == env) {
            let mut node = EnvNode {
                value: env,
                children: RefCell::new(vec![]),
                info: self.next_node_info(),
            };
            // environments are expanded by default
            node.info.expanded = true;
            self.children.push(node);
        }
    }

    /// Add new query to UI.
    pub(crate) fn add_query(&mut self, query: Rc<Query>) {
        if let Some(node) = self
            .children
            .iter()
            .find(|child_env| child_env.value == query.env)
        {
            let mut provider_node = ProviderNode {
                value: query.clone(),
                children: vec![],
                info: self.next_node_info(),
            };
            let candidate_nodes = match &query.results {
                Err(_) => vec![],
                Ok(results) => results
                    .iter()
                    .enumerate()
                    .map(|(index, _)| CandidateNode {
                        value: (query.clone(), index),
                        info: self.next_node_info(),
                    })
                    .collect::<Vec<_>>(),
            };
            provider_node.children = candidate_nodes;
            if provider_node.children.len() == 1 {
                // Auto-expand provider nodes with only a single result
                provider_node.info.expanded = true;
            }

            // Push provider node to parent env node
            let mut child_vec = node.children.borrow_mut();
            let pos = child_vec
                .binary_search_by(|elem| crate::ui::sort_by(&provider_node.value, &elem.value))
                .unwrap_or_else(|e| e);
            child_vec.insert(pos, provider_node);
        } else {
            tracing::warn!(
                "tried to add query '{:?}' to non-existent env '{:?}'",
                query,
                query.env
            );
        }
    }

    pub(crate) fn get_selected_candidate(&self) -> Option<(Rc<Query>, usize)> {
        let mut candidates = self
            .children
            .iter()
            .filter_map(|child| child.get_candidate(self.ui.select_id))
            .collect::<Vec<_>>();
        candidates.pop()
    }
}

/// Render this tree into a widget.
impl ratatui::widgets::Widget for &mut UiTree {
    fn render(self, area: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) {
        let symbol = ">> ";
        let (x, mut y) = (area.left() + symbol.chars().count() as u16, area.top());
        let area_height = area.height as usize;

        // UI tree information
        let tree_spans = self.to_spans();
        let span_ids = tree_spans.iter().zip(self.enumerate());

        let num_lines = tree_spans.iter().flatten().count();
        let skip_at_start = if num_lines <= area_height {
            // All content fits the screen
            0
        } else {
            // Content doesn't fit screen, clip it
            struct SelectionLines {
                pub first_line: usize,
                pub last_line: usize,
                pub height: usize,
            }

            // First get the line numbers of the selection
            let mut lines_so_far = 0;
            let selection_lines = 'escape: {
                for (span_vec, id) in span_ids.clone() {
                    let spans_height = span_vec.len();

                    if id == self.ui.select_id {
                        break 'escape SelectionLines {
                            first_line: lines_so_far,
                            last_line: lines_so_far + spans_height,
                            height: spans_height,
                        };
                    }
                    lines_so_far += spans_height;
                }
                panic!(
                    "current selection {} is not part of the visible tree with IDs '{:?}'",
                    self.ui.select_id,
                    self.enumerate()
                );
            };

            // Defines the scroll borders (i.e. how many lines of space to leave at bottom/top of
            // screen when scrolling). We use the default value, unless the screen height is too
            // small to hold the full selection + twice the scroll border. In this case, we take
            // how many lines are left and divide by 2 (symmetric scroll border up and down).
            let scroll_border = std::cmp::min(
                DEFAULT_SCROLL_BORDER,
                (area_height.saturating_sub(selection_lines.height)) / 2,
            );

            // Calculates how many lines to skip from the beginning of the UI tree
            let to_skip = (selection_lines.last_line + scroll_border).saturating_sub(area_height);
            if area_height <= selection_lines.height {
                // The visible area cannot even hold the whole selection. In this case display the
                // selections first line as top line of the tree area.
                selection_lines.first_line
            } else if to_skip > self.ui.last_viewport_scroll {
                // Scrolling down, this ensures that we use all lines of the screen when scrolled
                // to the bottom
                std::cmp::min(to_skip, num_lines - area_height)
            } else {
                // Check if we can keep the viewport from the last iteration.
                let to_skip = self.ui.last_viewport_scroll;
                let selection_start = selection_lines.first_line.saturating_sub(scroll_border);
                if selection_start < to_skip {
                    // Scrolling up, first line of selection must always be visible
                    selection_start
                } else {
                    // Don't scroll
                    to_skip
                }
            }
        };

        // Keep track of how many lines of the tree we have seen so far (printed and unprinted)
        let mut lines_seen = 0;
        for (span_vec, id) in span_ids {
            if id == self.ui.select_id {
                buf.set_string(0, y, symbol, Style::default());
            }

            for inner_span in span_vec {
                if (lines_seen >= skip_at_start) && (y <= area.height) {
                    buf.set_spans(x, y, inner_span, area.width - 10);
                    y += 1;
                }
                lines_seen += 1;
            }
        }

        // Store current scroll state for next iteration
        self.ui.last_viewport_scroll = skip_at_start;
    }
}