Skip to main content

native_gui_core/
bindings.rs

1//! Retained, change-only widget property writers.
2//!
3//! [`Bindings`] memoizes the last value written per widget and performs the
4//! `Ui::set_*` call only when the new value differs. A render pass that
5//! writes the model into the widgets therefore performs **zero** widget
6//! operations when nothing changed, which keeps idle frames free of native
7//! churn (scroll position, hover state, IME composition) without hand-rolled
8//! dirty flags per widget:
9//!
10//! ```no_run
11//! use native_gui_mock::MockBackend;
12//! use native_gui_core::{Bindings, Ui, WidgetKind};
13//!
14//! # fn main() -> native_gui_core::GuiResult<()> {
15//! let mut ui = Ui::new(MockBackend::default());
16//! let status = ui.create(WidgetKind::Label, Some("0"))?;
17//! let mut bindings = Bindings::new();
18//!
19//! // First sync writes; a second sync with the same value writes nothing.
20//! bindings.text(&mut ui, status, "1")?;
21//! bindings.text(&mut ui, status, "1")?;
22//! assert_eq!(bindings.writes(), 1);
23//! assert_eq!(bindings.skipped(), 1);
24//! # Ok(())
25//! # }
26//! ```
27//!
28//! The flow is one-way (model → widget): the app owns the state, calls the
29//! writers on every render pass, and the bindings suppress unchanged values.
30//! Two-way text binding (echoing `TextChanged` back into the model) is
31//! deliberately not provided yet: the IME echo rules
32//! must settle first, because writing text into a focused input can reset an
33//! in-progress composition.
34//!
35//! [`Bindings::clear`] forgets the cached values, forcing the next sync to
36//! rewrite everything — use it after mutating widgets outside the bindings
37//! (for example after loading a new document).
38
39use std::collections::HashMap;
40
41use crate::error::GuiResult;
42use crate::ui::{Backend, Ui};
43use crate::widgets::WidgetId;
44
45/// Last-written widget property values; `Ui::set_*` runs only when a value
46/// actually changed.
47///
48/// `writes` and `skipped` count the observed sync calls, so tests can assert
49/// that an idle pass performs no widget writes.
50#[derive(Debug, Default)]
51pub struct Bindings {
52    text: HashMap<WidgetId, String>,
53    checked: HashMap<WidgetId, bool>,
54    value: HashMap<WidgetId, i32>,
55    enabled: HashMap<WidgetId, bool>,
56    rows: HashMap<WidgetId, Vec<String>>,
57    writes: usize,
58    skipped: usize,
59}
60
61impl Bindings {
62    /// Creates an empty binding set (nothing written yet).
63    pub fn new() -> Self {
64        Self::default()
65    }
66
67    /// Widget writes performed since construction (or since the last
68    /// [`Bindings::clear`], which resets the counters too).
69    pub fn writes(&self) -> usize {
70        self.writes
71    }
72
73    /// Sync calls whose value was already current and were skipped.
74    pub fn skipped(&self) -> usize {
75        self.skipped
76    }
77
78    /// Forgets every cached value so the next sync writes all widgets again.
79    ///
80    /// Use this after changing widgets outside the bindings; ordinary model
81    /// updates do not need it because changed values are detected per call.
82    pub fn clear(&mut self) {
83        self.text.clear();
84        self.checked.clear();
85        self.value.clear();
86        self.enabled.clear();
87        self.rows.clear();
88        self.writes = 0;
89        self.skipped = 0;
90    }
91
92    /// Syncs a widget's text (label/button/input/…).
93    ///
94    /// Returns `true` when the value was written, `false` when it was
95    /// already current.
96    pub fn text<B: Backend>(
97        &mut self,
98        ui: &mut Ui<B>,
99        id: WidgetId,
100        value: &str,
101    ) -> GuiResult<bool> {
102        if self.text.get(&id).map(String::as_str) == Some(value) {
103            self.skipped += 1;
104            return Ok(false);
105        }
106        ui.set_text(id, value)?;
107        self.text.insert(id, value.to_owned());
108        self.writes += 1;
109        Ok(true)
110    }
111
112    /// Syncs a check-capable widget's checked state.
113    pub fn checked<B: Backend>(
114        &mut self,
115        ui: &mut Ui<B>,
116        id: WidgetId,
117        value: bool,
118    ) -> GuiResult<bool> {
119        if self.checked.get(&id) == Some(&value) {
120            self.skipped += 1;
121            return Ok(false);
122        }
123        ui.set_checked(id, value)?;
124        self.checked.insert(id, value);
125        self.writes += 1;
126        Ok(true)
127    }
128
129    /// Syncs a value-capable widget's numeric value (slider/spin/progress).
130    pub fn value<B: Backend>(
131        &mut self,
132        ui: &mut Ui<B>,
133        id: WidgetId,
134        value: i32,
135    ) -> GuiResult<bool> {
136        if self.value.get(&id) == Some(&value) {
137            self.skipped += 1;
138            return Ok(false);
139        }
140        ui.set_value(id, value)?;
141        self.value.insert(id, value);
142        self.writes += 1;
143        Ok(true)
144    }
145
146    /// Syncs a widget's enabled state.
147    pub fn enabled<B: Backend>(
148        &mut self,
149        ui: &mut Ui<B>,
150        id: WidgetId,
151        value: bool,
152    ) -> GuiResult<bool> {
153        if self.enabled.get(&id) == Some(&value) {
154            self.skipped += 1;
155            return Ok(false);
156        }
157        ui.set_enabled(id, value)?;
158        self.enabled.insert(id, value);
159        self.writes += 1;
160        Ok(true)
161    }
162
163    /// Memoized `Ui::set_data_list_items`: a list reloads only when its rows
164    /// actually changed.
165    pub fn rows<B: Backend>(
166        &mut self,
167        ui: &mut Ui<B>,
168        id: WidgetId,
169        value: &[String],
170    ) -> GuiResult<bool> {
171        if self.rows.get(&id).map(Vec::as_slice) == Some(value) {
172            self.skipped += 1;
173            return Ok(false);
174        }
175        ui.set_data_list_items(id, value)?;
176        self.rows.insert(id, value.to_vec());
177        self.writes += 1;
178        Ok(true)
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use crate::test_support::MockBackend;
186    use crate::widgets::WidgetKind;
187
188    fn fixture() -> (Ui<MockBackend>, Bindings) {
189        (Ui::new(MockBackend::default()), Bindings::new())
190    }
191
192    #[test]
193    #[cfg(all(
194        feature = "widgets-range",
195        feature = "widgets-choice",
196        feature = "widgets-data"
197    ))]
198    fn writers_write_once_then_skip_unchanged_values() {
199        let (mut ui, mut bindings) = fixture();
200        let window = ui.create(WidgetKind::Window, Some("W")).unwrap();
201        let label = ui.create(WidgetKind::Label, Some("")).unwrap();
202        let checkbox = ui.create(WidgetKind::Checkbox, Some("C")).unwrap();
203        let slider = ui.create(WidgetKind::Slider, None).unwrap();
204        let button = ui.create(WidgetKind::Button, Some("B")).unwrap();
205        let list = ui.create(WidgetKind::DataList, None).unwrap();
206        let _ = window;
207
208        assert!(bindings.text(&mut ui, label, "hello").unwrap());
209        assert!(bindings.checked(&mut ui, checkbox, true).unwrap());
210        assert!(bindings.value(&mut ui, slider, 7).unwrap());
211        assert!(bindings.enabled(&mut ui, button, false).unwrap());
212        assert!(bindings
213            .rows(&mut ui, list, &["a".to_owned(), "b".to_owned()])
214            .unwrap());
215        assert_eq!(bindings.writes(), 5);
216
217        // Idle pass: every writer skips.
218        assert!(!bindings.text(&mut ui, label, "hello").unwrap());
219        assert!(!bindings.checked(&mut ui, checkbox, true).unwrap());
220        assert!(!bindings.value(&mut ui, slider, 7).unwrap());
221        assert!(!bindings.enabled(&mut ui, button, false).unwrap());
222        assert!(!bindings
223            .rows(&mut ui, list, &["a".to_owned(), "b".to_owned()])
224            .unwrap());
225        assert_eq!(bindings.writes(), 5, "idle pass performs zero writes");
226        assert_eq!(bindings.skipped(), 5);
227
228        // The widgets really hold the values (Mock mirrors the spec).
229        assert_eq!(
230            ui.widget(label).and_then(|spec| spec.text.as_deref()),
231            Some("hello")
232        );
233        assert_eq!(
234            ui.widget(checkbox).and_then(|spec| spec.checked),
235            Some(true)
236        );
237        assert_eq!(ui.widget(slider).and_then(|spec| spec.value), Some(7));
238        assert_eq!(ui.widget(button).and_then(|spec| spec.enabled), Some(false));
239        assert_eq!(
240            ui.widget(list).map(|spec| spec.data_list_items.clone()),
241            Some(vec!["a".to_owned(), "b".to_owned()])
242        );
243    }
244
245    #[test]
246    fn changed_values_are_rewritten() {
247        let (mut ui, mut bindings) = fixture();
248        let label = ui.create(WidgetKind::Label, Some("")).unwrap();
249
250        bindings.text(&mut ui, label, "one").unwrap();
251        assert!(bindings.text(&mut ui, label, "two").unwrap());
252        assert_eq!(bindings.writes(), 2);
253        assert_eq!(bindings.skipped(), 0);
254        assert_eq!(
255            ui.widget(label).and_then(|spec| spec.text.as_deref()),
256            Some("two")
257        );
258    }
259
260    #[test]
261    #[cfg(feature = "widgets-data")]
262    fn rows_compare_by_content_not_identity() {
263        let (mut ui, mut bindings) = fixture();
264        let list = ui.create(WidgetKind::DataList, None).unwrap();
265
266        let first = vec!["x".to_owned()];
267        assert!(bindings.rows(&mut ui, list, &first).unwrap());
268        // A freshly built vector with equal content is still a skip.
269        assert!(!bindings.rows(&mut ui, list, &["x".to_owned()]).unwrap());
270        assert!(bindings
271            .rows(&mut ui, list, &["x".to_owned(), "y".to_owned()])
272            .unwrap());
273        assert_eq!(bindings.writes(), 2);
274    }
275
276    #[test]
277    #[cfg(feature = "widgets-data")]
278    fn clear_forces_a_full_rewrite_and_resets_counters() {
279        let (mut ui, mut bindings) = fixture();
280        let label = ui.create(WidgetKind::Label, Some("")).unwrap();
281        let list = ui.create(WidgetKind::DataList, None).unwrap();
282
283        bindings.text(&mut ui, label, "same").unwrap();
284        bindings.rows(&mut ui, list, &["r".to_owned()]).unwrap();
285        bindings.clear();
286        assert_eq!(bindings.writes(), 0);
287        assert_eq!(bindings.skipped(), 0);
288
289        assert!(bindings.text(&mut ui, label, "same").unwrap());
290        assert!(bindings.rows(&mut ui, list, &["r".to_owned()]).unwrap());
291        assert_eq!(bindings.writes(), 2, "clear rewrites even equal values");
292    }
293}