1pub mod lint;
59
60use std::cell::{Cell, RefCell};
61use std::collections::{BTreeMap, VecDeque};
62use std::sync::{Arc, Mutex};
63
64use egui::{Response, RichText, Ui};
65use egui_pop_core::debug::FnCollector;
66use egui_pop_core::lock;
67use egui_pop_core::strings;
68use egui_pop_model::commands::{CommandSpec, Origin};
69use egui_pop_model::ids::{CommandId, OwnerId, PluginId, StepId};
70use serde::Serialize;
71use serde_json::{Value as Json, json};
72
73use crate::app::AppHandle;
74use crate::clipboard::{self, ClipSource, CopyRequest};
75use crate::dialogs::{self, Custom, DIALOGS};
76use crate::hooks::{Lifecycle, On};
77use crate::host::{Pending, source_of};
78use crate::services::ServiceToken;
79use crate::steps::{Before, Outcome, StepSpec};
80use crate::strings as txt;
81use crate::toasts::{TOASTS, Toast};
82use crate::{Ctx, Plugin, PluginError};
83
84pub use egui_pop_model::links::{
85 Caps, Decision, Facts, How, Kind, Policy, Reason, Request, Source, Target,
86};
87
88pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.links");
90
91pub const LINKS: ServiceToken<Links> = ServiceToken::new("app.links");
93
94pub const STEP_OPEN: StepId = StepId::from_static("link.open");
101
102pub const CMD_OPEN: CommandId = CommandId::from_static("links.open");
105pub const CMD_CHECK: CommandId = CommandId::from_static("links.check");
108pub const CMD_COPY: CommandId = CommandId::from_static("links.copy");
110pub const CMD_REVEAL: CommandId = CommandId::from_static("files.reveal");
112pub const CMD_CONFIRMED: CommandId = CommandId::from_static("links.confirmed");
115
116pub const ENDPOINT: &str = "egui_pop.links";
118
119pub const AGENT_QUEUE: usize = 5;
121pub const RECENT: usize = 32;
123
124const NO_PLUGIN: &str = "no links service: the LinksPlugin is not connected";
125
126#[derive(Debug)]
128pub enum Opening {
129 Done(Result<(), String>),
131 Later(Pending),
133}
134
135#[derive(Clone, Copy, Debug)]
137pub struct OpenCall<'a> {
138 pub target: &'a Target,
139 pub how: How,
143 pub kind: Kind,
144 pub source: Source,
145 pub origin: &'a Origin,
146 pub egui: &'a egui::Context,
148}
149
150pub trait Opener: Send + Sync {
154 fn name(&self) -> &str;
156
157 fn caps(&self) -> Caps;
159
160 fn open(&self, call: &OpenCall<'_>) -> Opening;
163}
164
165pub trait Inside: Send + Sync {
173 fn name(&self) -> &str;
175
176 fn show(&self, app: &AppHandle, call: &OpenCall<'_>) -> Result<(), String>;
178
179 fn docs_pages(&self) -> Option<Vec<String>> {
182 None
183 }
184
185 fn plays_video(&self) -> bool {
188 false
189 }
190
191 fn plays_web_video(&self) -> bool {
194 false
195 }
196}
197
198#[derive(Clone, Copy, Debug, Default)]
204pub struct EguiOpener;
205
206impl Opener for EguiOpener {
207 fn name(&self) -> &str {
208 "egui"
209 }
210
211 fn caps(&self) -> Caps {
212 Caps::WEB
213 }
214
215 fn open(&self, call: &OpenCall<'_>) -> Opening {
216 if call.how != How::Outside || call.target.scheme() == "file" {
217 return Opening::Done(Err("egui's opener opens web pages and mail only".into()));
218 }
219 let new_tab = call.target.scheme() != "mailto";
220 emit_approved(call.egui, call.target.as_str(), new_tab);
221 Opening::Done(Ok(()))
222 }
223}
224
225pub fn emit_approved(ctx: &egui::Context, url: &str, new_tab: bool) {
228 ctx.with_plugin(|i: &mut Interceptor| {
229 i.approved.push(url.to_string());
230 if i.approved.len() > 16 {
231 i.approved.remove(0);
232 }
233 });
234 ctx.open_url(egui::OpenUrl {
235 url: url.to_string(),
236 new_tab,
237 });
238}
239
240#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
242pub struct Record {
243 pub target: String,
244 pub how: How,
245 pub kind: Kind,
246 pub source: Source,
247 pub origin: String,
249}
250
251#[derive(Debug)]
252struct Recording {
253 records: Vec<Record>,
254 answer: Result<(), String>,
255 caps: Caps,
256}
257
258#[derive(Clone, Debug)]
262pub struct RecordingOpener(Arc<Mutex<Recording>>);
263
264impl Default for RecordingOpener {
265 fn default() -> Self {
266 Self(Arc::new(Mutex::new(Recording {
267 records: Vec::new(),
268 answer: Ok(()),
269 caps: Caps::ALL,
270 })))
271 }
272}
273
274impl RecordingOpener {
275 pub fn fail(&self, reason: Option<&str>) {
277 lock(&self.0).answer = reason.map_or(Ok(()), |r| Err(r.to_string()));
278 }
279
280 pub fn set_caps(&self, caps: Caps) {
282 lock(&self.0).caps = caps;
283 }
284
285 pub fn records(&self) -> Vec<Record> {
287 lock(&self.0).records.clone()
288 }
289
290 pub fn clear(&self) {
291 lock(&self.0).records.clear();
292 }
293}
294
295impl Opener for RecordingOpener {
296 fn name(&self) -> &str {
297 "recording"
298 }
299
300 fn caps(&self) -> Caps {
301 lock(&self.0).caps
302 }
303
304 fn open(&self, call: &OpenCall<'_>) -> Opening {
305 let mut r = lock(&self.0);
306 r.records.push(Record {
307 target: call.target.as_str().to_string(),
308 how: call.how,
309 kind: call.kind,
310 source: call.source,
311 origin: source_of(call.origin),
312 });
313 Opening::Done(r.answer.clone())
314 }
315}
316
317type ForwardFn = Arc<dyn Fn(&OpenCall<'_>) -> Opening + Send + Sync>;
318
319#[derive(Clone)]
323pub struct NullOpener {
324 reason: String,
325 forward: Option<ForwardFn>,
326}
327
328impl std::fmt::Debug for NullOpener {
329 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
330 f.debug_struct("NullOpener")
331 .field("reason", &self.reason)
332 .field("forwards", &self.forward.is_some())
333 .finish()
334 }
335}
336
337impl Default for NullOpener {
338 fn default() -> Self {
339 Self {
340 reason: "no interface to open it in".into(),
341 forward: None,
342 }
343 }
344}
345
346impl NullOpener {
347 pub fn new(reason: &str) -> Self {
349 Self {
350 reason: reason.into(),
351 forward: None,
352 }
353 }
354
355 pub fn forward(f: impl Fn(&OpenCall<'_>) -> Opening + Send + Sync + 'static) -> Self {
358 Self {
359 reason: String::new(),
360 forward: Some(Arc::new(f)),
361 }
362 }
363}
364
365impl Opener for NullOpener {
366 fn name(&self) -> &str {
367 if self.forward.is_some() {
368 "forward"
369 } else {
370 "null"
371 }
372 }
373
374 fn caps(&self) -> Caps {
375 Caps {
377 inside: false,
378 ..Caps::ALL
379 }
380 }
381
382 fn open(&self, call: &OpenCall<'_>) -> Opening {
383 match &self.forward {
384 Some(f) => f(call),
385 None => Opening::Done(Err(self.reason.clone())),
386 }
387 }
388}
389
390pub struct Links {
393 opener: Mutex<Arc<dyn Opener>>,
394 policy: Mutex<Policy>,
395 inside: Mutex<Option<Arc<dyn Inside>>>,
396}
397
398impl std::fmt::Debug for Links {
399 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
400 f.debug_struct("Links")
401 .field("opener", &self.opener().name())
402 .field("inside", &self.inside().map(|i| i.name().to_string()))
403 .field("policy", &self.policy())
404 .finish()
405 }
406}
407
408impl Links {
409 pub fn new(opener: Arc<dyn Opener>, policy: Policy) -> Self {
410 Self {
411 opener: Mutex::new(opener),
412 policy: Mutex::new(policy),
413 inside: Mutex::new(None),
414 }
415 }
416
417 pub fn inside(&self) -> Option<Arc<dyn Inside>> {
419 lock(&self.inside).clone()
420 }
421
422 pub fn set_inside(&self, inside: Option<Arc<dyn Inside>>) {
425 *lock(&self.inside) = inside;
426 }
427
428 pub fn caps(&self) -> Caps {
431 let mut caps = self.opener().caps();
432 match self.inside() {
433 Some(inside) => {
434 caps.inside = true;
435 caps.video = inside.plays_video();
436 caps.web_video = inside.plays_web_video();
437 }
438 None => {
439 caps.video &= caps.inside;
440 caps.web_video &= caps.inside;
441 }
442 }
443 caps
444 }
445
446 pub fn opener(&self) -> Arc<dyn Opener> {
448 lock(&self.opener).clone()
449 }
450
451 pub fn set_opener(&self, opener: Arc<dyn Opener>) {
453 *lock(&self.opener) = opener;
454 }
455
456 pub fn policy(&self) -> Policy {
458 lock(&self.policy).clone()
459 }
460
461 pub fn update_policy(&self, f: impl FnOnce(&mut Policy)) {
464 f(&mut lock(&self.policy));
465 }
466
467 pub fn trust(&self, host: &str) {
470 lock(&self.policy).trust(host);
471 }
472}
473
474#[derive(Debug, Default)]
478pub struct Interceptor {
479 active: bool,
480 approved: Vec<String>,
481 taken: Vec<egui::OpenUrl>,
482}
483
484impl egui::Plugin for Interceptor {
485 fn debug_name(&self) -> &'static str {
486 "egui_pop.links"
487 }
488
489 fn output_hook(&mut self, ctx: &egui::Context, output: &mut egui::FullOutput) {
490 if !self.active {
491 return;
492 }
493 let (approved, taken) = (&mut self.approved, &mut self.taken);
494 let before = taken.len();
495 output.platform_output.commands.retain(|c| match c {
496 egui::OutputCommand::OpenUrl(u) => {
497 if let Some(i) = approved.iter().position(|a| *a == u.url) {
498 approved.remove(i);
499 true
500 } else {
501 taken.push(u.clone());
502 false
503 }
504 }
505 _ => true,
506 });
507 if taken.len() > before {
508 ctx.request_repaint();
509 }
510 }
511}
512
513#[derive(Clone, Debug)]
515struct Asking {
516 request: Request,
517 decision: Decision,
518 dialog: Option<u64>,
521 answered: bool,
523}
524
525struct Waiting {
527 summary: Json,
528 pending: Pending,
529 toast: bool,
530}
531
532#[derive(Default)]
533struct State {
534 connected: Cell<bool>,
535 next: Cell<u64>,
536 asking: RefCell<BTreeMap<u64, Asking>>,
537 accepted: RefCell<Vec<u64>>,
539 queued: RefCell<BTreeMap<String, VecDeque<u64>>>,
541 opening: RefCell<Vec<Waiting>>,
542 recent: RefCell<VecDeque<Json>>,
543 declared: RefCell<Vec<(OwnerId, String, String)>>,
545 seen: RefCell<BTreeMap<String, String>>,
547 copying: RefCell<String>,
549}
550
551fn state(app: &AppHandle) -> std::rc::Rc<State> {
552 app.local::<State>()
553}
554
555pub fn links(app: &AppHandle) -> Option<Arc<Links>> {
557 app.service(&LINKS)
558}
559
560pub fn facts_of(target: &Target) -> Option<Facts> {
562 let path = target.local_path()?;
563 read_facts(&path)
564}
565
566#[cfg(not(target_arch = "wasm32"))]
567fn read_facts(path: &str) -> Option<Facts> {
568 Some(match std::fs::metadata(path) {
569 Ok(m) => Facts {
570 exists: true,
571 dir: m.is_dir(),
572 executable: m.is_file() && executable_bit(&m) && !has_extension(path),
573 },
574 Err(_) => Facts::default(),
575 })
576}
577
578#[cfg(target_arch = "wasm32")]
579fn read_facts(_: &str) -> Option<Facts> {
580 None
581}
582
583#[cfg(not(target_arch = "wasm32"))]
587fn has_extension(path: &str) -> bool {
588 std::path::Path::new(path).extension().is_some()
589}
590
591#[cfg(unix)]
592fn executable_bit(m: &std::fs::Metadata) -> bool {
593 use std::os::unix::fs::PermissionsExt as _;
594 m.permissions().mode() & 0o111 != 0
595}
596
597#[cfg(all(not(unix), not(target_arch = "wasm32")))]
598fn executable_bit(_: &std::fs::Metadata) -> bool {
599 false
600}
601
602pub fn decide(app: &AppHandle, request: &Request) -> Result<Decision, String> {
605 let links = links(app).ok_or(NO_PLUGIN)?;
606 let facts = Target::parse(&request.target)
607 .ok()
608 .and_then(|t| facts_of(&t));
609 Ok(links
610 .policy()
611 .decide(request, &links.caps(), facts.as_ref()))
612}
613
614pub fn open(app: &AppHandle, request: Request) -> Outcome {
619 run(app, request, false, None)
620}
621
622pub fn dry_run(app: &AppHandle, request: Request) -> Outcome {
625 run(app, request, true, None)
626}
627
628fn run(app: &AppHandle, request: Request, dry_run: bool, confirmed: Option<u64>) -> Outcome {
629 let origin = request.origin.clone();
630 let mut args = serde_json::to_value(&request).unwrap_or(Json::Null);
631 args["origin"] = json!(source_of(&origin));
632 args["dry_run"] = json!(dry_run);
633 if let Some(id) = confirmed {
634 args["confirmed"] = json!(id);
635 }
636 let who = origin.clone();
637 let out = app.step(&STEP_OPEN, args.clone(), move |app, args| {
638 let mut req: Request =
639 serde_json::from_value(args.clone()).map_err(|e| format!("a link: {e}"))?;
640 req.origin = who.clone();
641 let dry = args["dry_run"].as_bool().unwrap_or(false);
642 let confirmed = args["confirmed"].as_u64();
643 run_default(app, req, dry, confirmed)
644 });
645 let toast = origin == Origin::User || confirmed.is_some();
646 if let Outcome::Vetoed { reason, .. } = &out
647 && toast
648 && !dry_run
649 {
650 fail_toast(app, &request.target, reason, false);
651 }
652 remember(app, &args, &out);
653 out
654}
655
656fn run_default(
657 app: &AppHandle,
658 req: Request,
659 dry: bool,
660 confirmed: Option<u64>,
661) -> Result<Json, String> {
662 let links = links(app).ok_or(NO_PLUGIN)?;
663 let opener = links.opener();
664 let caps = links.caps();
665 let target = Target::parse(&req.target).ok();
666 let facts = target.as_ref().and_then(facts_of);
667 let policy = links.policy();
668 let d = policy.decide(&req, &caps, facts.as_ref());
669 let mut summary = json!({
670 "target": d.target,
671 "kind": d.kind,
672 "how": d.how,
673 "source": req.source,
674 "origin": source_of(&req.origin),
675 "confirm": d.confirm,
676 "why": d.why,
677 "refused": d.refused.as_ref().map(ToString::to_string),
678 "reveal_instead": d.reveal_instead,
679 "host": d.host,
680 "disguised": d.disguised,
681 "opener": opener.name(),
682 "inside": links.inside().map(|i| i.name().to_string()),
683 });
684 if dry {
685 summary["dry_run"] = json!(true);
686 summary["status"] = json!(match (&d.refused, d.confirm) {
687 (Some(_), _) => "refused",
688 (None, true) => "would_ask",
689 (None, false) => "would_open",
690 });
691 return Ok(summary);
692 }
693 let toast = req.origin == Origin::User || confirmed.is_some();
694 if let Some(reason) = &d.refused {
695 let reason = reason.to_string();
696 app.publish(
697 &source_of(&req.origin),
698 None,
699 "link.refused",
700 json!({ "target": d.target, "reason": reason }),
701 );
702 if toast {
703 fail_toast(app, &req.target, &reason, d.reveal_instead);
704 }
705 return Err(reason);
706 }
707 let st = state(app);
708 let was_accepted = confirmed.is_some_and(|id| {
709 let mut acc = st.accepted.borrow_mut();
710 match acc.iter().position(|a| *a == id) {
711 Some(i) => {
712 acc.remove(i);
713 true
714 }
715 None => false,
716 }
717 });
718 if d.confirm && !was_accepted {
719 return ask(app, req, d, summary);
720 }
721 let target = target.ok_or("a link that does not parse")?;
722 perform(
723 app,
724 &req,
725 &d,
726 &target,
727 &policy,
728 Openers {
729 opener: opener.as_ref(),
730 inside: links.inside(),
731 },
732 summary,
733 toast,
734 )
735}
736
737struct Openers<'a> {
739 opener: &'a dyn Opener,
740 inside: Option<Arc<dyn Inside>>,
741}
742
743#[allow(
744 clippy::too_many_arguments,
745 reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
746)]
747fn perform(
748 app: &AppHandle,
749 req: &Request,
750 d: &Decision,
751 target: &Target,
752 policy: &Policy,
753 openers: Openers<'_>,
754 mut summary: Json,
755 toast: bool,
756) -> Result<Json, String> {
757 let who = source_of(&req.origin);
758 let opener = openers.opener;
759 let ctx = app.egui();
760 let call = OpenCall {
761 target,
762 how: d.how,
763 kind: d.kind,
764 source: req.source,
765 origin: &req.origin,
766 egui: &ctx,
767 };
768 if d.how == How::Inside
769 && matches!(
770 d.kind,
771 Kind::Doc | Kind::Markdown | Kind::Html | Kind::Image | Kind::Video
772 )
773 {
774 let shown = match &openers.inside {
776 Some(inside) => inside.show(app, &call),
777 None => match opener.open(&call) {
778 Opening::Done(r) => r,
779 Opening::Later(_) => Err("the opener answers later for a page inside".into()),
780 },
781 };
782 return match shown {
783 Ok(()) => {
784 app.publish(&who, None, "link.opened", summary.clone());
785 summary["status"] = json!("opened");
786 Ok(summary)
787 }
788 Err(e) => {
789 failed(app, &summary, &e, toast);
790 Err(e)
791 }
792 };
793 }
794 if d.how == How::Inside {
795 let (command, args) = match d.kind {
796 Kind::AppLink => (
797 CommandId::from_static("deeplink.open"),
798 json!({ "url": target.as_str() }),
799 ),
800 Kind::Command => {
801 let (id, args) = target.command().ok_or("a command link names no command")?;
802 let id = CommandId::new(id.clone()).map_err(|e| format!("`{id}`: {e}"))?;
803 (id, args)
804 }
805 _ => return Err("no viewer inside the application for this link".into()),
806 };
807 if !app.commands().iter().any(|(s, _)| s.id == command) {
808 let e = format!("nothing handles it: no command `{command}`");
809 if toast {
810 fail_toast(app, &req.target, &e, false);
811 }
812 return Err(e);
813 }
814 app.run_as(command, args, req.origin.clone());
815 app.publish(&who, None, "link.opened", summary.clone());
816 summary["status"] = json!("opened");
817 return Ok(summary);
818 }
819 let online;
821 let target = match (d.kind, target.doc_page()) {
822 (Kind::Doc, Some(page)) => {
823 let url = policy
824 .docs_url(&page)
825 .ok_or("this page has no online copy")?;
826 online = Target::parse(&url).map_err(|e| e.to_string())?;
827 &online
828 }
829 _ => target,
830 };
831 let call = OpenCall { target, ..call };
832 match opener.open(&call) {
833 Opening::Done(Ok(())) => {
834 app.publish(&who, None, "link.opened", summary.clone());
835 summary["status"] = json!("opened");
836 Ok(summary)
837 }
838 Opening::Done(Err(e)) => {
839 failed(app, &summary, &e, toast);
840 Err(e)
841 }
842 Opening::Later(pending) => {
843 state(app).opening.borrow_mut().push(Waiting {
844 summary: summary.clone(),
845 pending,
846 toast,
847 });
848 summary["status"] = json!("opening");
849 Ok(summary)
850 }
851 }
852}
853
854fn failed(app: &AppHandle, summary: &Json, error: &str, toast: bool) {
855 let mut data = summary.clone();
856 data["error"] = json!(error);
857 let who = summary["origin"].as_str().unwrap_or("user").to_string();
858 app.publish(&who, None, "link.failed", data);
859 if toast {
860 let target = summary["target"].as_str().unwrap_or_default().to_string();
861 fail_toast(app, &target, error, false);
862 }
863}
864
865fn fail_toast(app: &AppHandle, target: &str, reason: &str, reveal: bool) {
868 let Some(t) = app.service(&TOASTS) else {
869 return;
870 };
871 let ctx = app.egui();
872 let text = strings::tr_args(&ctx, &txt::LINKS_NOT_OPENED, &[("reason", reason)]);
873 let toast = Toast::warning(&text);
874 t.notify(if reveal {
875 toast.action(
876 &strings::tr(&ctx, &txt::LINKS_REVEAL),
877 CMD_REVEAL,
878 json!({ "path": target }),
879 )
880 } else {
881 toast.action(
882 &strings::tr(&ctx, &txt::LINKS_COPY),
883 CMD_COPY,
884 json!({ "target": target }),
885 )
886 });
887}
888
889fn session(origin: &Origin) -> Option<String> {
892 (*origin != Origin::User).then(|| source_of(origin))
893}
894
895fn ask(app: &AppHandle, req: Request, d: Decision, mut summary: Json) -> Result<Json, String> {
896 let st = state(app);
897 let id = st.next.get() + 1;
898 st.next.set(id);
899 let who = source_of(&req.origin);
900 if let Some(s) = session(&req.origin) {
902 let busy = st
903 .asking
904 .borrow()
905 .values()
906 .any(|a| a.dialog.is_some() && session(&a.request.origin).as_deref() == Some(&s));
907 if busy {
908 let mut queued = st.queued.borrow_mut();
909 let q = queued.entry(s.clone()).or_default();
910 if q.len() >= AGENT_QUEUE {
911 return Err(format!(
912 "`{s}` has {AGENT_QUEUE} link requests waiting already: answer them first"
913 ));
914 }
915 q.push_back(id);
916 let position = q.len();
917 drop(queued);
918 st.asking.borrow_mut().insert(
919 id,
920 Asking {
921 request: req,
922 decision: d,
923 dialog: None,
924 answered: false,
925 },
926 );
927 summary["status"] = json!("queued");
928 summary["id"] = json!(id);
929 summary["position"] = json!(position);
930 app.publish(&who, None, "link.asked", summary.clone());
931 return Ok(summary);
932 }
933 }
934 let dialog = show_confirm(app, id, &req, &d)?;
935 st.asking.borrow_mut().insert(
936 id,
937 Asking {
938 request: req,
939 decision: d,
940 dialog: Some(dialog),
941 answered: false,
942 },
943 );
944 summary["status"] = json!("asked");
945 summary["id"] = json!(id);
946 app.publish(&who, None, "link.asked", summary.clone());
947 Ok(summary)
948}
949
950fn show_confirm(app: &AppHandle, id: u64, req: &Request, d: &Decision) -> Result<u64, String> {
954 let dialogs = app
955 .service(&DIALOGS)
956 .ok_or("this link needs a confirmation, and the dialogs plugin is not connected")?;
957 let ctx = app.egui();
958 let target = Target::parse(&req.target).map_err(|e| e.to_string())?;
959 let shown = target.shown();
960 let title = match (&req.origin, d.how, d.kind) {
961 (Origin::Agent(name), _, _) => {
962 strings::tr_args(&ctx, &txt::LINKS_CONFIRM_AGENT, &[("agent", name)])
963 }
964 (o, _, _) if *o != Origin::User => {
965 strings::tr_args(&ctx, &txt::LINKS_CONFIRM_AGENT, &[("agent", &source_of(o))])
966 }
967 (_, How::Reveal, _) => strings::tr(&ctx, &txt::LINKS_CONFIRM_REVEAL),
968 (_, _, Kind::File | Kind::Image | Kind::Video | Kind::Folder)
969 if target.scheme() == "file" =>
970 {
971 strings::tr(&ctx, &txt::LINKS_CONFIRM_FILE)
972 }
973 _ => strings::tr(&ctx, &txt::LINKS_CONFIRM_TITLE),
974 };
975 let verb = if d.how == How::Reveal {
976 strings::tr(&ctx, &txt::LINKS_REVEAL)
977 } else {
978 strings::tr(&ctx, &txt::LINKS_OPEN)
979 };
980 let host = d.host.clone();
981 let trust_host = (req.source == Source::Content && d.why.as_deref() == Some("untrusted host"))
982 .then(|| d.host_ascii.clone())
983 .flatten();
984 let disguised = d.disguised.then(|| req.label.clone().unwrap_or_default());
985 let content = req.source == Source::Content;
986 let mut trust = false;
987 let spec = Custom::new(&title, &verb, CMD_CONFIRMED)
988 .args(json!({ "id": id }))
989 .size(480.0, 132.0);
990 let copy_target = req.target.clone();
991 let description = json!({
992 "target": shown,
993 "host": host,
994 "why": d.why,
995 "disguised": disguised,
996 "trust": trust_host,
997 });
998 dialogs.open_custom(app, spec, move |ui, app, pass| {
999 ui.label(RichText::new(&shown).monospace());
1000 if let Some(h) = &host {
1001 ui.label(strings::tr_args(ui.ctx(), &txt::LINKS_HOST, &[("host", h)]));
1002 }
1003 if let Some(label) = &disguised {
1004 ui.label(strings::tr_args(
1005 ui.ctx(),
1006 &txt::LINKS_CONFIRM_DISGUISED,
1007 &[("label", label)],
1008 ));
1009 } else if content {
1010 ui.weak(strings::tr(ui.ctx(), &txt::LINKS_CONFIRM_CONTENT));
1011 }
1012 ui.horizontal(|ui| {
1013 if let Some(h) = &trust_host {
1014 let text = strings::tr_args(ui.ctx(), &txt::LINKS_TRUST, &[("host", h)]);
1015 if ui.checkbox(&mut trust, text).changed() {
1016 pass.value("trust", json!(trust));
1017 }
1018 }
1019 if ui.button(strings::tr(ui.ctx(), &txt::LINKS_COPY)).clicked() {
1020 copy_link(app, ©_target, &Origin::User);
1021 }
1022 });
1023 pass.describe(description.clone());
1024 })
1025}
1026
1027fn confirmed(app: &AppHandle, args: &Json, origin: &Origin) -> Result<Json, String> {
1030 if *origin != Origin::User {
1031 return Err("only the user answers a link's confirmation".into());
1032 }
1033 let id = args["id"].as_u64().ok_or("`id` is missing")?;
1034 let st = state(app);
1035 let asking = st
1036 .asking
1037 .borrow_mut()
1038 .remove(&id)
1039 .ok_or_else(|| format!("no link waits for an answer under {id}"))?;
1040 if args["trust"].as_bool() == Some(true)
1041 && let (Some(links), Some(host)) = (links(app), &asking.decision.host_ascii)
1042 {
1043 links.trust(host);
1044 }
1045 st.accepted.borrow_mut().push(id);
1046 let out = run(app, asking.request.clone(), false, Some(id));
1047 next_of(app, &asking.request.origin);
1048 match out {
1049 Outcome::Done(r) => r,
1050 Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
1051 }
1052}
1053
1054fn cancelled(app: &AppHandle, id: u64) {
1057 let st = state(app);
1058 let Some(asking) = st.asking.borrow_mut().remove(&id) else {
1059 return;
1060 };
1061 let who = source_of(&asking.request.origin);
1062 app.publish(
1063 &who,
1064 None,
1065 "link.cancelled",
1066 json!({ "id": id, "target": asking.decision.target, "origin": who }),
1067 );
1068 remember(
1069 app,
1070 &json!({ "target": asking.request.target, "origin": who, "how": asking.request.how, "source": asking.request.source }),
1071 &Outcome::Done(Ok(json!({ "status": "cancelled" }))),
1072 );
1073 next_of(app, &asking.request.origin);
1074}
1075
1076fn next_of(app: &AppHandle, origin: &Origin) {
1078 let Some(s) = session(origin) else {
1079 return;
1080 };
1081 let st = state(app);
1082 loop {
1083 let next = st
1084 .queued
1085 .borrow_mut()
1086 .get_mut(&s)
1087 .and_then(VecDeque::pop_front);
1088 let Some(id) = next else {
1089 return;
1090 };
1091 let item = st.asking.borrow().get(&id).cloned();
1092 let Some(item) = item else {
1093 continue;
1094 };
1095 match show_confirm(app, id, &item.request, &item.decision) {
1096 Ok(dialog) => {
1097 if let Some(a) = st.asking.borrow_mut().get_mut(&id) {
1098 a.dialog = Some(dialog);
1099 }
1100 return;
1101 }
1102 Err(_) => {
1103 st.asking.borrow_mut().remove(&id);
1104 }
1105 }
1106 }
1107}
1108
1109pub fn copy_link(app: &AppHandle, target: &str, origin: &Origin) {
1113 let st = state(app);
1114 *st.copying.borrow_mut() = target.to_string();
1115 if clipboard::with_owner(app, |_| ()).is_some() {
1116 clipboard::copy(app, CopyRequest::new(ENDPOINT), origin);
1117 } else {
1118 app.egui().copy_text(target.to_string());
1119 }
1120}
1121
1122struct LinkSource;
1124
1125impl ClipSource for LinkSource {
1126 fn copy(&self, app: &AppHandle) -> Option<clipboard::ClipItem> {
1127 let target = state(app).copying.borrow().clone();
1128 (!target.is_empty()).then(|| {
1129 clipboard::ClipItem::new(clipboard::URI_LIST, 1, json!(target), "a link")
1130 .fallback(clipboard::TEXT, json!(target))
1131 })
1132 }
1133}
1134
1135fn remember(app: &AppHandle, args: &Json, out: &Outcome) {
1136 let (status, error) = match out {
1137 Outcome::Done(Ok(v)) => (v["status"].as_str().unwrap_or("done").to_string(), None),
1138 Outcome::Done(Err(e)) => ("failed".to_string(), Some(e.clone())),
1139 Outcome::Vetoed { by, reason } => ("vetoed".to_string(), Some(format!("{by}: {reason}"))),
1140 };
1141 let decision = match out {
1142 Outcome::Done(Ok(v)) => {
1143 json!({ "kind": v["kind"], "how": v["how"], "confirm": v["confirm"], "why": v["why"] })
1144 }
1145 _ => Json::Null,
1146 };
1147 let entry = json!({
1148 "target": args["target"],
1149 "how": args["how"],
1150 "source": args["source"],
1151 "origin": args["origin"],
1152 "dry_run": args["dry_run"],
1153 "status": status,
1154 "error": error,
1155 "decision": decision,
1156 });
1157 let st = state(app);
1158 let mut recent = st.recent.borrow_mut();
1159 recent.push_back(entry);
1160 while recent.len() > RECENT {
1161 recent.pop_front();
1162 }
1163}
1164
1165pub fn recent(app: &AppHandle) -> Vec<Json> {
1168 state(app).recent.borrow().iter().cloned().collect()
1169}
1170
1171pub fn declare(app: &AppHandle, place: &str, target: &str) {
1174 state(app).declared.borrow_mut().push((
1175 OwnerId::from_static("app"),
1176 place.into(),
1177 target.into(),
1178 ));
1179}
1180
1181pub fn declared(app: &AppHandle) -> Vec<(String, String)> {
1184 let st = state(app);
1185 let mut out: Vec<(String, String)> = st
1186 .declared
1187 .borrow()
1188 .iter()
1189 .map(|(_, p, t)| (p.clone(), t.clone()))
1190 .collect();
1191 out.extend(
1192 st.seen
1193 .borrow()
1194 .iter()
1195 .map(|(t, l)| (format!("drawn: {l}"), t.clone())),
1196 );
1197 out
1198}
1199
1200fn pass(app: &AppHandle) {
1204 if !state(app).connected.get() {
1205 return;
1206 }
1207 let ctx = app.egui();
1208 if ctx.with_plugin(|_: &mut Interceptor| ()).is_none() {
1209 ctx.add_plugin(Interceptor::default());
1210 }
1211 let taken = ctx
1212 .with_plugin(|i: &mut Interceptor| {
1213 i.active = true;
1214 std::mem::take(&mut i.taken)
1215 })
1216 .unwrap_or_default();
1217 for u in taken {
1218 let declared = ["http:", "https:", "mailto:"]
1221 .iter()
1222 .any(|s| u.url.to_ascii_lowercase().starts_with(s));
1223 let source = if declared {
1224 Source::Declared
1225 } else {
1226 Source::Content
1227 };
1228 open(app, Request::new(&u.url).source(source));
1229 }
1230 let st = state(app);
1231 let done: Vec<(Json, Result<Json, String>, bool)> = {
1232 let mut opening = st.opening.borrow_mut();
1233 let mut out = Vec::new();
1234 opening.retain(|o| match o.pending.take() {
1235 Some(r) => {
1236 out.push((o.summary.clone(), r, o.toast));
1237 false
1238 }
1239 None => true,
1240 });
1241 out
1242 };
1243 for (summary, result, toast) in done {
1244 match result {
1245 Ok(_) => {
1246 let who = summary["origin"].as_str().unwrap_or("user").to_string();
1247 app.publish(&who, None, "link.opened", summary);
1248 }
1249 Err(e) => failed(app, &summary, &e, toast),
1250 }
1251 }
1252 if let Some(d) = app.service(&DIALOGS) {
1254 let gone: Vec<u64> = st
1255 .asking
1256 .borrow()
1257 .iter()
1258 .filter(|(_, a)| !a.answered && a.dialog.is_some_and(|id| !d.is_open(id)))
1259 .map(|(id, _)| *id)
1260 .collect();
1261 for id in gone {
1262 cancelled(app, id);
1263 }
1264 }
1265}
1266
1267fn describe(app: &AppHandle) -> Json {
1269 let st = state(app);
1270 let (opener, inside, caps, policy) = match links(app) {
1271 Some(l) => (
1272 json!(l.opener().name()),
1273 json!(l.inside().map(|i| i.name().to_string())),
1274 json!(l.caps()),
1275 json!(l.policy()),
1276 ),
1277 None => (Json::Null, Json::Null, Json::Null, Json::Null),
1278 };
1279 let asking: Vec<Json> = st
1280 .asking
1281 .borrow()
1282 .iter()
1283 .map(|(id, a)| {
1284 json!({
1285 "id": id,
1286 "target": a.decision.target,
1287 "kind": a.decision.kind,
1288 "how": a.decision.how,
1289 "why": a.decision.why,
1290 "origin": source_of(&a.request.origin),
1291 "dialog": a.dialog,
1292 "queued": a.dialog.is_none(),
1293 })
1294 })
1295 .collect();
1296 json!({
1297 "opener": opener,
1298 "inside": inside,
1299 "caps": caps,
1300 "policy": policy,
1301 "asking": asking,
1302 "opening": st.opening.borrow().len(),
1303 "recent": recent(app),
1304 "declared": declared(app).into_iter().map(|(p, t)| json!({ "place": p, "target": t })).collect::<Vec<_>>(),
1305 })
1306}
1307
1308#[derive(Clone, Debug)]
1314pub struct Link {
1315 pub label: String,
1316 pub target: String,
1317 pub source: Source,
1318}
1319
1320impl Link {
1321 pub fn new(label: &str, target: &str) -> Self {
1323 Self {
1324 label: label.into(),
1325 target: target.into(),
1326 source: Source::Declared,
1327 }
1328 }
1329
1330 pub fn content(label: &str, target: &str) -> Self {
1332 Self::new(label, target).source(Source::Content)
1333 }
1334
1335 pub fn source(mut self, source: Source) -> Self {
1336 self.source = source;
1337 self
1338 }
1339
1340 fn request(&self, how: How) -> Request {
1341 Request::new(&self.target)
1342 .how(how)
1343 .source(self.source)
1344 .label(&self.label)
1345 }
1346
1347 pub fn show(self, ui: &mut Ui, app: &AppHandle) -> Response {
1349 let parsed = Target::parse(&self.target).ok();
1350 let response = ui.add(egui::Link::new(&self.label));
1351 let shown = parsed
1352 .as_ref()
1353 .map_or_else(|| self.target.clone(), Target::shown);
1354 ui.ctx().accesskit_node_builder(response.id, |node| {
1355 node.set_role(egui::accesskit::Role::Link);
1360 node.set_description(shown.clone());
1361 });
1362 if self.source == Source::Declared {
1363 state(app)
1364 .seen
1365 .borrow_mut()
1366 .insert(self.target.clone(), self.label.clone());
1367 }
1368 let response = response.on_hover_ui(|ui| hover(ui, &self.target, parsed.as_ref()));
1369 if response.clicked_with_open_in_background() || response.middle_clicked() {
1370 open(app, self.request(How::Outside));
1371 } else if response.clicked() {
1372 open(app, self.request(How::Auto));
1373 }
1374 egui_pop_core::pointer::claim::context_menu(&response, |ui| {
1375 let d = decide(app, &self.request(How::Auto)).ok();
1376 if ui.button(strings::tr(ui.ctx(), &txt::LINKS_OPEN)).clicked() {
1377 open(app, self.request(How::Auto));
1378 ui.close();
1379 }
1380 if d.as_ref().is_some_and(|d| d.how == How::Inside)
1381 && ui
1382 .button(strings::tr(ui.ctx(), &txt::LINKS_OPEN_OUTSIDE))
1383 .clicked()
1384 {
1385 open(app, self.request(How::Outside));
1386 ui.close();
1387 }
1388 let local = parsed.as_ref().is_some_and(|t| t.scheme() == "file");
1389 if local
1390 && ui
1391 .button(strings::tr(ui.ctx(), &txt::LINKS_REVEAL))
1392 .clicked()
1393 {
1394 open(app, self.request(How::Reveal));
1395 ui.close();
1396 }
1397 if ui.button(strings::tr(ui.ctx(), &txt::LINKS_COPY)).clicked() {
1398 copy_link(app, &self.target, &Origin::User);
1399 ui.close();
1400 }
1401 });
1402 response
1403 }
1404}
1405
1406pub fn link(ui: &mut Ui, app: &AppHandle, label: &str, target: &str) -> Response {
1408 Link::new(label, target).show(ui, app)
1409}
1410
1411#[derive(Clone, Debug)]
1418pub struct Inline<'a> {
1419 text: &'a str,
1420 weak: bool,
1421 color: Option<egui::Color32>,
1422 source: Source,
1423}
1424
1425impl<'a> Inline<'a> {
1426 pub fn new(text: &'a str) -> Self {
1428 Self {
1429 text,
1430 weak: false,
1431 color: None,
1432 source: Source::Declared,
1433 }
1434 }
1435
1436 pub fn weak(mut self) -> Self {
1438 self.weak = true;
1439 self
1440 }
1441
1442 pub fn color(mut self, color: egui::Color32) -> Self {
1444 self.color = Some(color);
1445 self
1446 }
1447
1448 pub fn source(mut self, source: Source) -> Self {
1450 self.source = source;
1451 self
1452 }
1453
1454 fn rich(&self, text: &str) -> RichText {
1455 let t = RichText::new(text);
1456 match self.color {
1457 Some(c) => t.color(c),
1458 None if self.weak => t.weak(),
1459 None => t,
1460 }
1461 }
1462
1463 pub fn show(self, ui: &mut Ui, app: &AppHandle) -> Response {
1465 use egui_pop_model::links::inline;
1466 if !inline::has_markup(self.text) {
1467 return ui.label(self.rich(self.text));
1468 }
1469 let runs = inline::runs(self.text);
1470 ui.horizontal_wrapped(|ui| {
1471 ui.spacing_mut().item_spacing.x = 0.0;
1472 for run in &runs {
1473 match &run.link {
1474 Some(target) => {
1475 Link::new(&run.text, target)
1476 .source(self.source)
1477 .show(ui, app);
1478 }
1479 None => {
1480 let mut t = self.rich(&run.text);
1481 if run.strong {
1482 t = t.strong();
1483 }
1484 if run.emphasis {
1485 t = t.italics();
1486 }
1487 if run.code {
1488 t = t.code();
1489 }
1490 ui.label(t);
1491 }
1492 }
1493 }
1494 })
1495 .response
1496 }
1497}
1498
1499pub fn inline(ui: &mut Ui, app: &AppHandle, text: &str) -> Response {
1502 Inline::new(text).show(ui, app)
1503}
1504
1505fn hover(ui: &mut Ui, raw: &str, target: Option<&Target>) {
1508 ui.set_max_width(420.0);
1509 let shown = target.map_or_else(|| raw.to_string(), Target::shown);
1510 ui.label(RichText::new(shown).monospace());
1511 if let Some(host) = target.and_then(Target::host_shown) {
1512 ui.label(
1513 RichText::new(strings::tr_args(
1514 ui.ctx(),
1515 &txt::LINKS_HOST,
1516 &[("host", &host)],
1517 ))
1518 .strong(),
1519 );
1520 }
1521}
1522
1523pub struct LinksPlugin {
1529 policy: Policy,
1530 opener: Arc<dyn Opener>,
1531}
1532
1533impl std::fmt::Debug for LinksPlugin {
1534 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1535 f.debug_struct("LinksPlugin")
1536 .field("policy", &self.policy)
1537 .field("opener", &self.opener.name())
1538 .finish()
1539 }
1540}
1541
1542impl Default for LinksPlugin {
1543 fn default() -> Self {
1544 Self {
1545 policy: Policy::default(),
1546 opener: Arc::new(EguiOpener),
1547 }
1548 }
1549}
1550
1551impl LinksPlugin {
1552 pub fn policy(mut self, policy: Policy) -> Self {
1555 self.policy = policy;
1556 self
1557 }
1558
1559 pub fn opener(mut self, opener: Arc<dyn Opener>) -> Self {
1561 self.opener = opener;
1562 self
1563 }
1564}
1565
1566fn outcome_json(o: Outcome) -> Result<Json, String> {
1567 match o {
1568 Outcome::Done(r) => r,
1569 Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
1570 }
1571}
1572
1573fn request_of(args: &Json, origin: &Origin, key: &str) -> Result<Request, String> {
1576 let target = args[key]
1577 .as_str()
1578 .ok_or_else(|| format!("`{key}` is missing"))?;
1579 let mut r = Request::new(target).origin(origin.clone());
1580 if let Some(how) = args.get("how").filter(|h| !h.is_null()) {
1581 r.how = serde_json::from_value(how.clone()).map_err(|e| format!("`how`: {e}"))?;
1582 }
1583 if let Some(label) = args["label"].as_str() {
1584 r.label = Some(label.into());
1585 }
1586 r.source = if *origin == Origin::User {
1587 match args.get("source").filter(|s| !s.is_null()) {
1588 Some(s) => serde_json::from_value(s.clone()).map_err(|e| format!("`source`: {e}"))?,
1589 None => Source::Declared,
1590 }
1591 } else {
1592 Source::Agent
1593 };
1594 Ok(r)
1595}
1596
1597impl Plugin for LinksPlugin {
1598 fn id(&self) -> PluginId {
1599 PLUGIN
1600 }
1601
1602 fn title(&self) -> String {
1603 "Links".into()
1604 }
1605
1606 fn priority(&self) -> i32 {
1608 -1
1609 }
1610
1611 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
1612 let app = ctx.app();
1613 state(&app).connected.set(true);
1614 ctx.service(&LINKS, Links::new(self.opener.clone(), self.policy.clone()))?;
1615 let egui_ctx = app.egui();
1616 egui_ctx.add_plugin(Interceptor::default());
1617 egui_ctx.with_plugin(|i: &mut Interceptor| i.active = true);
1618 ctx.step(
1619 StepSpec::new(
1620 STEP_OPEN,
1621 "Opening a link; a veto keeps it closed, a redirect opens another target or another way, a run-hook opens it its own way.",
1622 )
1623 .args(json!({ "target": "https://example.org/", "how": "auto", "source": "declared", "origin": "user", "dry_run": false })),
1624 )?;
1625 let category = "Links";
1626 ctx.command(
1627 CommandSpec::new(CMD_OPEN, "Open a link", category)
1628 .description("Opens a link (`target`) its kind's way or `how` (auto, outside, inside, reveal); an agent's request is always confirmed by the user; `dry_run` says the kind, how, whether it would ask and the verdict, opening nothing.")
1629 .args(json!({ "target": "https://example.org/", "how": "auto", "dry_run": true })),
1630 |call| {
1631 let req = request_of(call.args, call.origin, "target")?;
1632 if call.args["dry_run"].as_bool() == Some(true) {
1633 outcome_json(dry_run(call.app, req))
1634 } else {
1635 outcome_json(open(call.app, req))
1636 }
1637 },
1638 )?
1639 .command(
1640 CommandSpec::new(CMD_CHECK, "Check a link", category)
1641 .description("What a link (`target`) is and how it would open (`how`, `source`): its kind, the way, whether the user would be asked, the policy's verdict and the opener's capabilities; nothing is opened and no step runs.")
1642 .args(json!({ "target": "https://example.org/", "how": "auto" }))
1643 .read_only(),
1644 |call| {
1645 let req = request_of(call.args, call.origin, "target")?;
1646 let d = decide(call.app, &req)?;
1647 let caps = links(call.app).map(|l| l.caps());
1648 let mut out = serde_json::to_value(&d).map_err(|e| e.to_string())?;
1649 out["caps"] = json!(caps);
1650 out["refused"] = json!(d.refused.as_ref().map(ToString::to_string));
1651 Ok(out)
1652 },
1653 )?
1654 .command(
1655 CommandSpec::new(CMD_COPY, "Copy a link", category)
1656 .description("Copies a link (`target`) through the clipboard.")
1657 .args(json!({ "target": "https://example.org/" }))
1658 .hidden(),
1659 |call| {
1660 let target = call.args["target"].as_str().ok_or("`target` is missing")?;
1661 copy_link(call.app, target, call.origin);
1662 Ok(json!({ "copied": target }))
1663 },
1664 )?
1665 .command(
1666 CommandSpec::new(CMD_REVEAL, "Show in folder", "File")
1667 .description("Shows a file (`path`) selected in the file manager; an agent's request is confirmed by the user.")
1668 .args(json!({ "path": "/home/me/export.png" })),
1669 |call| {
1670 let req = request_of(call.args, call.origin, "path")?.how(How::Reveal);
1671 outcome_json(open(call.app, req))
1672 },
1673 )?
1674 .command(
1675 CommandSpec::new(CMD_CONFIRMED, "Open the confirmed link", category)
1676 .description("The user's answer to a link's confirmation (`id`, `trust`).")
1677 .args(json!({ "id": 1, "trust": false }))
1678 .hidden()
1679 .no_agent(),
1680 |call| confirmed(call.app, call.args, call.origin),
1681 )?;
1682 if ctx.is_connected(&dialogs::PLUGIN) {
1686 hook_answers(ctx);
1687 }
1688 ctx.clip_endpoint(ENDPOINT, Some(std::rc::Rc::new(LinkSource)), None);
1689 let weak = app.downgrade();
1690 ctx.collector(
1691 FnCollector::new(
1692 "links",
1693 "Links: the opener and its capabilities, the policy (schemes, trusted hosts, documentation hosts), the requests waiting for the user's answer or queued per agent, the recent requests with their decision and outcome, the links declared.",
1694 )
1695 .snapshot(move |_| match weak.get() {
1696 Ok(app) => describe(&app),
1697 Err(_) => Json::Null,
1698 }),
1699 )?;
1700 ctx.on(On::Pass, |app, _| pass(app))
1701 .on(On::Disconnected, |app, ev| {
1702 if let Lifecycle::Disconnected(p) = ev {
1703 let owner = OwnerId::from(p);
1704 state(app)
1705 .declared
1706 .borrow_mut()
1707 .retain(|(o, _, _)| *o != owner);
1708 }
1709 });
1710 Ok(())
1711 }
1712
1713 fn disconnect(&mut self, ctx: &mut Ctx<'_>) {
1714 let app = ctx.app();
1715 state(&app).connected.set(false);
1716 app.egui()
1717 .with_plugin(|i: &mut Interceptor| i.active = false);
1718 }
1719}
1720
1721fn hook_answers(ctx: &mut Ctx<'_>) {
1724 ctx.before(dialogs::STEP_ANSWER, |_, args| {
1725 let ours = args["dialog"]["command"].as_str() == Some(CMD_CONFIRMED.as_str());
1726 let cancel = args["answer"]["answer"].as_str() == Some("cancel");
1727 if ours && !cancel && args["origin"].as_str() != Some("user") {
1728 Before::Veto("only the user answers a link's confirmation".into())
1729 } else {
1730 Before::Go
1731 }
1732 })
1733 .after(dialogs::STEP_ANSWER, |app, args, result| {
1734 if args["dialog"]["command"].as_str() != Some(CMD_CONFIRMED.as_str()) || result.is_err() {
1735 return;
1736 }
1737 let Some(id) = args["dialog"]["args"]["id"].as_u64() else {
1738 return;
1739 };
1740 if args["answer"]["answer"].as_str() == Some("cancel") {
1741 cancelled(app, id);
1742 } else if let Some(a) = state(app).asking.borrow_mut().get_mut(&id) {
1743 a.answered = true;
1744 }
1745 });
1746}
1747
1748impl Ctx<'_> {
1749 pub fn link(&mut self, place: &str, target: &str) -> &mut Self {
1752 state(self.app).declared.borrow_mut().push((
1753 self.owner.clone(),
1754 place.into(),
1755 target.into(),
1756 ));
1757 self
1758 }
1759}