Skip to main content

egui_pop_api/
clipboard.rs

1//! The clipboard (ADR 0015): typed items kept by the application's
2//! owner, readable fallbacks on the system clipboard, a paste negotiated
3//! between what a copy offers and what the target accepts, and hooks at
4//! each boundary.
5//!
6//! <div class="warning">Experimental: may change in any release
7//! (docs/stability.md).</div>
8//!
9//! - **The owner** implements [`Clipboard`]: one item per slot (the
10//!   user's, and each agent session's own), `put`, `get`, a revision. The
11//!   host gives it ([`Host::clipboard`](crate::host::Host::clipboard));
12//!   without one, [`ClipboardPlugin`] keeps a [`LocalClipboard`] in
13//!   memory, shared by the application's windows. It publishes
14//!   `clipboard.changed` (the slot, the type, the revision; never the
15//!   payload).
16//! - **Sources and targets** are the components': a component registers
17//!   an endpoint by name ([`register`], or [`Ctx::clip_endpoint`]) with a
18//!   [`ClipSource`] (what a copy takes, what a cut deletes) and a
19//!   [`ClipTarget`] (the formats it accepts, how it applies a paste),
20//!   and says each pass which widget draws it ([`bind`]), which widgets
21//!   draw its elements ([`bind_element`]: a graph's nodes, a tree's
22//!   rows, each with its key) or which area it covers ([`bind_area`]):
23//!   the endpoint of the focused widget is the one the Edit commands
24//!   use, and its source and target receive the element's key.
25//! - **Types, transforms and sanitisers** are declared by plugins and go
26//!   with them ([`Ctx::clip_type`], [`Ctx::clip_transform`],
27//!   [`Ctx::clip_sanitiser`]): a type renders its fallbacks, lists its
28//!   parts and migrates its older versions; a transform makes one format
29//!   from another (lossy or not); a sanitiser removes what must not cross
30//!   a boundary and says what it removed.
31//! - **Steps** (ADR 0011): `clipboard.copy` and `clipboard.paste`, which
32//!   a before-hook vetoes (a secret field) or redirects (another
33//!   selection, another target, another format). A copy is never an
34//!   undo step; a cut deletes and copies as one undo step and copies
35//!   only once its delete is accepted; a paste is one undo step ("Paste
36//!   a colour"), through the host's history group
37//!   ([`Host::begin_group`](crate::host::Host::begin_group)).
38//! - **Commands**: `edit.cut` (Ctrl+X, Shift+Delete), `edit.copy`
39//!   (Ctrl+C, Ctrl+Insert), `edit.paste` (Ctrl+V, Shift+Insert) and
40//!   `edit.pasteSpecial` (Ctrl+Shift+V, a choice of every format,
41//!   transform and part that fits, each with the target's preview) in
42//!   the Edit menu, `when` `!textInputFocus` and the keys `canCut`,
43//!   `canCopy`, `canPaste`: greyed when nothing focused answers, and text
44//!   fields keep egui's own copy and paste. egui-winit turns the
45//!   platform's copy, cut and paste chords into events and swallows the
46//!   keys; those events are dispatched to the commands when an endpoint
47//!   has the focus (Shift held on a paste: paste special). Where a
48//!   backend reads the system clipboard (`egui-pop-platform`'s
49//!   `SystemClipboardPlugin`), `run_native` turns eframe's clipboard
50//!   shortcuts off instead: the chords arrive as keys, and the keymap
51//!   runs them in text fields too ([`set_keymap_shortcuts`]), so a
52//!   remapped chord edits text as well. For agents:
53//!   `clipboard.copy`, `clipboard.paste` (with `format`, `transform`,
54//!   `parts`, `if_rev` and `dry_run`), `clipboard.offers`,
55//!   `clipboard.read`, `clipboard.write`, each in the session's own slot
56//!   unless the owner allows otherwise; the `clipboard` collector.
57//!
58//! **The system clipboard** is reached through a [`SystemBackend`]: a
59//! copy gives it every representation it writes, at once; a paste reads
60//! every format it can (files, images, HTML, text) as one external item.
61//! The default, [`EguiText`], writes text through egui and reads
62//! nothing: a paste then knows the system clipboard only by the text the
63//! paste key brought, and a paste through the menu or a command uses the
64//! owner's item. A host gives its own backend ([`Clipboard::system`]),
65//! an application installs one ([`set_backend`]; `egui-pop-platform`'s
66//! `clipboard` feature has one over arboard).
67//!
68//! ```
69//! use std::rc::Rc;
70//! use std::cell::RefCell;
71//! use egui_pop_api::clipboard::{self, ClipSource, ClipTarget, ClipboardPlugin, Paste};
72//! use egui_pop_api::{App, AppHandle};
73//! use egui_pop_model::clipboard::{ClipItem, FormatId, TEXT};
74//! use egui_pop_model::commands::Origin;
75//!
76//! const NOTE: FormatId = FormatId::from_static("application/x-demo.note+json");
77//!
78//! /// A note: copied as a typed item, pasted from one or from text.
79//! #[derive(Default)]
80//! struct Note(RefCell<String>);
81//! impl ClipSource for Note {
82//!     fn copy(&self, _: &AppHandle) -> Option<ClipItem> {
83//!         let text = self.0.borrow().clone();
84//!         Some(ClipItem::new(NOTE, 1, serde_json::json!({ "text": text }), "a note")
85//!             .fallback(TEXT, serde_json::json!(text)))
86//!     }
87//! }
88//! impl ClipTarget for Note {
89//!     fn accepts(&self, _: &AppHandle) -> Vec<FormatId> { vec![NOTE, TEXT] }
90//!     fn paste(&self, _: &AppHandle, p: &Paste<'_>) -> Result<serde_json::Value, String> {
91//!         let text = p.repr.data["text"].as_str().or(p.repr.text()).unwrap_or("").to_string();
92//!         if !p.dry_run { *self.0.borrow_mut() = text.clone(); }
93//!         Ok(serde_json::json!({ "set": text }))
94//!     }
95//! }
96//!
97//! let app = App::builder().plugin(ClipboardPlugin::default())
98//!     .build(&egui::Context::default()).unwrap();
99//! let h = app.handle();
100//! let (a, b) = (Rc::new(Note::default()), Rc::new(Note::default()));
101//! *a.0.borrow_mut() = "hello".into();
102//! clipboard::register(h, "a", Some(a.clone()), Some(a.clone()));
103//! clipboard::register(h, "b", Some(b.clone()), Some(b.clone()));
104//! assert!(clipboard::copy(h, clipboard::CopyRequest::new("a"), &Origin::User).ok());
105//! assert!(clipboard::paste(h, clipboard::PasteRequest::new("b"), &Origin::User).ok());
106//! assert_eq!(*b.0.borrow(), "hello");
107//! ```
108
109use std::cell::{Cell, RefCell};
110use std::collections::{BTreeMap, BTreeSet, HashMap};
111use std::fmt;
112use std::rc::Rc;
113
114use egui_pop_core::debug::FnCollector;
115use egui_pop_core::strings;
116use egui_pop_model::clipboard as model;
117use egui_pop_model::commands::{CommandSpec, Origin};
118use egui_pop_model::ids::{CommandId, OwnerId, PluginId, StepId};
119use egui_pop_model::values::GestureId;
120use serde::{Deserialize, Serialize};
121use serde_json::{Value as Json, json};
122
123use crate::app::{AppHandle, MENU_EDIT};
124use crate::hooks::{Lifecycle, On};
125use crate::host::{Pending, source_of};
126use crate::steps::{Outcome, StepSpec};
127use crate::strings as txt;
128use crate::{Ctx, CtxError, Plugin, PluginError};
129
130pub use egui_pop_model::clipboard::{
131    Boundary, ClipItem, ClipOrigin, FormatId, HTML, PNG, Plan, Refusal, Repr, Slot, Stripped, TEXT,
132    TitleKey, TransformSpec, URI_LIST,
133};
134
135/// The plugin's id.
136pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.clipboard");
137
138/// The id of `egui-pop-platform`'s `SystemClipboardPlugin`, whose
139/// backend reads the system clipboard: with it added, `run_native` turns
140/// eframe's clipboard shortcuts off and the keymap runs the chords
141/// ([`set_keymap_shortcuts`]).
142pub const SYSTEM_PLUGIN: PluginId = PluginId::from_static("egui_pop.system_clipboard");
143
144/// The context key true while the keymap runs the copy, cut and paste
145/// chords in text fields too ([`set_keymap_shortcuts`]).
146pub const CONTEXT_KEYMAP_SHORTCUTS: &str = "clipboardKeymap";
147
148/// The Edit menu's group of the clipboard commands, under undo.
149pub const MENU_GROUP: &str = "1_clipboard";
150
151/// Cuts the focused endpoint's selection: copied once its delete is
152/// accepted, one undo step.
153pub const CMD_CUT: CommandId = CommandId::from_static("edit.cut");
154/// Copies the focused endpoint's selection.
155pub const CMD_COPY: CommandId = CommandId::from_static("edit.copy");
156/// Pastes into the focused endpoint, in the richest format it accepts.
157pub const CMD_PASTE: CommandId = CommandId::from_static("edit.paste");
158/// Pastes into the focused endpoint in a format, through a transform or
159/// only some parts, chosen in a dialog showing each one's preview.
160pub const CMD_PASTE_SPECIAL: CommandId = CommandId::from_static("edit.pasteSpecial");
161/// Copies from an endpoint by name (`source`, `slot`, `cut`,
162/// `dry_run`).
163pub const CMD_CLIP_COPY: CommandId = CommandId::from_static("clipboard.copy");
164/// Pastes into an endpoint by name (`target`, `slot`, `format`,
165/// `transform`, `parts`, `if_rev`, `dry_run`).
166pub const CMD_CLIP_PASTE: CommandId = CommandId::from_static("clipboard.paste");
167/// What a slot holds and the ways it fits a target (`slot`, `target`).
168pub const CMD_OFFERS: CommandId = CommandId::from_static("clipboard.offers");
169/// A slot's item, payload included (`slot`).
170pub const CMD_READ: CommandId = CommandId::from_static("clipboard.read");
171/// Puts an item in a slot (`slot`, `format`, `data`, `title`).
172pub const CMD_WRITE: CommandId = CommandId::from_static("clipboard.write");
173
174/// A copy (`{ source, slot, cut, dry_run, origin }`): a before-hook
175/// vetoes it or redirects it (another source, another slot); its default
176/// asks the source for the item, sanitises what goes to the system
177/// clipboard, deletes for a cut, and gives the item to the owner. Its
178/// result: the type, the title, the revision, what was left out.
179pub const STEP_COPY: StepId = StepId::from_static("clipboard.copy");
180/// A paste (`{ target, slot, format, transform, parts, if_rev, dry_run,
181/// text, origin }`): a before-hook vetoes it or redirects it (another
182/// target, another format); its default takes the owner's item (or the
183/// external text), sanitises external content, negotiates the format,
184/// runs the transform and has the target apply it as one undo step. Its
185/// result: the plan, what was lost, the target's changes.
186pub const STEP_PASTE: StepId = StepId::from_static("clipboard.paste");
187
188/// A sanitiser of egui-pop's own: control characters and escape
189/// sequences removed from external text.
190pub const SANITISE_CONTROLS: &str = "egui_pop.controls";
191/// A transform of egui-pop's own: HTML reduced to its text (lossy).
192pub const HTML_TO_TEXT: &str = "egui_pop.html-to-text";
193
194const NO_PLUGIN: &str = "no clipboard: the ClipboardPlugin is not connected";
195
196/// What the owner answers a `put`.
197#[derive(Debug)]
198pub enum Answer {
199    /// Kept (its new revision), or refused.
200    Done(Result<u64, String>),
201    /// A remote owner answers later.
202    Later(Pending),
203}
204
205/// The owner of the clipboard, as the interface reaches it.
206pub trait Clipboard {
207    /// Keeps an item in a slot, replacing what it held.
208    fn put(&mut self, slot: &Slot, item: ClipItem, origin: &Origin) -> Answer;
209
210    /// The item a slot holds.
211    fn get(&self, slot: &Slot) -> Option<ClipItem>;
212
213    /// The formats a slot offers.
214    fn offers(&self, slot: &Slot) -> Vec<FormatId> {
215        self.get(slot).map(|i| i.offers()).unwrap_or_default()
216    }
217
218    /// The revision: one more at each `put`.
219    fn rev(&self) -> u64;
220
221    /// Whether `origin` may read and write `slot`: by default, the user
222    /// any slot, a session its own only ([`default_access`]).
223    fn may_use(&self, origin: &Origin, slot: &Slot) -> Result<(), String> {
224        default_access(origin, slot)
225    }
226
227    /// The events to publish since the last call, as (name, data).
228    fn take_events(&mut self) -> Vec<(String, Json)> {
229        Vec::new()
230    }
231
232    /// The owner's own way to the system clipboard (a kernel writing
233    /// its private types there): it wins over the one installed with
234    /// [`set_backend`], which wins over egui's text.
235    fn system(&mut self) -> Option<&mut dyn SystemBackend> {
236        None
237    }
238}
239
240/// The system clipboard as egui-pop writes and reads it: what one copy
241/// leaves there for other applications, what a paste finds there.
242///
243/// The default, [`EguiText`], writes the text through egui and reads
244/// nothing (a paste knows only the text the paste key brought). A host
245/// gives its own through [`Clipboard::system`], an application installs
246/// one with [`set_backend`] (`egui-pop-platform`'s `clipboard` feature
247/// has one over arboard: files, images, HTML and the primary
248/// selection).
249///
250/// Representations follow the formats' usual data: text, HTML and a
251/// URI list (`text/uri-list`, one `file://` URI per line, CRLF between)
252/// are JSON strings; an image (`image/png`) is a string, the PNG file's
253/// bytes in standard base64; a private type is its JSON payload.
254pub trait SystemBackend {
255    /// What it is called, for the collector ("egui", "arboard").
256    fn name(&self) -> String;
257
258    /// Whether it writes a format: a copy gives it every representation
259    /// it writes, so a private type crosses only where it can.
260    fn writes(&self, format: &FormatId) -> bool {
261        *format == TEXT
262    }
263
264    /// Writes one copy's representations (richest first, sanitised for
265    /// the system boundary) at once, replacing what the system clipboard
266    /// held.
267    fn write(&mut self, ctx: &egui::Context, reprs: &[Repr]) -> Result<(), String>;
268
269    /// What the system clipboard holds, in each format it reads, richest
270    /// first; `None` when it cannot read (a paste then knows only the
271    /// text the paste key brought), empty when the clipboard is.
272    fn read(&mut self, ctx: &egui::Context) -> Option<Vec<Repr>> {
273        let _ = ctx;
274        None
275    }
276
277    /// The formats a read may bring besides text, so that the paste
278    /// command is enabled for a target taking only files or images.
279    fn readable(&self) -> Vec<FormatId> {
280        Vec::new()
281    }
282
283    /// The primary selection's text (X11 and Wayland: select to copy,
284    /// middle-click to paste); `None` where there is none.
285    fn read_primary(&mut self) -> Option<String> {
286        None
287    }
288
289    /// Sets the primary selection's text.
290    fn write_primary(&mut self, text: &str) -> Result<(), String> {
291        let _ = text;
292        Err("this clipboard backend has no primary selection".into())
293    }
294
295    /// What it says of itself for the collector: its platform path (on
296    /// Wayland: XWayland, the data-control protocol, or the core
297    /// protocol), what it reads and writes.
298    fn describe(&self) -> Json {
299        Json::Null
300    }
301}
302
303/// The default backend: text through egui (`Context::copy_text`, which
304/// eframe hands to its own clipboard at the end of the pass), nothing
305/// read.
306#[derive(Debug, Default, Clone, Copy)]
307pub struct EguiText;
308
309impl SystemBackend for EguiText {
310    fn name(&self) -> String {
311        "egui".into()
312    }
313
314    fn write(&mut self, ctx: &egui::Context, reprs: &[Repr]) -> Result<(), String> {
315        if let Some(text) = reprs.iter().find(|r| r.format == TEXT).and_then(Repr::text) {
316            ctx.copy_text(text.to_string());
317        }
318        Ok(())
319    }
320
321    fn describe(&self) -> Json {
322        json!({ "writes": [TEXT], "reads": "the paste key's text" })
323    }
324}
325
326/// Installs the system clipboard's backend (unless the owner gives its
327/// own, [`Clipboard::system`]); before, egui's text ([`EguiText`]).
328pub fn set_backend(app: &AppHandle, backend: Box<dyn SystemBackend>) {
329    let st = state(app);
330    *st.backend.borrow_mut() = Some(backend);
331    *st.read_cache.borrow_mut() = None;
332}
333
334/// Runs `f` on the system backend: the owner's, else the one installed,
335/// else egui's text.
336pub fn with_backend<R>(app: &AppHandle, f: impl FnOnce(&mut dyn SystemBackend) -> R) -> R {
337    let mut f = Some(f);
338    let by_owner = with_owner(app, |c| {
339        c.system().map(|b| f.take().expect("called once")(b))
340    })
341    .flatten();
342    if let Some(r) = by_owner {
343        return r;
344    }
345    let f = f.take().expect("called once");
346    let st = state(app);
347    let mut installed = st.backend.borrow_mut();
348    match installed.as_mut() {
349        Some(b) => f(b.as_mut()),
350        None => f(&mut EguiText),
351    }
352}
353
354/// What the system clipboard holds now, read once per paste (paste
355/// special asks several times) and per pass.
356fn system_read(app: &AppHandle) -> Option<Vec<Repr>> {
357    let ctx = app.egui();
358    let now = ctx.cumulative_pass_nr();
359    let st = state(app);
360    if let Some((at, reprs)) = st.read_cache.borrow().as_ref()
361        && *at == now
362    {
363        return reprs.clone();
364    }
365    let reprs = with_backend(app, |b| b.read(&ctx));
366    *st.read_cache.borrow_mut() = Some((now, reprs.clone()));
367    reprs
368}
369
370/// Says that the copy, cut and paste chords arrive as plain keys
371/// (eframe's `NativeOptions::clipboard_shortcuts` off), so the keymap
372/// runs them everywhere: `edit.copy`, `edit.cut` and `edit.paste` then
373/// also run while a text field has the focus, and give it egui's own
374/// `Event::Copy`, `Event::Cut` and `Event::Paste` (the text read through
375/// the system backend), as egui-winit would have. A remapped chord then
376/// edits text fields too.
377///
378/// `AppBuilder::run_native` sets it when it turns the shortcuts off:
379/// with [`SYSTEM_PLUGIN`] added, or when the application's options
380/// already have them off. Off (the default), text fields keep egui's own
381/// copy and paste: the web, the default backend (which reads nothing, so
382/// it could not paste into a text field) and applications on eframe's
383/// own runner.
384pub fn set_keymap_shortcuts(app: &AppHandle, on: bool) {
385    state(app).keymap_shortcuts.set(on);
386}
387
388/// Whether the keymap runs the copy, cut and paste chords in text fields
389/// too ([`set_keymap_shortcuts`]).
390pub fn keymap_shortcuts(app: &AppHandle) -> bool {
391    state(app).keymap_shortcuts.get()
392}
393
394/// An Edit command for the text field with the focus, when the keymap
395/// runs the chords there ([`set_keymap_shortcuts`]) and the command
396/// names no endpoint: egui's own event, as egui-winit would have sent
397/// it, read by the field later in this pass. A paste takes `args.text`,
398/// else the system clipboard's text.
399fn to_text_field(app: &AppHandle, args: &Json, event: egui::Event) -> Option<Result<Json, String>> {
400    if !keymap_shortcuts(app) || args.get("source").is_some() || args.get("target").is_some() {
401        return None;
402    }
403    let ctx = app.egui();
404    if !ctx.text_edit_focused() {
405        return None;
406    }
407    let event = match event {
408        egui::Event::Paste(_) => {
409            let text = match args.get("text").and_then(Json::as_str) {
410                Some(t) => Some(t.to_string()),
411                None => system_read(app).and_then(|reprs| {
412                    reprs
413                        .iter()
414                        .find(|r| r.format == TEXT)
415                        .and_then(Repr::text)
416                        .map(|t| t.replace("\r\n", "\n"))
417                }),
418            };
419            match text {
420                Some(t) if !t.is_empty() => egui::Event::Paste(t),
421                _ => return Some(Err("the system clipboard holds no text".into())),
422            }
423        }
424        e => e,
425    };
426    let name = match &event {
427        egui::Event::Copy => "copy",
428        egui::Event::Cut => "cut",
429        _ => "paste",
430    };
431    ctx.input_mut(|i| i.events.push(event));
432    Some(Ok(json!({ "text_field": name })))
433}
434
435/// The primary selection's text, through the system backend (opt-in:
436/// egui-pop's own widgets do not use it yet).
437pub fn primary_text(app: &AppHandle) -> Option<String> {
438    with_backend(app, |b| b.read_primary())
439}
440
441/// Sets the primary selection's text, through the system backend.
442pub fn set_primary_text(app: &AppHandle, text: &str) -> Result<(), String> {
443    with_backend(app, |b| b.write_primary(text))
444}
445
446/// The default rule: the user may use any slot, a session (an agent, a
447/// script) its own only.
448pub fn default_access(origin: &Origin, slot: &Slot) -> Result<(), String> {
449    if *origin == Origin::User || *slot == Slot::of(origin) {
450        Ok(())
451    } else {
452        Err(format!(
453            "`{}` may not use the `{slot}` clipboard: a session has its own unless the host allows it",
454            source_of(origin)
455        ))
456    }
457}
458
459/// The default owner: one item per slot, in memory.
460#[derive(Debug, Default)]
461pub struct LocalClipboard {
462    items: BTreeMap<Slot, ClipItem>,
463    rev: u64,
464    allowed: BTreeSet<String>,
465    events: Vec<(String, Json)>,
466}
467
468impl LocalClipboard {
469    pub fn new() -> Self {
470        Self::default()
471    }
472
473    /// Lets a session (`agent:<name>`) use every slot, the user's
474    /// included.
475    pub fn allow(&mut self, session: &str) {
476        self.allowed.insert(session.into());
477    }
478}
479
480impl Clipboard for LocalClipboard {
481    fn put(&mut self, slot: &Slot, item: ClipItem, _origin: &Origin) -> Answer {
482        self.rev += 1;
483        self.events.push((
484            "clipboard.changed".into(),
485            json!({ "slot": slot, "kind": item.kind, "rev": self.rev }),
486        ));
487        self.items.insert(slot.clone(), item);
488        Answer::Done(Ok(self.rev))
489    }
490
491    fn get(&self, slot: &Slot) -> Option<ClipItem> {
492        self.items.get(slot).cloned()
493    }
494
495    fn rev(&self) -> u64 {
496        self.rev
497    }
498
499    fn may_use(&self, origin: &Origin, slot: &Slot) -> Result<(), String> {
500        if self.allowed.contains(&source_of(origin)) {
501            return Ok(());
502        }
503        default_access(origin, slot)
504    }
505
506    fn take_events(&mut self) -> Vec<(String, Json)> {
507        std::mem::take(&mut self.events)
508    }
509}
510
511/// A cut's delete: the item copied, who cuts, and the history group its
512/// writes carry (`Set::gesture`) so that the delete is one undo step.
513#[derive(Debug)]
514pub struct Cut<'a> {
515    pub item: &'a ClipItem,
516    pub origin: &'a Origin,
517    pub group: Option<GestureId>,
518    /// The element cut (a node, a row): the key its widget was bound
519    /// with ([`bind_element`]), or the one a request named.
520    pub element: Option<&'a str>,
521}
522
523/// What a copy takes from a component.
524pub trait ClipSource {
525    /// The selection as an item; `None`: nothing to copy.
526    fn copy(&self, app: &AppHandle) -> Option<ClipItem>;
527
528    /// What a copy takes from one element of the endpoint (a node, a
529    /// row: the key its widget was bound with, [`bind_element`], or the
530    /// one a request named); by default [`ClipSource::copy`], whatever
531    /// the element.
532    fn copy_element(&self, app: &AppHandle, element: Option<&str>) -> Option<ClipItem> {
533        let _ = element;
534        self.copy(app)
535    }
536
537    /// Whether a copy would take something now (`canCopy`).
538    fn can_copy(&self, _app: &AppHandle) -> bool {
539        true
540    }
541
542    /// Whether a cut may delete the selection now (`canCut`); by
543    /// default a source copies only.
544    fn can_cut(&self, _app: &AppHandle) -> bool {
545        false
546    }
547
548    /// Deletes what a cut copies; an error refuses the cut, and nothing
549    /// is copied.
550    fn delete(&self, _app: &AppHandle, _cut: &Cut<'_>) -> Result<(), String> {
551        Err("this cannot be cut".into())
552    }
553}
554
555/// A paste as a target receives it.
556#[derive(Debug)]
557pub struct Paste<'a> {
558    /// The representation, in the format the plan chose (transformed).
559    pub repr: &'a Repr,
560    pub plan: &'a Plan,
561    /// The item it comes from (its title, origin, payload).
562    pub item: &'a ClipItem,
563    /// The parts asked for (paste special), all when `None`.
564    pub parts: Option<&'a [String]>,
565    /// Say what would change, change nothing.
566    pub dry_run: bool,
567    pub origin: &'a Origin,
568    /// The history group the target's writes carry (`Set::gesture`):
569    /// the paste is one undo step.
570    pub group: Option<GestureId>,
571    /// The element pasted into (a node, a row): the key its widget was
572    /// bound with ([`bind_element`]), or the one a request named.
573    pub element: Option<&'a str>,
574}
575
576impl Paste<'_> {
577    /// Whether a part is asked for.
578    pub fn wants(&self, part: &str) -> bool {
579        self.parts.is_none_or(|p| p.iter().any(|x| x == part))
580    }
581}
582
583/// Where a paste goes in a component.
584pub trait ClipTarget {
585    /// The formats it accepts, richest first.
586    fn accepts(&self, app: &AppHandle) -> Vec<FormatId>;
587
588    /// Applies a paste, or for a dry run says what it would change: its
589    /// changes as JSON (a dry run's are paste special's preview, a
590    /// string reading best).
591    fn paste(&self, app: &AppHandle, paste: &Paste<'_>) -> Result<Json, String>;
592
593    /// Applies a paste (never a dry run: paste special's previews and an
594    /// agent's plan go through [`ClipTarget::paste`]). A target whose
595    /// edit goes through the application's own loop (a network edit, a
596    /// viewport command applied next frame) answers [`Pasted::Later`]
597    /// with a result to come ([`crate::host::pending`]): its writes still
598    /// carry `paste.group`, which stays open until the result arrives,
599    /// so the paste remains one undo step; the result is published as
600    /// `clipboard.pasted` and a failure shown to the user. By default,
601    /// [`ClipTarget::paste`] now.
602    fn apply(&self, app: &AppHandle, paste: &Paste<'_>) -> Pasted {
603        Pasted::Done(self.paste(app, paste))
604    }
605
606    /// What a transform may know of the target before adapting a paste
607    /// to it ([`Transform::for_target`]): the image a mask lands on, the
608    /// range a value is clamped to, the names a pasted one must not
609    /// take. `element` is the element pasted into, if any. Nothing by
610    /// default.
611    fn context(&self, app: &AppHandle, element: Option<&str>) -> Json {
612        let _ = (app, element);
613        Json::Null
614    }
615}
616
617/// What a target answers a paste it applies ([`ClipTarget::apply`]).
618#[derive(Debug)]
619pub enum Pasted {
620    /// Its changes, or why it refused, now.
621    Done(Result<Json, String>),
622    /// The result comes later (the application's loop applies it).
623    Later(Pending),
624}
625
626/// A paste whose result is to come: its group stays open until then.
627struct Deferred {
628    pending: Pending,
629    group: Option<GestureId>,
630    origin: Origin,
631    summary: Json,
632}
633
634/// The target a transform adapts a paste to.
635#[derive(Clone, Copy, Debug)]
636pub struct Destination<'a> {
637    /// The endpoint's name.
638    pub target: &'a str,
639    /// The element pasted into, if any.
640    pub element: Option<&'a str>,
641    /// What the target says of itself ([`ClipTarget::context`]).
642    pub context: &'a Json,
643}
644
645type RenderFn = Rc<dyn Fn(&Json) -> Vec<Repr>>;
646type PartsFn = Rc<dyn Fn(&Json) -> Vec<Part>>;
647type MigrateFn = Rc<dyn Fn(u32, Json) -> Result<Json, String>>;
648type TransformFn = Rc<dyn Fn(&Repr, &Destination<'_>) -> Result<Transformed, String>>;
649type AppliesFn = Rc<dyn Fn(&Repr, &str) -> bool>;
650type SanitiseFn = Rc<dyn Fn(&mut Json) -> Vec<String>>;
651
652/// A part of an item a paste special may take alone (a parameter set's
653/// modules).
654#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
655pub struct Part {
656    pub id: String,
657    pub title: String,
658}
659
660impl Part {
661    pub fn new(id: &str, title: &str) -> Self {
662        Self {
663            id: id.into(),
664            title: title.into(),
665        }
666    }
667}
668
669/// A type of item a plugin declares and owns.
670#[derive(Clone)]
671pub struct ClipType {
672    pub format: FormatId,
673    /// Its current version: an older item is migrated before a paste.
674    pub version: u32,
675    /// What one is called ("a colour").
676    pub title: String,
677    /// Kept inside the owner only: nothing goes to the system clipboard.
678    pub internal: bool,
679    render: Option<RenderFn>,
680    parts: Option<PartsFn>,
681    migrate: Option<MigrateFn>,
682}
683
684impl fmt::Debug for ClipType {
685    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
686        f.debug_struct("ClipType")
687            .field("format", &self.format)
688            .field("version", &self.version)
689            .field("title", &self.title)
690            .field("internal", &self.internal)
691            .finish_non_exhaustive()
692    }
693}
694
695impl ClipType {
696    pub fn new(format: FormatId, version: u32, title: &str) -> Self {
697        Self {
698            format,
699            version,
700            title: title.into(),
701            internal: false,
702            render: None,
703            parts: None,
704            migrate: None,
705        }
706    }
707
708    /// Never written to the system clipboard (a secret, a huge item).
709    pub fn internal(mut self) -> Self {
710        self.internal = true;
711        self
712    }
713
714    /// Renders its fallbacks (text always; HTML when it has one), for
715    /// items whose source gave none.
716    pub fn fallbacks(mut self, f: impl Fn(&Json) -> Vec<Repr> + 'static) -> Self {
717        self.render = Some(Rc::new(f));
718        self
719    }
720
721    /// Lists its parts, for paste special.
722    pub fn parts(mut self, f: impl Fn(&Json) -> Vec<Part> + 'static) -> Self {
723        self.parts = Some(Rc::new(f));
724        self
725    }
726
727    /// Migrates a payload made at an older version (given) to the
728    /// current one.
729    pub fn migrate(mut self, f: impl Fn(u32, Json) -> Result<Json, String> + 'static) -> Self {
730        self.migrate = Some(Rc::new(f));
731        self
732    }
733}
734
735/// What a transform made: the data, and what it lost if anything.
736#[derive(Clone, Debug, PartialEq)]
737pub struct Transformed {
738    pub data: Json,
739    pub lost: Option<String>,
740}
741
742impl Transformed {
743    pub fn exact(data: Json) -> Self {
744        Self { data, lost: None }
745    }
746
747    pub fn lossy(data: Json, lost: &str) -> Self {
748        Self {
749            data,
750            lost: Some(lost.into()),
751        }
752    }
753}
754
755/// A transform a plugin declares and owns.
756#[derive(Clone)]
757pub struct Transform {
758    pub spec: TransformSpec,
759    applies: Option<AppliesFn>,
760    run: TransformFn,
761}
762
763impl fmt::Debug for Transform {
764    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
765        f.debug_struct("Transform")
766            .field("spec", &self.spec)
767            .finish_non_exhaustive()
768    }
769}
770
771impl Transform {
772    pub fn new(
773        spec: TransformSpec,
774        f: impl Fn(&Repr) -> Result<Transformed, String> + 'static,
775    ) -> Self {
776        Self {
777            spec,
778            applies: None,
779            run: Rc::new(move |r, _| f(r)),
780        }
781    }
782
783    /// A transform that adapts to the target: it also receives the
784    /// target's name, element and context ([`ClipTarget::context`]): a
785    /// mask scaled to the image it lands on, a value clamped to the
786    /// target's range, a name made unique. What it loses shows in the
787    /// toast and in paste special's preview like any other loss.
788    pub fn for_target(
789        spec: TransformSpec,
790        f: impl Fn(&Repr, &Destination<'_>) -> Result<Transformed, String> + 'static,
791    ) -> Self {
792        Self {
793            spec,
794            applies: None,
795            run: Rc::new(f),
796        }
797    }
798
799    /// When it applies: given the representation and the target's name.
800    pub fn when(mut self, f: impl Fn(&Repr, &str) -> bool + 'static) -> Self {
801        self.applies = Some(Rc::new(f));
802        self
803    }
804}
805
806/// A sanitiser a plugin declares and owns: run on each representation
807/// crossing its boundary (of its format, or all), it removes what must
808/// not cross and says what it removed.
809#[derive(Clone)]
810pub struct Sanitiser {
811    pub id: String,
812    pub boundary: Boundary,
813    pub format: Option<FormatId>,
814    run: SanitiseFn,
815}
816
817impl fmt::Debug for Sanitiser {
818    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
819        f.debug_struct("Sanitiser")
820            .field("id", &self.id)
821            .field("boundary", &self.boundary)
822            .field("format", &self.format)
823            .finish_non_exhaustive()
824    }
825}
826
827impl Sanitiser {
828    pub fn new(
829        id: &str,
830        boundary: Boundary,
831        f: impl Fn(&mut Json) -> Vec<String> + 'static,
832    ) -> Self {
833        Self {
834            id: id.into(),
835            boundary,
836            format: None,
837            run: Rc::new(f),
838        }
839    }
840
841    /// Only for one format.
842    pub fn format(mut self, format: FormatId) -> Self {
843        self.format = Some(format);
844        self
845    }
846}
847
848/// A component's endpoint: what a copy takes, where a paste goes.
849#[derive(Clone)]
850struct Endpoint {
851    owner: Option<OwnerId>,
852    source: Option<Rc<dyn ClipSource>>,
853    target: Option<Rc<dyn ClipTarget>>,
854    widget: Option<egui::Id>,
855    /// An area: any focused widget whose centre lies inside, with the
856    /// pass it was bound in.
857    area: Option<(egui::Rect, u64)>,
858    /// Its elements' widgets: their keys and the pass each was bound in.
859    elements: HashMap<egui::Id, (String, u64)>,
860}
861
862/// Whether something bound in pass `at` is still current in pass `now`
863/// (bound this pass or the one before: a pass may ask before drawing).
864fn current(at: u64, now: u64) -> bool {
865    now.saturating_sub(at) <= 1
866}
867
868/// What the system clipboard holds, as far as the owner knows.
869#[derive(Debug, Default)]
870struct System {
871    /// The format and the marker of what the last copy wrote there (its
872    /// text when it wrote some).
873    written: Option<(FormatId, u64)>,
874    /// The last user copy was internal only: nothing was written.
875    internal_only: bool,
876    /// The marker of what a paste found there since that copy.
877    seen: Option<u64>,
878}
879
880/// A representation's marker: its text's, else its data's.
881fn mark(r: &Repr) -> u64 {
882    match r.text() {
883        Some(t) => model::marker(t),
884        None => model::marker(&r.data.to_string()),
885    }
886}
887
888/// The representation a marker is taken from: text when there is some,
889/// else the first.
890fn marked(reprs: &[Repr]) -> Option<&Repr> {
891    reprs.iter().find(|r| r.format == TEXT).or(reprs.first())
892}
893
894#[derive(Default)]
895struct State {
896    connected: Cell<bool>,
897    custom: Cell<bool>,
898    local: RefCell<LocalClipboard>,
899    endpoints: RefCell<BTreeMap<String, Endpoint>>,
900    types: RefCell<Vec<(OwnerId, ClipType)>>,
901    transforms: RefCell<Vec<(OwnerId, Transform)>>,
902    sanitisers: RefCell<Vec<(OwnerId, Sanitiser)>>,
903    system: RefCell<System>,
904    deferred: RefCell<Vec<Deferred>>,
905    backend: RefCell<Option<Box<dyn SystemBackend>>>,
906    paste_key: RefCell<PasteKey>,
907    /// The last read of the system clipboard, with its pass.
908    read_cache: RefCell<Option<(u64, Option<Vec<Repr>>)>>,
909    /// The keymap runs the chords in text fields too
910    /// ([`set_keymap_shortcuts`]).
911    keymap_shortcuts: Cell<bool>,
912}
913
914fn state(app: &AppHandle) -> Rc<State> {
915    app.local::<State>()
916}
917
918/// Runs `f` on the owner: the host's, else the plugin's
919/// `LocalClipboard`. `None` without the plugin, or while the host
920/// (owning the clipboard) runs a command.
921pub fn with_owner<R>(app: &AppHandle, f: impl FnOnce(&mut dyn Clipboard) -> R) -> Option<R> {
922    let st = state(app);
923    if !st.connected.get() {
924        return None;
925    }
926    let custom = match app.with_host_mut(|h| h.clipboard().is_some()) {
927        Some(c) => {
928            st.custom.set(c);
929            c
930        }
931        None => st.custom.get(),
932    };
933    if custom {
934        app.with_host_mut(|h| h.clipboard().map(f)).flatten()
935    } else {
936        let mut local = st.local.borrow_mut();
937        Some(f(&mut *local))
938    }
939}
940
941/// Lets a session (`agent:<name>`) use the user's slot, when the owner
942/// is egui-pop's `LocalClipboard`.
943pub fn allow_session(app: &AppHandle, session: &str) {
944    state(app).local.borrow_mut().allow(session);
945}
946
947/// Registers a component's endpoint by name (replacing one of that
948/// name): its source, its target, or both.
949pub fn register(
950    app: &AppHandle,
951    name: &str,
952    source: Option<Rc<dyn ClipSource>>,
953    target: Option<Rc<dyn ClipTarget>>,
954) {
955    add_endpoint(app, None, name, source, target);
956}
957
958fn add_endpoint(
959    app: &AppHandle,
960    owner: Option<OwnerId>,
961    name: &str,
962    source: Option<Rc<dyn ClipSource>>,
963    target: Option<Rc<dyn ClipTarget>>,
964) {
965    let st = state(app);
966    let mut eps = st.endpoints.borrow_mut();
967    let (widget, area, elements) = eps
968        .remove(name)
969        .map(|e| (e.widget, e.area, e.elements))
970        .unwrap_or_default();
971    eps.insert(
972        name.into(),
973        Endpoint {
974            owner,
975            source,
976            target,
977            widget,
978            area,
979            elements,
980        },
981    );
982}
983
984/// Removes an endpoint.
985pub fn unregister(app: &AppHandle, name: &str) {
986    state(app).endpoints.borrow_mut().remove(name);
987}
988
989/// Says which widget draws an endpoint, each pass it is drawn: while
990/// that widget has the focus, the Edit commands use the endpoint.
991pub fn bind(app: &AppHandle, name: &str, widget: egui::Id) {
992    if let Some(e) = state(app).endpoints.borrow_mut().get_mut(name) {
993        e.widget = Some(widget);
994    }
995}
996
997/// The names of the endpoints registered.
998pub fn endpoints(app: &AppHandle) -> Vec<String> {
999    state(app).endpoints.borrow().keys().cloned().collect()
1000}
1001
1002/// Says that an endpoint covers an area, each pass it is drawn: any
1003/// focused widget whose centre lies inside it (a node of a graph, a row
1004/// of a tree, a slider of a list) uses the endpoint. A widget bound
1005/// alone ([`bind`], [`bind_element`]) wins over an area.
1006///
1007/// The focused widget's rectangle is read from egui's lists of widgets,
1008/// never through `Context::read_response`: building a response for a
1009/// widget that is not hovered during a press makes egui surrender its
1010/// focus.
1011pub fn bind_area(app: &AppHandle, name: &str, area: egui::Rect) {
1012    let now = app.egui().cumulative_pass_nr();
1013    if let Some(e) = state(app).endpoints.borrow_mut().get_mut(name) {
1014        e.area = Some((area, now));
1015    }
1016}
1017
1018/// Says which widget draws one element of an endpoint (a node, a row)
1019/// and its key, each pass it is drawn: while that widget has the focus,
1020/// the Edit commands use the endpoint, and its source and target receive
1021/// the key ([`ClipSource::copy_element`], [`Cut::element`],
1022/// [`Paste::element`]).
1023pub fn bind_element(app: &AppHandle, name: &str, widget: egui::Id, key: &str) {
1024    let now = app.egui().cumulative_pass_nr();
1025    if let Some(e) = state(app).endpoints.borrow_mut().get_mut(name) {
1026        e.elements.retain(|_, (_, at)| current(*at, now));
1027        e.elements.insert(widget, (key.into(), now));
1028    }
1029}
1030
1031/// The key of an endpoint's element whose widget has the focus, if one
1032/// was bound ([`bind_element`]).
1033pub fn element(app: &AppHandle, name: &str) -> Option<String> {
1034    let ctx = app.egui();
1035    let id = ctx.memory(|m| m.focused())?;
1036    let now = ctx.cumulative_pass_nr();
1037    state(app)
1038        .endpoints
1039        .borrow()
1040        .get(name)?
1041        .elements
1042        .get(&id)
1043        .filter(|(_, at)| current(*at, now))
1044        .map(|(k, _)| k.clone())
1045}
1046
1047/// A widget's rectangle from egui's lists of widgets (this pass's, else
1048/// the last one's), with no side effect on the focus.
1049fn widget_rect(ctx: &egui::Context, id: egui::Id) -> Option<egui::Rect> {
1050    ctx.viewport(|v| {
1051        v.this_pass
1052            .widgets
1053            .get(id)
1054            .or_else(|| v.prev_pass.widgets.get(id))
1055            .map(|w| w.rect)
1056    })
1057}
1058
1059/// The endpoint whose widget has the focus: one bound to it alone or as
1060/// an element, else one whose area holds it.
1061pub fn focused(app: &AppHandle) -> Option<String> {
1062    let ctx = app.egui();
1063    let id = ctx.memory(|m| m.focused())?;
1064    let now = ctx.cumulative_pass_nr();
1065    let st = state(app);
1066    let eps = st.endpoints.borrow();
1067    if let Some((n, _)) = eps.iter().find(|(_, e)| {
1068        e.widget == Some(id) || e.elements.get(&id).is_some_and(|(_, at)| current(*at, now))
1069    }) {
1070        return Some(n.clone());
1071    }
1072    let areas: Vec<(&String, egui::Rect)> = eps
1073        .iter()
1074        .filter_map(|(n, e)| {
1075            e.area
1076                .filter(|(_, at)| current(*at, now))
1077                .map(|(r, _)| (n, r))
1078        })
1079        .collect();
1080    if areas.is_empty() {
1081        return None;
1082    }
1083    let centre = widget_rect(&ctx, id)?.center();
1084    // The smallest area holding it: an area nested in another wins.
1085    areas
1086        .into_iter()
1087        .filter(|(_, r)| r.contains(centre))
1088        .min_by(|a, b| a.1.area().total_cmp(&b.1.area()))
1089        .map(|(n, _)| n.clone())
1090}
1091
1092fn endpoint(app: &AppHandle, name: &str) -> Option<Endpoint> {
1093    state(app).endpoints.borrow().get(name).cloned()
1094}
1095
1096/// The type declared for a format.
1097pub fn clip_type(app: &AppHandle, format: &FormatId) -> Option<ClipType> {
1098    state(app)
1099        .types
1100        .borrow()
1101        .iter()
1102        .find(|(_, t)| t.format == *format)
1103        .map(|(_, t)| t.clone())
1104}
1105
1106/// The transforms declared.
1107pub fn transforms(app: &AppHandle) -> Vec<TransformSpec> {
1108    state(app)
1109        .transforms
1110        .borrow()
1111        .iter()
1112        .map(|(_, t)| t.spec.clone())
1113        .collect()
1114}
1115
1116fn transform(app: &AppHandle, id: &str) -> Option<Transform> {
1117    state(app)
1118        .transforms
1119        .borrow()
1120        .iter()
1121        .find(|(_, t)| t.spec.id == id)
1122        .map(|(_, t)| t.clone())
1123}
1124
1125/// Runs the sanitisers of a boundary on representations: what went.
1126fn sanitise(app: &AppHandle, boundary: Boundary, reprs: &mut [Repr]) -> Vec<Stripped> {
1127    let sanitisers: Vec<Sanitiser> = state(app)
1128        .sanitisers
1129        .borrow()
1130        .iter()
1131        .filter(|(_, s)| s.boundary == boundary)
1132        .map(|(_, s)| s.clone())
1133        .collect();
1134    let mut out = Vec::new();
1135    for r in reprs.iter_mut() {
1136        for s in sanitisers
1137            .iter()
1138            .filter(|s| s.format.as_ref().is_none_or(|f| *f == r.format))
1139        {
1140            for what in (s.run)(&mut r.data) {
1141                out.push(Stripped {
1142                    by: s.id.clone(),
1143                    what,
1144                    boundary,
1145                    format: r.format.clone(),
1146                });
1147            }
1148        }
1149    }
1150    out
1151}
1152
1153/// The catalogue key of a type's title: `clip-<slug(format)>.title`.
1154pub fn type_title_key(format: &FormatId) -> String {
1155    strings::declared_key(strings::kind::CLIP, format.as_str(), Some("title"))
1156}
1157
1158/// What an item is called, in the interface's language: its own message
1159/// ([`ClipItem::title_key`]), else its type's declared title when the
1160/// item kept it, else its English title, else its format.
1161pub fn title_of(app: &AppHandle, item: &ClipItem) -> String {
1162    let ctx = app.egui();
1163    if let Some(k) = &item.title_key {
1164        let args: Vec<(&str, &str)> = k
1165            .args
1166            .iter()
1167            .map(|(a, v)| (a.as_str(), v.as_str()))
1168            .collect();
1169        return strings::lookup_args(&ctx, &k.key, &item.title, &args);
1170    }
1171    if item.external && item.kind == TEXT {
1172        return strings::tr(&ctx, &txt::CLIPBOARD_TEXT);
1173    }
1174    let ty = clip_type(app, &item.kind);
1175    match ty {
1176        Some(t) if item.title.is_empty() || item.title == t.title => {
1177            strings::lookup(&ctx, &type_title_key(&t.format), &t.title)
1178        }
1179        _ if !item.title.is_empty() => item.title.clone(),
1180        _ => item.kind.to_string(),
1181    }
1182}
1183
1184/// What a format is called, in the interface's language: plain text, a
1185/// declared type's title, else the format itself.
1186pub fn format_title(app: &AppHandle, format: &FormatId) -> String {
1187    let ctx = app.egui();
1188    if *format == TEXT {
1189        return strings::tr(&ctx, &txt::CLIPBOARD_TEXT);
1190    }
1191    clip_type(app, format).map_or_else(
1192        || format.to_string(),
1193        |t| strings::lookup(&ctx, &type_title_key(format), &t.title),
1194    )
1195}
1196
1197/// The types declared, with the plugin owning each (for catalogues:
1198/// each type's title is a declaration, keyed by [`type_title_key`]).
1199pub fn types(app: &AppHandle) -> Vec<(OwnerId, ClipType)> {
1200    state(app).types.borrow().clone()
1201}
1202
1203fn capitalised(text: &str) -> String {
1204    let mut c = text.chars();
1205    match c.next() {
1206        Some(f) => f.to_uppercase().chain(c).collect(),
1207        None => String::new(),
1208    }
1209}
1210
1211fn group_begin(app: &AppHandle, origin: &Origin, label: &str) -> Option<GestureId> {
1212    app.with_host_mut(|h| h.begin_group(origin, label))
1213        .flatten()
1214}
1215
1216fn group_end(app: &AppHandle, group: Option<GestureId>, keep: bool) {
1217    if let Some(g) = group {
1218        app.with_host_mut(|h| h.end_group(g, keep));
1219    }
1220}
1221
1222fn publish_events(app: &AppHandle, source: &str, events: Vec<(String, Json)>) {
1223    for (name, data) in events {
1224        app.publish(source, None, &name, data);
1225    }
1226}
1227
1228/// A copy, as the `clipboard.copy` step's arguments.
1229#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1230pub struct CopyRequest {
1231    /// The endpoint copied from.
1232    pub source: String,
1233    /// The slot written (the origin's own by default).
1234    #[serde(default, skip_serializing_if = "Option::is_none")]
1235    pub slot: Option<Slot>,
1236    /// A cut: the source deletes what was copied.
1237    #[serde(default)]
1238    pub cut: bool,
1239    /// Say what would be copied and left out, copy nothing.
1240    #[serde(default)]
1241    pub dry_run: bool,
1242    /// The element copied from (a node, a row); the focused one's when
1243    /// the Edit commands copy.
1244    #[serde(default, skip_serializing_if = "Option::is_none")]
1245    pub element: Option<String>,
1246}
1247
1248impl CopyRequest {
1249    pub fn new(source: &str) -> Self {
1250        Self {
1251            source: source.into(),
1252            ..Self::default()
1253        }
1254    }
1255
1256    pub fn cut(mut self) -> Self {
1257        self.cut = true;
1258        self
1259    }
1260
1261    pub fn dry_run(mut self) -> Self {
1262        self.dry_run = true;
1263        self
1264    }
1265
1266    pub fn slot(mut self, slot: Slot) -> Self {
1267        self.slot = Some(slot);
1268        self
1269    }
1270
1271    /// The element copied from.
1272    pub fn element(mut self, key: &str) -> Self {
1273        self.element = Some(key.into());
1274        self
1275    }
1276}
1277
1278/// A paste, as the `clipboard.paste` step's arguments.
1279#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1280pub struct PasteRequest {
1281    /// The endpoint pasted into.
1282    pub target: String,
1283    /// The slot read (the origin's own by default).
1284    #[serde(default, skip_serializing_if = "Option::is_none")]
1285    pub slot: Option<Slot>,
1286    /// The format the target should receive.
1287    #[serde(default, skip_serializing_if = "Option::is_none")]
1288    pub format: Option<FormatId>,
1289    /// The transform to go through.
1290    #[serde(default, skip_serializing_if = "Option::is_none")]
1291    pub transform: Option<String>,
1292    /// Only these parts of the item.
1293    #[serde(default, skip_serializing_if = "Option::is_none")]
1294    pub parts: Option<Vec<String>>,
1295    /// Refused unless the owner is at this revision.
1296    #[serde(default, skip_serializing_if = "Option::is_none")]
1297    pub if_rev: Option<u64>,
1298    /// Say what would be pasted and changed, change nothing.
1299    #[serde(default)]
1300    pub dry_run: bool,
1301    /// What the system clipboard held, when the paste key brought it.
1302    #[serde(default, skip_serializing_if = "Option::is_none")]
1303    pub text: Option<String>,
1304    /// The element pasted into (a node, a row); the focused one's when
1305    /// the Edit commands paste.
1306    #[serde(default, skip_serializing_if = "Option::is_none")]
1307    pub element: Option<String>,
1308    /// The paste key found no text on the system clipboard (it holds
1309    /// files, an image, or nothing): what it holds is read through the
1310    /// system backend, and a paste is refused when the backend reads
1311    /// nothing while the system clipboard no longer holds what the owner
1312    /// wrote there.
1313    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1314    pub no_text: bool,
1315}
1316
1317impl PasteRequest {
1318    pub fn new(target: &str) -> Self {
1319        Self {
1320            target: target.into(),
1321            ..Self::default()
1322        }
1323    }
1324
1325    pub fn dry_run(mut self) -> Self {
1326        self.dry_run = true;
1327        self
1328    }
1329
1330    pub fn format(mut self, format: FormatId) -> Self {
1331        self.format = Some(format);
1332        self
1333    }
1334
1335    pub fn transform(mut self, id: &str) -> Self {
1336        self.transform = Some(id.into());
1337        self
1338    }
1339
1340    pub fn parts(mut self, parts: &[&str]) -> Self {
1341        self.parts = Some(parts.iter().map(|p| p.to_string()).collect());
1342        self
1343    }
1344
1345    pub fn if_rev(mut self, rev: u64) -> Self {
1346        self.if_rev = Some(rev);
1347        self
1348    }
1349
1350    /// The text the system clipboard held (the paste key's).
1351    pub fn text(mut self, text: &str) -> Self {
1352        self.text = Some(text.into());
1353        self
1354    }
1355
1356    pub fn slot(mut self, slot: Slot) -> Self {
1357        self.slot = Some(slot);
1358        self
1359    }
1360
1361    /// The element pasted into.
1362    pub fn element(mut self, key: &str) -> Self {
1363        self.element = Some(key.into());
1364        self
1365    }
1366}
1367
1368/// Copies through the [`STEP_COPY`] step. A refusal or a veto asked by
1369/// the user shows in a toast, and so does what was left out.
1370pub fn copy(app: &AppHandle, request: CopyRequest, origin: &Origin) -> Outcome {
1371    let mut args = serde_json::to_value(&request).unwrap_or(Json::Null);
1372    args["origin"] = json!(source_of(origin));
1373    let who = origin.clone();
1374    let out = app.step(&STEP_COPY, args, move |app, args| {
1375        let req: CopyRequest = parse(args, "a copy")?;
1376        run_copy(app, &req, &who)
1377    });
1378    if *origin == Origin::User {
1379        match &out {
1380            Outcome::Done(Ok(v)) => {
1381                let what: Vec<&str> = v["stripped"]
1382                    .as_array()
1383                    .map(|a| a.iter().filter_map(|s| s["what"].as_str()).collect())
1384                    .unwrap_or_default();
1385                if !what.is_empty() {
1386                    toast(
1387                        app,
1388                        &txt::CLIPBOARD_COPIED_STRIPPED,
1389                        "what",
1390                        &what.join(", "),
1391                        false,
1392                    );
1393                }
1394            }
1395            Outcome::Done(Err(e)) => toast(app, &txt::CLIPBOARD_NOT_COPIED, "reason", e, true),
1396            Outcome::Vetoed { reason, .. } => {
1397                toast(app, &txt::CLIPBOARD_NOT_COPIED, "reason", reason, true);
1398            }
1399        }
1400    }
1401    out
1402}
1403
1404fn run_copy(app: &AppHandle, req: &CopyRequest, who: &Origin) -> Result<Json, String> {
1405    let slot = req.slot.clone().unwrap_or_else(|| Slot::of(who));
1406    with_owner(app, |c| c.may_use(who, &slot)).ok_or(NO_PLUGIN)??;
1407    let ep = endpoint(app, &req.source).ok_or_else(|| format!("no endpoint `{}`", req.source))?;
1408    let source = ep
1409        .source
1410        .ok_or_else(|| format!("nothing can be copied from `{}`", req.source))?;
1411    // What the source writes (a cut's delete) is its plugin's own.
1412    let _scope = ep.owner.as_ref().map(egui_pop_model::values::enter_scope);
1413    if req.cut && !source.can_cut(app) {
1414        return Err(format!("`{}` cannot be cut", req.source));
1415    }
1416    let mut item = source
1417        .copy_element(app, req.element.as_deref())
1418        .ok_or_else(|| "nothing is selected to copy".to_string())?;
1419    let ty = clip_type(app, &item.kind);
1420    if item.title.is_empty() {
1421        item.title = ty.as_ref().map(|t| t.title.clone()).unwrap_or_default();
1422    }
1423    if item.fallbacks.is_empty()
1424        && let Some(render) = ty.as_ref().and_then(|t| t.render.clone())
1425    {
1426        item.fallbacks = render(&item.payload);
1427    }
1428    item.origin.by = source_of(who);
1429    item.origin.source = req.source.clone();
1430    let place = app.context().get("place").to_string();
1431    item.origin.place = (!place.is_empty()).then_some(place);
1432    // Inside the owner: its own sanitisers only (none by default).
1433    let mut own = [Repr::new(item.kind.clone(), item.payload.clone())];
1434    let mut stripped = sanitise(app, Boundary::Owner, &mut own);
1435    let [own] = own;
1436    item.payload = own.data;
1437    // Towards the system clipboard: the fallbacks, sanitised, and the
1438    // private type itself where the backend writes it.
1439    let internal = ty.as_ref().is_some_and(|t| t.internal);
1440    let to_system = slot == Slot::User && !internal;
1441    let mut system_out: Vec<Repr> = Vec::new();
1442    if to_system {
1443        if with_backend(app, |b| b.writes(&item.kind)) {
1444            system_out.push(Repr::new(item.kind.clone(), item.payload.clone()));
1445        }
1446        system_out.extend(item.fallbacks.iter().cloned());
1447        stripped.extend(sanitise(app, Boundary::System, &mut system_out));
1448        system_out.retain(|r| with_backend(app, |b| b.writes(&r.format)));
1449    }
1450    item.stripped = stripped;
1451    let summary = json!({
1452        "source": req.source,
1453        "element": req.element,
1454        "slot": slot,
1455        "kind": item.kind,
1456        "title": item.title,
1457        "offers": item.offers(),
1458        "stripped": item.stripped,
1459        "system": to_system,
1460        "cut": req.cut,
1461        "dry_run": req.dry_run,
1462    });
1463    if req.dry_run {
1464        return Ok(summary);
1465    }
1466    let group = if req.cut {
1467        let label = strings::tr_args(
1468            &app.egui(),
1469            &txt::CLIPBOARD_CUT_STEP,
1470            &[("title", &title_of(app, &item))],
1471        );
1472        let g = group_begin(app, who, &label);
1473        if let Err(e) = source.delete(
1474            app,
1475            &Cut {
1476                item: &item,
1477                origin: who,
1478                group: g,
1479                element: req.element.as_deref(),
1480            },
1481        ) {
1482            group_end(app, g, false);
1483            return Err(e);
1484        }
1485        g
1486    } else {
1487        None
1488    };
1489    let (answer, events) = with_owner(app, |c| {
1490        let a = c.put(&slot, item.clone(), who);
1491        (a, c.take_events())
1492    })
1493    .ok_or(NO_PLUGIN)?;
1494    publish_events(app, &source_of(who), events);
1495    let rev = match answer {
1496        Answer::Done(Ok(rev)) => json!(rev),
1497        Answer::Done(Err(e)) => {
1498            // A cut copies only once kept: its delete is put back.
1499            group_end(app, group, false);
1500            return Err(e);
1501        }
1502        Answer::Later(_) => json!(null),
1503    };
1504    group_end(app, group, true);
1505    let mut summary = summary;
1506    summary["rev"] = rev;
1507    if slot == Slot::User {
1508        let written = marked(&system_out).map(|r| (r.format.clone(), mark(r)));
1509        let ctx = app.egui();
1510        let wrote = match &written {
1511            Some(_) => with_backend(app, |b| b.write(&ctx, &system_out)),
1512            None => Ok(()),
1513        };
1514        let st = state(app);
1515        *st.read_cache.borrow_mut() = None;
1516        *st.system.borrow_mut() = match (&written, &wrote) {
1517            (Some(_), Ok(())) => System {
1518                written,
1519                ..System::default()
1520            },
1521            // Nothing written (an internal type, or the backend failed):
1522            // the system clipboard keeps what it held.
1523            _ => System {
1524                internal_only: true,
1525                ..System::default()
1526            },
1527        };
1528        if let Err(e) = wrote {
1529            log::warn!("the system clipboard was not written: {e}");
1530            summary["system_error"] = json!(e);
1531        }
1532    }
1533    Ok(summary)
1534}
1535
1536/// A paste made ready: the item, the plan, the representation.
1537struct Ready {
1538    target: Rc<dyn ClipTarget>,
1539    /// The plugin that registered the target: its writes are its own.
1540    owner: Option<OwnerId>,
1541    item: ClipItem,
1542    internal: bool,
1543    plan: Plan,
1544    repr: Repr,
1545    lost: Option<String>,
1546    stripped: Vec<Stripped>,
1547    element: Option<String>,
1548}
1549
1550/// The item a paste takes: the owner's, or the external text the paste
1551/// key brought when the system clipboard no longer holds what the owner
1552/// wrote there.
1553fn current_item(
1554    app: &AppHandle,
1555    slot: &Slot,
1556    text: Option<&str>,
1557    no_text: bool,
1558) -> Result<(ClipItem, bool), String> {
1559    let internal = with_owner(app, |c| c.get(slot)).ok_or(NO_PLUGIN)?;
1560    let owners = |internal: Option<ClipItem>| {
1561        internal
1562            .map(|i| (i, true))
1563            .ok_or_else(|| "the clipboard is empty".to_string())
1564    };
1565    if *slot != Slot::User {
1566        return owners(internal);
1567    }
1568    // What the system clipboard holds: what the backend reads (every
1569    // format), else the text the paste key brought.
1570    let read = system_read(app);
1571    let reprs = match (read, text) {
1572        (Some(r), _) if !r.is_empty() => r,
1573        (_, Some(t)) => vec![Repr::new(TEXT, Json::String(t.into()))],
1574        // The paste key found no text, nothing reads the rest, and what
1575        // the owner wrote there is gone: something else is there.
1576        (None, None) if no_text && state(app).system.borrow().written.is_some() => {
1577            return Err(
1578                "the system clipboard holds no text, and the clipboard backend reads nothing else"
1579                    .into(),
1580            );
1581        }
1582        _ => return owners(internal),
1583    };
1584    let st = state(app);
1585    let mut sys = st.system.borrow_mut();
1586    let ours = internal.is_some()
1587        && match &sys.written {
1588            Some((format, m)) => reprs
1589                .iter()
1590                .find(|r| r.format == *format)
1591                .is_some_and(|r| mark(r) == *m),
1592            None => {
1593                let m = marked(&reprs).map(mark);
1594                let ours = sys.internal_only && (sys.seen.is_none() || sys.seen == m);
1595                if sys.internal_only {
1596                    sys.seen = m;
1597                }
1598                ours
1599            }
1600        };
1601    match internal {
1602        Some(item) if ours => Ok((item, true)),
1603        _ => ClipItem::external(reprs)
1604            .map(|i| (i, false))
1605            .ok_or_else(|| "the clipboard is empty".into()),
1606    }
1607}
1608
1609fn prepare(app: &AppHandle, req: &PasteRequest, who: &Origin) -> Result<Ready, String> {
1610    let slot = req.slot.clone().unwrap_or_else(|| Slot::of(who));
1611    with_owner(app, |c| c.may_use(who, &slot)).ok_or(NO_PLUGIN)??;
1612    if let Some(want) = req.if_rev {
1613        let rev = with_owner(app, |c| c.rev()).ok_or(NO_PLUGIN)?;
1614        if rev != want {
1615            return Err(format!("the clipboard is at revision {rev}, not {want}"));
1616        }
1617    }
1618    let ep = endpoint(app, &req.target).ok_or_else(|| format!("no endpoint `{}`", req.target))?;
1619    let target = ep
1620        .target
1621        .ok_or_else(|| format!("nothing can be pasted into `{}`", req.target))?;
1622    let (mut item, internal) = current_item(app, &slot, req.text.as_deref(), req.no_text)?;
1623    // An item made at an older version of its type is migrated first.
1624    if let Some(t) = clip_type(app, &item.kind)
1625        && item.version < t.version
1626        && let Some(m) = &t.migrate
1627    {
1628        item.payload = m(item.version, item.payload.clone())?;
1629        item.version = t.version;
1630    }
1631    // External content is sanitised before any target sees it.
1632    let mut stripped = Vec::new();
1633    if item.external {
1634        let mut reprs: Vec<Repr> =
1635            std::iter::once(Repr::new(item.kind.clone(), item.payload.clone()))
1636                .chain(item.fallbacks.iter().cloned())
1637                .collect();
1638        stripped = sanitise(app, Boundary::External, &mut reprs);
1639        let mut reprs = reprs.into_iter();
1640        if let Some(first) = reprs.next() {
1641            item.payload = first.data;
1642        }
1643        item.fallbacks = reprs.collect();
1644    }
1645    let accepts = target.accepts(app);
1646    let specs: Vec<TransformSpec> = state(app)
1647        .transforms
1648        .borrow()
1649        .iter()
1650        .filter(|(_, t)| {
1651            item.repr(&t.spec.from)
1652                .is_some_and(|r| t.applies.as_ref().is_none_or(|f| f(&r, &req.target)))
1653        })
1654        .map(|(_, t)| t.spec.clone())
1655        .collect();
1656    let plan = model::choose(
1657        &item.offers(),
1658        &accepts,
1659        &specs,
1660        req.format.as_ref(),
1661        req.transform.as_deref(),
1662    )
1663    .map_err(|r| {
1664        if r.offered.is_empty() || req.format.is_some() || req.transform.is_some() {
1665            r.reason
1666        } else {
1667            format!(
1668                "{} cannot be pasted here ({})",
1669                capitalised(&title_of(app, &item)),
1670                r.reason
1671            )
1672        }
1673    })?;
1674    let mut repr = item
1675        .repr(&plan.format)
1676        .ok_or_else(|| format!("the item has no `{}`", plan.format))?;
1677    let mut lost = None;
1678    if let Some(id) = &plan.transform {
1679        let t = transform(app, id).ok_or_else(|| format!("no transform `{id}`"))?;
1680        let context = target.context(app, req.element.as_deref());
1681        let dest = Destination {
1682            target: &req.target,
1683            element: req.element.as_deref(),
1684            context: &context,
1685        };
1686        let out = (t.run)(&repr, &dest)?;
1687        repr = Repr::new(plan.to.clone(), out.data);
1688        lost = out
1689            .lost
1690            .or_else(|| t.spec.lossy.then(|| "some information".into()));
1691    }
1692    Ok(Ready {
1693        target,
1694        owner: ep.owner,
1695        item,
1696        internal,
1697        plan,
1698        repr,
1699        lost,
1700        stripped,
1701        element: req.element.clone(),
1702    })
1703}
1704
1705/// Pastes through the [`STEP_PASTE`] step. A refusal or a veto asked by
1706/// the user shows in a toast, and so does what a lossy transform lost.
1707pub fn paste(app: &AppHandle, request: PasteRequest, origin: &Origin) -> Outcome {
1708    *state(app).read_cache.borrow_mut() = None;
1709    let mut args = serde_json::to_value(&request).unwrap_or(Json::Null);
1710    args["origin"] = json!(source_of(origin));
1711    let who = origin.clone();
1712    let out = app.step(&STEP_PASTE, args, move |app, args| {
1713        let req: PasteRequest = parse(args, "a paste")?;
1714        run_paste(app, &req, &who)
1715    });
1716    if *origin == Origin::User {
1717        match &out {
1718            Outcome::Done(Ok(v)) => {
1719                // A deferred paste says its loss once it is made.
1720                if let (Some(lost), false) = (v["lost"].as_str(), v["pending"] == json!(true)) {
1721                    toast(app, &txt::CLIPBOARD_PASTED_LOSSY, "what", lost, false);
1722                }
1723            }
1724            Outcome::Done(Err(e)) => toast(app, &txt::CLIPBOARD_NOT_PASTED, "reason", e, true),
1725            Outcome::Vetoed { reason, .. } => {
1726                toast(app, &txt::CLIPBOARD_NOT_PASTED, "reason", reason, true);
1727            }
1728        }
1729    }
1730    out
1731}
1732
1733fn run_paste(app: &AppHandle, req: &PasteRequest, who: &Origin) -> Result<Json, String> {
1734    let ready = prepare(app, req, who)?;
1735    // What the target writes is its plugin's own.
1736    let _scope = ready
1737        .owner
1738        .as_ref()
1739        .map(egui_pop_model::values::enter_scope);
1740    let group = if req.dry_run {
1741        None
1742    } else {
1743        let label = strings::tr_args(
1744            &app.egui(),
1745            &txt::CLIPBOARD_PASTE_STEP,
1746            &[("title", &title_of(app, &ready.item))],
1747        );
1748        group_begin(app, who, &label)
1749    };
1750    let paste = Paste {
1751        repr: &ready.repr,
1752        plan: &ready.plan,
1753        item: &ready.item,
1754        parts: req.parts.as_deref(),
1755        dry_run: req.dry_run,
1756        origin: who,
1757        group,
1758        element: req.element.as_deref(),
1759    };
1760    let answer = if req.dry_run {
1761        Pasted::Done(ready.target.paste(app, &paste))
1762    } else {
1763        ready.target.apply(app, &paste)
1764    };
1765    let (changes, later) = match answer {
1766        Pasted::Done(changes) => {
1767            group_end(app, group, changes.is_ok());
1768            (changes?, None)
1769        }
1770        Pasted::Later(p) => (Json::Null, Some(p)),
1771    };
1772    let summary = json!({
1773        "target": req.target,
1774        "element": req.element,
1775        "kind": ready.item.kind,
1776        "title": ready.item.title,
1777        "internal": ready.internal,
1778        "format": ready.plan.format,
1779        "to": ready.plan.to,
1780        "transform": ready.plan.transform,
1781        "lossy": ready.plan.lossy,
1782        "lost": ready.lost,
1783        "stripped": ready.stripped,
1784        "parts": req.parts,
1785        "changes": changes,
1786        "dry_run": req.dry_run,
1787        "pending": later.is_some(),
1788    });
1789    if let Some(pending) = later {
1790        state(app).deferred.borrow_mut().push(Deferred {
1791            pending,
1792            group,
1793            origin: who.clone(),
1794            summary: summary.clone(),
1795        });
1796        app.egui().request_repaint();
1797    }
1798    Ok(summary)
1799}
1800
1801/// How many pastes wait for their result ([`Pasted::Later`]).
1802pub fn pending_pastes(app: &AppHandle) -> usize {
1803    state(app).deferred.borrow().len()
1804}
1805
1806/// Each pass: the deferred pastes whose result arrived close their undo
1807/// group (kept when they succeeded), publish `clipboard.pasted` (the
1808/// paste's summary with its `changes`, or its `error`) and, for the
1809/// user, show a failure or a loss.
1810fn settle(app: &AppHandle) {
1811    let arrived: Vec<(Deferred, Result<Json, String>)> = {
1812        let st = state(app);
1813        let mut list = st.deferred.borrow_mut();
1814        let mut out = Vec::new();
1815        let mut i = 0;
1816        while i < list.len() {
1817            match list[i].pending.take() {
1818                Some(r) => out.push((list.remove(i), r)),
1819                None => i += 1,
1820            }
1821        }
1822        out
1823    };
1824    for (d, result) in arrived {
1825        group_end(app, d.group, result.is_ok());
1826        let mut data = d.summary;
1827        data["pending"] = json!(false);
1828        match &result {
1829            Ok(changes) => data["changes"] = changes.clone(),
1830            Err(e) => data["error"] = json!(e),
1831        }
1832        app.publish(
1833            &source_of(&d.origin),
1834            None,
1835            "clipboard.pasted",
1836            data.clone(),
1837        );
1838        if d.origin == Origin::User {
1839            match &result {
1840                Ok(_) => {
1841                    if let Some(lost) = data["lost"].as_str() {
1842                        toast(app, &txt::CLIPBOARD_PASTED_LOSSY, "what", lost, false);
1843                    }
1844                }
1845                Err(e) => toast(app, &txt::CLIPBOARD_NOT_PASTED, "reason", e, true),
1846            }
1847        }
1848    }
1849}
1850
1851/// Every way the clipboard fits a target, as paste special lists them:
1852/// the plan, its label, the target's preview (a dry run), and the parts.
1853#[derive(Clone, Debug, PartialEq, Serialize)]
1854pub struct Way {
1855    pub plan: Plan,
1856    pub label: String,
1857    pub preview: Option<String>,
1858    /// Only these parts (none: the whole item).
1859    pub parts: Option<Vec<String>>,
1860}
1861
1862/// The ways a slot's item fits a target (`text`: what the paste key
1863/// brought): each format and transform, then each part alone.
1864pub fn ways(
1865    app: &AppHandle,
1866    target: &str,
1867    slot: Option<Slot>,
1868    text: Option<&str>,
1869    origin: &Origin,
1870) -> Result<Vec<Way>, String> {
1871    let base = PasteRequest {
1872        target: target.into(),
1873        slot,
1874        text: text.map(Into::into),
1875        ..PasteRequest::default()
1876    };
1877    ways_for(app, &base, origin)
1878}
1879
1880/// The ways a request's item fits its target (its `target`, `slot`,
1881/// `text` and `element`; its format, transform and parts ignored).
1882pub fn ways_for(
1883    app: &AppHandle,
1884    request: &PasteRequest,
1885    origin: &Origin,
1886) -> Result<Vec<Way>, String> {
1887    *state(app).read_cache.borrow_mut() = None;
1888    let base = PasteRequest {
1889        target: request.target.clone(),
1890        slot: request.slot.clone(),
1891        text: request.text.clone(),
1892        element: request.element.clone(),
1893        no_text: request.no_text,
1894        dry_run: true,
1895        ..PasteRequest::default()
1896    };
1897    let first = prepare(app, &base, origin)?;
1898    let specs: Vec<TransformSpec> = transforms(app);
1899    let accepts = first.target.accepts(app);
1900    let ctx = app.egui();
1901    let mut out = Vec::new();
1902    for plan in model::candidates(&first.item.offers(), &accepts, &specs) {
1903        let mut req = base.clone();
1904        req.format = Some(plan.to.clone());
1905        req.transform = plan.transform.clone();
1906        let Ok(ready) = prepare(app, &req, origin) else {
1907            continue;
1908        };
1909        let to = format_title(app, &plan.to);
1910        let mut label = match &plan.transform {
1911            Some(t) => strings::tr_args(
1912                &ctx,
1913                &txt::CLIPBOARD_AS_THROUGH,
1914                &[("format", &to), ("transform", t)],
1915            ),
1916            None => strings::tr_args(&ctx, &txt::CLIPBOARD_AS, &[("format", &to)]),
1917        };
1918        if let Some(lost) = &ready.lost {
1919            label = format!(
1920                "{label} ({})",
1921                strings::tr_args(&ctx, &txt::CLIPBOARD_LOSES, &[("what", lost)])
1922            );
1923        }
1924        let preview = preview(app, &ready, None, origin);
1925        out.push(Way {
1926            plan,
1927            label,
1928            preview,
1929            parts: None,
1930        });
1931    }
1932    let parts = clip_type(app, &first.item.kind)
1933        .and_then(|t| t.parts.clone())
1934        .map(|f| f(&first.item.payload))
1935        .unwrap_or_default();
1936    if let Some(best) = out.first().cloned() {
1937        for part in parts {
1938            let ids = vec![part.id.clone()];
1939            out.push(Way {
1940                plan: best.plan.clone(),
1941                label: strings::tr_args(&ctx, &txt::CLIPBOARD_ONLY_PART, &[("part", &part.title)]),
1942                preview: preview(app, &first, Some(&ids), origin),
1943                parts: Some(ids),
1944            });
1945        }
1946    }
1947    Ok(out)
1948}
1949
1950fn preview(
1951    app: &AppHandle,
1952    ready: &Ready,
1953    parts: Option<&[String]>,
1954    origin: &Origin,
1955) -> Option<String> {
1956    let _scope = ready
1957        .owner
1958        .as_ref()
1959        .map(egui_pop_model::values::enter_scope);
1960    let v = ready
1961        .target
1962        .paste(
1963            app,
1964            &Paste {
1965                repr: &ready.repr,
1966                plan: &ready.plan,
1967                item: &ready.item,
1968                parts,
1969                dry_run: true,
1970                origin,
1971                group: None,
1972                element: ready.element.as_deref(),
1973            },
1974        )
1975        .ok()?;
1976    match v {
1977        Json::Null => None,
1978        Json::String(s) => Some(s),
1979        other => Some(other.to_string()),
1980    }
1981}
1982
1983/// Opens paste special for a target: a choice of every way, each with
1984/// its preview; choosing pastes it.
1985pub fn paste_special(
1986    app: &AppHandle,
1987    target: &str,
1988    text: Option<&str>,
1989    origin: &Origin,
1990) -> Result<Json, String> {
1991    let mut req = PasteRequest::new(target);
1992    req.text = text.map(Into::into);
1993    paste_special_for(app, &req, origin)
1994}
1995
1996/// Opens paste special for a request (its `target`, `text` and
1997/// `element`).
1998pub fn paste_special_for(
1999    app: &AppHandle,
2000    request: &PasteRequest,
2001    origin: &Origin,
2002) -> Result<Json, String> {
2003    let target = request.target.as_str();
2004    let text = request.text.as_deref();
2005    let dialogs = app
2006        .service(&crate::dialogs::DIALOGS)
2007        .ok_or("paste special needs the dialogs plugin")?;
2008    let ways = ways_for(app, request, origin)?;
2009    if ways.is_empty() {
2010        return Err("nothing on the clipboard fits here".into());
2011    }
2012    let ctx = app.egui();
2013    let options = ways
2014        .iter()
2015        .map(|w| {
2016            let value = json!({
2017                "format": w.plan.to,
2018                "transform": w.plan.transform,
2019                "parts": w.parts,
2020            });
2021            let o = crate::dialogs::ChooseOption::new(&w.label, value);
2022            match &w.preview {
2023                Some(p) => o.hint(p),
2024                None => o,
2025            }
2026        })
2027        .collect();
2028    let choose = crate::dialogs::Choose::with_options(
2029        &strings::tr(&ctx, &txt::CLIPBOARD_PASTE_SPECIAL),
2030        options,
2031        CMD_CLIP_PASTE,
2032    )
2033    .args(json!({
2034        "target": target,
2035        "text": text,
2036        "element": request.element,
2037        "no_text": request.no_text,
2038    }))
2039    .value_key("special");
2040    let id = dialogs.open(choose);
2041    Ok(json!({ "dialog": id, "ways": ways.len() }))
2042}
2043
2044fn parse<T: serde::de::DeserializeOwned>(args: &Json, what: &str) -> Result<T, String> {
2045    serde_json::from_value(args.clone()).map_err(|e| format!("{what}: {e}"))
2046}
2047
2048fn outcome_json(o: Outcome) -> Result<Json, String> {
2049    match o {
2050        Outcome::Done(r) => r,
2051        Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
2052    }
2053}
2054
2055fn toast(app: &AppHandle, key: &strings::StrKey, name: &str, value: &str, warning: bool) {
2056    if let Some(t) = app.service(&crate::toasts::TOASTS) {
2057        let text = strings::tr_args(&app.egui(), key, &[(name, value)]);
2058        t.notify(if warning {
2059            crate::toasts::Toast::warning(&text)
2060        } else {
2061            crate::toasts::Toast::info(&text)
2062        });
2063    }
2064}
2065
2066/// The context keys `canCopy`, `canCut` and `canPaste` for the focused
2067/// endpoint (`None` without the plugin). A paste counts text as offered:
2068/// the system clipboard may hold some.
2069pub(crate) fn keys(app: &AppHandle) -> Option<[(&'static str, bool); 4]> {
2070    let st = state(app);
2071    if !st.connected.get() {
2072        return None;
2073    }
2074    let keymap = (CONTEXT_KEYMAP_SHORTCUTS, st.keymap_shortcuts.get());
2075    let ep = focused(app).and_then(|n| endpoint(app, &n).map(|e| (n, e)));
2076    let Some((name, ep)) = ep else {
2077        return Some([
2078            ("canCopy", false),
2079            ("canCut", false),
2080            ("canPaste", false),
2081            keymap,
2082        ]);
2083    };
2084    let (copy, cut) = match &ep.source {
2085        Some(s) => {
2086            let copy = s.can_copy(app);
2087            (copy, copy && s.can_cut(app))
2088        }
2089        None => (false, false),
2090    };
2091    let paste = ep.target.as_ref().is_some_and(|t| {
2092        let mut offers = with_owner(app, |c| c.offers(&Slot::User)).unwrap_or_default();
2093        for f in std::iter::once(TEXT).chain(with_backend(app, |b| b.readable())) {
2094            if !offers.contains(&f) {
2095                offers.push(f);
2096            }
2097        }
2098        let item = with_owner(app, |c| c.get(&Slot::User)).flatten();
2099        let specs: Vec<TransformSpec> = st
2100            .transforms
2101            .borrow()
2102            .iter()
2103            .filter(|(_, t)| {
2104                let r = item
2105                    .as_ref()
2106                    .and_then(|i| i.repr(&t.spec.from))
2107                    .unwrap_or_else(|| Repr::new(t.spec.from.clone(), Json::Null));
2108                t.applies.as_ref().is_none_or(|f| f(&r, &name))
2109            })
2110            .map(|(_, t)| t.spec.clone())
2111            .collect();
2112        model::negotiate(&offers, &t.accepts(app), &specs).is_ok()
2113    });
2114    Some([
2115        ("canCopy", copy),
2116        ("canCut", cut),
2117        ("canPaste", paste),
2118        keymap,
2119    ])
2120}
2121
2122/// Each pass: the copy, cut and paste events egui-winit made of the
2123/// platform's chords go to the commands while an endpoint has the focus
2124/// (and no text field does); Shift held on a paste is paste special.
2125fn pass(app: &AppHandle) {
2126    // upstream: egui-winit sends these chords as events and swallows
2127    // their keys (docs/upstream.md).
2128    settle(app);
2129    let ctx = app.egui();
2130    let silent = watch_paste_key(app, &ctx);
2131    if ctx.text_edit_focused() || focused(app).is_none() {
2132        return;
2133    }
2134    let mut runs = Vec::new();
2135    if let Some(shift) = silent {
2136        let cmd = if shift { CMD_PASTE_SPECIAL } else { CMD_PASTE };
2137        runs.push((cmd, json!({ "no_text": true })));
2138    }
2139    ctx.input_mut(|i| {
2140        let shift = i.modifiers.shift;
2141        i.events.retain(|e| match e {
2142            egui::Event::Copy => {
2143                runs.push((CMD_COPY, Json::Null));
2144                false
2145            }
2146            egui::Event::Cut => {
2147                runs.push((CMD_CUT, Json::Null));
2148                false
2149            }
2150            egui::Event::Paste(text) => {
2151                let cmd = if shift { CMD_PASTE_SPECIAL } else { CMD_PASTE };
2152                runs.push((cmd, json!({ "text": text })));
2153                false
2154            }
2155            _ => true,
2156        });
2157    });
2158    for (cmd, args) in runs {
2159        app.run_as(cmd, args, Origin::User);
2160    }
2161}
2162
2163/// What the paste key did, as far as egui's events tell.
2164#[derive(Debug, Default)]
2165struct PasteKey {
2166    /// Its press arrived as a key (not a paste chord).
2167    down: bool,
2168    /// egui-winit made a paste of it (the system clipboard held text).
2169    pasted: bool,
2170    /// The command modifier was held since its last release.
2171    command: bool,
2172}
2173
2174fn is_paste_key(key: egui::Key, modifiers: egui::Modifiers) -> bool {
2175    key == egui::Key::Paste
2176        || key == egui::Key::V
2177        || (cfg!(target_os = "windows") && modifiers.shift && key == egui::Key::Insert)
2178}
2179
2180/// The paste chord egui-winit swallowed without an event: it makes
2181/// `Event::Paste` only when the system clipboard holds text, and drops
2182/// the key's press either way, but lets its release through. A release
2183/// of the paste key whose press egui never saw, with no paste since and
2184/// the command modifier held meanwhile, is that chord: the paste key
2185/// with no text on the system clipboard (files, an image). Gives
2186/// whether Shift was held (paste special) when it is.
2187///
2188/// Reads the events only while a pass runs: between passes (eframe's
2189/// ticks of a hidden window) the input is still the last pass's, read
2190/// already, and a second read of a release would take it for one whose
2191/// press egui never saw.
2192fn watch_paste_key(app: &AppHandle, ctx: &egui::Context) -> Option<bool> {
2193    crate::app::pass_in_progress(ctx)?;
2194    let st = state(app);
2195    let mut k = st.paste_key.borrow_mut();
2196    ctx.input(|i| {
2197        if i.modifiers.command {
2198            k.command = true;
2199        }
2200        let mut silent = None;
2201        for e in &i.events {
2202            match e {
2203                egui::Event::Paste(_) => k.pasted = true,
2204                egui::Event::Key {
2205                    key,
2206                    pressed,
2207                    modifiers,
2208                    ..
2209                } if is_paste_key(*key, *modifiers) => {
2210                    if *pressed {
2211                        k.down = true;
2212                    } else {
2213                        let chord = *key != egui::Key::V || modifiers.command || k.command;
2214                        if !k.down && !k.pasted && chord {
2215                            silent = Some(modifiers.shift);
2216                        }
2217                        *k = PasteKey::default();
2218                    }
2219                }
2220                _ => {}
2221            }
2222        }
2223        silent
2224    })
2225}
2226
2227/// The endpoint a command acts on: `args[key]`, else the focused one.
2228fn endpoint_arg(app: &AppHandle, args: &Json, key: &str) -> Result<String, String> {
2229    match args.get(key).and_then(Json::as_str) {
2230        Some(n) => Ok(n.to_string()),
2231        None => focused(app).ok_or_else(|| "no endpoint has the focus".into()),
2232    }
2233}
2234
2235/// The element a command acts on: `args.element`, else the focused
2236/// element of the endpoint.
2237fn element_arg(app: &AppHandle, args: &Json, endpoint: &str) -> Option<String> {
2238    match args.get("element").and_then(Json::as_str) {
2239        Some(k) => Some(k.to_string()),
2240        None => element(app, endpoint),
2241    }
2242}
2243
2244fn slot_arg(args: &Json, origin: &Origin) -> Slot {
2245    args.get("slot")
2246        .and_then(Json::as_str)
2247        .map_or_else(|| Slot::of(origin), Slot::parse)
2248}
2249
2250/// A paste request from a command's arguments, with paste special's
2251/// choice (`special`) merged in.
2252fn paste_args(args: &Json, target: String) -> Result<PasteRequest, String> {
2253    let mut a = match args {
2254        Json::Object(m) => m.clone(),
2255        _ => serde_json::Map::new(),
2256    };
2257    if let Some(Json::Object(s)) = a.remove("special") {
2258        a.extend(s);
2259    }
2260    a.retain(|_, v| !v.is_null());
2261    a.insert("target".into(), json!(target));
2262    for k in ["choice", "label"] {
2263        a.remove(k);
2264    }
2265    parse(&Json::Object(a), "a paste")
2266}
2267
2268fn describe(app: &AppHandle) -> Json {
2269    let st = state(app);
2270    let slots: Vec<Json> = {
2271        let local = st.local.borrow();
2272        if st.custom.get() {
2273            Vec::new()
2274        } else {
2275            local
2276                .items
2277                .iter()
2278                .map(|(s, i)| {
2279                    json!({
2280                        "slot": s,
2281                        "kind": i.kind,
2282                        "title": i.title,
2283                        "version": i.version,
2284                        "offers": i.offers(),
2285                        "stripped": i.stripped,
2286                        "external": i.external,
2287                        "origin": i.origin,
2288                    })
2289                })
2290                .collect()
2291        }
2292    };
2293    let focused = focused(app);
2294    let endpoints: Vec<Json> = st
2295        .endpoints
2296        .borrow()
2297        .iter()
2298        .map(|(n, e)| {
2299            json!({
2300                "name": n,
2301                "owner": e.owner,
2302                "source": e.source.is_some(),
2303                "target": e.target.is_some(),
2304                "bound": e.widget.is_some(),
2305                "area": e.area.map(|(r, _)| [r.min.x, r.min.y, r.max.x, r.max.y]),
2306                "elements": e.elements.len(),
2307                "focused": focused.as_deref() == Some(n.as_str()),
2308            })
2309        })
2310        .collect();
2311    json!({
2312        "rev": with_owner(app, |c| c.rev()),
2313        "owner": if st.custom.get() { "host" } else { "local" },
2314        "pending_pastes": st.deferred.borrow().len(),
2315        "system": with_backend(app, |b| json!({ "backend": b.name(), "about": b.describe() })),
2316        "slots": slots,
2317        "endpoints": endpoints,
2318        "types": st.types.borrow().iter().map(|(o, t)| json!({
2319            "format": t.format, "version": t.version, "title": t.title,
2320            "internal": t.internal, "owner": o,
2321        })).collect::<Vec<_>>(),
2322        "transforms": st.transforms.borrow().iter().map(|(o, t)| json!({
2323            "spec": t.spec, "owner": o,
2324        })).collect::<Vec<_>>(),
2325        "sanitisers": st.sanitisers.borrow().iter().map(|(o, s)| json!({
2326            "id": s.id, "boundary": s.boundary, "format": s.format, "owner": o,
2327        })).collect::<Vec<_>>(),
2328    })
2329}
2330
2331/// The clipboard as a plugin: the default owner (a [`LocalClipboard`],
2332/// unless the host owns the clipboard), the steps, the Edit commands and
2333/// keys, the agent commands, the `clipboard` collector, egui-pop's own
2334/// sanitiser of external text and its HTML to text transform.
2335#[derive(Debug, Default)]
2336pub struct ClipboardPlugin;
2337
2338impl Plugin for ClipboardPlugin {
2339    fn id(&self) -> PluginId {
2340        PLUGIN
2341    }
2342
2343    fn title(&self) -> String {
2344        "Clipboard".into()
2345    }
2346
2347    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
2348        state(&ctx.app()).connected.set(true);
2349        ctx.step(
2350            StepSpec::new(
2351                STEP_COPY,
2352                "A copy from an endpoint; a veto keeps it from being made, a redirect copies another source or into another slot.",
2353            )
2354            .args(json!({ "source": "demo.swatches", "slot": "user", "cut": false, "dry_run": false, "origin": "user" })),
2355        )?
2356        .step(
2357            StepSpec::new(
2358                STEP_PASTE,
2359                "A paste into an endpoint; a veto keeps it from being made, a redirect pastes into another target or in another format.",
2360            )
2361            .args(json!({ "target": "demo.swatches", "format": null, "transform": null, "dry_run": false, "origin": "user" })),
2362        )?;
2363        let category = "Edit";
2364        ctx.command(
2365            CommandSpec::new(CMD_CUT, "Cut", category)
2366                .icon("cut")
2367                .description("Cut the selection: copied once its delete is accepted.")
2368                .key("Ctrl+X")
2369                .key("Shift+Delete")
2370                .when("!textInputFocus && canCut || textInputFocus && clipboardKeymap")
2371                .menu(MENU_EDIT, MENU_GROUP, 0),
2372            |call| {
2373                if let Some(r) = to_text_field(call.app, call.args, egui::Event::Cut) {
2374                    return r;
2375                }
2376                let source = endpoint_arg(call.app, call.args, "source")?;
2377                let mut req = CopyRequest::new(&source).cut();
2378                req.element = element_arg(call.app, call.args, &source);
2379                outcome_json(copy(call.app, req, call.origin))
2380            },
2381        )?
2382        .command(
2383            CommandSpec::new(CMD_COPY, "Copy", category)
2384                .icon("copy")
2385                .description("Copy the selection.")
2386                .key("Ctrl+C")
2387                .key("Ctrl+Insert")
2388                .when("!textInputFocus && canCopy || textInputFocus && clipboardKeymap")
2389                .menu(MENU_EDIT, MENU_GROUP, 1),
2390            |call| {
2391                if let Some(r) = to_text_field(call.app, call.args, egui::Event::Copy) {
2392                    return r;
2393                }
2394                let source = endpoint_arg(call.app, call.args, "source")?;
2395                let mut req = CopyRequest::new(&source);
2396                req.element = element_arg(call.app, call.args, &source);
2397                outcome_json(copy(call.app, req, call.origin))
2398            },
2399        )?
2400        .command(
2401            CommandSpec::new(CMD_PASTE, "Paste", category)
2402                .icon("paste")
2403                .description("Paste in the richest format the focused element accepts.")
2404                .key("Ctrl+V")
2405                .key("Shift+Insert")
2406                .when("!textInputFocus && canPaste || textInputFocus && clipboardKeymap")
2407                .menu(MENU_EDIT, MENU_GROUP, 2),
2408            |call| {
2409                let event = egui::Event::Paste(String::new());
2410                if let Some(r) = to_text_field(call.app, call.args, event) {
2411                    return r;
2412                }
2413                let target = endpoint_arg(call.app, call.args, "target")?;
2414                let mut req = paste_args(call.args, target)?;
2415                if req.element.is_none() {
2416                    req.element = element(call.app, &req.target);
2417                }
2418                outcome_json(paste(call.app, req, call.origin))
2419            },
2420        )?
2421        .command(
2422            CommandSpec::new(CMD_PASTE_SPECIAL, "Paste special", category)
2423                .icon("paste-special")
2424                .description("Choose the format, the transform or the parts to paste, each with its preview.")
2425                .key("Ctrl+Shift+V")
2426                .when("!textInputFocus && canPaste")
2427                .menu(MENU_EDIT, MENU_GROUP, 3),
2428            |call| {
2429                let target = endpoint_arg(call.app, call.args, "target")?;
2430                let mut req = paste_args(call.args, target)?;
2431                if req.element.is_none() {
2432                    req.element = element(call.app, &req.target);
2433                }
2434                if req.format.is_some() || req.transform.is_some() || req.parts.is_some() {
2435                    return outcome_json(paste(call.app, req, call.origin));
2436                }
2437                paste_special_for(call.app, &req, call.origin)
2438            },
2439        )?;
2440        let category = "Clipboard";
2441        ctx.command(
2442            CommandSpec::new(CMD_CLIP_COPY, "Copy from an endpoint", category)
2443                .description("Copies from an endpoint (`source`), one of its elements (`element`), into the session's slot (`slot`); `cut` deletes what was copied; `dry_run` says what would be copied and left out.")
2444                .args(json!({ "source": "demo.swatches", "cut": false, "dry_run": true })),
2445            |call| {
2446                let mut req: CopyRequest = parse(call.args, "a copy")?;
2447                req.slot = Some(slot_arg(call.args, call.origin));
2448                outcome_json(copy(call.app, req, call.origin))
2449            },
2450        )?
2451        .command(
2452            CommandSpec::new(CMD_CLIP_PASTE, "Paste into an endpoint", category)
2453                .description("Pastes the session's slot (`slot`) into an endpoint (`target`), one of its elements (`element`), in a `format`, through a `transform`, only some `parts`, checked against `if_rev`; `dry_run` says the plan and the changes without making them.")
2454                .args(json!({ "target": "demo.swatches", "format": null, "transform": null, "if_rev": null, "dry_run": true })),
2455            |call| {
2456                let target = call.args["target"]
2457                    .as_str()
2458                    .ok_or("`target` is missing")?
2459                    .to_string();
2460                let mut req = paste_args(call.args, target)?;
2461                req.slot = Some(slot_arg(call.args, call.origin));
2462                outcome_json(paste(call.app, req, call.origin))
2463            },
2464        )?
2465        .command(
2466            CommandSpec::new(CMD_OFFERS, "What the clipboard offers", category)
2467                .description("What a slot holds (`slot`): its type, title, formats and revision; with `target`, every way it fits there, each with its preview.")
2468                .args(json!({ "target": "demo.swatches" }))
2469                .read_only(),
2470            |call| {
2471                let slot = slot_arg(call.args, call.origin);
2472                with_owner(call.app, |c| c.may_use(call.origin, &slot)).ok_or(NO_PLUGIN)??;
2473                let item = with_owner(call.app, |c| c.get(&slot)).flatten();
2474                let rev = with_owner(call.app, |c| c.rev());
2475                let ways = match call.args.get("target").and_then(Json::as_str) {
2476                    Some(t) => {
2477                        let text = call.args.get("text").and_then(Json::as_str);
2478                        match ways(call.app, t, Some(slot.clone()), text, call.origin) {
2479                            Ok(w) => json!(w),
2480                            Err(e) => json!({ "refused": e }),
2481                        }
2482                    }
2483                    None => Json::Null,
2484                };
2485                Ok(json!({
2486                    "slot": slot,
2487                    "rev": rev,
2488                    "item": item.map(|i| json!({
2489                        "kind": i.kind,
2490                        "title": i.title,
2491                        "version": i.version,
2492                        "offers": i.offers(),
2493                        "stripped": i.stripped,
2494                    })),
2495                    "ways": ways,
2496                }))
2497            },
2498        )?
2499        .command(
2500            CommandSpec::new(CMD_READ, "Read the clipboard", category)
2501                .description("A slot's item (`slot`, the session's own by default), payload included; the user's is refused to an agent unless the host allows it.")
2502                .args(json!({ "slot": null }))
2503                .read_only(),
2504            |call| {
2505                let slot = slot_arg(call.args, call.origin);
2506                with_owner(call.app, |c| c.may_use(call.origin, &slot)).ok_or(NO_PLUGIN)??;
2507                let item = with_owner(call.app, |c| c.get(&slot)).flatten();
2508                Ok(json!({ "slot": slot, "item": item }))
2509            },
2510        )?
2511        .command(
2512            CommandSpec::new(CMD_WRITE, "Write the clipboard", category)
2513                .description("Puts an item in a slot (`slot`, the session's own by default): its `format`, its `data`, a `title`.")
2514                .args(json!({ "format": "text/plain", "data": "hello", "title": null })),
2515            |call| {
2516                let slot = slot_arg(call.args, call.origin);
2517                with_owner(call.app, |c| c.may_use(call.origin, &slot)).ok_or(NO_PLUGIN)??;
2518                let format: FormatId = parse(&call.args["format"], "`format`")?;
2519                let ty = clip_type(call.app, &format);
2520                let title = call.args["title"]
2521                    .as_str()
2522                    .map(str::to_string)
2523                    .or_else(|| ty.as_ref().map(|t| t.title.clone()))
2524                    .unwrap_or_else(|| format.to_string());
2525                let mut item = ClipItem::new(
2526                    format,
2527                    ty.as_ref().map_or(0, |t| t.version),
2528                    call.args["data"].clone(),
2529                    &title,
2530                );
2531                if let Some(render) = ty.as_ref().and_then(|t| t.render.clone()) {
2532                    item.fallbacks = render(&item.payload);
2533                }
2534                item.origin.by = source_of(call.origin);
2535                let (answer, events) = with_owner(call.app, |c| {
2536                    let a = c.put(&slot, item, call.origin);
2537                    (a, c.take_events())
2538                })
2539                .ok_or(NO_PLUGIN)?;
2540                publish_events(call.app, &source_of(call.origin), events);
2541                match answer {
2542                    Answer::Done(Ok(rev)) => Ok(json!({ "slot": slot, "rev": rev })),
2543                    Answer::Done(Err(e)) => Err(e),
2544                    Answer::Later(_) => Ok(json!({ "slot": slot, "pending": true })),
2545                }
2546            },
2547        )?;
2548        // egui-pop's own: external text loses its control characters, and
2549        // HTML becomes text for a target that does not take HTML.
2550        ctx.clip_sanitiser(
2551            Sanitiser::new(SANITISE_CONTROLS, Boundary::External, |data| {
2552                let Some(text) = data.as_str() else {
2553                    return Vec::new();
2554                };
2555                let (clean, n) = model::strip_controls(text);
2556                if n == 0 {
2557                    return Vec::new();
2558                }
2559                *data = Json::String(clean);
2560                vec![format!("{n} control characters")]
2561            })
2562            .format(TEXT),
2563        )?
2564        .clip_transform(Transform::new(
2565            TransformSpec::new(HTML_TO_TEXT, HTML, TEXT).lossy(),
2566            |r| {
2567                let html = r.text().ok_or("HTML that is not text")?;
2568                Ok(Transformed::lossy(
2569                    Json::String(model::html_to_text(html)),
2570                    "formatting",
2571                ))
2572            },
2573        ))?;
2574        let w1 = ctx.app().downgrade();
2575        ctx.collector(
2576            FnCollector::new(
2577                "clipboard",
2578                "The clipboard: the owner (local or the host's), its revision, each slot's item (type, title, formats, what was left out; never the payload), the endpoints (source, target, bound, focused), the types, transforms and sanitisers declared.",
2579            )
2580            .snapshot(move |_| match w1.get() {
2581                Ok(app) => describe(&app),
2582                Err(_) => Json::Null,
2583            })
2584        )?;
2585        ctx.on(On::Pass, |app, _| pass(app))
2586            .on(On::Disconnected, |app, ev| {
2587                if let Lifecycle::Disconnected(p) = ev {
2588                    remove_owner(app, &OwnerId::from(p));
2589                }
2590            });
2591        Ok(())
2592    }
2593
2594    fn disconnect(&mut self, ctx: &mut Ctx<'_>) {
2595        state(&ctx.app()).connected.set(false);
2596    }
2597}
2598
2599fn remove_owner(app: &AppHandle, owner: &OwnerId) {
2600    let st = state(app);
2601    st.types.borrow_mut().retain(|(o, _)| o != owner);
2602    st.transforms.borrow_mut().retain(|(o, _)| o != owner);
2603    st.sanitisers.borrow_mut().retain(|(o, _)| o != owner);
2604    st.endpoints
2605        .borrow_mut()
2606        .retain(|_, e| e.owner.as_ref() != Some(owner));
2607}
2608
2609impl Ctx<'_> {
2610    /// Declares a type of clipboard item, owned by this plugin (gone with
2611    /// it). Its format must not be declared already.
2612    pub fn clip_type(&mut self, t: ClipType) -> Result<&mut Self, CtxError> {
2613        let st = state(self.app);
2614        let mut types = st.types.borrow_mut();
2615        if let Some((by, _)) = types.iter().find(|(_, x)| x.format == t.format) {
2616            return Err(CtxError::Clipboard(format!(
2617                "clipboard type `{}` is already declared by `{by}`",
2618                t.format
2619            )));
2620        }
2621        types.push((self.owner.clone(), t));
2622        Ok(self)
2623    }
2624
2625    /// Declares a clipboard transform, owned by this plugin.
2626    pub fn clip_transform(&mut self, t: Transform) -> Result<&mut Self, CtxError> {
2627        let st = state(self.app);
2628        let mut list = st.transforms.borrow_mut();
2629        if let Some((by, _)) = list.iter().find(|(_, x)| x.spec.id == t.spec.id) {
2630            return Err(CtxError::Clipboard(format!(
2631                "clipboard transform `{}` is already declared by `{by}`",
2632                t.spec.id
2633            )));
2634        }
2635        list.push((self.owner.clone(), t));
2636        Ok(self)
2637    }
2638
2639    /// Declares a clipboard sanitiser, owned by this plugin.
2640    pub fn clip_sanitiser(&mut self, s: Sanitiser) -> Result<&mut Self, CtxError> {
2641        let st = state(self.app);
2642        let mut list = st.sanitisers.borrow_mut();
2643        if let Some((by, _)) = list.iter().find(|(_, x)| x.id == s.id) {
2644            return Err(CtxError::Clipboard(format!(
2645                "clipboard sanitiser `{}` is already declared by `{by}`",
2646                s.id
2647            )));
2648        }
2649        list.push((self.owner.clone(), s));
2650        Ok(self)
2651    }
2652
2653    /// Registers a component's endpoint, owned by this plugin (gone with
2654    /// it); see [`register`].
2655    pub fn clip_endpoint(
2656        &mut self,
2657        name: &str,
2658        source: Option<Rc<dyn ClipSource>>,
2659        target: Option<Rc<dyn ClipTarget>>,
2660    ) -> &mut Self {
2661        add_endpoint(self.app, Some(self.owner.clone()), name, source, target);
2662        self
2663    }
2664}