mitsuami-core 2.5.0

Node tree, layout, styles, units, a11y model and backend contract for mitsuami
Documentation
//! Creating nodes and setting their props, styles and handlers.

use std::collections::BTreeMap;
use std::rc::Rc;

use crate::a11y::A11yProps;
use crate::command::{Command, UiEvent};
use crate::geometry::{Insets, Point, Rect, Size, WindowSize};
use crate::style::Style;
use crate::widget::{NodeId, Prop, WidgetKind};

use super::{Fit, Node, Ui};

impl Ui {
    pub fn create(&self, kind: WidgetKind, props: Vec<Prop>) -> NodeId {
        let id = {
            let mut inner = self.inner.borrow_mut();
            let id = NodeId(inner.next_id);
            inner.next_id += 1;
            let taffy = if kind.is_native() {
                let t = if kind.is_container() {
                    inner.taffy.new_leaf(taffy::Style::default())
                } else {
                    inner.taffy.new_leaf_with_context(taffy::Style::default(), id)
                };
                Some(t.expect("taffy: failed to create node"))
            } else {
                None
            };
            if kind.is_native() {
                inner.pending.push(Command::Create { id, kind, props: props.clone() });
                inner.created.insert(id);
            }
            inner.nodes.insert(
                id,
                Node {
                    kind,
                    parent: None,
                    children: Vec::new(),
                    native_children: Vec::new(),
                    native_parent: None,
                    props,
                    style: Style::default(),
                    a11y: A11yProps::default(),
                    test_id: None,
                    tab_index: None,
                    handlers: Vec::new(),
                    taffy,
                    frame: Rect::ZERO,
                    framed: false,
                    window_size: Size::ZERO,
                    fit: Fit::None,
                    heights: Vec::new(),
                    scroll_offset: Point::ZERO,
                    row_width: None,
                    tree_indent: crate::TreeIndent::default(),
                    viewport_insets: Insets::ZERO,
                    column_widths: None,
                    row_heights: BTreeMap::new(),
                    strip: Size::ZERO,
                    insets: None,
                    drawn_at: None,
                },
            );
            inner.styles_dirty = true;
            id
        };
        self.changed();
        id
    }

    /// A window fitting its height is sized at its first layout, so give it
    /// its content before the next commit.
    pub fn create_window(&self, title: impl Into<String>, size: impl Into<WindowSize>) -> NodeId {
        let size = match size.into() {
            // A fraction of the work area of the screen it opens on, as the
            // platform tells it now; without a screen, a common default.
            WindowSize::Screen { width, height } => {
                let area = self.inner.borrow().backend.work_area(None).unwrap_or(Size::new(1024.0, 768.0));
                WindowSize::Fixed(Size::new(
                    (area.width * width.clamp(0.0, 1.0)).round(),
                    (area.height * height.clamp(0.0, 1.0)).round(),
                ))
            }
            size => size,
        };
        let mut props = vec![Prop::Title(title.into())];
        if let WindowSize::FollowHeight(_) = size {
            props.push(Prop::HeightFollowsContent(true));
        }
        let id = self.create(WidgetKind::Window, props);
        let mut inner = self.inner.borrow_mut();
        let node = inner.nodes.get_mut(&id).expect("just created");
        let (size, fit) = match size {
            WindowSize::Fixed(size) => (size, Fit::None),
            WindowSize::FitHeight(width) => (Size::new(width, 0.0), Fit::Once),
            WindowSize::FollowHeight(width) => (Size::new(width, 0.0), Fit::Follow { until_resized: false }),
            WindowSize::FollowHeightUntilResized(width) => (Size::new(width, 0.0), Fit::Follow { until_resized: true }),
            WindowSize::Screen { .. } => unreachable!("resolved above"),
        };
        node.window_size = size;
        node.fit = fit;
        node.frame = Rect { origin: Point::ZERO, size };
        inner.windows.push(id);
        // A fitted size is sent with the first frames.
        if fit == Fit::None {
            inner.pending.push(Command::SetWindowSize { id, size });
        }
        id
    }

    /// The work area of a window's screen (the screen less its bars and
    /// docks), as the content size of a window filling it, in points: what
    /// to size a window to a fraction of its screen with
    /// [`Ui::set_window_size`]. With `None`, of the screen a new window opens
    /// on. `None` if the platform can't tell.
    pub fn work_area(&self, window: Option<NodeId>) -> Option<Size> {
        self.inner.borrow().backend.work_area(window)
    }

    /// Centres a window on its screen's work area now, as
    /// `Placement::Centred` does when it opens. Where the platform places
    /// windows itself (Wayland, GTK), it stays where it is.
    pub fn centre_window(&self, window: NodeId) {
        {
            let mut inner = self.inner.borrow_mut();
            if !inner.nodes.get(&window).is_some_and(|n| n.kind == WidgetKind::Window) {
                return;
            }
            inner.pending.push(Command::CentreWindow { window });
        }
        self.changed();
    }

    /// Asks for a window's content size, in points, as the app would resize
    /// it. The platform may refuse it (a window in full screen keeps the
    /// screen's), and gives it no smaller than the window's `MinSize`; the
    /// content is laid out at the size it reports (`WindowResized`). A
    /// `WindowSize::FollowHeight` window takes only the width: its content
    /// sets its height. Other windows stop fitting their height.
    pub fn set_window_size(&self, window: NodeId, size: Size) {
        {
            let mut inner = self.inner.borrow_mut();
            let Some(node) = inner.nodes.get_mut(&window).filter(|n| n.kind == WidgetKind::Window) else { return };
            let size = match node.fit {
                Fit::Follow { until_resized: false } => {
                    Size::new(size.width, node.heights.last().copied().unwrap_or(node.window_size.height))
                }
                _ => {
                    node.fit = Fit::None;
                    node.heights.clear();
                    size
                }
            };
            inner.pending.push(Command::SetWindowSize { id: window, size });
        }
        self.changed();
    }

    /// Sets a prop, sending it to the backend only if it changed.
    pub fn set_prop(&self, id: NodeId, prop: Prop) {
        // A choice of none, or of a tab or option that isn't there, is the
        // first, before the backend sees it (`always_chosen`).
        let prop = match prop {
            Prop::SelectedIndex(index) => Prop::SelectedIndex(self.choosable(id, index)),
            prop => prop,
        };
        {
            let mut inner = self.inner.borrow_mut();
            let inner = &mut *inner;
            let Some(node) = inner.nodes.get_mut(&id) else { return };
            if node.prop(&prop) == Some(&prop) {
                return;
            }
            node.props.retain(|p| p.key() != prop.key());
            node.props.push(prop.clone());
            if matches!(prop, Prop::Custom(_)) {
                node.drawn_at = None;
            }
            if prop.affects_measure(node.kind)
                && let Some(t) = node.taffy
            {
                let _ = inner.taffy.mark_dirty(t);
            }
            // A line limit changes a text's minimum width (`resolve_node`);
            // a split's position and orientation, its tracks.
            if matches!(prop, Prop::TextStyle(_) | Prop::MaxLines(_))
                || (node.kind == WidgetKind::Split && matches!(prop, Prop::Number(_) | Prop::Orientation(_)))
            {
                inner.styles_dirty = true;
            }
            // New titles, icons or another style may make the tab strip wider
            // (`size_tab_strips`), and a group's heading wider, or give it
            // the titled insets.
            if (matches!(prop, Prop::TabTitles(_) | Prop::TabIcons(_) | Prop::TabsStyle(_))
                || (node.kind == WidgetKind::Group && matches!(prop, Prop::Title(_))))
                && let Some(t) = node.taffy
            {
                let _ = inner.taffy.mark_dirty(t);
                inner.styles_dirty |= node.kind == WidgetKind::Group;
            }
            // A tab view's page shown, and a surface taking input, are in
            // the Tab order.
            if matches!(prop, Prop::SelectedIndex(_) | Prop::TakesInput(_)) {
                inner.focus_dirty = true;
            }
            if node.kind.is_native() {
                inner.queue_prop(id, prop);
            }
        }
        self.changed();
        if let Some(chosen) = self.always_chosen(id) {
            self.set_prop(id, Prop::SelectedIndex(chosen));
        }
    }

    /// A `Tabs` or `Select` with tabs or options always has one chosen, the
    /// first unless the app chose another that's there: GTK's notebook and
    /// drop-down can't show none. WinUI's selector bar can, and a tab view
    /// whose app chose no tab (the C ABI's, SourceGit's statistics) showed
    /// an empty page there. What to choose, if not what's chosen now.
    fn always_chosen(&self, id: NodeId) -> Option<Option<usize>> {
        let chosen = {
            let inner = self.inner.borrow();
            let node = inner.nodes.get(&id)?;
            matches!(node.kind, WidgetKind::Tabs | WidgetKind::Select)
                .then(|| crate::find_prop!(node.props, SelectedIndex).flatten())?
        };
        let wanted = self.choosable(id, chosen);
        (wanted != chosen).then_some(wanted)
    }

    /// What a `Tabs` or `Select` can have chosen for `index`: it, if it's
    /// there, or else the first; none only without tabs or options. Any
    /// other node's index as it is.
    fn choosable(&self, id: NodeId, index: Option<usize>) -> Option<usize> {
        let inner = self.inner.borrow();
        let Some(node) = inner.nodes.get(&id) else { return index };
        let count = match node.kind {
            WidgetKind::Tabs => crate::find_prop!(node.props, TabTitles).map(|t| t.len()),
            WidgetKind::Select => crate::find_prop!(node.props, Options).map(|o| o.len()),
            _ => return index,
        };
        match count {
            // Titles or options may come after the index.
            None => index,
            Some(count) => (count > 0).then(|| index.filter(|i| *i < count).unwrap_or(0)),
        }
    }

    pub fn set_style(&self, id: NodeId, style: Style) {
        {
            let mut inner = self.inner.borrow_mut();
            let Some(node) = inner.nodes.get_mut(&id) else { return };
            if node.style == style {
                return;
            }
            node.style = style;
            inner.styles_dirty = true;
        }
        self.changed();
    }

    /// Edits a node's style in place (used by reactive style bindings).
    pub fn update_style(&self, id: NodeId, f: impl FnOnce(&mut Style)) {
        let style = {
            let inner = self.inner.borrow();
            let Some(node) = inner.nodes.get(&id) else { return };
            let mut style = node.style.clone();
            f(&mut style);
            style
        };
        self.set_style(id, style);
    }

    pub fn set_a11y(&self, id: NodeId, a11y: A11yProps) {
        {
            let mut inner = self.inner.borrow_mut();
            let Some(node) = inner.nodes.get_mut(&id) else { return };
            if node.a11y == a11y {
                return;
            }
            node.a11y = a11y.clone();
            if node.kind.is_native() {
                inner.pending.push(Command::SetA11y { id, a11y });
            }
        }
        self.changed();
    }

    /// Changes part of a node's semantics.
    pub fn update_a11y(&self, id: NodeId, f: impl FnOnce(&mut A11yProps)) {
        let Some(mut a11y) = self.inner.borrow().nodes.get(&id).map(|n| n.a11y.clone()) else { return };
        f(&mut a11y);
        self.set_a11y(id, a11y);
    }

    pub fn set_test_id(&self, id: NodeId, test_id: impl Into<String>) {
        if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
            node.test_id = Some(test_id.into());
        }
    }

    /// The current owner, or, with none, a scope of its own that goes when
    /// node `id` is destroyed, so what a view built straight on a `Ui` (a
    /// `For`, a `List`) hangs off it is freed with its node.
    pub(crate) fn owner_or_node_scope(&self, id: NodeId) -> mitsuami_reactive::Owner {
        use mitsuami_reactive::Owner;
        if let Some(owner) = Owner::current() {
            return owner;
        }
        struct DisposeOnDrop(Owner);
        impl Drop for DisposeOnDrop {
            fn drop(&mut self) {
                self.0.dispose();
            }
        }
        let scope = Owner::new_root();
        let guard = DisposeOnDrop(scope);
        // Kept by a handler that does nothing: the node drops its handlers
        // when it's destroyed (after the tree's borrow, `destroy`).
        if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
            node.handlers.push(Rc::new(move |_: &UiEvent| {
                let _ = &guard;
            }));
        }
        scope
    }

    /// Adds an event handler. It runs in the reactive scope that is current
    /// now (usually the component being built), so `inject`, `spawn_local`
    /// and friends work inside it.
    pub fn on_event(&self, id: NodeId, handler: impl Fn(&UiEvent) + 'static) {
        let owner = mitsuami_reactive::Owner::current();
        let handler = move |event: &UiEvent| match owner {
            Some(owner) if owner.is_alive() => owner.with(|| handler(event)),
            _ => handler(event),
        };
        if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
            node.handlers.push(Rc::new(handler));
        }
    }
}