feather-ui 0.4.0

Feather UI library
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2025 Fundament Research Institute <https://fundament.institute>

pub mod base;
pub mod domain_write;
pub mod fixed;
pub mod flex;
pub mod grid;
pub mod leaf;
pub mod list;
pub mod root;
pub mod text;

use dyn_clone::DynClone;
use guillotiere::euclid::{Point2D, Vector2D};
use wide::f32x4;

use crate::color::sRGB32;
use crate::render::Renderable;
use crate::render::compositor::CompositorView;
use crate::{
    Error, PxDim, PxLimits, PxPoint, PxRect, RelLimits, SourceID, UNSIZED_AXIS, URect, rtree,
};
use derive_where::derive_where;
use std::marker::PhantomData;
use std::rc::{Rc, Weak};
use std::sync::Arc;

/// Represents an arbitrary layout node that hasn't been staged yet. The vast
/// majority of the time, components should simply use the standard [`Node`]
/// implementation of this trait, which handles most common layout cases.
/// However, some components, like the text component, have complex layout logic
/// or special cases that [`Node`] can't cover.
pub trait Layout<Props: ?Sized>: DynClone {
    fn get_props(&self) -> &Props;
    fn stage<'a>(
        &self,
        area: PxRect,
        limits: PxLimits,
        window: &mut crate::component::window::WindowState,
    ) -> Box<dyn Staged + 'a>;
}

dyn_clone::clone_trait_object!(<Imposed> Layout<Imposed> where Imposed:?Sized);

impl<U: ?Sized, T> Layout<U> for Box<dyn Layout<T>>
where
    for<'a> &'a T: Into<&'a U>,
{
    fn get_props(&self) -> &U {
        use std::ops::Deref;
        Box::deref(self).get_props().into()
    }

    fn stage<'a>(
        &self,
        area: PxRect,
        limits: PxLimits,
        window: &mut crate::component::window::WindowState,
    ) -> Box<dyn Staged + 'a> {
        use std::ops::Deref;
        Box::deref(self).stage(area, limits, window)
    }
}

impl<U: ?Sized, T> Layout<U> for &dyn Layout<T>
where
    for<'a> &'a T: Into<&'a U>,
{
    fn get_props(&self) -> &U {
        (*self).get_props().into()
    }

    fn stage<'a>(
        &self,
        area: PxRect,
        limits: PxLimits,
        window: &mut crate::component::window::WindowState,
    ) -> Box<dyn Staged + 'a> {
        (*self).stage(area, limits, window)
    }
}

pub trait Desc {
    type Props: ?Sized;
    type Child: ?Sized;
    type Children: Clone;

    /// Resolves a pending layout into a resolved node, which contains a pointer
    /// to the R-tree
    fn stage<'a>(
        props: &Self::Props,
        outer_area: PxRect,
        limits: PxLimits,
        children: &Self::Children,
        id: std::sync::Weak<SourceID>,
        renderable: Option<Rc<dyn Renderable>>,
        window: &mut crate::component::window::WindowState,
    ) -> Box<dyn Staged + 'a>;
}

/// The standard layout node. Expects the layout properties, which must be
/// compatible with the layout description `D` provided, which also determines
/// the type that contains the children. A unique ID must be provided, and a
/// renderable is optional - it will be passed to staging if provided. The
/// layer, if provided will create a new layer operation with the given color
/// and rotation. This is normally used to do correct transparency.
///
/// # Examples
/// See [`super::component::Component`]
#[derive_where(Clone)]
pub struct Node<T, D: Desc + ?Sized> {
    pub props: Rc<T>,
    pub id: std::sync::Weak<SourceID>,
    pub children: D::Children,
    pub renderable: Option<Rc<dyn Renderable>>,
    pub layer: Option<(sRGB32, f32)>,
}

impl<T, D: Desc + ?Sized> Layout<T> for Node<T, D>
where
    for<'a> &'a T: Into<&'a D::Props>,
{
    fn get_props(&self) -> &T {
        self.props.as_ref()
    }
    fn stage<'a>(
        &self,
        area: PxRect,
        limits: PxLimits,
        window: &mut crate::component::window::WindowState,
    ) -> Box<dyn Staged + 'a> {
        let mut staged = D::stage(
            self.props.as_ref().into(),
            area,
            limits,
            &self.children,
            self.id.clone(),
            self.renderable.as_ref().map(|x| x.clone()),
            window,
        );
        if let Some((color, rotation)) = self.layer {
            window.driver.shared.create_layer(
                &window.driver.device,
                self.id.upgrade().unwrap(),
                staged.get_area().to_untyped(),
                None,
                color,
                rotation,
                false,
            );
            staged.set_layer(self.id.clone());
        }
        staged
    }
}

pub trait Staged: DynClone {
    fn render(
        &self,
        parent_pos: PxPoint,
        driver: &crate::graphics::Driver,
        compositor: &mut CompositorView<'_>,
        dependents: &mut Vec<std::sync::Weak<SourceID>>,
    ) -> Result<(), Error>;
    fn get_rtree(&self) -> Weak<rtree::Node>;
    fn get_area(&self) -> PxRect;
    fn set_layer(&mut self, _id: std::sync::Weak<SourceID>) {
        panic!("This staged object doesn't support layers!");
    }
}

dyn_clone::clone_trait_object!(Staged);

#[derive(Clone)]
pub(crate) struct Concrete {
    renderable: Option<Rc<dyn Renderable>>,
    area: PxRect,
    rtree: Rc<rtree::Node>,
    children: im::Vector<Option<Box<dyn Staged>>>,
    layer: Option<std::sync::Weak<SourceID>>,
}

impl Concrete {
    pub fn new(
        renderable: Option<Rc<dyn Renderable>>,
        area: PxRect,
        rtree: Rc<rtree::Node>,
        children: im::Vector<Option<Box<dyn Staged>>>,
    ) -> Self {
        debug_assert!(area.v.is_finite().all());
        let (unsized_x, unsized_y) = check_unsized_abs(area.bottomright());
        assert!(
            !unsized_x && !unsized_y,
            "concrete area must always be sized!: {area:?}",
        );
        Self {
            renderable,
            area,
            rtree,
            children,
            layer: None,
        }
    }

    fn render_self(
        &self,
        parent_pos: PxPoint,
        driver: &crate::graphics::Driver,
        compositor: &mut CompositorView<'_>,
    ) -> Result<(), Error> {
        debug_assert!(self.area.v.is_finite().all());
        if let Some(r) = &self.renderable {
            r.render((self.area + parent_pos).to_untyped(), driver, compositor)?;
        }
        Ok(())
    }

    fn render_children(
        &self,
        parent_pos: PxPoint,
        driver: &crate::graphics::Driver,
        compositor: &mut CompositorView<'_>,
        dependents: &mut Vec<std::sync::Weak<SourceID>>,
    ) -> Result<(), Error> {
        for child in (&self.children).into_iter().flatten() {
            // TODO: If we assign z-indexes to children, ones with negative z-indexes should
            // be rendered before the parent
            child.render(
                parent_pos + self.area.topleft().to_vector(),
                driver,
                compositor,
                dependents,
            )?;
        }
        Ok(())
    }
}

impl Staged for Concrete {
    fn render(
        &self,
        parent_pos: PxPoint,
        driver: &crate::graphics::Driver,
        compositor: &mut CompositorView<'_>,
        dependents: &mut Vec<std::sync::Weak<SourceID>>,
    ) -> Result<(), Error> {
        if let Some(id) = self.layer.as_ref().and_then(|x| x.upgrade()) {
            let layers = driver.shared.access_layers();
            let layer = layers.get(&id).expect("Missing layer in render call!");
            let mut deps = Vec::new();
            let mut region_uv = None;

            let (mut view, depview) = if layer.target.is_some() {
                // If this is a "real" layer with a texture target, mark it as a dependency of
                // our parent
                dependents.push(Arc::downgrade(&id));

                // Acquire a region if we don't have one already. This is done carefully so that
                // the layer can be moved to a different dependency layer and
                // therefore switched to a different atlas without the user render functions
                // needing to care.
                let index = match compositor.index {
                    0 => 1,
                    1 => 2,
                    2 => 1,
                    _ => panic!("Invalid index!"),
                };

                let mut atlas = driver.layer_atlas[index - 1].write();
                let region = atlas.cache_region(
                    &driver.device,
                    &id,
                    layer.area.dim().ceil().to_i32(),
                    None,
                    None,
                )?;
                region_uv = Some(region.uv);

                // Make sure we aren't cached in the opposite atlas
                driver.layer_atlas[index % 2].write().remove_cache(&id);
                assert!(compositor.pass < 0b111111);

                let mut v = CompositorView {
                    index: index as u8,
                    window: compositor.window,
                    layer0: compositor.layer0,
                    layer1: compositor.layer1,
                    clipstack: compositor.clipstack,
                    offset: region.uv.min.to_f32() - layer.area.topleft() - parent_pos.to_vector(),
                    surface_dim: compositor.surface_dim,
                    pass: compositor.pass + 1,
                    slice: region.index,
                };

                v.reserve(driver);
                // And return a reference to a new dependency vector
                (v, &mut deps)
            } else {
                // Otherwise, we don't create a new compositor view, instead copying our
                // previous one, and passing in the parent's dependency tracker.
                (
                    CompositorView {
                        index: compositor.index,
                        window: compositor.window,
                        layer0: compositor.layer0,
                        layer1: compositor.layer1,
                        clipstack: compositor.clipstack,
                        offset: compositor.offset,
                        surface_dim: compositor.surface_dim,
                        pass: compositor.pass,
                        slice: compositor.slice,
                    },
                    dependents,
                )
            };

            // Always push a new clipping area, but remember that a layer can only store
            // it's relative area.
            view.with_clip(layer.area + parent_pos, |refview| {
                self.render_self(parent_pos, driver, refview)?;
                self.render_children(parent_pos, driver, refview, depview)
            })?;

            if let Some(target) = layer.target.as_ref() {
                // If this was a real layer, now we need to actually assign the result of our
                // dependencies, and append ourselves to the parent layer. We
                // must be very careful not to use the wrong view here.
                target.write().dependents = deps;
                compositor.append_layer(layer, parent_pos, region_uv.unwrap());
            }
        } else {
            self.render_self(parent_pos, driver, compositor)?;
            self.render_children(parent_pos, driver, compositor, dependents)?;
        };

        Ok(())
    }

    fn get_rtree(&self) -> Weak<rtree::Node> {
        Rc::downgrade(&self.rtree)
    }

    fn get_area(&self) -> PxRect {
        self.area
    }

    fn set_layer(&mut self, id: std::sync::Weak<SourceID>) {
        self.layer = Some(id)
    }
}

#[must_use]
#[inline]
pub(crate) fn map_unsized_area(mut area: URect, adjust: PxDim) -> URect {
    let (unsized_x, unsized_y) = check_unsized(area);
    let abs = area.abs.v.as_array_mut();
    let rel = area.rel.v.as_array_mut();
    // Unsized objects must always have a single anchor point to make sense, so we
    // copy over from topleft.
    if unsized_x {
        rel[2] = rel[0];
        // Fix the bottomright abs area in unsized scenarios, because it was relative to
        // the topleft instead of being independent.
        abs[2] += abs[0] + adjust.width;
    }
    if unsized_y {
        rel[3] = rel[1];
        abs[3] += abs[1] + adjust.height;
    }
    area
}

#[must_use]
#[inline]
pub(crate) fn nuetralize_unsized(v: PxRect) -> PxRect {
    let (unsized_x, unsized_y) = check_unsized_abs(v.bottomright());
    let ltrb = v.v.to_array();
    PxRect {
        v: f32x4::new([
            ltrb[0],
            ltrb[1],
            if unsized_x { ltrb[0] } else { ltrb[2] },
            if unsized_y { ltrb[1] } else { ltrb[3] },
        ]),
        _unit: PhantomData,
    }
}

#[must_use]
#[inline]
pub(crate) fn limit_area(mut v: PxRect, limits: PxLimits) -> PxRect {
    // We do this by checking clamp(topleft + limit) instead of clamp(bottomright -
    // topleft) because this avoids floating point precision issues.
    v.set_bottomright(
        v.bottomright()
            .max(v.topleft() + limits.min())
            .min(v.topleft() + limits.max()),
    );
    v
}

#[must_use]
#[inline]
pub(crate) fn limit_dim(v: PxDim, limits: PxLimits) -> PxDim {
    let (unsized_x, unsized_y) = check_unsized_dim(v);
    PxDim::new(
        if unsized_x {
            v.width
        } else {
            v.width.max(limits.min().width).min(limits.max().width)
        },
        if unsized_y {
            v.height
        } else {
            v.height.max(limits.min().height).min(limits.max().height)
        },
    )
}

#[must_use]
#[inline]
pub(crate) fn eval_dim(area: URect, dim: PxDim) -> PxDim {
    let (unsized_x, unsized_y) = check_unsized(area);
    PxDim::new(
        if unsized_x {
            area.bottomright().rel().x
        } else {
            let top = area.topleft().abs().x + (area.topleft().rel().x * dim.width);
            let bottom = area.bottomright().abs().x + (area.bottomright().rel().x * dim.width);
            bottom - top
        },
        if unsized_y {
            area.bottomright().rel().y
        } else {
            let top = area.topleft().abs().y + (area.topleft().rel().y * dim.height);
            let bottom = area.bottomright().abs().y + (area.bottomright().rel().y * dim.height);
            bottom - top
        },
    )
}

#[must_use]
#[inline]
pub(crate) fn apply_limit(dim: PxDim, limits: PxLimits, rlimits: RelLimits) -> PxLimits {
    let (unsized_x, unsized_y) = check_unsized_dim(dim);
    let sign = limits.v.sign_bit() | rlimits.v.sign_bit();

    let px = f32x4::new([
        if unsized_x {
            limits.min().width
        } else {
            limits.min().width.max(dim.width)
        },
        if unsized_y {
            limits.min().height
        } else {
            limits.min().height.max(dim.height)
        },
        if unsized_x {
            limits.max().width
        } else {
            limits.max().width.min(dim.width)
        },
        if unsized_y {
            limits.max().height
        } else {
            limits.max().height.min(dim.height)
        },
    ]);

    PxLimits {
        v: (rlimits.v.is_finite().blend(px, f32x4::ONE) * rlimits.v).copysign(sign),
        _unit: PhantomData,
    }
}

// Returns true if an axis is unsized, which means it is defined as the size of
// it's children's maximum extent.
#[must_use]
#[inline]
pub(crate) fn check_unsized(area: URect) -> (bool, bool) {
    (
        area.bottomright().rel().x == UNSIZED_AXIS,
        area.bottomright().rel().y == UNSIZED_AXIS,
    )
}

// Returns true if an axis is unsized, which means it is defined as the size of
// it's children's maximum extent.
#[must_use]
#[inline]
pub(crate) fn check_unsized_abs<U>(bottomright: Point2D<f32, U>) -> (bool, bool) {
    (bottomright.x == UNSIZED_AXIS, bottomright.y == UNSIZED_AXIS)
}

// Returns true if an axis is unsized, which means it is defined as the size of
// it's children's maximum extent.
#[must_use]
#[inline]
pub(crate) fn check_unsized_dim(dim: PxDim) -> (bool, bool) {
    check_unsized_abs(dim.to_vector().to_point())
}

pub(crate) fn assert_sized(area: PxRect) {
    let ltrb = area.v.as_array_ref();

    for v in ltrb {
        assert_ne!(*v, UNSIZED_AXIS);
        assert!(v.is_finite());
    }
}

#[must_use]
#[inline]
pub(crate) fn cap_unsized(area: PxRect) -> PxRect {
    let ltrb = area.v.to_array();
    PxRect {
        v: f32x4::new(ltrb.map(|x| {
            if x.is_finite() {
                x
            } else {
                crate::UNSIZED_AXIS
            }
        })),
        _unit: PhantomData,
    }
}

#[must_use]
#[inline]
pub(crate) fn apply_anchor(area: PxRect, outer_area: PxRect, mut anchor: PxPoint) -> PxRect {
    let (unsized_outer_x, unsized_outer_y) = check_unsized_abs(outer_area.bottomright());
    if unsized_outer_x {
        anchor.x = 0.0;
    }
    if unsized_outer_y {
        anchor.y = 0.0;
    }
    area - anchor
}

#[must_use]
#[inline]
fn swap_pair<T>(xaxis: bool, v: (T, T)) -> (T, T) {
    if xaxis { (v.0, v.1) } else { (v.1, v.0) }
}

trait Swappable<T> {
    fn swap_axis(self, xaxis: bool) -> (T, T);
}

impl<T, U> Swappable<T> for Point2D<T, U> {
    #[inline]
    fn swap_axis(self, xaxis: bool) -> (T, T) {
        swap_pair(xaxis, (self.x, self.y))
    }
}

impl<T, U> Swappable<T> for guillotiere::euclid::Size2D<T, U> {
    #[inline]
    fn swap_axis(self, xaxis: bool) -> (T, T) {
        swap_pair(xaxis, (self.width, self.height))
    }
}

impl<T, U> Swappable<T> for Vector2D<T, U> {
    #[inline]
    fn swap_axis(self, xaxis: bool) -> (T, T) {
        swap_pair(xaxis, (self.x, self.y))
    }
}

/// If prev is NAN, always returns zero, which is the correct action for margin
/// edges.
#[must_use]
#[inline]
fn merge_margin(prev: f32, margin: f32) -> f32 {
    if prev.is_nan() { 0.0 } else { margin.max(prev) }
}