cranpose-ui 0.28.0

Composable widgets, text, layouts and input for Cranpose apps
Documentation
use std::rc::Rc;

use cranpose_core::collections::pass_aged::PassAgedCache;
use cranpose_ui_graphics::MemoryHeadroom;
use smallvec::{SmallVec, smallvec};

use super::{
    TextAlign,
    measure::{PreparedTextLayout, TextFrame},
    returning_texts::ReturningTexts,
    style::TextStyle,
    text_key::TextKey,
};

/// Prepared layouts kept across nodes. Each node keeps its own, so this
/// serves the items a list composes again, a few screens of them.
const TEXT_PREPARED_CACHE_CAPACITY: usize = 1024;
// Layouts kept for one text at different widths.
const WIDTHS_PER_TEXT: usize = 2;
// Layouts of draw scopes' text kept until a pass draws none of them, the
// last drawn taking the place of the one drawn longest ago.
const DRAWN_LAYOUTS: usize = 8;

// The layouts of one text at different widths, the newest first.
type Widths = SmallVec<[Rc<PreparedTextLayout>; WIDTHS_PER_TEXT]>;

// What the cache holds of a text for a frame.
pub(super) enum Cached {
    // A layout that breaks into the same lines, aligned to the frame.
    Held(Rc<PreparedTextLayout>),
    Missed(Miss),
}

// What the cache holds of a text it holds no layout of for a frame.
#[derive(Clone, Copy)]
pub(super) enum Miss {
    // Layouts at other widths, which a new one joins.
    OtherWidths,
    Absent,
}

// How the cache keeps a layout it missed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CacheAdmission {
    // At once: a node's first text, which a list composes again.
    First,
    // Once it comes back: text a node changed in place, whose strings come
    // back only sometimes, as a stat's do, or never, as a ticker's. The
    // node keeps its own layout meanwhile.
    Changed,
    // Until a pass draws it no more, and for longer once it comes back: text
    // a draw scope draws, with no node to keep its layout.
    Drawn,
}

// The layouts recent passes used, shared across nodes.
pub(super) struct LayoutCache {
    kept: PassAgedCache<TextKey, Widths>,
    // A number drawn anew each frame keeps one or two layouts here, and a
    // string drawn every frame keeps its first.
    drawn: DrawnLayouts,
    // The texts changed in place or drawn lately: one laid out again while
    // here came back, and goes into `kept`.
    returning: ReturningTexts,
    // The host's memory headroom when the pass began. A tight heap keeps
    // no layout of a text that changes in place.
    headroom: MemoryHeadroom,
    // Room for the layouts a pass's start ages out, which `begin_pass`
    // lends and `give_back` returns empty.
    aged: Vec<Rc<PreparedTextLayout>>,
}

impl LayoutCache {
    pub(super) fn new() -> Self {
        Self {
            kept: PassAgedCache::with_capacity_at_least_one(TEXT_PREPARED_CACHE_CAPACITY),
            drawn: DrawnLayouts::default(),
            returning: ReturningTexts::new(TEXT_PREPARED_CACHE_CAPACITY),
            headroom: MemoryHeadroom::default(),
            aged: Vec::new(),
        }
    }

    // Drops every layout and every key it remembers.
    pub(super) fn clear(&mut self) {
        self.kept.clear();
        self.drawn = DrawnLayouts::default();
        self.returning.clear();
    }

    // Forgets the texts that changed in place or were drawn, and gives back
    // the room that took: the texts rest.
    pub(super) fn rest(&mut self) {
        self.returning.clear();
    }

    // What the cache holds of `key` for `frame`, laid out as `admission`
    // says: a layout that breaks into the same lines, aligned to its widths,
    // or layouts at other widths only, or nothing.
    pub(super) fn cached(
        &mut self,
        key: TextKey,
        frame: TextFrame,
        (style, admission): (&TextStyle, CacheAdmission),
    ) -> Cached {
        let align = style.paragraph_style.text_align;
        if admission == CacheAdmission::Drawn
            && let Some(drawn) = self.drawn.get(key, frame, align)
        {
            return Cached::Held(drawn);
        }
        let Some(widths) = self.kept.get_mut(&key) else {
            return Cached::Missed(Miss::Absent);
        };
        let Some(held) = widths
            .iter()
            .find(|prepared| prepared.layout.holds(frame.min_width, frame.max_width))
            .map(Rc::clone)
        else {
            return Cached::Missed(Miss::OtherWidths);
        };
        let aligned = held.at_widths((frame.min_width, frame.max_width), align, None);
        if !Rc::ptr_eq(&aligned, &held) {
            remember(widths, &aligned);
        }
        Cached::Held(aligned)
    }

    // Puts `prepared`, laid out for `key` after `miss`, beside the layouts
    // of `key` at other widths, or keeps it as `admission` says when the
    // cache held none. Returns the layout of the text that a full cache let
    // go for it, when the cache alone held that layout.
    pub(super) fn keep(
        &mut self,
        key: TextKey,
        prepared: &Rc<PreparedTextLayout>,
        (miss, admission): (Miss, CacheAdmission),
    ) -> Option<Rc<PreparedTextLayout>> {
        if let Miss::OtherWidths = miss {
            if let Some(widths) = self.kept.get_mut(&key) {
                remember(widths, prepared);
            }
            return None;
        }
        match admission {
            CacheAdmission::First => {}
            _ if self.headroom == MemoryHeadroom::Tight => return None,
            CacheAdmission::Changed | CacheAdmission::Drawn => {
                let hash = key.mixed_hash();
                if !self.returning.contains(hash) {
                    self.returning.put(hash);
                    if admission == CacheAdmission::Drawn {
                        self.drawn.push(key, Rc::clone(prepared));
                    }
                    return None;
                }
            }
        }
        self.keep_first(key, prepared)
    }

    // Keeps `prepared` as the one layout of `key`; returns the layout a full
    // cache let go for it, as `keep` does. Out of line: a text drawn anew
    // each frame stops before it.
    #[inline(never)]
    fn keep_first(
        &mut self,
        key: TextKey,
        prepared: &Rc<PreparedTextLayout>,
    ) -> Option<Rc<PreparedTextLayout>> {
        let (_, mut widths) = self.kept.push(key, smallvec![Rc::clone(prepared)])?;
        held_alone(&mut widths, self.headroom)
    }

    // Starts a layout pass on a host with `headroom`. It drops the drawn
    // layouts that the last pass did not draw, and the kept ones that no
    // pass asked for in the last `idle_passes`. Returns, in room that
    // `give_back` takes back, the layouts of those texts that the cache
    // alone held, which a tight heap drops too.
    pub(super) fn begin_pass(
        &mut self,
        idle_passes: u64,
        headroom: MemoryHeadroom,
    ) -> Vec<Rc<PreparedTextLayout>> {
        let aged = &mut self.aged;
        self.kept.begin_pass(idle_passes, |mut widths| {
            aged.extend(held_alone(&mut widths, headroom));
        });
        self.drawn.begin_pass();
        self.returning.begin_pass(idle_passes);
        self.headroom = headroom;
        std::mem::take(&mut self.aged)
    }

    // Takes back the room `begin_pass` lent, empty, for the next pass.
    pub(super) fn give_back(&mut self, aged: Vec<Rc<PreparedTextLayout>>) {
        self.aged = aged;
    }
}

// The first layout of `widths`, the layouts of a text the full cache let
// go, when the cache alone held it on a heap with `headroom` to spare. The
// layouts at other widths drop: a copy aligned at another width shares the
// first one's lines, which would keep both waiting among the retired
// layouts. A text still draws most layouts let go by a full cache; those
// drop with no more work, as everything does on a tight heap.
fn held_alone(widths: &mut Widths, headroom: MemoryHeadroom) -> Option<Rc<PreparedTextLayout>> {
    let alone = widths
        .first()
        .is_some_and(|first| Rc::strong_count(first) == 1);
    (alone && headroom == MemoryHeadroom::Ample).then(|| widths.swap_remove(0))
}

// Puts `prepared` first among the layouts of one text, keeping the newest.
// Out of line, as only a text laid out at another width gets here.
#[inline(never)]
fn remember(widths: &mut Widths, prepared: &Rc<PreparedTextLayout>) {
    widths.truncate(WIDTHS_PER_TEXT - 1);
    widths.insert(0, Rc::clone(prepared));
}

// The layouts of draw scopes' text the last pass drew, and the pass now.
#[derive(Default)]
struct DrawnLayouts {
    slots: Vec<DrawnLayout>,
    pass: u64,
}

struct DrawnLayout {
    key: TextKey,
    prepared: Rc<PreparedTextLayout>,
    // The pass that drew it last.
    pass: u64,
}

impl DrawnLayouts {
    // The layout of `key`, aligned to `frame`, marked drawn in this pass;
    // `None`, leaving no layout of `key`, when it breaks into other lines.
    fn get(
        &mut self,
        key: TextKey,
        frame: TextFrame,
        align: TextAlign,
    ) -> Option<Rc<PreparedTextLayout>> {
        let index = self.slots.iter().position(|slot| slot.key == key)?;
        let pass = self.pass;
        let slot = self.slots.get_mut(index)?;
        if !slot.prepared.layout.holds(frame.min_width, frame.max_width) {
            self.slots.swap_remove(index);
            return None;
        }
        slot.prepared = slot
            .prepared
            .at_widths((frame.min_width, frame.max_width), align, None);
        slot.pass = pass;
        Some(Rc::clone(&slot.prepared))
    }

    fn push(&mut self, key: TextKey, prepared: Rc<PreparedTextLayout>) {
        let drawn = DrawnLayout {
            key,
            prepared,
            pass: self.pass,
        };
        if self.slots.len() < DRAWN_LAYOUTS {
            self.slots.reserve_exact(DRAWN_LAYOUTS - self.slots.len());
            self.slots.push(drawn);
        } else if let Some(oldest) = self.slots.iter_mut().min_by_key(|slot| slot.pass) {
            *oldest = drawn;
        }
    }

    // Starts a pass: drops the layouts the last pass did not draw.
    fn begin_pass(&mut self) {
        self.pass += 1;
        let pass = self.pass;
        if self.slots.iter().any(|slot| pass - slot.pass > 1) {
            drop_undrawn(&mut self.slots, pass);
        }
    }
}

// forwards on purpose: a pass whose texts drew what they drew before drops
// none, and inlined the drops take room in the code each pass runs.
#[inline(never)]
fn drop_undrawn(slots: &mut Vec<DrawnLayout>, pass: u64) {
    slots.retain(|slot| pass - slot.pass <= 1);
}