garage44.eu/jeroen/pinnacle

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

.. /ui/src/lib.rs

raw

//! Apps on Pinnacle: a window from the display server, drawn into directly
//! (shared memory), with only "this rectangle changed" sent back; input as
//! events; and the system's look (`theme`).
//!
//! The protocol is small messages on one channel to the `display` service:
//! [`protocol`] has their layout.

#![no_std]

extern crate alloc;

pub mod access;
pub mod bluetooth;
pub mod brightness;
pub mod command;
pub mod confirm;
pub mod fien;
pub mod icons;
pub mod keyboard;
pub mod model;
pub mod p2p;
pub mod phone;
pub mod remote;
pub mod sound;
pub mod store;
pub mod theme;
pub mod updates;
pub mod verbs;

pub use pinnacle_layout as layout;

use alloc::vec::Vec;
use pinnacle_gfx::{Canvas, Rect};
use pinnacle_rt::abi::InputEvent;
use pinnacle_rt::{Channel, Memory, Received};

/// Messages between an app and the display server: a kind byte, three
/// bytes of padding, then the body.
pub mod protocol {
    /// App → display: "I am this app" (body: its task id as u64, then the
    /// title, UTF-8).
    pub const HELLO: u8 = 1;
    /// App → display: a rectangle of the window changed (body: x, y,
    /// width, height as i32).
    pub const DAMAGE: u8 = 2;
    /// App → display: start the app `name` (body: the name).
    pub const LAUNCH: u8 = 3;
    /// App → display: turn the screen a quarter, as the device's orientation
    /// sensor would (no body).
    pub const TURN: u8 = 4;
    /// App → display: put the body (UTF-8) on the clipboard.
    pub const COPY: u8 = 5;
    /// App → display: send me the clipboard ([`CLIPBOARD`]).
    pub const PASTE: u8 = 6;
    /// Any program → display: a notification (body: the app that shows it,
    /// its title and its text, a line each). Shown as a banner unless that
    /// app is in front; a tap on the banner brings the app.
    pub const NOTIFY: u8 = 7;
    /// Any program → display: is the app `name` running (body: the name)?
    /// Answered with [`RUNNING_IS`]. The updates service asks before it
    /// changes an app's files.
    pub const RUNNING: u8 = 8;
    /// App → display: its UI tree, as [`crate::access::encode`] writes
    /// it, sent with a present while the display asked ([`WANT_TREE`]).
    pub const TREE: u8 = 9;
    /// Settings → display: the preferences changed; read them again and
    /// tell every app (no body).
    pub const PREFERENCES_CHANGED: u8 = 10;
    /// App → display: lock the screen now, if there is a PIN (no body).
    pub const LOCK: u8 = 0x40;
    /// Display → app: your window (body: width, height as u32), with its
    /// memory as the message's one handle. Sent again when the screen
    /// changes size: the app takes the new window and lets the old one go.
    pub const WINDOW: u8 = 0x81;
    /// Display → app: input, in window coordinates (body: an InputEvent).
    pub const INPUT: u8 = 0x82;
    /// Display → app: shown (body: 1) or hidden (0).
    pub const SHOWN: u8 = 0x83;
    /// Display → app: the clipboard (body: UTF-8), as [`PASTE`] asked.
    pub const CLIPBOARD: u8 = 0x84;
    /// Display → program: whether the app [`RUNNING`] asked about is (body:
    /// 1) or is not (0).
    pub const RUNNING_IS: u8 = 0x88;
    /// Display → app: the person's preferences (body: as
    /// [`crate::access::Preferences::to_bytes`]), before the first window
    /// and whenever they change.
    pub const PREFERENCES: u8 = 0x89;
    /// Display → app: send your UI tree with each present from now on
    /// (body: 1), or stop (0).
    pub const WANT_TREE: u8 = 0x8a;
}

pub fn message(kind: u8, body: &[u8]) -> Vec<u8> {
    let mut m = alloc::vec![kind, 0, 0, 0];
    m.extend_from_slice(body);
    m
}

pub fn rect_bytes(r: Rect) -> [u8; 16] {
    let mut b = [0; 16];
    for (i, v) in [r.x, r.y, r.width, r.height].into_iter().enumerate() {
        b[i * 4..i * 4 + 4].copy_from_slice(&v.to_le_bytes());
    }
    b
}

pub fn rect_from(b: &[u8]) -> Option<Rect> {
    let v = |i: usize| Some(i32::from_le_bytes(b.get(i * 4..i * 4 + 4)?.try_into().ok()?));
    Some(Rect::new(v(0)?, v(1)?, v(2)?, v(3)?))
}

/// What an app waits for.
pub enum Event {
    Input(InputEvent),
    /// The app came to the front (true) or left it.
    Shown(bool),
    /// The window changed size (the screen turned, or changed): `width` and
    /// `height` are new, the window is blank, and the app draws it afresh.
    Resized,
    /// The deadline passed.
    Timeout,
    /// A message on another of the channels waited on (`wait`): its index
    /// among them, its length in the buffer given, and the handles it
    /// carried.
    Channel {
        index: usize,
        len: usize,
        handles: Vec<pinnacle_rt::Handle>,
    },
    /// Another channel waited on closed.
    ChannelClosed {
        index: usize,
    },
    /// What is on the clipboard, as [`App::paste`] asked.
    Clipboard(alloc::string::String),
    /// The person's preferences changed (`access::current()` has them):
    /// the language, the text size, contrast. Draw again, in the new
    /// language.
    Preferences,
    /// The display server is gone.
    Closed,
}

/// An app's window.
pub struct App {
    display: Channel,
    memory: Memory,
    pub width: u32,
    pub height: u32,
    pub shown: bool,
}

/// A WINDOW message's size and memory.
fn window(message: &[u8], handles: &mut Vec<pinnacle_rt::Handle>) -> Option<(u32, u32, Memory)> {
    if message.len() < 12 || message[0] != protocol::WINDOW || handles.is_empty() {
        return None;
    }
    let width = u32::from_le_bytes(message[4..8].try_into().unwrap());
    let height = u32::from_le_bytes(message[8..12].try_into().unwrap());
    let memory = Memory::map(handles.remove(0))?;
    Some((width, height, memory))
}

impl App {
    /// Connects to the display server and gets a window.
    pub fn new(title: &str) -> App {
        let display = loop {
            if let Some(channel) = pinnacle_rt::connect("display") {
                break channel;
            }
            pinnacle_rt::sleep(10);
        };
        let mut hello = pinnacle_rt::pid().to_le_bytes().to_vec();
        hello.extend_from_slice(title.as_bytes());
        display.send(&message(protocol::HELLO, &hello), Vec::new());
        let mut buffer = [0u8; 64];
        loop {
            match display.receive(&mut buffer) {
                // The preferences come before the window, so the first
                // frame is in the person's language and size.
                Received::Message { len, .. } if len >= 12 && buffer[0] == protocol::PREFERENCES => {
                    if let Some(p) = access::Preferences::from_bytes(&buffer[4..len]) {
                        access::set(p);
                    }
                }
                Received::Message { len, .. } if len >= 5 && buffer[0] == protocol::WANT_TREE => {
                    access::want_tree(buffer[4] != 0);
                }
                Received::Message { len, mut handles, .. } => {
                    let (width, height, memory) =
                        window(&buffer[..len], &mut handles).expect("the display server gave no window");
                    return App {
                        display,
                        memory,
                        width,
                        height,
                        shown: true,
                    };
                }
                _ => panic!("the display server gave no window"),
            }
        }
    }

    pub fn canvas(&mut self) -> Canvas<'_> {
        let (width, height) = (self.width, self.height);
        Canvas::new(self.memory.pixels(), width, height)
    }

    /// Tells the display server `rect` changed.
    pub fn present(&self, rect: Rect) {
        self.display
            .send(&message(protocol::DAMAGE, &rect_bytes(rect)), Vec::new());
        if let Some(tree) = access::take_tree() {
            self.display.send(&message(protocol::TREE, &tree), Vec::new());
        }
    }

    /// Tells the display server the whole window changed.
    pub fn present_all(&self) {
        self.present(Rect::new(0, 0, self.width as i32, self.height as i32));
    }

    /// Asks the display server to turn the screen a quarter.
    pub fn turn(&self) {
        self.display.send(&message(protocol::TURN, &[]), Vec::new());
    }

    /// Tells the display server the preferences changed (Settings, after
    /// writing them): it reads them again and tells every app.
    pub fn preferences_changed(&self) {
        self.display
            .send(&message(protocol::PREFERENCES_CHANGED, &[]), Vec::new());
    }

    /// Asks the display server to lock the screen.
    pub fn lock(&self) {
        self.display.send(&message(protocol::LOCK, &[]), Vec::new());
    }

    /// Puts `text` on the clipboard, which every app shares.
    pub fn copy(&self, text: &str) {
        self.display
            .send(&message(protocol::COPY, clip(text).as_bytes()), Vec::new());
    }

    /// Asks for what is on the clipboard: it comes as [`Event::Clipboard`].
    pub fn paste(&self) {
        self.display.send(&message(protocol::PASTE, &[]), Vec::new());
    }

    /// Asks the display server to start app `name`.
    pub fn launch(&self, name: &str) {
        self.display
            .send(&message(protocol::LAUNCH, name.as_bytes()), Vec::new());
    }

    /// What a message from the display server means for the app, if
    /// anything: a new window is taken here (the old one given back).
    fn display_message(&mut self, message: &[u8], handles: &mut Vec<pinnacle_rt::Handle>) -> Option<Event> {
        if message.len() < 4 {
            return None;
        }
        match message[0] {
            protocol::INPUT => InputEvent::from_bytes(&message[4..]).map(Event::Input),
            protocol::SHOWN => {
                self.shown = message.get(4) != Some(&0);
                Some(Event::Shown(self.shown))
            }
            protocol::CLIPBOARD => Some(Event::Clipboard(
                alloc::string::String::from_utf8_lossy(&message[4..]).into_owned(),
            )),
            protocol::PREFERENCES => {
                let p = access::Preferences::from_bytes(&message[4..])?;
                access::set(p).then_some(Event::Preferences)
            }
            // The display server follows it with SHOWN, which has the app
            // draw everything again, and its tree go with the present.
            protocol::WANT_TREE => {
                access::want_tree(message.get(4) == Some(&1));
                None
            }
            protocol::WINDOW => {
                let (width, height, memory) = window(message, handles)?;
                core::mem::replace(&mut self.memory, memory).unmap();
                (self.width, self.height) = (width, height);
                Some(Event::Resized)
            }
            _ => None,
        }
    }

    /// Waits for the next event, until `deadline` (ms since boot) if given.
    pub fn next_event(&mut self, deadline: Option<u64>) -> Event {
        let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
        loop {
            match pinnacle_rt::receive(&[&self.display], &mut buffer, deadline) {
                Received::Message { len, mut handles, .. } => {
                    if let Some(event) = self.display_message(&buffer[..len], &mut handles) {
                        return event;
                    }
                }
                Received::Timeout => return Event::Timeout,
                Received::Closed { .. } => return Event::Closed,
            }
        }
    }

    /// Waits for the next event from the display or from any of `others`,
    /// whose messages land in `buffer`.
    pub fn wait(&mut self, others: &[&Channel], buffer: &mut [u8], deadline: Option<u64>) -> Event {
        let mut own = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
        loop {
            let mut all: Vec<&Channel> = alloc::vec![&self.display];
            all.extend_from_slice(others);
            let got = pinnacle_rt::receive(&all, buffer, deadline);
            drop(all);
            match got {
                Received::Message {
                    index: 0,
                    len,
                    mut handles,
                } => {
                    let len = len.min(own.len());
                    own[..len].copy_from_slice(&buffer[..len]);
                    if let Some(event) = self.display_message(&own[..len], &mut handles) {
                        return event;
                    }
                }
                Received::Message { index, len, handles } => {
                    return Event::Channel {
                        index: index - 1,
                        len,
                        handles,
                    };
                }
                Received::Timeout => return Event::Timeout,
                Received::Closed { index: 0 } => return Event::Closed,
                Received::Closed { index } => return Event::ChannelClosed { index: index - 1 },
            }
        }
    }
}

/// Splits `text` into lines no wider than `width` in `font`, at spaces where
/// it can.
pub fn wrap(font: &pinnacle_gfx::Font, text: &str, width: i32) -> Vec<alloc::string::String> {
    let mut lines = Vec::new();
    let mut line = alloc::string::String::new();
    for word in text.split(' ') {
        let candidate = if line.is_empty() {
            alloc::string::String::from(word)
        } else {
            alloc::format!("{line} {word}")
        };
        if font.measure(&candidate) <= width || line.is_empty() {
            line = candidate;
        } else {
            lines.push(core::mem::take(&mut line));
            line = word.into();
        }
    }
    lines.push(line);
    lines
}

/// `text` cut, at a character's edge, to what one message carries.
fn clip(text: &str) -> &str {
    let mut end = text.len().min(pinnacle_rt::abi::MAX_MESSAGE - 8);
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    &text[..end]
}

/// Sends a notification through `display` (a channel to the display
/// server, which a program without a window connects too): `app` is the
/// app a tap on it opens.
pub fn notify(display: &Channel, app: &str, title: &str, text: &str) {
    let body = alloc::format!("{app}\n{title}\n{text}");
    display.send(&message(protocol::NOTIFY, clip(&body).as_bytes()), Vec::new());
}

/// Whether the app `name` is running, as `display` (a channel to the
/// display server) says within a second; running when it does not say.
pub fn running(display: &Channel, name: &str) -> bool {
    display.send(&message(protocol::RUNNING, name.as_bytes()), Vec::new());
    let mut buffer = [0u8; 8];
    let deadline = pinnacle_rt::time() + 1000;
    loop {
        match pinnacle_rt::receive(&[display], &mut buffer, Some(deadline)) {
            Received::Message { len, .. } if len >= 5 && buffer[0] == protocol::RUNNING_IS => {
                return buffer[4] != 0;
            }
            Received::Message { .. } => continue,
            _ => return true,
        }
    }
}