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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2025 Fundament Research Institute <https://fundament.institute>

use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use crate::component::window::WindowNodeTrack;
use crate::input::{MouseState, RawEvent, RawEventKind, TouchState};
use crate::persist::{FnPersist2, Persist2, VectorFold};
use crate::{
    Dispatchable, InputResult, Pixel, PxPoint, PxRect, PxVector, RelDim, SourceID, StateManager,
    WindowStateMachine,
};
use guillotiere::euclid::Point3D;
use std::rc::Rc;
use winit::dpi::PhysicalPosition;

pub struct Node {
    pub area: PxRect, /* This is the calculated area of the node from the layout relative to the
                       * topleft corner of the parent. */
    pub extent: PxRect, /* This is the minimal bounding rectangle of the children's extent
                         * relative to OUR topleft corner. */
    pub top: i32, /* 2D R-tree nodes are actually 3 dimensional, but the z-axis can never
                   * overlap (because layout rects have no depth). */
    pub bottom: i32,
    pub mask: AtomicU64,
    pub id: std::sync::Weak<SourceID>,
    pub children: im::Vector<Option<Rc<Node>>>,
    pub parent: std::cell::OnceCell<std::rc::Weak<Node>>,
}

// A tuple like this is necessary to build a chain of parent nodes down the
// recursive process call, but we currently don't need it. This is left here as
// reference. pub struct ParentTuple<'a>(&'a Rc<Node>, Option<&'a
// ParentTuple<'a>>);

impl Node {
    pub fn new(
        area: PxRect,
        z: Option<i32>,
        children: im::Vector<Option<Rc<Node>>>,
        id: std::sync::Weak<SourceID>,
        window: &mut crate::component::window::WindowState,
    ) -> Rc<Self> {
        let this = Rc::new_cyclic(|this| {
            let mut fold = VectorFold::new(Persist2::new(
                |(rect, top, bottom): (PxRect, i32, i32),

                 n: &Option<Rc<Node>>|

                 -> (PxRect, i32, i32) {
                    let n = n.as_ref().unwrap();
                    (rect.extend(n.area), top.max(n.top), bottom.min(n.bottom))
                },
            ));

            // TODO: This is inefficient for large trees, but the alternative is to somehow
            // maintain a "capture" pointer on each rtree node, which requires
            // cooperation from the persistent data structure to maintain, which we don't
            // have right now.
            for child in &children {
                child.as_ref().unwrap().parent.get_or_init(|| this.clone());
            }

            // If no z index is provided for this node, try to use a zindex from the first
            // child. If there is no first child, default to 0
            let z = z.unwrap_or_else(|| {
                children
                    .front()
                    .map(|x| x.as_ref().unwrap().top)
                    .unwrap_or(0)
            });
            let (_, (extent, top, bottom)) =
                fold.call(fold.init(), (Default::default(), z, z), &children);

            Self {
                area,
                extent,
                top,
                bottom,
                id: id.clone(),
                children,
                parent: Default::default(),
                mask: u64::MAX.into(),
            }
        });

        if let Some(id) = id.upgrade() {
            window.update_node(id, Rc::downgrade(&this));
        }

        this
    }

    // This handles event postprocessing that must always happen, even for directly
    // injected events
    pub(crate) fn postprocess(
        self: &Rc<Self>,
        event: &RawEvent,
        dpi: RelDim,
        offset: PxVector,
        window_id: Arc<SourceID>,
        manager: &mut StateManager,
    ) -> InputResult<()> {
        match event {
            // If we successfully process a mousemove event, this node gains hover
            RawEvent::MouseMove {
                device_id,
                pos,
                modifiers,
                all_buttons,
            } => {
                let state = match manager.get_mut::<WindowStateMachine>(&window_id) {
                    Ok(v) => v,
                    Err(e) => return InputResult::Error(e),
                };

                let window = &mut state.state;

                // Either replace the old node, or simply remove it if this is not a valid focus
                // target
                let (old, valid) = if let Some(id) = self.id.upgrade() {
                    (
                        window.set(WindowNodeTrack::Hover, *device_id, id, Rc::downgrade(self)),
                        true,
                    )
                } else {
                    (window.remove(WindowNodeTrack::Hover, device_id), false)
                };

                let driver = Arc::downgrade(&window.driver);

                // Tell the old node that it lost hover (if it cares).
                if let Some(old) = old.and_then(|x| x.upgrade()) {
                    let evt = RawEvent::MouseOff {
                        device_id: *device_id,
                        modifiers: *modifiers,
                        all_buttons: *all_buttons,
                    };

                    // We don't care about the result of this event
                    let _ = old.inject_event(
                        &evt,
                        evt.kind(),
                        dpi,
                        PxVector::zero(),
                        window_id.clone(),
                        &driver,
                        manager,
                    );
                }

                // We delay injecting MouseOn until after an old node gets MouseOff to present
                // events in a sensible order
                if valid {
                    let evt = RawEvent::MouseOn {
                        device_id: *device_id,
                        modifiers: *modifiers,
                        pos: *pos,
                        all_buttons: *all_buttons,
                    };
                    let _ = self.inject_event(
                        &evt,
                        evt.kind(),
                        dpi,
                        offset,
                        window_id,
                        &driver,
                        manager,
                    );
                }
            }
            RawEvent::Mouse {
                device_id,
                state: MouseState::Up,
                all_buttons: 0,
                pos: crate::PxPoint { x, y, .. },
                ..
            }
            | RawEvent::Touch {
                device_id,
                state: TouchState::End,
                pos: Point3D::<f32, Pixel> { x, y, .. },
                ..
            } => {
                // On any mouseup event, uncapture the cursor if no buttons are down
                let state = match manager.get_mut::<WindowStateMachine>(&window_id) {
                    Ok(v) => v,
                    Err(e) => return InputResult::Error(e),
                };

                let window = &mut state.state;
                window.remove(WindowNodeTrack::Capture, device_id);
                let driver = Arc::downgrade(&window.driver);

                // We don't care if this is accepted or not
                let _ = crate::component::window::Window::on_window_event(
                    window_id,
                    Self::find_root(self.clone()),
                    winit::event::WindowEvent::CursorMoved {
                        device_id: *device_id,
                        position: PhysicalPosition::<f64>::new(*x as f64, *y as f64),
                    },
                    manager,
                    driver,
                );
            }
            _ => (),
        };

        InputResult::Consume(())
    }

    pub(crate) fn inject_event(
        self: &Rc<Self>,
        event: &RawEvent,
        kind: RawEventKind,
        dpi: RelDim,
        offset: PxVector,
        window_id: Arc<SourceID>,
        driver: &std::sync::Weak<crate::Driver>,
        manager: &mut StateManager,
    ) -> InputResult<u64> {
        if let Some(id) = self.id.upgrade()
            && let Ok(state) = manager.get_trait(&id)
        {
            let mask = state.input_mask();
            if (kind as u64 & mask) != 0 {
                match manager.process(
                    event.clone().extract(),
                    &crate::Slot(id.clone(), 0), /* TODO: We currently don't use the slot index
                                                  * here, but we might need to later */
                    dpi,
                    self.area + offset,
                    self.extent,
                    driver,
                ) {
                    Ok(false) => return InputResult::Forward(mask),
                    Ok(true) => (),
                    Err(e) => return InputResult::Error(e),
                }

                return self
                    .postprocess(event, dpi, offset, window_id, manager)
                    .map(|_| mask);
            }
            return InputResult::Forward(mask);
        }
        InputResult::Forward(u64::MAX)
    }

    // We allow this to return an invalid weak pointer because returning an
    // *invalid* root is a more obvious problem than returning the *wrong* node
    // as if it were the root (which can be very confusing).
    fn find_root(mut node: Rc<Node>) -> std::rc::Weak<Node> {
        while let Some(parent) = node.parent.get() {
            if let Some(n) = parent.upgrade() {
                node = n;
            } else {
                return parent.clone();
            }
        }
        Rc::downgrade(&node)
    }

    pub(crate) fn offset(mut node: Rc<Node>) -> PxVector {
        let mut offset = PxVector::zero();
        while let Some(parent) = node.parent.get().and_then(|x| x.upgrade()) {
            offset = (parent.area.topleft() + offset).to_vector();
            node = parent;
        }
        offset
    }

    pub fn process(
        self: &Rc<Self>,
        event: &RawEvent,
        kind: RawEventKind,
        position: PxPoint,
        offset: PxVector,
        dpi: RelDim,
        driver: &std::sync::Weak<crate::Driver>,
        manager: &mut StateManager,
        window_id: Arc<SourceID>,
    ) -> InputResult<()> {
        if (self.mask.load(Ordering::Acquire) & kind as u64) != 0
            && self.area.contains(position - offset)
        {
            let child_offset = self.area.topleft() + offset;

            let mut mask = 0;
            // Children should be sorted from top to bottom
            for child in self.children.iter().rev() {
                // TODO: Split these iterations into positive and negative z indexes, then call
                // this node after processing index 0 but before negative indices.
                let child = child.as_ref().unwrap();
                let r = child.process(
                    event,
                    kind,
                    position,
                    child_offset.to_vector(),
                    dpi,
                    driver,
                    manager,
                    window_id.clone(),
                );
                if !r.is_reject() {
                    // At this point, we should've already set focus, and are simply walking back up
                    // the stack
                    return r;
                }

                mask |= child.mask.load(Ordering::Relaxed);
            }

            let e = self.inject_event(event, kind, dpi, offset, window_id.clone(), driver, manager);
            match e {
                InputResult::Consume(m) | InputResult::Forward(m) => mask |= m,
                _ => (),
            };

            // This is only ever stored when a message has been rejected by all children and
            // this node. It's mostly used as an optimization for large sets of
            // non-interactive nodes, but it could be made more aggressive.
            self.mask.store(mask, Ordering::Release);

            if e.is_accept() {
                match event {
                    // If we successfully process a mouse event, this node gains focus in it's
                    // parent window
                    RawEvent::Mouse {
                        device_id,
                        state: MouseState::Down,
                        pos: crate::PxPoint { x, y, .. },
                        ..
                    }
                    | RawEvent::Touch {
                        device_id,
                        state: TouchState::Start,
                        pos: Point3D::<f32, Pixel> { x, y, .. },
                        ..
                    } => {
                        let state = manager.get_mut::<WindowStateMachine>(&window_id);
                        let state = if let Err(e) = state {
                            return InputResult::Error(e);
                        } else {
                            state.unwrap()
                        };

                        let window = &mut state.state;
                        let inner = window.window.clone();

                        // Either replace the old node, or simply remove it if this is not a valid
                        // focus target
                        let (old, valid) = if let Some(id) = self.id.upgrade() {
                            // On any mousedown event, capture the cursor if it wasn't captured
                            // already
                            window.set(
                                WindowNodeTrack::Capture,
                                *device_id,
                                id.clone(),
                                Rc::downgrade(self),
                            );
                            (
                                window.set(
                                    WindowNodeTrack::Focus,
                                    *device_id,
                                    id,
                                    Rc::downgrade(self),
                                ),
                                true,
                            )
                        } else {
                            window.remove(WindowNodeTrack::Capture, device_id);
                            (window.remove(WindowNodeTrack::Focus, device_id), false)
                        };

                        // Tell the old node that it lost focus (if it cares).
                        if let Some(old) = old.and_then(|old| old.upgrade()) {
                            let evt = RawEvent::Focus {
                                acquired: false,
                                window: inner.clone(),
                            };

                            // We don't care about the result of this event
                            let _ = old.inject_event(
                                &evt,
                                evt.kind(),
                                dpi,
                                PxVector::zero(),
                                window_id.clone(),
                                driver,
                                manager,
                            );
                        }

                        // We delay injecting Focus until after the old node gets it's own Focus
                        // event to preserve a sensible ordering
                        if valid {
                            let evt = RawEvent::Focus {
                                acquired: true,
                                window: inner,
                            };
                            let _ = self.inject_event(
                                &evt,
                                evt.kind(),
                                dpi,
                                offset,
                                window_id.clone(),
                                driver,
                                manager,
                            );
                        } else {
                            // If this wasn't a valid node, we removed capture but didn't replace
                            // it, so we have to inject a mousemove event
                            let _ = crate::component::window::Window::on_window_event(
                                window_id.clone(),
                                Self::find_root(self.clone()),
                                winit::event::WindowEvent::CursorMoved {
                                    device_id: *device_id,
                                    position: PhysicalPosition::<f64>::new(*x as f64, *y as f64),
                                },
                                manager,
                                driver.clone(),
                            );
                        }
                    }
                    _ => (),
                }
            }
            return e.map(|_| ());
        }
        InputResult::Forward(())
    }
}

/*
// 2.5D node which contains a 2D r-tree, embedded inside the parent 3D space.
struct Node25 {
    pub area: AnyRect,
    pub extent: AnyRect,
    pub z: f32, // there is only one z coordinate because the contained area must be flat.
    pub transform: Rotor3,
    pub id: std::sync::Weak<SourceID>,
    pub children: im::Vector<Option<Rc<Node>>>,
}

// 3D node capable of arbitrary translation (though it's AABB must still be fully contained within it's parent node)[]
struct Node3D {
    pub area: AbsVolume,
    pub extent: AbsVolume,
    pub transform: Rotor3,
    pub id: std::sync::Weak<SourceID>,
    pub children: im::Vector<Either<Rc<Node3D>, Rc<Node25>>>,
}
*/