native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
use std::cell::RefCell;
use std::rc::Rc;

type Listener<T> = Box<dyn Fn(&T)>;

/// A reactive signal that notifies listeners when its value changes.
///
/// # Bridging signals to the UI thread (`async` feature)
///
/// `Signal` is UI-thread-only (`Rc` internals, not `Send`) and listeners run
/// synchronously inside [`Signal::set`]/[`Signal::update`]. To drive widgets
/// from a signal, bridge the listener into the bounded UI command queue
/// instead of touching widgets directly:
///
/// 1. Create a `UiProxy` with `Ui::task_proxy` before wiring the listener.
/// 2. Subscribe once on the UI thread; the listener converts the new value
///    into proxy posts (`set_text`, `set_value`, `set_checked`, `set_enabled`,
///    `set_visible`, `progress`). A `UiProxy` is `Send` and bounded, so the
///    same wiring works when the signal is updated on the UI thread and the
///    commands are applied on the next event-loop turn.
/// 3. Drain the queue from the event loop: [`Ui::wait_event`](crate::Ui::wait_event),
///    [`Ui::poll_event`](crate::Ui::poll_event),
///    [`Ui::dispatch_events`](crate::Ui::dispatch_events), and
///    `run_until_closed` apply posted commands in FIFO order on the UI thread
///    before returning backend events.
///
/// Posts that arrive after teardown, or when the bounded queue is full,
/// report `TaskSendError` instead of blocking or
/// panicking, so a listener can degrade gracefully. Background threads cannot
/// hold a `Signal`: send raw values through the proxy (or a channel) and
/// update the signal on the UI thread, where its listeners run.
///
/// ```rust
/// use native_gui_mock::MockBackend;
/// use native_gui_core::state::Signal;
/// use native_gui_core::{Ui, WidgetKind};
///
/// # fn main() -> native_gui_core::GuiResult<()> {
/// # #[cfg(feature = "async")]
/// # {
/// let mut ui = Ui::new(MockBackend::default());
/// let label = ui.create(WidgetKind::Label, Some("0"))?;
/// let proxy = ui.task_proxy();
///
/// let counter = Signal::new(0i32);
/// counter.subscribe(move |value| {
///     let _ = proxy.set_text(label, value.to_string());
/// });
///
/// counter.set(1);
/// // The queue drains on the next event-loop turn (here: a dispatch pass).
/// ui.dispatch_events(|_| {})?;
/// assert_eq!(
///     ui.widget(label).and_then(|spec| spec.text.clone()),
///     Some("1".to_owned())
/// );
/// # }
/// # Ok(())
/// # }
/// ```
pub struct Signal<T> {
    inner: Rc<RefCell<SignalInner<T>>>,
}

struct SignalInner<T> {
    value: T,
    listeners: Vec<Listener<T>>,
}

impl<T: Clone> Clone for Signal<T> {
    fn clone(&self) -> Self {
        Self {
            inner: Rc::clone(&self.inner),
        }
    }
}

impl<T: Clone + PartialEq> Signal<T> {
    /// Creates a new reactive signal with an initial value.
    pub fn new(initial: T) -> Self {
        Self {
            inner: Rc::new(RefCell::new(SignalInner {
                value: initial,
                listeners: Vec::new(),
            })),
        }
    }

    /// Gets the current value of the signal.
    pub fn get(&self) -> T {
        self.inner.borrow().value.clone()
    }

    /// Sets a new value for the signal, notifying listeners if the value changed.
    pub fn set(&self, new_value: T) {
        let mut inner = self.inner.borrow_mut();
        if inner.value != new_value {
            inner.value = new_value.clone();
            for listener in &inner.listeners {
                listener(&new_value);
            }
        }
    }

    /// Mutates the value in place and notifies listeners once if it changed.
    ///
    /// This is the main entry point for the observable store: views subscribe
    /// with [`Signal::subscribe`] and rebuild the affected widgets when the
    /// value they depend on changes.
    pub fn update(&self, mutate: impl FnOnce(&mut T)) {
        let mut inner = self.inner.borrow_mut();
        let mut candidate = inner.value.clone();
        mutate(&mut candidate);
        if inner.value != candidate {
            inner.value = candidate.clone();
            for listener in &inner.listeners {
                listener(&candidate);
            }
        }
    }

    /// Registers a callback to be invoked when the value changes.
    pub fn subscribe<F: Fn(&T) + 'static>(&self, callback: F) {
        self.inner.borrow_mut().listeners.push(Box::new(callback));
    }
}