ferrokit 0.8.0

Native macOS GUI framework for Rust: every view a real AppKit control (NSTableView, NSOutlineView, NSTextView), updated in place by fine-grained signals
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
//! Fine-grained, main-thread reactive state.
//!
//! An [`Effect`] remembers which signals it read during its last run;
//! changing one of them queues the effect. Everything runs inside a
//! [`batch`]: effects run once, when the outermost batch ends, so an effect
//! never re-enters itself and several changes cost one run. Views own the
//! effects that update their native views.
//!
//! [`Signal`] and [`Memo`] are `Copy` handles into a per-thread arena, so
//! closures capture them without cloning. Each belongs to the *owner* that
//! was current when it was created: a window's view tree, a list row, a
//! [`dynamic`](crate::dynamic) branch or a document. It's freed with that
//! owner. Signals created outside any owner (app state made in `main`) live
//! as long as the app.

use ferrokit_core::kept::{UiCell, UiLocal};
use std::any::Any;
use std::cell::{Cell, RefCell};
use std::fmt;
use std::marker::PhantomData;
use std::rc::{Rc, Weak};

struct EffectInner {
    f: RefCell<Box<dyn FnMut()>>,
    /// Bumped on every run; subscriptions from older runs are stale.
    generation: Cell<u64>,
    queued: Cell<bool>,
    /// A memo's effect: it only computes, so a memo read may run it early.
    memo: Cell<bool>,
    stopped: Cell<bool>,
    /// The owner current when the effect was made: current again while it
    /// runs, so signals it creates belong there.
    owner: Option<Weak<OwnerInner>>,
}

// ---- owners and the arena ----

/// Frees the signals (and memos' effects) created while it was current,
/// when the last clone is dropped. Nodes, windows and documents hold one.
#[derive(Clone)]
pub(crate) struct Owner(Rc<OwnerInner>);

#[derive(Default)]
pub(crate) struct OwnerInner {
    signals: RefCell<Vec<(u32, u32)>>,
    effects: RefCell<Vec<Effect>>,
    /// Async tasks started while it was current (see [`crate::spawn_local`]):
    /// cancelled when it goes, unless detached or already finished.
    tasks: RefCell<Vec<u64>>,
}

impl Owner {
    pub(crate) fn new() -> Owner {
        Owner(Rc::new(OwnerInner::default()))
    }

    /// Runs `f` with this owner current.
    pub(crate) fn with<R>(&self, f: impl FnOnce() -> R) -> R {
        // Put back even if `f` unwinds (a failure caught further out):
        // otherwise this owner would stay current, kept alive, and take
        // every signal made afterwards.
        struct Restore(Option<Rc<OwnerInner>>);
        impl Drop for Restore {
            fn drop(&mut self) {
                let prev = self.0.take();
                // The owner that was current is dropped outside the borrow
                // (its last reference may be this one).
                let was = OWNER.try_with(|o| std::mem::replace(&mut *o.borrow_mut(), prev));
                drop(was);
            }
        }
        let _restore = Restore(OWNER.with_borrow_mut(|o| o.replace(self.0.clone())));
        f()
    }
}

impl Drop for OwnerInner {
    fn drop(&mut self) {
        // Its tasks are cancelled first (their futures may read its
        // signals as they're dropped), then memos' effects stop, then the
        // signals go.
        let tasks = std::mem::take(&mut *self.tasks.borrow_mut());
        crate::task::cancel_all(tasks);
        self.effects.borrow_mut().clear();
        let signals = std::mem::take(&mut *self.signals.borrow_mut());
        // The values are dropped outside the arena's borrow (a value may
        // own another owner). (The arena is a `UiCell`: still there as the
        // process exits.)
        let freed: Vec<Rc<dyn Any>> = ARENA.with_borrow_mut(|a| signals.iter().filter_map(|&(i, g)| a.free(i, g)).collect());
        drop(freed);
    }
}

struct Slot {
    value: Option<Rc<dyn Any>>,
    generation: u32,
}

#[derive(Default)]
struct Arena {
    slots: Vec<Slot>,
    free: Vec<u32>,
}

impl Arena {
    fn insert(&mut self, value: Rc<dyn Any>) -> (u32, u32) {
        match self.free.pop() {
            Some(i) => {
                let slot = &mut self.slots[i as usize];
                slot.value = Some(value);
                (i, slot.generation)
            }
            None => {
                self.slots.push(Slot { value: Some(value), generation: 0 });
                ((self.slots.len() - 1) as u32, 0)
            }
        }
    }

    fn free(&mut self, index: u32, generation: u32) -> Option<Rc<dyn Any>> {
        let slot = self.slots.get_mut(index as usize)?;
        if slot.generation != generation {
            return None;
        }
        slot.generation = slot.generation.wrapping_add(1);
        self.free.push(index);
        slot.value.take()
    }
}

/// Runs `f` with no owner: what it makes lives as long as the app.
pub(crate) fn unowned<R>(f: impl FnOnce() -> R) -> R {
    struct Restore(Option<Rc<OwnerInner>>);
    impl Drop for Restore {
        fn drop(&mut self) {
            let prev = self.0.take();
            let _ = OWNER.try_with(|o| *o.borrow_mut() = prev);
        }
    }
    let _restore = Restore(OWNER.with_borrow_mut(Option::take));
    f()
}

/// `f`, run with the owner current now (for callbacks registered while
/// building: signals a button's action makes, say for a sheet's form,
/// belong to the button's view tree rather than living for the app).
pub(crate) fn with_current_owner(f: impl Fn() + 'static) -> impl Fn() + 'static {
    let owner = OWNER.with_borrow(|o| o.as_ref().map(Rc::downgrade));
    move || match owner.as_ref().and_then(Weak::upgrade) {
        Some(o) => Owner(o).with(&f),
        None => f(),
    }
}

/// Adds task `id` to the current owner, returned (weakly) for the task's
/// polls; `None` outside any owner (the task lives as long as the app).
pub(crate) fn own_task(id: u64) -> Option<Weak<OwnerInner>> {
    OWNER.with_borrow(|o| {
        o.as_ref().map(|o| {
            o.tasks.borrow_mut().push(id);
            Rc::downgrade(o)
        })
    })
}

/// Takes task `id` off its owner's list (it finished, or was detached).
pub(crate) fn disown_task(owner: &Weak<OwnerInner>, id: u64) {
    if let Some(o) = owner.upgrade() {
        o.tasks.borrow_mut().retain(|&t| t != id);
    }
}

/// Runs `f` with `owner` current if it's still there (else with none).
pub(crate) fn with_weak_owner<R>(owner: Option<&Weak<OwnerInner>>, f: impl FnOnce() -> R) -> R {
    match owner.and_then(Weak::upgrade) {
        Some(o) => Owner(o).with(f),
        None => unowned(f),
    }
}

/// Live signals in the arena (diagnostic: freed ones are reused).
pub fn live_signals() -> usize {
    ARENA.with_borrow(|a| a.slots.len() - a.free.len())
}

thread_local! {
    static OBSERVER: UiCell<Option<Rc<EffectInner>>> = const { UiCell::new(None) };
    static DEPTH: Cell<u32> = const { Cell::new(0) };
    static PENDING: UiCell<Vec<Rc<EffectInner>>> = const { UiCell::new(Vec::new()) };
    static AFTER: UiCell<Vec<Rc<dyn Fn()>>> = const { UiCell::new(Vec::new()) };
    static RUNS: Cell<u64> = const { Cell::new(0) };
    /// How many of `PENDING` are memos' effects (a memo read looks for them
    /// only when there are some).
    static QUEUED_MEMOS: Cell<u32> = const { Cell::new(0) };
    static OWNER: UiCell<Option<Rc<OwnerInner>>> = const { UiCell::new(None) };
    static ARENA: UiCell<Arena> = UiCell::new(Arena::default());
}

impl EffectInner {
    /// Taken out of `PENDING`.
    fn dequeued(&self) {
        self.queued.set(false);
        if self.memo.get() {
            QUEUED_MEMOS.with(|n| n.set(n.get().saturating_sub(1)));
        }
    }

    fn run(self: &Rc<Self>) {
        if self.stopped.get() {
            return;
        }
        // The effect's own owner is current (none for app-level effects),
        // whatever was current where the batch flushed. (Looked up before
        // anything is changed: an effect that doesn't run leaves the
        // observer as it was.)
        let owner = match &self.owner {
            None => None,
            Some(weak) => match weak.upgrade() {
                Some(owner) => Some(owner),
                // Its owner (a closed window or document) is gone, and the
                // signals it reads with it: it doesn't run again. (Queued
                // in a batch that closed its window, a text's effect read
                // a freed signal.)
                None => {
                    self.stopped.set(true);
                    return;
                }
            },
        };
        RUNS.with(|r| r.set(r.get() + 1));
        self.generation.set(self.generation.get() + 1);
        let prev = OBSERVER.with_borrow_mut(|o| o.replace(self.clone()));
        let prev_owner = OWNER.with_borrow_mut(|c| std::mem::replace(c, owner));
        // Put back even if the effect unwinds (a failure caught further out).
        struct Restore(Option<Rc<EffectInner>>, Option<Rc<OwnerInner>>);
        impl Drop for Restore {
            fn drop(&mut self) {
                let (observer, owner) = (self.0.take(), self.1.take());
                let _ = OWNER.try_with(|c| *c.borrow_mut() = owner);
                let _ = OBSERVER.try_with(|o| *o.borrow_mut() = observer);
            }
        }
        let _restore = Restore(prev, prev_owner);
        (self.f.borrow_mut())();
    }
}

/// A side effect that re-runs when the signals it read change. It stops when
/// the handle is dropped.
#[must_use = "an effect stops when its handle is dropped"]
pub struct Effect(Rc<EffectInner>);

impl Effect {
    /// Runs `f` now, and again (once per batch) whenever a signal it read
    /// during its last run changes.
    pub fn new(f: impl FnMut() + 'static) -> Effect {
        let inner = Rc::new(EffectInner {
            f: RefCell::new(Box::new(f)),
            generation: Cell::new(0),
            queued: Cell::new(false),
            memo: Cell::new(false),
            stopped: Cell::new(false),
            owner: OWNER.with_borrow(|o| o.as_ref().map(Rc::downgrade)),
        });
        // In a batch: a first run that sets a signal it read runs again
        // once it has returned, not inside itself.
        batch(|| inner.run());
        Effect(inner)
    }
}

impl Drop for Effect {
    fn drop(&mut self) {
        self.0.stopped.set(true);
    }
}

impl fmt::Debug for Effect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Effect").field("runs", &self.0.generation.get()).finish()
    }
}

/// Total effect runs on this thread so far (diagnostic).
pub fn effect_runs() -> u64 {
    RUNS.with(Cell::get)
}

/// Runs `f`; effects triggered inside run once, when the outermost batch ends.
///
/// The outermost batch also drains its own autorelease pool, so a burst of
/// updates (each creating and removing native views) doesn't pile up
/// autoreleased AppKit objects until the run loop's next pass.
pub fn batch<R>(f: impl FnOnce() -> R) -> R {
    if DEPTH.with(Cell::get) > 0 {
        return nested(f);
    }
    use crate::platform::{Native, Platform};
    Native::scope(|| nested(f))
}

fn nested<R>(f: impl FnOnce() -> R) -> R {
    /// Leaves the batch even when `f` unwinds (a failure caught further
    /// out): otherwise no later batch would flush.
    struct Leave;
    impl Drop for Leave {
        fn drop(&mut self) {
            let _ = DEPTH.try_with(|d| d.set(d.get().saturating_sub(1)));
        }
    }
    DEPTH.with(|d| d.set(d.get() + 1));
    let leave = Leave;
    let r = f();
    if DEPTH.with(Cell::get) == 1 {
        flush();
    }
    drop(leave);
    r
}

/// Registers `f` to run after every outermost batch, once its effects have
/// run (the layout pass hooks in here).
pub fn after_batch(f: impl Fn() + 'static) {
    AFTER.with_borrow_mut(|a| a.push(Rc::new(f)));
}

/// Reads signals inside `f` without subscribing the running effect to them.
pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
    struct Restore(Option<Rc<EffectInner>>);
    impl Drop for Restore {
        fn drop(&mut self) {
            let prev = self.0.take();
            let _ = OBSERVER.try_with(|o| *o.borrow_mut() = prev);
        }
    }
    let _restore = Restore(OBSERVER.with_borrow_mut(Option::take));
    f()
}

/// Runs the effects waiting for the current batch to end now (printing
/// needs a view's drawing recorded before the batch it's called in ends).
pub(crate) fn run_pending() {
    while let Some(e) = PENDING.with_borrow_mut(|p| (!p.is_empty()).then(|| p.remove(0))) {
        e.dequeued();
        e.run();
    }
}

fn flush() {
    loop {
        while let Some(e) = PENDING.with_borrow_mut(|p| (!p.is_empty()).then(|| p.remove(0))) {
            e.dequeued();
            e.run();
        }
        let hooks: Vec<_> = AFTER.with_borrow(|a| a.clone());
        for h in hooks {
            h();
        }
        if PENDING.with_borrow(Vec::is_empty) {
            break;
        }
    }
}

/// `Copy` for any `T` and `!Send` (main-thread only).
type Handle<T> = (fn() -> T, *const ());

/// Mutable state: a `Copy` handle (closures capture it as is). It belongs
/// to the owner current when it was made (see the module docs) and is freed
/// with it; afterwards reading it panics and setting it does nothing.
pub struct Signal<T> {
    index: u32,
    generation: u32,
    _marker: PhantomData<Handle<T>>,
}

struct SignalInner<T> {
    value: RefCell<T>,
    subs: RefCell<Vec<(Weak<EffectInner>, u64)>>,
    /// Subscriber count at which `track` next sweeps out dead and outdated
    /// entries (`notify` drops them all, but a signal that rarely changes,
    /// read by views that come and go, would otherwise keep every one).
    sweep_at: Cell<usize>,
}

/// The smallest subscriber list `track` sweeps.
const SWEEP_MIN: usize = 32;

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

impl<T> Copy for Signal<T> {}

impl<T> PartialEq for Signal<T> {
    fn eq(&self, other: &Self) -> bool {
        (self.index, self.generation) == (other.index, other.generation)
    }
}

impl<T> Eq for Signal<T> {}

impl<T: fmt::Debug + 'static> fmt::Debug for Signal<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.try_inner() {
            Some(inner) => f.debug_tuple("Signal").field(&inner.value.borrow()).finish(),
            None => f.write_str("Signal(<freed>)"),
        }
    }
}

impl<T: 'static> Signal<T> {
    /// A signal holding `value`, owned by the current owner (if any).
    pub fn new(value: T) -> Self {
        let inner: Rc<dyn Any> = Rc::new(SignalInner { value: RefCell::new(value), subs: RefCell::new(Vec::new()), sweep_at: Cell::new(SWEEP_MIN) });
        let (index, generation) = ARENA.with_borrow_mut(|a| a.insert(inner));
        OWNER.with_borrow(|o| {
            if let Some(o) = o {
                o.signals.borrow_mut().push((index, generation));
            }
        });
        Signal { index, generation, _marker: PhantomData }
    }

    fn try_inner(&self) -> Option<Rc<SignalInner<T>>> {
        let value = ARENA.with_borrow(|a| {
            let slot = a.slots.get(self.index as usize)?;
            (slot.generation == self.generation).then(|| slot.value.clone()).flatten()
        })?;
        value.downcast::<SignalInner<T>>().ok()
    }

    fn inner(&self) -> Rc<SignalInner<T>> {
        self.try_inner().expect(
            "signal read after it was freed: it belonged to a window, list row, dynamic branch or document that has closed",
        )
    }

    /// Identifies this signal (for keying work by it).
    pub(crate) fn key(&self) -> u64 {
        (u64::from(self.index) << 32) | u64::from(self.generation)
    }

    /// Whether the signal still exists (its owner hasn't been dropped).
    pub fn is_alive(&self) -> bool {
        self.try_inner().is_some()
    }

    /// A copy of the value, subscribing the running effect; `None` once the
    /// signal was freed.
    pub fn try_get(&self) -> Option<T>
    where
        T: Clone,
    {
        self.try_inner()?;
        Some(self.get())
    }

    fn track(inner: &SignalInner<T>) {
        OBSERVER.with_borrow(|o| {
            if let Some(e) = o {
                let generation = e.generation.get();
                let mut subs = inner.subs.borrow_mut();
                if !subs.iter().any(|(w, g)| *g == generation && std::ptr::eq(w.as_ptr(), Rc::as_ptr(e))) {
                    if subs.len() >= inner.sweep_at.get() {
                        // Keep live effects still on the run that read this
                        // signal; doubling the threshold keeps sweeps amortised O(1).
                        subs.retain(|(w, g)| w.upgrade().is_some_and(|e| e.generation.get() == *g && !e.stopped.get()));
                        inner.sweep_at.set((subs.len() * 2).max(SWEEP_MIN));
                    }
                    subs.push((Rc::downgrade(e), generation));
                }
            }
        });
    }

    /// Reads the value through `f`, subscribing the running effect.
    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        let inner = self.inner();
        Self::track(&inner);
        f(&inner.value.borrow())
    }

    /// A copy of the value, subscribing the running effect.
    pub fn get(&self) -> T
    where
        T: Clone,
    {
        self.with(T::clone)
    }

    /// A copy of the value, without subscribing.
    pub fn get_untracked(&self) -> T
    where
        T: Clone,
    {
        self.inner().value.borrow().clone()
    }

    /// Reads the value through `f` without subscribing: like
    /// [`with`](Self::with), for a large value (a `Vec`, a tree) that an
    /// effect reads but shouldn't re-run for.
    pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        f(&self.inner().value.borrow())
    }

    /// Replaces the value and notifies readers (nothing, once freed).
    pub fn set(&self, value: T) {
        let Some(inner) = self.try_inner() else { return };
        *inner.value.borrow_mut() = value;
        Self::notify(&inner);
    }

    /// Replaces the value and notifies readers only if it changed.
    pub fn set_if_changed(&self, value: T)
    where
        T: PartialEq,
    {
        let Some(inner) = self.try_inner() else { return };
        if *inner.value.borrow() != value {
            *inner.value.borrow_mut() = value;
            Self::notify(&inner);
        }
    }

    /// Changes the value in place and notifies readers (nothing, once freed).
    pub fn update(&self, f: impl FnOnce(&mut T)) {
        let Some(inner) = self.try_inner() else { return };
        f(&mut inner.value.borrow_mut());
        Self::notify(&inner);
    }

    fn notify(inner: &SignalInner<T>) {
        // Effects subscribe again when they re-run, so take them all.
        let subs = std::mem::take(&mut *inner.subs.borrow_mut());
        batch(|| {
            for (w, g) in subs {
                if let Some(e) = w.upgrade().filter(|e| e.generation.get() == g && !e.stopped.get())
                    && !e.queued.replace(true)
                {
                    if e.memo.get() {
                        QUEUED_MEMOS.with(|n| n.set(n.get() + 1));
                    }
                    PENDING.with_borrow_mut(|p| p.push(e));
                }
            }
        });
    }
}

/// Derived state: recomputed when its inputs change; readers are notified
/// only when the value actually changes. A `Copy` handle, owned like a
/// [`Signal`].
pub struct Memo<T> {
    signal: Signal<T>,
}

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

impl<T> Copy for Memo<T> {}

thread_local! {
    /// Effects of memos made outside any owner: they live as long as the app.
    static ROOT_EFFECTS: UiCell<Vec<Effect>> = const { UiCell::new(Vec::new()) };
}

/// Keeps `effect` running for as long as the current owner (or the app,
/// outside one).
pub(crate) fn keep_with_owner(effect: Effect) {
    OWNER.with_borrow(|o| match o {
        Some(o) => o.effects.borrow_mut().push(effect),
        None => ROOT_EFFECTS.with_borrow_mut(|r| r.push(effect)),
    });
}

impl<T: PartialEq + Clone + 'static> Memo<T> {
    /// A value computed by `f` from other signals.
    pub fn new(f: impl Fn() -> T + 'static) -> Self {
        let cell: Rc<Cell<Option<Signal<T>>>> = Rc::new(Cell::new(None));
        let c = cell.clone();
        let effect = Effect::new(move || {
            let v = f();
            match c.get() {
                None => c.set(Some(Signal::new(v))),
                Some(s) => s.set_if_changed(v),
            }
        });
        let signal = cell.get().expect("memo computed");
        effect.0.memo.set(true);
        keep_with_owner(effect);
        Memo { signal }
    }

    /// Recomputes now if an input changed in the batch under way: a memo
    /// read after setting what it depends on gives the new value, even
    /// inside an action. The input may be another memo, itself waiting for
    /// the batch to end, so every waiting memo runs, in the order queued,
    /// until none is left (one that runs may queue the next in a chain).
    /// Memos only compute; ordinary effects still wait for the batch.
    fn refresh(&self) {
        while QUEUED_MEMOS.with(Cell::get) > 0 {
            // Not one that is computing now (it read this memo).
            let next = PENDING.with_borrow_mut(|p| p.iter().position(|e| e.memo.get() && e.f.try_borrow_mut().is_ok()).map(|i| p.remove(i)));
            let Some(e) = next else { break };
            e.dequeued();
            e.run();
        }
    }

    /// The current value, subscribing the running effect.
    pub fn get(&self) -> T {
        self.refresh();
        self.signal.get()
    }

    /// Reads the value through `f`, subscribing the running effect.
    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        self.refresh();
        self.signal.with(f)
    }

    /// The current value, without subscribing.
    pub fn get_untracked(&self) -> T {
        self.refresh();
        self.signal.get_untracked()
    }

    /// Reads the value through `f` without subscribing.
    pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        self.refresh();
        self.signal.with_untracked(f)
    }
}

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

    fn counter() -> (Rc<Cell<u32>>, impl Fn() + Clone) {
        let n = Rc::new(Cell::new(0));
        let m = n.clone();
        (n, move || m.set(m.get() + 1))
    }

    /// An owner kept in a thread-local can outlive the arena as the thread
    /// exits (`std::process::exit` in an app); dropping it must not panic,
    /// which aborts the process there.
    #[test]
    fn owner_dropped_after_the_arena() {
        thread_local! {
            static KEEP: RefCell<Option<Owner>> = const { RefCell::new(None) };
        }
        let exited = std::thread::spawn(|| {
            // KEEP's destructor is registered first, so it runs last.
            KEEP.with_borrow(|_| ());
            let owner = Owner::new();
            owner.with(|| Signal::new(1).set(2));
            KEEP.with_borrow_mut(|k| *k = Some(owner));
        })
        .join();
        assert!(exited.is_ok());
    }

    /// Inside a batch (an action), a memo read after setting its input has
    /// the new value, not the one from before the batch.
    #[test]
    fn memo_is_current_inside_a_batch() {
        let (seen, n) = (Signal::new(1), Rc::new(Cell::new(0)));
        let runs = n.clone();
        let doubled = Memo::new(move || {
            runs.set(runs.get() + 1);
            seen.get() * 2
        });
        let inside = batch(|| {
            seen.set(5);
            doubled.get_untracked()
        });
        assert_eq!(inside, 10);
        assert_eq!(doubled.get_untracked(), 10);
        assert_eq!(n.get(), 2, "computed once at first, once for the change: not again when the batch ended");
    }

    /// A memo of a memo: setting the first one's input queues only the
    /// first, and the second must still be current when read.
    #[test]
    fn chained_memos_are_current_inside_a_batch() {
        let source = Signal::new(1);
        let middle = Memo::new(move || source.get() + 1);
        let leaf = Memo::new(move || middle.get() * 10);
        let last = Memo::new(move || leaf.get() + 1);
        let (runs, bump) = counter();
        let _e = Effect::new(move || {
            last.get();
            bump();
        });
        let inside = batch(|| {
            source.set(2);
            let first = (leaf.get_untracked(), last.get_untracked());
            source.set(3);
            (first, leaf.get_untracked(), last.get_untracked())
        });
        assert_eq!(inside, ((30, 31), 40, 41));
        assert_eq!(runs.get(), 2, "the effect ran once at first and once for the batch");
        // A diamond: both sides are current, whichever is read first.
        let (a, b) = (Memo::new(move || source.get() * 2), Memo::new(move || source.get() * 3));
        let sum = Memo::new(move || a.get() + b.get());
        assert_eq!(batch(|| { source.set(10); sum.get_untracked() }), 50);
    }

    #[test]
    fn the_owner_is_put_back_after_a_panic() {
        let outer = Owner::new();
        let before = live_signals();
        outer.with(|| {
            let inner = Owner::new();
            let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                inner.with(|| {
                    Signal::new(1);
                    panic!("on purpose");
                })
            }));
            assert!(caught.is_err());
            // Made after the panic: in `outer`, not in the owner that failed.
            Signal::new(2);
            drop(inner);
            assert_eq!(live_signals(), before + 1, "the failed owner's signal went with it");
        });
        assert!(OWNER.with_borrow(Option::is_none));
        drop(outer);
        assert_eq!(live_signals(), before);
    }

    #[test]
    fn an_effect_that_does_not_run_leaves_the_observer() {
        let trigger = Signal::new(0);
        let owner = Owner::new();
        let effect = owner.with(|| Effect::new(move || { trigger.get(); }));
        batch(|| {
            trigger.set(1);
            drop(owner);
        });
        assert!(OBSERVER.with_borrow(Option::is_none), "no observer is left at top level");
        drop(effect);
    }

    /// An effect made outside a batch that sets a signal it read: it runs
    /// again after its first run, not inside it.
    #[test]
    fn a_first_run_that_sets_what_it_read_runs_again_after() {
        let value = Signal::new(150);
        let (runs, bump) = counter();
        let _e = Effect::new(move || {
            bump();
            if value.get() > 100 {
                value.set(100);
            }
        });
        assert_eq!((value.get_untracked(), runs.get()), (100, 2));
    }

    #[test]
    fn with_untracked_reads_without_subscribing() {
        let s = Signal::new(vec![1, 2, 3]);
        let m = Memo::new(move || s.with(|v| v.len()));
        let (runs, bump) = counter();
        let seen = Rc::new(Cell::new(0));
        let seen2 = seen.clone();
        let _e = Effect::new(move || {
            bump();
            seen2.set(s.with_untracked(|v| v.iter().sum::<i32>()) + m.with_untracked(|n| *n as i32) + m.get_untracked() as i32);
        });
        assert_eq!((runs.get(), seen.get()), (1, 12));
        s.update(|v| v.push(4));
        assert_eq!(runs.get(), 1, "neither the signal nor the memo subscribed");
    }

    #[test]
    fn effect_runs_on_change_and_stops_on_drop() {
        let s = Signal::new(1);
        let (runs, bump) = counter();
        let seen = Rc::new(Cell::new(0));
        let (s2, seen2) = (s, seen.clone());
        let e = Effect::new(move || {
            bump();
            seen2.set(s2.get());
        });
        assert_eq!((runs.get(), seen.get()), (1, 1));
        s.set(2);
        assert_eq!((runs.get(), seen.get()), (2, 2));
        drop(e);
        s.set(3);
        assert_eq!(runs.get(), 2);
    }

    #[test]
    fn batch_coalesces() {
        let (a, b) = (Signal::new(0), Signal::new(0));
        let (runs, bump) = counter();
        let (a2, b2) = (a, b);
        let _e = Effect::new(move || {
            bump();
            let _ = a2.get() + b2.get();
        });
        batch(|| {
            a.set(1);
            b.set(1);
            a.set(2);
        });
        assert_eq!(runs.get(), 2);
    }

    #[test]
    fn dynamic_dependencies() {
        let (flag, x, y) = (Signal::new(true), Signal::new(0), Signal::new(0));
        let (runs, bump) = counter();
        let (f2, x2, y2) = (flag, x, y);
        let _e = Effect::new(move || {
            bump();
            let _ = if f2.get() { x2.get() } else { y2.get() };
        });
        y.set(1); // not read yet
        assert_eq!(runs.get(), 1);
        flag.set(false);
        assert_eq!(runs.get(), 2);
        x.set(1); // no longer read
        assert_eq!(runs.get(), 2);
        y.set(2);
        assert_eq!(runs.get(), 3);
    }

    #[test]
    fn memo_notifies_only_on_change() {
        let n = Signal::new(4);
        let n2 = n;
        let even = Memo::new(move || n2.get() % 2 == 0);
        let (runs, bump) = counter();
        let e2 = even;
        let _e = Effect::new(move || {
            bump();
            let _ = e2.get();
        });
        n.set(6); // still even
        assert_eq!(runs.get(), 1);
        n.set(7);
        assert_eq!(runs.get(), 2);
        assert!(!even.get());
    }

    #[test]
    fn diamond_runs_once() {
        let a = Signal::new(1);
        let (a1, a2) = (a, a);
        let b = Memo::new(move || a1.get() + 1);
        let c = Memo::new(move || a2.get() * 2);
        let (runs, bump) = counter();
        let (b2, c2) = (b, c);
        let total = Rc::new(Cell::new(0));
        let t2 = total.clone();
        let _e = Effect::new(move || {
            bump();
            t2.set(b2.get() + c2.get());
        });
        a.set(10);
        assert_eq!(total.get(), 31);
        assert_eq!(runs.get(), 2);
    }

    #[test]
    fn effects_can_set_signals() {
        let (src, dst) = (Signal::new(1), Signal::new(0));
        let (s2, d2) = (src, dst);
        let _copy = Effect::new(move || d2.set(s2.get() * 10));
        assert_eq!(dst.get_untracked(), 10);
        src.set(2);
        assert_eq!(dst.get_untracked(), 20);
    }

    #[test]
    fn untrack_and_set_if_changed() {
        let s = Signal::new(1);
        let (runs, bump) = counter();
        let s2 = s;
        let _e = Effect::new(move || {
            bump();
            untrack(|| s2.get());
        });
        s.set(2);
        assert_eq!(runs.get(), 1);
        let t = Signal::new(5);
        let t2 = t;
        let (runs, bump) = counter();
        let _e = Effect::new(move || {
            bump();
            let _ = t2.get();
        });
        t.set_if_changed(5);
        assert_eq!(runs.get(), 1);
    }

    #[test]
    fn short_lived_readers_dont_pile_up() {
        // A signal that never changes, read by effects that come and go (views
        // in windows that open and close): its list stays small.
        let s = Signal::new(0);
        let keep = Signal::new(0);
        let (k, (runs, bump)) = (keep, counter());
        let _kept = Effect::new(move || {
            bump();
            let _ = k.get();
        });
        for _ in 0..10_000 {
            let s2 = s;
            let e = Effect::new(move || {
                let _ = s2.get();
            });
            drop(e);
        }
        assert!(s.inner().subs.borrow().len() <= 2 * SWEEP_MIN, "{} entries", s.inner().subs.borrow().len());
        // Live readers survive sweeps and still run.
        let live: Vec<Effect> = (0..100)
            .map(|_| {
                let s2 = s;
                Effect::new(move || {
                    let _ = s2.get();
                })
            })
            .collect();
        for _ in 0..1_000 {
            let s2 = s;
            drop(Effect::new(move || {
                let _ = s2.get();
            }));
        }
        let before = effect_runs();
        s.set(1);
        assert_eq!(effect_runs() - before, 100);
        keep.set(1);
        assert_eq!(runs.get(), 2);
        drop(live);
    }

    #[test]
    fn owners_free_their_signals() {
        let before = live_signals();
        let owner = Owner::new();
        let (a, m) = owner.with(|| {
            let a = Signal::new(1);
            (a, Memo::new(move || a.get() * 2))
        });
        let outside = Signal::new(0);
        assert_eq!(m.get(), 2);
        assert_eq!(live_signals(), before + 3);
        drop(owner);
        assert_eq!(live_signals(), before + 1);
        assert!(!a.is_alive());
        assert_eq!(a.try_get(), None);
        a.set(5); // a no-op once freed
        assert!(outside.is_alive());
        // Freed slots are reused, and the old handle stays dead.
        let b = Signal::new(7);
        assert!(!a.is_alive());
        assert_eq!(b.get(), 7);
    }

    #[test]
    fn an_effect_whose_owner_is_gone_does_not_run() {
        let trigger = Signal::new(0);
        let owner = Owner::new();
        let runs = Rc::new(Cell::new(0));
        let r = runs.clone();
        let effect = owner.with(|| {
            let own = Signal::new(1);
            Effect::new(move || {
                trigger.get();
                r.set(r.get() + own.get());
            })
        });
        assert_eq!(runs.get(), 1);
        // Queued in a batch, then its owner freed (a window closed) before
        // the batch ends: it would read a freed signal.
        batch(|| {
            trigger.set(1);
            drop(owner);
        });
        assert_eq!(runs.get(), 1);
        drop(effect);
    }

    #[test]
    fn effects_create_signals_in_their_owner() {
        let before = live_signals();
        let trigger = Signal::new(0);
        let made = Rc::new(Cell::new(0));
        let owner = Owner::new();
        let m = made.clone();
        let effect = owner.with(|| {
            Effect::new(move || {
                trigger.get();
                Signal::new(0u8);
                m.set(m.get() + 1);
            })
        });
        // Re-run outside the owner: the new signal still goes to it.
        trigger.set(1);
        assert_eq!(made.get(), 2);
        drop(effect);
        drop(owner);
        assert_eq!(live_signals(), before + 1); // only `trigger`
    }

    #[test]
    #[should_panic(expected = "freed")]
    fn reading_a_freed_signal_panics() {
        let owner = Owner::new();
        let s = owner.with(|| Signal::new(1));
        drop(owner);
        s.get();
    }
}