cella_gui 1.0.0

A GUI for the Cella cellular automata library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! The model parameter panel: one control per parameter an attached
//! [`cella_lib::ExternalModel`] says it has.
//!
//! The panel is *generic*. It asks the model what its parameters are
//! (`params()`), what they are worth right now (`get_param`), and writes edits
//! back through `Grid2D::set_model_param`. That is the one rule this file
//! lives by: **no model-specific code**. Nothing here may name a particular
//! model, its parameter keys, or its groups — a new model gets a panel for
//! free, and an old one cannot break this file by changing its parameters.

use std::collections::HashMap;

use crate::gui::actions::Action;
use crate::gui::app::CellaApp;
use crate::gui::theme::section;
use cella_lib::{GridState, ParamDesc, ParamKind, ParamValue};

impl CellaApp {
    /// Draw one control per parameter the attached model declares.
    ///
    /// Renders nothing at all when no model is attached, so a Life or Rule 30
    /// scenario does not grow an empty section. Everything worth testing lives
    /// in [`group_params`], [`commit_on`], [`gesture_ended`] and
    /// [`CellaApp::apply_model_param`]; what is left here is the egui plumbing.
    pub(in crate::gui) fn ui_model_params(&mut self, ui: &mut egui::Ui) {
        let Some(model) = self.scenario.d2.as_ref().and_then(|g| g.model.as_ref()) else {
            return;
        };
        // Read everything the panel needs while the model is borrowed, so the
        // widgets below are free to borrow `self` mutably and commit an edit.
        let title = model.typetag_name().to_string();
        let descs = model.params();
        let values: HashMap<String, ParamValue> = descs
            .iter()
            .filter_map(|d| Some((d.key.clone(), model.get_param(&d.key)?)))
            .collect();
        let groups = group_params(descs);

        // One slot is enough: a person finishes at most one control per frame,
        // and the edit has to leave the closures before `self` can be touched.
        let mut commit: Option<(String, ParamValue)> = None;
        section(ui, &title, |ui| {
            for (group, descs) in &groups {
                if let Some(name) = group {
                    ui.separator();
                    ui.strong(name);
                }
                for desc in descs {
                    // A key `params` lists but `get_param` will not answer
                    // has no current value to draw, so it is skipped.
                    let Some(value) = values.get(&desc.key) else {
                        continue;
                    };
                    if let Some(edited) = param_control(ui, desc, value) {
                        commit = Some((desc.key.clone(), edited));
                    }
                }
            }
        });
        if let Some((key, value)) = commit {
            self.push(Action::ApplyModelParam { key, value });
        }
    }

    /// Write one edited parameter to the live grid, and — only when the grid
    /// accepts it — to the snapshot Reset restores as well.
    ///
    /// A refusal goes to the status bar and nothing else: `set_model_param`
    /// has already rolled the model back, and the control redraws from
    /// `get_param` on the next frame, so there is no local state to undo.
    ///
    /// Does nothing when no 2D grid is loaded. The panel only calls this once
    /// it has drawn a control, so that cannot happen from there; the guard is
    /// here so a future caller cannot turn a missing grid into a panic.
    pub(in crate::gui) fn apply_model_param(&mut self, key: &str, value: ParamValue) {
        let Some(grid) = self.scenario.d2.as_mut() else {
            return;
        };
        match grid.set_model_param(key, value.clone()) {
            Ok(()) => self.mirror_param_into_initial_state(key, value),
            Err(e) => self.set_status(format!("Model parameter error: {e}")),
        }
    }

    /// Apply an accepted parameter to the model inside the Reset snapshot.
    ///
    /// `Scenario::initial_state` holds a *clone* of the model taken when the
    /// scenario was loaded, with the parameters it had then. Left alone, Reset
    /// would put those old parameters back and a slider someone had just moved
    /// would snap — the wrong surprise while tuning a model. Copying the
    /// accepted value across means Reset rewinds the cells, not the sliders.
    ///
    /// A plain `set_param` is the right call here: this model is not attached
    /// to a grid, and `Grid2D::from_state` re-runs `attach` when Reset restores
    /// it. The value was already accepted by the live model, so a failure here
    /// would mean the two copies disagree about their own parameters — nothing
    /// anyone could act on, so it is ignored.
    pub(in crate::gui) fn mirror_param_into_initial_state(&mut self, key: &str, value: ParamValue) {
        if let Some(GridState::D2 {
            model: Some(snapshot),
            ..
        }) = self.scenario.initial_state.as_mut()
        {
            let _ = snapshot.set_param(key, value);
        }
    }
}

/// Split parameters into the sections the panel draws, in a stable order.
///
/// The ungrouped bucket comes first however late the model lists it, then each
/// named group in the order it first appears; inside a bucket the model's own
/// order is kept. Order has to be stable because controls that reshuffle
/// between frames are impossible to use.
fn group_params(descs: Vec<ParamDesc>) -> Vec<(Option<String>, Vec<ParamDesc>)> {
    let mut out: Vec<(Option<String>, Vec<ParamDesc>)> = Vec::new();
    for desc in descs {
        match out.iter_mut().find(|(group, _)| *group == desc.group) {
            Some((_, bucket)) => bucket.push(desc),
            None => out.push((desc.group.clone(), vec![desc])),
        }
    }
    if let Some(i) = out.iter().position(|(group, _)| group.is_none()) {
        let ungrouped = out.remove(i);
        out.insert(0, ungrouped);
    }
    out
}

/// Whether this frame is where an edit to `desc` should be written.
///
/// A cheap parameter commits the moment its widget changes, so dragging its
/// slider looks live. An expensive one — `reattach`, meaning the model rebuilds
/// derived state on every write — waits for the end of the gesture (see
/// [`gesture_ended`]), so the rebuild happens once per drag instead of once per
/// frame. A read-only parameter never commits at all.
fn commit_on(desc: &ParamDesc, changed: bool, ended: bool) -> bool {
    if desc.read_only {
        return false;
    }
    if desc.reattach { ended } else { changed }
}

/// Whether the person is *done* with this control for now.
///
/// Only expensive (`reattach`) parameters ask, because they pay a model
/// rebuild per commit and so should not commit mid-drag. Three things end a
/// gesture: letting go of a drag, moving focus off the control, and — the case
/// that is easy to miss — any change that was not made by dragging at all. A
/// focused slider accepts arrow keys, and a keystroke is a complete gesture the
/// moment it lands; waiting for a drag that never starts would throw the edit
/// away and redraw the old value on the next frame.
fn gesture_ended(changed: bool, dragged: bool, drag_stopped: bool, lost_focus: bool) -> bool {
    drag_stopped || lost_focus || (changed && !dragged)
}

/// Whether this frame commits `desc`, given the widget that just drew it.
///
/// `edited` is the only thing that makes a commit possible: it says the
/// widget's value really differs from the one the model holds. Without that
/// guard a bare click, a Tab away, or a widget that quietly reformatted its own
/// value would write the model a value it already had — and, for a `reattach`
/// parameter, pay a full rebuild for it. Everything else is timing, and that is
/// [`commit_on`]'s decision.
fn commit_now(desc: &ParamDesc, resp: &egui::Response, edited: bool) -> bool {
    let ended = gesture_ended(
        // A combo box reports no change of its own, so `edited` stands in for
        // it: the selection landed in a variable, not in the response.
        resp.changed() || edited,
        resp.dragged(),
        resp.drag_stopped(),
        resp.lost_focus(),
    );
    edited && commit_on(desc, edited, ended)
}

/// Draw the control for one parameter, and return the value to write if this
/// frame is where the edit should be committed.
///
/// The `ParamKind` picks the widget; the current `ParamValue` supplies what it
/// starts at. A value whose shape does not match the kind the descriptor
/// promised is not drawable, so nothing is drawn for it.
fn param_control(ui: &mut egui::Ui, desc: &ParamDesc, value: &ParamValue) -> Option<ParamValue> {
    if desc.read_only {
        with_help(
            ui.label(format!("{}: {}", desc.label, value_text(value))),
            desc,
        );
        return None;
    }
    match (&desc.kind, value) {
        (ParamKind::Float { min, max, step }, ParamValue::Float(current)) => {
            let mut v = *current;
            let mut slider = egui::Slider::new(&mut v, *min..=*max)
                .step_by(*step)
                // Clamp what someone *types*, never what the model already
                // holds: the default rounds the existing value onto the step
                // grid on every draw and reports that as an edit, which would
                // rewrite a value the model is perfectly happy with the first
                // time the panel is drawn.
                .clamping(egui::SliderClamping::Edits)
                .text(&desc.label);
            if let Some(unit) = &desc.unit {
                slider = slider.suffix(unit);
            }
            let resp = with_help(ui.add(slider), desc);
            commit_now(desc, &resp, v != *current).then_some(ParamValue::Float(v))
        }
        (ParamKind::Int { min, max }, ParamValue::Int(current)) => {
            let mut v = *current;
            let resp = ui
                .horizontal(|ui| {
                    let resp = ui.add(
                        egui::DragValue::new(&mut v)
                            .range(*min..=*max)
                            // Same reason as the slider above: an existing
                            // value outside the range is shown as it is, not
                            // silently pulled to the nearest end stop.
                            .clamp_existing_to_range(false),
                    );
                    ui.label(&desc.label);
                    resp
                })
                .inner;
            let resp = with_help(resp, desc);
            commit_now(desc, &resp, v != *current).then_some(ParamValue::Int(v))
        }
        (ParamKind::Bool, ParamValue::Bool(current)) => {
            let mut v = *current;
            let resp = with_help(ui.checkbox(&mut v, &desc.label), desc);
            commit_now(desc, &resp, v != *current).then_some(ParamValue::Bool(v))
        }
        (ParamKind::Choice { options }, ParamValue::Choice(current)) => {
            let mut sel = current.clone();
            // The response carries the tooltip and the focus signals; what it
            // does not carry is the selection, which lands in `sel` below.
            let resp = with_help(
                egui::ComboBox::from_label(&desc.label)
                    .selected_text(sel.clone())
                    .show_ui(ui, |ui| {
                        for opt in options {
                            ui.selectable_value(&mut sel, opt.clone(), opt);
                        }
                    })
                    .response,
                desc,
            );
            // A dropdown has no `changed` of its own: the selection landed in
            // `sel`, so comparing it with the current value is the change.
            commit_now(desc, &resp, sel != *current).then_some(ParamValue::Choice(sel))
        }
        (ParamKind::Bits { len }, ParamValue::Bits(current)) => {
            // The typed text lives in egui's memory while the field has focus,
            // so a half-typed code is not overwritten by the model's value on
            // the next redraw. It commits when focus leaves the field (Enter
            // drops focus too), and only if it parses and fits in `len` bits.
            let id = ui.make_persistent_id(("bits", &desc.key));
            let mut text = ui
                .data_mut(|d| d.get_temp::<String>(id))
                .unwrap_or_else(|| format!("{current:#x}"));
            let resp = ui
                .horizontal(|ui| {
                    let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(160.0));
                    ui.label(format!("{} ({len} bits; hex, binary or decimal)", desc.label));
                    r
                })
                .inner;
            let resp = with_help(resp, desc);
            let parsed = parse_bits(&text).filter(|v| bits_fit(*v, *len));
            if resp.has_focus() {
                ui.data_mut(|d| d.insert_temp(id, text));
            } else {
                ui.data_mut(|d| d.remove::<String>(id));
            }
            match parsed {
                Some(v) if v != *current && resp.lost_focus() && !desc.read_only => {
                    Some(ParamValue::Bits(v))
                }
                _ => None,
            }
        }
        _ => None,
    }
}

/// Read a bit-string typed by a person: `0x1e`, `0b11110` or `30` all mean
/// the same thing. Surrounding whitespace and `_` separators are ignored.
/// Returns `None` for anything that is not a number.
fn parse_bits(text: &str) -> Option<u128> {
    let t: String = text.trim().chars().filter(|c| *c != '_').collect();
    let lower = t.to_ascii_lowercase();
    if let Some(hex) = lower.strip_prefix("0x") {
        u128::from_str_radix(hex, 16).ok()
    } else if let Some(bin) = lower.strip_prefix("0b") {
        u128::from_str_radix(bin, 2).ok()
    } else {
        lower.parse::<u128>().ok()
    }
}

/// Whether `v` uses no bit at or above position `len`.
fn bits_fit(v: u128, len: u32) -> bool {
    len >= 128 || (v >> len) == 0
}

/// Attach the descriptor's tooltip to a widget, if it has one.
fn with_help(resp: egui::Response, desc: &ParamDesc) -> egui::Response {
    match &desc.help {
        Some(help) => resp.on_hover_text(help),
        None => resp,
    }
}

/// A parameter value written out for a read-only row, without the `Debug`
/// wrapper a reader would have to look past.
pub(in crate::gui) fn value_text(value: &ParamValue) -> String {
    match value {
        ParamValue::Float(v) => v.to_string(),
        ParamValue::Int(v) => v.to_string(),
        ParamValue::Bool(v) => v.to_string(),
        ParamValue::Choice(v) => v.clone(),
        ParamValue::Bits(v) => format!("{v:#x}"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// One parameter descriptor, with only the fields a grouping or commit
    /// decision looks at spelled out.
    fn desc(key: &str, group: Option<&str>, reattach: bool, read_only: bool) -> ParamDesc {
        ParamDesc {
            key: key.to_string(),
            label: key.to_string(),
            group: group.map(str::to_string),
            help: None,
            unit: None,
            kind: ParamKind::Bool,
            reattach,
            read_only,
        }
    }

    /// The keys each bucket holds, which is all these tests care about.
    fn shape(groups: &[(Option<String>, Vec<ParamDesc>)]) -> Vec<(Option<String>, Vec<String>)> {
        groups
            .iter()
            .map(|(g, ds)| (g.clone(), ds.iter().map(|d| d.key.clone()).collect()))
            .collect()
    }

    #[test]
    fn group_params_returns_no_buckets_for_no_parameters() {
        assert!(group_params(Vec::new()).is_empty());
    }

    #[test]
    fn group_params_puts_every_ungrouped_parameter_in_one_bucket_in_order() {
        let out = group_params(vec![
            desc("a", None, false, false),
            desc("b", None, false, false),
        ]);

        assert_eq!(
            shape(&out),
            vec![(None, vec!["a".to_string(), "b".to_string()])]
        );
    }

    #[test]
    fn group_params_lists_the_ungrouped_bucket_first_even_when_it_appears_last() {
        let out = group_params(vec![
            desc("a", Some("Wind"), false, false),
            desc("b", None, false, false),
        ]);

        assert_eq!(
            shape(&out),
            vec![
                (None, vec!["b".to_string()]),
                (Some("Wind".to_string()), vec!["a".to_string()]),
            ]
        );
    }

    #[test]
    fn group_params_keeps_interleaved_groups_in_first_appearance_order() {
        let out = group_params(vec![
            desc("a1", Some("A"), false, false),
            desc("b1", Some("B"), false, false),
            desc("a2", Some("A"), false, false),
            desc("b2", Some("B"), false, false),
        ]);

        assert_eq!(
            shape(&out),
            vec![
                (
                    Some("A".to_string()),
                    vec!["a1".to_string(), "a2".to_string()]
                ),
                (
                    Some("B".to_string()),
                    vec!["b1".to_string(), "b2".to_string()]
                ),
            ]
        );
    }

    #[test]
    fn a_cheap_parameter_commits_as_soon_as_the_widget_changes() {
        let cheap = desc("a", None, false, false);

        assert!(commit_on(&cheap, true, false), "changed alone is enough");
        assert!(commit_on(&cheap, true, true));
        assert!(!commit_on(&cheap, false, true), "no change, nothing to do");
        assert!(!commit_on(&cheap, false, false));
    }

    #[test]
    fn an_expensive_parameter_waits_until_the_gesture_ends() {
        let expensive = desc("a", None, true, false);

        assert!(
            !commit_on(&expensive, true, false),
            "mid-drag changes are skipped so the rebuild runs once"
        );
        assert!(commit_on(&expensive, true, true));
        assert!(commit_on(&expensive, false, true), "release always commits");
        assert!(!commit_on(&expensive, false, false));
    }

    /// The gesture-end rule, spelled out for every combination that matters.
    ///
    /// The case that used to be wrong is the first one: a focused slider takes
    /// arrow keys, which change its value with no pointer drag anywhere. An
    /// expensive parameter that waited for `drag_stopped` threw that keystroke
    /// away, redrew from the model next frame, and then committed the *old*
    /// value when focus moved on — a rebuild that changed nothing.
    #[test]
    fn any_change_outside_a_drag_ends_the_gesture_by_itself() {
        // changed, dragged, drag_stopped, lost_focus
        assert!(
            gesture_ended(true, false, false, false),
            "an arrow-key edit is a whole gesture on its own"
        );
        assert!(
            !gesture_ended(true, true, false, false),
            "a change under the pointer is mid-drag, so it waits"
        );
        assert!(
            gesture_ended(true, true, true, false),
            "the frame the drag ends on commits it"
        );
        assert!(
            gesture_ended(false, false, true, false),
            "releasing the slider ends the gesture"
        );
        assert!(
            gesture_ended(false, false, false, true),
            "so does clicking away from it"
        );
        assert!(
            !gesture_ended(false, false, false, false),
            "an untouched frame is not the end of anything"
        );
    }

    #[test]
    fn read_only_values_read_as_plain_text() {
        assert_eq!(value_text(&ParamValue::Float(7.5)), "7.5");
        assert_eq!(value_text(&ParamValue::Int(42)), "42");
        assert_eq!(value_text(&ParamValue::Bool(true)), "true");
        assert_eq!(value_text(&ParamValue::Choice("Moore".into())), "Moore");
        assert_eq!(value_text(&ParamValue::Bits(30)), "0x1e");
    }

    #[test]
    fn parse_bits_reads_hex_binary_and_decimal_and_rejects_junk() {
        assert_eq!(parse_bits("30"), Some(30));
        assert_eq!(parse_bits(" 0x1E "), Some(30));
        assert_eq!(parse_bits("0b1_1110"), Some(30));
        assert_eq!(parse_bits(&u128::MAX.to_string()), Some(u128::MAX));
        assert_eq!(parse_bits(""), None);
        assert_eq!(parse_bits("thirty"), None);
        assert_eq!(parse_bits("0x"), None);
        assert_eq!(parse_bits("-1"), None);
    }

    #[test]
    fn bits_fit_checks_the_table_width() {
        assert!(bits_fit(255, 8));
        assert!(!bits_fit(256, 8));
        assert!(bits_fit(u128::MAX, 128));
        assert!(bits_fit(0, 1));
        assert!(!bits_fit(2, 1));
    }

    /// Every kind of control the panel knows how to draw, plus a read-only row
    /// and a value whose shape contradicts its descriptor.
    ///
    /// `egui::__run_test_ui` builds a throwaway context, so the widget code
    /// really runs — no window, no GPU. Nobody touches anything during the
    /// pass, so every control must report that there is nothing to commit.
    #[test]
    fn an_untouched_control_of_any_kind_commits_nothing() {
        let float = ParamDesc {
            kind: ParamKind::Float {
                min: 0.0,
                max: 10.0,
                step: 0.5,
            },
            unit: Some("m/s".into()),
            help: Some("a tooltip".into()),
            ..desc("float", Some("Group"), false, false)
        };
        let int = ParamDesc {
            kind: ParamKind::Int { min: 0, max: 10 },
            ..desc("int", None, true, false)
        };
        let boolean = desc("bool", None, false, false);
        let choice = ParamDesc {
            kind: ParamKind::Choice {
                options: vec!["one".into(), "two".into()],
            },
            ..desc("choice", None, false, false)
        };
        let bits = ParamDesc {
            kind: ParamKind::Bits { len: 8 },
            ..desc("bits", None, false, false)
        };
        let locked = ParamDesc {
            kind: ParamKind::Int { min: 0, max: 10 },
            ..desc("locked", None, false, true)
        };
        // A descriptor that promises a number next to a value that is a name:
        // not drawable, so the panel draws nothing for it.
        let mismatched = (&float, ParamValue::Choice("nonsense".into()));

        let rows = [
            (&float, ParamValue::Float(1.0)),
            (&int, ParamValue::Int(3)),
            (&boolean, ParamValue::Bool(true)),
            (&choice, ParamValue::Choice("one".into())),
            (&bits, ParamValue::Bits(30)),
            (&locked, ParamValue::Int(7)),
            mismatched,
        ];
        let mut committed = Vec::new();
        egui::__run_test_ui(|ui| {
            committed = rows
                .iter()
                .map(|(desc, value)| param_control(ui, desc, value))
                .collect();
        });

        assert_eq!(committed, vec![None; rows.len()]);
    }

    /// A value that is not on its descriptor's step grid, or that sits outside
    /// the range the descriptor declares, must be *shown* — never quietly
    /// rewritten by the widget that displays it.
    ///
    /// egui's default clamping rounds an existing value onto the slider's step
    /// grid on every draw and reports the widget as changed, so merely opening
    /// the panel would commit `c2 = 0.131` as `0.13` — and mirror the rounded
    /// value into the snapshot Reset restores. Nobody touched anything here,
    /// so there is nothing to commit.
    #[test]
    fn a_value_off_the_step_grid_or_outside_the_range_is_shown_not_rewritten() {
        let off_grid = ParamDesc {
            kind: ParamKind::Float {
                min: 0.0,
                max: 1.0,
                step: 0.005,
            },
            ..desc("off_grid", None, false, false)
        };
        let out_of_range = ParamDesc {
            kind: ParamKind::Int { min: 1, max: 1000 },
            ..desc("out_of_range", None, false, false)
        };

        let mut committed = Vec::new();
        egui::__run_test_ui(|ui| {
            committed = vec![
                param_control(ui, &off_grid, &ParamValue::Float(0.131)),
                param_control(ui, &out_of_range, &ParamValue::Int(1500)),
            ];
        });

        assert_eq!(
            committed,
            vec![None, None],
            "an untouched control must not commit a value the widget invented"
        );
    }

    #[test]
    fn a_read_only_parameter_never_commits() {
        for reattach in [false, true] {
            let locked = desc("a", None, reattach, true);
            for changed in [false, true] {
                for drag_stopped in [false, true] {
                    assert!(
                        !commit_on(&locked, changed, drag_stopped),
                        "read-only parameters are never written"
                    );
                }
            }
        }
    }
}