1use crate::{EditorState, Unregister};
19use std::any::Any;
20use std::cell::{Cell, RefCell};
21use std::marker::PhantomData;
22use std::rc::{Rc, Weak};
23
24const RUNNING: u8 = 1 << 0;
25const NOTIFIED: u8 = 1 << 1;
26const OUTDATED: u8 = 1 << 2;
27const DISPOSED: u8 = 1 << 3;
28const TRACKING: u8 = 1 << 5;
29
30type Value = Rc<dyn Any>;
31type SourceCallback = Option<Rc<dyn Fn(&Rc<Source>)>>;
32type EffectFn = Rc<dyn Fn() -> Option<Unregister>>;
33pub type SignalCallback<T> = Option<Rc<dyn Fn(&Signal<T>)>>;
35
36struct Node {
39 source: Rc<Source>,
40 target: Target,
41 version: Cell<i64>,
42 rollback_node: RefCell<Option<Rc<Node>>>,
43}
44
45#[derive(Clone)]
48enum Target {
49 Computed(Weak<Source>),
50 Effect(Rc<EffectInner>),
51}
52
53impl Target {
54 fn is(&self, other: &Target) -> bool {
55 match (self, other) {
56 (Target::Computed(a), Target::Computed(b)) => a.ptr_eq(b),
57 (Target::Effect(a), Target::Effect(b)) => Rc::ptr_eq(a, b),
58 _ => false,
59 }
60 }
61
62 fn flags(&self) -> u8 {
63 match self {
64 Target::Computed(c) => c
65 .upgrade()
66 .map_or(0, |c| c.computed.as_ref().expect("computed").flags.get()),
67 Target::Effect(e) => e.flags.get(),
68 }
69 }
70
71 fn with_sources<R>(&self, f: impl FnOnce(&RefCell<Vec<Rc<Node>>>) -> R) -> Option<R> {
72 match self {
73 Target::Computed(c) => {
74 let c = c.upgrade()?;
75 Some(f(&c.computed.as_ref().expect("computed").sources))
76 }
77 Target::Effect(e) => Some(f(&e.sources)),
78 }
79 }
80
81 fn notify(&self) {
82 match self {
83 Target::Computed(c) => {
84 if let Some(c) = c.upgrade() {
85 computed_notify(&c);
86 }
87 }
88 Target::Effect(e) => effect_notify(e),
89 }
90 }
91}
92
93struct Source {
95 value: RefCell<Option<Value>>,
96 version: Cell<i64>,
97 node: RefCell<Option<Rc<Node>>>,
98 targets: RefCell<Vec<Rc<Node>>>,
100 batch_snapshot_version: Cell<u64>,
101 watched: SourceCallback,
102 unwatched: SourceCallback,
103 same: fn(&dyn Any, &dyn Any) -> bool,
105 computed: Option<ComputedData>,
106}
107
108struct ComputedData {
109 func: Box<dyn Fn() -> Value>,
110 sources: RefCell<Vec<Rc<Node>>>,
111 global_version: Cell<u64>,
112 flags: Cell<u8>,
113}
114
115struct EffectInner {
116 func: RefCell<Option<EffectFn>>,
117 cleanup: RefCell<Option<Unregister>>,
118 sources: RefCell<Vec<Rc<Node>>>,
119 flags: Cell<u8>,
120}
121
122struct BatchSnapshot {
123 source: Rc<Source>,
124 value: Option<Value>,
125 version: i64,
126}
127
128#[derive(Default)]
130struct State {
131 eval_context: RefCell<Option<Target>>,
132 batched_effects: RefCell<Vec<Rc<EffectInner>>>,
134 batch_depth: Cell<u32>,
135 batch_iteration: Cell<u32>,
136 batch_snapshot_version: Cell<u64>,
137 current_batch_snapshot_version: Cell<u64>,
138 batch_snapshots: RefCell<Vec<BatchSnapshot>>,
140 global_version: Cell<u64>,
141}
142
143thread_local! {
144 static STATE: State = State::default();
145}
146
147fn with_state<R>(f: impl FnOnce(&State) -> R) -> R {
148 STATE.with(f)
149}
150
151pub trait SignalValue: Clone + 'static {
155 fn is_same(&self, other: &Self) -> bool;
156}
157
158impl<T: Clone + PartialEq + 'static> SignalValue for T {
159 fn is_same(&self, other: &Self) -> bool {
160 self == other
161 }
162}
163
164impl SignalValue for EditorState {
165 fn is_same(&self, other: &Self) -> bool {
166 self.ptr_eq(other)
167 }
168}
169
170fn same_value<T: SignalValue>(a: &dyn Any, b: &dyn Any) -> bool {
171 match (a.downcast_ref::<T>(), b.downcast_ref::<T>()) {
172 (Some(a), Some(b)) => a.is_same(b),
173 _ => false,
174 }
175}
176
177fn values_same(source: &Source, a: &Option<Value>, b: &Option<Value>) -> bool {
178 match (a, b) {
179 (Some(a), Some(b)) => (source.same)(a.as_ref(), b.as_ref()),
180 (None, None) => true,
181 _ => false,
182 }
183}
184
185fn start_batch() {
186 with_state(|s| s.batch_depth.set(s.batch_depth.get() + 1));
187}
188
189fn end_batch() {
190 if with_state(|s| {
191 let depth = s.batch_depth.get();
192 if depth > 1 {
193 s.batch_depth.set(depth - 1);
194 }
195 depth > 1
196 }) {
197 return;
198 }
199 reconcile_batch_snapshots();
200 loop {
201 let effects = with_state(|s| std::mem::take(&mut *s.batched_effects.borrow_mut()));
202 if effects.is_empty() {
203 break;
204 }
205 with_state(|s| s.batch_iteration.set(s.batch_iteration.get() + 1));
206 for effect in effects.iter().rev() {
207 effect.flags.set(effect.flags.get() & !NOTIFIED);
208 if effect.flags.get() & DISPOSED == 0
209 && needs_to_recompute(&Target::Effect(effect.clone()))
210 {
211 effect_callback(effect);
212 }
213 }
214 }
215 with_state(|s| {
216 s.batch_iteration.set(0);
217 s.batch_depth.set(s.batch_depth.get() - 1);
218 });
219}
220
221pub fn batch<R>(f: impl FnOnce() -> R) -> R {
224 if with_state(|s| s.batch_depth.get() > 0) {
225 return f();
226 }
227 with_state(|s| {
228 let version = s.batch_snapshot_version.get() + 1;
229 s.batch_snapshot_version.set(version);
230 s.current_batch_snapshot_version.set(version);
231 });
232 start_batch();
233 let result = f();
234 end_batch();
235 result
236}
237
238struct ContextGuard(Option<Target>);
240
241impl Drop for ContextGuard {
242 fn drop(&mut self) {
243 let prev = self.0.take();
244 with_state(|s| *s.eval_context.borrow_mut() = prev);
245 }
246}
247
248fn set_eval_context(target: Option<Target>) -> Option<Target> {
249 with_state(|s| std::mem::replace(&mut *s.eval_context.borrow_mut(), target))
250}
251
252pub fn untracked<R>(f: impl FnOnce() -> R) -> R {
255 let _guard = ContextGuard(set_eval_context(None));
256 f()
257}
258
259fn record_batch_snapshot(source: &Rc<Source>) {
260 with_state(|s| {
261 if s.batch_depth.get() == 0 || s.batch_iteration.get() != 0 {
262 return;
263 }
264 let current = s.current_batch_snapshot_version.get();
265 if source.batch_snapshot_version.get() != current {
266 source.batch_snapshot_version.set(current);
267 s.batch_snapshots.borrow_mut().insert(
268 0,
269 BatchSnapshot {
270 source: source.clone(),
271 value: source.value.borrow().clone(),
272 version: source.version.get(),
273 },
274 );
275 }
276 });
277}
278
279fn reconcile_batch_snapshots() {
280 let snapshots = with_state(|s| std::mem::take(&mut *s.batch_snapshots.borrow_mut()));
281 for snapshot in snapshots {
282 let source = &snapshot.source;
283 if values_same(source, &source.value.borrow(), &snapshot.value) {
284 for node in source.targets.borrow().iter() {
285 if node.version.get() == snapshot.version {
286 node.version.set(source.version.get());
287 }
288 }
289 }
290 }
291}
292
293fn add_dependency(source: &Rc<Source>) -> Option<Rc<Node>> {
294 let context = with_state(|s| s.eval_context.borrow().clone())?;
295 let existing = source.node.borrow().clone();
296 match existing {
297 Some(node) if node.target.is(&context) => {
298 if node.version.get() != -1 {
299 return None;
300 }
301 node.version.set(0);
302 context.with_sources(|sources| {
305 let mut sources = sources.borrow_mut();
306 if let Some(i) = sources.iter().position(|n| Rc::ptr_eq(n, &node))
307 && i != sources.len() - 1
308 {
309 let node = sources.remove(i);
310 sources.push(node);
311 }
312 });
313 Some(node)
314 }
315 existing => {
316 let node = Rc::new(Node {
317 source: source.clone(),
318 target: context.clone(),
319 version: Cell::new(0),
320 rollback_node: RefCell::new(existing),
321 });
322 context.with_sources(|sources| sources.borrow_mut().push(node.clone()));
323 *source.node.borrow_mut() = Some(node.clone());
324 if context.flags() & TRACKING != 0 {
325 subscribe(source, &node);
326 }
327 Some(node)
328 }
329 }
330}
331
332fn subscribe(source: &Rc<Source>, node: &Rc<Node>) {
333 if let Some(computed) = &source.computed
334 && source.targets.borrow().is_empty()
335 {
336 computed
337 .flags
338 .set(computed.flags.get() | OUTDATED | TRACKING);
339 let sources = computed.sources.borrow().clone();
340 for n in &sources {
341 subscribe(&n.source, n);
342 }
343 }
344 let was_empty = {
345 let mut targets = source.targets.borrow_mut();
346 if targets.iter().any(|n| Rc::ptr_eq(n, node)) {
347 return;
348 }
349 let was_empty = targets.is_empty();
350 targets.insert(0, node.clone());
351 was_empty
352 };
353 if was_empty && let Some(watched) = source.watched.clone() {
354 untracked(|| watched(source));
355 }
356}
357
358fn unsubscribe(source: &Rc<Source>, node: &Rc<Node>) {
359 if source.targets.borrow().is_empty() {
360 return;
361 }
362 let removed_last = {
363 let mut targets = source.targets.borrow_mut();
364 match targets.iter().position(|n| Rc::ptr_eq(n, node)) {
365 Some(i) => {
366 targets.remove(i);
367 targets.is_empty()
368 }
369 None => false,
370 }
371 };
372 if removed_last && let Some(unwatched) = source.unwatched.clone() {
373 untracked(|| unwatched(source));
374 }
375 if let Some(computed) = &source.computed
378 && source.targets.borrow().is_empty()
379 {
380 computed.flags.set(computed.flags.get() & !TRACKING);
381 let sources = computed.sources.borrow().clone();
382 for n in &sources {
383 unsubscribe(&n.source, n);
384 }
385 }
386}
387
388fn refresh(source: &Rc<Source>) -> bool {
389 match &source.computed {
390 None => true,
391 Some(_) => computed_refresh(source),
392 }
393}
394
395fn needs_to_recompute(target: &Target) -> bool {
396 let sources = target
397 .with_sources(|s| s.borrow().clone())
398 .unwrap_or_default();
399 for node in &sources {
400 if node.source.version.get() != node.version.get()
401 || !refresh(&node.source)
402 || node.source.version.get() != node.version.get()
403 {
404 return true;
405 }
406 }
407 false
408}
409
410fn prepare_sources(target: &Target) {
411 target.with_sources(|sources| {
412 for node in sources.borrow().iter() {
413 if let Some(rollback) = node.source.node.borrow().clone() {
414 *node.rollback_node.borrow_mut() = Some(rollback);
415 }
416 *node.source.node.borrow_mut() = Some(node.clone());
417 node.version.set(-1);
418 }
419 });
420}
421
422fn cleanup_sources(target: &Target) {
423 let sources = target
424 .with_sources(|s| s.borrow().clone())
425 .unwrap_or_default();
426 let mut kept = Vec::new();
427 for node in sources.iter().rev() {
428 if node.version.get() == -1 {
429 unsubscribe(&node.source, node);
430 } else {
431 kept.push(node.clone());
432 }
433 let rollback = node.rollback_node.borrow_mut().take();
434 *node.source.node.borrow_mut() = rollback;
435 }
436 kept.reverse();
437 target.with_sources(|s| *s.borrow_mut() = kept);
438}
439
440fn computed_refresh(source: &Rc<Source>) -> bool {
441 let computed = source.computed.as_ref().expect("computed");
442 let flags = &computed.flags;
443 flags.set(flags.get() & !NOTIFIED);
444 if flags.get() & RUNNING != 0 {
445 return false;
446 }
447 if flags.get() & (OUTDATED | TRACKING) == TRACKING {
448 return true;
449 }
450 flags.set(flags.get() & !OUTDATED);
451 let global_version = with_state(|s| s.global_version.get());
452 if computed.global_version.get() == global_version {
453 return true;
454 }
455 computed.global_version.set(global_version);
456 flags.set(flags.get() | RUNNING);
457 let target = Target::Computed(Rc::downgrade(source));
458 if source.version.get() > 0 && !needs_to_recompute(&target) {
459 flags.set(flags.get() & !RUNNING);
460 return true;
461 }
462 prepare_sources(&target);
463 let prev = set_eval_context(Some(target.clone()));
464 let value = Some((computed.func)());
465 if source.version.get() == 0 || !values_same(source, &source.value.borrow(), &value) {
466 *source.value.borrow_mut() = value;
467 source.version.set(source.version.get() + 1);
468 }
469 set_eval_context(prev);
470 cleanup_sources(&target);
471 flags.set(flags.get() & !RUNNING);
472 true
473}
474
475fn computed_notify(source: &Rc<Source>) {
476 let computed = source.computed.as_ref().expect("computed");
477 if computed.flags.get() & NOTIFIED == 0 {
478 computed
479 .flags
480 .set(computed.flags.get() | OUTDATED | NOTIFIED);
481 let targets = source.targets.borrow().clone();
482 for node in &targets {
483 node.target.notify();
484 }
485 }
486}
487
488fn effect_notify(effect: &Rc<EffectInner>) {
489 if effect.flags.get() & NOTIFIED == 0 {
490 effect.flags.set(effect.flags.get() | NOTIFIED);
491 with_state(|s| s.batched_effects.borrow_mut().push(effect.clone()));
492 }
493}
494
495fn effect_callback(effect: &Rc<EffectInner>) {
496 let prev = effect_start(effect);
497 if effect.flags.get() & DISPOSED == 0 {
498 let func = effect.func.borrow().clone();
499 if let Some(func) = func
500 && let Some(cleanup) = func()
501 {
502 *effect.cleanup.borrow_mut() = Some(cleanup);
503 }
504 }
505 effect_end(effect, prev);
506}
507
508fn effect_start(effect: &Rc<EffectInner>) -> Option<Target> {
509 if effect.flags.get() & RUNNING != 0 {
510 panic!("Cycle detected");
511 }
512 effect.flags.set((effect.flags.get() | RUNNING) & !DISPOSED);
513 cleanup_effect(effect);
514 let target = Target::Effect(effect.clone());
515 prepare_sources(&target);
516 start_batch();
517 set_eval_context(Some(target))
518}
519
520fn effect_end(effect: &Rc<EffectInner>, prev: Option<Target>) {
521 let target = Target::Effect(effect.clone());
522 let current = with_state(|s| s.eval_context.borrow().clone());
523 assert!(
524 current.is_some_and(|c| c.is(&target)),
525 "Out-of-order effect"
526 );
527 cleanup_sources(&target);
528 set_eval_context(prev);
529 effect.flags.set(effect.flags.get() & !RUNNING);
530 if effect.flags.get() & DISPOSED != 0 {
531 dispose_effect(effect);
532 }
533 end_batch();
534}
535
536fn cleanup_effect(effect: &Rc<EffectInner>) {
537 let cleanup = effect.cleanup.borrow_mut().take();
538 if let Some(cleanup) = cleanup {
539 start_batch();
540 let prev = set_eval_context(None);
541 cleanup();
542 set_eval_context(prev);
543 end_batch();
544 }
545}
546
547fn dispose_effect(effect: &Rc<EffectInner>) {
548 let sources = std::mem::take(&mut *effect.sources.borrow_mut());
549 for node in &sources {
550 unsubscribe(&node.source, node);
551 }
552 *effect.func.borrow_mut() = None;
553 cleanup_effect(effect);
554}
555
556fn effect_dispose(effect: &Rc<EffectInner>) {
557 effect.flags.set(effect.flags.get() | DISPOSED);
558 if effect.flags.get() & RUNNING == 0 {
559 dispose_effect(effect);
560 }
561}
562
563pub struct SignalOptions<T> {
566 pub watched: SignalCallback<T>,
567 pub unwatched: SignalCallback<T>,
568}
569
570impl<T> Default for SignalOptions<T> {
571 fn default() -> Self {
572 Self {
573 watched: None,
574 unwatched: None,
575 }
576 }
577}
578
579pub struct Signal<T>(Rc<Source>, PhantomData<T>);
582
583impl<T> Clone for Signal<T> {
584 fn clone(&self) -> Self {
585 Signal(self.0.clone(), PhantomData)
586 }
587}
588
589pub struct ReadonlySignal<T>(Rc<Source>, PhantomData<T>);
592
593impl<T> Clone for ReadonlySignal<T> {
594 fn clone(&self) -> Self {
595 ReadonlySignal(self.0.clone(), PhantomData)
596 }
597}
598
599fn read_value<T: Clone + 'static>(source: &Rc<Source>) -> T {
600 source
601 .value
602 .borrow()
603 .as_ref()
604 .and_then(|v| v.downcast_ref::<T>())
605 .cloned()
606 .expect("a signal holds a value of its type")
607}
608
609fn source_value<T: Clone + 'static>(source: &Rc<Source>) -> T {
610 if let Some(computed) = &source.computed {
611 if computed.flags.get() & RUNNING != 0 {
612 panic!("Cycle detected");
613 }
614 let node = add_dependency(source);
615 computed_refresh(source);
616 if let Some(node) = node {
617 node.version.set(source.version.get());
618 }
619 } else if let Some(node) = add_dependency(source) {
620 node.version.set(source.version.get());
621 }
622 read_value(source)
623}
624
625pub fn signal<T: SignalValue>(value: T) -> Signal<T> {
627 signal_with_options(value, SignalOptions::default())
628}
629
630pub fn signal_with_options<T: SignalValue>(value: T, options: SignalOptions<T>) -> Signal<T> {
632 let typed = |f: SignalCallback<T>| -> SourceCallback {
633 f.map(|f| Rc::new(move |s: &Rc<Source>| f(&Signal(s.clone(), PhantomData))) as _)
634 };
635 Signal(
636 Rc::new(Source {
637 value: RefCell::new(Some(Rc::new(value))),
638 version: Cell::new(0),
639 node: RefCell::new(None),
640 targets: RefCell::new(Vec::new()),
641 batch_snapshot_version: Cell::new(0),
642 watched: typed(options.watched),
643 unwatched: typed(options.unwatched),
644 same: same_value::<T>,
645 computed: None,
646 }),
647 PhantomData,
648 )
649}
650
651impl<T: SignalValue> Signal<T> {
652 pub fn value(&self) -> T {
655 source_value(&self.0)
656 }
657
658 pub fn set_value(&self, value: T) {
662 let source = &self.0;
663 if source
664 .value
665 .borrow()
666 .as_ref()
667 .and_then(|v| v.downcast_ref::<T>())
668 .is_some_and(|v| v.is_same(&value))
669 {
670 return;
671 }
672 if with_state(|s| s.batch_iteration.get()) > 100 {
673 panic!("Cycle detected");
674 }
675 record_batch_snapshot(source);
676 *source.value.borrow_mut() = Some(Rc::new(value));
677 source.version.set(source.version.get() + 1);
678 with_state(|s| s.global_version.set(s.global_version.get() + 1));
679 start_batch();
680 let targets = source.targets.borrow().clone();
681 for node in &targets {
682 node.target.notify();
683 }
684 end_batch();
685 }
686
687 pub fn peek(&self) -> T {
689 untracked(|| self.value())
690 }
691
692 pub fn subscribe(&self, f: impl Fn(T) + 'static) -> Unregister {
695 let this = self.clone();
696 effect(move || {
697 let value = this.value();
698 untracked(|| f(value));
699 None
700 })
701 }
702
703 pub fn as_readonly(&self) -> ReadonlySignal<T> {
705 ReadonlySignal(self.0.clone(), PhantomData)
706 }
707}
708
709impl<T: Clone + 'static> ReadonlySignal<T> {
710 pub fn value(&self) -> T {
712 source_value(&self.0)
713 }
714
715 pub fn peek(&self) -> T {
717 untracked(|| self.value())
718 }
719}
720
721pub fn computed<T: SignalValue>(f: impl Fn() -> T + 'static) -> ReadonlySignal<T> {
724 let global_version = with_state(|s| s.global_version.get());
725 ReadonlySignal(
726 Rc::new(Source {
727 value: RefCell::new(None),
728 version: Cell::new(0),
729 node: RefCell::new(None),
730 targets: RefCell::new(Vec::new()),
731 batch_snapshot_version: Cell::new(0),
732 watched: None,
733 unwatched: None,
734 same: same_value::<T>,
735 computed: Some(ComputedData {
736 func: Box::new(move || Rc::new(f()) as Value),
737 sources: RefCell::new(Vec::new()),
738 global_version: Cell::new(global_version.wrapping_sub(1)),
739 flags: Cell::new(OUTDATED),
740 }),
741 }),
742 PhantomData,
743 )
744}
745
746pub fn effect(f: impl Fn() -> Option<Unregister> + 'static) -> Unregister {
750 let effect = Rc::new(EffectInner {
751 func: RefCell::new(Some(Rc::new(f))),
752 cleanup: RefCell::new(None),
753 sources: RefCell::new(Vec::new()),
754 flags: Cell::new(TRACKING),
755 });
756 effect_callback(&effect);
757 Box::new(move || effect_dispose(&effect))
758}