native_gui_core/state.rs
1use std::cell::RefCell;
2use std::rc::Rc;
3
4type Listener<T> = Box<dyn Fn(&T)>;
5
6/// A reactive signal that notifies listeners when its value changes.
7///
8/// # Bridging signals to the UI thread (`async` feature)
9///
10/// `Signal` is UI-thread-only (`Rc` internals, not `Send`) and listeners run
11/// synchronously inside [`Signal::set`]/[`Signal::update`]. To drive widgets
12/// from a signal, bridge the listener into the bounded UI command queue
13/// instead of touching widgets directly:
14///
15/// 1. Create a `UiProxy` with `Ui::task_proxy` before wiring the listener.
16/// 2. Subscribe once on the UI thread; the listener converts the new value
17/// into proxy posts (`set_text`, `set_value`, `set_checked`, `set_enabled`,
18/// `set_visible`, `progress`). A `UiProxy` is `Send` and bounded, so the
19/// same wiring works when the signal is updated on the UI thread and the
20/// commands are applied on the next event-loop turn.
21/// 3. Drain the queue from the event loop: [`Ui::wait_event`](crate::Ui::wait_event),
22/// [`Ui::poll_event`](crate::Ui::poll_event),
23/// [`Ui::dispatch_events`](crate::Ui::dispatch_events), and
24/// `run_until_closed` apply posted commands in FIFO order on the UI thread
25/// before returning backend events.
26///
27/// Posts that arrive after teardown, or when the bounded queue is full,
28/// report `TaskSendError` instead of blocking or
29/// panicking, so a listener can degrade gracefully. Background threads cannot
30/// hold a `Signal`: send raw values through the proxy (or a channel) and
31/// update the signal on the UI thread, where its listeners run.
32///
33/// ```rust
34/// use native_gui_mock::MockBackend;
35/// use native_gui_core::state::Signal;
36/// use native_gui_core::{Ui, WidgetKind};
37///
38/// # fn main() -> native_gui_core::GuiResult<()> {
39/// # #[cfg(feature = "async")]
40/// # {
41/// let mut ui = Ui::new(MockBackend::default());
42/// let label = ui.create(WidgetKind::Label, Some("0"))?;
43/// let proxy = ui.task_proxy();
44///
45/// let counter = Signal::new(0i32);
46/// counter.subscribe(move |value| {
47/// let _ = proxy.set_text(label, value.to_string());
48/// });
49///
50/// counter.set(1);
51/// // The queue drains on the next event-loop turn (here: a dispatch pass).
52/// ui.dispatch_events(|_| {})?;
53/// assert_eq!(
54/// ui.widget(label).and_then(|spec| spec.text.clone()),
55/// Some("1".to_owned())
56/// );
57/// # }
58/// # Ok(())
59/// # }
60/// ```
61pub struct Signal<T> {
62 inner: Rc<RefCell<SignalInner<T>>>,
63}
64
65struct SignalInner<T> {
66 value: T,
67 listeners: Vec<Listener<T>>,
68}
69
70impl<T: Clone> Clone for Signal<T> {
71 fn clone(&self) -> Self {
72 Self {
73 inner: Rc::clone(&self.inner),
74 }
75 }
76}
77
78impl<T: Clone + PartialEq> Signal<T> {
79 /// Creates a new reactive signal with an initial value.
80 pub fn new(initial: T) -> Self {
81 Self {
82 inner: Rc::new(RefCell::new(SignalInner {
83 value: initial,
84 listeners: Vec::new(),
85 })),
86 }
87 }
88
89 /// Gets the current value of the signal.
90 pub fn get(&self) -> T {
91 self.inner.borrow().value.clone()
92 }
93
94 /// Sets a new value for the signal, notifying listeners if the value changed.
95 pub fn set(&self, new_value: T) {
96 let mut inner = self.inner.borrow_mut();
97 if inner.value != new_value {
98 inner.value = new_value.clone();
99 for listener in &inner.listeners {
100 listener(&new_value);
101 }
102 }
103 }
104
105 /// Mutates the value in place and notifies listeners once if it changed.
106 ///
107 /// This is the main entry point for the observable store: views subscribe
108 /// with [`Signal::subscribe`] and rebuild the affected widgets when the
109 /// value they depend on changes.
110 pub fn update(&self, mutate: impl FnOnce(&mut T)) {
111 let mut inner = self.inner.borrow_mut();
112 let mut candidate = inner.value.clone();
113 mutate(&mut candidate);
114 if inner.value != candidate {
115 inner.value = candidate.clone();
116 for listener in &inner.listeners {
117 listener(&candidate);
118 }
119 }
120 }
121
122 /// Registers a callback to be invoked when the value changes.
123 pub fn subscribe<F: Fn(&T) + 'static>(&self, callback: F) {
124 self.inner.borrow_mut().listeners.push(Box::new(callback));
125 }
126}