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
//! Signals kept in the app's user defaults: settings that survive a relaunch.

use ferrokit_core::kept::{UiCell, UiLocal};

use objc2::rc::Retained;
use objc2_foundation::{NSString, NSUserDefaults};

use crate::signal::{Effect, Signal, untrack};

/// A value [`stored`] can keep in user defaults.
pub trait Stored: Clone + PartialEq + 'static {
    /// Reads the value under `key`, if there is one.
    fn read(defaults: &NSUserDefaults, key: &NSString) -> Option<Self>;
    /// Writes the value under `key`.
    fn write(&self, defaults: &NSUserDefaults, key: &NSString);
}

fn present(defaults: &NSUserDefaults, key: &NSString) -> bool {
    defaults.objectForKey(key).is_some()
}

impl Stored for bool {
    fn read(d: &NSUserDefaults, key: &NSString) -> Option<Self> {
        present(d, key).then(|| d.boolForKey(key))
    }
    fn write(&self, d: &NSUserDefaults, key: &NSString) {
        d.setBool_forKey(*self, key);
    }
}

impl Stored for f64 {
    fn read(d: &NSUserDefaults, key: &NSString) -> Option<Self> {
        present(d, key).then(|| d.doubleForKey(key))
    }
    fn write(&self, d: &NSUserDefaults, key: &NSString) {
        d.setDouble_forKey(*self, key);
    }
}

impl Stored for i64 {
    fn read(d: &NSUserDefaults, key: &NSString) -> Option<Self> {
        present(d, key).then(|| d.integerForKey(key) as i64)
    }
    fn write(&self, d: &NSUserDefaults, key: &NSString) {
        d.setInteger_forKey(*self as isize, key);
    }
}

impl Stored for String {
    fn read(d: &NSUserDefaults, key: &NSString) -> Option<Self> {
        d.stringForKey(key).map(|s| s.to_string())
    }
    fn write(&self, d: &NSUserDefaults, key: &NSString) {
        // SAFETY: an NSString is a property-list value.
        unsafe { d.setObject_forKey(Some(&NSString::from_str(self)), key) };
    }
}

thread_local! {
    /// The write-back effects of stored signals (they live as long as the app).
    static WRITERS: UiCell<Vec<Effect>> = const { UiCell::new(Vec::new()) };
    /// The stored signal of each key (a `Signal<T>`).
    static SIGNALS: UiCell<std::collections::HashMap<String, Box<dyn std::any::Any>>> = UiCell::new(std::collections::HashMap::new());
}

/// A signal holding the user-defaults value under `key` (or `default` when
/// there is none yet); every change is written back. Bind it to a control
/// in a Settings window and read it anywhere: it lives as long as the app,
/// and every `stored` with the same key (and type) gives the same signal.
pub fn stored<T: Stored>(key: &str, default: T) -> Signal<T> {
    // One signal per key, for the app's life whoever asks first (a window
    // being built, an action): a second `stored` with the same key is the
    // same signal, so both follow each other.
    if let Some(signal) = SIGNALS.with_borrow(|s| s.get(key).and_then(|any| any.downcast_ref::<Signal<T>>().copied())) {
        return signal;
    }
    let name = key.to_string();
    let defaults = NSUserDefaults::standardUserDefaults();
    let key: Retained<NSString> = NSString::from_str(key);
    let signal = crate::signal::unowned(|| {
        let signal = Signal::new(T::read(&defaults, &key).unwrap_or(default));
        let s = signal;
        let mut first = true;
        let writer = Effect::new(move || {
            let value = s.get();
            // Nothing to write for the initial value: an untouched setting keeps
            // following the default.
            if !std::mem::take(&mut first) {
                untrack(|| value.write(&defaults, &key));
            }
        });
        WRITERS.with_borrow_mut(|w| w.push(writer));
        signal
    });
    SIGNALS.with_borrow_mut(|s| s.insert(name, Box::new(signal)));
    signal
}

/// The user-defaults value under `key`, if there is one: for values kept
/// per document or per item (a database's open tabs, a diagram's layout),
/// where a [`stored`] signal for each, living as long as the app, would
/// pile up.
pub fn read_stored<T: Stored>(key: &str) -> Option<T> {
    T::read(&NSUserDefaults::standardUserDefaults(), &NSString::from_str(key))
}

/// Writes `value` under `key` in user defaults now (see [`read_stored`]).
pub fn write_stored<T: Stored>(key: &str, value: &T) {
    value.write(&NSUserDefaults::standardUserDefaults(), &NSString::from_str(key));
}

/// Removes the user-defaults value under `key`.
pub fn remove_stored(key: &str) {
    NSUserDefaults::standardUserDefaults().removeObjectForKey(&NSString::from_str(key));
}