1use 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
135pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.clipboard");
137
138pub const SYSTEM_PLUGIN: PluginId = PluginId::from_static("egui_pop.system_clipboard");
143
144pub const CONTEXT_KEYMAP_SHORTCUTS: &str = "clipboardKeymap";
147
148pub const MENU_GROUP: &str = "1_clipboard";
150
151pub const CMD_CUT: CommandId = CommandId::from_static("edit.cut");
154pub const CMD_COPY: CommandId = CommandId::from_static("edit.copy");
156pub const CMD_PASTE: CommandId = CommandId::from_static("edit.paste");
158pub const CMD_PASTE_SPECIAL: CommandId = CommandId::from_static("edit.pasteSpecial");
161pub const CMD_CLIP_COPY: CommandId = CommandId::from_static("clipboard.copy");
164pub const CMD_CLIP_PASTE: CommandId = CommandId::from_static("clipboard.paste");
167pub const CMD_OFFERS: CommandId = CommandId::from_static("clipboard.offers");
169pub const CMD_READ: CommandId = CommandId::from_static("clipboard.read");
171pub const CMD_WRITE: CommandId = CommandId::from_static("clipboard.write");
173
174pub const STEP_COPY: StepId = StepId::from_static("clipboard.copy");
180pub const STEP_PASTE: StepId = StepId::from_static("clipboard.paste");
187
188pub const SANITISE_CONTROLS: &str = "egui_pop.controls";
191pub const HTML_TO_TEXT: &str = "egui_pop.html-to-text";
193
194const NO_PLUGIN: &str = "no clipboard: the ClipboardPlugin is not connected";
195
196#[derive(Debug)]
198pub enum Answer {
199 Done(Result<u64, String>),
201 Later(Pending),
203}
204
205pub trait Clipboard {
207 fn put(&mut self, slot: &Slot, item: ClipItem, origin: &Origin) -> Answer;
209
210 fn get(&self, slot: &Slot) -> Option<ClipItem>;
212
213 fn offers(&self, slot: &Slot) -> Vec<FormatId> {
215 self.get(slot).map(|i| i.offers()).unwrap_or_default()
216 }
217
218 fn rev(&self) -> u64;
220
221 fn may_use(&self, origin: &Origin, slot: &Slot) -> Result<(), String> {
224 default_access(origin, slot)
225 }
226
227 fn take_events(&mut self) -> Vec<(String, Json)> {
229 Vec::new()
230 }
231
232 fn system(&mut self) -> Option<&mut dyn SystemBackend> {
236 None
237 }
238}
239
240pub trait SystemBackend {
255 fn name(&self) -> String;
257
258 fn writes(&self, format: &FormatId) -> bool {
261 *format == TEXT
262 }
263
264 fn write(&mut self, ctx: &egui::Context, reprs: &[Repr]) -> Result<(), String>;
268
269 fn read(&mut self, ctx: &egui::Context) -> Option<Vec<Repr>> {
273 let _ = ctx;
274 None
275 }
276
277 fn readable(&self) -> Vec<FormatId> {
280 Vec::new()
281 }
282
283 fn read_primary(&mut self) -> Option<String> {
286 None
287 }
288
289 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 fn describe(&self) -> Json {
299 Json::Null
300 }
301}
302
303#[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
326pub 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
334pub 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
354fn 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
370pub fn set_keymap_shortcuts(app: &AppHandle, on: bool) {
385 state(app).keymap_shortcuts.set(on);
386}
387
388pub fn keymap_shortcuts(app: &AppHandle) -> bool {
391 state(app).keymap_shortcuts.get()
392}
393
394fn 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
435pub fn primary_text(app: &AppHandle) -> Option<String> {
438 with_backend(app, |b| b.read_primary())
439}
440
441pub fn set_primary_text(app: &AppHandle, text: &str) -> Result<(), String> {
443 with_backend(app, |b| b.write_primary(text))
444}
445
446pub 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#[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 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#[derive(Debug)]
514pub struct Cut<'a> {
515 pub item: &'a ClipItem,
516 pub origin: &'a Origin,
517 pub group: Option<GestureId>,
518 pub element: Option<&'a str>,
521}
522
523pub trait ClipSource {
525 fn copy(&self, app: &AppHandle) -> Option<ClipItem>;
527
528 fn copy_element(&self, app: &AppHandle, element: Option<&str>) -> Option<ClipItem> {
533 let _ = element;
534 self.copy(app)
535 }
536
537 fn can_copy(&self, _app: &AppHandle) -> bool {
539 true
540 }
541
542 fn can_cut(&self, _app: &AppHandle) -> bool {
545 false
546 }
547
548 fn delete(&self, _app: &AppHandle, _cut: &Cut<'_>) -> Result<(), String> {
551 Err("this cannot be cut".into())
552 }
553}
554
555#[derive(Debug)]
557pub struct Paste<'a> {
558 pub repr: &'a Repr,
560 pub plan: &'a Plan,
561 pub item: &'a ClipItem,
563 pub parts: Option<&'a [String]>,
565 pub dry_run: bool,
567 pub origin: &'a Origin,
568 pub group: Option<GestureId>,
571 pub element: Option<&'a str>,
574}
575
576impl Paste<'_> {
577 pub fn wants(&self, part: &str) -> bool {
579 self.parts.is_none_or(|p| p.iter().any(|x| x == part))
580 }
581}
582
583pub trait ClipTarget {
585 fn accepts(&self, app: &AppHandle) -> Vec<FormatId>;
587
588 fn paste(&self, app: &AppHandle, paste: &Paste<'_>) -> Result<Json, String>;
592
593 fn apply(&self, app: &AppHandle, paste: &Paste<'_>) -> Pasted {
603 Pasted::Done(self.paste(app, paste))
604 }
605
606 fn context(&self, app: &AppHandle, element: Option<&str>) -> Json {
612 let _ = (app, element);
613 Json::Null
614 }
615}
616
617#[derive(Debug)]
619pub enum Pasted {
620 Done(Result<Json, String>),
622 Later(Pending),
624}
625
626struct Deferred {
628 pending: Pending,
629 group: Option<GestureId>,
630 origin: Origin,
631 summary: Json,
632}
633
634#[derive(Clone, Copy, Debug)]
636pub struct Destination<'a> {
637 pub target: &'a str,
639 pub element: Option<&'a str>,
641 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#[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#[derive(Clone)]
671pub struct ClipType {
672 pub format: FormatId,
673 pub version: u32,
675 pub title: String,
677 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 pub fn internal(mut self) -> Self {
710 self.internal = true;
711 self
712 }
713
714 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 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 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#[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#[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 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 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#[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 pub fn format(mut self, format: FormatId) -> Self {
843 self.format = Some(format);
844 self
845 }
846}
847
848#[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 area: Option<(egui::Rect, u64)>,
858 elements: HashMap<egui::Id, (String, u64)>,
860}
861
862fn current(at: u64, now: u64) -> bool {
865 now.saturating_sub(at) <= 1
866}
867
868#[derive(Debug, Default)]
870struct System {
871 written: Option<(FormatId, u64)>,
874 internal_only: bool,
876 seen: Option<u64>,
878}
879
880fn 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
888fn 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 read_cache: RefCell<Option<(u64, Option<Vec<Repr>>)>>,
909 keymap_shortcuts: Cell<bool>,
912}
913
914fn state(app: &AppHandle) -> Rc<State> {
915 app.local::<State>()
916}
917
918pub 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
941pub fn allow_session(app: &AppHandle, session: &str) {
944 state(app).local.borrow_mut().allow(session);
945}
946
947pub 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
984pub fn unregister(app: &AppHandle, name: &str) {
986 state(app).endpoints.borrow_mut().remove(name);
987}
988
989pub 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
997pub fn endpoints(app: &AppHandle) -> Vec<String> {
999 state(app).endpoints.borrow().keys().cloned().collect()
1000}
1001
1002pub 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
1018pub 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
1031pub 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
1047fn 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
1059pub 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 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
1096pub 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
1106pub 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
1125fn 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
1153pub fn type_title_key(format: &FormatId) -> String {
1155 strings::declared_key(strings::kind::CLIP, format.as_str(), Some("title"))
1156}
1157
1158pub 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
1184pub 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
1197pub 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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1230pub struct CopyRequest {
1231 pub source: String,
1233 #[serde(default, skip_serializing_if = "Option::is_none")]
1235 pub slot: Option<Slot>,
1236 #[serde(default)]
1238 pub cut: bool,
1239 #[serde(default)]
1241 pub dry_run: bool,
1242 #[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 pub fn element(mut self, key: &str) -> Self {
1273 self.element = Some(key.into());
1274 self
1275 }
1276}
1277
1278#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1280pub struct PasteRequest {
1281 pub target: String,
1283 #[serde(default, skip_serializing_if = "Option::is_none")]
1285 pub slot: Option<Slot>,
1286 #[serde(default, skip_serializing_if = "Option::is_none")]
1288 pub format: Option<FormatId>,
1289 #[serde(default, skip_serializing_if = "Option::is_none")]
1291 pub transform: Option<String>,
1292 #[serde(default, skip_serializing_if = "Option::is_none")]
1294 pub parts: Option<Vec<String>>,
1295 #[serde(default, skip_serializing_if = "Option::is_none")]
1297 pub if_rev: Option<u64>,
1298 #[serde(default)]
1300 pub dry_run: bool,
1301 #[serde(default, skip_serializing_if = "Option::is_none")]
1303 pub text: Option<String>,
1304 #[serde(default, skip_serializing_if = "Option::is_none")]
1307 pub element: Option<String>,
1308 #[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 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 pub fn element(mut self, key: &str) -> Self {
1363 self.element = Some(key.into());
1364 self
1365 }
1366}
1367
1368pub 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 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 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 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 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 _ => 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
1536struct Ready {
1538 target: Rc<dyn ClipTarget>,
1539 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
1550fn 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 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 (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 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 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
1705pub 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 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 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
1801pub fn pending_pastes(app: &AppHandle) -> usize {
1803 state(app).deferred.borrow().len()
1804}
1805
1806fn 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#[derive(Clone, Debug, PartialEq, Serialize)]
1854pub struct Way {
1855 pub plan: Plan,
1856 pub label: String,
1857 pub preview: Option<String>,
1858 pub parts: Option<Vec<String>>,
1860}
1861
1862pub 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
1880pub 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
1983pub 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
1996pub 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
2066pub(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
2122fn pass(app: &AppHandle) {
2126 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#[derive(Debug, Default)]
2165struct PasteKey {
2166 down: bool,
2168 pasted: bool,
2170 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
2180fn 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
2227fn 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
2235fn 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
2250fn 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#[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 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 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 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 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 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}