settings_model/
control_hints.rs1use std::collections::BTreeMap;
5
6pub const SECTION: &str = "control_hints";
7
8#[cfg_attr(feature = "model", derive(tilo_resource::Model))]
9#[cfg_attr(feature = "model", model(defaults))]
10#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
11pub struct Learned {
12 #[serde(default = "enabled_by_default")]
14 pub enabled: bool,
15 #[serde(default)]
17 pub known: Vec<String>,
18 #[serde(default)]
20 pub shown: BTreeMap<String, u8>,
21}
22
23fn enabled_by_default() -> bool {
24 true
25}
26
27impl Default for Learned {
28 fn default() -> Self {
29 Self {
30 enabled: true,
31 known: Vec::new(),
32 shown: BTreeMap::new(),
33 }
34 }
35}
36
37impl Learned {
38 #[must_use]
39 pub fn knows(&self, id: &str) -> bool {
40 self.known.iter().any(|known| known == id)
41 }
42
43 #[must_use]
44 pub fn showings(&self, id: &str) -> u8 {
45 self.shown.get(id).copied().unwrap_or(0)
46 }
47
48 pub fn learn(&mut self, id: &str) {
49 if !self.knows(id) {
50 self.known.push(id.to_owned());
51 self.known.sort();
52 }
53 }
54
55 pub fn note_shown(&mut self, id: &str) {
56 let count = self.shown.entry(id.to_owned()).or_insert(0);
57 *count = count.saturating_add(1);
58 }
59
60 pub fn withdraw_shown(&mut self, id: &str) {
62 if let Some(count) = self.shown.get_mut(id) {
63 *count = count.saturating_sub(1);
64 if *count == 0 {
65 self.shown.remove(id);
66 }
67 }
68 }
69
70 pub fn merge(&mut self, other: &Self) {
74 for id in &other.known {
75 self.learn(id);
76 }
77 for (id, count) in &other.shown {
78 let mine = self.shown.entry(id.clone()).or_insert(0);
79 *mine = (*mine).max(*count);
80 }
81 self.enabled = other.enabled;
82 }
83}
84
85#[cfg(test)]
86mod tests {
87 use super::*;
88
89 #[test]
90 fn a_merge_keeps_what_either_device_learned() {
91 let mut here = Learned::default();
92 here.learn("move");
93 here.note_shown("open");
94 let mut there = Learned::default();
95 there.learn("open");
96 there.note_shown("open");
97 there.note_shown("open");
98 there.enabled = false;
99 here.merge(&there);
100 assert!(here.knows("move") && here.knows("open"));
101 assert_eq!(here.showings("open"), 2);
102 assert!(!here.enabled);
103 }
104}