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
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
//! Turning pointer and key events into container state and callbacks.
//!
//! A container resolves every event against its [`HitContext`] — the geometry
//! it was laid out and transformed into. Hit testing therefore happens in two
//! steps: undo the container's own transform, then test the point against the
//! laid-out bounds *and* their corner radius, so a rounded container does not
//! answer for the pixels outside its shape.
//!
//! Hover is tracked **before** children see the event ([`track_pointer`]),
//! because a child handling a `MouseMove` must not stop its ancestors from
//! noticing the pointer passed over them. Everything else is handled after the
//! children have had their turn ([`handle_own_event`]), so the innermost
//! interested widget wins.
//!
//! The hover *state* changes where the walk finds it; `on_hover` waits for the
//! dispatch to return, which says every leave before any enter
//! ([`Tree::hover_changed`]).
//!
//! [`track_pointer`]: Container::track_pointer
//! [`handle_own_event`]: Container::handle_own_event

use crate::clock::EventInstant;
use crate::reactive::focus::{focus_within, request_focus};

use super::*;

/// The geometry an event is resolved against: where the container ended up,
/// what shape it is, and the transform standing between the two.
pub(super) struct HitContext {
    pub bounds: Rect,
    pub corners: crate::widgets::Corners,
    pub transform: Transform,
    pub pivot: Pivot,
}

impl HitContext {
    /// Whether a point falls inside the container's *shape* — its bounds
    /// narrowed by the corner radius, not the bounding box.
    ///
    /// An event with no position is inside nothing. That is the whole of
    /// #227: a container collapsed to a line has no inverse to undo, so the
    /// point that reaches it is `None`, and every bounds test below it answers
    /// no without any of them having to know why.
    #[inline]
    pub(super) fn contains(&self, at: Option<Point>) -> bool {
        self.bounds.contains_shape_at(at, self.corners)
    }

    /// A surface-space point expressed relative to the container's own origin
    /// — the space ripples and pointer callbacks work in.
    pub(super) fn local(&self, at: Point) -> Option<Point> {
        Some(
            untransform_point(&self.transform, self.pivot, self.bounds, at)?
                .offset(-self.bounds.x, -self.bounds.y),
        )
    }

    /// The same, for a point that has already had the transform undone.
    pub(super) fn rebase(&self, at: Point) -> Point {
        at.offset(-self.bounds.x, -self.bounds.y)
    }
}

/// Map a point from surface space into the container's untransformed space,
/// or `None` where the container occupies no space to be pointed at.
///
/// A container's own transform is applied around its origin at paint time, so
/// hit testing has to undo it before comparing against the laid-out bounds.
/// An identity transform returns the point unchanged.
///
/// A transform that has collapsed the container onto a line or a point has no
/// inverse, and there is no coordinate that means "nowhere" — every number is
/// somewhere, and a descendant that rotates or mirrors would carry a far-away
/// sentinel back into the visible half-plane. So the absence is the answer.
pub(super) fn untransform_point(
    transform: &Transform,
    origin: Pivot,
    bounds: Rect,
    at: Point,
) -> Option<Point> {
    if transform.is_identity() {
        return Some(at);
    }
    let (origin_x, origin_y) = origin.resolve(bounds);
    let (ux, uy) = transform
        .center_at(origin_x, origin_y)
        .inverse()?
        .transform_point(at.x, at.y);
    Some(Point::new(ux, uy))
}

impl Container {
    /// Let a state-layer animation pick up its new target after a hover or
    /// press change.
    ///
    /// The *repaint* needs no request: the flag write is a signal write, and
    /// whatever resolved a state layer — this container, and any descendant
    /// text whose colour resolves through it — subscribed to that signal and
    /// is marked by it. What a signal write cannot do is drive the clock, so a
    /// container with animated state properties still asks for its Animation
    /// job here.
    pub(super) fn request_state_change_repaint(&self, id: WidgetId) {
        if self.has_animated_state_properties() {
            request_job(id, JobRequest::Animation(RequiredJob::Paint));
        }
    }

    /// Give up the pointer: the hover, the press, and a ripple that will now
    /// never be completed.
    ///
    /// Three things lead here and they mean the same thing. A `MouseLeave`
    /// says the pointer went somewhere else; the two gates at the top of
    /// [`event`](Widget::event), hidden and disabled, say this container
    /// stopped accepting it — and reach it through
    /// [`switched_off`](Self::switched_off), which says so to what is inside
    /// as well. In every case nothing was activated, so the ripple
    /// is cancelled rather than completed, and `on_hover(false)` is owed to
    /// whoever asked to be told.
    ///
    /// The gates need this because they return before
    /// [`track_pointer`](Self::track_pointer) and before the `MouseUp` arm:
    /// nothing else would ever take `HOVERED` or `PRESSED` off a container
    /// while it was switched off. (For a disabled container the *reads* are
    /// gated too — see [`Control::is_hovered`] — which is what makes the flip
    /// itself immediate; this is what keeps it true afterwards.) It happens on
    /// the next event that reaches the container, not at the instant it was
    /// switched off.
    ///
    /// Every write here is change-guarded, so the events that keep arriving
    /// over a switched-off subtree cost one comparison each and wake nobody.
    ///
    /// [`Control::is_hovered`]: crate::widgets::Control::is_hovered
    pub(super) fn pointer_left(&mut self, tree: &mut Tree, id: WidgetId) {
        let now = tree.event_instant();
        let Some(ref mut ix) = self.interaction else {
            return;
        };
        let was_hovered = ix.is_hovered();
        let was_pressed = ix.is_pressed();
        if was_hovered {
            ix.set_flag(InteractionFlags::HOVERED, false);
            if let Some(ref callback) = ix.on_hover {
                tree.hover_changed(id, false, callback);
            }
        }
        ix.set_flag(InteractionFlags::PRESSED, false);

        // The pointer left without releasing, so nothing was activated and
        // there is nothing to complete: the ripple just goes.
        if ix.ripple.is_active()
            && let Some(config) = ix.ripple_config()
        {
            ix.ripple.cancel(&config, now.as_frame_start());
            request_job(id, JobRequest::Animation(RequiredJob::Paint));
        }

        if (was_hovered && ix.declares(|w| matches!(w, StateWhen::Hovered)))
            || (was_pressed && ix.declares(|w| matches!(w, StateWhen::Pressed)))
        {
            self.request_state_change_repaint(id);
        }
    }

    /// Stop taking the pointer, here and below: what one of the two gates at
    /// the top of [`event`](Widget::event) does before it returns.
    ///
    /// The gate returns before the children are asked, so nothing else would
    /// take the hover or the press off what is inside — shown or enabled
    /// again, a child would still be drawn pressed and still take a release
    /// that belongs to a press somewhere else (#716). Each child the pointer
    /// record owes an event is told the pointer left, and passes it on down
    /// the same way, so the walk is the record's and not the subtree's. A
    /// hover is told once; a press is told again on each event until its
    /// button comes up, because the record holds it that long, and every
    /// `MouseLeave` arm is change-guarded. After that, the events that keep
    /// arriving over a switched-off container ask one search of the record and
    /// tell nobody.
    ///
    /// Not inside [`pointer_left`](Self::pointer_left), which the
    /// `MouseLeave` arm also calls after that event has already been through
    /// the children.
    pub(super) fn switched_off(&mut self, tree: &mut Tree, id: WidgetId) {
        let children = self.children_source.get();
        let owed = tree.event_targets(
            id,
            children,
            &Event::MouseLeave,
            None,
            self.children_sorted_along,
        );
        for (index, _) in owed {
            let child_id = children[index];
            if !is_detached(child_id) {
                tree.with_widget_mut(child_id, |child, child_id, tree| {
                    child.event(tree, child_id, &Event::MouseLeave)
                });
            }
        }
        self.pointer_left(tree, id);
    }

    /// Say this container's cursor for a point inside its shape.
    ///
    /// Before the children, so that one of them declaring its own says it
    /// later and wins. A container that does not take input claims nothing:
    /// the compositor is not giving it the pointer, so whatever is beneath it
    /// answers.
    pub(super) fn claim_the_cursor(&self, tree: &mut Tree, hit: &HitContext, event: &Event) {
        if let Some(ix) = self.interaction.as_deref()
            && ix.cursor.is_set()
            && self.takes_input.get_or_untracked(true)
            && hit.contains(event.coords())
        {
            tree.point_shows_cursor(ix.cursor);
        }
    }

    /// Whether the point is on this container, for a container none of whose
    /// children it is on: inside its shape, where it draws or listens.
    ///
    /// Flutter's rule rather than the DOM's. A container that only lays out —
    /// a full-size layer of a `ZStack` aligning its content — is not hit, so
    /// the layers beneath it are still reached without a pass-through
    /// declaration on every one above (#636).
    pub(super) fn is_hit(&self, id: WidgetId, hit: &HitContext, event: &Event) -> bool {
        hit.contains(event.coords())
            && (self.is_control()
                || self
                    .interaction
                    .as_deref()
                    .is_some_and(|ix| ix.cursor.is_set())
                || self.draws_its_own_surface(id))
    }

    /// Update hover state and fire the pointer-move callback, before children
    /// get the event: a child that handles a `MouseMove` must not stop its
    /// ancestors from tracking their own hover.
    pub(super) fn track_pointer(
        &mut self,
        tree: &mut Tree,
        id: WidgetId,
        hit: &HitContext,
        event: &Event,
        now: EventInstant,
    ) {
        let has_animated = self.has_animated_state_properties();
        // Read before the mutable borrow: cancelling a ripple below needs it.
        let ripple_config = self.interaction.as_ref().and_then(|ix| ix.ripple_config());
        let Some(ref mut ix) = self.interaction else {
            return;
        };
        // See `request_state_change_repaint`: the flag write invalidates, this
        // only advances an animation.
        let request_repaint = |id: WidgetId| {
            if has_animated {
                request_job(id, JobRequest::Animation(RequiredJob::Paint));
            }
        };

        match event {
            // An enter with no position is an enter into nothing, so it is
            // the falling edge rather than the rising one. The platform only
            // ever sends a positioned one (`input.rs`), but a container that
            // collapses is what takes the position away on the way down, and
            // the move that would otherwise clear the hover is a whole event
            // later.
            Event::MouseEnter { at: None } if ix.is_hovered() => {
                ix.set_flag(InteractionFlags::HOVERED, false);
                if ix.declares(|w| matches!(w, StateWhen::Hovered)) {
                    request_repaint(id);
                }
                if let Some(ref callback) = ix.on_hover {
                    tree.hover_changed(id, false, callback);
                }
            }
            Event::MouseEnter { at } if hit.contains(*at) && !ix.is_hovered() => {
                ix.set_flag(InteractionFlags::HOVERED, true);
                if ix.declares(|w| matches!(w, StateWhen::Hovered)) {
                    request_repaint(id);
                }
                if let Some(ref callback) = ix.on_hover {
                    tree.hover_changed(id, true, callback);
                }
            }
            Event::MouseMove { at, .. } => {
                // A pressed container keeps receiving moves that leave it —
                // that implicit capture is what makes dragging work. A move
                // with no position is not one of those: there is nowhere to
                // report, so the callback is not called and the hover below
                // simply falls.
                // One question, asked once and answered twice below.
                let inside = hit.contains(*at);

                if let Some(ref callback) = ix.on_pointer_move
                    && (inside || ix.is_pressed())
                    && let Some(at) = at
                {
                    let local = hit.rebase(*at);
                    callback(local.x, local.y);
                }

                let was_hovered = ix.is_hovered();
                ix.set_flag(InteractionFlags::HOVERED, inside);

                // Dragging off the container abandons the press. Only leaving
                // the whole surface used to say so, which left a ripple
                // growing at full brightness on a button the pointer had left
                // several hundred pixels ago.
                if was_hovered
                    && !ix.is_hovered()
                    && ix.ripple.is_active()
                    && let Some(ref config) = ripple_config
                {
                    ix.ripple.cancel(config, now.as_frame_start());
                    request_job(id, JobRequest::Animation(RequiredJob::Paint));
                }

                if was_hovered != ix.is_hovered() {
                    if ix.declares(|w| matches!(w, StateWhen::Hovered)) {
                        request_repaint(id);
                    }
                    if let Some(ref callback) = ix.on_hover {
                        tree.hover_changed(id, ix.is_hovered(), callback);
                    }
                }
            }
            _ => {}
        }
    }

    /// Handle an event the children did not take.
    ///
    /// `event` is the original, still in surface space: the ripple needs it to
    /// place its origin under the actual cursor. `local` is the same event with
    /// this container's transform undone, which is what everything else tests
    /// against.
    pub(super) fn handle_own_event(
        &mut self,
        tree: &mut Tree,
        id: WidgetId,
        hit: &HitContext,
        event: &Event,
        local: &Event,
        now: EventInstant,
    ) -> EventResponse {
        // Asked once and read by whichever arm handles the press: `contains`
        // runs the corner SDF, and a press inside the shape is exactly the
        // case that would otherwise run it more than once.
        let pressed_inside =
            matches!(local, Event::MouseDown { .. }) && hit.contains(local.coords());

        // A press inside a focusable container that nothing in it took is a
        // press on the container, and the focus goes there — said on the tree
        // rather than by consuming it, for the reason the end of this
        // function gives. A focusable container inside that already said so
        // keeps it: the innermost is the one pressed.
        if pressed_inside && self.is_focusable() && !tree.focus_claimed_the_press() {
            request_focus(tree, id);
            tree.keep_the_focus_this_press_landed_on();
        }

        match local {
            // Hover was tracked before the children ran. Returning Ignored
            // here is deliberate: a hover change must not stop sibling
            // containers from tracking their own.
            Event::MouseEnter { .. } | Event::MouseMove { .. } => {}

            Event::MouseDown { button, .. } if *button != MouseButton::Left => {
                if pressed_inside && let Some(ref ix) = self.interaction {
                    let callback = match button {
                        MouseButton::Right => ix.on_right_click.as_ref(),
                        MouseButton::Middle => ix.on_middle_click.as_ref(),
                        MouseButton::Left => None,
                    };
                    if let Some(callback) = callback {
                        callback();
                        return EventResponse::Handled;
                    }
                }
            }

            Event::MouseDown { at, button, .. } => {
                if pressed_inside
                    && let Some(at) = at
                    && *button == MouseButton::Left
                    && let Some(ref mut ix) = self.interaction
                {
                    let was_pressed = ix.is_pressed();
                    ix.set_flag(InteractionFlags::PRESSED, true);

                    let has_ripple = ix
                        .states
                        .iter()
                        .any(|(w, s)| matches!(w, StateWhen::Pressed) && s.ripple.is_some());
                    if has_ripple {
                        // The ripple starts under the finger, so it wants the
                        // point as the surface gave it, not the one already
                        // rebased for this container.
                        let on_screen = event.coords().unwrap_or(*at);
                        if let Some(local) = hit.local(on_screen) {
                            ix.ripple.start(local.x, local.y, now.as_frame_start());
                        }
                        request_job(id, JobRequest::Animation(RequiredJob::Paint));
                    }

                    if !was_pressed && ix.declares(|w| matches!(w, StateWhen::Pressed)) {
                        self.request_state_change_repaint(id);
                    }
                    if let Some(ref ix) = self.interaction
                        && let Some(ref callback) = ix.on_mouse_down
                    {
                        let local = hit.rebase(*at);
                        callback(local.x, local.y);
                        return EventResponse::Handled;
                    }
                    // A press is claimed even without a down handler, so the
                    // matching release reaches the click handler.
                    if let Some(ref ix) = self.interaction
                        && (ix.on_click.is_some() || ix.on_mouse_up.is_some())
                    {
                        return EventResponse::Handled;
                    }
                }
            }

            Event::MouseUp { at, button } => {
                if let Some(ref mut ix) = self.interaction
                    && ix.is_pressed()
                    && *button == MouseButton::Left
                {
                    let was_pressed = ix.is_pressed();
                    ix.set_flag(InteractionFlags::PRESSED, false);

                    // The ripple has to say the same thing `on_click` below
                    // says: a release inside activated something and finishes
                    // its expansion, a release that wandered off did not and
                    // simply goes.
                    if ix.ripple.is_active()
                        && let Some(config) = ix.ripple_config()
                    {
                        if hit.contains(*at) {
                            ix.ripple.release(&config, now.as_frame_start());
                        } else {
                            ix.ripple.cancel(&config, now.as_frame_start());
                        }
                        request_job(id, JobRequest::Animation(RequiredJob::Paint));
                    }

                    if was_pressed && ix.declares(|w| matches!(w, StateWhen::Pressed)) {
                        self.request_state_change_repaint(id);
                    }

                    let mut handled = false;
                    if let Some(at) = at
                        && let Some(ref ix) = self.interaction
                        && let Some(ref callback) = ix.on_mouse_up
                    {
                        let local = hit.rebase(*at);
                        callback(local.x, local.y);
                        handled = true;
                    }
                    // A click is a release *inside* the shape; a release that
                    // wandered off only ends the press.
                    if let Some(ref ix) = self.interaction
                        && hit.contains(*at)
                        && let Some(ref callback) = ix.on_click
                    {
                        callback();
                        return EventResponse::Handled;
                    }
                    if handled {
                        return EventResponse::Handled;
                    }
                }
            }

            Event::MouseLeave => self.pointer_left(tree, id),

            Event::Scroll {
                at,
                delta_x,
                delta_y,
                source,
            } => {
                if hit.contains(*at) {
                    // Our own scrolling consumes the event first; the callback
                    // only sees what scrolling did not take.
                    if self.scroll_axis != ScrollAxis::None
                        && self.apply_scroll(*delta_x, *delta_y, *source, now)
                    {
                        // A paint, and only a paint. A sample means the finger
                        // is still down, so there is no momentum for an
                        // animation pass to advance — it begins on the
                        // end-of-gesture, which asks for its own frames.
                        request_job(id, JobRequest::Paint);
                        return EventResponse::Handled;
                    }

                    if let Some(ref ix) = self.interaction
                        && let Some(ref callback) = ix.on_scroll
                    {
                        callback(*delta_x, *delta_y, *source);
                        return EventResponse::Handled;
                    }
                }
            }

            Event::KeyDown {
                key,
                modifiers,
                repeat,
            } => {
                if let Some(ref ix) = self.interaction
                    && let Some(ref callback) = ix.on_key_down
                    && !tree.heard_this_key(id)
                    && callback(*key, *modifiers, *repeat) == EventResponse::Handled
                {
                    return EventResponse::Handled;
                }
            }

            Event::KeyUp { key, modifiers } => {
                if let Some(ref ix) = self.interaction
                    && let Some(ref callback) = ix.on_key_up
                    && !tree.heard_this_key(id)
                    && callback(*key, *modifiers) == EventResponse::Handled
                {
                    return EventResponse::Handled;
                }
            }

            // The finger lifted, and that is where the glide begins — the
            // frame that carries it decays it by however late it was, rather
            // than starting it fresh or cancelling it for the delay (#265,
            // #340).
            Event::ScrollEnd { at } => {
                if self.scroll_axis != ScrollAxis::None && hit.contains(*at) {
                    return self.hand_off_to_momentum(id, now);
                }
            }

            Event::FocusIn | Event::FocusOut | Event::Pasted(_) => {}
        }

        // A press inside the box that lights up for this focus is a press on
        // the field the box draws — its padding, its border, the gap beside the
        // caret. The dispatcher takes the focus off a press nobody claimed, so
        // this is how the box says the keyboard is still its own.
        //
        // Said here and not there because `hit` is this container's: the point
        // arrived rebased through every ancestor, with the scroll offset added
        // and the transform undone. Nothing outside the walk has that point
        // without redoing the walk. Said on the tree and not by returning
        // `Handled` because that also means consumed, which silenced an outer
        // clickable row and made it work or not depending on where the keyboard
        // was (#308).
        if pressed_inside && self.holds_the_focus_it_draws(id) {
            tree.keep_the_focus_this_press_landed_on();
        }

        EventResponse::Ignored
    }

    /// Whether this container declares `when_focused` and the focus is
    /// currently inside it.
    fn holds_the_focus_it_draws(&self, id: WidgetId) -> bool {
        self.interaction
            .as_ref()
            .is_some_and(|ix| ix.declares(|w| matches!(w, StateWhen::Focused)))
            && focus_within(id)
    }
}