1use serde::{Deserialize, Serialize};
4use serde_json::{Value as Json, json};
5
6use crate::ids::OwnerId;
7
8#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
10#[serde(rename_all = "lowercase")]
11pub enum Value {
12 Float(f64),
13 Int(i64),
14 Bool(bool),
15 Choice(String),
17 Floats(Vec<f64>),
19 Ints(Vec<i64>),
21 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 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 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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
119#[serde(rename_all = "lowercase")]
120pub enum PathKind {
121 Dir,
122 File,
123}
124
125#[derive(Clone, Debug, PartialEq, Serialize)]
132#[non_exhaustive]
133pub struct PathHint {
134 pub kind: PathKind,
135 #[serde(skip_serializing_if = "Vec::is_empty")]
137 pub extensions: Vec<String>,
138 #[serde(skip_serializing_if = "Option::is_none")]
141 pub title: Option<String>,
142 #[serde(skip_serializing_if = "Option::is_none")]
145 pub purpose: Option<String>,
146 #[serde(skip_serializing_if = "Option::is_none")]
149 pub filter_name: Option<String>,
150}
151
152impl PathHint {
153 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 pub fn title(mut self, title: &str) -> Self {
166 self.title = Some(title.into());
167 self
168 }
169
170 pub fn purpose(mut self, key: &str) -> Self {
172 self.purpose = Some(key.into());
173 self
174 }
175
176 pub fn filter_name(mut self, name: &str) -> Self {
178 self.filter_name = Some(name.into());
179 self
180 }
181
182 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#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
195#[serde(rename_all = "lowercase")]
196pub enum Writers {
197 #[default]
199 Owner,
200 Also(Vec<OwnerId>),
202 Any,
204}
205
206impl Writers {
207 pub fn is_owner(&self) -> bool {
208 *self == Writers::Owner
209 }
210
211 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#[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 #[serde(skip_serializing_if = "Option::is_none")]
234 pub hard: Option<(f64, f64)>,
235 #[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 pub display_scale: f64,
244 pub precision: u32,
246 #[serde(skip_serializing_if = "Vec::is_empty")]
247 pub choices: Vec<String>,
248 #[serde(skip_serializing_if = "Option::is_none")]
250 pub count: Option<u32>,
251 #[serde(skip_serializing_if = "Option::is_none")]
253 pub capacity: Option<u32>,
254 #[serde(skip_serializing_if = "Option::is_none")]
256 pub path: Option<PathHint>,
257 #[serde(skip_serializing_if = "Writers::is_owner")]
259 pub writers: Writers,
260 #[serde(skip_serializing_if = "std::ops::Not::not")]
263 pub sensitive: bool,
264 #[serde(skip_serializing_if = "Vec::is_empty")]
270 pub scopes: Vec<crate::admin::ValueScope>,
271 #[serde(skip_serializing_if = "std::ops::Not::not")]
275 pub note: bool,
276}
277
278fn 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 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 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 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 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 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 pub fn dialog_title(mut self, title: &str) -> Self {
390 self.path = self.path.map(|p| p.title(title));
391 self
392 }
393
394 pub fn dialog_purpose(mut self, key: &str) -> Self {
398 self.path = self.path.map(|p| p.purpose(key));
399 self
400 }
401
402 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 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 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 pub fn display(mut self, scale: f64, precision: u32) -> Self {
443 self.display_scale = scale;
444 self.precision = precision;
445 self
446 }
447
448 pub fn capacity(mut self, bytes: u32) -> Self {
450 self.capacity = Some(bytes);
451 self
452 }
453
454 pub fn writers(mut self, writers: &[OwnerId]) -> Self {
457 self.writers = Writers::Also(writers.to_vec());
458 self
459 }
460
461 pub fn any_writer(mut self) -> Self {
463 self.writers = Writers::Any;
464 self
465 }
466
467 pub fn scopes(mut self, scopes: &[crate::admin::ValueScope]) -> Self {
473 self.scopes = scopes.to_vec();
474 self
475 }
476
477 pub fn sensitive(mut self) -> Self {
479 self.sensitive = true;
480 self
481 }
482
483 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 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}