guido 0.12.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
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
//! A leaf written from outside the crate, against the public API only.
//!
//! Two things have to hold for a third-party widget to be a first-class one:
//! it has to compile without reaching into the crate, and its signal reads
//! have to belong to *it*. The second is the framework's job on both passes
//! now — `layout_child` since #387, `paint_child` since #390 — so a widget
//! that opens no scope of its own is not punished for it. It was: a paint that
//! read a signal without a scope subscribed to nothing at all, drew once, and
//! then stayed as it was. The last test in this file is that one.
//!
//! This file covers the first: the two preludes are the only imports, which is
//! the point of `widget_prelude` existing — the tree, the paint context and the
//! tracking scope used to have to be reached for one module at a time.
//!
//! It also covers `event`, which is not required but is what a widget needs to
//! be pointed at. That method's signature names `Event`, and a positional
//! `Event` names `Point`, so this is where those two being reachable from the
//! documented pair of preludes is checked.

use std::cell::Cell;
use std::rc::Rc;

use guido::prelude::*;
use guido::widget_prelude::*;

/// A box whose size follows a signal. Deliberately minimal: `layout` and
/// `paint` are the only required methods, and what a layout has to do is read
/// a signal and answer with a size — the scope that attributes that read, the
/// check that decides whether it runs at all, and the cache it answers into
/// belong to the framework, around the call.
struct Bar {
    extent: Signal<f32>,
    measured: f32,
    /// How many times the framework has asked this widget to lay itself out.
    /// A leaf that writes no skip check of its own still must not be asked
    /// twice for an answer it has already given.
    layouts: Rc<Cell<u32>>,
    /// Where the last pointer event said it was, if it said anywhere. Shared
    /// with the test, which has no other way to look inside a boxed widget.
    pointed_at: Rc<Cell<Option<Option<Point>>>>,
}

impl Widget for Bar {
    fn layout(&mut self, _ctx: &mut LayoutCtx, _constraints: Constraints) -> Size {
        self.layouts.set(self.layouts.get() + 1);
        let extent = self.extent.get();
        self.measured = extent;
        Size::new(extent, extent)
    }

    fn event(&mut self, _tree: &mut Tree, _id: WidgetId, event: &Event) -> EventResponse {
        // A pointer event may have no position — see `Event::coords`. A widget
        // outside the crate has to be able to say so, which means naming the
        // `Option` rather than unwrapping it.
        if let Event::MouseMove { at, .. } = event {
            self.pointed_at.set(Some(*at));
            return EventResponse::Handled;
        }
        EventResponse::Ignored
    }

    fn paint(&self, ctx: &mut PaintContext) {
        ctx.draw_rounded_rect(
            Rect::new(0.0, 0.0, self.measured, self.measured),
            Color::RED,
            0.0,
        );
    }
}

fn lay_out(widget: impl Widget + 'static) -> (Tree, WidgetId, Size) {
    let mut tree = Tree::new();
    let root = tree.register(Box::new(widget));
    tree.with_widget_mut(root, |w, id, t| w.register_children(t, id));
    let size = tree
        .layout_widget(root, Constraints::new(0.0, 0.0, 400.0, 400.0))
        .expect("root is registered");
    (tree, root, size)
}

#[test]
fn a_widget_from_outside_the_crate_lays_out_and_paints() {
    let extent = create_signal(20.0f32);
    let (tree, root, size) = lay_out(Bar {
        extent: extent.into(),
        measured: 0.0,
        layouts: Rc::new(Cell::new(0)),
        pointed_at: Rc::new(Cell::new(None)),
    });

    assert_eq!(size, Size::new(20.0, 20.0));

    let mut node = RenderNode::new(root.as_u64());
    tree.paint_widget(root, &mut node, 1.0);
    assert!(!node.commands.is_empty(), "the widget drew nothing");
}

/// The value follows the signal on the layout that runs after a write.
///
/// Marked by hand, because driving the job queue that turns a write into
/// `needs_layout` is crate-internal — as is *which* widget it marks, which is
/// asserted where that is reachable:
/// `a_layout_is_attributed_to_the_widget_that_ran_it` in `src/lib.rs`, and
/// `reactive::invalidation::the_innermost_scope_owns_the_read` beneath it. What
/// this half says is that the widget re-reads: a leaf laid out again answers
/// from the signal, not from what it measured last time.
#[test]
fn it_re_measures_from_the_signal_it_read() {
    let extent = create_signal(20.0f32);
    let (mut tree, root, _) = lay_out(Bar {
        extent: extent.into(),
        measured: 0.0,
        layouts: Rc::new(Cell::new(0)),
        pointed_at: Rc::new(Cell::new(None)),
    });

    extent.set(40.0);
    tree.mark_needs_layout(root);
    let size = tree
        .layout_widget(root, Constraints::new(0.0, 0.0, 400.0, 400.0))
        .expect("root is registered");

    assert_eq!(size, Size::new(40.0, 40.0));
}

/// A pointer event reaches a widget written outside the crate, and it can tell
/// a position from the absence of one.
///
/// `Event`'s positional variants carry `Option<Point>` rather than a pair of
/// floats, because a subtree collapsed to nothing has no position to give and
/// no number could have said so (#227). That is public API, so a third-party
/// widget has to be able to spell both halves — with nothing imported but the
/// two preludes.
#[test]
fn a_widget_from_outside_the_crate_can_tell_a_position_from_none() {
    let extent = create_signal(20.0f32);
    let pointed_at = Rc::new(Cell::new(None));
    let (mut tree, root, _) = lay_out(Bar {
        extent: extent.into(),
        measured: 0.0,
        layouts: Rc::new(Cell::new(0)),
        pointed_at: Rc::clone(&pointed_at),
    });

    let mut send = |at| {
        tree.dispatch(
            root,
            &Event::MouseMove {
                at,
                pointer: PointerKind::Mouse,
            },
        );
    };

    send(Some(Point::new(3.0, 4.0)));
    assert_eq!(
        pointed_at.get(),
        Some(Some(Point::new(3.0, 4.0))),
        "a positioned move arrives with its position"
    );

    send(None);
    assert_eq!(
        pointed_at.get(),
        Some(None),
        "and one that lost its position arrives without it, rather than not \
         arriving or arriving at the origin"
    );
}

/// A leaf that writes no skip check of its own is not asked twice for the same
/// answer.
///
/// The check belongs to the framework, around the call, rather than to each
/// widget inside it: `Container` and `Text` wrote one, `TextInput` and `Image`
/// did not, and a widget written outside the crate had to know it should.
#[test]
fn a_leaf_with_no_check_of_its_own_is_not_laid_out_twice_for_one_answer() {
    let extent = create_signal(20.0f32);
    let layouts = Rc::new(Cell::new(0));
    let (mut tree, root, _) = lay_out(Bar {
        extent: extent.into(),
        measured: 0.0,
        layouts: Rc::clone(&layouts),
        pointed_at: Rc::new(Cell::new(None)),
    });
    assert_eq!(layouts.get(), 1, "the first layout runs");

    tree.layout_widget(root, Constraints::new(0.0, 0.0, 400.0, 400.0));

    assert_eq!(
        layouts.get(),
        1,
        "the same constraints, and nothing dirty: there is nothing to ask"
    );
}

/// An application without a compositor, or `None` where there is no adapter
/// to draw with — which is a failure where `GUIDO_GPU_REQUIRED` says one must
/// be there. Its own copy rather than `common`'s, because this file takes
/// nothing but the public API.
#[cfg(feature = "testing")]
fn headless() -> Option<guido::testing::Headless> {
    let app = guido::testing::Headless::new();
    if app.is_none() {
        if std::env::var_os("GUIDO_GPU_REQUIRED").is_some() {
            panic!("GUIDO_GPU_REQUIRED is set and no GPU adapter was found");
        }
        eprintln!("no GPU adapter; skipping");
    }
    app
}

/// A leaf written outside the crate whose `paint` reads a signal and opens no
/// scope of its own — which is what the book tells its reader costs an
/// over-broad repaint, and in fact costs every repaint.
///
/// Needs an adapter, because the only honest way to ask "did it repaint" from
/// outside the crate is to look at the pixels.
#[cfg(feature = "testing")]
mod a_paint_that_opens_no_scope {
    use super::*;

    /// A parent written outside the crate, which paints its one child through
    /// the call the framework provides — the reason `paint_child` and the
    /// options it takes are exported at all.
    struct Frame {
        child: Option<Box<dyn Widget>>,
        child_id: Option<WidgetId>,
    }

    impl Widget for Frame {
        fn register_children(&mut self, tree: &mut Tree, id: WidgetId) {
            let child = self.child.take().expect("registered once");
            let child_id = tree.register(child);
            tree.set_parent(child_id, id);
            self.child_id = Some(child_id);
        }

        fn layout(&mut self, ctx: &mut LayoutCtx, constraints: Constraints) -> Size {
            let child = self.child_id.expect("registered before layout");
            let size = ctx.layout_child(child, constraints).unwrap_or_default();
            ctx.tree().set_origin(child, 0.0, 0.0);
            size
        }

        fn paint(&self, ctx: &mut PaintContext) {
            let child = self.child_id.expect("registered before paint");
            ctx.paint_child(child, &ChildPaintOptions::default());
        }
    }

    /// Draws a colour straight from the signal. No `with_signal_tracking`.
    struct Swatch {
        colour: Signal<Color>,
    }

    impl Widget for Swatch {
        fn layout(&mut self, _ctx: &mut LayoutCtx, constraints: Constraints) -> Size {
            Size::new(constraints.max_width, constraints.max_height)
        }

        fn paint(&self, ctx: &mut PaintContext) {
            let bounds = Rect::new(0.0, 0.0, 100.0, 32.0);
            ctx.draw_rounded_rect(bounds, self.colour.get(), 0.0);
        }
    }

    #[test]
    fn a_widget_that_opens_no_paint_scope_still_follows_its_signal() {
        let Some(mut app) = headless() else { return };

        let colour = create_signal(Color::rgb(1.0, 0.0, 0.0));
        let surface = app.surface(
            SurfaceConfig::new()
                .height(32)
                .anchor(Anchor::TOP | Anchor::LEFT | Anchor::RIGHT),
            move || Frame {
                child: Some(Box::new(Swatch {
                    colour: colour.into(),
                })),
                child_id: None,
            },
        );
        app.configure(surface, 100, 32, 1.0);
        app.step();

        let [r, _, b, _] = app.read_pixel(surface, 50, 16);
        assert!(
            r > b,
            "the first frame drew the colour it was given: {r} vs {b}"
        );

        colour.set(Color::rgb(0.0, 0.0, 1.0));
        app.step();

        let [r, _, b, _] = app.read_pixel(surface, 50, 16);
        assert!(
            b > r,
            "the write reached nothing: the widget still shows the colour it \
             was built with. Its paint read the signal, so the read belongs to \
             it — but no scope was open to hear it ({r} vs {b})"
        );
    }
}

/// A widget that rasterises its own image reads the scale its frame is painted
/// at, so the image it builds has one pixel per device pixel (#673).
///
/// Needs an adapter, because the scale is the loop's: it comes from what the
/// compositor sent the surface, and only the loop paints with it.
#[cfg(feature = "testing")]
mod the_scale_a_frame_is_painted_at {
    use super::*;
    use guido::testing::Headless;
    use std::cell::RefCell;
    use std::sync::Arc;

    /// Builds a raster of its own at the size it is painted at, in device
    /// pixels, and keeps the size of each one it built so the test can look.
    struct Raster {
        built: Built,
    }

    /// The size of each raster a widget built, in the order it built them.
    type Built = Rc<RefCell<Vec<(u32, u32)>>>;

    impl Widget for Raster {
        fn layout(&mut self, _ctx: &mut LayoutCtx, constraints: Constraints) -> Size {
            constraints.constrain(Size::new(100.0, 20.0))
        }

        fn paint(&self, ctx: &mut PaintContext) {
            let scale = ctx.scale_factor();
            let (width, height) = (
                (100.0 * scale).round() as u32,
                (20.0 * scale).round() as u32,
            );
            self.built.borrow_mut().push((width, height));
            ctx.draw_image(
                ImageSource::Rgba {
                    width,
                    height,
                    pixels: Arc::from(vec![255u8; width as usize * height as usize * 4]),
                },
                Rect::new(0.0, 0.0, 100.0, 20.0),
                ContentFit::Fill,
                None,
            );
        }
    }

    /// Under a container, so the scale has to reach it through `paint_child`
    /// and not only through the root's context.
    fn raster_surface(app: &mut Headless) -> (SurfaceId, Built) {
        let built = Rc::new(RefCell::new(Vec::new()));
        let widget = Raster {
            built: Rc::clone(&built),
        };
        let surface = app.surface(SurfaceConfig::new().width(100).height(20), move || {
            container().child(widget)
        });
        (surface, built)
    }

    #[test]
    fn a_widget_rebuilds_its_raster_at_the_scale_it_is_painted_at() {
        let Some(mut app) = headless() else { return };
        let (surface, built) = raster_surface(&mut app);

        app.configure(surface, 100, 20, 1.0);
        app.step();
        assert_eq!(built.borrow().last(), Some(&(100, 20)), "first frame at 1");

        app.configure(surface, 100, 20, 1.5);
        app.step();
        assert_eq!(app.physical_size(surface), (150, 30));
        assert_eq!(
            built.borrow().last(),
            Some(&(150, 30)),
            "the frame after a fractional scale rebuilds the raster at one \
             pixel per device pixel"
        );
    }

    #[test]
    fn a_surface_that_was_never_sent_a_scale_is_painted_at_one() {
        let Some(mut app) = headless() else { return };
        let (surface, built) = raster_surface(&mut app);

        app.configure_size(surface, 100, 20);
        app.step();
        assert_eq!(built.borrow().as_slice(), &[(100, 20)]);
    }

    #[test]
    fn each_surface_is_painted_at_its_own_scale() {
        let Some(mut app) = headless() else { return };
        let (first, first_built) = raster_surface(&mut app);
        let (second, second_built) = raster_surface(&mut app);

        app.configure(first, 100, 20, 1.0);
        app.configure(second, 100, 20, 2.0);
        app.step();
        assert_eq!(first_built.borrow().last(), Some(&(100, 20)));
        assert_eq!(second_built.borrow().last(), Some(&(200, 40)));

        app.send_scale(first, 1.5);
        app.step();
        assert_eq!(
            first_built.borrow().last(),
            Some(&(150, 30)),
            "the first follows its own"
        );
        assert!(
            second_built.borrow().iter().all(|&size| size == (200, 40)),
            "the second is never painted at the first's scale: {:?}",
            second_built.borrow()
        );
    }
}