Skip to main content

data_beans/interactive/
qc_tui.rs

1//! `data-beans qc`'s full-screen view: the cell QC rules in a table, each
2//! with its edge, how many cells it fails and how many it alone removes;
3//! the selected rule's histogram in three layers (every cell, the cells
4//! passing the other rules, the cells only it removes); total counts
5//! against detected genes; and the removed cells by the rules they fail.
6//!
7//! The view moves a [`CellRules`], so every count is `qc_lib`'s own
8//! decision and `p` shows `qc` flags that decide the same cells. Where the
9//! terminal has an image protocol the plots are the figure's own panels
10//! ([`crate::figure::qc::panel`]); `s` saves the whole figure as PDF and
11//! PNG.
12
13use ratatui::buffer::Buffer;
14use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
15use ratatui::layout::{Constraint, Layout, Rect};
16use ratatui::style::{Color, Style};
17use ratatui::text::{Line, Span};
18use ratatui::widgets::{Paragraph, Wrap};
19use ratatui::Frame;
20use ratatui_image::picker::Picker;
21
22use super::ui::{header, help_line, input_line, panel, title_bar, Screen, Tui, LOOK};
23use crate::figure::qc::{edge_text, panel as panel_svg, Panel};
24use crate::figure::term::PlotImage;
25use crate::figure::{free_name, save, taken, Axis};
26use crate::qc_rules::{CellRules, Mode, Rule};
27
28/// What the view ended with.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum Decision {
31    /// Enter: go on with these settings.
32    Apply,
33    /// q, Esc, Ctrl-C or a `kill`: write nothing.
34    Cancel,
35}
36
37enum Typing {
38    /// A value for the selected rule's edge.
39    Edge(String),
40    /// The name to save the figure under.
41    Save(String),
42    /// The output to write the kept cells to.
43    Output(String),
44}
45
46/// The view over `rules`.
47pub struct QcView {
48    rules: CellRules,
49    /// The data's name, for the title and the figure.
50    name: String,
51    /// Where Enter writes the kept cells; asked for when none was given.
52    output: Option<String>,
53    /// The output name offered when one is asked for.
54    suggest: String,
55    focus: usize,
56    typing: Option<Typing>,
57    decision: Option<Decision>,
58    /// A line for the footer until the next key: a save, the flags.
59    note: Option<Line<'static>>,
60    picker: Option<Picker>,
61    picked_at: Option<u64>,
62    images: bool,
63    detecting: bool,
64    plots: [PlotImage; 2],
65    /// How many cells, and genes, the rules keep now.
66    kept: (usize, usize),
67}
68
69/// Colours of the text histogram's layers, back to front.
70const LAYERS: [Color; 3] = [
71    Color::DarkGray,
72    Color::Gray,
73    match LOOK.accent.fg {
74        Some(c) => c,
75        None => Color::Reset,
76    },
77];
78
79impl QcView {
80    /// The view of `rules` for data `name`. Enter writes the kept cells to
81    /// `output`, or, without one, asks where (offering a free name after
82    /// `suggest`, say `pbmc.qc`).
83    pub fn new(rules: CellRules, name: &str, output: Option<String>, suggest: &str) -> Self {
84        Self {
85            kept: kept(&rules),
86            rules,
87            name: name.into(),
88            output,
89            suggest: suggest.into(),
90            focus: 0,
91            typing: None,
92            decision: None,
93            note: None,
94            picker: None,
95            picked_at: None,
96            images: true,
97            detecting: false,
98            plots: Default::default(),
99        }
100    }
101
102    /// Ask the attached terminal for images, as each attach brings one.
103    pub fn detect_images(mut self) -> Self {
104        self.detecting = true;
105        self
106    }
107
108    pub fn rules(&self) -> &CellRules {
109        &self.rules
110    }
111
112    pub fn into_rules(self) -> CellRules {
113        self.rules
114    }
115
116    pub fn decision(&self) -> Option<Decision> {
117        self.decision
118    }
119
120    /// Where the kept cells go, once Enter has settled it.
121    pub fn output(&self) -> Option<&str> {
122        self.output.as_deref()
123    }
124
125    fn rule(&self) -> Rule {
126        self.rules.rules()[self.focus]
127    }
128
129    /// After a key that may have moved a rule or the selection: the
130    /// figures are drawn again and the kept cells and genes counted again.
131    fn changed(&mut self) {
132        for p in &mut self.plots {
133            p.invalidate();
134        }
135        self.kept = kept(&self.rules);
136    }
137
138    /// Ask the terminal attached now for images, once per attach.
139    fn refresh_picker(&mut self) {
140        if !self.detecting {
141            return;
142        }
143        let attach = legume_tui::attaches();
144        if self.picked_at == Some(attach) {
145            return;
146        }
147        self.picked_at = Some(attach);
148        self.picker = legume_tui::current().and_then(crate::figure::term::picker);
149        self.changed();
150    }
151
152    /// Move the selected rule's edge `steps` to the right on its axis.
153    fn nudge(&mut self, steps: i32) {
154        let rule = self.rule();
155        if !self.rules.is_on(rule) {
156            self.rules.set_on(rule, true);
157            self.changed();
158            return;
159        }
160        match self.rules.mode(rule) {
161            Mode::Mad => {
162                // A wider band moves a lower edge left and an upper one right.
163                let sign = if rule.keeps_above() { -1.0 } else { 1.0 };
164                let k = self.rules.config().n_mads + sign * 0.25 * steps as f32;
165                self.rules.set_mads(k);
166            }
167            Mode::Value => {
168                let values = self.rules.values(rule);
169                let axis = Axis::fit(values, rule.count());
170                let edge = self.rules.edge(rule).unwrap_or(axis.lo as f32) as f64;
171                let mut next = axis.at(axis.frac(edge) + steps as f64 / 80.0);
172                if matches!(rule, Rule::Genes | Rule::GeneCells) {
173                    next = next.round();
174                    if next == edge {
175                        next = edge + steps.signum() as f64;
176                    }
177                }
178                self.rules.set_value(rule, next.clamp(0.0, axis.hi) as f32);
179            }
180        }
181        self.changed();
182    }
183
184    fn save_figure(&mut self, name: &str) {
185        let svg = crate::figure::qc::figure(&self.rules, &self.name);
186        self.note = Some(match save(&svg, name) {
187            Ok(paths) => Line::from(Span::styled(
188                format!(" saved {}", paths.join(", ")),
189                LOOK.hint,
190            )),
191            Err(e) => Line::from(Span::styled(format!(" save failed: {e}"), LOOK.highlight())),
192        });
193    }
194
195    /// The flags that decide what the view shows, as shell words; empty for
196    /// the defaults.
197    fn flags_text(&self) -> String {
198        self.rules
199            .flags()
200            .iter()
201            .map(|f| shell_word(f))
202            .collect::<Vec<_>>()
203            .join(" ")
204    }
205
206    fn flags_line(&self) -> Line<'static> {
207        let text = match self.flags_text() {
208            t if t.is_empty() => "the defaults: no flags needed".to_string(),
209            t => t,
210        };
211        Line::from(vec![
212            Span::styled(" flags: ", LOOK.hint),
213            Span::styled(text, LOOK.page),
214        ])
215    }
216
217    fn handle_typing(&mut self, key: KeyEvent) {
218        self.note = None;
219        let Some(typing) = self.typing.as_mut() else {
220            return;
221        };
222        let buf = match typing {
223            Typing::Edge(b) | Typing::Save(b) | Typing::Output(b) => b,
224        };
225        match key.code {
226            KeyCode::Esc => self.typing = None,
227            KeyCode::Backspace => {
228                buf.pop();
229            }
230            KeyCode::Enter => match self.typing.take() {
231                // `inf` and `1e39` parse too, and are no edge on an axis.
232                Some(Typing::Edge(text)) => match text.trim().parse::<f32>() {
233                    Ok(v) if v.is_finite() => {
234                        let rule = self.rule();
235                        self.rules.set_value(rule, v);
236                        self.changed();
237                    }
238                    _ => {
239                        self.note = Some(Line::from(Span::styled(
240                            format!(" not a number: {text}"),
241                            LOOK.highlight(),
242                        )))
243                    }
244                },
245                Some(Typing::Save(name)) if !name.trim().is_empty() => {
246                    let name = name.trim();
247                    if taken(name) {
248                        // Never over a file: the next free name, offered.
249                        self.typing = Some(Typing::Save(free_name(name)));
250                        self.note = Some(Line::from(Span::styled(
251                            format!(" {name} is already there; not replacing it"),
252                            LOOK.highlight(),
253                        )));
254                    } else {
255                        self.save_figure(name)
256                    }
257                }
258                Some(Typing::Output(name)) => {
259                    let name = name.trim();
260                    if name.is_empty() {
261                        self.note = Some(Line::from(Span::styled(
262                            " no output named: Enter again to name one, q to leave",
263                            LOOK.hint,
264                        )));
265                    } else if output_taken(name) {
266                        self.typing = Some(Typing::Output(free_output(name)));
267                        self.note = Some(Line::from(Span::styled(
268                            format!(" {name} is already there; not replacing it"),
269                            LOOK.highlight(),
270                        )));
271                    } else {
272                        self.output = Some(name.to_string());
273                        self.decision = Some(Decision::Apply);
274                    }
275                }
276                _ => {}
277            },
278            KeyCode::Char(c) if buf.len() < 512 => buf.push(c),
279            _ => {}
280        }
281    }
282
283    fn render_rules(&self, frame: &mut Frame, area: Rect) {
284        let block = panel(" cell QC rules ".into(), true, &LOOK);
285        let inner = block.inner(area);
286        frame.render_widget(block, area);
287        let mut lines = vec![Line::from(Span::styled(
288            format!(
289                "  {:<16}{:>22}{:>9}{:>6}",
290                "rule", "edge", "removes", "only"
291            ),
292            LOOK.hint,
293        ))];
294        for (i, &rule) in self.rules.rules().iter().enumerate() {
295            if rule == Rule::GeneCells {
296                lines.push(Line::from(Span::styled("  genes", LOOK.hint)));
297            }
298            let sel = i == self.focus;
299            let on = self.rules.is_on(rule);
300            let c = self.rules.count(rule);
301            let style = if sel {
302                LOOK.highlight()
303            } else if on {
304                LOOK.page
305            } else {
306                LOOK.hint
307            };
308            let num = |n: usize, w: usize| {
309                Span::styled(
310                    format!("{n:>w$}"),
311                    if n > 0 { LOOK.accent } else { LOOK.hint },
312                )
313            };
314            lines.push(Line::from(vec![
315                Span::styled(if sel { "▸ " } else { "  " }, LOOK.highlight()),
316                Span::styled(format!("{:<16}", rule.label()), style),
317                Span::styled(format!("{:>22}", edge_text(&self.rules, rule)), style),
318                num(c.removes, 9),
319                num(c.only, 6),
320            ]));
321        }
322        let v = self.rules.verdicts();
323        let (cells, genes) = (v.train_keep.len(), v.feature_keep.len());
324        let (kept, kept_genes) = self.kept;
325        lines.push(Line::from(""));
326        lines.push(Line::from(vec![
327            Span::raw("  kept "),
328            Span::styled(kept.to_string(), LOOK.highlight()),
329            Span::raw(format!(
330                " / {cells} cells ({:.1}%)",
331                100.0 * kept as f64 / cells.max(1) as f64
332            )),
333        ]));
334        lines.push(Line::from(format!("       {kept_genes} / {genes} genes")));
335        if v.guarded {
336            lines.push(Line::from(Span::styled(
337                "  every cell (or gene) fails: QC keeps them all instead",
338                LOOK.highlight(),
339            )));
340        }
341        // Held to a value, the genes rule is the near-empty floor, which
342        // the other bands are fitted above.
343        if self.rules.mode(Rule::Genes) == Mode::Value && self.rules.is_on(Rule::Genes) {
344            lines.push(Line::from(Span::styled(
345                "  the bands are fitted on the cells above the genes floor",
346                LOOK.hint,
347            )));
348        }
349        lines.push(Line::from(""));
350        lines.push(Line::from(Span::styled(
351            "  removes: fails it on its own; only: no other rule removes",
352            LOOK.hint,
353        )));
354        frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
355    }
356
357    fn render_overlap(&self, frame: &mut Frame, area: Rect) {
358        let block = panel(
359            " removed cells, by the rules they fail ".into(),
360            false,
361            &LOOK,
362        );
363        let inner = block.inner(area);
364        frame.render_widget(block, area);
365        let groups = self.rules.overlap();
366        let most = groups.first().map_or(1, |g| g.1).max(1);
367        let label_w = 26usize;
368        let room = (inner.width as usize).saturating_sub(label_w + 9).max(4);
369        let mut lines = vec![];
370        for (set, n) in groups.iter().take(inner.height as usize) {
371            let name = if set.is_empty() {
372                "(the rules together)".to_string()
373            } else {
374                set.iter()
375                    .map(|r| r.short())
376                    .collect::<Vec<_>>()
377                    .join(" + ")
378            };
379            let eighths = (n * room * 8).div_ceil(most);
380            let bar =
381                "█".repeat(eighths / 8) + ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"][eighths % 8];
382            lines.push(Line::from(vec![
383                Span::raw(format!("  {name:<label_w$}")),
384                Span::raw(format!("{n:>6} ")),
385                Span::styled(bar, LOOK.accent),
386            ]));
387        }
388        if groups.is_empty() {
389            lines.push(Line::from(Span::styled("  no cell is removed", LOOK.hint)));
390        }
391        frame.render_widget(Paragraph::new(lines), inner);
392    }
393
394    fn render_focus(&mut self, frame: &mut Frame, area: Rect) {
395        let rule = self.rule();
396        let title = format!(
397            " {} · {} per bin ",
398            rule.label(),
399            if rule.on_cells() { "cells" } else { "genes" }
400        );
401        let block = panel(title, true, &LOOK);
402        let inner = block.inner(area);
403        frame.render_widget(block, area);
404        if let Some(picker) = self.picker.as_ref().filter(|_| self.images) {
405            let rules = &self.rules;
406            if self.plots[0].render(frame, inner, picker, |w, h| {
407                panel_svg(rules, Panel::Rule(rule), None, w, h)
408            }) {
409                return;
410            }
411        }
412        let [legend, plot] =
413            Layout::vertical([Constraint::Length(1), Constraint::Fill(1)]).areas(inner);
414        let count = self.rules.count(rule);
415        let values = self.rules.values(rule);
416        let mut axis = Axis::fit(values, rule.count());
417        let edge = self.rules.edge(rule);
418        if let Some(e) = edge {
419            axis = axis.including(e as f64);
420        }
421        layered_text(
422            frame.buffer_mut(),
423            plot,
424            values,
425            &axis,
426            &[None, Some(&count.pass_others), Some(&count.only_mask)],
427            edge.map(f64::from),
428        );
429        let pass = count.pass_others.iter().filter(|&&p| p).count();
430        frame.render_widget(
431            Line::from(vec![
432                Span::styled(" █", Style::new().fg(LAYERS[0])),
433                Span::raw(format!(" all {}  ", values.len())),
434                Span::styled("█", Style::new().fg(LAYERS[1])),
435                Span::raw(format!(" pass the other rules {pass}  ")),
436                Span::styled("█", Style::new().fg(LAYERS[2])),
437                Span::raw(format!(" removed only by this {}", count.only)),
438            ]),
439            legend,
440        );
441    }
442
443    fn render_joint(&mut self, frame: &mut Frame, area: Rect) {
444        let block = panel(" total counts × detected genes · log ".into(), false, &LOOK);
445        let inner = block.inner(area);
446        frame.render_widget(block, area);
447        if let Some(picker) = self.picker.as_ref().filter(|_| self.images) {
448            let rules = &self.rules;
449            if self.plots[1].render(frame, inner, picker, |w, h| {
450                panel_svg(rules, Panel::Joint, None, w, h)
451            }) {
452                return;
453            }
454        }
455        braille_scatter(frame.buffer_mut(), inner, &self.rules);
456    }
457}
458
459/// `s` as one shell word.
460pub fn shell_word(s: &str) -> String {
461    if !s.is_empty()
462        && s.chars()
463            .all(|c| c.is_ascii_alphanumeric() || "-_=./,:+".contains(c))
464    {
465        s.to_string()
466    } else {
467        format!("'{}'", s.replace('\'', r"'\''"))
468    }
469}
470
471const EIGHTHS: [&str; 9] = [" ", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
472
473/// A histogram of `values` as text, layers (masks; `None` for all) drawn
474/// back to front in [`LAYERS`], two columns a bin, the y axis in a 6-wide
475/// gutter, x ticks below, and the edge as a dotted rule with ▲.
476fn layered_text(
477    buf: &mut Buffer,
478    area: Rect,
479    values: &[f32],
480    axis: &Axis,
481    layers: &[Option<&[bool]>],
482    edge: Option<f64>,
483) {
484    if area.height < 4 || area.width < 12 {
485        return;
486    }
487    let gutter = 6u16;
488    let (cx, cw) = (area.x + gutter + 1, area.width - gutter - 1);
489    let ph = area.height - 2;
490    let n = (cw / 2).max(1) as usize;
491    let counts: Vec<Vec<usize>> = layers
492        .iter()
493        .map(|m| axis.counts(values, n, |i| m.is_none_or(|m| m[i])))
494        .collect();
495    let top = counts.iter().flatten().copied().max().unwrap_or(0).max(1);
496    let style = |fg: Color, bg: Option<Color>| {
497        let s = Style::reset().fg(fg);
498        match bg {
499            Some(b) => s.bg(b),
500            None => s,
501        }
502    };
503    for b in 0..n {
504        let hs: Vec<usize> = counts
505            .iter()
506            .map(|c| (c[b] * ph as usize * 8).div_ceil(top))
507            .collect();
508        for k in 0..ph as usize {
509            let at = k * 8;
510            let Some(front) = (0..hs.len()).rev().find(|&l| hs[l] > at) else {
511                continue;
512            };
513            let frac = (hs[front] - at).min(8);
514            let back = (0..front)
515                .rev()
516                .find(|&l| hs[l] > at + frac)
517                .map(|l| LAYERS[l]);
518            let y = area.y + ph - 1 - k as u16;
519            for dx in 0..2 {
520                let x = cx + 2 * b as u16 + dx;
521                if x < area.right() {
522                    buf[(x, y)]
523                        .set_symbol(EIGHTHS[frac])
524                        .set_style(style(LAYERS[front], back));
525                }
526            }
527        }
528    }
529    let dim = Style::reset().add_modifier(ratatui::style::Modifier::DIM);
530    for y in area.y..area.y + ph {
531        buf[(area.x + gutter, y)].set_symbol("│").set_style(dim);
532    }
533    buf.set_string(area.x, area.y, format!("{top:>5}"), dim);
534    buf.set_string(area.x, area.y + ph - 1, format!("{:>5}", 0), dim);
535    let axis_y = area.y + ph;
536    buf.set_string(
537        area.x + gutter,
538        axis_y,
539        format!("└{}", "─".repeat(cw as usize)),
540        dim,
541    );
542    for t in axis.ticks() {
543        let label = crate::figure::short(t);
544        let x = cx + (axis.frac(t) * (cw.saturating_sub(1)) as f64).round() as u16;
545        let x = x
546            .saturating_sub(label.len() as u16 / 2)
547            .max(cx)
548            .min(area.right().saturating_sub(label.len() as u16));
549        buf.set_string(x, axis_y + 1, &label, dim);
550    }
551    if let Some(e) = edge {
552        let x = cx + (axis.frac(e).clamp(0.0, 1.0) * (cw.saturating_sub(1)) as f64).round() as u16;
553        for y in area.y..area.y + ph {
554            if buf[(x, y)].symbol() == " " {
555                buf[(x, y)]
556                    .set_symbol("┊")
557                    .set_style(Style::reset().patch(LOOK.accent));
558            }
559        }
560        buf[(x, axis_y)]
561            .set_symbol("▲")
562            .set_style(Style::reset().patch(LOOK.accent));
563    }
564}
565
566/// Total counts against detected genes in braille dots, log on both;
567/// a cell holding any removed cell in the accent, both edges dotted.
568fn braille_scatter(buf: &mut Buffer, area: Rect, rules: &CellRules) {
569    if area.height < 4 || area.width < 16 {
570        return;
571    }
572    let m = rules.metrics();
573    let v = rules.verdicts();
574    let gutter = 6u16;
575    let (sx, sw, sh) = (
576        area.x + gutter + 1,
577        area.width - gutter - 1,
578        area.height - 2,
579    );
580    let mut xa = Axis::fit(&m.total_counts, true);
581    let mut ya = Axis::fit(&m.n_genes, true);
582    let (ce, ge) = (rules.edge(Rule::Counts), rules.edge(Rule::Genes));
583    if let Some(e) = ce {
584        xa = xa.including(e as f64);
585    }
586    if let Some(e) = ge {
587        ya = ya.including(e as f64);
588    }
589    let accent = Style::reset().patch(LOOK.accent);
590    let dim = Style::reset().add_modifier(ratatui::style::Modifier::DIM);
591    // Edges first; dots drawn over them. An edge off the axis (a floor
592    // given as `inf`) is drawn at its end.
593    let within = |f: f64| f.clamp(0.0, 1.0);
594    if let Some(e) = ce {
595        let x = sx + (within(xa.frac(e as f64)) * (sw - 1) as f64).round() as u16;
596        for y in area.y..area.y + sh {
597            buf[(x, y)].set_symbol("┊").set_style(accent);
598        }
599    }
600    if let Some(e) = ge {
601        let y = area.y + sh - 1 - (within(ya.frac(e as f64)) * (sh - 1) as f64).round() as u16;
602        for x in sx..sx + sw {
603            buf[(x, y)].set_symbol("┄").set_style(accent);
604        }
605    }
606    let (w, h) = (sw as usize, sh as usize);
607    let mut dots = vec![(0u8, false); w * h];
608    for c in 0..m.n_genes.len() {
609        let (fx, fy) = (
610            xa.frac(m.total_counts[c] as f64),
611            ya.frac(m.n_genes[c] as f64),
612        );
613        if !(fx.is_finite() && fy.is_finite()) {
614            continue;
615        }
616        let px = ((fx * (2 * w - 1) as f64).round() as usize).min(2 * w - 1);
617        let py = ((fy * (4 * h - 1) as f64).round() as usize).min(4 * h - 1);
618        let (col, row) = (px / 2, h - 1 - py / 4);
619        let bit = [[0x40u8, 0x80], [0x04, 0x20], [0x02, 0x10], [0x01, 0x08]][py % 4][px % 2];
620        let d = &mut dots[row * w + col];
621        d.0 |= bit;
622        d.1 |= !v.emitted(c);
623    }
624    for (k, &(bits, gone)) in dots.iter().enumerate() {
625        if bits == 0 {
626            continue;
627        }
628        let (x, y) = (sx + (k % w) as u16, area.y + (k / w) as u16);
629        let ch = char::from_u32(0x2800 + bits as u32).unwrap_or('⣿');
630        buf[(x, y)].set_symbol(&ch.to_string()).set_style(if gone {
631            accent
632        } else {
633            Style::reset()
634        });
635    }
636    for y in area.y..area.y + sh {
637        buf[(area.x + gutter, y)].set_symbol("│").set_style(dim);
638    }
639    buf.set_string(
640        area.x,
641        area.y,
642        format!("{:>5}", crate::figure::short(ya.hi)),
643        dim,
644    );
645    buf.set_string(
646        area.x,
647        area.y + sh - 1,
648        format!("{:>5}", crate::figure::short(ya.lo)),
649        dim,
650    );
651    buf.set_string(
652        area.x + gutter,
653        area.y + sh,
654        format!("└{}", "─".repeat(sw as usize)),
655        dim,
656    );
657    for t in xa.ticks() {
658        let label = crate::figure::short(t);
659        let x = sx + (xa.frac(t) * (sw - 1) as f64).round() as u16;
660        let x = x
661            .saturating_sub(label.len() as u16 / 2)
662            .max(sx)
663            .min(area.right().saturating_sub(label.len() as u16));
664        buf.set_string(x, area.y + sh + 1, &label, dim);
665    }
666    // Top left is empty: no cell detects more genes than it counts.
667    let key = "⣿ kept  ";
668    buf.set_string(sx + 1, area.y, key, Style::reset());
669    buf.set_string(
670        sx + 1 + key.chars().count() as u16,
671        area.y,
672        "⣿ removed",
673        accent,
674    );
675}
676
677impl Screen for QcView {
678    fn render(&mut self, frame: &mut Frame) {
679        self.refresh_picker();
680        let [top, body, footer] = Layout::vertical([
681            Constraint::Length(1),
682            Constraint::Fill(1),
683            Constraint::Length(1),
684        ])
685        .areas(frame.area());
686        let v = self.rules.verdicts();
687        let extra = format!(
688            "{} cells × {} genes{}",
689            v.train_keep.len(),
690            v.feature_keep.len(),
691            match (&self.picker, self.images) {
692                (None, _) => "",
693                (Some(_), true) => " · image",
694                (Some(_), false) => " · text",
695            }
696        );
697        title_bar(
698            frame,
699            top,
700            header("qc", &self.name, &extra, &LOOK),
701            &super::session_keys(),
702            &LOOK,
703        );
704        let left_w = (body.width * 2 / 5).clamp(58, 70).min(body.width / 2);
705        let [left, right] =
706            Layout::horizontal([Constraint::Length(left_w), Constraint::Fill(1)]).areas(body);
707        let rows = self.rules.rules().len() as u16 + 12;
708        let [rules_area, overlap] =
709            Layout::vertical([Constraint::Length(rows), Constraint::Fill(1)]).areas(left);
710        let [focus, joint] =
711            Layout::vertical([Constraint::Percentage(50), Constraint::Fill(1)]).areas(right);
712        self.render_rules(frame, rules_area);
713        self.render_overlap(frame, overlap);
714        self.render_focus(frame, focus);
715        self.render_joint(frame, joint);
716        let line = match &self.typing {
717            Some(Typing::Edge(b)) => input_line(
718                &format!("{} edge: ", self.rule().label()),
719                b,
720                &[("Enter", "set"), ("Esc", "back")],
721                &LOOK,
722            ),
723            Some(Typing::Save(b)) => match &self.note {
724                Some(note) => note.clone(),
725                None => input_line(
726                    "save the figure as (.pdf + .png): ",
727                    b,
728                    &[("Enter", "save"), ("Esc", "back")],
729                    &LOOK,
730                ),
731            },
732            Some(Typing::Output(b)) => match &self.note {
733                Some(note) => note.clone(),
734                None => input_line(
735                    "write the kept cells to: ",
736                    b,
737                    &[("Enter", "write"), ("Esc", "back")],
738                    &LOOK,
739                ),
740            },
741            None => match &self.note {
742                Some(note) => note.clone(),
743                None => {
744                    let mut keys = vec![
745                        ("↑/↓", "rule"),
746                        ("←/→", "move edge"),
747                        ("m", "MAD ↔ value"),
748                        ("e", "type edge"),
749                        ("o", "on/off"),
750                        ("r", "reset"),
751                        ("s", "save figure"),
752                        ("p", "flags"),
753                        ("c", "copy flags"),
754                    ];
755                    if self.picker.is_some() {
756                        keys.push(("i", "image/text"));
757                    }
758                    let enter = match &self.output {
759                        Some(out) => format!("write {}", stem(out)),
760                        None => "write…".to_string(),
761                    };
762                    keys.push(("Enter", enter.as_str()));
763                    keys.push(("q", "quit"));
764                    help_line(&keys, &LOOK)
765                }
766            },
767        };
768        frame.render_widget(line, footer);
769    }
770
771    fn handle_key(&mut self, key: KeyEvent) {
772        if self.typing.is_some() {
773            self.handle_typing(key);
774            return;
775        }
776        self.note = None;
777        let n = self.rules.rules().len();
778        let step = if key.modifiers.contains(KeyModifiers::SHIFT) {
779            5
780        } else {
781            1
782        };
783        match key.code {
784            KeyCode::Up | KeyCode::Char('k') => {
785                self.focus = (self.focus + n - 1) % n;
786                self.changed();
787            }
788            KeyCode::Down | KeyCode::Char('j') | KeyCode::Tab => {
789                self.focus = (self.focus + 1) % n;
790                self.changed();
791            }
792            KeyCode::Left | KeyCode::Char('h') => self.nudge(-step),
793            KeyCode::Right | KeyCode::Char('l') => self.nudge(step),
794            KeyCode::Char('H') => self.nudge(-5),
795            KeyCode::Char('L') => self.nudge(5),
796            KeyCode::Char('m') => {
797                let rule = self.rule();
798                if CellRules::banded(rule) {
799                    self.rules.toggle_mode(rule);
800                    self.changed();
801                } else {
802                    self.note = Some(Line::from(Span::styled(
803                        format!(" {} has no MAD band; it takes a value", rule.label()),
804                        LOOK.hint,
805                    )));
806                }
807            }
808            KeyCode::Char('o') => {
809                let rule = self.rule();
810                let on = self.rules.is_on(rule);
811                self.rules.set_on(rule, !on);
812                self.changed();
813            }
814            KeyCode::Char('e') => {
815                let now = self
816                    .rules
817                    .edge(self.rule())
818                    .map(|e| e.to_string())
819                    .unwrap_or_default();
820                self.typing = Some(Typing::Edge(now));
821            }
822            KeyCode::Char('r') => {
823                self.rules.reset();
824                self.changed();
825            }
826            KeyCode::Char('s') => {
827                self.typing = Some(Typing::Save(free_name(&format!("{}_qc", stem(&self.name)))));
828            }
829            KeyCode::Char('p') => self.note = Some(self.flags_line()),
830            KeyCode::Char('c') => {
831                let flags = self.flags_text();
832                super::ui::copy(&flags);
833                let said = match flags.is_empty() {
834                    true => " copied nothing: these are the defaults".to_string(),
835                    false => format!(" copied to the clipboard: {flags}"),
836                };
837                self.note = Some(Line::from(Span::styled(said, LOOK.hint)));
838            }
839            KeyCode::Char('i') if self.picker.is_some() => {
840                self.images = !self.images;
841                self.changed();
842            }
843            KeyCode::Enter => match self.output {
844                Some(_) => self.decision = Some(Decision::Apply),
845                None => self.typing = Some(Typing::Output(free_output(&self.suggest))),
846            },
847            KeyCode::Char('q') | KeyCode::Esc => self.decision = Some(Decision::Cancel),
848            _ => {}
849        }
850    }
851
852    fn interrupt(&mut self) {
853        self.decision = Some(Decision::Cancel);
854    }
855
856    fn done(&self) -> bool {
857        self.decision.is_some()
858    }
859
860    /// A resized figure is drawn at its new size once the resize settles.
861    fn tick(&mut self) -> bool {
862        self.picker.is_some() && self.plots.iter().any(PlotImage::is_stale)
863    }
864
865    fn status(&self) -> Option<String> {
866        Some(format!(
867            "qc {}: keeps {} of {} cells",
868            self.name,
869            self.kept.0,
870            self.rules.verdicts().train_keep.len()
871        ))
872    }
873}
874
875/// How many cells, and genes, `rules` keep: the lengths of
876/// [`CellRules::kept_cells`] and [`CellRules::kept_genes`], counted without
877/// listing them.
878fn kept(rules: &CellRules) -> (usize, usize) {
879    let kept = |removed: &[bool]| removed.iter().filter(|&&r| !r).count();
880    (
881        kept(rules.removed(Rule::Genes)),
882        kept(rules.removed(Rule::GeneCells)),
883    )
884}
885
886/// A backend's name without its extension: `pbmc` of `pbmc.zarr.zip`.
887pub fn stem(name: &str) -> &str {
888    let base = name.rsplit('/').next().unwrap_or(name);
889    [".zarr.zip", ".zarr", ".h5ad", ".h5"]
890        .iter()
891        .find_map(|e| base.strip_suffix(e))
892        .unwrap_or(base)
893}
894
895/// Whether an output named `name` would replace something: the name as
896/// given, or the backend a write under it makes.
897pub fn output_taken(name: &str) -> bool {
898    let base = name.trim_end_matches(".zip").trim_end_matches(".zarr");
899    [
900        name.to_string(),
901        format!("{base}.zarr.zip"),
902        format!("{base}.zarr"),
903        format!("{base}.h5"),
904    ]
905    .iter()
906    .any(|p| std::path::Path::new(p).exists())
907}
908
909/// `name`, or failing that the first of `{name}-2`, `{name}-3`, … that
910/// [`output_taken`] lets through.
911pub fn free_output(name: &str) -> String {
912    (1..)
913        .map(|k| match k {
914            1 => name.to_string(),
915            k => format!("{name}-{k}"),
916        })
917        .find(|n| !output_taken(n))
918        .expect("some suffix is free")
919}
920
921/// Run the view of `rules` in `tui` until Enter or quit: the rules as left,
922/// how it ended, and where the kept cells go (`output`, or the name Enter
923/// asked for, offering `suggest`).
924pub fn choose_rules(
925    tui: &mut Tui<'_>,
926    rules: CellRules,
927    name: &str,
928    output: Option<String>,
929    suggest: &str,
930) -> anyhow::Result<(CellRules, Decision, Option<String>)> {
931    let mut view = QcView::new(rules, name, output, suggest).detect_images();
932    tui.run(&mut view)?;
933    let decision = view.decision().unwrap_or(Decision::Cancel);
934    let output = view.output().map(str::to_string);
935    Ok((view.into_rules(), decision, output))
936}
937
938#[cfg(test)]
939#[path = "tests/qc_tui.rs"]
940mod tests;