1mod 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
99pub const TIPS_PLUGIN: PluginId = PluginId::from_static("egui_pop.tips");
101
102pub const TIPS: ServiceToken<Tips> = ServiceToken::new("egui_pop.tips");
104
105pub const SETTING_TIPS_SHOW: SettingId = SettingId::from_static("tips.show");
107pub const SETTING_TIPS_DISMISSED: SettingId = SettingId::from_static("tips.dismissed");
109pub const SETTING_TIPS_SEEN: SettingId = SettingId::from_static("tips.seen");
112pub const SETTING_TIPS_USED: SettingId = SettingId::from_static("tips.used");
114pub const SETTING_TIPS_OFF: SettingId = SettingId::from_static("tips.off");
116
117pub 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
132pub const CONTEXT_TIP_SHOWN: &str = "tipShown";
134
135pub const FIRST_AFTER: f64 = 5.0;
137
138pub const TIP_KIND: &str = "tip";
140
141fn setting_path(id: &SettingId) -> String {
142 format!("settings/{id}")
143}
144
145pub use file::TipError;
146
147#[derive(Clone, Debug, PartialEq)]
149pub struct Tip {
150 pub id: String,
151 pub title: String,
152 pub text: String,
155 pub contextual: bool,
157 pub surface: String,
159 pub command: Option<CommandId>,
161 pub target: Option<String>,
163 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 pub fn contextual(mut self) -> Self {
183 self.contextual = true;
184 self
185 }
186
187 pub fn surface(mut self, when: &str) -> Self {
189 self.surface = when.into();
190 self
191 }
192
193 pub fn command(mut self, command: CommandId) -> Self {
195 self.command = Some(command);
196 self
197 }
198
199 pub fn target(mut self, name: &str) -> Self {
201 self.target = Some(name.into());
202 self
203 }
204
205 pub fn origin(mut self, origin: &str) -> Self {
207 self.origin = origin.into();
208 self
209 }
210
211 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 pub fn parse(file: &str, source: &str) -> Result<Tip, TipError> {
222 file::parse(file, source)
223 }
224
225 pub fn title_in(&self, ctx: &egui::Context) -> String {
227 strings::declared(ctx, TIP_KIND, &self.id, Some("title"), &self.title)
228 }
229
230 pub fn text_in(&self, ctx: &egui::Context) -> String {
232 strings::declared(ctx, TIP_KIND, &self.id, Some("text"), &self.text)
233 }
234
235 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
277fn 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 at: usize,
299 closed: bool,
301 current: Option<String>,
303 auto: bool,
305 started: Option<f64>,
307 first_done: bool,
309 entered: BTreeSet<String>,
311 read_to: Seq,
313 clock: Clock,
314}
315
316#[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#[derive(Debug, Default)]
332pub struct Tips {
333 state: Mutex<State>,
334}
335
336impl Tips {
337 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 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 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 pub fn set_auto(&self, on: bool) {
376 lock(&self.state).auto = on;
377 }
378
379 pub fn auto(&self) -> bool {
381 lock(&self.state).auto
382 }
383
384 pub fn set_clock(&self, clock: SharedClock) {
386 lock(&self.state).clock = Clock(Some(clock));
387 }
388
389 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 pub fn used(&self, app: &AppHandle) -> BTreeSet<String> {
423 pick::read_ids(&Self::text_setting(app, &SETTING_TIPS_USED))
424 }
425
426 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 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 pub fn off(&self, app: &AppHandle) -> BTreeSet<String> {
456 pick::read_ids(&Self::text_setting(app, &SETTING_TIPS_OFF))
457 }
458
459 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 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 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 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 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 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 pub fn show_next(&self, app: &AppHandle) -> Option<Tip> {
572 self.show_next_where(app, |_| true)
573 }
574
575 pub fn not_now(&self, app: &AppHandle) {
578 self.set_current(app, None);
579 }
580
581 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 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 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 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 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 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 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 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 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 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 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 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 pub fn close(&self) {
793 lock(&self.state).closed = true;
794 }
795}
796
797#[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 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 ctx.block(
1018 zones::WINDOW_OVERLAYS,
1019 Block::add(BlockId::from_static("egui_pop.tips"), 19, screen::show),
1020 );
1021 Ok(())
1022 }
1023}
1024
1025fn 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
1031fn 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#[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
1089pub 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
1146pub 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}