dfui 0.1.0

Declarative UI framework that draws shapes, text and icons analytically in one wgpu shader
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
use std::any::Any;
use std::borrow::Cow;
use std::marker::PhantomData;
use std::rc::Rc;
use web_time::Instant;

use taffy::{AvailableSpace, Size, Style};

use crate::path::{Path, Quad, Shape};
use crate::render::{Bitmap, Color, Rect, Scene, Shadow};
use crate::runtime::task::Tasks;
use crate::text::{Font, Text, TextLayout};

#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum Event {
    PointerDown {
        x: f32,
        y: f32,
    },
    PointerMove {
        x: f32,
        y: f32,
    },
    PointerUp {
        x: f32,
        y: f32,
    },
    /// Mouse wheel, logical pixels, positive scrolls content up.
    Wheel {
        x: f32,
        y: f32,
        dy: f32,
    },
    /// Another widget captured the pointer; drop any in-progress gesture.
    Cancel,
    /// The pointer is gone: finger lifted or cursor left the window.
    Leave,
    /// Text typed while this widget has focus.
    Text(String),
    /// Editing key pressed while this widget has focus.
    Key(Key),
    /// Escape, or the Android back button: sent topmost first, so the
    /// uppermost overlay can dismiss itself and stop it.
    Back,
}

/// The soft keyboard a text field asks for.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Keyboard {
    #[default]
    Text,
    Number,
    Email,
    /// Keeps what's typed out of suggestions and the keyboard's learning.
    Password,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Key {
    Backspace,
    Delete,
    /// Deletes whole graphemes covering this many UTF-16 units before the
    /// caret, the unit Android keyboards count in.
    DeleteBefore(usize),
    Left,
    Right,
    Home,
    End,
    SelectAll,
    Copy,
    Cut,
}

/// A retained node description. `view` rebuilds the tree; framework-owned
/// per-widget state survives rebuilds, keyed by tree position or `key`.
pub struct Element {
    pub(crate) widget: Box<dyn Widget>,
    pub(crate) key: Option<u64>,
}

impl Element {
    pub fn new(w: impl Widget + 'static) -> Self {
        Element {
            widget: Box::new(w),
            key: None,
        }
    }

    /// Stable identity for state across rebuilds, e.g. items in a reorderable list.
    pub fn key(mut self, key: u64) -> Self {
        self.key = Some(key);
        self
    }
}

/// Boxes [`Widget::scroll`] works from, logical px.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Placement {
    /// What children are clipped to: the widget's box, or for a
    /// [`Layer::Parent`] widget the box its children rest in, moved to stay in
    /// the window.
    pub clip: Rect,
    /// Where a layer's children rest before scrolling; `clip` otherwise.
    pub rest: Rect,
    /// A layer's anchor: its parent's box, or the window; `clip` otherwise.
    pub anchor: Rect,
    /// Extent of the children, for a scroller's range.
    pub content: Size<f32>,
}

/// What a layer widget is laid out over.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Layer {
    /// Its parent's box, e.g. a dropdown menu or tooltip.
    Parent,
    /// The window, inside the system bars, e.g. a dialog or drawer.
    Window,
}

/// Primitive building block. Composite widgets are plain functions returning
/// [`Element`]; implement this only for new layout/paint/input behavior.
pub trait Widget {
    fn style(&self) -> Style {
        Style::default()
    }

    fn children(&self) -> &[Element] {
        &[]
    }

    /// Runs before `children` with this node's id, state slot and providers;
    /// lets a widget build its subtree from framework-owned state.
    fn expand(&self, _cx: &mut BuildCx) {}

    /// Takes this subtree out of the layout flow: it covers [`Layer`]'s box,
    /// isn't clipped by ancestors, paints above and gets input before the
    /// rest of the tree.
    fn layer(&self) -> Option<Layer> {
        None
    }

    /// Whether this subtree is drawn but ignores the pointer.
    fn inert(&self) -> bool {
        false
    }

    /// Value made available to descendants through [`Scope::get`].
    fn provide(&self) -> Option<&dyn Any> {
        None
    }

    /// Intrinsic size of a leaf (children-less) widget.
    fn measure(
        &self,
        _known: Size<Option<f32>>,
        _available: Size<AvailableSpace>,
        _text: &Text,
    ) -> Size<f32> {
        Size::ZERO
    }

    /// Hash of everything `measure` reads besides its arguments. Layout is
    /// kept across rebuilds and a leaf is only re-measured when this changes,
    /// so widgets whose size depends on their data must override it.
    fn measure_key(&self) -> u64 {
        0
    }

    /// Children are clipped to `at.clip` and shifted by the returned offset,
    /// as of frame time `now`.
    fn scroll(&self, _state: &mut State, _at: Placement, _now: Instant) -> Option<(f32, f32)> {
        None
    }

    /// Whether children moved by `scroll` are clipped to this widget's box.
    fn clips(&self) -> bool {
        true
    }

    fn paint(&self, _cx: &mut PaintCx) {}

    /// Pointer events reach a widget while the pointer is over it, once more
    /// when it leaves, and throughout a press that began on it; layers get
    /// them all.
    fn event(&self, _ev: &Event, _cx: &mut EventCx) {}
}

/// Framework-owned per-widget state slot.
#[derive(Default)]
pub struct State(Option<Box<dyn Any>>);

impl State {
    pub fn get<T: Default + 'static>(&mut self) -> &mut T {
        self.get_or_insert_with(T::default)
    }

    pub(crate) fn get_or_insert_with<T: 'static>(&mut self, init: impl FnOnce() -> T) -> &mut T {
        if !self.0.as_ref().is_some_and(|b| b.is::<T>()) {
            self.0 = Some(Box::new(init()));
        }
        self.0.as_mut().unwrap().downcast_mut().unwrap()
    }
}

/// Typed reference to a stateful widget's state, cheap to capture in handlers.
pub struct Handle<S> {
    pub(crate) id: u64,
    _s: PhantomData<fn() -> S>,
}

impl<S> Handle<S> {
    pub(crate) fn new(id: u64) -> Self {
        Handle {
            id,
            _s: PhantomData,
        }
    }
}

impl<S> Clone for Handle<S> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<S> Copy for Handle<S> {}

pub(crate) type Update = (u64, Box<dyn FnOnce(&mut State)>);

/// Values provided by ancestors (`provide`), innermost last.
#[derive(Clone, Copy)]
pub struct Scope<'a>(pub(crate) &'a [&'a dyn Any]);

impl<'a> Scope<'a> {
    /// The nearest ancestor-provided `T`.
    pub fn get<T: 'static>(&self) -> Option<&'a T> {
        self.0.iter().rev().find_map(|v| v.downcast_ref())
    }
}

pub struct BuildCx<'a> {
    pub id: u64,
    pub state: &'a mut State,
    pub scope: Scope<'a>,
    pub(crate) tasks: &'a mut Tasks,
}

pub struct PaintCx<'a> {
    /// Frame time, shared by every widget painted this frame.
    pub now: Instant,
    pub rect: Rect,
    pub clip: Rect,
    pub focused: bool,
    pub theme: &'a crate::Theme,
    pub state: &'a mut State,
    pub(crate) scene: &'a mut Scene,
    pub(crate) text: &'a mut Text,
    pub(crate) frame: &'a mut bool,
    pub(crate) wake: &'a mut Option<Instant>,
    pub(crate) place: &'a mut bool,
    pub(crate) rebuild: &'a mut bool,
}

impl PaintCx<'_> {
    /// `ink` in this widget's theme.
    pub fn color(&self, ink: impl Into<crate::Ink>) -> Color {
        match ink.into() {
            crate::Ink::Fixed(c) => c,
            crate::Ink::Role(r) => self.theme.color(r),
            crate::Ink::Content => self.theme.ink,
        }
    }

    /// Rebuild the tree after this frame, for widgets that build their
    /// children from what is on screen (a virtualized list scrolled past
    /// the rows it built).
    pub fn request_rebuild(&mut self) {
        *self.frame = true;
        *self.rebuild = true;
    }

    /// Paint again next frame, for animations or live readouts.
    pub fn request_frame(&mut self) {
        *self.frame = true;
    }

    /// Re-run placement ([`Widget::scroll`]) and paint again next frame, for
    /// animated scroll offsets.
    pub fn request_placement(&mut self) {
        *self.frame = true;
        *self.place = true;
    }

    /// Paint again at `t`, for slow animations like a caret blink; the
    /// runtime sleeps until then instead of painting every frame.
    pub fn request_frame_at(&mut self, t: Instant) {
        *self.wake = Some(self.wake.map_or(t, |w| w.min(t)));
    }

    /// Fills `path` through the glyph renderer.
    pub fn path(&mut self, path: &Path, color: Color) {
        self.fill_path(path, None, color);
    }

    /// Fills `path` only where `mask` covers it: the edges stay `path`'s, and
    /// `mask` just decides how much shows, e.g. to reveal a shape progressively.
    pub fn path_masked(&mut self, path: &Path, mask: &Path, color: Color) {
        self.fill_path(path, Some(mask), color);
    }

    fn fill_path(&mut self, path: &Path, mask: Option<&Path>, color: Color) {
        let quads = || path.contours.iter().flatten();
        let mask_quads = || mask.into_iter().flat_map(|m| m.contours.iter().flatten());
        let (mut lo, mut hi) = ([f32::MAX; 2], [f32::MIN; 2]);
        for p in quads().chain(mask_quads()).flatten() {
            lo = [lo[0].min(p[0]), lo[1].min(p[1])];
            hi = [hi[0].max(p[0]), hi[1].max(p[1])];
        }
        let span = (hi[0] - lo[0]).max(hi[1] - lo[1]);
        if !span.is_finite() || span <= 0.0 || mask.is_some_and(|m| m.contours.is_empty()) {
            return;
        }
        // Stored like a glyph: y up, scaled to a unit box, which keeps the
        // shader's line test and precision where glyphs have them.
        let s = 1.0 / span;
        let unit = |q: &Quad| q.map(|[x, y]| [(x - lo[0]) * s, (hi[1] - y) * s]);
        // Out-and-back slivers at the corners give a path and its mask one
        // box, so the shader reads both with the same coordinates.
        let far = [(hi[0] - lo[0]) * s, (hi[1] - lo[1]) * s];
        let (p0, p1, p2, p3) = ([0.0; 2], [1e-4, 0.0], far, [far[0] - 1e-4, far[1]]);
        let rim = [[p0, p0, p1], [p1, p1, p0], [p2, p2, p3], [p3, p3, p2]];
        let corners = mask.map(|_| rim).into_iter().flatten();
        // 1px padding keeps the edge antialiasing.
        let body = quads().map(unit).chain(corners).collect();
        let Some(g) = self.text.outlines.transient(body, s) else {
            return;
        };
        let cover = mask.and_then(|_| {
            let edge = mask_quads().map(unit).chain(rim);
            self.text.outlines.transient(edge.collect(), s)
        });
        let [x0, y0, x1, y1] = g.bbox;
        let r = Rect::new(lo[0] + x0 / s, hi[1] - y1 / s, (x1 - x0) / s, (y1 - y0) / s);
        let bands = [g.header as f32, g.bands_h as f32, g.bands_v as f32];
        let cover = cover.map(|c| [c.header as f32, c.bands_h as f32, c.bands_v as f32]);
        self.scene
            .glyph(r, [x0, y1, x1, y0], color, self.clip, bands, cover);
    }

    /// `shape` with its view box mapped onto `r`; stored once, so drawing it
    /// at any size or every frame is cheap.
    pub fn shape(&mut self, shape: &Shape, r: Rect, color: Color) {
        self.text.draw_shape(shape, r, color, self.clip, self.scene);
    }

    /// Outline of `c` at `size` px, pen at the origin on the baseline.
    pub fn glyph_path(&self, font: Font, c: char, size: f32) -> Option<Path> {
        self.text.glyph_path(font, c, size)
    }

    pub fn fill(&mut self, r: Rect, radius: f32, color: Color) {
        self.scene
            .shape(r, radius, color, 0.0, Color::TRANSPARENT, self.clip);
    }

    pub fn fill_bordered(
        &mut self,
        r: Rect,
        radius: f32,
        color: Color,
        border: f32,
        border_color: Color,
    ) {
        self.scene
            .shape(r, radius, color, border, border_color, self.clip);
    }

    pub fn shadow(&mut self, r: Rect, radius: f32, s: Shadow) {
        self.scene.shadow(r, radius, s, self.clip);
    }

    /// `bitmap` stretched over `r`, multiplied by `tint` ([`Color::WHITE`] keeps it as is).
    pub fn image(&mut self, r: Rect, bitmap: &Bitmap, radius: f32, tint: Color) {
        self.scene.image(r, bitmap, radius, tint, self.clip);
    }

    /// Paints what `f` paints clipped to `r` as well.
    pub fn with_clip<R>(&mut self, r: Rect, f: impl FnOnce(&mut Self) -> R) -> R {
        let saved = self.clip;
        self.clip = saved.intersect(&r);
        let out = f(self);
        self.clip = saved;
        out
    }

    /// `s` cut to fit `max_lines` lines of `max_width`, ending in "…" when cut.
    pub fn truncate<'s>(
        &self,
        s: &'s str,
        font: Font,
        size: f32,
        max_width: f32,
        max_lines: usize,
    ) -> Cow<'s, str> {
        self.text.truncate(s, font, size, max_width, max_lines)
    }

    /// `s` laid out as `text` would draw it, for its `width` and `height`.
    pub fn measure(
        &self,
        s: &str,
        font: Font,
        size: f32,
        max_width: Option<f32>,
    ) -> Rc<TextLayout> {
        self.text.layout(s, font, size, max_width)
    }

    pub fn text(
        &mut self,
        s: &str,
        font: Font,
        size: f32,
        color: Color,
        max_width: Option<f32>,
        origin: (f32, f32),
    ) {
        self.text.draw(
            s, font, size, max_width, origin, color, self.clip, self.scene,
        );
    }
}

pub struct EventCx<'a> {
    /// When the event was dispatched.
    pub now: Instant,
    pub rect: Rect,
    pub clip: Rect,
    /// Extent of laid-out children, relative to this widget's origin.
    pub content: Size<f32>,
    pub focused: bool,
    /// Shift is held: arrows and clicks extend a selection.
    pub shift: bool,
    pub state: &'a mut State,
    pub(crate) text: &'a Text,
    pub(crate) updates: &'a mut Vec<Update>,
    pub(crate) copied: &'a mut Option<String>,
    pub(crate) capture: bool,
    pub(crate) focus: Option<Keyboard>,
    pub(crate) stop: bool,
    pub(crate) redraw: bool,
}

impl EventCx<'_> {
    pub fn hit(&self, x: f32, y: f32) -> bool {
        self.rect.contains(x, y) && self.clip.contains(x, y)
    }

    /// Modify a stateful widget's state after this event; its subtree is rebuilt.
    pub fn update<S: 'static>(&mut self, h: Handle<S>, f: impl FnOnce(&mut S) + 'static) {
        let apply = move |st: &mut State| {
            if let Some(s) = st.0.as_mut().and_then(|b| b.downcast_mut()) {
                f(s);
            }
        };
        self.updates.push((h.id, Box::new(apply)));
    }

    /// Route all pointer events to this widget until pointer up; others get `Cancel`.
    pub fn capture(&mut self) {
        self.capture = true;
    }

    /// Put `text` on the clipboard after this event.
    pub fn copy(&mut self, text: impl Into<String>) {
        *self.copied = Some(text.into());
    }

    /// Take keyboard focus; on touch devices this shows the given soft keyboard.
    pub fn focus(&mut self, keyboard: Keyboard) {
        self.focus = Some(keyboard);
    }

    /// Don't offer this event to ancestors.
    pub fn stop(&mut self) {
        self.stop = true;
    }

    pub fn request_redraw(&mut self) {
        self.redraw = true;
    }
}