garage44.eu/jeroen/pinnacle

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

.. /ui/src/access.rs

raw

//! How the person wants the system to read: their language, the size of
//! text, contrast, and the screen reader; and the description of an app's
//! interface the screen reader reads (the UI tree).
//!
//! The display server keeps the preferences (the language in
//! `system:/locale/language`, which any program may read, the rest in
//! `/settings/access`, which only system programs reach) and tells every
//! app with a window: before its first window, and again when Settings
//! changes one ([`crate::protocol::PREFERENCES`]). An app reads them here.
//!
//! The UI tree is what an app's interface is made of, as a list of nodes
//! in reading order, each with its role, its name, its state and where it
//! is. An app built from views makes it from its view's elements by
//! itself (`pinnacle-view`); the display server asks for it while the
//! screen reader is on, and the agent's act protocol is to read the same
//! tree. It goes to the display server after the app's next present.

use alloc::string::String;
use alloc::vec::Vec;
use core::cell::UnsafeCell;
use core::sync::atomic::{AtomicBool, AtomicU16, Ordering};

use pinnacle_gfx::Rect;
use pinnacle_locale::Language;

/// The speech service, which says aloud what the screen reader reads.
pub const SPEECH: &str = "system-speech";

/// Where the preferences other than the language are kept.
pub const ACCESS_PATH: &str = "system:/settings/access";

/// The text sizes Settings offers, in percent.
pub const TEXT_SIZES: [u16; 4] = [100, 125, 150, 200];

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Preferences {
    pub language: Language,
    /// Text, and the interface around it, at this many percent.
    pub text_size: u16,
    /// Black ground, white text, strong borders.
    pub high_contrast: bool,
    /// The screen reader says what is touched, and a double tap acts.
    pub reader: bool,
}

impl Default for Preferences {
    fn default() -> Preferences {
        Preferences {
            language: Language::English,
            text_size: 100,
            high_contrast: false,
            reader: false,
        }
    }
}

impl Preferences {
    /// As a [`crate::protocol::PREFERENCES`] message's body carries them.
    pub fn to_bytes(self) -> [u8; 8] {
        let size = self.text_size.to_le_bytes();
        [
            self.language as u8,
            size[0],
            size[1],
            u8::from(self.high_contrast),
            u8::from(self.reader),
            0,
            0,
            0,
        ]
    }

    pub fn from_bytes(b: &[u8]) -> Option<Preferences> {
        let b: &[u8; 8] = b.get(..8)?.try_into().ok()?;
        Some(Preferences {
            language: if b[0] == 1 {
                Language::Dutch
            } else {
                Language::English
            },
            text_size: u16::from_le_bytes([b[1], b[2]]).clamp(50, 400),
            high_contrast: b[3] != 0,
            reader: b[4] != 0,
        })
    }

    /// As `/settings/access` keeps them, a `name=value` line each.
    pub fn access_text(self) -> String {
        alloc::format!(
            "text-size={}\ncontrast={}\nreader={}\n",
            self.text_size,
            if self.high_contrast { "high" } else { "normal" },
            if self.reader { "on" } else { "off" }
        )
    }

    /// Reads `/settings/access` and the language file: what a system
    /// program (the display server) starts from.
    pub fn read() -> Preferences {
        let mut p = Preferences::default();
        if let Some(code) = pinnacle_rt::fs::read_string(pinnacle_locale::LANGUAGE_PATH) {
            p.language = Language::from_code(&code).unwrap_or(Language::English);
        }
        if let Some(text) = pinnacle_rt::fs::read_string(ACCESS_PATH) {
            for line in text.lines() {
                match line.split_once('=') {
                    Some(("text-size", v)) => p.text_size = v.trim().parse().unwrap_or(100),
                    Some(("contrast", v)) => p.high_contrast = v.trim() == "high",
                    Some(("reader", v)) => p.reader = v.trim() == "on",
                    _ => {}
                }
            }
        }
        p
    }

    /// Writes them where [`Preferences::read`] finds them.
    pub fn write(self) -> bool {
        let _ = pinnacle_rt::fs::create_dir("system:/locale");
        pinnacle_rt::fs::write(pinnacle_locale::LANGUAGE_PATH, self.language.code().as_bytes())
            && pinnacle_rt::fs::write(ACCESS_PATH, self.access_text().as_bytes())
    }
}

static TEXT_SIZE: AtomicU16 = AtomicU16::new(100);
static CONTRAST: AtomicBool = AtomicBool::new(false);
static READER: AtomicBool = AtomicBool::new(false);

/// The preferences this program was told.
pub fn current() -> Preferences {
    Preferences {
        language: pinnacle_locale::current(),
        text_size: TEXT_SIZE.load(Ordering::Relaxed),
        high_contrast: CONTRAST.load(Ordering::Relaxed),
        reader: READER.load(Ordering::Relaxed),
    }
}

/// Takes the preferences the display server sent; whether they changed.
pub fn set(p: Preferences) -> bool {
    let changed = current() != p;
    pinnacle_locale::set(p.language);
    TEXT_SIZE.store(p.text_size, Ordering::Relaxed);
    CONTRAST.store(p.high_contrast, Ordering::Relaxed);
    READER.store(p.reader, Ordering::Relaxed);
    changed
}

/// Before the display server says, a program without a window (a
/// service) takes the language from its file.
pub fn read_language() {
    if let Some(code) = pinnacle_rt::fs::read_string(pinnacle_locale::LANGUAGE_PATH)
        && let Some(l) = Language::from_code(&code)
    {
        pinnacle_locale::set(l);
    }
}

/// What a node of the UI tree is, as a screen reader says it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum Role {
    Text,
    Heading,
    Button,
    Link,
    Switch,
    Checkbox,
    TextField,
    Slider,
    ListItem,
    Image,
    /// Something to act on that says no more (an element with a click).
    Control,
}

impl Role {
    fn from_u8(v: u8) -> Role {
        use Role::*;
        [
            Text, Heading, Button, Link, Switch, Checkbox, TextField, Slider, ListItem, Image, Control,
        ]
        .get(usize::from(v))
        .copied()
        .unwrap_or(Text)
    }

    /// Whether a double tap does something to it.
    pub fn actionable(self) -> bool {
        !matches!(self, Role::Text | Role::Heading | Role::Image | Role::ListItem)
    }

    /// What the reader says after its name: "button", "switch".
    pub fn spoken(self) -> &'static str {
        use pinnacle_locale::t;
        match self {
            Role::Text | Role::ListItem | Role::Control => "",
            Role::Heading => t("heading"),
            Role::Button => t("button"),
            Role::Link => t("link"),
            Role::Switch => t("switch"),
            Role::Checkbox => t("checkbox"),
            Role::TextField => t("text field"),
            Role::Slider => t("slider"),
            Role::Image => t("image"),
        }
    }
}

/// A node of the UI tree.
#[derive(Clone, PartialEq, Debug)]
pub struct Node {
    pub role: Role,
    /// What it says: a button's label, a heading's text, a field's label.
    pub name: String,
    /// What it holds: a field's text, a slider's value; empty when none.
    pub value: String,
    /// A switch's or checkbox's state, when it has one.
    pub checked: Option<bool>,
    pub disabled: bool,
    /// Where it is in the window, in window pixels.
    pub rect: Rect,
}

impl Node {
    /// What the screen reader says for it: "Wi-Fi, switch, on".
    pub fn speech(&self) -> String {
        use pinnacle_locale::t;
        let mut parts: Vec<&str> = Vec::new();
        if !self.name.is_empty() {
            parts.push(&self.name);
        }
        let role = self.role.spoken();
        if !role.is_empty() {
            parts.push(role);
        }
        if !self.value.is_empty() {
            parts.push(&self.value);
        }
        match self.checked {
            Some(true) => parts.push(t("on")),
            Some(false) => parts.push(t("off")),
            None => {}
        }
        if self.disabled {
            parts.push(t("unavailable"));
        }
        parts.join(", ")
    }
}

/// The longest name or value a node carries on the wire, in bytes.
const TEXT_MAX: usize = 200;

/// A tree as a [`crate::protocol::TREE`] message's body: per node its
/// role, flags, rectangle, and its name and value with their lengths.
pub fn encode(nodes: &[Node], max: usize) -> Vec<u8> {
    let mut out = Vec::new();
    for n in nodes {
        let name = cut(&n.name);
        let value = cut(&n.value);
        let size = 1 + 1 + 16 + 2 + name.len() + 2 + value.len();
        if out.len() + size > max {
            break;
        }
        out.push(n.role as u8);
        let flags = match n.checked {
            None => 0,
            Some(false) => 1,
            Some(true) => 3,
        } | if n.disabled { 4 } else { 0 };
        out.push(flags);
        out.extend_from_slice(&crate::rect_bytes(n.rect));
        out.extend_from_slice(&(name.len() as u16).to_le_bytes());
        out.extend_from_slice(name.as_bytes());
        out.extend_from_slice(&(value.len() as u16).to_le_bytes());
        out.extend_from_slice(value.as_bytes());
    }
    out
}

fn cut(text: &str) -> &str {
    let mut end = text.len().min(TEXT_MAX);
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    &text[..end]
}

pub fn decode(mut b: &[u8]) -> Vec<Node> {
    let mut out = Vec::new();
    let take_str = |b: &mut &[u8]| -> Option<String> {
        let len = usize::from(u16::from_le_bytes(b.get(..2)?.try_into().ok()?));
        let s = String::from_utf8_lossy(b.get(2..2 + len)?).into_owned();
        *b = &b[2 + len..];
        Some(s)
    };
    while b.len() >= 18 {
        let role = Role::from_u8(b[0]);
        let flags = b[1];
        let Some(rect) = crate::rect_from(&b[2..18]) else {
            break;
        };
        b = &b[18..];
        let (Some(name), Some(value)) = (take_str(&mut b), take_str(&mut b)) else {
            break;
        };
        out.push(Node {
            role,
            name,
            value,
            checked: (flags & 1 != 0).then_some(flags & 2 != 0),
            disabled: flags & 4 != 0,
            rect,
        });
    }
    out
}

/// The tree waiting to go to the display server with the app's next
/// present, and whether the display server wants trees at all.
struct Pending {
    wanted: AtomicBool,
    locked: AtomicBool,
    tree: UnsafeCell<Option<Vec<u8>>>,
}

// SAFETY: `tree` is only touched with `locked` held.
unsafe impl Sync for Pending {}

static PENDING: Pending = Pending {
    wanted: AtomicBool::new(false),
    locked: AtomicBool::new(false),
    tree: UnsafeCell::new(None),
};

fn with_pending<R>(f: impl FnOnce(&mut Option<Vec<u8>>) -> R) -> R {
    while PENDING.locked.swap(true, Ordering::Acquire) {
        core::hint::spin_loop();
    }
    // SAFETY: the lock is held.
    let r = f(unsafe { &mut *PENDING.tree.get() });
    PENDING.locked.store(false, Ordering::Release);
    r
}

/// Whether the display server asked for the UI tree.
pub fn tree_wanted() -> bool {
    PENDING.wanted.load(Ordering::Relaxed)
}

pub(crate) fn want_tree(wanted: bool) {
    PENDING.wanted.store(wanted, Ordering::Relaxed);
}

/// Hands the app's tree over, to go with its next present.
pub fn offer_tree(nodes: &[Node]) {
    let bytes = encode(nodes, pinnacle_rt::abi::MAX_MESSAGE - 8);
    with_pending(|t| *t = Some(bytes));
}

pub(crate) fn take_tree() -> Option<Vec<u8>> {
    with_pending(Option::take)
}