garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /programs/src/bin/terminal.rs

raw

//! The terminal: commands typed, their output as records
//! (`docs/terminal-and-agent.md`). No byte stream, no escape codes: a
//! command sends typed records on a channel (text, tables, progress, a
//! status), which the terminal lays out for the window; a plain program's
//! `println!` arrives as lines of text. Each command is started as a std
//! program is (`abi::STD_START` and a start message), holds nothing the
//! terminal did not give it, and is ended by Stop or Ctrl+C (KILL), not a
//! signal.
//!
//! It looks and types as a terminal does: one fixed-width font edge to
//! edge, the prompt under the output with the working folder in it, a
//! cursor that moves (arrows, Home, End, Ctrl+A/E/U/K/W), the commands run
//! before on Up and Down, Tab completing commands and paths. `cd` and `pwd`
//! are its own, as `clear`, `history` and `help` are; the file commands
//! (`ls`, `cat`, …) run in its working folder. On a touch screen a row of
//! the keys the on-screen keyboard lacks (Tab, arrows, `-` `/` `=` …) sits
//! above it.
//!
//! A question (`Ask`) is answered at the prompt, or by a row of buttons for
//! a choice; the answer goes back on the command's stdin. An image comes
//! as shared memory beside its record and is drawn in the output. The
//! session is kept in the data vault and comes back when the terminal
//! starts again.
//!
//! A system program, not an installed app: an app may not start programs.
//! It starts the commands built into the system ([`COMMANDS`]) and any
//! installed app by name, which runs confined as from the launcher.
//!
//! `remote <contact>` runs the commands that follow on that contact's
//! device instead, until `local`: the p2p service carries them over an
//! encrypted stream, and the other device runs them only if its person
//! allowed this contact to, in its Settings. Output, questions and Stop
//! work as here.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::rc::Rc;
use alloc::string::String;
use alloc::vec::Vec;
use core::cell::RefCell;
use pinnacle_gfx::{Canvas, Color, Font, Rect};
use pinnacle_records::pipe::{FILTERS, Join};
use pinnacle_records::start::resolve;
use pinnacle_records::{AskKind, Output, Record};
use pinnacle_rt::abi::KILLED;
use pinnacle_rt::{Channel, Handle, Memory, Process, fs};
use pinnacle_ui::command::{self, COMMANDS};
use pinnacle_ui::keyboard::Key;
use pinnacle_ui::layout::terminal;
use pinnacle_ui::p2p::{Client, Contact};
use pinnacle_ui::{App, Event, theme, wrap};
use pinnacle_view::{Clipboard, IntoView, SCALE, Screen, Signal, View, el, signal};
/// The largest image a command may show, in pixels: a program cannot make
/// the terminal copy gigabytes.
const MAX_IMAGE: u64 = 4096 * 4096;
/// How many of the latest commands the kept session holds.
const KEPT: usize = 50;
/// The most lines one command keeps: a program printing for ever does not
/// fill the memory.
const MAX_ITEMS: usize = 2000;
/// The most commands the session keeps.
const MAX_ENTRIES: usize = 200;
/// The most lines Up and Down go back through.
const MAX_HISTORY: usize = 500;
/// Between one command's output and the next prompt.
const ENTRY_GAP: i32 = 10;

/// The terminal's own colours: darker than the system's background, and
/// the prompt in green, as terminals have it.
const BACKGROUND: Color = Color::rgb(0x0b, 0x0e, 0x12);
const BAR: Color = Color::rgb(0x14, 0x18, 0x1e);
const RULE: Color = Color::rgb(0x23, 0x29, 0x31);
const FOREGROUND: Color = Color::rgb(0xd8, 0xde, 0xe6);
const PROMPT: Color = Color::rgb(0x6c, 0xd4, 0x8e);
const QUESTION: Color = Color::rgb(0xe8, 0xc0, 0x6a);
const CURSOR: Color = Color::rgb(0xd8, 0xde, 0xe6);

/// The commands the terminal runs itself, beside [`COMMANDS`].
const OWN: [(&str, &str); 4] = [
    ("cd", "Into a folder: cd path, cd .. up, cd alone home"),
    ("pwd", "The folder commands run in"),
    ("history", "The commands run before: ↑ and ↓ bring them back"),
    (
        "remote",
        "What follows runs on a contact's device, if it allows you: remote name",
    ),
];

enum Item {
    Record(Record),
    /// A line of a plain program's output; `error` when from stderr.
    Line {
        text: String,
        error: bool,
    },
    /// An image's pixels, copied out of the memory it came in.
    Image {
        pixels: Vec<u32>,
        width: i32,
        height: i32,
    },
    /// What was answered to a question.
    Answer(String),
}

/// A command that still runs: its output and stderr, and the channel its
/// exit code comes on, each dropped as it closes; and its stdin, where
/// answers go. Here it is a process; on another device, the p2p service
/// stops it when asked on `control`, or when `control` closes.
struct Run {
    process: Option<Process>,
    control: Option<Channel>,
    streams: [Option<Channel>; 3],
    input: Channel,
    /// In a pipeline, the commands before its last `|`.
    upstream: command::Upstream,
}

impl From<command::Run> for Run {
    fn from(run: command::Run) -> Run {
        Run {
            process: Some(run.process),
            control: None,
            streams: run.streams,
            input: run.input,
            upstream: run.upstream,
        }
    }
}

impl Run {
    fn stop(&self) -> bool {
        match (&self.process, &self.control) {
            (Some(process), _) => {
                self.upstream.kill();
                process.kill()
            }
            (None, Some(control)) => control.send(b"stop", Vec::new()),
            _ => false,
        }
    }
}

/// A question waiting for its answer.
struct Asking {
    id: u32,
    kind: AskKind,
    options: Vec<String>,
}

struct Entry {
    /// Where it ran: the working folder, or the contact's name.
    prompt: String,
    line: String,
    items: Vec<Item>,
    /// A plain program's unfinished last line, per stream (stdout, stderr).
    partial: [String; 2],
    exit: Option<u64>,
    stopped: bool,
    run: Option<Run>,
    asking: Option<Asking>,
    /// The rest of its line: the commands after a `;` or `&&`, run once
    /// it ends (`Terminal::chain`).
    then: Vec<(Join, String)>,
}

impl Entry {
    fn new(prompt: &str, line: &str) -> Entry {
        Entry {
            prompt: prompt.into(),
            line: line.into(),
            items: Vec::new(),
            partial: [String::new(), String::new()],
            exit: None,
            stopped: false,
            run: None,
            asking: None,
            then: Vec::new(),
        }
    }

    /// How the log names it: the line, with the contact it ran on.
    fn label(&self) -> String {
        match self.prompt.contains(":/") || self.prompt.is_empty() {
            true => self.line.clone(),
            false => alloc::format!("{} › {}", self.prompt, self.line),
        }
    }

    fn push(&mut self, item: Item) {
        if self.items.len() < MAX_ITEMS {
            self.items.push(item);
        }
    }

    fn say(&mut self, text: impl Into<String>, error: bool) {
        self.push(Item::Line {
            text: text.into(),
            error,
        });
    }

    /// A message on stdout (`stream` 0) or stderr (1), with the handles it
    /// carried.
    fn output(&mut self, stream: usize, message: &[u8], mut handles: Vec<Handle>) {
        match Output::of(message) {
            Output::Record(Record::Image { width, height }) => {
                let count = u64::from(width) * u64::from(height);
                let image = (count <= MAX_IMAGE && !handles.is_empty())
                    .then(|| Memory::map(handles.remove(0)))
                    .flatten()
                    .filter(|m| m.size as u64 >= count * 4);
                match image {
                    Some(mut memory) => {
                        let pixels = memory.pixels()[..count as usize].to_vec();
                        memory.unmap();
                        self.push(Item::Image {
                            pixels,
                            width: width as i32,
                            height: height as i32,
                        });
                    }
                    None => self.say(
                        alloc::format!("(an image, {width}×{height}, that did not come)"),
                        true,
                    ),
                }
            }
            Output::Record(Record::Ask {
                id,
                kind,
                prompt,
                options,
            }) => {
                let options = match kind {
                    AskKind::YesNo => alloc::vec!["Yes".into(), "No".into()],
                    _ => options,
                };
                pinnacle_rt::println!("terminal: asked {prompt}");
                self.asking = Some(Asking {
                    id,
                    kind,
                    options: options.clone(),
                });
                self.push(Item::Record(Record::Ask {
                    id,
                    kind,
                    prompt,
                    options,
                }));
            }
            Output::Record(Record::Progress {
                id,
                done,
                total,
                label,
            }) => {
                let same = |i: &Item| matches!(i, Item::Record(Record::Progress { id: j, .. }) if *j == id);
                let progress = Record::Progress {
                    id,
                    done,
                    total,
                    label,
                };
                match self.items.iter_mut().find(|i| same(i)) {
                    Some(item) => *item = Item::Record(progress),
                    None => self.push(Item::Record(progress)),
                }
            }
            Output::Record(record) => self.push(Item::Record(record)),
            Output::Bytes(bytes) => {
                self.partial[stream].push_str(&String::from_utf8_lossy(bytes));
                while let Some(end) = self.partial[stream].find('\n') {
                    let text = String::from(self.partial[stream][..end].trim_end_matches('\r'));
                    self.partial[stream].drain(..=end);
                    self.say(text, stream == 1);
                }
            }
            Output::Malformed => self.say("(a record that did not parse)", true),
        }
    }

    /// A stream closed: its unfinished line is a line after all.
    fn flush(&mut self, stream: usize) {
        let text = core::mem::take(&mut self.partial[stream]);
        if !text.is_empty() {
            self.say(text, stream == 1);
        }
    }

    /// The command's text output, for the clipboard.
    fn text(&self) -> String {
        let mut out = String::new();
        for item in &self.items {
            match item {
                Item::Line { text, .. } | Item::Record(Record::Text(text)) => {
                    out.push_str(text);
                    out.push('\n');
                }
                Item::Record(Record::Table { columns, rows }) => {
                    if columns.iter().any(|c| !c.is_empty()) {
                        out.push_str(&columns.join("\t"));
                        out.push('\n');
                    }
                    for row in rows {
                        out.push_str(&row.join("\t"));
                        out.push('\n');
                    }
                }
                _ => {}
            }
        }
        out
    }
}

/// The contacts, from the p2p service: asked afresh each time, and the
/// connection let go, since the service also sends its apps every message
/// that arrives.
fn contacts() -> Vec<Contact> {
    Client::connect(2000).map_or_else(Vec::new, |c| c.contacts(&mut Vec::new()))
}

/// Starts `line`'s command on `contact`'s device, through the p2p service.
fn start_remote(contact: &Contact, line: &str) -> Result<Run, String> {
    let (input, their_in) = Channel::pair();
    let (out, their_out) = Channel::pair();
    let (err, their_err) = Channel::pair();
    let (watch, their_watch) = Channel::pair();
    let (control, their_control) = Channel::pair();
    let handles = alloc::vec![
        their_in.0,
        their_out.0,
        their_err.0,
        their_watch.0,
        their_control.0
    ];
    if !pinnacle_ui::p2p::exec(&contact.key, line, handles) {
        return Err("The p2p service is not running".into());
    }
    Ok(Run {
        process: None,
        control: Some(control),
        streams: [Some(out), Some(err), Some(watch)],
        input,
        upstream: command::Upstream::default(),
    })
}

/// `help`: the commands, as a table, then the keys.
fn help() -> [Record; 2] {
    let mut rows: Vec<Vec<String>> = OWN
        .iter()
        .chain(COMMANDS)
        .chain(FILTERS)
        .map(|(c, what)| alloc::vec![String::from(*c), String::from(*what)])
        .collect();
    rows.push(alloc::vec![
        "a | b".into(),
        "What a gives, b changes: ls | where Size > 1 KB | sort Size down".into()
    ]);
    rows.push(alloc::vec![
        "a > file".into(),
        "What a gives written to the file as text; >> adds to it: ps > ps.txt".into()
    ]);
    rows.push(alloc::vec![
        "a; b   a && b".into(),
        "One after the other; b only if a succeeded: cd logs && tail -n 20 system.log".into()
    ]);
    rows.push(alloc::vec![
        "\"…\"  '…'".into(),
        "Words with spaces kept whole: grep \"no address\" log.txt".into()
    ]);
    rows.push(alloc::vec![
        "an app's name".into(),
        "The app, as from the home screen".into()
    ]);
    rows.push(alloc::vec![
        "local".into(),
        "Back to this device, after remote".into()
    ]);
    let keys = "Tab completes a command or a path · ↑ ↓ the commands run before · Ctrl+C stops what runs · Ctrl+L clears · PgUp PgDn scroll";
    [
        Record::Table {
            columns: alloc::vec!["Command".into(), "What it does".into()],
            rows,
        },
        Record::Text(keys.into()),
    ]
}

/// What is drawn, laid out for the page: each element at its y from the
/// session's top, and its height.
enum Shape<'a> {
    /// A command as it was typed: where it ran, and the line.
    Command(&'a str, &'a str),
    Line(String, Color),
    /// A table's row: each cell's lines, the columns' x's and widths, a
    /// header row or not.
    Row(Vec<Vec<String>>, Vec<(i32, i32)>, bool),
    Progress(&'a str, u64, u64),
    /// Pixels, their width and height, and the height drawn: an image wider
    /// than the page is scaled down to it.
    Image(&'a [u32], i32, i32, i32),
    /// A row of the prompt being typed: its characters and their colours,
    /// and the cursor's column on it.
    Input(Vec<(char, Color)>, Option<usize>),
}

/// Columns for a table on `width`: each as wide as its widest cell, cut
/// back evenly from the widest when they do not all fit; two characters
/// between them.
fn columns(font: &Font, columns: &[String], rows: &[Vec<String>], width: i32) -> Vec<(i32, i32)> {
    let gap = 2 * font.measure("M");
    let n = columns.len().max(rows.iter().map(Vec::len).max().unwrap_or(0));
    let mut widths: Vec<i32> = (0..n)
        .map(|c| {
            let cells = rows.iter().filter_map(|r| r.get(c)).chain(columns.get(c));
            cells.map(|s| font.measure(s)).max().unwrap_or(0)
        })
        .collect();
    let room = width - gap * (n as i32 - 1).max(0);
    while widths.iter().sum::<i32>() > room {
        let widest = (0..n).max_by_key(|&i| widths[i]).unwrap();
        widths[widest] -= (widths.iter().sum::<i32>() - room).min(widths[widest] / 4 + 1);
    }
    let mut x = 0;
    widths
        .into_iter()
        .map(|w| {
            let at = (x, w);
            x += w + gap;
            at
        })
        .collect()
}

/// Shapes stacked down the page.
struct Stack<'a> {
    shapes: Vec<(i32, i32, Shape<'a>)>,
    y: i32,
}

impl<'a> Stack<'a> {
    fn add(&mut self, shape: Shape<'a>, height: i32) {
        self.shapes.push((self.y, height, shape));
        self.y += height;
    }
}

/// Text cut into lines of `width`: at spaces where it can, inside a word
/// too long for a line where it must.
fn lines(font: &Font, text: &str, width: i32) -> Vec<String> {
    let cols = (width / font.measure("M").max(1)).max(1) as usize;
    let mut out = Vec::new();
    for paragraph in text.split('\n') {
        // A tab is spaces to the next stop of eight: the fonts draw it as
        // a box, and a saved table's columns are tab-separated.
        let expanded;
        let paragraph = match paragraph.contains('\t') {
            false => paragraph,
            true => {
                let mut line = String::new();
                for c in paragraph.chars() {
                    match c {
                        '\t' => line.extend(core::iter::repeat_n(' ', 8 - line.chars().count() % 8)),
                        c => line.push(c),
                    }
                }
                expanded = line;
                expanded.as_str()
            }
        };
        // A line that fits keeps its spaces, leading ones too.
        if paragraph.chars().count() <= cols {
            out.push(paragraph.into());
            continue;
        }
        for line in wrap(font, paragraph, width) {
            let chars: Vec<char> = line.chars().collect();
            if chars.len() <= cols {
                out.push(line);
            } else {
                out.extend(chars.chunks(cols).map(|c| c.iter().collect()));
            }
        }
    }
    out
}

fn layout<'a>(entries: &'a [Entry], width: i32) -> Stack<'a> {
    let font = theme::mono();
    let lh = font.line_height;
    let mut out = Stack {
        shapes: Vec::new(),
        y: 0,
    };
    for entry in entries {
        out.add(Shape::Command(&entry.prompt, &entry.line), lh);
        for item in &entry.items {
            match item {
                Item::Line { text, error } => {
                    let color = if *error { theme::BAD } else { FOREGROUND };
                    for line in lines(font, text, width) {
                        out.add(Shape::Line(line, color), lh);
                    }
                }
                Item::Record(Record::Text(text)) => {
                    for line in lines(font, text, width) {
                        out.add(Shape::Line(line, FOREGROUND), lh);
                    }
                }
                Item::Record(Record::Table { columns: names, rows }) => {
                    let at = columns(font, names, rows, width);
                    // A cell longer than its column wraps inside it.
                    let mut row = |cells: &[String], header: bool| {
                        let cells: Vec<Vec<String>> = cells
                            .iter()
                            .zip(&at)
                            .map(|(c, &(_, w))| lines(font, c, w))
                            .collect();
                        let height = cells.iter().map(Vec::len).max().unwrap_or(1) as i32 * lh;
                        out.add(Shape::Row(cells, at.clone(), header), height);
                    };
                    if names.iter().any(|c| !c.is_empty()) {
                        row(names, true);
                    }
                    for cells in rows {
                        row(cells, false);
                    }
                }
                Item::Record(Record::Progress {
                    done, total, label, ..
                }) => out.add(Shape::Progress(label, *done, *total), lh),
                Item::Record(Record::Status { summary, .. }) if summary.is_empty() => {}
                Item::Record(Record::Status { code, summary }) => {
                    let color = if *code == 0 { theme::TEXT_DIM } else { theme::BAD };
                    for line in lines(font, summary, width) {
                        out.add(Shape::Line(line, color), lh);
                    }
                }
                Item::Record(Record::File { name, size }) => {
                    let text = alloc::format!("(a file, {name}, {size} bytes: not shown yet)");
                    out.add(Shape::Line(text, theme::TEXT_DIM), lh);
                }
                Item::Image {
                    pixels,
                    width: w,
                    height: h,
                } => {
                    let shown = if *w > width { h * width / w } else { *h };
                    out.add(Shape::Image(pixels, *w, *h, shown), shown + 8);
                }
                Item::Answer(text) => {
                    out.add(Shape::Line(alloc::format!("› {text}"), theme::TEXT_DIM), lh);
                }
                // Images arrive with their pixels, as an `Item::Image`.
                Item::Record(Record::Image { .. }) | Item::Record(Record::Answer { .. }) => {}
                Item::Record(Record::Ask {
                    prompt,
                    options,
                    kind,
                    ..
                }) => {
                    for line in lines(font, &alloc::format!("? {prompt}"), width) {
                        out.add(Shape::Line(line, QUESTION), lh);
                    }
                    if *kind != AskKind::Text && !options.is_empty() {
                        let list: Vec<String> = options
                            .iter()
                            .enumerate()
                            .map(|(i, o)| alloc::format!("{}) {o}", i + 1))
                            .collect();
                        for line in lines(font, &alloc::format!("  {}", list.join("   ")), width) {
                            out.add(Shape::Line(line, theme::TEXT_DIM), lh);
                        }
                    }
                }
            }
        }
        // As a terminal has it: nothing when it went well.
        let end = match (entry.exit, entry.stopped, &entry.run) {
            (_, _, Some(_)) => Some((String::from("… running"), theme::TEXT_DIM)),
            (_, true, None) => Some((String::from("^C stopped"), theme::TEXT_DIM)),
            (Some(code), _, None) if code >= KILLED => Some((String::from("ended by a fault"), theme::BAD)),
            (Some(code), _, None) if code != 0 => Some((alloc::format!("exit {code}"), theme::BAD)),
            _ => None,
        };
        if let Some((text, color)) = end {
            out.add(Shape::Line(text, color), lh);
        }
        out.y += ENTRY_GAP;
    }
    out
}

/// The cells of `prefix` and `input`, cut into rows of `cols`, the cursor
/// (a character index into `input`) on one of them.
fn input_rows(prefix: &[(&str, Color)], input: &str, cursor: usize, cols: usize) -> Vec<Shape<'static>> {
    let mut cells: Vec<(char, Color)> = Vec::new();
    for (text, color) in prefix {
        cells.extend(text.chars().map(|c| (c, *color)));
    }
    let at = cells.len() + cursor;
    cells.extend(input.chars().map(|c| (c, FOREGROUND)));
    let rows = at / cols + 1;
    let rows = rows.max(cells.len().div_ceil(cols));
    (0..rows)
        .map(|r| {
            let row = cells.iter().skip(r * cols).take(cols).copied().collect();
            Shape::Input(row, (at / cols == r).then_some(at % cols))
        })
        .collect()
}

/// Where the session is kept: in the data vault once it is open, else on
/// the system disk.
fn kept_at() -> &'static str {
    if fs::disk("data").is_some() {
        "data:/terminal/session"
    } else {
        "system:/terminal/session"
    }
}

/// The session's latest [`KEPT`] commands, kept, and the working folder:
/// each command its folder or contact, its line, how it ended and what it
/// showed. Records are kept as their messages; an image as its size alone.
fn save(entries: &[Entry], cwd: &str) {
    fn put(out: &mut Vec<u8>, bytes: &[u8]) {
        out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
        out.extend_from_slice(bytes);
    }
    let kept = &entries[entries.len().saturating_sub(KEPT)..];
    let mut out = b"PTS2".to_vec();
    put(&mut out, cwd.as_bytes());
    out.extend_from_slice(&(kept.len() as u32).to_le_bytes());
    for entry in kept {
        put(&mut out, entry.prompt.as_bytes());
        put(&mut out, entry.line.as_bytes());
        out.extend_from_slice(&entry.exit.unwrap_or(u64::MAX).to_le_bytes());
        out.push(u8::from(entry.stopped));
        out.extend_from_slice(&(entry.items.len() as u32).to_le_bytes());
        for item in &entry.items {
            let (tag, bytes) = match item {
                Item::Record(r) => (0, r.encode().unwrap_or_default()),
                Item::Line { text, error } => (1 + u8::from(*error), text.as_bytes().to_vec()),
                Item::Answer(text) => (3, text.as_bytes().to_vec()),
                Item::Image { width, height, .. } => (
                    4,
                    alloc::format!("(an image, {width}×{height}, not kept)").into_bytes(),
                ),
            };
            out.push(tag);
            put(&mut out, &bytes);
        }
    }
    let path = kept_at();
    fs::create_dir(path.rsplit_once('/').map_or(path, |(dir, _)| dir));
    if !fs::write(path, &out) {
        pinnacle_rt::println!("terminal: could not keep the session");
    }
}

/// The session kept by [`save`] and its working folder, or none. A
/// session kept before there were folders (`PTS1`) comes back too.
fn load() -> (Vec<Entry>, Option<String>) {
    struct At<'a>(&'a [u8]);
    impl<'a> At<'a> {
        fn take(&mut self, n: usize) -> Option<&'a [u8]> {
            let (b, rest) = self.0.split_at_checked(n)?;
            self.0 = rest;
            Some(b)
        }
        fn u32(&mut self) -> Option<u32> {
            Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?))
        }
        fn bytes(&mut self) -> Option<&'a [u8]> {
            let n = self.u32()? as usize;
            self.take(n)
        }
        fn text(&mut self) -> Option<String> {
            Some(String::from_utf8_lossy(self.bytes()?).into_owned())
        }
    }
    let read = |data: &[u8]| -> Option<(Vec<Entry>, Option<String>)> {
        let (at, folders) = match (data.strip_prefix(b"PTS2"), data.strip_prefix(b"PTS1")) {
            (Some(rest), _) => (&mut At(rest), true),
            (None, Some(rest)) => (&mut At(rest), false),
            _ => return None,
        };
        let cwd = if folders { Some(at.text()?) } else { None };
        let mut entries = Vec::new();
        for _ in 0..at.u32()?.min(KEPT as u32) {
            let prompt = if folders { at.text()? } else { String::new() };
            let mut entry = Entry::new(&prompt, &at.text()?);
            let exit = u64::from_le_bytes(at.take(8)?.try_into().ok()?);
            entry.exit = (exit != u64::MAX).then_some(exit);
            entry.stopped = at.take(1)?[0] != 0;
            for _ in 0..at.u32()? {
                let tag = at.take(1)?[0];
                let item = match tag {
                    0 => Item::Record(Record::decode(at.bytes()?)?),
                    1 | 2 | 4 => Item::Line {
                        text: at.text()?,
                        error: tag == 2,
                    },
                    3 => Item::Answer(at.text()?),
                    _ => return None,
                };
                entry.push(item);
            }
            entries.push(entry);
        }
        Some((entries, cwd))
    };
    let (entries, cwd) = fs::read(kept_at())
        .and_then(|data| read(&data))
        .unwrap_or_default();
    pinnacle_rt::println!("terminal: {} commands kept", entries.len());
    (entries, cwd)
}

/// Whether `path` is a folder (a disk's root lists, though it may not stat).
fn is_folder(path: &str) -> bool {
    fs::stat(path).map_or_else(|| fs::list(path).is_some(), |s| s.directory)
}

/// The longest start all of `words` share.
fn common_start(words: &[String]) -> String {
    let Some(first) = words.first() else {
        return String::new();
    };
    let mut end = first.len();
    for w in &words[1..] {
        end = first
            .char_indices()
            .zip(w.chars())
            .find(|((_, a), b)| a != b)
            .map_or(end.min(w.len()), |((i, _), _)| i.min(end));
    }
    String::from(&first[..end])
}

struct Terminal {
    entries: Vec<Entry>,
    input: String,
    /// Where the cursor is in `input`, in bytes.
    cursor: usize,
    /// The commands run before, the latest last.
    history: Vec<String>,
    /// Going through `history` with Up and Down: where, and the line that
    /// was being typed before.
    recall: Option<(usize, String)>,
    /// What Tab found when it could not choose: shown under the prompt.
    hint: Vec<String>,
    /// The folder commands run in, `disk:/path`.
    cwd: String,
    /// How far the session is scrolled back from its end, in pixels.
    scroll: i32,
    /// A finger on the session: where it was last, and whether it moved.
    drag: Option<(i32, bool)>,
    /// The contact whose device commands run on, after `remote`.
    remote: Option<Contact>,
}

impl Terminal {
    fn running(&self) -> bool {
        self.entries.iter().any(|e| e.run.is_some())
    }

    /// The question waiting for an answer, the newest first: its command.
    fn asking(&self) -> Option<usize> {
        (0..self.entries.len())
            .rev()
            .find(|&i| self.entries[i].asking.is_some() && self.entries[i].run.is_some())
    }

    /// The answers to tap, when the question has options.
    fn options(&self) -> &[String] {
        match self.asking().and_then(|i| self.entries[i].asking.as_ref()) {
            Some(a) if a.kind != AskKind::Text => &a.options,
            _ => &[],
        }
    }

    /// Answers the waiting question with `text`, on the command's stdin.
    fn answer(&mut self, text: &str) {
        let Some(i) = self.asking() else { return };
        let entry = &mut self.entries[i];
        let asking = entry.asking.take().unwrap();
        let answer = Record::Answer {
            id: asking.id,
            text: String::from(pinnacle_records::clip(text, 2048)),
        };
        if let (Some(run), Some(bytes)) = (&entry.run, answer.encode()) {
            run.input.send(&bytes, Vec::new());
        }
        pinnacle_rt::println!("terminal: answered {text}");
        entry.push(Item::Answer(text.into()));
        self.scroll = 0;
    }

    /// What the prompt starts with: the folder (or contact) and `$`, or a
    /// mark while a question waits for its answer.
    fn prefix(&self) -> Vec<(&str, Color)> {
        if self.asking().is_some() {
            return alloc::vec![("› ", QUESTION)];
        }
        match &self.remote {
            Some(c) => alloc::vec![(c.name.as_str(), theme::ACCENT), (" $ ", theme::TEXT_DIM)],
            None => alloc::vec![(self.cwd.as_str(), PROMPT), (" $ ", theme::TEXT_DIM)],
        }
    }

    /// The session, then the prompt, its end in view unless scrolled back,
    /// in `area` of the window: the view's `<canvas>` for it.
    fn draw(&mut self, canvas: &mut Canvas, area: Rect) {
        let font = theme::mono();
        let (lh, cw) = (font.line_height, font.measure("M").max(1));
        let clip = canvas.clip();
        canvas.fill_rect(area, BACKGROUND);
        let page = Rect::new(
            area.x + terminal::PAD,
            area.y + 8,
            area.width - 2 * terminal::PAD,
            area.height - 16,
        );
        let mut stack = layout(&self.entries, page.width);
        if self.entries.is_empty() {
            let hello =
                "Pinnacle terminal. help lists the commands; Tab completes, ↑ ↓ bring back what you ran.";
            for line in lines(font, hello, page.width) {
                stack.add(Shape::Line(line, theme::TEXT_DIM), lh);
            }
            stack.y += ENTRY_GAP;
        }
        let cols = (page.width / cw).max(1) as usize;
        let cursor = self.input[..self.cursor].chars().count();
        for row in input_rows(&self.prefix(), &self.input, cursor, cols) {
            stack.add(row, lh);
        }
        if !self.hint.is_empty() {
            for line in lines(font, &self.hint.join("  "), page.width) {
                stack.add(Shape::Line(line, theme::TEXT_DIM), lh);
            }
        }
        let shapes = stack.shapes;
        let total = shapes.last().map_or(0, |(y, h, _)| y + h);
        self.scroll = self.scroll.clamp(0, (total - page.height).max(0));
        // Short of a page, the session starts at the top, as a terminal's does.
        let top = (total - page.height).max(0) - self.scroll;
        canvas.set_clip(page.intersect(&clip));
        for (y, h, shape) in &shapes {
            let y = page.y + y - top;
            if y + h < page.y || y > page.bottom() {
                continue;
            }
            let base = y + font.ascent;
            match shape {
                Shape::Command(prompt, line) => {
                    let x = match prompt.contains(":/") || prompt.is_empty() {
                        true => canvas.text(font, page.x, base, prompt, PROMPT),
                        false => canvas.text(font, page.x, base, prompt, theme::ACCENT),
                    };
                    let x = canvas.text(font, x, base, " $ ", theme::TEXT_DIM);
                    canvas.text(font, x, base, line, FOREGROUND);
                }
                Shape::Line(text, color) => {
                    canvas.text(font, page.x, base, text, *color);
                }
                Shape::Row(cells, at, header) => {
                    let color = if *header { theme::TEXT_DIM } else { FOREGROUND };
                    for (cell, &(x, w)) in cells.iter().zip(at) {
                        canvas.set_clip(
                            Rect::new(page.x + x, page.y, w, page.height)
                                .intersect(&page)
                                .intersect(&clip),
                        );
                        for (k, line) in cell.iter().enumerate() {
                            canvas.text(font, page.x + x, base + k as i32 * lh, line, color);
                        }
                    }
                    canvas.set_clip(page.intersect(&clip));
                }
                Shape::Progress(label, done, total) => {
                    let percent = (*done).min(*total) * 100 / (*total).max(1);
                    let count = alloc::format!(" {done}/{total} {percent:>3}%");
                    let x = canvas.text(font, page.x, base, label, FOREGROUND) + cw;
                    let room = page.right() - font.measure(&count) - x;
                    let bar = Rect::new(x, y + lh / 2 - 4, room.max(0), 8);
                    canvas.fill_rect(bar, RULE);
                    let filled = (i64::from(bar.width) * percent as i64 / 100) as i32;
                    canvas.fill_rect(Rect::new(bar.x, bar.y, filled, bar.height), PROMPT);
                    canvas.text(font, bar.right(), base, &count, theme::TEXT_DIM);
                }
                Shape::Image(pixels, w, h, shown) => {
                    if *shown == *h {
                        canvas.blit(pixels, *w, *h, page.x, y);
                    } else {
                        // Scaled down to the page, nearest pixel.
                        let sw = page.width;
                        let scaled: Vec<u32> = (0..sw * shown)
                            .map(|i| {
                                let (x, row) = (i % sw, i / sw);
                                pixels[(row * h / shown * w + x * w / sw) as usize]
                            })
                            .collect();
                        canvas.blit(&scaled, sw, *shown, page.x, y);
                    }
                }
                Shape::Input(cells, cursor) => {
                    let mut text = [0u8; 4];
                    for (i, (c, color)) in cells.iter().enumerate() {
                        let x = page.x + i as i32 * cw;
                        let color = match *cursor == Some(i) {
                            true => {
                                canvas.fill_rect(Rect::new(x, y, cw, lh), CURSOR);
                                BACKGROUND
                            }
                            false => *color,
                        };
                        canvas.text(font, x, base, c.encode_utf8(&mut text), color);
                    }
                    if let Some(at) = cursor.filter(|&at| at >= cells.len()) {
                        canvas.fill_rect(Rect::new(page.x + at as i32 * cw, y, cw, lh), CURSOR);
                    }
                }
            }
        }
        canvas.set_clip(clip);
    }

    /// The line typed, replaced: the cursor at its end.
    fn set_input(&mut self, text: String) {
        self.cursor = text.len();
        self.input = text;
    }

    fn insert(&mut self, text: &str) {
        self.input.insert_str(self.cursor, text);
        self.cursor += text.len();
    }

    /// The character boundary before (or after) the cursor.
    fn step(&self, back: bool) -> usize {
        match back {
            true => self.input[..self.cursor]
                .chars()
                .next_back()
                .map_or(0, |c| self.cursor - c.len_utf8()),
            false => self.input[self.cursor..]
                .chars()
                .next()
                .map_or(self.cursor, |c| self.cursor + c.len_utf8()),
        }
    }

    /// Up (`back`) or Down through the commands run before.
    fn recall(&mut self, back: bool) {
        let at = match (&self.recall, back) {
            (None, true) if !self.history.is_empty() => {
                self.recall = Some((self.history.len(), self.input.clone()));
                self.history.len() - 1
            }
            (None, _) => return,
            (Some((i, _)), true) => i.saturating_sub(1),
            (Some((i, _)), false) => i + 1,
        };
        if at >= self.history.len() {
            let (_, draft) = self.recall.take().unwrap();
            self.set_input(draft);
        } else {
            self.recall.as_mut().unwrap().0 = at;
            self.set_input(self.history[at].clone());
        }
    }

    /// Tab: the word before the cursor completed, as far as what it can be
    /// agrees; what it can be shown when that is not far enough.
    fn complete(&mut self) {
        let before = &self.input[..self.cursor];
        let start = before.rfind(' ').map_or(0, |i| i + 1);
        let word = String::from(&before[start..]);
        // A command's name comes first on the line, and after each `|`.
        let first = before[..start].trim().is_empty() || before[..start].trim_end().ends_with('|');
        let after_remote = before[..start].trim() == "remote";
        // Each candidate, and what Tab shows of it.
        let mut found: Vec<(String, String)> = Vec::new();
        if first {
            let names = OWN
                .iter()
                .chain(COMMANDS)
                .chain(FILTERS)
                .map(|(c, _)| String::from(*c))
                .chain(["local".into()])
                .chain(pinnacle_ui::verbs::SERVICES.iter().map(|(s, _)| String::from(*s)))
                .chain(command::apps());
            for name in names {
                if name.starts_with(word.as_str()) && !found.iter().any(|(n, _)| *n == name) {
                    found.push((name.clone(), name));
                }
            }
        } else if after_remote {
            for c in contacts() {
                if c.name.to_lowercase().starts_with(&word.to_lowercase()) {
                    found.push((c.name.clone(), c.name));
                }
            }
        } else if self.remote.is_none() {
            // A path: the folder it names so far, and the start of a name.
            let (folder, part) = match word.rfind('/') {
                Some(i) => (&word[..=i], &word[i + 1..]),
                None => ("", word.as_str()),
            };
            let at = resolve(
                &self.cwd,
                command::home(),
                if folder.is_empty() { "." } else { folder },
            );
            for name in fs::list(&at).unwrap_or_default() {
                // A folder is listed with a `/` after its name.
                let name = name.trim_end_matches('/');
                if name.starts_with(part) {
                    let full = alloc::format!("{}/{name}", at.trim_end_matches('/'));
                    let slash = if is_folder(&full) { "/" } else { "" };
                    found.push((
                        alloc::format!("{folder}{name}{slash}"),
                        alloc::format!("{name}{slash}"),
                    ));
                }
            }
            if folder.is_empty() {
                for disk in ["data:/", "system:/"] {
                    if disk.starts_with(word.as_str()) && !word.is_empty() && is_folder(disk) {
                        found.push((disk.into(), disk.into()));
                    }
                }
            }
        }
        found.sort();
        let words: Vec<String> = found.iter().map(|(w, _)| w.clone()).collect();
        let done = match words.len() {
            0 => return,
            1 if words[0].ends_with('/') => words[0].clone(),
            1 => alloc::format!("{} ", words[0]),
            _ => common_start(&words),
        };
        if done.len() > word.len() {
            self.input.replace_range(start..self.cursor, &done);
            self.cursor = start + done.len();
            self.hint.clear();
        } else {
            self.hint = found.into_iter().map(|(_, shown)| shown).collect();
        }
    }

    /// Runs what is at the prompt, or answers the question waiting.
    fn enter(&mut self) {
        let text = core::mem::take(&mut self.input);
        self.cursor = 0;
        self.hint.clear();
        self.recall = None;
        if self.asking().is_none() {
            self.input = text;
            return self.run();
        }
        let options = self.options().to_vec();
        if options.is_empty() {
            return self.answer(&text);
        }
        // A choice: its number, or its words.
        let wanted = text.trim();
        let chosen = wanted
            .parse::<usize>()
            .ok()
            .and_then(|n| options.get(n.wrapping_sub(1)))
            .or_else(|| options.iter().find(|o| o.eq_ignore_ascii_case(wanted)))
            .or_else(|| match wanted.to_lowercase().as_str() {
                "y" if options[0] == "Yes" => options.first(),
                "n" if options[0] == "Yes" => options.get(1),
                _ => None,
            });
        match chosen {
            Some(option) => {
                let option = option.clone();
                self.answer(&option);
            }
            None => {
                self.hint = alloc::vec![alloc::format!("Answer with a number, 1 to {}", options.len())];
            }
        }
    }

    /// Runs what is in the field: its first command now, the rest of a line
    /// joined by `;` and `&&` as each before ends ([`Self::next`]).
    fn run(&mut self) {
        let line = String::from(self.input.trim());
        self.input.clear();
        self.cursor = 0;
        self.scroll = 0;
        if line.is_empty() {
            return;
        }
        if self.history.last() != Some(&line) {
            self.history.push(line.clone());
            if self.history.len() > MAX_HISTORY {
                self.history.remove(0);
            }
        }
        let parts = pinnacle_records::pipe::sequence(&line)
            .into_iter()
            .map(|(join, part)| (join, String::from(part)))
            .collect();
        self.chain(parts, None);
    }

    /// The commands of a line, from the first in `parts` on, `done` saying
    /// whether the one before succeeded: each runs as the one before ends
    /// (the rest kept on its entry, [`Entry::then`]), one after `&&` only
    /// if that one succeeded.
    fn chain(&mut self, mut parts: Vec<(Join, String)>, mut done: Option<bool>) {
        while !parts.is_empty() {
            let (join, line) = parts.remove(0);
            if join == Join::IfDone && done == Some(false) {
                // Not run, and so not done either: a `;` after runs again.
                continue;
            }
            let Some(i) = self.run_one(line) else {
                done = Some(true);
                continue;
            };
            let entry = &mut self.entries[i];
            if entry.run.is_some() {
                entry.then = parts;
                return;
            }
            done = Some(entry.exit == Some(0));
        }
    }

    /// Command `i` ended: the rest of its line, unless it was stopped.
    fn ended(&mut self, i: usize) {
        let entry = &mut self.entries[i];
        let then = core::mem::take(&mut entry.then);
        if !then.is_empty() && !entry.stopped {
            let done = entry.exit == Some(0);
            self.chain(then, Some(done));
        }
    }

    /// Runs one command of a line: the entry it made, if it made one.
    fn run_one(&mut self, line: String) -> Option<usize> {
        pinnacle_rt::println!("terminal: {line}");
        let prompt = match &self.remote {
            Some(c) => c.name.clone(),
            None => self.cwd.clone(),
        };
        let mut entry = Entry::new(&prompt, &line);
        let all = pinnacle_records::pipe::words(&line);
        let mut words = all.iter().map(String::as_str);
        match words.next() {
            Some(own)
                if line.contains(['|', '>'])
                    && (matches!(own, "clear" | "help" | "local") || OWN.iter().any(|(c, _)| *c == own)) =>
            {
                entry.say(
                    alloc::format!("{own} is the terminal's own, and gives nothing to a | or >"),
                    true,
                );
                entry.exit = Some(2);
            }
            Some("clear") => {
                self.entries.retain(|e| e.run.is_some());
                save(&self.entries, &self.cwd);
                return None;
            }
            Some("help") => {
                for record in help() {
                    entry.push(Item::Record(record));
                }
                entry.exit = Some(0);
            }
            Some("history") => {
                let rows = self
                    .history
                    .iter()
                    .enumerate()
                    .map(|(i, l)| alloc::vec![alloc::format!("{:>4}", i + 1), l.clone()])
                    .collect();
                entry.push(Item::Record(Record::Table {
                    columns: alloc::vec![String::new(), String::new()],
                    rows,
                }));
                entry.exit = Some(0);
            }
            Some("pwd") if self.remote.is_none() => {
                entry.say(self.cwd.clone(), false);
                entry.exit = Some(0);
            }
            Some("cd") if self.remote.is_some() => {
                entry.say("cd is for this device: local comes back to it", true);
                entry.exit = Some(1);
            }
            Some("cd") => {
                let to = words.next().unwrap_or("~");
                let path = resolve(&self.cwd, command::home(), to);
                if is_folder(&path) {
                    self.cwd = path;
                    entry.exit = Some(0);
                } else {
                    let why = match fs::stat(&path) {
                        Some(_) => alloc::format!("{path} is a file, not a folder"),
                        None => alloc::format!("No folder {path}"),
                    };
                    entry.say(why, true);
                    entry.exit = Some(1);
                }
            }
            Some("local") => {
                let text = match self.remote.take() {
                    Some(c) => alloc::format!("Back on this device, from {}", c.name),
                    None => "Commands already run on this device".into(),
                };
                entry.push(Item::Record(Record::Text(text)));
                entry.exit = Some(0);
            }
            Some("remote") => {
                let wanted = line["remote".len()..].trim();
                let all = contacts();
                match all.iter().find(|c| c.name.eq_ignore_ascii_case(wanted)) {
                    Some(c) if !wanted.is_empty() => {
                        let text = alloc::format!(
                            "Commands now run on {}'s device, if it allows you: local comes back",
                            c.name
                        );
                        entry.push(Item::Record(Record::Text(text)));
                        entry.exit = Some(0);
                        self.remote = Some(c.clone());
                    }
                    _ => {
                        let rows = all.iter().map(|c| alloc::vec![c.name.clone()]).collect();
                        let text = if wanted.is_empty() {
                            "remote and a contact's name: your contacts are".into()
                        } else {
                            alloc::format!("No contact named “{wanted}”: your contacts are")
                        };
                        entry.push(Item::Record(Record::Text(text)));
                        entry.push(Item::Record(Record::Table {
                            columns: alloc::vec![String::new()],
                            rows,
                        }));
                        entry.exit = Some(u64::from(!wanted.is_empty()));
                    }
                }
            }
            _ if self.remote.is_some() => {
                let contact = self.remote.clone().unwrap();
                match start_remote(&contact, &line) {
                    Ok(run) => entry.run = Some(run),
                    Err(why) => {
                        entry.say(why, true);
                        entry.exit = Some(1);
                    }
                }
            }
            _ => match command::start_in(&line, &self.cwd).map(Run::from) {
                Ok(run) => entry.run = Some(run),
                Err(why) => {
                    entry.say(why, true);
                    entry.exit = Some(127);
                }
            },
        }
        if self.entries.len() >= MAX_ENTRIES
            && let Some(i) = self.entries.iter().position(|e| e.run.is_none())
        {
            self.entries.remove(i);
        }
        if entry.run.is_none() {
            pinnacle_rt::println!("terminal: {} ended ({:?})", entry.label(), entry.exit);
        }
        self.entries.push(entry);
        save(&self.entries, &self.cwd);
        Some(self.entries.len() - 1)
    }

    /// Stop: ends the newest command still running.
    fn stop(&mut self) -> bool {
        if let Some(entry) = self.entries.iter_mut().rev().find(|e| e.run.is_some()) {
            let run = entry.run.as_ref().unwrap();
            if run.stop() {
                entry.stopped = true;
                pinnacle_rt::println!("terminal: stopped {}", entry.label());
                return true;
            }
        }
        false
    }

    /// A key, typed or tapped: whether to draw again.
    fn key(&mut self, app: &App, key: Option<Key>, page: i32) -> bool {
        let Some(key) = key else { return false };
        if !matches!(key, Key::Tab | Key::PageUp | Key::PageDown) {
            self.hint.clear();
        }
        if !matches!(key, Key::PageUp | Key::PageDown | Key::Copy) {
            self.scroll = 0;
        }
        match key {
            Key::Char(c) => {
                let mut text = [0u8; 4];
                self.insert(c.encode_utf8(&mut text));
            }
            Key::Space => self.insert(" "),
            Key::Backspace => {
                let at = self.step(true);
                self.input.drain(at..self.cursor);
                self.cursor = at;
            }
            Key::Delete => {
                let to = self.step(false);
                self.input.drain(self.cursor..to);
            }
            Key::Left => self.cursor = self.step(true),
            Key::Right => self.cursor = self.step(false),
            Key::Home | Key::Ctrl('a') => self.cursor = 0,
            Key::End | Key::Ctrl('e') => self.cursor = self.input.len(),
            Key::Ctrl('u') => {
                self.input.drain(..self.cursor);
                self.cursor = 0;
            }
            Key::Ctrl('k') => self.input.truncate(self.cursor),
            Key::Ctrl('w') => {
                let before = self.input[..self.cursor].trim_end_matches(' ');
                let at = before.rfind(' ').map_or(0, |i| i + 1);
                self.input.drain(at..self.cursor);
                self.cursor = at;
            }
            Key::Ctrl('l') => {
                self.entries.retain(|e| e.run.is_some());
                save(&self.entries, &self.cwd);
            }
            Key::Up => self.recall(true),
            Key::Down => self.recall(false),
            Key::Tab => self.complete(),
            Key::Escape => {
                if let Some((_, draft)) = self.recall.take() {
                    self.set_input(draft);
                }
            }
            Key::PageUp => self.scroll += page,
            Key::PageDown => self.scroll -= page,
            Key::Enter => self.enter(),
            Key::Paste => app.paste(),
            // Ctrl+C: stops what runs; else drops the line typed; else
            // copies the last command's output.
            Key::Copy if self.stop() => {}
            Key::Copy if !self.input.is_empty() => {
                self.set_input(String::new());
                self.recall = None;
            }
            Key::Copy => {
                if let Some(entry) = self.entries.last() {
                    app.copy(&entry.text());
                }
                return false;
            }
            Key::Shift | Key::Ctrl(_) => return false,
        }
        true
    }

    /// What extra key `i` types.
    fn extra_key(i: usize) -> Key {
        match terminal::EXTRA_KEYS[i] {
            "Tab" => Key::Tab,
            "↑" => Key::Up,
            "↓" => Key::Down,
            "←" => Key::Left,
            "→" => Key::Right,
            s => Key::Char(s.chars().next().unwrap_or(' ')),
        }
    }

    /// The channels of the commands still running, and whose each is:
    /// (entry, stream).
    fn channels(&self) -> (Vec<&Channel>, Vec<(usize, usize)>) {
        let mut refs = Vec::new();
        let mut owners = Vec::new();
        for (i, entry) in self.entries.iter().enumerate() {
            let Some(run) = &entry.run else { continue };
            for (s, channel) in run.streams.iter().enumerate() {
                if let Some(c) = channel {
                    refs.push(c);
                    owners.push((i, s));
                }
            }
        }
        (refs, owners)
    }

    /// A stream of command `i` closed: once all have, it has ended (true).
    fn closed(&mut self, i: usize, stream: usize) -> bool {
        let entry = &mut self.entries[i];
        if stream < 2 {
            entry.flush(stream);
        }
        let Some(run) = &mut entry.run else { return false };
        run.streams[stream] = None;
        if run.streams.iter().all(Option::is_none) {
            entry.run = None;
            entry.asking = None;
            pinnacle_rt::println!("terminal: {} ended ({:?})", entry.label(), entry.exit);
            return true;
        }
        false
    }
}

/// How it says where its named controls are (`Screen::announce`), for
/// `cargo xtask` to tap them.
const ANNOUNCE: &str = "terminal: button ";

/// What a tap asked for.
#[derive(Clone, Copy, PartialEq)]
enum Tap {
    Stop,
    /// Answer `i` of the question waiting.
    Answer(usize),
    /// Extra key `i` (`terminal::EXTRA_KEYS`).
    Extra(usize),
}

/// What reached the session's `<canvas>`: a key as the DOM names it
/// (with Ctrl held, or not), a finger on it, the wheel.
enum Got {
    Key(String, bool),
    Down(f32),
    Move(f32),
    Up,
    Wheel(f32),
}

/// A key as the DOM names it, as the terminal takes it.
fn key_of(name: &str, ctrl: bool) -> Option<Key> {
    let mut chars = name.chars();
    let one = match (chars.next(), chars.next()) {
        (Some(c), None) => Some(c),
        _ => None,
    };
    Some(match (one, name) {
        (Some(c), _) if ctrl => Key::Ctrl(c.to_ascii_lowercase()),
        (Some(' '), _) => Key::Space,
        (Some('\n'), _) => Key::Enter,
        (Some(c), _) => Key::Char(c),
        (None, "Enter") => Key::Enter,
        (None, "Backspace") => Key::Backspace,
        (None, "Delete") => Key::Delete,
        (None, "ArrowLeft") => Key::Left,
        (None, "ArrowRight") => Key::Right,
        (None, "ArrowUp") => Key::Up,
        (None, "ArrowDown") => Key::Down,
        (None, "Home") => Key::Home,
        (None, "End") => Key::End,
        (None, "Tab") => Key::Tab,
        (None, "Escape") => Key::Escape,
        (None, "PageUp") => Key::PageUp,
        (None, "PageDown") => Key::PageDown,
        _ => return None,
    })
}

fn css(c: Color) -> String {
    alloc::format!("#{:06x}", c.0 & 0xff_ffff)
}

/// What the page around the session shows, a signal each: a part that
/// changes is built again alone, and a press on another is not lost under
/// the finger.
struct Chrome {
    place: Signal<String>,
    running: Signal<bool>,
    options: Signal<Vec<String>>,
    /// How many extra keys there is room for while the on-screen keyboard
    /// is up; none while it is down.
    keys: Signal<usize>,
}

/// Sets `s` to `v` when it differs. Returns whether it did.
fn update<T: Clone + PartialEq + 'static>(s: &Signal<T>, v: T) -> bool {
    let changed = s.get_untracked() != v;
    if changed {
        s.set(v);
    }
    changed
}

/// A key of the terminal's own (Stop, an answer, an extra key), named for
/// `cargo xtask`. Not a `<button>`: a tap on one leaves the focus on the
/// session, and the keyboard up.
fn key(label: String, name: String, tap: Tap, style: &str, tapped: &Signal<Option<Tap>>) -> View {
    let tapped = tapped.clone();
    el("div")
        .attr("role", "button")
        .attr("data-name", name)
        .attr(
            "style",
            alloc::format!(
                "font-family: monospace; min-width: 0; padding: 8px 6px; text-align: center; \
                 border-radius: 5px; color: {}; background: {}; {style}",
                css(FOREGROUND),
                css(BACKGROUND)
            ),
        )
        .on("click", move |_| tapped.set(Some(tap)))
        .child(label)
        .into_view()
}

/// The header (where commands run, Stop while one does), the session, a
/// question's answers, and the keys the on-screen keyboard lacks. Mounted
/// once: what is around the session follows `chrome`, so the session keeps
/// the focus (and the keyboard stays up) as it changes.
fn page(
    chrome: &Chrome,
    revision: &Signal<u32>,
    got: &Rc<RefCell<Vec<Got>>>,
    tapped: &Signal<Option<Tap>>,
) -> View {
    let (place, stop, t) = (chrome.place.clone(), chrome.running.clone(), tapped.clone());
    let header = el("div")
        .attr(
            "style",
            alloc::format!(
                "flex: none; display: flex; align-items: center; gap: 8px; padding: 6px 12px; \
                 min-height: 36px; background: {}; border-bottom: 1px solid {}; font-family: monospace",
                css(BAR),
                css(RULE)
            ),
        )
        .child(
            el("span")
                .attr("style", alloc::format!("color: {}", css(FOREGROUND)))
                .child("terminal"),
        )
        .child(
            el("span")
                .attr(
                    "style",
                    "flex: 1; min-width: 0; color: var(--m-text-dim); white-space: nowrap; overflow: hidden",
                )
                .child(move || place.get()),
        )
        .child(move || {
            stop.get().then(|| {
                let bad = css(theme::BAD);
                key(
                    "■ Stop".into(),
                    "stop".into(),
                    Tap::Stop,
                    &alloc::format!("color: {bad}; border: 1px solid {bad}"),
                    &t,
                )
            })
        });
    let event = |f: fn(&pinnacle_view::Event) -> Got| {
        let got = got.clone();
        move |e: &pinnacle_view::Event| {
            got.borrow_mut().push(f(e));
            e.prevent_default();
        }
    };
    let revision = revision.clone();
    let session = el("canvas")
        .attr("data-name", "session")
        .attr("role", "textbox")
        .attr("tabindex", "0")
        .attr("data-revision", move || alloc::format!("{}", revision.get()))
        .attr("style", "flex: 1; min-height: 0; display: block")
        .prop_bool("@focus", true)
        .on(
            "keydown",
            event(|e| Got::Key(e.key.clone().unwrap_or_default(), e.ctrl)),
        )
        .on("pointerdown", event(|e| Got::Down(e.y)))
        .on("pointermove", event(|e| Got::Move(e.y)))
        .on("pointerup", event(|_| Got::Up))
        .on("wheel", event(|e| Got::Wheel(e.dy)));
    let (answers, t) = (chrome.options.clone(), tapped.clone());
    let answers = move || {
        let options = answers.get();
        (!options.is_empty()).then(|| {
            let mut row = el("div").attr("style", "flex: none; display: flex; gap: 6px; padding: 6px 12px");
            for (i, option) in options.iter().enumerate() {
                row = row.child(key(
                    alloc::format!("{}) {option}", i + 1),
                    alloc::format!("answer-{i}"),
                    Tap::Answer(i),
                    &alloc::format!(
                        "flex: 1; border: 1px solid {}; background: {}",
                        css(QUESTION),
                        css(BAR)
                    ),
                    &t,
                ));
            }
            row
        })
    };
    let (extra, t) = (chrome.keys.clone(), tapped.clone());
    let extra = move || {
        let keys = extra.get();
        (keys > 0).then(|| {
            let mut row = el("div").attr(
                "style",
                alloc::format!(
                    "flex: none; display: flex; gap: 4px; padding: 4px; background: {}",
                    css(BAR)
                ),
            );
            for (i, label) in terminal::EXTRA_KEYS.iter().take(keys).enumerate() {
                row = row.child(key(
                    String::from(*label),
                    alloc::format!("key-{i}"),
                    Tap::Extra(i),
                    "flex: 1; border: 0",
                    &t,
                ));
            }
            row
        })
    };
    el("main")
        .attr(
            "style",
            alloc::format!(
                "height: 100vh; display: flex; flex-direction: column; background: {}",
                css(BACKGROUND)
            ),
        )
        .child(header)
        .child(session)
        .child(answers)
        .child(extra)
        .into_view()
}

/// Takes what a signal holds, leaving it empty.
fn take<T: Clone + 'static>(s: &Signal<Option<T>>) -> Option<T> {
    let v = s.get_untracked();
    if v.is_some() {
        s.set(None);
    }
    v
}

#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
    let mut app = App::new("Terminal");
    let (entries, cwd) = load();
    let cwd = cwd
        .filter(|c| is_folder(c))
        .unwrap_or_else(|| command::home().into());
    let history = entries.iter().map(|e| e.line.clone()).collect();
    let mut term = Terminal {
        entries,
        input: String::new(),
        cursor: 0,
        history,
        recall: None,
        hint: Vec::new(),
        cwd,
        scroll: 0,
        drag: None,
        remote: None,
    };
    let mut screen = Screen::new(app.width, app.height);
    let revision = signal(0u32);
    let tapped: Signal<Option<Tap>> = signal(None);
    let got: Rc<RefCell<Vec<Got>>> = Rc::default();
    // Where the session is in the window, from the last frame that drew it.
    let mut area = Rect::new(0, 0, 0, 0);
    let chrome = Chrome {
        place: signal(String::new()),
        running: signal(false),
        options: signal(Vec::new()),
        keys: signal(0),
    };
    screen.mount(page(&chrome, &revision, &got, &tapped));
    let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    let mut redraw = true;
    let mut all = true;
    let mut ready = false;
    loop {
        // What is around the session follows the terminal; only what changed
        // is drawn (all of it after a resize).
        // Drawn at least once: a press may have brought the keyboard up,
        // which only drawing does.
        let mut drawn_once = false;
        loop {
            let place = match &term.remote {
                Some(c) => alloc::format!("— on {}'s device", c.name),
                None => alloc::format!("— {}", term.cwd),
            };
            let keys = if screen.keyboard_shown() {
                terminal::extra_keys(app.width as i32)
            } else {
                0
            };
            let changed = update(&chrome.place, place)
                | update(&chrome.running, term.running())
                | update(&chrome.options, term.options().to_vec())
                | update(&chrome.keys, keys);
            if !changed && drawn_once && !redraw && !all {
                break;
            }
            if redraw {
                revision.set(revision.get_untracked().wrapping_add(1));
            }
            let drawn = screen.draw_with(&mut app.canvas(), all, &mut |name, canvas, r| {
                if name == "session" {
                    area = r;
                    term.draw(canvas, r);
                }
            });
            if all {
                app.present_all();
                screen.announce(ANNOUNCE);
            } else if let Some(r) = drawn {
                app.present(r);
            }
            redraw = false;
            all = false;
            drawn_once = true;
        }
        if !ready {
            pinnacle_rt::println!("terminal: ready");
            ready = true;
        }
        let (refs, owners) = term.channels();
        let event = app.wait(&refs, &mut buffer, None);
        drop(refs);
        let scroll_by = area.height - theme::mono().line_height;
        match event {
            Event::Channel { index, len, handles } => {
                let (i, stream) = owners[index];
                if stream == 2 {
                    if let Some(code) = buffer.get(..8) {
                        term.entries[i].exit = Some(u64::from_le_bytes(code.try_into().unwrap()));
                    }
                } else {
                    term.entries[i].output(stream, &buffer[..len.min(buffer.len())], handles);
                }
                redraw = true;
            }
            Event::ChannelClosed { index } => {
                let (i, stream) = owners[index];
                if term.closed(i, stream) {
                    term.ended(i);
                    save(&term.entries, &term.cwd);
                }
                redraw = true;
            }
            Event::Input(e) => {
                screen.input(&e);
                match screen.clipboard() {
                    Some(Clipboard::Paste) => app.paste(),
                    Some(Clipboard::Copy) => redraw |= term.key(&app, Some(Key::Copy), scroll_by),
                    None => {}
                }
                match take(&tapped) {
                    Some(Tap::Stop) => redraw |= term.stop(),
                    Some(Tap::Answer(i)) => {
                        if let Some(text) = term.options().get(i).cloned() {
                            term.answer(&text);
                            redraw = true;
                        }
                    }
                    Some(Tap::Extra(i)) => redraw |= term.key(&app, Some(Terminal::extra_key(i)), scroll_by),
                    None => {}
                }
                let got: Vec<Got> = got.borrow_mut().drain(..).collect();
                for g in got {
                    match g {
                        Got::Key(name, ctrl) => redraw |= term.key(&app, key_of(&name, ctrl), scroll_by),
                        Got::Down(y) => term.drag = Some(((y * SCALE) as i32, false)),
                        // A finger that wanders a little still taps.
                        Got::Move(y) => {
                            let y = (y * SCALE) as i32;
                            if let Some((last, moved)) = term.drag
                                && (moved || (y - last).abs() > 8)
                            {
                                term.scroll += y - last;
                                term.drag = Some((y, true));
                                redraw = true;
                            }
                        }
                        Got::Up => term.drag = None,
                        Got::Wheel(dy) => {
                            term.scroll -= (dy * SCALE) as i32;
                            redraw = true;
                        }
                    }
                }
            }
            Event::Clipboard(text) => {
                // One line: what is pasted is a command, not a script.
                term.insert(text.lines().next().unwrap_or(""));
                redraw = true;
            }
            Event::Shown(true) | Event::Resized => {
                screen.resize(app.width, app.height);
                all = true;
            }
            Event::Closed => {
                for entry in &term.entries {
                    if let Some(run) = &entry.run {
                        run.stop();
                    }
                }
                save(&term.entries, &term.cwd);
                return 0;
            }
            _ => {}
        }
    }
}