Skip to main content

egui_pop_api/
tips.rs

1//! Tips, as a plugin ([`TipsPlugin`]): a tip of the day and contextual
2//! hints, which plugins register ([`Tips::add`]), each dismissible and
3//! remembered in the settings (`tips.dismissed`, the ids of the tips not
4//! to show again; `tips.show` turns them all off).
5//!
6//! <div class="warning">Experimental: may change in any release
7//! (docs/stability.md).</div>
8//!
9//! A tip's title and text are translated by keys derived from its id,
10//! `tip-<id>.title` and `tip-<id>.text` (the id's dots become dashes), in
11//! the application's catalogues; the English given is the fallback.
12//!
13//! - [`tip_of_the_day`] draws a card with the next tip not dismissed:
14//!   the previous and next ones, "Don't show again", close (for this
15//!   session);
16//! - [`hint`] draws one contextual tip where it is called, beside what
17//!   it is about, with "Got it".
18//!
19//! | Step | Arguments | Default |
20//! |---|---|---|
21//! | `tips.dismiss` | `tip`, `cause` (`user`, `agent`) | adds it to `tips.dismissed` |
22//!
23//! Commands: `tips.reset` (every tip shown again, in the Help menu's
24//! category) and, for agents, `tips.list` and `tips.dismiss` (`tip`).
25//!
26//! Tips also come by themselves ([`Tips::set_auto`]), chosen by rules
27//! ([`pick`]: not dismissed, their command never used, their surface
28//! holding, not shown in the last day, the one shown longest ago), as a
29//! card that never takes the focus, beside the element a tip is about
30//! (its `target`, named with [`mark`] or [`target`]) with a halo around
31//! it. Commands `tips.show`, `tips.next`, `tips.gotIt`, `tips.notNow`
32//! (Escape), `tips.off` and, for agents, `tips.current`.
33//!
34//! Tips are also declared in files, `tips/<id>.md` ([`mod@file`]): a header
35//! (`id`, `surface`, `command`, `target`, `contextual`), a `# Title` and
36//! the text, read with [`Tips::add_files`] (the files' text, built into
37//! the binary with `include_str!`) or [`Tips::add_dir`]. A text shows
38//! `**bold**` and `` `code` ``; `{key}` is the key bound to the tip's
39//! command in the keymap in force, `{key:<command>}` another command's
40//! ([`markup`]), so a rebound key shows rebound.
41//!
42//! Owned: egui has tooltips (`on_hover_text`), which stay as they are;
43//! no crate offers remembered, translated tips (see docs/tips.md).
44//!
45//! ```
46//! use egui_pop_api::tips::{TIPS, Tip, TipsPlugin};
47//! use egui_pop_api::App;
48//!
49//! let app = App::builder()
50//!     .plugin(TipsPlugin)
51//!     .build(&egui::Context::default())
52//!     .unwrap();
53//! let tips = app.handle().service(&TIPS).unwrap();
54//! tips.add(Tip::new("photos.rate", "Rate quickly", "Press 1 to 5 to rate the selected photos."));
55//! assert_eq!(tips.of_the_day(app.handle()).map(|t| t.id), Some("photos.rate".into()));
56//! tips.dismiss(app.handle(), "photos.rate").unwrap();
57//! assert!(tips.of_the_day(app.handle()).is_none());
58//! ```
59
60mod browser;
61pub mod file;
62pub mod lint;
63pub mod markup;
64pub mod pick;
65mod screen;
66
67use std::collections::{BTreeMap, BTreeSet};
68use std::path::Path;
69use std::sync::Mutex;
70
71use egui::Ui;
72use egui::accesskit::Role;
73use egui_pop_core::icon::{Icon, Size, Tone};
74use egui_pop_core::kit::{self, Kit};
75use egui_pop_core::lock;
76use egui_pop_core::strings;
77use egui_pop_core::ui::UiPop as _;
78use egui_pop_model::clock::SharedClock;
79use egui_pop_model::commands::{CommandSpec, Origin};
80use egui_pop_model::ids::{CommandId, OwnerId, PluginId, SettingId, StepId};
81use egui_pop_model::keymap::Layer;
82use egui_pop_model::values::{Change, Descriptor, Set, Value};
83use egui_pop_model::when::{When, WhenContext};
84use serde_json::{Value as Json, json};
85
86use crate::app::AppHandle;
87use crate::hooks::On;
88use crate::host::Seq;
89use crate::services::ServiceToken;
90use crate::steps::{Outcome, StepSpec};
91use crate::strings as txt;
92use crate::zones::{self, Block};
93use crate::{Ctx, Plugin, PluginError};
94use egui_pop_model::ids::BlockId;
95
96pub use browser::{browser, groups};
97pub use screen::{halo_color, mark, target, target_rect, targets_seen};
98
99/// The plugin's id.
100pub const TIPS_PLUGIN: PluginId = PluginId::from_static("egui_pop.tips");
101
102/// The tips registered, as a service.
103pub const TIPS: ServiceToken<Tips> = ServiceToken::new("egui_pop.tips");
104
105/// Whether tips are shown at all.
106pub const SETTING_TIPS_SHOW: SettingId = SettingId::from_static("tips.show");
107/// The tips not to show again: their ids, separated by commas.
108pub const SETTING_TIPS_DISMISSED: SettingId = SettingId::from_static("tips.dismissed");
109/// When each tip was shown last: `id@seconds` (since 1970), separated
110/// by commas.
111pub const SETTING_TIPS_SEEN: SettingId = SettingId::from_static("tips.seen");
112/// The commands a person used: their ids, separated by commas.
113pub const SETTING_TIPS_USED: SettingId = SettingId::from_static("tips.used");
114/// The origins (plugins) whose tips are off, separated by commas.
115pub const SETTING_TIPS_OFF: SettingId = SettingId::from_static("tips.off");
116
117/// A tip is dismissed.
118pub const STEP_TIPS_DISMISS: StepId = StepId::from_static("tips.dismiss");
119
120pub const CMD_TIPS_RESET: CommandId = CommandId::from_static("tips.reset");
121pub const CMD_TIPS_LIST: CommandId = CommandId::from_static("tips.list");
122pub const CMD_TIPS_DISMISS: CommandId = CommandId::from_static("tips.dismiss");
123pub const CMD_TIPS_SHOW: CommandId = CommandId::from_static("tips.show");
124pub const CMD_TIPS_NEXT: CommandId = CommandId::from_static("tips.next");
125pub const CMD_TIPS_GOT_IT: CommandId = CommandId::from_static("tips.gotIt");
126pub const CMD_TIPS_NOT_NOW: CommandId = CommandId::from_static("tips.notNow");
127pub const CMD_TIPS_OFF: CommandId = CommandId::from_static("tips.off");
128pub const CMD_TIPS_CURRENT: CommandId = CommandId::from_static("tips.current");
129pub const CMD_TIPS_BROWSE: CommandId = CommandId::from_static("tips.browse");
130pub const CMD_TIPS_ORIGIN: CommandId = CommandId::from_static("tips.origin");
131
132/// The context key set while a tip's card is shown.
133pub const CONTEXT_TIP_SHOWN: &str = "tipShown";
134
135/// How long after the start the first tip shows by itself, in seconds.
136pub const FIRST_AFTER: f64 = 5.0;
137
138/// The kind of declaration a tip's keys are derived from (`tip-<id>`).
139pub const TIP_KIND: &str = "tip";
140
141fn setting_path(id: &SettingId) -> String {
142    format!("settings/{id}")
143}
144
145pub use file::TipError;
146
147/// A tip: a title and a text, in English (translated by its id's keys).
148#[derive(Clone, Debug, PartialEq)]
149pub struct Tip {
150    pub id: String,
151    pub title: String,
152    /// The text: paragraphs on lines of their own, `**bold**`,
153    /// `` `code` ``, `{key}` and `{key:<command>}`.
154    pub text: String,
155    /// Shown only where [`hint`] is called, never as the tip of the day.
156    pub contextual: bool,
157    /// Where the tip makes sense, a `when` clause (empty: anywhere).
158    pub surface: String,
159    /// The command it teaches: `{key}` shows its binding.
160    pub command: Option<CommandId>,
161    /// The name of what it is about, as drawn ([`target`]).
162    pub target: Option<String>,
163    /// Who declared it, for grouping (empty: the id's first segment).
164    pub origin: String,
165}
166
167impl Tip {
168    pub fn new(id: &str, title: &str, text: &str) -> Self {
169        Self {
170            id: id.into(),
171            title: title.into(),
172            text: text.into(),
173            contextual: false,
174            surface: String::new(),
175            command: None,
176            target: None,
177            origin: String::new(),
178        }
179    }
180
181    /// Kept for [`hint`]: not in the tip of the day's turn.
182    pub fn contextual(mut self) -> Self {
183        self.contextual = true;
184        self
185    }
186
187    /// Where the tip makes sense, a `when` clause.
188    pub fn surface(mut self, when: &str) -> Self {
189        self.surface = when.into();
190        self
191    }
192
193    /// The command it teaches.
194    pub fn command(mut self, command: CommandId) -> Self {
195        self.command = Some(command);
196        self
197    }
198
199    /// The name of what it is about ([`target`]).
200    pub fn target(mut self, name: &str) -> Self {
201        self.target = Some(name.into());
202        self
203    }
204
205    /// Who declared it (a plugin's id).
206    pub fn origin(mut self, origin: &str) -> Self {
207        self.origin = origin.into();
208        self
209    }
210
211    /// Who declared it: the origin given, else the id's first segment.
212    pub fn origin_name(&self) -> &str {
213        if self.origin.is_empty() {
214            self.id.split('.').next().unwrap_or(&self.id)
215        } else {
216            &self.origin
217        }
218    }
219
220    /// Reads a tip from a file's text ([`mod@file`]).
221    pub fn parse(file: &str, source: &str) -> Result<Tip, TipError> {
222        file::parse(file, source)
223    }
224
225    /// The title in the interface's language.
226    pub fn title_in(&self, ctx: &egui::Context) -> String {
227        strings::declared(ctx, TIP_KIND, &self.id, Some("title"), &self.title)
228    }
229
230    /// The text in the interface's language, placeholders left.
231    pub fn text_in(&self, ctx: &egui::Context) -> String {
232        strings::declared(ctx, TIP_KIND, &self.id, Some("text"), &self.text)
233    }
234
235    /// The text as shown: in the interface's language, `{key}` and
236    /// `{key:<command>}` replaced by the bindings in force (as
237    /// `` `Ctrl+K` ``), a command without one by its title in bold. A
238    /// translation writes them `{ $key }` and `{ $key-<command> }` (the
239    /// command's dots as dashes), Fluent's own placeholders.
240    pub fn text_shown(&self, ctx: &egui::Context, app: &AppHandle) -> String {
241        let shown = |c: &str| CommandId::new(c).ok().and_then(|c| key_text(ctx, app, &c));
242        let own = self.command.as_ref().and_then(|c| shown(c.as_str()));
243        let mut args: Vec<(String, String)> = Vec::new();
244        if let Some(k) = &own {
245            args.push(("key".into(), k.clone()));
246        }
247        for c in markup::named_commands(&self.text) {
248            if let Some(k) = shown(&c) {
249                args.push((format!("key-{}", strings::slug(&c)), k));
250            }
251        }
252        let args: Vec<(&str, &str)> = args.iter().map(|(a, b)| (a.as_str(), b.as_str())).collect();
253        let text = strings::lookup_args(
254            ctx,
255            &strings::declared_key(TIP_KIND, &self.id, Some("text")),
256            &self.text,
257            &args,
258        );
259        markup::resolve(&text, own.as_deref(), shown)
260    }
261
262    fn to_json(&self, dismissed: bool) -> Json {
263        json!({
264            "id": self.id,
265            "title": self.title,
266            "text": self.text,
267            "contextual": self.contextual,
268            "surface": self.surface,
269            "command": self.command,
270            "target": self.target,
271            "origin": self.origin_name(),
272            "dismissed": dismissed,
273        })
274    }
275}
276
277/// A command's key as a tip shows it: its first binding in force as
278/// code, else its title in bold; `None` for a command not declared.
279fn key_text(ctx: &egui::Context, app: &AppHandle, id: &CommandId) -> Option<String> {
280    if let Some(k) = app.keys_for(id).into_iter().next() {
281        return Some(format!("`{k}`"));
282    }
283    let (spec, _) = app.commands().into_iter().find(|(s, _)| s.id == *id)?;
284    let title = strings::declared(
285        ctx,
286        strings::kind::COMMAND,
287        id.as_str(),
288        Some("title"),
289        &spec.title,
290    );
291    Some(format!("**{title}**"))
292}
293
294#[derive(Debug, Default)]
295struct State {
296    tips: Vec<Tip>,
297    /// Which tip of the day shows, among those left.
298    at: usize,
299    /// The tip of the day closed for this session.
300    closed: bool,
301    /// The tip shown as a card by itself (or by `tips.show`).
302    current: Option<String>,
303    /// Tips show by themselves.
304    auto: bool,
305    /// The interface's time at the first pass.
306    started: Option<f64>,
307    /// The first tip by itself came (or its time passed).
308    first_done: bool,
309    /// The surfaces entered in this session.
310    entered: BTreeSet<String>,
311    /// The journal read up to here, for the commands used.
312    read_to: Seq,
313    clock: Clock,
314}
315
316/// Where "now" comes from: the system's time, or a test's clock.
317#[derive(Default)]
318struct Clock(Option<SharedClock>);
319
320impl std::fmt::Debug for Clock {
321    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322        f.write_str(if self.0.is_some() {
323            "Clock(set)"
324        } else {
325            "Clock(system)"
326        })
327    }
328}
329
330/// The tips registered, and the tip of the day's place.
331#[derive(Debug, Default)]
332pub struct Tips {
333    state: Mutex<State>,
334}
335
336impl Tips {
337    /// Registers a tip (replacing one of the same id).
338    pub fn add(&self, tip: Tip) {
339        let mut s = lock(&self.state);
340        match s.tips.iter_mut().find(|t| t.id == tip.id) {
341            Some(t) => *t = tip,
342            None => s.tips.push(tip),
343        }
344    }
345
346    /// Registers tips from files' text, `(name, text)` (`photos.rate.md`
347    /// and its text, built in with `include_str!`), as declared by
348    /// `origin` (a plugin's id). Returns the files that could not be read;
349    /// the others are registered.
350    pub fn add_files(&self, origin: &str, files: &[(&str, &str)]) -> Vec<TipError> {
351        let mut errors = Vec::new();
352        for (name, text) in files {
353            match file::parse(name, text) {
354                Ok(t) => self.add(t.origin(origin)),
355                Err(e) => errors.push(e),
356            }
357        }
358        errors
359    }
360
361    /// Registers the tips of a folder's `*.md` files (a plugin's `tips/`
362    /// folder shipped beside it), as declared by `origin`. Returns the
363    /// files that could not be read.
364    pub fn add_dir(&self, origin: &str, dir: &Path) -> Vec<TipError> {
365        let (tips, errors) = file::read_dir(dir);
366        for t in tips {
367            self.add(t.origin(origin));
368        }
369        errors
370    }
371
372    /// Shows tips by themselves, as cards: once [`FIRST_AFTER`] seconds
373    /// after the start, then the first time a tip's surface is entered.
374    /// Off by default: the application turns it on.
375    pub fn set_auto(&self, on: bool) {
376        lock(&self.state).auto = on;
377    }
378
379    /// Whether tips show by themselves.
380    pub fn auto(&self) -> bool {
381        lock(&self.state).auto
382    }
383
384    /// Reads "now" from a clock (seconds since 1970), for tests.
385    pub fn set_clock(&self, clock: SharedClock) {
386        lock(&self.state).clock = Clock(Some(clock));
387    }
388
389    /// Now, in seconds since 1970.
390    pub fn now(&self) -> f64 {
391        if let Some(c) = &lock(&self.state).clock.0 {
392            return c.now();
393        }
394        web_time::SystemTime::now()
395            .duration_since(web_time::UNIX_EPOCH)
396            .map_or(0.0, |d| d.as_secs_f64())
397    }
398
399    fn text_setting(app: &AppHandle, id: &SettingId) -> String {
400        lock(&app.store())
401            .get(&setting_path(id))
402            .and_then(|e| e.value.as_text().map(str::to_string))
403            .unwrap_or_default()
404    }
405
406    fn write_setting(app: &AppHandle, id: &SettingId, text: String) -> Result<(), String> {
407        lock(&app.store())
408            .set(
409                Set::new(
410                    &setting_path(id),
411                    Change::To(Value::Text(text)),
412                    Origin::User,
413                )
414                .by(&OwnerId::FRAMEWORK)
415                .untracked(),
416            )
417            .map(|_| ())
418            .map_err(|e| e.to_string())
419    }
420
421    /// The commands a person used (the `tips.used` setting).
422    pub fn used(&self, app: &AppHandle) -> BTreeSet<String> {
423        pick::read_ids(&Self::text_setting(app, &SETTING_TIPS_USED))
424    }
425
426    /// Records commands as used: their tips are not picked any more.
427    pub fn mark_used<'a>(
428        &self,
429        app: &AppHandle,
430        commands: impl IntoIterator<Item = &'a str>,
431    ) -> Result<(), String> {
432        let mut used = self.used(app);
433        let before = used.len();
434        used.extend(commands.into_iter().map(String::from));
435        if used.len() == before {
436            return Ok(());
437        }
438        Self::write_setting(app, &SETTING_TIPS_USED, pick::write_ids(&used))
439    }
440
441    /// When each tip was shown last (the `tips.seen` setting).
442    pub fn seen(&self, app: &AppHandle) -> BTreeMap<String, f64> {
443        pick::read_seen(&Self::text_setting(app, &SETTING_TIPS_SEEN))
444    }
445
446    fn mark_seen(&self, app: &AppHandle, id: &str) {
447        let mut seen = self.seen(app);
448        seen.insert(id.to_string(), self.now());
449        if let Err(e) = Self::write_setting(app, &SETTING_TIPS_SEEN, pick::write_seen(&seen)) {
450            log::warn!("tips: {e}");
451        }
452    }
453
454    /// The origins whose tips are off (the `tips.off` setting).
455    pub fn off(&self, app: &AppHandle) -> BTreeSet<String> {
456        pick::read_ids(&Self::text_setting(app, &SETTING_TIPS_OFF))
457    }
458
459    /// Turns an origin's tips (a plugin's) on or off, the others kept.
460    pub fn set_origin_on(&self, app: &AppHandle, origin: &str, on: bool) -> Result<(), String> {
461        let mut off = self.off(app);
462        let changed = if on {
463            off.remove(origin)
464        } else {
465            off.insert(origin.to_string())
466        };
467        if !changed {
468            return Ok(());
469        }
470        Self::write_setting(app, &SETTING_TIPS_OFF, pick::write_ids(&off))?;
471        if !on && self.current().is_some_and(|t| t.origin_name() == origin) {
472            self.set_current(app, None);
473        }
474        Ok(())
475    }
476
477    /// The tip the rules pick in a context, among those `keep` accepts
478    /// ([`pick`]); none when tips are off.
479    pub fn pick(
480        &self,
481        app: &AppHandle,
482        cx: &WhenContext,
483        keep: impl Fn(&Tip) -> bool,
484    ) -> Option<Tip> {
485        if !self.enabled(app) {
486            return None;
487        }
488        let (dismissed, used, seen, off) = (
489            self.dismissed(app),
490            self.used(app),
491            self.seen(app),
492            self.off(app),
493        );
494        let holds = |w: &str| When::parse(w).is_ok_and(|w| w.eval(cx));
495        let rules = pick::Rules {
496            dismissed: &dismissed,
497            used: &used,
498            seen: &seen,
499            off: &off,
500            now: self.now(),
501            holds: &holds,
502        };
503        let tips = self.all();
504        rules.pick(&tips, keep).cloned()
505    }
506
507    /// Why a tip would not be picked now, or `None` when it would.
508    pub fn refusal(&self, app: &AppHandle, id: &str) -> Option<String> {
509        let tip = self.get(id)?;
510        if !self.enabled(app) {
511            return Some("tips are off".into());
512        }
513        let cx = app.when_context();
514        let (dismissed, used, seen, off) = (
515            self.dismissed(app),
516            self.used(app),
517            self.seen(app),
518            self.off(app),
519        );
520        let holds = |w: &str| When::parse(w).is_ok_and(|w| w.eval(&cx));
521        pick::Rules {
522            dismissed: &dismissed,
523            used: &used,
524            seen: &seen,
525            off: &off,
526            now: self.now(),
527            holds: &holds,
528        }
529        .refusal(&tip)
530        .map(String::from)
531    }
532
533    /// The tip shown as a card, if any.
534    pub fn current(&self) -> Option<Tip> {
535        let id = lock(&self.state).current.clone()?;
536        self.get(&id)
537    }
538
539    fn set_current(&self, app: &AppHandle, id: Option<String>) {
540        let shown = id.is_some();
541        lock(&self.state).current = id;
542        app.set_context(CONTEXT_TIP_SHOWN, if shown { "true" } else { "false" });
543        app.egui().request_repaint();
544    }
545
546    /// Shows a tip as a card, whatever the rules say, and records it as
547    /// shown now.
548    pub fn show(&self, app: &AppHandle, id: &str) -> Result<Tip, String> {
549        let tip = self.get(id).ok_or_else(|| format!("no tip `{id}`"))?;
550        self.mark_seen(app, id);
551        self.set_current(app, Some(id.to_string()));
552        app.publish("app", None, "tip.shown", json!({ "tip": id }));
553        Ok(tip)
554    }
555
556    /// Shows the tip the rules pick in the current context (among those
557    /// `keep` accepts); closes the card when there is none.
558    pub fn show_next_where(&self, app: &AppHandle, keep: impl Fn(&Tip) -> bool) -> Option<Tip> {
559        let cx = app.when_context();
560        match self.pick(app, &cx, keep) {
561            Some(t) => self.show(app, &t.id).ok(),
562            None => {
563                self.set_current(app, None);
564                None
565            }
566        }
567    }
568
569    /// Shows the next tip the rules pick (the card's "Next tip"): the one
570    /// shown was recorded, so it is not picked again today.
571    pub fn show_next(&self, app: &AppHandle) -> Option<Tip> {
572        self.show_next_where(app, |_| true)
573    }
574
575    /// Closes the card for now ("Not now", Escape): the tip may come
576    /// back another day.
577    pub fn not_now(&self, app: &AppHandle) {
578        self.set_current(app, None);
579    }
580
581    /// Dismisses the tip shown for good ("Got it") and closes the card.
582    pub fn got_it(&self, app: &AppHandle) -> Result<(), String> {
583        let id = lock(&self.state).current.clone().ok_or("no tip is shown")?;
584        self.dismiss(app, &id)?;
585        self.set_current(app, None);
586        Ok(())
587    }
588
589    /// Turns every tip off (the `tips.show` setting) and closes the card.
590    pub fn turn_off(&self, app: &AppHandle) -> Result<(), String> {
591        lock(&app.store())
592            .set(
593                Set::new(
594                    &setting_path(&SETTING_TIPS_SHOW),
595                    Change::To(Value::Bool(false)),
596                    Origin::User,
597                )
598                .by(&OwnerId::FRAMEWORK)
599                .untracked(),
600            )
601            .map_err(|e| e.to_string())?;
602        self.set_current(app, None);
603        Ok(())
604    }
605
606    /// Reads the journal for the commands a person ran since the last
607    /// call (a person: the user or a device, not an agent or a script).
608    fn read_journal(&self, app: &AppHandle) {
609        let from = lock(&self.state).read_to;
610        let events = app.events_since(from);
611        let Some(last) = events.last().map(|e| e.seq) else {
612            return;
613        };
614        lock(&self.state).read_to = last;
615        let ran: Vec<&str> = events
616            .iter()
617            .filter(|e| {
618                e.name == "command.done" && (e.source == "user" || e.source.starts_with("device:"))
619            })
620            .filter_map(|e| e.data["command"].as_str())
621            .collect();
622        if !ran.is_empty()
623            && let Err(e) = self.mark_used(app, ran)
624        {
625            log::warn!("tips: {e}");
626        }
627    }
628
629    /// Each pass: the commands used, then a tip by itself when its
630    /// moment comes.
631    fn tick(&self, app: &AppHandle) {
632        self.read_journal(app);
633        if !self.auto() || !self.enabled(app) || lock(&self.state).current.is_some() {
634            return;
635        }
636        let time = app.egui().input(|i| i.time);
637        let started = *lock(&self.state).started.get_or_insert(time);
638        let cx = app.when_context();
639        if cx.get("modalOpen") == "true" {
640            return;
641        }
642        let surfaces: BTreeSet<String> = lock(&self.state)
643            .tips
644            .iter()
645            .filter(|t| !t.contextual && !t.surface.is_empty())
646            .map(|t| t.surface.clone())
647            .collect();
648        let entered: Vec<String> = {
649            let mut s = lock(&self.state);
650            let new: Vec<String> = surfaces
651                .into_iter()
652                .filter(|w| !s.entered.contains(w) && When::parse(w).is_ok_and(|c| c.eval(&cx)))
653                .collect();
654            s.entered.extend(new.iter().cloned());
655            new
656        };
657        if !lock(&self.state).first_done {
658            let left = started + FIRST_AFTER - time;
659            if left > 0.0 {
660                app.egui()
661                    .request_repaint_after(std::time::Duration::from_secs_f64(left));
662                return;
663            }
664            lock(&self.state).first_done = true;
665            self.show_next(app);
666        } else if !entered.is_empty() {
667            self.show_next_where(app, |t| entered.contains(&t.surface));
668        }
669    }
670
671    /// Every tip, in the order registered.
672    pub fn all(&self) -> Vec<Tip> {
673        lock(&self.state).tips.clone()
674    }
675
676    pub fn get(&self, id: &str) -> Option<Tip> {
677        lock(&self.state).tips.iter().find(|t| t.id == id).cloned()
678    }
679
680    /// Whether tips are shown (the `tips.show` setting).
681    pub fn enabled(&self, app: &AppHandle) -> bool {
682        lock(&app.store())
683            .get(&setting_path(&SETTING_TIPS_SHOW))
684            .and_then(|e| e.value.as_bool())
685            .unwrap_or(true)
686    }
687
688    /// The ids of the tips dismissed (the `tips.dismissed` setting).
689    pub fn dismissed(&self, app: &AppHandle) -> BTreeSet<String> {
690        lock(&app.store())
691            .get(&setting_path(&SETTING_TIPS_DISMISSED))
692            .and_then(|e| e.value.as_text().map(str::to_string))
693            .unwrap_or_default()
694            .split(',')
695            .map(str::trim)
696            .filter(|s| !s.is_empty())
697            .map(String::from)
698            .collect()
699    }
700
701    pub fn is_dismissed(&self, app: &AppHandle, id: &str) -> bool {
702        self.dismissed(app).contains(id)
703    }
704
705    fn write_dismissed(&self, app: &AppHandle, ids: &BTreeSet<String>) -> Result<(), String> {
706        let text = ids.iter().cloned().collect::<Vec<_>>().join(",");
707        lock(&app.store())
708            .set(
709                Set::new(
710                    &setting_path(&SETTING_TIPS_DISMISSED),
711                    Change::To(Value::Text(text)),
712                    Origin::User,
713                )
714                .by(&OwnerId::FRAMEWORK)
715                .untracked(),
716            )
717            .map(|_| ())
718            .map_err(|e| e.to_string())
719    }
720
721    /// Dismisses a tip for good, through the `tips.dismiss` step.
722    pub fn dismiss(&self, app: &AppHandle, id: &str) -> Result<(), String> {
723        self.dismiss_by(app, id, "user")
724    }
725
726    fn dismiss_by(&self, app: &AppHandle, id: &str, cause: &str) -> Result<(), String> {
727        if self.get(id).is_none() {
728            return Err(format!("no tip `{id}`"));
729        }
730        let args = json!({ "tip": id, "cause": cause });
731        match app.step(&STEP_TIPS_DISMISS, args, |app, a| {
732            let tips = app
733                .service(&TIPS)
734                .ok_or("the tips plugin is not connected")?;
735            let tip = a["tip"].as_str().ok_or("`tip` is missing")?;
736            let mut ids = tips.dismissed(app);
737            ids.insert(tip.to_string());
738            tips.write_dismissed(app, &ids)?;
739            Ok(json!(tip))
740        }) {
741            Outcome::Done(r) => r.map(|_| ()),
742            Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
743        }
744    }
745
746    /// Shows every tip again: none dismissed, none held back for having
747    /// been shown today. The commands used stay recorded: what a person
748    /// knows does not change, and the browser still shows those tips.
749    pub fn reset(&self, app: &AppHandle) -> Result<(), String> {
750        lock(&self.state).closed = false;
751        self.write_dismissed(app, &BTreeSet::new())?;
752        Self::write_setting(app, &SETTING_TIPS_SEEN, String::new())
753    }
754
755    /// The tips of the day still to show, in order.
756    fn left(&self, app: &AppHandle) -> Vec<Tip> {
757        let dismissed = self.dismissed(app);
758        let off = self.off(app);
759        lock(&self.state)
760            .tips
761            .iter()
762            .filter(|t| {
763                !t.contextual && !dismissed.contains(&t.id) && !off.contains(t.origin_name())
764            })
765            .cloned()
766            .collect()
767    }
768
769    /// The tip of the day: the one in turn among those not dismissed;
770    /// none when tips are off, all dismissed or closed for the session.
771    pub fn of_the_day(&self, app: &AppHandle) -> Option<Tip> {
772        if !self.enabled(app) || lock(&self.state).closed {
773            return None;
774        }
775        let left = self.left(app);
776        let at = lock(&self.state).at;
777        (!left.is_empty()).then(|| left[at % left.len()].clone())
778    }
779
780    /// Turns to the next tip of the day (`back`: the previous one).
781    pub fn turn(&self, app: &AppHandle, back: bool) {
782        let n = self.left(app).len().max(1);
783        let mut s = lock(&self.state);
784        s.at = if back {
785            (s.at % n + n - 1) % n
786        } else {
787            (s.at + 1) % n
788        };
789    }
790
791    /// Closes the tip of the day for this session.
792    pub fn close(&self) {
793        lock(&self.state).closed = true;
794    }
795}
796
797/// Declares the tips' service, settings, step and commands.
798#[derive(Debug, Default)]
799pub struct TipsPlugin;
800
801impl Plugin for TipsPlugin {
802    fn id(&self) -> PluginId {
803        TIPS_PLUGIN
804    }
805
806    fn title(&self) -> String {
807        "Tips".into()
808    }
809
810    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
811        const CAT: &str = "Help";
812        ctx.service(&TIPS, Tips::default())?;
813        ctx.setting(
814            SETTING_TIPS_SHOW,
815            Descriptor::bool("Show tips", true)
816                .description("The tip of the day and the hints beside what they are about."),
817        )?;
818        ctx.setting(
819            SETTING_TIPS_DISMISSED,
820            Descriptor::text("Dismissed tips", "")
821                .description("The tips not to show again, by id; empty to show them all again."),
822        )?;
823        ctx.setting(
824            SETTING_TIPS_OFF,
825            Descriptor::text("Plugins without tips", "").description(
826                "The plugins whose tips are off, by id; the others still show theirs.",
827            ),
828        )?;
829        ctx.setting(
830            SETTING_TIPS_SEEN,
831            Descriptor::text("Tips shown", "").description(
832                "When each tip was shown last, so it does not show again the same day.",
833            ),
834        )?;
835        ctx.setting(
836            SETTING_TIPS_USED,
837            Descriptor::text("Commands used", "")
838                .description("The commands already used: their tips are not shown by themselves."),
839        )?;
840        ctx.step(
841            StepSpec::new(
842                STEP_TIPS_DISMISS,
843                "A tip is dismissed for good (`tip`, `cause`: user or agent); a veto keeps it showing.",
844            )
845            .args(json!({ "tip": "photos.rate", "cause": "user" })),
846        )?;
847        ctx.command(
848            CommandSpec::new(CMD_TIPS_RESET, "Show every tip again", CAT)
849                .description("Forgets which tips were dismissed and which were shown today."),
850            |call| {
851                let tips = call
852                    .app
853                    .service(&TIPS)
854                    .ok_or("the tips plugin is not connected")?;
855                tips.reset(call.app)?;
856                Ok(Json::Null)
857            },
858        )?;
859        ctx.command(
860            CommandSpec::new(CMD_TIPS_LIST, "List the tips", CAT)
861                .description("Every tip registered: its id, English title and text, whether it is contextual and whether it was dismissed.")
862                .hidden()
863                .read_only(),
864            |call| {
865                let tips = call
866                    .app
867                    .service(&TIPS)
868                    .ok_or("the tips plugin is not connected")?;
869                let dismissed = tips.dismissed(call.app);
870                Ok(json!(
871                    tips.all()
872                        .iter()
873                        .map(|t| t.to_json(dismissed.contains(&t.id)))
874                        .collect::<Vec<_>>()
875                ))
876            },
877        )?;
878        ctx.command(
879            CommandSpec::new(CMD_TIPS_DISMISS, "Dismiss a tip", CAT)
880                .description(
881                    "Dismisses a tip for good (`tip`, its id), through the tips.dismiss step.",
882                )
883                .hidden()
884                .args(json!({ "tip": "photos.rate" })),
885            |call| {
886                let tips = call
887                    .app
888                    .service(&TIPS)
889                    .ok_or("the tips plugin is not connected")?;
890                let id = call
891                    .args
892                    .get("tip")
893                    .and_then(Json::as_str)
894                    .ok_or("`tip` is missing")?;
895                tips.dismiss_by(call.app, id, "agent")?;
896                Ok(json!({ "dismissed": id }))
897            },
898        )?;
899        let shown = CONTEXT_TIP_SHOWN;
900        ctx.command(
901            CommandSpec::new(CMD_TIPS_SHOW, "Show a tip", CAT)
902                .description("Shows the tip the rules pick here, as a card beside what it is about; `tip`, an id, shows that one.")
903                .args(json!({ "tip": "photos.rate" })),
904            |call| {
905                let tips = service(call.app)?;
906                let tip = match call.args.get("tip").and_then(Json::as_str) {
907                    Some(id) => Some(tips.show(call.app, id)?),
908                    None => tips.show_next(call.app),
909                };
910                Ok(json!({ "shown": tip.map(|t| t.id) }))
911            },
912        )?
913        .command(
914            CommandSpec::new(CMD_TIPS_NEXT, "Next tip", CAT)
915                .description("Shows the next tip the rules pick in place of the one shown.")
916                .when(shown),
917            |call| {
918                let tip = service(call.app)?.show_next(call.app);
919                Ok(json!({ "shown": tip.map(|t| t.id) }))
920            },
921        )?
922        .command(
923            CommandSpec::new(CMD_TIPS_GOT_IT, "Got it", CAT)
924                .description("Dismisses the tip shown for good.")
925                .when(shown),
926            |call| {
927                service(call.app)?.got_it(call.app)?;
928                Ok(Json::Null)
929            },
930        )?
931        .command(
932            CommandSpec::new(CMD_TIPS_NOT_NOW, "Not now", CAT)
933                .description("Closes the tip shown; it may show again another day.")
934                .when(shown)
935                .hidden(),
936            |call| {
937                service(call.app)?.not_now(call.app);
938                Ok(Json::Null)
939            },
940        )?
941        .command(
942            CommandSpec::new(CMD_TIPS_OFF, "Turn tips off", CAT)
943                .description("Shows no more tips (the tips.show setting)."),
944            |call| {
945                service(call.app)?.turn_off(call.app)?;
946                Ok(Json::Null)
947            },
948        )?
949        .command(
950            CommandSpec::new(CMD_TIPS_CURRENT, "The tip shown", CAT)
951                .description("The tip shown as a card (its id, title, text and target, null when none), and where its card and its target are.")
952                .hidden(),
953            |call| {
954                let tips = service(call.app)?;
955                Ok(match tips.current() {
956                    Some(t) => screen::describe(call.app, &t),
957                    None => Json::Null,
958                })
959            },
960        )?;
961        ctx.command(
962            CommandSpec::new(CMD_TIPS_BROWSE, "Tips…", CAT)
963                .description("Every tip, by the plugin that declared it, each plugin's with its own switch.")
964                .menu(crate::app::MENU_HELP, "1_tips", 0),
965            |call| {
966                let dialogs = call
967                    .app
968                    .service(&crate::dialogs::DIALOGS)
969                    .ok_or("the dialogs plugin is not connected")?;
970                let title = strings::tr(&call.app.egui(), &txt::TIPS_BROWSER);
971                let id = dialogs.open_custom(
972                    call.app,
973                    crate::dialogs::Custom::closing(&title),
974                    |ui, app, _| {
975                        ui.scroll_area(egui::ScrollArea::vertical()
976                            .auto_shrink([false, false])
977                            , |ui| browser::browser(ui, app));
978                    },
979                )?;
980                Ok(json!({ "dialog": id }))
981            },
982        )?
983        .command(
984            CommandSpec::new(CMD_TIPS_ORIGIN, "Turn a plugin's tips on or off", CAT)
985                .description("Turns the tips of one plugin (`origin`, its id) on or off (`on`), the others kept.")
986                .hidden()
987                .args(json!({ "origin": "photos", "on": false })),
988            |call| {
989                let origin = call
990                    .args
991                    .get("origin")
992                    .and_then(Json::as_str)
993                    .ok_or("`origin` is missing")?;
994                let on = call
995                    .args
996                    .get("on")
997                    .and_then(Json::as_bool)
998                    .ok_or("`on` is missing")?;
999                service(call.app)?.set_origin_on(call.app, origin, on)?;
1000                Ok(json!({ "origin": origin, "on": on }))
1001            },
1002        )?;
1003        // Escape closes the card, unless something else wants it.
1004        ctx.keybinding(
1005            "Escape",
1006            CMD_TIPS_NOT_NOW,
1007            "tipShown && !modePushed && !overlayOpen && !textInputFocus && !workbenchZen",
1008            Layer::Default,
1009        )?;
1010        ctx.app().set_context(CONTEXT_TIP_SHOWN, "false");
1011        ctx.on(On::Pass, |app, _| {
1012            if let Some(tips) = app.service(&TIPS) {
1013                tips.tick(app);
1014            }
1015        });
1016        // Drawn in every window, shown in the active one.
1017        ctx.block(
1018            zones::WINDOW_OVERLAYS,
1019            Block::add(BlockId::from_static("egui_pop.tips"), 19, screen::show),
1020        );
1021        Ok(())
1022    }
1023}
1024
1025/// The tips' service, or why it is missing.
1026fn service(app: &AppHandle) -> Result<std::sync::Arc<Tips>, String> {
1027    app.service(&TIPS)
1028        .ok_or_else(|| "the tips plugin is not connected".to_string())
1029}
1030
1031/// A tip's card: an icon, a heading, the text (in the inline subset:
1032/// emphasis, code, links), then the buttons `actions` draws: a note for
1033/// screen readers.
1034fn card(
1035    ui: &mut Ui,
1036    app: &AppHandle,
1037    heading: &str,
1038    title: &str,
1039    text: &str,
1040    actions: impl FnOnce(&mut Ui),
1041) {
1042    card_in(
1043        ui,
1044        app,
1045        egui::Shadow::NONE,
1046        heading,
1047        title,
1048        text,
1049        None::<fn(&mut Ui)>,
1050        actions,
1051    );
1052}
1053
1054/// [`card`] with a shadow, and `corner` drawn at the end of the heading
1055/// (a close button).
1056#[allow(
1057    clippy::too_many_arguments,
1058    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
1059)]
1060fn card_in(
1061    ui: &mut Ui,
1062    app: &AppHandle,
1063    shadow: egui::Shadow,
1064    heading: &str,
1065    title: &str,
1066    text: &str,
1067    corner: Option<impl FnOnce(&mut Ui)>,
1068    actions: impl FnOnce(&mut Ui),
1069) {
1070    Kit::of(ui.ctx())
1071        .tip_card
1072        .show(ui, kit::State::REST, shadow, |ui| {
1073            ui.ctx().accesskit_node_builder(ui.unique_id(), |node| {
1074                node.set_role(Role::Note);
1075            });
1076            ui.horizontal(|ui| {
1077                ui.add(Icon::Info.size(Size::Inline).tone(Tone::Info));
1078                ui.weak(heading);
1079                if let Some(corner) = corner {
1080                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), corner);
1081                }
1082            });
1083            ui.strong(title);
1084            crate::links::inline(ui, app, text);
1085            ui.horizontal_wrapped(actions);
1086        });
1087}
1088
1089/// Draws the tip of the day, when there is one to show (it needs
1090/// [`TipsPlugin`]). Returns whether a card was drawn.
1091pub fn tip_of_the_day(ui: &mut Ui, app: &AppHandle) -> bool {
1092    let Some(tips) = app.service(&TIPS) else {
1093        return false;
1094    };
1095    let Some(tip) = tips.of_the_day(app) else {
1096        return false;
1097    };
1098    let ctx = ui.ctx().clone();
1099    let left = tips.left(app).len();
1100    let at = lock(&tips.state).at % left.max(1) + 1;
1101    let heading = strings::tr(&ctx, &txt::TIPS_OF_THE_DAY);
1102    card(
1103        ui,
1104        app,
1105        &heading,
1106        &tip.title_in(&ctx),
1107        &tip.text_shown(&ctx, app),
1108        |ui| {
1109            let several = left > 1;
1110            if ui
1111                .add_enabled(
1112                    several,
1113                    egui::Button::new(strings::tr(&ctx, &txt::TIPS_PREVIOUS)),
1114                )
1115                .clicked()
1116            {
1117                tips.turn(app, true);
1118            }
1119            if ui
1120                .add_enabled(
1121                    several,
1122                    egui::Button::new(strings::tr(&ctx, &txt::TIPS_NEXT)),
1123                )
1124                .clicked()
1125            {
1126                tips.turn(app, false);
1127            }
1128            ui.weak(strings::tr_with(
1129                &ctx,
1130                &txt::TIPS_AT,
1131                &[("at", at.into()), ("count", left.into())],
1132            ));
1133            if ui.button(strings::tr(&ctx, &txt::TIPS_DONT_SHOW)).clicked()
1134                && let Err(e) = tips.dismiss(app, &tip.id)
1135            {
1136                log::warn!("tips: {e}");
1137            }
1138            if ui.button(strings::tr(&ctx, &strings::CLOSE)).clicked() {
1139                tips.close();
1140            }
1141        },
1142    );
1143    true
1144}
1145
1146/// Draws a contextual tip where it is called (it needs [`TipsPlugin`]),
1147/// unless tips are off or it was dismissed. Returns whether it was
1148/// drawn.
1149pub fn hint(ui: &mut Ui, app: &AppHandle, id: &str) -> bool {
1150    let Some(tips) = app.service(&TIPS) else {
1151        return false;
1152    };
1153    let Some(tip) = tips.get(id) else {
1154        return false;
1155    };
1156    if !tips.enabled(app) || tips.is_dismissed(app, id) || tips.off(app).contains(tip.origin_name())
1157    {
1158        return false;
1159    }
1160    let ctx = ui.ctx().clone();
1161    let heading = strings::tr(&ctx, &txt::TIPS_HINT);
1162    card(
1163        ui,
1164        app,
1165        &heading,
1166        &tip.title_in(&ctx),
1167        &tip.text_shown(&ctx, app),
1168        |ui| {
1169            let got = strings::tr(&ctx, &txt::TIPS_GOT_IT);
1170            let name = strings::tr_args(
1171                &ctx,
1172                &txt::TIPS_GOT_IT_NAME,
1173                &[("tip", &tip.title_in(&ctx))],
1174            );
1175            let r = ui.button(&got);
1176            egui_pop_core::a11y::name(&r, egui::Role::Button, &name);
1177            if r.clicked()
1178                && let Err(e) = tips.dismiss(app, id)
1179            {
1180                log::warn!("tips: {e}");
1181            }
1182        },
1183    );
1184    true
1185}