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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
use std::marker::PhantomData;

use super::diagnostics::{check_reactive_scope, snapshot_zone};
use super::invalidation::{notify_signal_change, record_signal_read, suspend_widget_tracking};
use super::owner::register_signal;
use super::runtime::{
    SignalId, current_write_epoch, notify_write, queue_bg_write, record_effect_read,
    suspend_effect_tracking, with_runtime,
};
use super::storage::{
    call_derived, compare_and_set_signal_value, compare_and_update_signal_value,
    create_derived_value, create_signal_value, create_stored_value, get_signal_value,
    get_stored_value, has_signal, try_get_signal_value, with_signal_value, with_stored_value,
};

/// Implement Clone (via Copy), Copy, PartialEq (by SignalId), and Eq for a signal type.
macro_rules! impl_signal_id_traits {
    ($ty:ident) => {
        impl<T> Clone for $ty<T> {
            fn clone(&self) -> Self {
                *self
            }
        }
        impl<T> Copy for $ty<T> {}
        impl<T> PartialEq for $ty<T> {
            fn eq(&self, other: &Self) -> bool {
                self.id == other.id
            }
        }
        impl<T> Eq for $ty<T> {}
    };
}

/// Internal discriminant for the three signal kinds.
/// Same size as `bool` (1 byte) so `Signal<T>` stays at 16 bytes.
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum SignalKind {
    /// Immutable stored value (`Rc<T>`, no RefCell, no tracking).
    Stored = 0,
    /// Reactive read-write value (`Rc<RefCell<T>>`, tracked).
    Mutable = 1,
    /// Closure-backed derived signal (the closure is the slot's value).
    Derived = 2,
}

/// Common read operations for signal types.
/// - Stored: no tracking (value never changes), reads `Rc<T>` directly
/// - Mutable: full effect + widget tracking, reads `Rc<RefCell<T>>`
/// - Derived: calls the closure (which tracks its own reads internally)
#[inline]
#[cfg_attr(debug_assertions, track_caller)]
fn tracked_get<T: Clone + 'static>(id: SignalId, kind: SignalKind) -> T {
    match kind {
        // A stored value never changes: reading it outside a scope is not a
        // missed subscription, there is nothing to subscribe to.
        SignalKind::Stored => get_stored_value(id),
        SignalKind::Derived => {
            check_reactive_scope();
            // The closure's own reads would otherwise report a second time
            snapshot_zone(|| call_derived::<T>(id))
        }
        SignalKind::Mutable => {
            check_reactive_scope();
            record_effect_read(id);
            record_signal_read(id);
            get_signal_value(id)
        }
    }
}

/// Common read-with-borrow operation for signal types.
/// - Stored: no tracking, borrows `Rc<T>` directly
/// - Mutable: full tracking, borrows through `Rc<RefCell<T>>`
/// - Derived: calls the closure and passes the result to `f`
#[inline]
#[cfg_attr(debug_assertions, track_caller)]
fn tracked_with<T: Clone + 'static, R>(
    id: SignalId,
    kind: SignalKind,
    f: impl FnOnce(&T) -> R,
) -> R {
    match kind {
        SignalKind::Stored => with_stored_value(id, f),
        SignalKind::Derived => {
            check_reactive_scope();
            let val = snapshot_zone(|| call_derived::<T>(id));
            f(&val)
        }
        SignalKind::Mutable => {
            check_reactive_scope();
            record_effect_read(id);
            record_signal_read(id);
            with_signal_value(id, f)
        }
    }
}

/// Perform a signal write with change detection and notification (main thread only).
fn write_and_notify<T: Clone + PartialEq + 'static>(id: SignalId, value: T) {
    if compare_and_set_signal_value(id, value) {
        notify_signal_change(id);
        notify_write(id);
    }
}

/// Perform a signal update with change detection and notification (main thread only).
fn update_and_notify<T: Clone + PartialEq + 'static>(id: SignalId, f: impl FnOnce(&mut T)) {
    if compare_and_update_signal_value(id, f) {
        notify_signal_change(id);
        notify_write(id);
    }
}

/// Write without comparison: every write notifies (main thread only).
fn write_and_notify_always<T: Clone + 'static>(id: SignalId, value: T) {
    if crate::reactive::storage::set_signal_value_always(id, value) {
        notify_signal_change(id);
        notify_write(id);
    }
}

/// Update without comparison: every update notifies (main thread only).
fn update_and_notify_always<T: 'static>(id: SignalId, f: impl FnOnce(&mut T)) {
    if crate::reactive::storage::update_signal_value_always(id, f) {
        notify_signal_change(id);
        notify_write(id);
    }
}

/// A read-only reactive signal.
///
/// `Signal<T>` provides read access to reactive values. It is returned by
/// [`create_stored`] (static values) and [`create_derived`] (closure-backed).
/// Widget properties accept `Signal<T>` via the
/// [`IntoSignal`](super::IntoSignal) trait.
///
/// To create a read-write signal, use [`create_signal`] which returns [`RwSignal<T>`].
///
/// Signals are `Copy` — they can be freely passed into closures without cloning.
///
/// # Thread Safety
///
/// `Signal<T>` is `!Send` — it can only be used on the main thread.
pub struct Signal<T> {
    id: SignalId,
    /// Discriminant for the three signal kinds (Stored, Mutable, Derived).
    kind: SignalKind,
    _marker: PhantomData<T>,
    _not_send: PhantomData<*const ()>,
}

/// Run a derived signal's closure with nothing listening.
///
/// One place, because there are two callers and they were not the same: the
/// diagnostic zone alone is compiled away in release, so a `with_untracked` that
/// had only that still recorded every signal the closure read against whatever
/// happened to be tracking. Two sister functions with different contracts is
/// worse than either contract.
fn untracked_derived<T: Clone + 'static>(id: SignalId) -> T {
    snapshot_zone(|| suspend_widget_tracking(|| suspend_effect_tracking(|| call_derived::<T>(id))))
}

impl_signal_id_traits!(Signal);

impl<T> Signal<T> {
    /// Whether the scope that made this signal still holds it.
    ///
    /// For a reader that outlives the declaration it watches — the cursor's,
    /// which stays on what the pointer last rested over after that widget is
    /// gone. A derived one is the case that bites: its closure is disposed
    /// with its scope, but the signals the closure read are not, and a write
    /// to one of them still reaches the reader.
    pub(crate) fn is_live(&self) -> bool {
        has_signal(self.id)
    }
}

impl<T: Clone + 'static> Signal<T> {
    /// Get the current value (tracks as dependency for effects)
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn get(&self) -> T {
        tracked_get(self.id, self.kind)
    }

    /// Get the current value without tracking.
    ///
    /// Untracked all the way down for a derived one: its closure runs with the
    /// widget and effect scopes suspended, the same three-part suspension
    /// [`create_memo`](crate::reactive::create_memo) seeds itself with. The
    /// diagnostic zone alone was not it — in release it compiles to nothing, so
    /// every signal the closure read was still recorded against whatever
    /// happened to be tracking. A `get_untracked` inside a dynamic-children
    /// closure therefore subscribed the *parent's children list* to it, and
    /// writing it rebuilt the whole list where a repaint was the work.
    pub fn get_untracked(&self) -> T {
        match self.kind {
            SignalKind::Stored => get_stored_value(self.id),
            // The caller asked for a snapshot; the closure's own reads are
            // part of that snapshot and must not be reported either
            SignalKind::Derived => untracked_derived::<T>(self.id),
            SignalKind::Mutable => get_signal_value(self.id),
        }
    }

    /// Borrow the value for reading
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        tracked_with(self.id, self.kind, f)
    }

    /// Borrow the value without tracking.
    ///
    /// The borrowing half of [`get_untracked`](Self::get_untracked), suspended
    /// the same three ways for the same reason: a derived signal's closure runs
    /// somewhere, and unsuspended it runs inside whatever scope the caller was
    /// in.
    pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        match self.kind {
            SignalKind::Stored => with_stored_value(self.id, f),
            SignalKind::Derived => {
                let val = untracked_derived::<T>(self.id);
                f(&val)
            }
            SignalKind::Mutable => with_signal_value(self.id, f),
        }
    }
}

impl<T: Clone + Send + Sync + 'static> Signal<T> {
    /// Watch this signal from a background task.
    ///
    /// See [`RwSignal::watch`].
    pub fn watch(&self) -> tokio::sync::watch::Receiver<T> {
        let this = *self;
        watch_value(this.get_untracked(), move || this.get())
    }
}

/// A read-write reactive signal.
///
/// Created by [`create_signal`]. Provides both read and write access.
/// Can be converted to a read-only [`Signal<T>`] via [`read_only()`](RwSignal::read_only)
/// or the [`From`] impl. Widget properties accept `RwSignal<T>` via
/// [`IntoSignal`](super::IntoSignal).
///
/// `RwSignal<T>` is `Copy` (8 bytes — just a signal ID).
///
/// # Thread Safety
///
/// `RwSignal<T>` is `!Send`. Use [`.writer()`](RwSignal::writer) to get a
/// [`WriteSignal<T>`] which is `Send` for background thread writes.
pub struct RwSignal<T> {
    id: SignalId,
    _marker: PhantomData<T>,
    _not_send: PhantomData<*const ()>,
}

impl_signal_id_traits!(RwSignal);

impl<T> RwSignal<T> {
    /// Rebuild a handle from an id kept elsewhere.
    ///
    /// For the global registry, which stores ids because it holds signals of
    /// many types (`reactive/global.rs`). An id whose signal was disposed
    /// fails the generation check on the next read, as any stale handle does.
    pub(crate) const fn from_id(id: SignalId) -> Self {
        Self {
            id,
            _marker: PhantomData,
            _not_send: PhantomData,
        }
    }

    /// This signal's id.
    pub(crate) fn id(&self) -> SignalId {
        self.id
    }
}

/// What needs no copy of the value: borrowing it, and changing it in place.
/// A value that cannot be cloned — a `Secret` — is still a signal's to hold.
impl<T: 'static> RwSignal<T> {
    /// Borrow the value for reading
    #[inline]
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        check_reactive_scope();
        record_effect_read(self.id);
        record_signal_read(self.id);
        with_signal_value(self.id, f)
    }

    /// Borrow the value without tracking
    #[inline]
    pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        with_signal_value(self.id, f)
    }

    /// Update the value using a closure, notifying unconditionally.
    pub fn update_always<F: FnOnce(&mut T)>(&self, f: F) {
        update_and_notify_always(self.id, f);
    }
}

impl<T: Clone + 'static> RwSignal<T> {
    /// Get the current value (tracks as dependency for effects)
    #[inline]
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn get(&self) -> T {
        check_reactive_scope();
        record_effect_read(self.id);
        record_signal_read(self.id);
        get_signal_value(self.id)
    }

    /// Get the current value without tracking
    #[inline]
    pub fn get_untracked(&self) -> T {
        get_signal_value(self.id)
    }

    /// Get the current value without tracking, or `None` if the owner that
    /// created this signal has been disposed.
    ///
    /// For state that outlives the scopes it holds handles from and has to
    /// ask rather than assume — the widget-ref registry. Ordinary reads
    /// should keep panicking: a dead handle there is a bug, not a race.
    #[inline]
    pub(crate) fn try_get_untracked(&self) -> Option<T> {
        try_get_signal_value(self.id)
    }

    /// Convert to a read-only [`Signal<T>`].
    pub fn read_only(self) -> Signal<T> {
        Signal {
            id: self.id,
            kind: SignalKind::Mutable,
            _marker: PhantomData,
            _not_send: PhantomData,
        }
    }
}

impl<T: Clone + PartialEq + 'static> RwSignal<T> {
    /// Set a new value (notifies subscribers if changed).
    ///
    /// This is the STATE write: equal values are deduplicated. For
    /// trigger-style writes where every emission must notify — or for
    /// types with no meaningful `PartialEq` — use [`RwSignal::set_always`].
    pub fn set(&self, value: T) {
        write_and_notify(self.id, value);
    }

    /// Update the value using a closure
    pub fn update<F: FnOnce(&mut T)>(&self, f: F) {
        update_and_notify(self.id, f);
    }
}

impl<T: Clone + 'static> RwSignal<T> {
    /// Set a new value, notifying subscribers unconditionally.
    ///
    /// Equality is a property of the WRITE SITE, not of the signal: `set`
    /// publishes state (equal values deduplicate), `set_always` fires a
    /// trigger (every emission notifies). No `PartialEq` bound — types
    /// without meaningful equality can only be written this way, and the
    /// compiler steers them here.
    ///
    /// Note that a signal still holds ONE value: two `set_always` calls
    /// before the consumer runs coalesce to the last value (one
    /// notification per flush). That is correct for frame-coalescing
    /// triggers (an OSD flash, an animation kick); event streams that
    /// must not lose emissions belong in an async channel, not a signal.
    pub fn set_always(&self, value: T) {
        write_and_notify_always(self.id, value);
    }
}

impl<T: Clone + Send + Sync + 'static> RwSignal<T> {
    /// Watch this signal from a background task.
    ///
    /// The mirror of [`writer()`](RwSignal::writer): that one carries writes
    /// from a task to the main thread, this one carries the value the other
    /// way. The returned `watch::Receiver` is `Send`, always holds the current
    /// value (`borrow()`), and can be awaited (`changed()`) instead of polled
    /// — which is what an `Arc<AtomicBool>` mirrored by hand cannot do.
    ///
    /// When the scope that created it is disposed the sender drops, so
    /// `changed()` returns `Err`: the task's cue that the UI is gone.
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # use std::time::Duration;
    /// # #[derive(Clone, Copy, PartialEq)] enum Menu { SystemInfo }
    /// # #[derive(Clone, Copy)] enum Scope { All, Bar }
    /// # let menu = create_signal(None::<Menu>);
    /// # let interval = Duration::from_secs(1);
    /// # let sample = |_: Scope| {};
    /// let wide = create_memo(move || menu.get() == Some(Menu::SystemInfo));
    /// let mut wide_rx = wide.watch();
    ///
    /// create_task(move |ctx| async move {
    ///     while ctx.is_running() {
    ///         let scope = if *wide_rx.borrow() { Scope::All } else { Scope::Bar };
    ///         sample(scope);
    ///         tokio::select! {
    ///             _ = wide_rx.changed() => {}                       // react at once
    ///             _ = tokio::time::sleep(interval) => {}
    ///         }
    ///     }
    /// });
    /// ```
    pub fn watch(&self) -> tokio::sync::watch::Receiver<T> {
        let this = *self;
        watch_value(this.get_untracked(), move || this.get())
    }
}

impl<T: Clone + Send + 'static> RwSignal<T> {
    /// Get a `WriteSignal<T>` for writing from background threads.
    ///
    /// `WriteSignal<T>` is `Send` and can be captured in `create_service` closures.
    /// Writes from background threads are queued and applied on the main thread
    /// at the start of the next frame.
    pub fn writer(&self) -> WriteSignal<T> {
        WriteSignal {
            id: self.id,
            epoch: current_write_epoch(),
            _marker: PhantomData,
        }
    }
}

impl<T: Clone + 'static> From<RwSignal<T>> for Signal<T> {
    fn from(rw: RwSignal<T>) -> Self {
        rw.read_only()
    }
}

/// Write-only handle to a signal. `Send` — can be used from background threads.
///
/// On the main thread, writes are applied immediately with change detection.
/// On background threads, writes are queued and applied at the start of the
/// next frame on the main thread.
///
/// # Example
///
/// ```no_run
/// # use guido::prelude::*;
/// # use std::time::Duration;
/// # let get_current_time = || String::from("09:41");
/// let time = create_signal(get_current_time());
/// let time_w = time.writer();
///
/// create_task(move |ctx| async move {
///     while ctx.is_running() {
///         time_w.set(get_current_time()); // queued for main thread
///         tokio::time::sleep(Duration::from_secs(1)).await;
///     }
/// });
/// ```
pub struct WriteSignal<T> {
    id: SignalId,
    /// Write epoch captured when the writer was created. Writes queued from
    /// a stale epoch (after App restart) are silently discarded.
    epoch: u64,
    _marker: PhantomData<T>,
}

impl<T> Clone for WriteSignal<T> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<T> Copy for WriteSignal<T> {}

impl<T: Clone + PartialEq + Send + 'static> WriteSignal<T> {
    /// Sets the signal's value, only triggering updates if the value actually changed.
    ///
    /// If the signal exists in the current thread's storage: applies immediately.
    /// Otherwise (background threads): queued for next frame with the epoch
    /// captured when this writer was created.
    pub fn set(&self, value: T) {
        if has_signal(self.id) {
            write_and_notify(self.id, value);
        } else {
            let id = self.id;
            let epoch = self.epoch;
            queue_bg_write(epoch, move || {
                // The signal may have been disposed between queueing and this
                // flush (e.g. a service outliving a removed dynamic child).
                // That race is inherent to background writers, so drop the
                // write instead of panicking the main loop.
                if has_signal(id) {
                    write_and_notify(id, value);
                } else {
                    log::debug!("dropping background write to disposed signal {id}");
                }
            });
        }
    }

    /// Updates the signal's value using a closure, only triggering updates if the value changed.
    ///
    /// If the signal exists in the current thread's storage: applies immediately.
    /// Otherwise (background threads): queued for next frame with the epoch
    /// captured when this writer was created.
    pub fn update<F>(&self, f: F)
    where
        F: FnOnce(&mut T) + Send + 'static,
    {
        if has_signal(self.id) {
            update_and_notify(self.id, f);
        } else {
            let id = self.id;
            let epoch = self.epoch;
            queue_bg_write(epoch, move || {
                // See `set()`: disposal can race a queued write; drop it.
                if has_signal(id) {
                    update_and_notify(id, f);
                } else {
                    log::debug!("dropping background update to disposed signal {id}");
                }
            });
        }
    }
}

impl<T: Clone + Send + 'static> WriteSignal<T> {
    /// Sets the signal's value, notifying subscribers unconditionally.
    ///
    /// The trigger-style counterpart of [`WriteSignal::set`]: no
    /// comparison, no `PartialEq` bound. Same threading semantics
    /// (immediate on the main thread, queued for the next frame from
    /// background threads).
    pub fn set_always(&self, value: T) {
        if has_signal(self.id) {
            write_and_notify_always(self.id, value);
        } else {
            let id = self.id;
            let epoch = self.epoch;
            queue_bg_write(epoch, move || {
                // See `set()`: disposal can race a queued write; drop it.
                if has_signal(id) {
                    write_and_notify_always(id, value);
                } else {
                    log::debug!("dropping background write to disposed signal {id}");
                }
            });
        }
    }

    /// Updates the signal's value using a closure, notifying unconditionally.
    pub fn update_always<F>(&self, f: F)
    where
        F: FnOnce(&mut T) + Send + 'static,
    {
        if has_signal(self.id) {
            update_and_notify_always(self.id, f);
        } else {
            let id = self.id;
            let epoch = self.epoch;
            queue_bg_write(epoch, move || {
                if has_signal(id) {
                    update_and_notify_always(id, f);
                } else {
                    log::debug!("dropping background update to disposed signal {id}");
                }
            });
        }
    }
}

/// Create a read-write reactive signal.
///
/// Returns an [`RwSignal<T>`] that supports both reading and writing.
/// Converts to [`Signal<T>`] (read-only) via `.read_only()` or `Into`.
///
/// # Example
///
/// ```no_run
/// # use guido::prelude::*;
/// let count = create_signal(0.0f32);
/// count.set(1.0);         // write
/// count.get();            // read
/// container().padding(count); // auto-converts to Signal<T> via IntoSignal
/// ```
pub fn create_signal<T: Clone + Send + 'static>(value: T) -> RwSignal<T> {
    new_rw_signal(value)
}

/// [`create_signal`] without the bounds a public signal promises its readers:
/// for a value the crate holds in a signal and never hands out by copy.
pub(crate) fn new_rw_signal<T: 'static>(value: T) -> RwSignal<T> {
    let id = create_signal_value(value);
    // Safe even inside effect callbacks: the runtime borrow is never held
    // across user code anymore.
    with_runtime(|rt| rt.register_signal(id));
    register_signal(id);
    RwSignal {
        id,
        _marker: PhantomData,
        _not_send: PhantomData,
    }
}

/// Create a read-only signal from a static value.
///
/// Unlike `create_signal`, this only requires `Clone` (no `PartialEq` or `Send`).
/// The returned `Signal<T>` is `Copy` and can be freely passed into closures.
/// It cannot be written to — there is no `set()` or `writer()`.
///
/// # Example
///
/// ```no_run
/// # use guido::prelude::*;
/// let color = create_stored(Color::RED);
/// container().background(color); // Copy, no clone needed
/// ```
pub fn create_stored<T: Clone + 'static>(value: T) -> Signal<T> {
    let id = create_stored_value(value);
    register_signal(id);
    Signal {
        id,
        kind: SignalKind::Stored,
        _marker: PhantomData,
        _not_send: PhantomData,
    }
}

/// Create a derived signal from a closure.
///
/// The closure is called on each `.get()` — there is no caching. The closure's
/// internal signal reads register dependencies directly with the calling
/// widget/effect, so there is no double-tracking.
///
/// Only requires `T: Clone` (no `PartialEq` or `Send`).
///
/// # Example
///
/// ```no_run
/// # use guido::prelude::*;
/// let count = create_signal(0);
/// let label = create_derived(move || format!("Count: {}", count.get()));
/// text(label); // Copy, reactive
/// ```
pub fn create_derived<T: Clone + 'static>(f: impl Fn() -> T + 'static) -> Signal<T> {
    let id = create_derived_value(f);
    register_signal(id);
    Signal {
        id,
        kind: SignalKind::Derived,
        _marker: PhantomData,
        _not_send: PhantomData,
    }
}

/// Feed a `tokio::watch` channel from a reactive read.
///
/// Shared by the `watch()` of every signal kind. The effect that pumps the
/// channel belongs to the current scope, so it dies with whatever created it
/// — exactly like the task on the other end of the channel.
fn watch_value<T: Clone + Send + Sync + 'static>(
    initial: T,
    read: impl Fn() -> T + 'static,
) -> tokio::sync::watch::Receiver<T> {
    let (tx, rx) = tokio::sync::watch::channel(initial);
    // Owned by the scope that asked for the channel: disposing it drops the
    // sender, which is how the task on the other end learns the UI is gone
    // (`changed()` returns Err).
    super::effect::create_effect(move || {
        let _ = tx.send(read());
    });
    rx
}

#[cfg(test)]
mod watch_tests {
    use super::*;

    /// The bridge apps were hand-rolling with `Arc<AtomicBool>`: a value a
    /// background task can read, kept current by the reactive graph.
    #[test]
    fn a_watcher_sees_the_current_value_and_every_change() {
        let flag = create_signal(false);
        let rx = flag.watch();
        assert!(!*rx.borrow());

        flag.set(true);
        assert!(*rx.borrow(), "the watcher follows the signal");
        assert!(rx.has_changed().unwrap(), "and is notified, not polled");
    }

    /// A memo is the natural thing to watch: only real transitions wake the
    /// task.
    #[test]
    fn watching_a_memo_reports_only_real_changes() {
        let count = create_signal(0);
        let is_high = crate::reactive::create_memo(move || count.get() > 10);
        let mut rx = is_high.watch();
        assert!(!*rx.borrow_and_update());

        count.set(5);
        assert!(
            !rx.has_changed().unwrap(),
            "still false: nothing to wake for"
        );

        count.set(50);
        assert!(rx.has_changed().unwrap());
        assert!(*rx.borrow_and_update());
    }

    /// Disposing the scope drops the sender, which is how the task learns the
    /// UI is gone.
    #[test]
    fn disposing_the_scope_closes_the_channel() {
        let (rx, owner) = crate::reactive::owner::with_owner(|| {
            let flag = create_signal(false);
            flag.watch()
        });

        assert!(!rx.borrow().to_owned());
        crate::reactive::__internal::dispose_owner(owner);

        // The sender is gone: the channel reports closed without awaiting
        assert!(
            rx.has_changed().is_err(),
            "a disposed scope must close the channel"
        );
    }
}

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

    #[test]
    fn test_create_signal_and_get() {
        let signal = create_signal(42);
        assert_eq!(signal.get(), 42);
    }

    #[test]
    fn test_set_updates_value() {
        let signal = create_signal(10);
        signal.set(20);
        assert_eq!(signal.get(), 20);
    }

    #[test]
    fn test_update_with_closure() {
        let signal = create_signal(5);
        signal.update(|v| *v += 10);
        assert_eq!(signal.get(), 15);
    }

    #[test]
    fn test_with_for_borrowing() {
        let signal = create_signal(String::from("hello"));
        let length = signal.with(|s| s.len());
        assert_eq!(length, 5);
    }

    #[test]
    fn test_get_untracked() {
        let signal = create_signal(100);
        let value = signal.get_untracked();
        assert_eq!(value, 100);
    }

    #[test]
    fn test_clone_shares_underlying_value() {
        let signal1 = create_signal(50);
        let signal2 = signal1; // Copy, not clone!

        signal1.set(75);
        assert_eq!(signal2.get(), 75);

        signal2.set(100);
        assert_eq!(signal1.get(), 100);
    }

    #[test]
    fn test_with_untracked() {
        let signal = create_signal(String::from("test"));
        let result = signal.with_untracked(|s| format!("{}ing", s));
        assert_eq!(result, "testing");
    }

    #[test]
    fn test_update_only_triggers_on_change() {
        let signal = create_signal(10);
        signal.update(|v| *v = 10); // No actual change
        assert_eq!(signal.get(), 10);
    }

    #[test]
    fn test_set_only_triggers_on_change() {
        let signal = create_signal(5);
        signal.set(5); // No actual change
        assert_eq!(signal.get(), 5);
        signal.set(10); // Actual change
        assert_eq!(signal.get(), 10);
    }

    #[test]
    fn test_rw_signal_is_copy() {
        let signal = create_signal(42);
        let _copy1 = signal;
        let _copy2 = signal;
        assert_eq!(signal.get(), 42);
    }

    #[test]
    fn test_rw_signal_to_signal() {
        let rw = create_signal(42);
        let read_only: Signal<i32> = rw.into();
        assert_eq!(read_only.get(), 42);
        rw.set(100);
        assert_eq!(read_only.get(), 100);
    }

    #[test]
    fn test_rw_signal_size() {
        // SignalId is two u32s (index + generation), so alignment is 4:
        // RwSignal is exactly the id, Signal adds the 1-byte kind + padding.
        assert_eq!(std::mem::size_of::<RwSignal<i32>>(), 8);
        assert_eq!(std::mem::size_of::<Signal<i32>>(), 12);
    }

    /// Regression test: a signal handle that outlives its owner must stay
    /// invalid even after the storage slot is recycled by a same-typed
    /// signal. With non-generational ids the stale handle silently read and
    /// wrote the new signal's value.
    #[test]
    fn test_stale_handle_does_not_alias_recycled_slot() {
        use super::super::owner::{dispose_owner_now, with_owner};

        let (stale, owner_id) = with_owner(|| create_signal(1_i32));
        dispose_owner_now(owner_id);

        // Recycles the freed slot with the same value type
        let fresh = create_signal(2_i32);
        assert_eq!(
            stale.id.index(),
            fresh.id.index(),
            "slot should be recycled"
        );
        assert_ne!(stale.id.generation(), fresh.id.generation());

        // The stale handle must not resolve to the new signal
        assert!(!has_signal(stale.id));
        assert!(has_signal(fresh.id));
        assert_eq!(fresh.get(), 2);
    }

    // ================================================================
    // writer() tests
    // ================================================================

    #[test]
    fn test_writer_set_on_main_thread() {
        let signal = create_signal(42);
        let writer = signal.writer();
        writer.set(100);
        assert_eq!(signal.get(), 100);
    }

    #[test]
    fn test_writer_update_on_main_thread() {
        let signal = create_signal(10);
        let writer = signal.writer();
        writer.update(|v| *v += 5);
        assert_eq!(signal.get(), 15);
    }

    /// Equality is a property of the write site: `set` deduplicates equal
    /// values, `set_always` notifies unconditionally.
    #[test]
    fn set_dedups_but_set_always_notifies() {
        use crate::reactive::create_effect;
        use std::cell::Cell;
        use std::rc::Rc;

        let sig = create_signal(7);
        let runs = Rc::new(Cell::new(0));
        let counter = runs.clone();
        create_effect(move || {
            let _ = sig.get();
            counter.set(counter.get() + 1);
        });
        assert_eq!(runs.get(), 1);

        sig.set(7); // equal: state write deduplicates
        assert_eq!(runs.get(), 1, "set of an equal value must not notify");

        sig.set_always(7); // equal, but trigger write
        assert_eq!(runs.get(), 2, "set_always must notify unconditionally");
    }

    /// A type with no `PartialEq` can live in a signal — the compiler
    /// steers it to the trigger-style writes.
    #[test]
    fn non_partialeq_type_uses_always_writes() {
        #[derive(Clone)]
        struct Snapshot {
            value: u32,
        }

        let sig = create_signal(Snapshot { value: 1 });
        sig.set_always(Snapshot { value: 2 });
        assert_eq!(sig.with(|s| s.value), 2);

        sig.update_always(|s| s.value += 1);
        assert_eq!(sig.with(|s| s.value), 3);

        // Background-writer path too (same-thread branch)
        let w = sig.writer();
        w.set_always(Snapshot { value: 10 });
        assert_eq!(sig.with(|s| s.value), 10);
    }
}