1use alloc::string::String;
46use alloc::vec::Vec;
47use core::marker::PhantomData;
48
49use crate::ini::Ini;
50use crate::num::{f64_format, f64_parse, parse_i64};
51
52pub const KF_HIDDEN: u32 = 1;
54pub const KF_RESTART: u32 = 2;
56
57#[derive(Clone, Copy, Debug)]
59#[non_exhaustive]
60pub enum Kind {
61 Bool(bool),
62 Int { def: i64, min: i64, max: i64, step: i64 },
63 Num { def: f64, min: f64, max: f64, dec: u32 },
64 Text { def: &'static str, max: usize },
65 Choice { def: usize, items: &'static [(&'static str, &'static str)] },
66 Color(u32),
67}
68
69#[derive(Clone, Copy, Debug)]
71pub struct Desc {
72 pub name: &'static str,
73 pub label: &'static str,
74 pub help: &'static str,
75 pub flags: u32,
76 pub kind: Kind,
77}
78
79impl Desc {
80 pub fn split(&self) -> (&'static str, &'static str) {
82 split(self.name)
83 }
84
85 pub fn default_val(&self) -> Val {
87 match self.kind {
88 Kind::Bool(d) => Val::Bool(d),
89 Kind::Int { def, .. } => Val::Int(def),
90 Kind::Num { def, .. } => Val::Num(def),
91 Kind::Text { def, max } => Val::Text(canon(def, max)),
92 Kind::Choice { def, .. } => Val::Choice(def),
93 Kind::Color(d) => Val::Color(d & 0xFF_FFFF),
94 }
95 }
96
97 pub fn fit(&self, v: Val) -> Val {
99 match (self.kind, v) {
100 (Kind::Bool(_), Val::Bool(b)) => Val::Bool(b),
101 (Kind::Int { min, max, .. }, Val::Int(x)) => Val::Int(x.clamp(min, max.max(min))),
102 (Kind::Num { min, max, .. }, Val::Num(x)) if !x.is_nan() && !min.is_nan() && !max.is_nan() => Val::Num(x.clamp(min, max.max(min))),
103 (Kind::Text { max, .. }, Val::Text(s)) => Val::Text(canon(&s, max)),
104 (Kind::Choice { items, .. }, Val::Choice(i)) if i < items.len() => Val::Choice(i),
105 (Kind::Color(_), Val::Color(c)) => Val::Color(c & 0xFF_FFFF),
106 _ => self.default_val(),
107 }
108 }
109
110 pub fn format(&self, v: &Val) -> String {
112 match v {
113 Val::Bool(b) => String::from(if *b { "true" } else { "false" }),
114 Val::Int(x) => alloc::format!("{}", x),
115 Val::Num(x) => f64_format(*x),
116 Val::Text(s) => s.clone(),
117 Val::Choice(i) => match self.kind {
118 Kind::Choice { items, .. } => String::from(items.get(*i).map_or("", |it| it.0)),
119 _ => String::new(),
120 },
121 Val::Color(c) => alloc::format!("#{:06X}", c & 0xFF_FFFF),
122 }
123 }
124
125 pub fn parse(&self, s: &str) -> Option<Val> {
127 let t = s.trim();
128 let v = match self.kind {
129 Kind::Bool(_) => Val::Bool(parse_i64(t.as_bytes())? != 0),
130 Kind::Int { .. } => Val::Int(parse_i64(t.as_bytes())?),
131 Kind::Num { .. } => {
132 let (x, used) = f64_parse(t.as_bytes());
133 if used == 0 || used != t.len() || x.is_nan() {
134 return None;
135 }
136 Val::Num(x)
137 }
138 Kind::Text { .. } => Val::Text(String::from(s)),
139 Kind::Choice { items, .. } => Val::Choice(items.iter().position(|it| it.0.eq_ignore_ascii_case(t))?),
140 Kind::Color(_) => {
141 let h = t.strip_prefix('#').unwrap_or(t);
142 if h.len() != 6 || !h.bytes().all(|b| b.is_ascii_hexdigit()) {
143 return None;
144 }
145 Val::Color(u32::from_str_radix(h, 16).ok()?)
146 }
147 };
148 Some(self.fit(v))
149 }
150}
151
152#[derive(Clone, Debug, PartialEq)]
154#[non_exhaustive]
155pub enum Val {
156 Bool(bool),
157 Int(i64),
158 Num(f64),
159 Text(String),
160 Choice(usize),
161 Color(u32),
162}
163
164pub trait Value: Sized {
166 #[doc(hidden)]
167 fn from_val(v: &Val) -> Option<Self>;
168 #[doc(hidden)]
169 fn into_val(self) -> Val;
170}
171
172impl Value for bool {
173 fn from_val(v: &Val) -> Option<bool> {
174 if let Val::Bool(b) = v { Some(*b) } else { None }
175 }
176 fn into_val(self) -> Val {
177 Val::Bool(self)
178 }
179}
180
181impl Value for i64 {
182 fn from_val(v: &Val) -> Option<i64> {
183 if let Val::Int(x) = v { Some(*x) } else { None }
184 }
185 fn into_val(self) -> Val {
186 Val::Int(self)
187 }
188}
189
190impl Value for f64 {
191 fn from_val(v: &Val) -> Option<f64> {
192 if let Val::Num(x) = v { Some(*x) } else { None }
193 }
194 fn into_val(self) -> Val {
195 Val::Num(self)
196 }
197}
198
199impl Value for String {
200 fn from_val(v: &Val) -> Option<String> {
201 if let Val::Text(s) = v { Some(s.clone()) } else { None }
202 }
203 fn into_val(self) -> Val {
204 Val::Text(self)
205 }
206}
207
208impl Value for usize {
209 fn from_val(v: &Val) -> Option<usize> {
210 if let Val::Choice(i) = v { Some(*i) } else { None }
211 }
212 fn into_val(self) -> Val {
213 Val::Choice(self)
214 }
215}
216
217impl Value for u32 {
218 fn from_val(v: &Val) -> Option<u32> {
219 if let Val::Color(c) = v { Some(*c) } else { None }
220 }
221 fn into_val(self) -> Val {
222 Val::Color(self)
223 }
224}
225
226pub struct Key<T> {
228 pub d: Desc,
229 t: PhantomData<fn() -> T>,
230}
231
232impl<T> Clone for Key<T> {
233 fn clone(&self) -> Key<T> {
234 *self
235 }
236}
237impl<T> Copy for Key<T> {}
238
239const fn key<T>(name: &'static str, kind: Kind) -> Key<T> {
240 Key { d: Desc { name, label: name, help: "", flags: 0, kind }, t: PhantomData }
241}
242
243impl Key<bool> {
244 pub const fn bool(name: &'static str, def: bool) -> Key<bool> {
245 key(name, Kind::Bool(def))
246 }
247}
248
249impl Key<i64> {
250 pub const fn int(name: &'static str, def: i64, min: i64, max: i64) -> Key<i64> {
252 key(name, Kind::Int { def, min, max, step: 1 })
253 }
254
255 pub const fn step(self, step: i64) -> Key<i64> {
257 let mut k = self;
258 if let Kind::Int { def, min, max, .. } = k.d.kind {
259 k.d.kind = Kind::Int { def, min, max, step };
260 }
261 k
262 }
263}
264
265impl Key<f64> {
266 pub const fn num(name: &'static str, def: f64, min: f64, max: f64, dec: u32) -> Key<f64> {
268 key(name, Kind::Num { def, min, max, dec })
269 }
270}
271
272impl Key<String> {
273 pub const fn text(name: &'static str, def: &'static str, max: usize) -> Key<String> {
275 key(name, Kind::Text { def, max })
276 }
277}
278
279impl Key<usize> {
280 pub const fn choice(name: &'static str, def: usize, items: &'static [(&'static str, &'static str)]) -> Key<usize> {
282 key(name, Kind::Choice { def, items })
283 }
284}
285
286impl Key<u32> {
287 pub const fn color(name: &'static str, def: u32) -> Key<u32> {
289 key(name, Kind::Color(def))
290 }
291}
292
293impl<T> Key<T> {
294 pub const fn label(self, label: &'static str) -> Key<T> {
296 let mut k = self;
297 k.d.label = label;
298 k
299 }
300
301 pub const fn help(self, help: &'static str) -> Key<T> {
303 let mut k = self;
304 k.d.help = help;
305 k
306 }
307
308 pub const fn hidden(self) -> Key<T> {
310 let mut k = self;
311 k.d.flags |= KF_HIDDEN;
312 k
313 }
314
315 pub const fn restart(self) -> Key<T> {
317 let mut k = self;
318 k.d.flags |= KF_RESTART;
319 k
320 }
321}
322
323pub struct Schema {
326 pub version: u32,
327 pub keys: &'static [Desc],
328 pub sections: &'static [(&'static str, &'static str)],
331 pub migrate: Option<fn(u32, &mut Ini)>,
333}
334
335impl Schema {
336 pub const fn new(version: u32, keys: &'static [Desc]) -> Schema {
337 Schema { version, keys, sections: &[], migrate: None }
338 }
339
340 pub const fn sections(self, sections: &'static [(&'static str, &'static str)]) -> Schema {
341 Schema { sections, ..self }
342 }
343
344 pub const fn migrate(self, f: fn(u32, &mut Ini)) -> Schema {
345 Schema { migrate: Some(f), ..self }
346 }
347
348 pub fn index(&self, name: &str) -> Option<usize> {
350 self.keys.iter().position(|d| d.name == name)
351 }
352}
353
354pub fn split(name: &str) -> (&str, &str) {
356 name.split_once('.').unwrap_or(("", name))
357}
358
359pub fn rename(ini: &mut Ini, old: &str, new: &str) -> bool {
361 let (os, ok) = split(old);
362 let Some(v) = ini.get(os, ok).map(String::from) else { return false };
363 let (ns, nk) = split(new);
364 if !ini.set(ns, nk, &v) {
365 return false;
366 }
367 if (os, ok) != (ns, nk) {
368 ini.remove(os, ok);
369 }
370 true
371}
372
373fn cut(s: &str, max: usize) -> &str {
375 let mut n = max.min(s.len());
376 while !s.is_char_boundary(n) {
377 n -= 1;
378 }
379 s[..n].trim_end_matches([' ', '\t'])
380}
381
382fn canon(s: &str, max: usize) -> String {
385 let t: String = s.chars().map(|c| if matches!(c, '\r' | '\n' | '\0') { ' ' } else { c }).collect();
386 String::from(cut(t.trim_matches([' ', '\t']), max))
387}
388
389pub struct Settings {
391 schema: &'static Schema,
392 path: String,
393 ini: Ini,
394 vals: Vec<Val>,
395 dirty: bool,
396 rev: u32,
397 file_version: u32,
398 unreadable: bool, }
400
401impl Settings {
402 pub fn open(path: &str, schema: &'static Schema) -> Settings {
404 let exists = plat::file_exists(path) == 1;
405 let loaded = Ini::load_checked(path);
406 let unreadable = loaded.is_none();
407 let mut s = Settings::from_ini_ex(loaded.unwrap_or_else(Ini::new), schema, exists && !unreadable);
408 s.path = String::from(path);
409 s.unreadable = unreadable;
410 if unreadable {
411 plat::log_warn("settings", &alloc::format!("could not read {}, it is not overwritten", path));
412 }
413 s
414 }
415
416 pub fn new(schema: &'static Schema) -> Settings {
418 Settings::from_ini_ex(Ini::new(), schema, false)
419 }
420
421 pub fn from_ini(ini: Ini, schema: &'static Schema) -> Settings {
423 Settings::from_ini_ex(ini, schema, true)
424 }
425
426 fn from_ini_ex(mut ini: Ini, schema: &'static Schema, existed: bool) -> Settings {
427 let mut dirty = false;
428 let file_version = ini.get_int("", "version", 0).clamp(0, u32::MAX as i64) as u32;
429 if existed && file_version < schema.version {
430 if let Some(m) = schema.migrate {
431 m(file_version, &mut ini);
432 }
433 ini.set_int("", "version", schema.version as i64);
434 dirty = true;
435 plat::log_info("settings", &alloc::format!("migrated from version {} to {}", file_version, schema.version));
436 } else if file_version > schema.version {
437 plat::log_warn("settings", &alloc::format!("the file has version {}, the program knows {}", file_version, schema.version));
438 }
439 let vals = schema.keys.iter().map(|d| read(&ini, d)).collect();
440 Settings { schema, path: String::new(), ini, vals, dirty, rev: 0, file_version, unreadable: false }
441 }
442
443 pub fn schema(&self) -> &'static Schema {
444 self.schema
445 }
446
447 pub fn path(&self) -> &str {
449 &self.path
450 }
451
452 pub fn file_version(&self) -> u32 {
454 self.file_version
455 }
456
457 pub fn get<T: Value>(&self, k: &Key<T>) -> T {
459 let v = match self.schema.index(k.d.name) {
460 Some(i) => T::from_val(&self.vals[i]),
461 None => T::from_val(&read(&self.ini, &k.d)),
462 };
463 v.or_else(|| T::from_val(&k.d.default_val())).unwrap_or_else(|| {
464 plat::log_warn("settings", &alloc::format!("{}: the key has another type than the schema's", k.d.name));
465 T::from_val(&Val::Bool(false)).or_else(|| T::from_val(&Val::Int(0))).or_else(|| T::from_val(&Val::Num(0.0))).or_else(|| T::from_val(&Val::Text(String::new()))).or_else(|| T::from_val(&Val::Choice(0))).or_else(|| T::from_val(&Val::Color(0))).expect("settings: the type of a key")
466 })
467 }
468
469 pub fn text(&self, k: &Key<String>) -> &str {
471 match self.schema.index(k.d.name).map(|i| &self.vals[i]) {
472 Some(Val::Text(s)) => s,
473 _ => {
475 let (s, n) = k.d.split();
476 let max = match k.d.kind {
477 Kind::Text { max, .. } => max,
478 _ => usize::MAX,
479 };
480 match self.ini.get(s, n) {
481 Some(t) => cut(t, max),
482 None => match k.d.kind {
483 Kind::Text { def, .. } => cut(def.trim_matches([' ', '\t']), max),
484 _ => "",
485 },
486 }
487 }
488 }
489 }
490
491 pub fn set<T: Value>(&mut self, k: &Key<T>, v: T) -> bool {
494 match self.schema.index(k.d.name) {
495 Some(i) => self.set_at(i, v.into_val()),
496 None => {
497 let v = k.d.fit(v.into_val());
498 let old = read(&self.ini, &k.d);
499 let Some(file) = write(&mut self.ini, &k.d, &v) else { return false };
500 if old == v && !file {
501 return false;
502 }
503 self.changed();
504 true
505 }
506 }
507 }
508
509 pub fn reset<T>(&mut self, k: &Key<T>) -> bool {
512 match self.schema.index(k.d.name) {
513 Some(i) => self.set_at(i, k.d.default_val()),
514 None => {
515 let gone = write(&mut self.ini, &k.d, &k.d.default_val()) == Some(true);
516 if gone {
517 self.changed();
518 }
519 gone
520 }
521 }
522 }
523
524 pub fn reset_all(&mut self) -> bool {
526 let mut any = false;
527 for i in 0..self.schema.keys.len() {
528 any |= self.set_at(i, self.schema.keys[i].default_val());
529 }
530 any
531 }
532
533 pub fn is_default<T>(&self, k: &Key<T>) -> bool {
535 match self.schema.index(k.d.name) {
536 Some(i) => self.vals[i] == self.default_at(i),
537 None => read(&self.ini, &k.d) == k.d.default_val(),
538 }
539 }
540
541 pub fn at(&self, i: usize) -> &Val {
543 &self.vals[i]
544 }
545
546 pub fn default_at(&self, i: usize) -> Val {
548 self.schema.keys[i].default_val()
549 }
550
551 pub fn set_at(&mut self, i: usize, v: Val) -> bool {
553 let d = &self.schema.keys[i];
554 let v = d.fit(v);
555 let Some(file) = write(&mut self.ini, d, &v) else { return false };
557 if self.vals[i] == v && !file {
558 return false;
559 }
560 self.vals[i] = v;
561 self.changed();
562 true
563 }
564
565 fn changed(&mut self) {
566 self.dirty = true;
567 self.rev = self.rev.wrapping_add(1);
568 }
569
570 pub fn dirty(&self) -> bool {
572 self.dirty
573 }
574
575 pub fn revision(&self) -> u32 {
577 self.rev
578 }
579
580 pub fn ini(&self) -> &Ini {
582 &self.ini
583 }
584
585 pub fn ini_mut(&mut self) -> &mut Ini {
587 self.changed();
588 &mut self.ini
589 }
590
591 pub fn save(&mut self) -> bool {
593 if !self.dirty {
594 return true;
595 }
596 if self.path.is_empty() {
597 self.dirty = false;
598 return true;
599 }
600 if self.unreadable {
601 return false;
602 }
603 if self.ini.get("", "version").is_none() || self.file_version < self.schema.version {
604 self.ini.set_int("", "version", self.schema.version.max(self.file_version) as i64);
605 }
606 let ok = self.ini.save(&self.path);
607 if ok {
608 self.dirty = false;
609 } else {
610 plat::log_warn("settings", &alloc::format!("could not write {}", self.path));
611 }
612 ok
613 }
614}
615
616fn read(ini: &Ini, d: &Desc) -> Val {
618 let (s, n) = d.split();
619 match ini.get(s, n) {
620 None => d.default_val(),
621 Some(t) => match d.parse(t) {
622 Some(v) => v,
623 None => {
624 plat::log_warn("settings", &alloc::format!("{}: \"{}\" is not a valid value, the default is used", d.name, t));
625 d.default_val()
626 }
627 },
628 }
629}
630
631fn write(ini: &mut Ini, d: &Desc, v: &Val) -> Option<bool> {
635 let (s, n) = d.split();
636 if *v == d.default_val() {
637 let mut gone = false;
638 while ini.remove(s, n) {
639 gone = true;
640 }
641 return Some(gone);
642 }
643 let text = d.format(v);
644 if ini.get(s, n) == Some(text.as_str()) {
645 return Some(false);
646 }
647 if !ini.set(s, n, &text) {
648 plat::log_warn("settings", &alloc::format!("{}: the value is too long for the file and is not set", d.name));
649 return None;
650 }
651 Some(true)
652}