native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
//! Retained, change-only widget property writers.
//!
//! [`Bindings`] memoizes the last value written per widget and performs the
//! `Ui::set_*` call only when the new value differs. A render pass that
//! writes the model into the widgets therefore performs **zero** widget
//! operations when nothing changed, which keeps idle frames free of native
//! churn (scroll position, hover state, IME composition) without hand-rolled
//! dirty flags per widget:
//!
//! ```no_run
//! use native_gui_mock::MockBackend;
//! use native_gui_core::{Bindings, Ui, WidgetKind};
//!
//! # fn main() -> native_gui_core::GuiResult<()> {
//! let mut ui = Ui::new(MockBackend::default());
//! let status = ui.create(WidgetKind::Label, Some("0"))?;
//! let mut bindings = Bindings::new();
//!
//! // First sync writes; a second sync with the same value writes nothing.
//! bindings.text(&mut ui, status, "1")?;
//! bindings.text(&mut ui, status, "1")?;
//! assert_eq!(bindings.writes(), 1);
//! assert_eq!(bindings.skipped(), 1);
//! # Ok(())
//! # }
//! ```
//!
//! The flow is one-way (model → widget): the app owns the state, calls the
//! writers on every render pass, and the bindings suppress unchanged values.
//! Two-way text binding (echoing `TextChanged` back into the model) is
//! deliberately not provided yet: the IME echo rules
//! must settle first, because writing text into a focused input can reset an
//! in-progress composition.
//!
//! [`Bindings::clear`] forgets the cached values, forcing the next sync to
//! rewrite everything — use it after mutating widgets outside the bindings
//! (for example after loading a new document).

use std::collections::HashMap;

use crate::error::GuiResult;
use crate::ui::{Backend, Ui};
use crate::widgets::WidgetId;

/// Last-written widget property values; `Ui::set_*` runs only when a value
/// actually changed.
///
/// `writes` and `skipped` count the observed sync calls, so tests can assert
/// that an idle pass performs no widget writes.
#[derive(Debug, Default)]
pub struct Bindings {
    text: HashMap<WidgetId, String>,
    checked: HashMap<WidgetId, bool>,
    value: HashMap<WidgetId, i32>,
    enabled: HashMap<WidgetId, bool>,
    rows: HashMap<WidgetId, Vec<String>>,
    writes: usize,
    skipped: usize,
}

impl Bindings {
    /// Creates an empty binding set (nothing written yet).
    pub fn new() -> Self {
        Self::default()
    }

    /// Widget writes performed since construction (or since the last
    /// [`Bindings::clear`], which resets the counters too).
    pub fn writes(&self) -> usize {
        self.writes
    }

    /// Sync calls whose value was already current and were skipped.
    pub fn skipped(&self) -> usize {
        self.skipped
    }

    /// Forgets every cached value so the next sync writes all widgets again.
    ///
    /// Use this after changing widgets outside the bindings; ordinary model
    /// updates do not need it because changed values are detected per call.
    pub fn clear(&mut self) {
        self.text.clear();
        self.checked.clear();
        self.value.clear();
        self.enabled.clear();
        self.rows.clear();
        self.writes = 0;
        self.skipped = 0;
    }

    /// Syncs a widget's text (label/button/input/…).
    ///
    /// Returns `true` when the value was written, `false` when it was
    /// already current.
    pub fn text<B: Backend>(
        &mut self,
        ui: &mut Ui<B>,
        id: WidgetId,
        value: &str,
    ) -> GuiResult<bool> {
        if self.text.get(&id).map(String::as_str) == Some(value) {
            self.skipped += 1;
            return Ok(false);
        }
        ui.set_text(id, value)?;
        self.text.insert(id, value.to_owned());
        self.writes += 1;
        Ok(true)
    }

    /// Syncs a check-capable widget's checked state.
    pub fn checked<B: Backend>(
        &mut self,
        ui: &mut Ui<B>,
        id: WidgetId,
        value: bool,
    ) -> GuiResult<bool> {
        if self.checked.get(&id) == Some(&value) {
            self.skipped += 1;
            return Ok(false);
        }
        ui.set_checked(id, value)?;
        self.checked.insert(id, value);
        self.writes += 1;
        Ok(true)
    }

    /// Syncs a value-capable widget's numeric value (slider/spin/progress).
    pub fn value<B: Backend>(
        &mut self,
        ui: &mut Ui<B>,
        id: WidgetId,
        value: i32,
    ) -> GuiResult<bool> {
        if self.value.get(&id) == Some(&value) {
            self.skipped += 1;
            return Ok(false);
        }
        ui.set_value(id, value)?;
        self.value.insert(id, value);
        self.writes += 1;
        Ok(true)
    }

    /// Syncs a widget's enabled state.
    pub fn enabled<B: Backend>(
        &mut self,
        ui: &mut Ui<B>,
        id: WidgetId,
        value: bool,
    ) -> GuiResult<bool> {
        if self.enabled.get(&id) == Some(&value) {
            self.skipped += 1;
            return Ok(false);
        }
        ui.set_enabled(id, value)?;
        self.enabled.insert(id, value);
        self.writes += 1;
        Ok(true)
    }

    /// Memoized `Ui::set_data_list_items`: a list reloads only when its rows
    /// actually changed.
    pub fn rows<B: Backend>(
        &mut self,
        ui: &mut Ui<B>,
        id: WidgetId,
        value: &[String],
    ) -> GuiResult<bool> {
        if self.rows.get(&id).map(Vec::as_slice) == Some(value) {
            self.skipped += 1;
            return Ok(false);
        }
        ui.set_data_list_items(id, value)?;
        self.rows.insert(id, value.to_vec());
        self.writes += 1;
        Ok(true)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::MockBackend;
    use crate::widgets::WidgetKind;

    fn fixture() -> (Ui<MockBackend>, Bindings) {
        (Ui::new(MockBackend::default()), Bindings::new())
    }

    #[test]
    #[cfg(all(
        feature = "widgets-range",
        feature = "widgets-choice",
        feature = "widgets-data"
    ))]
    fn writers_write_once_then_skip_unchanged_values() {
        let (mut ui, mut bindings) = fixture();
        let window = ui.create(WidgetKind::Window, Some("W")).unwrap();
        let label = ui.create(WidgetKind::Label, Some("")).unwrap();
        let checkbox = ui.create(WidgetKind::Checkbox, Some("C")).unwrap();
        let slider = ui.create(WidgetKind::Slider, None).unwrap();
        let button = ui.create(WidgetKind::Button, Some("B")).unwrap();
        let list = ui.create(WidgetKind::DataList, None).unwrap();
        let _ = window;

        assert!(bindings.text(&mut ui, label, "hello").unwrap());
        assert!(bindings.checked(&mut ui, checkbox, true).unwrap());
        assert!(bindings.value(&mut ui, slider, 7).unwrap());
        assert!(bindings.enabled(&mut ui, button, false).unwrap());
        assert!(bindings
            .rows(&mut ui, list, &["a".to_owned(), "b".to_owned()])
            .unwrap());
        assert_eq!(bindings.writes(), 5);

        // Idle pass: every writer skips.
        assert!(!bindings.text(&mut ui, label, "hello").unwrap());
        assert!(!bindings.checked(&mut ui, checkbox, true).unwrap());
        assert!(!bindings.value(&mut ui, slider, 7).unwrap());
        assert!(!bindings.enabled(&mut ui, button, false).unwrap());
        assert!(!bindings
            .rows(&mut ui, list, &["a".to_owned(), "b".to_owned()])
            .unwrap());
        assert_eq!(bindings.writes(), 5, "idle pass performs zero writes");
        assert_eq!(bindings.skipped(), 5);

        // The widgets really hold the values (Mock mirrors the spec).
        assert_eq!(
            ui.widget(label).and_then(|spec| spec.text.as_deref()),
            Some("hello")
        );
        assert_eq!(
            ui.widget(checkbox).and_then(|spec| spec.checked),
            Some(true)
        );
        assert_eq!(ui.widget(slider).and_then(|spec| spec.value), Some(7));
        assert_eq!(ui.widget(button).and_then(|spec| spec.enabled), Some(false));
        assert_eq!(
            ui.widget(list).map(|spec| spec.data_list_items.clone()),
            Some(vec!["a".to_owned(), "b".to_owned()])
        );
    }

    #[test]
    fn changed_values_are_rewritten() {
        let (mut ui, mut bindings) = fixture();
        let label = ui.create(WidgetKind::Label, Some("")).unwrap();

        bindings.text(&mut ui, label, "one").unwrap();
        assert!(bindings.text(&mut ui, label, "two").unwrap());
        assert_eq!(bindings.writes(), 2);
        assert_eq!(bindings.skipped(), 0);
        assert_eq!(
            ui.widget(label).and_then(|spec| spec.text.as_deref()),
            Some("two")
        );
    }

    #[test]
    #[cfg(feature = "widgets-data")]
    fn rows_compare_by_content_not_identity() {
        let (mut ui, mut bindings) = fixture();
        let list = ui.create(WidgetKind::DataList, None).unwrap();

        let first = vec!["x".to_owned()];
        assert!(bindings.rows(&mut ui, list, &first).unwrap());
        // A freshly built vector with equal content is still a skip.
        assert!(!bindings.rows(&mut ui, list, &["x".to_owned()]).unwrap());
        assert!(bindings
            .rows(&mut ui, list, &["x".to_owned(), "y".to_owned()])
            .unwrap());
        assert_eq!(bindings.writes(), 2);
    }

    #[test]
    #[cfg(feature = "widgets-data")]
    fn clear_forces_a_full_rewrite_and_resets_counters() {
        let (mut ui, mut bindings) = fixture();
        let label = ui.create(WidgetKind::Label, Some("")).unwrap();
        let list = ui.create(WidgetKind::DataList, None).unwrap();

        bindings.text(&mut ui, label, "same").unwrap();
        bindings.rows(&mut ui, list, &["r".to_owned()]).unwrap();
        bindings.clear();
        assert_eq!(bindings.writes(), 0);
        assert_eq!(bindings.skipped(), 0);

        assert!(bindings.text(&mut ui, label, "same").unwrap());
        assert!(bindings.rows(&mut ui, list, &["r".to_owned()]).unwrap());
        assert_eq!(bindings.writes(), 2, "clear rewrites even equal values");
    }
}