frui_core 0.0.1

Core functionality of Frui UI framework
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
use std::{
    cell::{Ref, RefMut},
    marker::PhantomData,
    ops::{AddAssign, Deref, DerefMut},
    sync::atomic::Ordering,
};

use druid_shell::{kurbo::Point, IdleToken};

use crate::{
    api::events::Event,
    app::{
        runner::{handler::APP_HANDLE, PaintContext},
        tree::WidgetNodeRef,
    },
    prelude::{MultiChildWidget, SingleChildWidget, WidgetState},
};

#[derive(Debug, Clone, Copy, Default)]
pub struct Offset {
    pub x: f64,
    pub y: f64,
}

impl From<Offset> for Point {
    fn from(offset: Offset) -> Self {
        Point {
            x: offset.x,
            y: offset.y,
        }
    }
}

impl From<&Offset> for Point {
    fn from(offset: &Offset) -> Self {
        Point {
            x: offset.x,
            y: offset.y,
        }
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub struct Size {
    pub width: f64,
    pub height: f64,
}

impl Size {
    pub fn new(width: f64, height: f64) -> Self {
        Self { width, height }
    }
}

impl From<druid_shell::kurbo::Size> for Size {
    fn from(size: druid_shell::kurbo::Size) -> Self {
        Self {
            width: size.width,
            height: size.height,
        }
    }
}

impl From<Size> for druid_shell::kurbo::Size {
    fn from(size: Size) -> Self {
        Self {
            width: size.width,
            height: size.height,
        }
    }
}

impl AddAssign for Size {
    fn add_assign(&mut self, rhs: Self) {
        self.width += rhs.width;
        self.height += rhs.height;
    }
}

impl PartialEq for Size {
    fn eq(&self, other: &Self) -> bool {
        self.width == other.width && self.height == other.height
    }
}

impl PartialOrd for Size {
    fn partial_cmp(&self, _: &Self) -> Option<std::cmp::Ordering> {
        None
    }

    fn lt(&self, other: &Self) -> bool {
        self.width < other.width || self.height < other.height
    }

    fn le(&self, other: &Self) -> bool {
        self.width <= other.width || self.height <= other.height
    }

    fn gt(&self, other: &Self) -> bool {
        self.width > other.width || self.height > other.height
    }

    fn ge(&self, other: &Self) -> bool {
        self.width >= other.width || self.height >= other.height
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub struct Constraints {
    pub min_width: f64,
    pub max_width: f64,
    pub min_height: f64,
    pub max_height: f64,
}

impl Constraints {
    pub fn max(&self) -> Size {
        Size {
            width: self.max_width,
            height: self.max_height,
        }
    }

    pub fn loosen(&self) -> Self {
        Self {
            min_width: 0.0,
            max_width: self.max_width,
            min_height: 0.0,
            max_height: self.max_height,
        }
    }

    pub fn tighten(&self) -> Self {
        Self {
            min_width: self.max_width,
            max_width: self.max_width,
            min_height: self.max_height,
            max_height: self.max_height,
        }
    }
}

pub trait RenderState {
    type State: 'static;

    fn create_state(&self) -> Self::State;
}

pub type RenderContext<'a, T> = &'a mut _RenderContext<'a, T>;

pub struct _RenderContext<'a, T> {
    ctx: &'a mut AnyRenderContext,
    _p: PhantomData<T>,
}

impl<'a, T> _RenderContext<'a, T> {
    pub(crate) fn new(any: &'a mut AnyRenderContext) -> Self {
        Self {
            ctx: any,
            _p: PhantomData,
        }
    }

    /// Render state.
    pub fn rstate(&self) -> Ref<T::State>
    where
        T: RenderState,
    {
        Ref::map(self.ctx.node.borrow(), |node| {
            node.render_data.state.deref().downcast_ref().unwrap()
        })
    }

    /// Render state mutably.
    pub fn rstate_mut(&mut self) -> RefMut<T::State>
    where
        T: RenderState,
    {
        RefMut::map(self.ctx.node.borrow_mut(), |node| {
            node.render_data.state.deref_mut().downcast_mut().unwrap()
        })
    }

    /// Widget state.
    pub fn wstate(&self) -> Ref<T::State>
    where
        T: WidgetState,
    {
        Ref::map(self.ctx.node.borrow(), |node| {
            node.state.deref().downcast_ref().unwrap()
        })
    }

    /// Widget state mutably.
    pub fn wstate_mut(&self) -> RefMut<T::State>
    where
        T: WidgetState,
    {
        if !STATE_UPDATE_SUPRESSED.load(Ordering::SeqCst) {
            self.ctx.node.mark_dirty();
        }

        RefMut::map(self.ctx.node.borrow_mut(), |node| {
            node.state.deref_mut().downcast_mut().unwrap()
        })
    }

    pub fn schedule_layout(&mut self) {
        APP_HANDLE.with(|handle| {
            handle
                .borrow_mut()
                .as_mut()
                .expect("APP_HANDLE wasn't set")
                .schedule_idle(IdleToken::new(0));
        });
    }

    //

    pub fn child(&mut self) -> ChildContext
    where
        T: SingleChildWidget,
    {
        self.ctx.child()
    }

    pub fn children(&mut self) -> ChildIter
    where
        T: MultiChildWidget,
    {
        self.ctx.children()
    }

    //

    #[track_caller]
    pub fn size(&self) -> Size {
        self.ctx.node.borrow().render_data.size
    }

    #[track_caller]
    pub fn offset(&self) -> Offset {
        self.ctx.node.borrow().render_data.offset
    }

    pub fn point_in_layout_bounds(&self, point: Point) -> bool {
        let Offset { x: o_x, y: o_y } = self.offset();
        let Point { x, y } = point;

        // Make point position local to the tested widget origin.
        let (x, y) = (x - o_x, y - o_y);

        let Size { width, height } = self.size();

        // Check if that point is in the widget bounds computed during layout.
        x >= 0.0 && x <= width && y >= 0.0 && y <= height
    }
}

pub struct ChildContext<'a> {
    ctx: AnyRenderContext,
    _p: PhantomData<&'a ()>,
}

impl<'a> ChildContext<'a> {
    pub fn size(&self) -> Size {
        self.ctx.node.borrow().render_data.size
    }

    pub fn try_data<'b, T: 'static>(&'b self) -> Option<Ref<'b, T>> {
        self.ctx
            .node
            .borrow()
            .render_data
            .state
            .downcast_ref::<T>()?;

        Some(Ref::map(self.ctx.node.borrow(), |node| {
            node.render_data.state.downcast_ref().unwrap()
        }))
    }

    pub fn layout(&mut self, constraints: Constraints) -> Size {
        let size = self.ctx.layout(constraints.clone());

        if cfg!(debug_assertions) {
            if size > constraints.max() {
                if self.ctx.node.widget().debug_name_short() != "DebugContainer" {
                    log::warn!("`{}` overflowed", self.ctx.node.widget().debug_name_short());
                }
            }
        }

        self.ctx.node.borrow_mut().render_data.laid_out = true;

        size
    }

    #[track_caller]
    pub fn paint(&mut self, canvas: &mut PaintContext, offset: &Offset) {
        assert!(
            self.ctx.node.borrow().render_data.laid_out,
            "child was not laid out"
        );
        self.ctx.node.borrow_mut().render_data.offset = *offset;
        self.ctx.paint(canvas, offset)
    }

    #[track_caller]
    pub fn handle_event(&mut self, event: &Event) {
        self.ctx.handle_event(event)
    }
}

pub struct AnyRenderContext {
    node: WidgetNodeRef,
}

impl AnyRenderContext {
    pub(crate) fn new(node: WidgetNodeRef) -> Self {
        Self { node }
    }

    pub(crate) fn child(&mut self) -> ChildContext {
        let child_node = self
            .node
            .children()
            .get(0)
            .expect("specified node didn't have any children");

        ChildContext {
            ctx: AnyRenderContext::new(crate::app::tree::WidgetNode::node_ref(child_node)),
            _p: PhantomData,
        }
    }

    pub(crate) fn children(&mut self) -> ChildIter {
        ChildIter {
            child_idx: 0,
            parent: &self.node,
        }
    }

    pub(crate) fn layout(&mut self, constraints: Constraints) -> Size {
        let widget = self.node.widget().clone();

        let size = widget.layout(self, constraints);

        self.node.borrow_mut().render_data.size = size;

        size
    }

    pub(crate) fn paint(&mut self, piet: &mut PaintContext, offset: &Offset) {
        self.node.widget().clone().paint(self, piet, offset);
    }

    pub(crate) fn handle_event(&mut self, event: &Event) {
        self.node.widget().clone().handle_event(self, event);
    }
}

pub struct ChildIter<'a> {
    child_idx: usize,
    parent: &'a WidgetNodeRef,
}

impl<'a> ChildIter<'a> {
    pub fn len(&self) -> usize {
        self.parent.children().len()
    }
}

impl<'a> Iterator for ChildIter<'a> {
    type Item = ChildContext<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let next_child = match self.parent.children().get(self.child_idx) {
            Some(c) => c,
            None => return None,
        };

        self.child_idx += 1;

        Some(ChildContext {
            ctx: AnyRenderContext::new(crate::app::tree::WidgetNode::node_ref(next_child)),
            _p: PhantomData,
        })
    }
}

pub(crate) use sealed::RenderStateOS;

use super::build_ctx::STATE_UPDATE_SUPRESSED;

mod sealed {
    use std::any::Any;

    pub trait RenderStateOS {
        fn create_render_state(&self) -> Box<dyn Any>;
    }

    impl<T> RenderStateOS for T {
        default fn create_render_state(&self) -> Box<dyn Any> {
            Box::new(())
        }
    }

    impl<T: super::RenderState> RenderStateOS for T {
        fn create_render_state(&self) -> Box<dyn Any> {
            Box::new(T::create_state(&self))
        }
    }
}