cranpose-ui 0.9.8

Composable widgets, text, layouts and input for Cranpose apps
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! The window root modifier: a node whose subtree is the content of its own
//! window while staying inside the one composition.
//!
//! The node measures its content into the window's size and reports a zero
//! size to its parent, so the parent lays out as if the subtree were absent.
//! It registers itself with the app context's window root registry, which a
//! platform reads after each update to learn which windows exist; the window
//! is identified by the layout node that carries the modifier. The scene
//! builder skips window roots when it builds a parent's scene and starts at
//! one when it builds that window's scene.

use std::{
    any::Any,
    cell::{Cell, RefCell},
    collections::HashMap,
    fmt,
    hash::{Hash, Hasher},
    rc::Rc,
};

use cranpose_core::{Applier, MemoryApplier, NodeId};
use cranpose_foundation::{
    Constraints, DelegatableNode, InvalidationKind, LayoutModifierNode, Measurable, ModifierNode,
    ModifierNodeContext, ModifierNodeElement, NodeCapabilities, NodeState, Size,
};
use cranpose_ui_layout::LayoutModifierMeasureResult;

use super::Modifier;
use crate::{
    render_state::{AppContextId, current_app_context, with_app_context_by_id},
    widgets::nodes::layout_node::LayoutNode,
};

/// What a window root needs from the platform's description of its window:
/// the logical size to lay the content out into, read on every measure so a
/// resize needs no new modifier, and the description itself for the platform
/// to take back.
pub trait WindowRootDescriptor: Any {
    /// The window's content size in logical pixels.
    fn layout_size(&self) -> Size;

    /// The descriptor as `Any`, so the platform that made it can downcast it.
    fn as_any(&self) -> &dyn Any;
}

/// A window root the registry knows about.
#[derive(Clone)]
pub struct WindowRootEntry {
    /// The layout node carrying the window root modifier, which identifies
    /// the window: it stays the same node across recompositions.
    pub node: NodeId,
    /// The platform's description of the window.
    pub descriptor: Rc<dyn WindowRootDescriptor>,
}

impl fmt::Debug for WindowRootEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WindowRootEntry")
            .field("node", &self.node)
            .finish()
    }
}

/// The window roots attached in an app context, in attach order, with a
/// revision that changes whenever the set changes.
#[derive(Default)]
pub struct WindowRootRegistry {
    entries: RefCell<Vec<WindowRootEntry>>,
    revision: Cell<u64>,
}

impl WindowRootRegistry {
    fn register(&self, entry: WindowRootEntry) {
        let mut entries = self.entries.borrow_mut();
        if let Some(existing) = entries.iter_mut().find(|known| known.node == entry.node) {
            *existing = entry;
        } else {
            entries.push(entry);
        }
        self.bump();
    }

    fn unregister(&self, node: NodeId) {
        let mut entries = self.entries.borrow_mut();
        let before = entries.len();
        entries.retain(|entry| entry.node != node);
        if entries.len() != before {
            self.bump();
        }
    }

    fn bump(&self) {
        self.revision.set(self.revision.get().wrapping_add(1));
    }

    /// Whether no window root is attached.
    pub fn is_empty(&self) -> bool {
        self.entries.borrow().is_empty()
    }

    /// Every attached window root.
    pub fn entries(&self) -> Vec<WindowRootEntry> {
        self.entries.borrow().clone()
    }

    /// Changes whenever a window root attaches, detaches or is updated.
    pub fn revision(&self) -> u64 {
        self.revision.get()
    }
}

/// The window roots attached in the current app context.
pub fn window_roots() -> Vec<WindowRootEntry> {
    current_app_context().map_or_else(Vec::new, |context| context.window_roots().entries())
}

/// The current app context's window root revision; see
/// [`WindowRootRegistry::revision`].
pub fn window_roots_revision() -> u64 {
    current_app_context().map_or(0, |context| context.window_roots().revision())
}

/// Whether `node` is a layout node whose modifier chain carries a window root.
pub fn is_window_root(applier: &mut MemoryApplier, node: NodeId) -> bool {
    applier
        .with_node::<LayoutNode, _>(node, |layout_node| layout_node.is_window_root())
        .unwrap_or(false)
}

/// The window root that owns `node`: the nearest node, `node` included, whose
/// modifier chain carries a window root. `None` when the node belongs to the
/// primary root.
pub fn nearest_window_root(applier: &mut MemoryApplier, node: NodeId) -> Option<NodeId> {
    let mut current = node;
    for _ in 0..100_000 {
        if is_window_root(applier, current) {
            return Some(current);
        }
        current = applier.get_mut(current).ok()?.parent()?;
    }
    None
}

/// Reusable ancestry storage for [`nearest_window_roots_into`].
#[derive(Default)]
pub struct WindowRootRoutingScratch {
    owners: HashMap<NodeId, Option<NodeId>>,
    path: Vec<NodeId>,
}

/// [`nearest_window_root`] for each of `nodes`, in order, with every
/// ancestor looked up at most once. In an app context with no window root
/// attached, every node belongs to the primary root and none is looked up.
pub fn nearest_window_roots(applier: &mut MemoryApplier, nodes: &[NodeId]) -> Vec<Option<NodeId>> {
    let mut output = Vec::new();
    nearest_window_roots_into(
        applier,
        nodes.iter().copied(),
        &mut output,
        &mut WindowRootRoutingScratch::default(),
    );
    output
}

/// Fills `output` with [`nearest_window_roots`] results, reusing its storage
/// and the ancestry cache in `scratch` across batches.
///
/// The cache is cleared for every batch, so changes to window-root modifiers
/// and tree attachment are observed immediately.
///
/// ```
/// use cranpose_core::MemoryApplier;
/// use cranpose_ui::{WindowRootRoutingScratch, nearest_window_roots_into};
///
/// let mut applier = MemoryApplier::new();
/// let mut scratch = WindowRootRoutingScratch::default();
/// let mut owners = Vec::new();
/// nearest_window_roots_into(&mut applier, [], &mut owners, &mut scratch);
/// assert!(owners.is_empty());
/// ```
pub fn nearest_window_roots_into(
    applier: &mut MemoryApplier,
    nodes: impl IntoIterator<Item = NodeId>,
    output: &mut Vec<Option<NodeId>>,
    scratch: &mut WindowRootRoutingScratch,
) {
    let nodes = nodes.into_iter();
    output.clear();
    scratch.owners.clear();
    scratch.path.clear();
    let (lower_bound, upper_bound) = nodes.size_hint();
    if lower_bound == 0 && upper_bound == Some(0) {
        return;
    }
    output.reserve(lower_bound);
    if current_app_context().is_some_and(|context| context.window_roots().is_empty()) {
        output.extend(nodes.map(|_| None));
        return;
    }
    for node in nodes {
        let mut current = node;
        scratch.path.clear();
        let owner = loop {
            if let Some(known) = scratch.owners.get(&current) {
                break *known;
            }
            scratch.path.push(current);
            if is_window_root(applier, current) {
                break Some(current);
            }
            match applier.get_mut(current).ok().and_then(|node| node.parent()) {
                Some(parent) if scratch.path.len() < 100_000 => current = parent,
                _ => break None,
            }
        };
        for visited in scratch.path.drain(..) {
            scratch.owners.insert(visited, owner);
        }
        output.push(owner);
    }
}

/// Node that lays its content out into the window's size. That size is the
/// node's own, for the window's scene; the layout pass reports a zero size
/// to the node's parent.
pub struct WindowRootNode {
    descriptor: Rc<dyn WindowRootDescriptor>,
    node_id: Cell<Option<NodeId>>,
    owner: Cell<Option<AppContextId>>,
    state: NodeState,
}

impl fmt::Debug for WindowRootNode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WindowRootNode")
            .field("node_id", &self.node_id.get())
            .finish()
    }
}

impl WindowRootNode {
    /// A window root described by `descriptor`, for a platform node that
    /// delegates its layout and registration here.
    pub fn new(descriptor: Rc<dyn WindowRootDescriptor>) -> Self {
        Self {
            descriptor,
            node_id: Cell::new(None),
            owner: Cell::new(None),
            state: NodeState::new(),
        }
    }

    /// Takes a new description of the window and re-registers the root when
    /// it is attached.
    pub fn set_descriptor(&mut self, descriptor: Rc<dyn WindowRootDescriptor>) {
        self.descriptor = descriptor;
        self.register();
    }

    fn entry(&self, node: NodeId) -> WindowRootEntry {
        WindowRootEntry {
            node,
            descriptor: Rc::clone(&self.descriptor),
        }
    }

    fn register(&self) {
        let Some(node) = self.node_id.get() else {
            return;
        };
        let Some(context) = current_app_context() else {
            log::debug!("window root {node} attached outside an app context");
            return;
        };
        self.owner.set(Some(context.id()));
        context.window_roots().register(self.entry(node));
    }

    fn unregister(&self) {
        let (Some(node), Some(owner)) = (self.node_id.get(), self.owner.take()) else {
            return;
        };
        with_app_context_by_id(owner, |context| context.window_roots().unregister(node));
    }
}

impl DelegatableNode for WindowRootNode {
    fn node_state(&self) -> &NodeState {
        &self.state
    }
}

impl ModifierNode for WindowRootNode {
    fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
        self.node_id.set(context.node_id());
        self.register();
        context.invalidate(InvalidationKind::Layout);
    }

    fn on_detach(&mut self) {
        self.unregister();
    }

    fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
        Some(self)
    }

    fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
        Some(self)
    }
}

impl LayoutModifierNode for WindowRootNode {
    fn measure(
        &self,
        _context: &mut dyn ModifierNodeContext,
        measurable: &dyn Measurable,
        _constraints: Constraints,
    ) -> LayoutModifierMeasureResult {
        let size = self.descriptor.layout_size();
        let size = Size::new(size.width.max(0.0), size.height.max(0.0));
        let _content = measurable.measure(Constraints {
            min_width: 0.0,
            max_width: size.width,
            min_height: 0.0,
            max_height: size.height,
        });
        LayoutModifierMeasureResult::with_size(size)
    }

    fn min_intrinsic_width(
        &self,
        _measurable: &dyn Measurable,
        _height: f32,
        _density: f32,
    ) -> f32 {
        0.0
    }

    fn max_intrinsic_width(
        &self,
        _measurable: &dyn Measurable,
        _height: f32,
        _density: f32,
    ) -> f32 {
        0.0
    }

    fn min_intrinsic_height(
        &self,
        _measurable: &dyn Measurable,
        _width: f32,
        _density: f32,
    ) -> f32 {
        0.0
    }

    fn max_intrinsic_height(
        &self,
        _measurable: &dyn Measurable,
        _width: f32,
        _density: f32,
    ) -> f32 {
        0.0
    }
}

/// Element that creates and updates window root nodes.
#[derive(Clone)]
pub struct WindowRootElement {
    descriptor: Rc<dyn WindowRootDescriptor>,
}

impl WindowRootElement {
    /// A window root described by `descriptor`.
    pub fn new(descriptor: Rc<dyn WindowRootDescriptor>) -> Self {
        Self { descriptor }
    }

    fn descriptor_address(&self) -> usize {
        Rc::as_ptr(&self.descriptor).cast::<()>() as usize
    }
}

impl fmt::Debug for WindowRootElement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WindowRootElement").finish()
    }
}

impl PartialEq for WindowRootElement {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.descriptor, &other.descriptor)
    }
}

impl Hash for WindowRootElement {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.descriptor_address().hash(state);
    }
}

impl ModifierNodeElement for WindowRootElement {
    type Node = WindowRootNode;

    fn create(&self) -> Self::Node {
        WindowRootNode::new(Rc::clone(&self.descriptor))
    }

    fn update(&self, node: &mut Self::Node) {
        node.set_descriptor(Rc::clone(&self.descriptor));
    }

    fn capabilities(&self) -> NodeCapabilities {
        NodeCapabilities::LAYOUT | NodeCapabilities::WINDOW_ROOT
    }

    fn inspector_name(&self) -> &'static str {
        "windowRoot"
    }
}

impl Modifier {
    /// Makes the node the root of its own window, described by `descriptor`
    /// and identified by the node itself. The subtree is laid out into the
    /// descriptor's size and drawn into that window's scene; the parent sees
    /// a node of zero size and its scene skips the subtree. Platforms wrap
    /// this in a modifier that takes their own window configuration.
    pub fn window_root(self, descriptor: Rc<dyn WindowRootDescriptor>) -> Self {
        self.then(Self::with_element(WindowRootElement::new(descriptor)))
    }
}