Skip to main content

egui_pop_model/values/
value.rs

1//! A value and what it is: [`Value`], [`Type`] and [`Descriptor`].
2
3use serde::{Deserialize, Serialize};
4use serde_json::{Value as Json, json};
5
6use crate::ids::OwnerId;
7
8/// A value the store holds.
9#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
10#[serde(rename_all = "lowercase")]
11pub enum Value {
12    Float(f64),
13    Int(i64),
14    Bool(bool),
15    /// One of a descriptor's choices.
16    Choice(String),
17    /// Numbers that belong together (a colour, a matrix).
18    Floats(Vec<f64>),
19    /// Whole numbers that belong together.
20    Ints(Vec<i64>),
21    /// Free text.
22    Text(String),
23}
24
25impl Value {
26    pub fn as_f64(&self) -> Option<f64> {
27        match self {
28            Value::Float(v) => Some(*v),
29            Value::Int(v) => Some(*v as f64),
30            _ => None,
31        }
32    }
33
34    pub fn as_i64(&self) -> Option<i64> {
35        match self {
36            Value::Int(v) => Some(*v),
37            _ => None,
38        }
39    }
40
41    pub fn as_bool(&self) -> Option<bool> {
42        match self {
43            Value::Bool(v) => Some(*v),
44            _ => None,
45        }
46    }
47
48    pub fn as_choice(&self) -> Option<&str> {
49        match self {
50            Value::Choice(v) => Some(v),
51            _ => None,
52        }
53    }
54
55    pub fn as_text(&self) -> Option<&str> {
56        match self {
57            Value::Text(v) | Value::Choice(v) => Some(v),
58            _ => None,
59        }
60    }
61
62    /// As plain JSON (a number, a bool, a string, an array).
63    pub fn to_json(&self) -> Json {
64        match self {
65            Value::Float(v) => json!(v),
66            Value::Int(v) => json!(v),
67            Value::Bool(v) => json!(v),
68            Value::Choice(v) | Value::Text(v) => json!(v),
69            Value::Floats(v) => json!(v),
70            Value::Ints(v) => json!(v),
71        }
72    }
73
74    /// Plain JSON as the type a path holds.
75    pub fn from_json(ty: Type, json: &Json) -> Result<Value, String> {
76        let wrong = || format!("{json} is not a {ty:?}");
77        Ok(match ty {
78            Type::Float => Value::Float(json.as_f64().ok_or_else(wrong)?),
79            Type::Int => match json.as_i64() {
80                Some(v) => Value::Int(v),
81                None => Value::Float(json.as_f64().ok_or_else(wrong)?),
82            },
83            Type::Bool => Value::Bool(json.as_bool().ok_or_else(wrong)?),
84            Type::Choice => Value::Choice(json.as_str().ok_or_else(wrong)?.into()),
85            Type::Text => Value::Text(json.as_str().ok_or_else(wrong)?.into()),
86            Type::Floats => Value::Floats(
87                json.as_array()
88                    .ok_or_else(wrong)?
89                    .iter()
90                    .map(|v| v.as_f64().ok_or_else(wrong))
91                    .collect::<Result<_, _>>()?,
92            ),
93            Type::Ints => Value::Ints(
94                json.as_array()
95                    .ok_or_else(wrong)?
96                    .iter()
97                    .map(|v| v.as_i64().ok_or_else(wrong))
98                    .collect::<Result<_, _>>()?,
99            ),
100        })
101    }
102}
103
104/// The type of a value.
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
106#[serde(rename_all = "lowercase")]
107pub enum Type {
108    Float,
109    Int,
110    Bool,
111    Choice,
112    Floats,
113    Ints,
114    Text,
115}
116
117/// What a path names: a directory or a file.
118#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
119#[serde(rename_all = "lowercase")]
120pub enum PathKind {
121    Dir,
122    File,
123}
124
125/// A text that names a path on disk: what it names and, for a file, the
126/// extensions accepted (none: any). A form shows it with a Browse button,
127/// whose chooser [`title`](Self::title), [`purpose`](Self::purpose) and
128/// [`filter_name`](Self::filter_name) the hint may give. Built with
129/// [`PathHint::new`] or [`Descriptor::path`]: a field added later breaks
130/// nobody.
131#[derive(Clone, Debug, PartialEq, Serialize)]
132#[non_exhaustive]
133pub struct PathHint {
134    pub kind: PathKind,
135    /// Without the dot, lowercase (`json`, `txt`).
136    #[serde(skip_serializing_if = "Vec::is_empty")]
137    pub extensions: Vec<String>,
138    /// The chooser's title, a task ("Choose the export folder"); none: the
139    /// field's label.
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub title: Option<String>,
142    /// The key the chooser's last folder is remembered under; none: the
143    /// form's command and the field's key.
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub purpose: Option<String>,
146    /// What the chooser calls the extensions' filter ("Enrolment files");
147    /// none: the extensions joined.
148    #[serde(skip_serializing_if = "Option::is_none")]
149    pub filter_name: Option<String>,
150}
151
152impl PathHint {
153    /// A path of `kind`; for a file, the extensions accepted (none: any).
154    pub fn new(kind: PathKind, extensions: &[&str]) -> Self {
155        Self {
156            kind,
157            extensions: extensions.iter().map(|e| e.to_lowercase()).collect(),
158            title: None,
159            purpose: None,
160            filter_name: None,
161        }
162    }
163
164    /// The chooser's title, a task rather than the field's label.
165    pub fn title(mut self, title: &str) -> Self {
166        self.title = Some(title.into());
167        self
168    }
169
170    /// The key the chooser's last folder is remembered under.
171    pub fn purpose(mut self, key: &str) -> Self {
172        self.purpose = Some(key.into());
173        self
174    }
175
176    /// What the chooser calls the extensions' filter.
177    pub fn filter_name(mut self, name: &str) -> Self {
178        self.filter_name = Some(name.into());
179        self
180    }
181
182    /// Whether a file's name has an accepted extension.
183    pub fn accepts(&self, path: &std::path::Path) -> bool {
184        self.extensions.is_empty()
185            || path
186                .extension()
187                .and_then(|e| e.to_str())
188                .is_some_and(|e| self.extensions.iter().any(|x| x.eq_ignore_ascii_case(e)))
189    }
190}
191
192/// Who may write a path, besides the framework acting for a person (see
193/// [`Store::set`](super::Store::set)).
194#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
195#[serde(rename_all = "lowercase")]
196pub enum Writers {
197    /// Its owner alone: one writer per value (the default).
198    #[default]
199    Owner,
200    /// Its owner and these.
201    Also(Vec<OwnerId>),
202    /// Anyone.
203    Any,
204}
205
206impl Writers {
207    pub fn is_owner(&self) -> bool {
208        *self == Writers::Owner
209    }
210
211    /// Whether `writer` may write a path `owner` declared.
212    pub fn allow(&self, owner: &OwnerId, writer: &OwnerId) -> bool {
213        writer == owner
214            || *writer == OwnerId::FRAMEWORK
215            || match self {
216                Writers::Owner => false,
217                Writers::Also(list) => list.contains(writer),
218                Writers::Any => true,
219            }
220    }
221}
222
223/// What a value is and how it is shown and moved.
224#[derive(Clone, Debug, PartialEq, Serialize)]
225#[non_exhaustive]
226pub struct Descriptor {
227    #[serde(rename = "type")]
228    pub ty: Type,
229    pub label: String,
230    pub description: String,
231    pub default: Value,
232    /// What the value can be, at most.
233    #[serde(skip_serializing_if = "Option::is_none")]
234    pub hard: Option<(f64, f64)>,
235    /// What a slider spans; past it up to `hard` only when forced.
236    #[serde(skip_serializing_if = "Option::is_none")]
237    pub soft: Option<(f64, f64)>,
238    pub step: f64,
239    pub coarse: f64,
240    #[serde(skip_serializing_if = "Option::is_none")]
241    pub unit: Option<String>,
242    /// Shown value = value × scale.
243    pub display_scale: f64,
244    /// Decimals shown.
245    pub precision: u32,
246    #[serde(skip_serializing_if = "Vec::is_empty")]
247    pub choices: Vec<String>,
248    /// How many values a list holds at most.
249    #[serde(skip_serializing_if = "Option::is_none")]
250    pub count: Option<u32>,
251    /// How many bytes a text holds at most.
252    #[serde(skip_serializing_if = "Option::is_none")]
253    pub capacity: Option<u32>,
254    /// A text that names a path on disk.
255    #[serde(skip_serializing_if = "Option::is_none")]
256    pub path: Option<PathHint>,
257    /// Who may write it besides its owner.
258    #[serde(skip_serializing_if = "Writers::is_owner")]
259    pub writers: Writers,
260    /// A secret (a token, a password): never written to a settings
261    /// export, never read from one.
262    #[serde(skip_serializing_if = "std::ops::Not::not")]
263    pub sensitive: bool,
264    /// The host's value scopes it may also be set for, above `app`
265    /// (opt-in, [`crate::admin::ValueScope`]); empty: app-wide only.
266    ///
267    /// <div class="warning">Experimental: may change in any release
268    /// (docs/stability.md).</div>
269    #[serde(skip_serializing_if = "Vec::is_empty")]
270    pub scopes: Vec<crate::admin::ValueScope>,
271    /// Not a value but a read-only line, its words the label
272    /// ([`Descriptor::note`]): a dialog's form shows it under the fields
273    /// before it and answers no value for it.
274    #[serde(skip_serializing_if = "std::ops::Not::not")]
275    pub note: bool,
276}
277
278/// Decimals enough to show one step.
279fn precision_of(step: f64) -> u32 {
280    if step >= 1.0 || step <= 0.0 {
281        0
282    } else {
283        (-step.log10()).ceil() as u32
284    }
285}
286
287impl Descriptor {
288    fn base(ty: Type, label: &str, default: Value) -> Self {
289        Self {
290            ty,
291            label: label.into(),
292            description: String::new(),
293            default,
294            hard: None,
295            soft: None,
296            step: 1.0,
297            coarse: 10.0,
298            unit: None,
299            display_scale: 1.0,
300            precision: 0,
301            choices: Vec::new(),
302            count: None,
303            capacity: None,
304            path: None,
305            writers: Writers::Owner,
306            sensitive: false,
307            scopes: Vec::new(),
308            note: false,
309        }
310    }
311
312    /// A read-only line of a form, what the command will also do ("Also
313    /// updates 2 templates"): the forms' counterpart of the admin forms'
314    /// `note` field kind.
315    pub fn note(text: &str) -> Self {
316        Self {
317            note: true,
318            ..Self::base(Type::Text, text, Value::Text(String::new()))
319        }
320    }
321
322    /// A float in `[min, max]`, its fine step a hundredth of the range.
323    pub fn float(label: &str, min: f64, max: f64, default: f64) -> Self {
324        let step = if max > min { (max - min) / 100.0 } else { 0.01 };
325        Self {
326            hard: Some((min, max)),
327            step,
328            coarse: step * 10.0,
329            precision: precision_of(step),
330            ..Self::base(Type::Float, label, Value::Float(default))
331        }
332    }
333
334    pub fn int(label: &str, min: i64, max: i64, default: i64) -> Self {
335        Self {
336            hard: Some((min as f64, max as f64)),
337            ..Self::base(Type::Int, label, Value::Int(default))
338        }
339    }
340
341    pub fn bool(label: &str, default: bool) -> Self {
342        Self::base(Type::Bool, label, Value::Bool(default))
343    }
344
345    pub fn choice(label: &str, choices: &[&str], default: &str) -> Self {
346        Self {
347            choices: choices.iter().map(|c| c.to_string()).collect(),
348            ..Self::base(Type::Choice, label, Value::Choice(default.into()))
349        }
350    }
351
352    pub fn text(label: &str, default: &str) -> Self {
353        Self::base(Type::Text, label, Value::Text(default.into()))
354    }
355
356    /// Floats in `[min, max]`, at most `count` of them.
357    pub fn floats(label: &str, count: u32, min: f64, max: f64, default: &[f64]) -> Self {
358        let step = if max > min { (max - min) / 100.0 } else { 0.01 };
359        Self {
360            hard: Some((min, max)),
361            count: Some(count),
362            step,
363            coarse: step * 10.0,
364            precision: precision_of(step),
365            ..Self::base(Type::Floats, label, Value::Floats(default.to_vec()))
366        }
367    }
368
369    /// Ints in `[min, max]`, at most `count` of them.
370    pub fn ints(label: &str, count: u32, min: i64, max: i64, default: &[i64]) -> Self {
371        Self {
372            hard: Some((min as f64, max as f64)),
373            count: Some(count),
374            ..Self::base(Type::Ints, label, Value::Ints(default.to_vec()))
375        }
376    }
377
378    /// A text naming a directory or a file, empty by default; for a file,
379    /// the extensions accepted (none: any).
380    pub fn path(label: &str, kind: PathKind, extensions: &[&str]) -> Self {
381        Self {
382            path: Some(PathHint::new(kind, extensions)),
383            ..Self::base(Type::Text, label, Value::Text(String::new()))
384        }
385    }
386
387    /// A path's chooser title, a task ("Open a workspace") rather than the
388    /// field's label; nothing for a value that names no path.
389    pub fn dialog_title(mut self, title: &str) -> Self {
390        self.path = self.path.map(|p| p.title(title));
391        self
392    }
393
394    /// The key a path's chooser remembers its last folder under (default:
395    /// the form's command and the field's key); nothing for a value that
396    /// names no path.
397    pub fn dialog_purpose(mut self, key: &str) -> Self {
398        self.path = self.path.map(|p| p.purpose(key));
399        self
400    }
401
402    /// What a path's chooser calls its extensions' filter ("Enrolment
403    /// files"); nothing for a value that names no path.
404    pub fn filter_name(mut self, name: &str) -> Self {
405        self.path = self.path.map(|p| p.filter_name(name));
406        self
407    }
408
409    pub fn description(mut self, text: &str) -> Self {
410        self.description = text.into();
411        self
412    }
413
414    /// The range a slider spans, within the hard range.
415    pub fn soft(mut self, lo: f64, hi: f64) -> Self {
416        self.soft = Some(match self.hard {
417            Some((min, max)) => (lo.max(min), hi.min(max)),
418            None => (lo, hi),
419        });
420        self
421    }
422
423    /// The fine step (the coarse one becomes ten of them).
424    pub fn step(mut self, step: f64) -> Self {
425        self.step = step;
426        self.coarse = step * 10.0;
427        self.precision = precision_of(step);
428        self
429    }
430
431    pub fn coarse(mut self, coarse: f64) -> Self {
432        self.coarse = coarse;
433        self
434    }
435
436    pub fn unit(mut self, unit: &str) -> Self {
437        self.unit = Some(unit.into());
438        self
439    }
440
441    /// Shown value = value × scale, with so many decimals.
442    pub fn display(mut self, scale: f64, precision: u32) -> Self {
443        self.display_scale = scale;
444        self.precision = precision;
445        self
446    }
447
448    /// At most so many bytes of text.
449    pub fn capacity(mut self, bytes: u32) -> Self {
450        self.capacity = Some(bytes);
451        self
452    }
453
454    /// Lets these write it too, besides its owner (one writer per value
455    /// otherwise).
456    pub fn writers(mut self, writers: &[OwnerId]) -> Self {
457        self.writers = Writers::Also(writers.to_vec());
458        self
459    }
460
461    /// Lets anyone write it.
462    pub fn any_writer(mut self) -> Self {
463        self.writers = Writers::Any;
464        self
465    }
466
467    /// Opts into host value scopes: the settings app offers "Set for"
468    /// with `app` and these (those the host has open).
469    ///
470    /// <div class="warning">Experimental: may change in any release
471    /// (docs/stability.md).</div>
472    pub fn scopes(mut self, scopes: &[crate::admin::ValueScope]) -> Self {
473        self.scopes = scopes.to_vec();
474        self
475    }
476
477    /// A secret: left out of settings exports and refused from them.
478    pub fn sensitive(mut self) -> Self {
479        self.sensitive = true;
480        self
481    }
482
483    /// Checks a value read from outside (an imported file) against what
484    /// the value can be: its type, its hard range (refused, never
485    /// clamped), its choices, its count and its capacity. The value as
486    /// the store holds it, or why not.
487    pub fn accept(&self, json: &Json) -> Result<Value, String> {
488        let v = Value::from_json(self.ty, json)?;
489        let (lo, hi) = self.hard.unwrap_or((f64::NEG_INFINITY, f64::INFINITY));
490        let number = |x: f64| -> Result<(), String> {
491            if !x.is_finite() {
492                Err(format!("{x} is not a number"))
493            } else if x < lo {
494                Err(format!("{x} is below {lo}"))
495            } else if x > hi {
496                Err(format!("{x} is above {hi}"))
497            } else {
498                Ok(())
499            }
500        };
501        let count = |n: usize| match self.count {
502            Some(max) if n > max as usize => Err(format!("{n} values, at most {max}")),
503            _ => Ok(()),
504        };
505        match &v {
506            Value::Float(x) if self.ty == Type::Int => {
507                return Err(format!("{x} is not a whole number"));
508            }
509            Value::Float(x) => number(*x)?,
510            Value::Int(x) => number(*x as f64)?,
511            Value::Floats(xs) => {
512                count(xs.len())?;
513                xs.iter().try_for_each(|x| number(*x))?;
514            }
515            Value::Ints(xs) => {
516                count(xs.len())?;
517                xs.iter().try_for_each(|x| number(*x as f64))?;
518            }
519            Value::Choice(c) if !self.choices.contains(c) => {
520                return Err(format!("`{c}` is not one of {}", self.choices.join(", ")));
521            }
522            Value::Text(t) => {
523                if let Some(n) = self.capacity.filter(|n| t.len() > *n as usize) {
524                    return Err(format!("{} bytes, at most {n}", t.len()));
525                }
526            }
527            Value::Bool(_) | Value::Choice(_) => {}
528        }
529        Ok(v)
530    }
531
532    /// The range a write is held to: the soft one unless forced.
533    pub(crate) fn range(&self, force: bool) -> Option<(f64, f64)> {
534        if force {
535            self.hard
536        } else {
537            self.soft.or(self.hard)
538        }
539    }
540}