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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! Signal tracking and widget invalidation system.
//!
//! This module connects the reactive signal system to the widget tree, enabling
//! automatic UI updates when signals change.
//!
//! ## Signal Tracking Context
//!
//! During widget paint/layout, [`with_signal_tracking()`] establishes a context
//! that records which signals are read. These become the widget's dependencies.
//!
//! ## Subscriber Registry
//!
//! A global registry maps signal IDs to their subscribers (widget + job type pairs).
//! Signal IDs are dense sequential integers so we use `Vec` for direct O(1) indexing.
//! A reverse index maps widget IDs to their subscribed signals for O(1) cleanup.
//!
//! ## Integration with Jobs System
//!
//! When a signal is written, [`notify_signal_change()`] creates jobs for all
//! subscribers. The jobs system deduplicates these and wakes the event loop.

use rustc_hash::{FxHashMap, FxHashSet};
use smallvec::SmallVec;

use super::state::{ReactiveState, with_reactive};
use crate::app_state::with_app_state;
use crate::jobs::{JobRequest, JobType, request_job};
use crate::reactive::runtime::SignalId;
use crate::tree::WidgetId;

/// Context for tracking signal reads and associating them with a widget
pub(crate) struct SignalTrackingContext {
    widget_id: WidgetId,
    job_type: JobType,
    /// For reconciliation: which dynamic-children segment of the widget is
    /// reading. Lets a signal write dirty exactly one segment instead of
    /// re-running every dynamic segment of the container.
    segment: Option<u32>,
}

/// Run a closure while tracking signal reads for a widget.
///
/// Any signal read inside registers `widget_id` as a subscriber for
/// `job_type`, so a later write to it queues exactly that job for exactly this
/// widget. A widget implementing [`Widget`](crate::widgets::Widget) opens one
/// around each of its own phases: `JobType::Layout` around what it measures
/// from, `JobType::Paint` around what it draws from.
///
/// Scopes nest, and the innermost wins, so a widget that opens its own is
/// claiming its reads back from its parent. One that does not is not
/// unreactive — its reads land on whichever ancestor opened the enclosing
/// scope — but it is *imprecise*: a change to its content marks the parent
/// container for layout, which re-lays-out every sibling as well.
///
/// ```ignore
/// // not compiled: a fragment of a `Widget` impl, shown without the impl it
/// // belongs to — `self` has no meaning on its own. `tests/external_widget.rs`
/// // is where the same call is compiled.
/// fn layout(&mut self, tree: &mut Tree, id: WidgetId, c: Constraints) -> Size {
///     with_signal_tracking(id, JobType::Layout, || {
///         let text = self.content.get();   // subscribes this widget, not its parent
///         measure(&text, c)
///     })
/// }
/// ```
pub fn with_signal_tracking<F, R>(widget_id: WidgetId, job_type: JobType, f: F) -> R
where
    F: FnOnce() -> R,
{
    with_tracking_context(widget_id, job_type, None, f)
}

/// Run a closure while tracking signal reads for one dynamic-children
/// segment of a widget. Reads register the widget for `Reconcile` jobs and
/// additionally mark the segment, so reconciliation re-runs only the
/// segments whose dependencies actually changed.
pub(crate) fn with_segment_tracking<F, R>(widget_id: WidgetId, segment: u32, f: F) -> R
where
    F: FnOnce() -> R,
{
    with_tracking_context(widget_id, JobType::Reconcile, Some(segment), f)
}

fn with_tracking_context<F, R>(
    widget_id: WidgetId,
    job_type: JobType,
    segment: Option<u32>,
    f: F,
) -> R
where
    F: FnOnce() -> R,
{
    with_reactive(|reactive| {
        reactive
            .tracking_context
            .borrow_mut()
            .push(SignalTrackingContext {
                widget_id,
                job_type,
                segment,
            });
    });
    // Pop on unwind too: a leaked frame would silently attribute every
    // later signal read in the app to this widget.
    let _guard = crate::reactive::guard::defer(|| {
        with_reactive(|reactive| {
            reactive.tracking_context.borrow_mut().pop();
        });
    });
    f()
}

/// Suspend widget-level signal tracking during the given closure.
///
/// Signal reads inside the closure will NOT register any widget as a subscriber.
/// Used during effect execution to prevent effects from polluting the widget
/// tracking context when an effect runs inside a factory during reconciliation.
///
/// Effect-level tracking (`ReactiveState::effect_tracking`) is unaffected.
pub fn suspend_widget_tracking<F, R>(f: F) -> R
where
    F: FnOnce() -> R,
{
    let saved: Vec<_> =
        with_reactive(|reactive| reactive.tracking_context.borrow_mut().drain(..).collect());
    // Restore on unwind too: losing the saved stack would permanently
    // disable widget invalidation for every context that was active.
    let _guard = crate::reactive::guard::defer(move || {
        with_reactive(|reactive| *reactive.tracking_context.borrow_mut() = saved);
    });
    f()
}

/// Whether a widget tracking scope is currently active (layout/paint/reconcile).
///
/// Only the non-reactive-read diagnostic asks, and that lives behind
/// `debug_assertions` — so does this, or release builds warn about it.
#[cfg(debug_assertions)]
pub(crate) fn widget_tracking_active() -> bool {
    with_reactive(|reactive| !reactive.tracking_context.borrow().is_empty())
}

/// Record that a signal was read. Called from Signal::get().
/// If tracking is active, registers the current widget as a subscriber.
pub fn record_signal_read(signal_id: SignalId) {
    with_reactive(|reactive| {
        // One visit for both fields: this runs on every tracked read, and the
        // scope that says who is reading and the registry that records it are
        // fields of the same struct.
        if let Some(tracking) = reactive.tracking_context.borrow().last() {
            register_subscriber_in(
                reactive,
                tracking.widget_id,
                signal_id,
                tracking.job_type,
                tracking.segment,
            );
        }
    });
}

// ============================================================================
// Unified Subscriber Registry
// ============================================================================

/// Subscriber entry with widget ID, job type and (for reconciliation) the
/// dynamic-children segment that performed the read.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct Subscriber {
    widget_id: WidgetId,
    job_type: JobType,
    segment: Option<u32>,
}

/// Most signals have 1-2 widget subscribers (e.g. one paint, one layout).
type SubscriberList = SmallVec<[Subscriber; 2]>;

/// Most widgets subscribe to 2-6 signals (background, padding, etc.).
type SignalList = SmallVec<[SignalId; 4]>;

#[derive(Default)]
pub(crate) struct SubscriberRegistry {
    /// Forward index: signal index → subscribers. Sparse, because most
    /// signals no widget reads: a read that is already registered returns at
    /// `active` and never gets here, so the map is consulted on a first
    /// subscription, a write and a disposal. Disposal removes the entry, so a
    /// recycled index starts with none.
    signal_to_widgets: FxHashMap<usize, SubscriberList>,
    /// Reverse index: widget_id → subscribed signal IDs. For O(1) widget cleanup.
    widget_to_signals: FxHashMap<WidgetId, SignalList>,
    /// All live (signal index, subscriber) pairs. This is the hot-path
    /// dedup: widgets re-read their signals every frame, and without this
    /// set each re-read paid a linear scan over the signal's subscriber
    /// list — O(N²) per frame for a signal read by N widgets (e.g. a theme
    /// color). With it, an already-registered read is one hash lookup.
    active: FxHashSet<(usize, Subscriber)>,
    /// Widgets taken out of the reactive graph while they stay in the tree: a
    /// child playing its exit. What they read registers nothing, so paint can
    /// go on reading their properties without subscribing them again. Empty
    /// unless something is leaving, which is what keeps the check off the
    /// read path's cost.
    detached: FxHashSet<WidgetId>,
}

impl SubscriberRegistry {
    /// Whether a widget is detached — see [`detach_widget`]. The emptiness
    /// check first, because that is the answer on every read but the ones
    /// made while something is leaving.
    fn is_detached(&self, widget_id: WidgetId) -> bool {
        !self.detached.is_empty() && self.detached.contains(&widget_id)
    }
}

/// Take (and clear) the set of dirty dynamic-children segments for a widget.
/// `None` means no segment-tracked signal of this widget changed since the
/// last call.
pub(crate) fn take_dirty_segments(widget_id: WidgetId) -> Option<SmallVec<[u32; 4]>> {
    with_app_state(|app| app.dirty_segments.borrow_mut().remove(&widget_id))
}

/// Register a widget as a subscriber for a signal with a specific job type.
///
/// Called on every tracked signal read, so the already-registered case (the
/// overwhelming majority — widgets re-read their signals every frame) is a
/// single hash-set lookup.
pub fn register_subscriber(widget_id: WidgetId, signal_id: SignalId, job_type: JobType) {
    with_reactive(|reactive| {
        register_subscriber_in(reactive, widget_id, signal_id, job_type, None);
    });
}

/// Takes the state rather than reaching for it, so a caller already inside
/// `with_reactive` — which the read path is — pays one visit rather than two.
fn register_subscriber_in(
    reactive: &ReactiveState,
    widget_id: WidgetId,
    signal_id: SignalId,
    job_type: JobType,
    segment: Option<u32>,
) {
    let mut reg = reactive.subscribers.borrow_mut();

    if reg.is_detached(widget_id) {
        return;
    }
    let sub = Subscriber {
        widget_id,
        job_type,
        segment,
    };
    if !reg.active.insert((signal_id.index(), sub)) {
        return; // Already subscribed — the hot path
    }

    reg.signal_to_widgets
        .entry(signal_id.index())
        .or_default()
        .push(sub);

    // Update reverse index (deduped: the same widget/signal pair can
    // arrive with several job types, but only one entry is needed)
    let signals = reg.widget_to_signals.entry(widget_id).or_default();
    if !signals.contains(&signal_id) {
        signals.push(signal_id);
    }
}

/// Notify all subscribers of a signal change by creating jobs.
///
/// Iterates under the registry borrow: `request_job` only touches the job
/// queue and wake state, never the registry, so no re-entrant
/// borrow is possible and no snapshot allocation is needed.
pub fn notify_signal_change(signal_id: SignalId) {
    with_reactive(|reactive| {
        let reg = reactive.subscribers.borrow();
        let Some(subs) = reg.signal_to_widgets.get(&signal_id.index()) else {
            return;
        };
        for sub in subs {
            if let Some(segment) = sub.segment {
                mark_segment_dirty(sub.widget_id, segment);
            }
            let request = match sub.job_type {
                JobType::Layout => JobRequest::Layout,
                JobType::Paint => JobRequest::Paint,
                JobType::Reconcile => JobRequest::Reconcile,
                JobType::Unregister => JobRequest::Unregister,
                JobType::Animation => JobRequest::Animation(crate::jobs::RequiredJob::None),
            };
            request_job(sub.widget_id, request);
        }
    });
}

/// Clear signal subscribers for a specific signal (when signal is disposed)
pub fn clear_signal_subscribers(signal_id: SignalId) {
    with_reactive(|reactive| {
        let mut reg = reactive.subscribers.borrow_mut();
        if let Some(subs) = reg.signal_to_widgets.remove(&signal_id.index()) {
            // Remove this signal from the reverse index of each subscriber
            for sub in &subs {
                reg.active.remove(&(signal_id.index(), *sub));
                if let Some(signals) = reg.widget_to_signals.get_mut(&sub.widget_id) {
                    signals.retain(|&mut s| s != signal_id);
                    if signals.is_empty() {
                        reg.widget_to_signals.remove(&sub.widget_id);
                    }
                }
            }
        }
    });
}

/// Take a widget out of the reactive graph while it stays in the tree: clear
/// what it subscribed to, and let nothing it reads subscribe it again until
/// [`reattach_widget`] or [`clear_widget_subscribers`].
///
/// What a child playing its exit is: it still paints, and paint reads, but a
/// write to anything it read must not wake it — its item may be gone.
pub(crate) fn detach_widget(widget_id: WidgetId) {
    clear_widget_subscribers(widget_id);
    with_reactive(|reactive| {
        reactive.subscribers.borrow_mut().detached.insert(widget_id);
    });
}

/// Put a detached widget back: what it reads subscribes it again.
///
/// Nothing it subscribed to before survived the detach, so whoever calls this
/// owes it the passes that read them again.
pub(crate) fn reattach_widget(widget_id: WidgetId) {
    with_reactive(|reactive| {
        reactive
            .subscribers
            .borrow_mut()
            .detached
            .remove(&widget_id);
    });
}

/// Whether a widget has been detached — see [`detach_widget`].
pub(crate) fn is_detached(widget_id: WidgetId) -> bool {
    with_reactive(|reactive| reactive.subscribers.borrow().is_detached(widget_id))
}

/// A segment index no container has: marking it dirty re-runs every dynamic
/// segment the widget holds. What a reattached subtree needs, since the
/// subscriptions that would have said which ones went with the detach.
pub(crate) const EVERY_SEGMENT: u32 = u32::MAX;

/// Re-run every dynamic segment of `widget_id` at its next reconcile.
pub(crate) fn mark_every_segment_dirty(widget_id: WidgetId) {
    mark_segment_dirty(widget_id, EVERY_SEGMENT);
}

/// Re-run one dynamic segment of `widget_id` at its next reconcile.
fn mark_segment_dirty(widget_id: WidgetId, segment: u32) {
    with_app_state(|app| {
        let mut dirty = app.dirty_segments.borrow_mut();
        let segments = dirty.entry(widget_id).or_default();
        if !segments.contains(&segment) {
            segments.push(segment);
        }
    });
}

/// Remove a widget from all signal subscriber sets.
/// Called when a widget is unregistered to prevent stale subscribers
/// from causing wasted job creation — and it forgets a detach too, since a
/// widget leaving the tree has nothing left to be detached from.
pub fn clear_widget_subscribers(widget_id: WidgetId) {
    with_reactive(|reactive| {
        let mut reg = reactive.subscribers.borrow_mut();
        reg.detached.remove(&widget_id);
        // Use reverse index: only touch the signals this widget actually subscribes to
        if let Some(signal_ids) = reg.widget_to_signals.remove(&widget_id) {
            for signal_id in signal_ids {
                let Some(subs) = reg.signal_to_widgets.get_mut(&signal_id.index()) else {
                    continue;
                };
                // Collect the widget's exact entries first so `active` drops
                // precisely what was registered (job types and segments are
                // unknown to the caller).
                let removed: SmallVec<[Subscriber; 2]> = subs
                    .iter()
                    .filter(|s| s.widget_id == widget_id)
                    .copied()
                    .collect();
                subs.retain(|s| s.widget_id != widget_id);
                if subs.is_empty() {
                    reg.signal_to_widgets.remove(&signal_id.index());
                }
                for sub in removed {
                    reg.active.remove(&(signal_id.index(), sub));
                }
            }
        }
    });
    with_app_state(|app| {
        app.dirty_segments.borrow_mut().remove(&widget_id);
    });
}

/// Get the number of signals with active subscribers (for testing).
#[cfg(test)]
fn subscriber_count() -> usize {
    with_reactive(|reactive| reactive.subscribers.borrow().signal_to_widgets.len())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tree::WidgetId;

    fn widget_id(n: u64) -> WidgetId {
        WidgetId::from_u64(n)
    }

    fn signal_id(n: u32) -> SignalId {
        SignalId::new(n, 0)
    }

    /// Which widget a read belongs to is decided by the innermost scope, and
    /// a widget that opens none inherits its parent's — the whole reason
    /// `with_signal_tracking` is public. A leaf that skips it is not
    /// unreactive; it is imprecise, because its parent is what gets marked.
    #[test]
    fn the_innermost_scope_owns_the_read() {
        let parent = widget_id(300);
        let leaf = widget_id(301);

        with_signal_tracking(parent, JobType::Layout, || {
            // A leaf that opens its own scope claims the read back.
            with_signal_tracking(leaf, JobType::Layout, || {
                record_signal_read(signal_id(70));
            });
            // One that does not leaves it with the parent.
            record_signal_read(signal_id(71));
        });

        let subscribers = |sig: u32| {
            with_reactive(|reactive| {
                let reg = reactive.subscribers.borrow();
                reg.signal_to_widgets
                    .get(&(sig as usize))
                    .map(|s| s.iter().map(|e| e.widget_id).collect::<Vec<_>>())
                    .unwrap_or_default()
            })
        };

        assert_eq!(subscribers(70), vec![leaf]);
        assert_eq!(subscribers(71), vec![parent]);
    }

    /// A signal no widget reads costs the widget index nothing: the thousand
    /// made here add no entry, and the one read adds exactly one — not one for
    /// every index below it.
    #[test]
    fn only_a_signal_a_widget_reads_has_an_entry() {
        use crate::reactive::create_signal;

        let before = subscriber_count();
        let signals: Vec<_> = (0..1000).map(|_| create_signal(0u32)).collect();
        assert_eq!(subscriber_count(), before, "nothing has read them");

        let last = signals.last().unwrap();
        with_signal_tracking(widget_id(600), JobType::Paint, || last.get());
        assert_eq!(subscriber_count(), before + 1, "one read, one entry");
    }

    #[test]
    fn test_clear_signal_subscribers_removes_entry() {
        let wid = widget_id(100);
        register_subscriber(wid, signal_id(42), JobType::Paint);
        assert!(subscriber_count() > 0);

        clear_signal_subscribers(signal_id(42));

        // Signal 42 should have no subscribers
        with_reactive(|reactive| {
            let reg = reactive.subscribers.borrow();
            assert!(!reg.signal_to_widgets.contains_key(&42));
        });
    }

    #[test]
    fn test_clear_widget_subscribers_removes_from_all_signals() {
        let wid = widget_id(200);
        let other = widget_id(201);

        // Widget 200 subscribes to signals 10 and 11
        register_subscriber(wid, signal_id(10), JobType::Paint);
        register_subscriber(wid, signal_id(11), JobType::Layout);
        // Widget 201 subscribes to signal 10
        register_subscriber(other, signal_id(10), JobType::Paint);

        clear_widget_subscribers(wid);

        with_reactive(|reactive| {
            let reg = reactive.subscribers.borrow();
            // Signal 10 should still have widget 201
            let s10 = &reg.signal_to_widgets[&10];
            assert!(s10.iter().all(|s| s.widget_id != wid));
            assert!(s10.iter().any(|s| s.widget_id == other));
            // Signal 11 should be empty (only widget 200 subscribed)
            assert!(!reg.signal_to_widgets.contains_key(&11));
        });
    }

    /// `get_untracked` and `with_untracked` have to be untracked for a
    /// *derived* signal too. Its
    /// closure runs somewhere, and where it ran was inside whatever scope the
    /// caller happened to be in: the diagnostic snapshot zone around it is
    /// compiled away in release and never suppressed the recording.
    ///
    /// The cost is not a stale value but the wrong granularity — a read inside a
    /// dynamic-children closure subscribed the parent's *children list*, so
    /// writing it rebuilt every row where a repaint was the whole job.
    #[test]
    fn an_untracked_read_of_a_derived_subscribes_nobody() {
        use crate::reactive::{create_derived, create_signal};

        let subscribed = |wid: WidgetId| {
            with_reactive(|reactive| {
                reactive
                    .subscribers
                    .borrow()
                    .widget_to_signals
                    .get(&wid)
                    .is_some_and(|signals| !signals.is_empty())
            })
        };

        let inner = create_signal(1i32);
        let derived = create_derived(move || inner.get() + 1);

        let untracked = widget_id(500);
        with_signal_tracking(untracked, JobType::Paint, || {
            assert_eq!(derived.get_untracked(), 2);
        });
        assert!(
            !subscribed(untracked),
            "an untracked read must leave the scope holding nothing"
        );

        // The borrowing half is the same promise, and was the same bug.
        let borrowed = widget_id(502);
        with_signal_tracking(borrowed, JobType::Paint, || {
            assert_eq!(derived.with_untracked(|v| *v), 2);
        });
        assert!(
            !subscribed(borrowed),
            "`with_untracked` says untracked too, and has to mean it"
        );

        // The control: the same read, asked for by its tracking name.
        let tracked = widget_id(501);
        with_signal_tracking(tracked, JobType::Paint, || {
            assert_eq!(derived.get(), 2);
        });
        assert!(
            subscribed(tracked),
            "and a tracked one still has to subscribe, or the test proves nothing"
        );
    }

    #[test]
    fn test_with_signal_tracking_registers_subscriber() {
        let wid = widget_id(300);
        let sid = signal_id(99);

        with_signal_tracking(wid, JobType::Paint, || {
            record_signal_read(sid);
        });

        with_reactive(|reactive| {
            let reg = reactive.subscribers.borrow();
            let s = &reg.signal_to_widgets[&sid.index()];
            assert!(s.contains(&Subscriber {
                widget_id: wid,
                job_type: JobType::Paint,
                segment: None,
            }));
        });

        // Clean up
        clear_signal_subscribers(sid);
    }

    /// Whether `wid` is subscribed to `sid` for anything.
    fn subscribed(wid: WidgetId, sid: SignalId) -> bool {
        with_reactive(|reactive| {
            reactive
                .subscribers
                .borrow()
                .signal_to_widgets
                .get(&sid.index())
                .is_some_and(|subs| subs.iter().any(|s| s.widget_id == wid))
        })
    }

    /// A detached widget loses what it had subscribed to, and what it reads
    /// while detached — a leaving child still paints — subscribes it to
    /// nothing. Reattached, its next read subscribes it again; unregistered,
    /// nothing of the detach is left behind.
    #[test]
    fn a_detached_widget_reads_without_subscribing() {
        let wid = widget_id(410);
        let sid = signal_id(60);
        let read = || with_signal_tracking(wid, JobType::Paint, || record_signal_read(sid));

        read();
        assert!(subscribed(wid, sid), "the control: a read subscribes");

        detach_widget(wid);
        assert!(!subscribed(wid, sid), "the detach clears it");
        read();
        assert!(
            !subscribed(wid, sid),
            "and a read while detached registers nothing"
        );
        assert!(is_detached(wid));

        reattach_widget(wid);
        read();
        assert!(subscribed(wid, sid), "reattached, reading subscribes again");

        detach_widget(wid);
        clear_widget_subscribers(wid);
        assert!(
            !is_detached(wid),
            "a widget leaving the tree forgets its detach"
        );
        clear_signal_subscribers(sid);
    }

    #[test]
    fn test_reverse_index_consistency() {
        let wid = widget_id(400);
        register_subscriber(wid, signal_id(50), JobType::Paint);
        register_subscriber(wid, signal_id(51), JobType::Layout);

        with_reactive(|reactive| {
            let reg = reactive.subscribers.borrow();
            let signals = reg.widget_to_signals.get(&wid).unwrap();
            assert!(signals.contains(&signal_id(50)));
            assert!(signals.contains(&signal_id(51)));
        });

        clear_widget_subscribers(wid);

        with_reactive(|reactive| {
            let reg = reactive.subscribers.borrow();
            assert!(!reg.widget_to_signals.contains_key(&wid));
        });
    }
}