Skip to main content

egui_pop_api/
links.rs

1//! Links (ADR 0017): one service opens them, through one policy and one
2//! step, with a replaceable opener.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! - **Requests** ([`Request`], from `egui_pop_model::links`) name the
8//!   target, how (`Auto`, `Outside`, `Inside`, `Reveal`), the source
9//!   (declared by the application, found in content, asked by an agent),
10//!   the text the link was shown under and who asks. [`open`] runs them
11//!   through the `link.open` step: a before-hook vetoes or redirects, a
12//!   run-hook opens its own way, the journal says `link.opened`,
13//!   `link.failed`, `link.asked` or `link.cancelled`.
14//! - **The policy** ([`Policy`]) classifies the target and decides how it
15//!   opens and whether the user confirms first: declared web and mail
16//!   links open at once; a content link asks while its host is not
17//!   trusted (the confirmation offers to trust it for the session); a
18//!   local file is always confirmed and a program refused, its folder
19//!   offered; an agent's request is always confirmed, one at a time per
20//!   agent, five more queued, then refused. [`Links`] (the `app.links`
21//!   service) holds it, with the opener.
22//! - **Openers** ([`Opener`]) do the opening: [`EguiOpener`] (the
23//!   default: web pages and mail through egui's `OpenUrl`, eframe's
24//!   `links` feature on native, a new tab on the web build),
25//!   [`RecordingOpener`] (tests: records each call, answers as
26//!   scripted), [`NullOpener`] (a headless node: refuses with the reason,
27//!   or forwards). `egui_pop_platform::open::SystemOpener` adds local
28//!   files, folders and Reveal.
29//! - **egui's own `OpenUrl`** (`ui.hyperlink`, a third-party widget,
30//!   `ctx.open_url`) is taken out of each frame's output and opened
31//!   through the same step, so no link bypasses the policy.
32//! - **The widget** ([`link`], [`Link`]): the theme's link colour, the
33//!   real target on hover (an internationalised host with its punycode),
34//!   a context menu (Open, Open outside, Show in folder, Copy link),
35//!   Enter and Space, Ctrl+click and middle click for outside, the role
36//!   `link` with the target as its description.
37//! - **Commands**: `links.open` (`target`, `how`, `dry_run`: a dry run
38//!   says the kind, how, whether it would ask and the verdict, opening
39//!   nothing) and `links.check` for agents, `files.reveal` (`path`), and
40//!   the `links` collector; [`lint`] checks the links an application
41//!   declares.
42//!
43//! ```
44//! use std::sync::Arc;
45//! use egui_pop_api::links::{self, LinksPlugin, RecordingOpener, Request};
46//! use egui_pop_api::App;
47//!
48//! let rec = RecordingOpener::default();
49//! let app = App::builder()
50//!     .plugin(LinksPlugin::default().opener(Arc::new(rec.clone())))
51//!     .build(&egui::Context::default())
52//!     .unwrap();
53//! let out = links::open(app.handle(), Request::new("https://example.org/"));
54//! assert!(out.ok());
55//! assert_eq!(rec.records()[0].target, "https://example.org/");
56//! ```
57
58pub 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
88/// The plugin's id.
89pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.links");
90
91/// The links service: the policy and the opener.
92pub const LINKS: ServiceToken<Links> = ServiceToken::new("app.links");
93
94/// Opening a link (`{ target, how, source, label, origin, dry_run }`): a
95/// before-hook vetoes it or redirects it (another target, another way);
96/// a run-hook opens it its own way; its default decides through the
97/// policy, asks the user when it must, and has the opener open it. Its
98/// result: the decision and the status (`opened`, `opening`, `asked`,
99/// `queued`, or a dry run's verdict).
100pub const STEP_OPEN: StepId = StepId::from_static("link.open");
101
102/// Opens a link (`target`, `how`, `label`, `dry_run`); an agent's
103/// request is always confirmed by the user.
104pub const CMD_OPEN: CommandId = CommandId::from_static("links.open");
105/// What a link is and how it would open (`target`, `how`, `source`),
106/// opening nothing.
107pub const CMD_CHECK: CommandId = CommandId::from_static("links.check");
108/// Copies a link (`target`), through the clipboard.
109pub const CMD_COPY: CommandId = CommandId::from_static("links.copy");
110/// Shows a file in its folder (`path`).
111pub const CMD_REVEAL: CommandId = CommandId::from_static("files.reveal");
112/// The user's answer to a confirmation (`id`, `trust`): kept from
113/// agents and the palette.
114pub const CMD_CONFIRMED: CommandId = CommandId::from_static("links.confirmed");
115
116/// The clipboard endpoint a link is copied from.
117pub const ENDPOINT: &str = "egui_pop.links";
118
119/// How many requests of one agent wait behind its confirmation.
120pub const AGENT_QUEUE: usize = 5;
121/// How many requests the `links` collector keeps.
122pub const RECENT: usize = 32;
123
124const NO_PLUGIN: &str = "no links service: the LinksPlugin is not connected";
125
126/// What an opener answers.
127#[derive(Debug)]
128pub enum Opening {
129    /// Done, or refused with the reason.
130    Done(Result<(), String>),
131    /// The answer comes later (a portal, a thread).
132    Later(Pending),
133}
134
135/// One call to an opener: what to open and how, from where, for whom.
136#[derive(Clone, Copy, Debug)]
137pub struct OpenCall<'a> {
138    pub target: &'a Target,
139    /// `Outside` or `Reveal`; `Inside` for a page or an image when no
140    /// viewer ([`Inside`]) is installed and the opener says it shows
141    /// them itself (`Caps::inside`).
142    pub how: How,
143    pub kind: Kind,
144    pub source: Source,
145    pub origin: &'a Origin,
146    /// The context of the window it is asked from.
147    pub egui: &'a egui::Context,
148}
149
150/// What opens a link outside the application, replaceable by the host
151/// (ADR 0010): a kiosk opening nothing, a host opening in its own
152/// browser, a headless node forwarding to an attached interface.
153pub trait Opener: Send + Sync {
154    /// Its name, as the `links` collector shows it.
155    fn name(&self) -> &str;
156
157    /// What it can do here: the policy refuses the rest with the reason.
158    fn caps(&self) -> Caps;
159
160    /// Opens a target the policy approved (and the user confirmed when
161    /// asked).
162    fn open(&self, call: &OpenCall<'_>) -> Opening;
163}
164
165/// What shows pages and images inside the application (the viewer of
166/// `egui_pop_views::viewer`, or the host's own): the links service hands
167/// it each request the policy sends inside (`docs:` pages, pages on the
168/// application's documentation hosts, local images, local videos when it
169/// [`plays`](Inside::plays_video) them, YouTube videos when it
170/// [`plays`](Inside::plays_web_video) those), after the policy and the user's
171/// confirmation.
172pub trait Inside: Send + Sync {
173    /// Its name, as the `links` collector shows it.
174    fn name(&self) -> &str;
175
176    /// Shows a target (`call.how` is `Inside`), or says why not.
177    fn show(&self, app: &AppHandle, call: &OpenCall<'_>) -> Result<(), String>;
178
179    /// The `docs:` pages it has, when it knows them: the lint checks
180    /// the declared `docs:` links against them.
181    fn docs_pages(&self) -> Option<Vec<String>> {
182        None
183    }
184
185    /// Whether it plays local video files: without that they open
186    /// outside, as any local file.
187    fn plays_video(&self) -> bool {
188        false
189    }
190
191    /// Whether it plays YouTube links (in a web view): without that they
192    /// open outside, as any web video.
193    fn plays_web_video(&self) -> bool {
194        false
195    }
196}
197
198/// The default opener: web pages and `mailto:` through egui's `OpenUrl`
199/// (eframe's `links` feature, webbrowser, on native; a new tab on the web
200/// build, `mailto:` in the same tab, which hands it to the mail client).
201/// Local files, folders and Reveal need the platform's
202/// `SystemOpener`.
203#[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
225/// Emits egui's `OpenUrl` for a link the policy approved: the
226/// interceptor lets it through to eframe.
227pub 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/// One call a [`RecordingOpener`] received.
241#[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    /// Who asked (`user`, `agent:<name>`).
248    pub origin: String,
249}
250
251#[derive(Debug)]
252struct Recording {
253    records: Vec<Record>,
254    answer: Result<(), String>,
255    caps: Caps,
256}
257
258/// An opener for tests: records each call (target, how, kind, source,
259/// origin) and answers as scripted (success by default), with every
260/// capability. Clones share the record.
261#[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    /// Answers every later call with this failure (`None`: success).
276    pub fn fail(&self, reason: Option<&str>) {
277        lock(&self.0).answer = reason.map_or(Ok(()), |r| Err(r.to_string()));
278    }
279
280    /// What it says it can do.
281    pub fn set_caps(&self, caps: Caps) {
282        lock(&self.0).caps = caps;
283    }
284
285    /// The calls so far, oldest first.
286    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/// An opener for a node without a screen: every request is refused with
320/// the reason (its `link.failed` in the journal), or forwarded to an
321/// attached interface when the host offers one.
322#[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    /// Refuses with this reason.
348    pub fn new(reason: &str) -> Self {
349        Self {
350            reason: reason.into(),
351            forward: None,
352        }
353    }
354
355    /// Forwards each request (to an attached interface, which asks its
356    /// user).
357    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        // The policy decides as anywhere; the answer is the refusal.
376        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
390/// The links service: the policy and the opener, shared by the
391/// application's windows.
392pub 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    /// What shows pages and images inside, if anything.
418    pub fn inside(&self) -> Option<Arc<dyn Inside>> {
419        lock(&self.inside).clone()
420    }
421
422    /// Installs (or removes) what shows pages and images inside: with
423    /// one, `docs:` pages open there rather than in their online copy.
424    pub fn set_inside(&self, inside: Option<Arc<dyn Inside>>) {
425        *lock(&self.inside) = inside;
426    }
427
428    /// What the application can do: the opener's capabilities, and
429    /// showing pages inside when a viewer is installed.
430    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    /// The opener in use.
447    pub fn opener(&self) -> Arc<dyn Opener> {
448        lock(&self.opener).clone()
449    }
450
451    /// Replaces the opener (the platform's, a test's, a host's).
452    pub fn set_opener(&self, opener: Arc<dyn Opener>) {
453        *lock(&self.opener) = opener;
454    }
455
456    /// The policy, as it is now.
457    pub fn policy(&self) -> Policy {
458        lock(&self.policy).clone()
459    }
460
461    /// Changes the policy (schemes, documentation hosts, the
462    /// application's scheme).
463    pub fn update_policy(&self, f: impl FnOnce(&mut Policy)) {
464        f(&mut lock(&self.policy));
465    }
466
467    /// Trusts a host for the session: content links to it open without
468    /// asking.
469    pub fn trust(&self, host: &str) {
470        lock(&self.policy).trust(host);
471    }
472}
473
474/// egui's plugin taking `OpenUrl` out of each frame's output (every
475/// window's): the commands the service approved go on to eframe, the
476/// others are opened through the service on the next pass.
477#[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/// A request waiting for the user's answer.
514#[derive(Clone, Debug)]
515struct Asking {
516    request: Request,
517    decision: Decision,
518    /// The dialog showing it; none while queued behind another of the
519    /// same agent.
520    dialog: Option<u64>,
521    /// Answered (accepted): its command runs next.
522    answered: bool,
523}
524
525/// An open whose answer comes later.
526struct 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    /// Requests the user accepted: the next run opens them.
538    accepted: RefCell<Vec<u64>>,
539    /// Per agent session, the requests queued behind its confirmation.
540    queued: RefCell<BTreeMap<String, VecDeque<u64>>>,
541    opening: RefCell<Vec<Waiting>>,
542    recent: RefCell<VecDeque<Json>>,
543    /// Links declared by plugins: owner, place, target.
544    declared: RefCell<Vec<(OwnerId, String, String)>>,
545    /// Declared links drawn so far: target, label.
546    seen: RefCell<BTreeMap<String, String>>,
547    /// The link a copy takes.
548    copying: RefCell<String>,
549}
550
551fn state(app: &AppHandle) -> std::rc::Rc<State> {
552    app.local::<State>()
553}
554
555/// The links service, when the plugin is connected.
556pub fn links(app: &AppHandle) -> Option<Arc<Links>> {
557    app.service(&LINKS)
558}
559
560/// What is known of a local target on disk (nothing on the web build).
561pub 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/// Many file systems mark every file executable (FAT, network shares):
584/// the bit counts only for a file without an extension, which the
585/// extension list cannot judge.
586#[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
602/// What the policy decides for a request now, with the opener's
603/// capabilities and what the disk says (nothing is opened).
604pub 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
614/// Opens a link through the [`STEP_OPEN`] step. A refusal or a failure
615/// asked by the user shows in a toast with Copy link (or Show in folder
616/// for a program); a request needing a confirmation opens it and ends
617/// `asked` (or `queued` behind an agent's earlier one).
618pub fn open(app: &AppHandle, request: Request) -> Outcome {
619    run(app, request, false, None)
620}
621
622/// What opening a link would do (the kind, how, whether it asks, the
623/// verdict) through the [`STEP_OPEN`] step, opening nothing.
624pub 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
737/// Who opens: the opener, and the viewer inside when there is one.
738struct 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        // The viewer, else an opener that shows pages itself.
775        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    // A `docs:` page without the viewer: its online copy.
820    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
865/// A warning toast saying why a link did not open, with Copy link, or
866/// Show in folder for a program.
867fn 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
889/// The session an origin asks for (`agent:<name>`), when it is not the
890/// user.
891fn 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    // One confirmation per agent at a time; five more wait, then no.
901    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
950/// The confirmation: the full target, the host (its punycode beside an
951/// internationalised one), why it asks, Copy link, Open, Cancel, and for
952/// a content link "Trust <host> for this session".
953fn 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, &copy_target, &Origin::User);
1021            }
1022        });
1023        pass.describe(description.clone());
1024    })
1025}
1026
1027/// The user's answer to a confirmation: open it (trusting its host when
1028/// asked), then the agent's next request.
1029fn 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
1054/// A confirmation cancelled (or never shown): the agent hears it, its
1055/// next request comes up.
1056fn 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
1076/// Shows the next queued request of an agent, if any.
1077fn 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
1109/// Copies a link: through the clipboard (the `clipboard.copy` step, a
1110/// `text/uri-list` item with its text) when its plugin is connected,
1111/// else as text.
1112pub 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
1122/// What a copy of a link takes.
1123struct 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
1165/// The requests seen lately, oldest first, as the `links` collector
1166/// shows them.
1167pub fn recent(app: &AppHandle) -> Vec<Json> {
1168    state(app).recent.borrow().iter().cloned().collect()
1169}
1170
1171/// Declares a link the application shows (About, help, a tip): checked
1172/// by [`lint`] (the plugin-owned form is [`Ctx::link`]).
1173pub 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
1181/// The links declared (place, target) and those drawn as declared so far
1182/// (`drawn`, the label).
1183pub 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
1200/// Each pass: egui's own `OpenUrl` taken from the last frame opened
1201/// through the service, later answers collected, confirmations closed
1202/// without an answer cancelled.
1203fn 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        // What an application's own hyperlink is: declared for web and
1219        // mail, content otherwise.
1220        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    // A confirmation gone without an answer (its `dialog.show` vetoed).
1253    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
1267/// The collector's snapshot.
1268fn 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/// The link widget: the theme's link colour and a pointing hand, the
1309/// real target on hover, a context menu (Open, Open outside when the
1310/// default is inside, Show in folder for a local file, Copy link), Enter
1311/// and Space to open, Ctrl+click and middle click to open outside, role
1312/// `link` with the label as its name and the target as its description.
1313#[derive(Clone, Debug)]
1314pub struct Link {
1315    pub label: String,
1316    pub target: String,
1317    pub source: Source,
1318}
1319
1320impl Link {
1321    /// A link the application declares.
1322    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    /// A link found in content (a document, a program's output).
1331    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    /// Draws it; a click opens it through [`open`].
1348    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            // upstream: with selectable labels on (egui's default),
1356            // `egui::Link` draws through the label text selection, which
1357            // sets the node's role back to `Label` after the link set it
1358            // (docs/upstream.md): the role is set again here, after it.
1359            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
1406/// Draws a link the application declares; see [`Link`].
1407pub fn link(ui: &mut Ui, app: &AppHandle, label: &str, target: &str) -> Response {
1408    Link::new(label, target).show(ui, app)
1409}
1410
1411/// A short text in the inline subset (ADR 0017): emphasis, strong,
1412/// code and links (`[label](target)`, `<https://…>`, a bare address),
1413/// each link drawn with [`Link`]; tips, toasts and settings descriptions
1414/// use it, so their text needs no markdown renderer. A text without any
1415/// of it is a plain label. See `egui_pop_model::links::inline` for what
1416/// is read.
1417#[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    /// A text the application declares: its links are declared ones.
1427    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    /// Drawn weak (a description).
1437    pub fn weak(mut self) -> Self {
1438        self.weak = true;
1439        self
1440    }
1441
1442    /// Drawn in this colour (a toast's text), links aside.
1443    pub fn color(mut self, color: egui::Color32) -> Self {
1444        self.color = Some(color);
1445        self
1446    }
1447
1448    /// Where its links come from (`Declared` unless said).
1449    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    /// Draws it.
1464    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
1499/// Draws a short text the application declares in the inline subset;
1500/// see [`Inline`].
1501pub fn inline(ui: &mut Ui, app: &AppHandle, text: &str) -> Response {
1502    Inline::new(text).show(ui, app)
1503}
1504
1505/// A link's hover: the full target, then its host (an internationalised
1506/// one with its punycode).
1507fn 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
1523/// The links service as a plugin (in `DefaultPlugins`): the policy and
1524/// the opener ([`EguiOpener`] unless given), the `link.open` step, the
1525/// interceptor of egui's `OpenUrl`, the confirmation, the commands
1526/// (`links.open`, `links.check`, `links.copy`, `files.reveal`) and the
1527/// `links` collector.
1528pub 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    /// The policy to start from (schemes, the application's scheme,
1553    /// documentation hosts).
1554    pub fn policy(mut self, policy: Policy) -> Self {
1555        self.policy = policy;
1556        self
1557    }
1558
1559    /// The opener to use.
1560    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
1573/// A request from a command's arguments: an agent's (or a script's) is
1574/// always the agent's source, whatever it says.
1575fn 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    /// After the dialogs plugin, whose answers it watches.
1607    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        // Only the user answers a confirmation; an agent may cancel it.
1683        // (Without the dialogs plugin nothing is confirmed: a request
1684        // that must be is refused with the reason.)
1685        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
1721/// The confirmation's answers: only the user's accepts one; a cancel
1722/// tells the agent and brings its next request up.
1723fn 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    /// Declares a link this plugin shows (its About, a help entry, a
1750    /// tip): [`lint`] checks it; it goes with the plugin.
1751    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}