Skip to main content

egui_pop_api/tips/
pick.rs

1//! Which tip to show by itself: the rules, without egui.
2//!
3//! A tip is a candidate when
4//! - it is not contextual (those show only where the application asks);
5//! - it was not dismissed ("Got it");
6//! - its plugin's tips are not turned off;
7//! - its command was never used (a user who ran it knows it);
8//! - its surface holds (where it makes sense);
9//! - it was not shown in the last day ([`AGAIN_AFTER`]).
10//!
11//! Among the candidates, the one shown longest ago wins (never shown
12//! first), then the first registered.
13
14use std::collections::{BTreeMap, BTreeSet};
15
16use super::Tip;
17
18/// How long before a tip shown may show again, in seconds: a day.
19pub const AGAIN_AFTER: f64 = 24.0 * 3600.0;
20
21/// What the rules read.
22pub struct Rules<'a> {
23    /// The tips dismissed, by id.
24    pub dismissed: &'a BTreeSet<String>,
25    /// The commands used, by id.
26    pub used: &'a BTreeSet<String>,
27    /// When each tip was shown last, in seconds.
28    pub seen: &'a BTreeMap<String, f64>,
29    /// The origins whose tips are turned off.
30    pub off: &'a BTreeSet<String>,
31    /// Now, in the same seconds as `seen`.
32    pub now: f64,
33    /// Whether a surface (a `when` clause) holds; an empty one always
34    /// does.
35    pub holds: &'a dyn Fn(&str) -> bool,
36}
37
38impl std::fmt::Debug for Rules<'_> {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("Rules")
41            .field("dismissed", self.dismissed)
42            .field("used", self.used)
43            .field("seen", self.seen)
44            .field("off", self.off)
45            .field("now", &self.now)
46            .finish_non_exhaustive()
47    }
48}
49
50impl Rules<'_> {
51    /// Why a tip is not a candidate, or `None` when it is.
52    pub fn refusal(&self, tip: &Tip) -> Option<&'static str> {
53        if tip.contextual {
54            return Some("contextual");
55        }
56        if self.dismissed.contains(&tip.id) {
57            return Some("dismissed");
58        }
59        if self.off.contains(tip.origin_name()) {
60            return Some("its plugin's tips are off");
61        }
62        if tip
63            .command
64            .as_ref()
65            .is_some_and(|c| self.used.contains(c.as_str()))
66        {
67            return Some("its command was used");
68        }
69        if !tip.surface.is_empty() && !(self.holds)(&tip.surface) {
70            return Some("its surface does not hold");
71        }
72        if self
73            .seen
74            .get(&tip.id)
75            .is_some_and(|t| self.now - t < AGAIN_AFTER)
76        {
77            return Some("shown in the last day");
78        }
79        None
80    }
81
82    /// The tip to show among `tips`, those `keep` accepts.
83    pub fn pick<'t>(&self, tips: &'t [Tip], keep: impl Fn(&Tip) -> bool) -> Option<&'t Tip> {
84        tips.iter()
85            .filter(|t| keep(t) && self.refusal(t).is_none())
86            .min_by(|a, b| {
87                let at = |t: &Tip| self.seen.get(&t.id).copied().unwrap_or(f64::NEG_INFINITY);
88                // `min_by` keeps the first of equals: the first registered.
89                at(a).total_cmp(&at(b))
90            })
91    }
92}
93
94/// `id@seconds` pairs, separated by commas, as the setting keeps them.
95pub fn read_seen(text: &str) -> BTreeMap<String, f64> {
96    text.split(',')
97        .filter_map(|p| {
98            let (id, t) = p.trim().rsplit_once('@')?;
99            Some((id.to_string(), t.parse().ok()?))
100        })
101        .collect()
102}
103
104/// The pairs written back.
105pub fn write_seen(seen: &BTreeMap<String, f64>) -> String {
106    seen.iter()
107        .map(|(id, t)| format!("{id}@{}", t.round()))
108        .collect::<Vec<_>>()
109        .join(",")
110}
111
112/// Ids separated by commas, as the settings keep them.
113pub fn read_ids(text: &str) -> BTreeSet<String> {
114    text.split(',')
115        .map(str::trim)
116        .filter(|s| !s.is_empty())
117        .map(String::from)
118        .collect()
119}
120
121/// The ids written back.
122pub fn write_ids(ids: &BTreeSet<String>) -> String {
123    ids.iter().cloned().collect::<Vec<_>>().join(",")
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use egui_pop_model::ids::CommandId;
130
131    fn tips() -> Vec<Tip> {
132        vec![
133            Tip::new("p.rate", "Rate", "Press R.").command(CommandId::from_static("p.rate")),
134            Tip::new("p.zoom", "Zoom", "Press Z.").surface("panel == 'viewer'"),
135            Tip::new("p.compare", "Compare", "Press C."),
136        ]
137    }
138
139    #[test]
140    fn the_rules_choose_the_tip_shown_longest_ago_among_those_left() {
141        let tips = tips();
142        let none = BTreeSet::new();
143        let mut seen = BTreeMap::new();
144        let holds = |w: &str| w == "panel == 'viewer'";
145        let rules = |used: &BTreeSet<String>, seen: &BTreeMap<String, f64>, now: f64| {
146            let r = Rules {
147                dismissed: &none,
148                used,
149                seen,
150                off: &none,
151                now,
152                holds: &holds,
153            };
154            r.pick(&tips, |_| true).map(|t| t.id.clone())
155        };
156        // Never shown: the first registered.
157        assert_eq!(rules(&none, &seen, 0.0).as_deref(), Some("p.rate"));
158        // A command used: never its tip.
159        let used: BTreeSet<String> = ["p.rate".to_string()].into();
160        assert_eq!(rules(&used, &seen, 0.0).as_deref(), Some("p.zoom"));
161        // Not twice in a day; then the one shown longest ago.
162        seen.insert("p.zoom".into(), 0.0);
163        seen.insert("p.compare".into(), 10.0);
164        assert_eq!(rules(&used, &seen, 100.0), None);
165        assert_eq!(
166            rules(&used, &seen, AGAIN_AFTER + 100.0).as_deref(),
167            Some("p.zoom")
168        );
169    }
170
171    #[test]
172    fn dismissed_off_and_elsewhere_are_never_chosen() {
173        let tips = tips();
174        let dismissed: BTreeSet<String> = ["p.rate".to_string()].into();
175        let off: BTreeSet<String> = BTreeSet::new();
176        let none = BTreeSet::new();
177        let seen = BTreeMap::new();
178        let nowhere = |_: &str| false;
179        let r = Rules {
180            dismissed: &dismissed,
181            used: &none,
182            seen: &seen,
183            off: &off,
184            now: 0.0,
185            holds: &nowhere,
186        };
187        assert_eq!(r.refusal(&tips[0]), Some("dismissed"));
188        assert_eq!(r.refusal(&tips[1]), Some("its surface does not hold"));
189        assert_eq!(
190            r.pick(&tips, |_| true).map(|t| t.id.as_str()),
191            Some("p.compare")
192        );
193        let off: BTreeSet<String> = ["p".to_string()].into();
194        let r = Rules { off: &off, ..r };
195        assert_eq!(r.pick(&tips, |_| true), None);
196    }
197
198    #[test]
199    fn the_settings_text_reads_back() {
200        let seen = read_seen("a.b@12, c@3.4,broken,d@x");
201        assert_eq!(seen.len(), 2);
202        assert_eq!(write_seen(&seen), "a.b@12,c@3");
203        assert_eq!(write_ids(&read_ids(" x, ,y ")), "x,y");
204    }
205}