garage44.eu/jeroen/pinnacle

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

.. /rt/src/output.rs

raw

//! A command's output as records (`pinnacle_records`): what a program the
//! terminal starts sends it, instead of bytes. Started some other way (no
//! start message, or stdout the console), the same calls print to the
//! console, so a command runs anywhere.

use alloc::string::String;
use alloc::vec::Vec;

use crate::{Channel, Handle, Received};
pub use pinnacle_records::{AskKind, Record, start::Start};

/// Where a command's records go, where answers to its questions come
/// from, and what it was started with.
pub struct Output {
    channel: Option<Channel>,
    input: Option<Channel>,
    pub args: Vec<String>,
    pub env: Vec<(String, String)>,
    /// Handles the start message carried beyond its streams, in order:
    /// what a starter gives a command besides its input and output (the
    /// agent's gatekeeper gets its grants so).
    pub extra: Vec<Handle>,
}

impl Output {
    /// Reads the start message on handle 1 when `argument` says there is
    /// one (`abi::STD_START`): its arguments, stdout when it is a channel
    /// (records go there), and stdin (answers come there). Call it once, at
    /// entry.
    pub fn start(argument: u64) -> Output {
        let mut out = Output {
            channel: None,
            input: None,
            args: Vec::new(),
            env: Vec::new(),
            extra: Vec::new(),
        };
        if argument != crate::abi::STD_START {
            return out;
        }
        // SAFETY: a program started with STD_START is given handle 1 for
        // this message alone.
        let first = Channel(unsafe { Handle::from_raw(1) });
        let mut buffer = alloc::vec![0u8; crate::abi::MAX_MESSAGE];
        if let Received::Message { len, handles, .. } = first.receive(&mut buffer)
            && let Some(start) = Start::decode(&buffer[..len])
        {
            let mut handles: Vec<Option<Handle>> = handles.into_iter().map(Some).collect();
            let mut take = |n: usize| {
                let i = start.handle_index(n)?;
                handles.get_mut(i)?.take().map(Channel)
            };
            out.input = take(0);
            out.channel = take(1);
            out.args = start.args.clone();
            if let Some(i) = start.handle_index(2) {
                // Stderr is not kept, but is not one of the extras either.
                handles[i] = None;
            }
            out.extra = handles.into_iter().flatten().collect();
            // More handles than one message carries come in messages after
            // it, as many as `EXTRA_MESSAGES` says.
            let more = start
                .env
                .iter()
                .find(|(k, _)| k == "EXTRA_MESSAGES")
                .and_then(|(_, v)| v.parse::<usize>().ok())
                .unwrap_or(0);
            for _ in 0..more {
                match first.receive(&mut buffer) {
                    Received::Message { handles, .. } => out.extra.extend(handles),
                    _ => break,
                }
            }
            out.env = start.env;
        }
        out
    }

    /// Asks whoever is at the terminal (`options` for a choice) and waits
    /// for the answer. `None` when there is no terminal to ask, or it went.
    pub fn ask(&self, kind: AskKind, prompt: &str, options: &[&str]) -> Option<String> {
        let (channel, input) = (self.channel.as_ref()?, self.input.as_ref()?);
        let id = crate::time() as u32;
        let ask = Record::Ask {
            id,
            kind,
            prompt: prompt.into(),
            options: options.iter().map(|&o| o.into()).collect(),
        };
        channel.send(&ask.encode()?, Vec::new());
        let mut buffer = alloc::vec![0u8; crate::abi::MAX_MESSAGE];
        loop {
            match input.receive(&mut buffer) {
                Received::Message { len, .. } => {
                    if let Some(Record::Answer { id: answered, text }) = Record::decode(&buffer[..len])
                        && answered == id
                    {
                        return Some(text);
                    }
                }
                _ => return None,
            }
        }
    }

    /// The next message on stdin, with its handles: in a pipeline, the
    /// command before's output. `None` once it has closed, or with no
    /// stdin.
    pub fn receive(&self, buffer: &mut [u8]) -> Option<(usize, Vec<Handle>)> {
        match self.input.as_ref()?.receive(buffer) {
            Received::Message { len, handles, .. } => Some((len, handles)),
            _ => None,
        }
    }

    /// A message sent on as it came, with its handles: a record a filter
    /// does not change. False when there is no channel, or it went.
    pub fn forward(&self, message: &[u8], handles: Vec<Handle>) -> bool {
        self.channel.as_ref().is_some_and(|c| c.send(message, handles))
    }

    /// An image of `width` × `height` pixels (0x00RRGGBB, a row after
    /// another), drawn in the output: its pixels go across as shared
    /// memory, not in the message.
    pub fn image(&self, width: u32, height: u32, pixels: &[u32]) -> bool {
        let Some(channel) = &self.channel else {
            crate::println!("(an image, {width}×{height})");
            return true;
        };
        let count = (width * height) as usize;
        let Some(mut memory) = crate::Memory::new(count * 4) else {
            return false;
        };
        memory.pixels()[..count].copy_from_slice(&pixels[..count]);
        let record = Record::Image { width, height };
        let sent = channel.send(&record.encode().unwrap(), alloc::vec![memory.handle]);
        crate::unmap(memory.address);
        sent
    }

    /// Sends a record; a text or table too large for one message goes as
    /// several. False when the terminal is gone.
    pub fn send(&self, record: &Record) -> bool {
        let Some(channel) = &self.channel else {
            print(record);
            return true;
        };
        match record.encode() {
            Some(bytes) => channel.send(&bytes, Vec::new()),
            None => {
                let parts = match record {
                    Record::Text(text) => pinnacle_records::texts(text),
                    Record::Table { columns, rows } => {
                        let columns: Vec<&str> = columns.iter().map(String::as_str).collect();
                        pinnacle_records::tables(&columns, rows)
                    }
                    _ => return false,
                };
                parts
                    .iter()
                    .all(|p| p.encode().is_some_and(|b| channel.send(&b, Vec::new())))
            }
        }
    }

    pub fn text(&self, text: &str) -> bool {
        self.send(&Record::text(text))
    }

    pub fn table(&self, columns: &[&str], rows: Vec<Vec<String>>) -> bool {
        self.send(&Record::Table {
            columns: columns.iter().map(|&c| c.into()).collect(),
            rows,
        })
    }

    /// The last record: how it ended. Returns `code`, for `main` to return.
    pub fn status(&self, code: u64, summary: &str) -> u64 {
        self.send(&Record::Status {
            code,
            summary: summary.into(),
        });
        code
    }
}

/// A record on the console, as plain lines.
fn print(record: &Record) {
    match record {
        Record::Text(text) => crate::println!("{text}"),
        Record::Table { columns, rows } => {
            crate::println!("{}", columns.join("\t"));
            for row in rows {
                crate::println!("{}", row.join("\t"));
            }
        }
        Record::Status { code, summary } => crate::println!("[{code}] {summary}"),
        other => crate::println!("{other:?}"),
    }
}