1use crate::abi::{
84 self, FfiError, FfiErrorKind, FfiResult, FilterFrame, FilterView, HostBox, Pixels, PluginBox,
85 PluginFfi, PluginFfi_TO, PluginModule, PluginModuleRef, RasterUpload, RegionRequest, SlideBox,
86 SlideFfi, SlideFfi_TO, SlideRegion, SlideSourceBox, SlideSourceFfi, SlideSourceFfi_TO,
87};
88use crate::i18n::Catalog;
89use crate::protocol::{methods, *};
90use abi_stable::{
91 prefix_type::PrefixTypeTrait,
92 sabi_trait::{TD_CanDowncast, TD_Opaque},
93 std_types::{RErr, ROk, RSliceMut, RStr, RString},
94};
95use serde::{Serialize, de::DeserializeOwned};
96use serde_json::{Map, Value};
97use std::any::Any;
98use std::panic::{AssertUnwindSafe, catch_unwind};
99use std::sync::Arc;
100
101pub const ROOT_MODULE_LOADER_SYMBOL: &str = "_1as_0lib_1header_0root_bmodule_bloader";
105
106pub trait Plugin: Send + Sync + Sized + 'static {
119 fn create(host: Host, init: PluginInit) -> Result<Self, String>;
121
122 fn on_event(&self, event: HostEvent) -> Result<(), String> {
125 let _ = event;
126 Ok(())
127 }
128
129 fn context_menu(&self, context: &MenuContext) -> Vec<MenuItem> {
131 let _ = context;
132 Vec::new()
133 }
134
135 fn ui_callback(&self, surface_id: &str, name: &str, args: &[Value]) -> Result<Value, String> {
139 let _ = (surface_id, name, args);
140 Ok(Value::Null)
141 }
142
143 fn apply_filter(&self, filter_id: &str, frame: &mut Frame<'_>) -> Result<(), String> {
146 let _ = (filter_id, frame);
147 Ok(())
148 }
149
150 fn open_slide(&self, request: &SlideOpenRequest) -> Result<Box<dyn SlideReader>, String> {
162 Err(format!(
163 "this plugin reads no slide formats (asked for '{}')",
164 request.format_id
165 ))
166 }
167
168 fn shutdown(&self) {}
172}
173
174pub trait SlideReader: Send + Sync + 'static {
182 fn info(&self) -> SlideInfo;
185
186 fn read_region(&self, region: &SlideRegion, out: &mut [u8]) -> Result<(), String>;
191
192 fn read_associated_image(&self, name: &str) -> Result<Image, String> {
195 Err(format!("no associated image '{name}'"))
196 }
197}
198
199#[derive(Debug, Clone, PartialEq, Eq)]
205pub struct HostError {
206 pub kind: FfiErrorKind,
207 pub message: String,
208}
209
210impl HostError {
211 fn new(kind: FfiErrorKind, message: impl Into<String>) -> Self {
212 Self {
213 kind,
214 message: message.into(),
215 }
216 }
217
218 pub fn is_unsupported(&self) -> bool {
220 self.kind == FfiErrorKind::Unsupported
221 }
222}
223
224impl std::fmt::Display for HostError {
225 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226 f.write_str(&self.message)
227 }
228}
229
230impl std::error::Error for HostError {}
231
232impl From<FfiError> for HostError {
233 fn from(error: FfiError) -> Self {
234 Self::new(error.kind(), error.message.into_string())
235 }
236}
237
238impl From<HostError> for String {
239 fn from(error: HostError) -> Self {
240 error.message
241 }
242}
243
244pub type HostResult<T> = Result<T, HostError>;
245
246fn from_ffi<T>(result: FfiResult<T>) -> HostResult<T> {
247 result.into_result().map_err(HostError::from)
248}
249
250#[derive(Debug, Clone, PartialEq, Eq, Default)]
256pub struct Image {
257 pub width: u32,
258 pub height: u32,
259 pub data: Vec<u8>,
260}
261
262impl Image {
263 pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
265 if x >= self.width || y >= self.height {
266 return None;
267 }
268 let i = (y as usize * self.width as usize + x as usize) * 4;
269 self.data.get(i..i + 4).map(|p| [p[0], p[1], p[2], p[3]])
270 }
271
272 fn into_pixels(self) -> abi::Pixels {
273 abi::Pixels {
274 width: self.width,
275 height: self.height,
276 data: self.data.into(),
277 }
278 }
279}
280
281impl From<abi::Pixels> for Image {
282 fn from(pixels: abi::Pixels) -> Self {
283 Self {
284 width: pixels.width,
285 height: pixels.height,
286 data: pixels.data.into_vec(),
287 }
288 }
289}
290
291pub struct Frame<'a> {
293 pixels: &'a mut [u8],
294 width: u32,
295 height: u32,
296 stride: usize,
297 view: FilterView,
298}
299
300impl<'a> Frame<'a> {
301 pub fn new(
304 pixels: &'a mut [u8],
305 width: u32,
306 height: u32,
307 stride: usize,
308 view: FilterView,
309 ) -> Option<Self> {
310 let row = (width as usize).checked_mul(4)?;
311 if stride < row {
312 return None;
313 }
314 let needed = if height == 0 {
315 0
316 } else {
317 stride.checked_mul(height as usize - 1)?.checked_add(row)?
318 };
319 (pixels.len() >= needed).then_some(Self {
320 pixels,
321 width,
322 height,
323 stride,
324 view,
325 })
326 }
327
328 pub fn width(&self) -> u32 {
329 self.width
330 }
331
332 pub fn height(&self) -> u32 {
333 self.height
334 }
335
336 pub fn stride(&self) -> usize {
338 self.stride
339 }
340
341 pub fn view(&self) -> &FilterView {
343 &self.view
344 }
345
346 pub fn row_mut(&mut self, y: u32) -> &mut [u8] {
348 assert!(y < self.height, "row {y} out of range");
349 let start = y as usize * self.stride;
350 &mut self.pixels[start..start + self.width as usize * 4]
351 }
352
353 pub fn rows_mut(&mut self) -> impl Iterator<Item = &mut [u8]> + '_ {
355 let row = self.width as usize * 4;
356 let height = self.height as usize;
357 self.pixels
358 .chunks_mut(self.stride.max(1))
359 .take(height)
360 .map(move |chunk| &mut chunk[..row])
361 }
362
363 pub fn for_each_pixel(&mut self, mut f: impl FnMut(u32, u32, &mut [u8])) {
365 let width = self.width;
366 for (y, row) in self.rows_mut().enumerate() {
367 let (pixels, _) = row.as_chunks_mut::<4>();
368 for (x, px) in pixels.iter_mut().enumerate().take(width as usize) {
369 f(x as u32, y as u32, px);
370 }
371 }
372 }
373}
374
375#[derive(Clone)]
381pub struct Host {
382 ffi: Arc<HostBox>,
383}
384
385impl Host {
386 pub fn from_ffi(ffi: HostBox) -> Self {
389 Self { ffi: Arc::new(ffi) }
390 }
391
392 pub fn call_raw(&self, method: &str, args_json: &str) -> HostResult<String> {
394 from_ffi(
395 self.ffi
396 .call(RStr::from_str(method), RStr::from_str(args_json)),
397 )
398 .map(RString::into_string)
399 }
400
401 pub fn call<A, R>(&self, method: &str, args: &A) -> HostResult<R>
403 where
404 A: Serialize + ?Sized,
405 R: DeserializeOwned,
406 {
407 let args = serde_json::to_string(args)
408 .map_err(|e| HostError::new(FfiErrorKind::InvalidArguments, e.to_string()))?;
409 let reply = self.call_raw(method, &args)?;
410 serde_json::from_str(&reply).map_err(|e| {
411 HostError::new(
412 FfiErrorKind::Failed,
413 format!("unexpected reply to '{method}': {e}"),
414 )
415 })
416 }
417
418 fn command<A: Serialize + ?Sized>(&self, method: &str, args: &A) -> HostResult<()> {
419 self.call::<A, Value>(method, args).map(|_| ())
420 }
421
422 pub fn log(&self, level: LogLevel, message: impl Into<String>) {
442 let _ = self.command(
443 methods::LOG,
444 &LogArgs {
445 level,
446 message: message.into(),
447 },
448 );
449 }
450
451 pub fn debug(&self, message: impl Into<String>) {
452 self.log(LogLevel::Debug, message);
453 }
454
455 pub fn info(&self, message: impl Into<String>) {
456 self.log(LogLevel::Info, message);
457 }
458
459 pub fn warn(&self, message: impl Into<String>) {
463 self.log(LogLevel::Warn, message);
464 }
465
466 pub fn error(&self, message: impl Into<String>) {
470 self.log(LogLevel::Error, message);
471 }
472
473 pub fn notify(&self, level: NotifyLevel, message: impl Into<String>) {
475 let _ = self.command(
476 methods::NOTIFY,
477 &NotifyArgs {
478 level,
479 message: message.into(),
480 detail: None,
481 },
482 );
483 }
484
485 pub fn notify_error(&self, message: impl Into<String>, detail: impl Into<String>) {
487 let _ = self.command(
488 methods::NOTIFY,
489 &NotifyArgs {
490 level: NotifyLevel::Error,
491 message: message.into(),
492 detail: Some(detail.into()),
493 },
494 );
495 }
496
497 pub fn set_status(&self, text: Option<&str>) {
499 let _ = self.command(
500 methods::STATUS,
501 &StatusArgs {
502 text: text.map(str::to_string),
503 },
504 );
505 }
506
507 pub fn snapshot(&self) -> HostResult<HostSnapshot> {
511 self.call(methods::SNAPSHOT, &Map::new())
512 }
513
514 pub fn file_info(&self, file_id: FileId) -> HostResult<FileInfo> {
515 self.call(methods::FILE_INFO, &FileArgs { file_id })
516 }
517
518 pub fn file_properties(&self, file_id: FileId) -> HostResult<PropertyMap> {
520 self.call(methods::FILE_PROPERTIES, &FileArgs { file_id })
521 }
522
523 pub fn open_file(&self, path: impl Into<String>) -> HostResult<()> {
525 self.command(methods::FILE_OPEN, &OpenFileArgs { path: path.into() })
526 }
527
528 pub fn read_region(&self, request: RegionRequest) -> HostResult<Image> {
537 from_ffi(self.ffi.read_region(request)).map(Image::from)
538 }
539
540 pub fn read_associated_image(&self, file_id: FileId, name: &str) -> HostResult<Image> {
542 from_ffi(
543 self.ffi
544 .read_associated_image(file_id, RStr::from_str(name)),
545 )
546 .map(Image::from)
547 }
548
549 pub fn roi(&self, file_id: FileId) -> HostResult<Option<Rect>> {
551 self.call(methods::ROI_GET, &FileArgs { file_id })
552 }
553
554 pub fn measurements(&self, file_id: FileId) -> HostResult<Vec<MeasurementInfo>> {
556 self.call(methods::MEASUREMENTS_LIST, &FileArgs { file_id })
557 }
558
559 pub fn add_toolbar_button(&self, spec: ToolbarButtonSpec) -> HostResult<()> {
562 self.command(methods::TOOLBAR_ADD, &spec)
563 }
564
565 pub fn update_toolbar_button(&self, update: ButtonUpdate) -> HostResult<()> {
566 self.command(methods::TOOLBAR_UPDATE, &update)
567 }
568
569 pub fn set_toolbar_button_active(&self, button_id: &str, active: bool) -> HostResult<()> {
571 self.update_toolbar_button(ButtonUpdate {
572 button_id: button_id.to_string(),
573 active: Some(active),
574 ..Default::default()
575 })
576 }
577
578 pub fn remove_toolbar_button(&self, button_id: &str) -> HostResult<()> {
579 self.command(
580 methods::TOOLBAR_REMOVE,
581 &IdArgs {
582 id: button_id.into(),
583 },
584 )
585 }
586
587 pub fn add_hud_button(&self, spec: HudButtonSpec) -> HostResult<()> {
588 self.command(methods::HUD_ADD, &spec)
589 }
590
591 pub fn update_hud_button(&self, update: ButtonUpdate) -> HostResult<()> {
592 self.command(methods::HUD_UPDATE, &update)
593 }
594
595 pub fn remove_hud_button(&self, button_id: &str) -> HostResult<()> {
596 self.command(
597 methods::HUD_REMOVE,
598 &IdArgs {
599 id: button_id.into(),
600 },
601 )
602 }
603
604 pub fn set_badge(
608 &self,
609 badge_id: &str,
610 file_id: Option<FileId>,
611 text: Option<&str>,
612 ) -> HostResult<()> {
613 self.command(
614 methods::BADGE_SET,
615 &BadgeArgs {
616 badge_id: badge_id.to_string(),
617 file_id,
618 text: text.map(str::to_string),
619 },
620 )
621 }
622
623 pub fn register_batch_command(&self, spec: BatchCommandSpec) -> HostResult<()> {
627 self.command(methods::BATCH_REGISTER, &spec)
628 }
629
630 pub fn batch_progress(
632 &self,
633 run_id: &str,
634 fraction: Option<f32>,
635 message: Option<&str>,
636 ) -> HostResult<()> {
637 self.command(
638 methods::BATCH_PROGRESS,
639 &BatchProgressArgs {
640 run_id: run_id.to_string(),
641 fraction,
642 message: message.map(str::to_string),
643 },
644 )
645 }
646
647 pub fn finish_batch(&self, result: BatchFinishArgs) -> HostResult<()> {
650 self.command(methods::BATCH_FINISH, &result)
651 }
652
653 pub fn register_hotkey(&self, spec: HotkeySpec) -> HostResult<()> {
660 self.command(methods::HOTKEY_REGISTER, &spec)
661 }
662
663 pub fn unregister_hotkey(&self, hotkey_id: &str) -> HostResult<()> {
664 self.command(
665 methods::HOTKEY_UNREGISTER,
666 &IdArgs {
667 id: hotkey_id.to_string(),
668 },
669 )
670 }
671
672 pub fn register_tool(&self, spec: ToolSpec) -> HostResult<()> {
673 self.command(methods::TOOL_REGISTER, &spec)
674 }
675
676 pub fn unregister_tool(&self, tool_id: &str) -> HostResult<()> {
677 self.command(methods::TOOL_UNREGISTER, &IdArgs { id: tool_id.into() })
678 }
679
680 pub fn activate_tool(&self, tool_id: &str) -> HostResult<()> {
681 self.command(methods::TOOL_ACTIVATE, &IdArgs { id: tool_id.into() })
682 }
683
684 pub fn deactivate_tools(&self) -> HostResult<()> {
686 self.command(methods::TOOL_DEACTIVATE, &Map::new())
687 }
688
689 pub fn create_layer(&self, spec: LayerSpec) -> HostResult<Layer> {
693 let layer_id = spec.layer_id.clone();
694 self.command(methods::LAYER_CREATE, &spec)?;
695 Ok(self.layer(layer_id))
696 }
697
698 pub fn layer(&self, layer_id: impl Into<String>) -> Layer {
700 Layer {
701 host: self.clone(),
702 layer_id: layer_id.into(),
703 }
704 }
705
706 pub fn open_surface(&self, spec: SurfaceSpec) -> HostResult<Surface> {
710 let opened: SurfaceOpened = self.call(methods::SURFACE_OPEN, &spec)?;
711 Ok(self.surface(opened.surface_id))
712 }
713
714 pub fn surface(&self, surface_id: impl Into<String>) -> Surface {
716 Surface {
717 host: self.clone(),
718 surface_id: surface_id.into(),
719 }
720 }
721
722 pub fn confirm(&self, args: ConfirmArgs) -> HostResult<String> {
727 self.call::<_, RequestId>(methods::DIALOG_CONFIRM, &args)
728 .map(|r| r.request_id)
729 }
730
731 pub fn open_file_dialog(&self, args: FileDialogArgs) -> HostResult<String> {
734 self.call::<_, RequestId>(methods::DIALOG_OPEN_FILE, &args)
735 .map(|r| r.request_id)
736 }
737
738 pub fn save_file_dialog(&self, args: FileDialogArgs) -> HostResult<String> {
741 self.call::<_, RequestId>(methods::DIALOG_SAVE_FILE, &args)
742 .map(|r| r.request_id)
743 }
744
745 pub fn fetch_model(&self, args: ModelFetchArgs) -> HostResult<String> {
753 self.call::<_, RequestId>(methods::MODEL_FETCH, &args)
754 .map(|r| r.request_id)
755 }
756
757 pub fn resolve_model(&self, sha256: &str) -> HostResult<Option<ModelRecord>> {
759 self.call(
760 methods::MODEL_RESOLVE,
761 &ModelResolveArgs {
762 sha256: sha256.to_ascii_lowercase(),
763 },
764 )
765 }
766
767 pub fn models(&self) -> HostResult<Vec<ModelRecord>> {
769 self.call(methods::MODEL_LIST, &Map::new())
770 }
771
772 pub fn set_view(&self, args: ViewSetArgs) -> HostResult<()> {
775 self.command(methods::VIEW_SET, &args)
776 }
777
778 pub fn pan(&self, pane: Option<PaneId>, dx: f64, dy: f64) -> HostResult<()> {
780 self.command(methods::VIEW_PAN, &ViewPanArgs { pane, dx, dy })
781 }
782
783 pub fn zoom(&self, pane: Option<PaneId>, factor: f64) -> HostResult<()> {
785 self.command(
786 methods::VIEW_ZOOM,
787 &ViewZoomArgs {
788 pane,
789 factor,
790 anchor_x: None,
791 anchor_y: None,
792 animate: false,
793 },
794 )
795 }
796
797 pub fn fit(&self, pane: Option<PaneId>) -> HostResult<()> {
798 self.command(methods::VIEW_FIT, &PaneArgs { pane })
799 }
800
801 pub fn set_view_orientation(
805 &self,
806 pane: Option<PaneId>,
807 rotation_deg: f64,
808 flipped: bool,
809 ) -> HostResult<()> {
810 self.command(
811 methods::VIEW_ORIENTATION,
812 &ViewOrientationArgs {
813 pane,
814 rotation_deg,
815 flipped,
816 },
817 )
818 }
819
820 pub fn display_adjustments(&self, pane: Option<PaneId>) -> HostResult<DisplayAdjustments> {
823 self.call(methods::VIEW_DISPLAY, &PaneArgs { pane })
824 }
825
826 pub fn frame(&self, pane: Option<PaneId>, rect: Rect) -> HostResult<()> {
828 self.command(
829 methods::VIEW_FRAME,
830 &ViewFrameArgs {
831 pane,
832 rect,
833 padding: None,
834 },
835 )
836 }
837
838 pub fn cycle_pane(&self, offset: i32) -> HostResult<()> {
839 self.command(methods::APP_CYCLE_PANE, &OffsetArgs { offset })
840 }
841
842 pub fn cycle_tab(&self, offset: i32) -> HostResult<()> {
843 self.command(methods::APP_CYCLE_TAB, &OffsetArgs { offset })
844 }
845
846 pub fn series(&self, action: SeriesAction) -> HostResult<()> {
847 self.command(methods::APP_SERIES, &SeriesArgs { action })
848 }
849
850 pub fn request_render(&self) -> HostResult<()> {
853 self.command(methods::RENDER_REQUEST, &Map::new())
854 }
855
856 pub fn push_undo(
861 &self,
862 entry_id: impl Into<String>,
863 file_id: Option<FileId>,
864 label: impl Into<String>,
865 ) -> HostResult<()> {
866 self.command(
867 methods::UNDO_PUSH,
868 &UndoPushArgs {
869 entry_id: entry_id.into(),
870 file_id,
871 label: label.into(),
872 },
873 )
874 }
875
876 pub fn clear_undo(&self, file_id: Option<FileId>) -> HostResult<()> {
878 self.command(methods::UNDO_CLEAR, &UndoClearArgs { file_id })
879 }
880
881 pub fn register_filter(&self, spec: FilterSpec) -> HostResult<()> {
884 self.command(methods::FILTER_REGISTER, &spec)
885 }
886
887 pub fn set_filter_enabled(&self, filter_id: &str, enabled: bool) -> HostResult<()> {
888 self.command(
889 methods::FILTER_SET_ENABLED,
890 &FilterEnableArgs {
891 filter_id: filter_id.into(),
892 enabled,
893 },
894 )
895 }
896
897 pub fn unregister_filter(&self, filter_id: &str) -> HostResult<()> {
898 self.command(
899 methods::FILTER_UNREGISTER,
900 &IdArgs {
901 id: filter_id.into(),
902 },
903 )
904 }
905
906 pub fn setting<T: DeserializeOwned>(&self, key: &str) -> HostResult<Option<T>> {
910 let value: Value = self.call(methods::SETTINGS_GET, &KeyArgs { key: key.into() })?;
911 if value.is_null() {
912 return Ok(None);
913 }
914 serde_json::from_value(value)
915 .map(Some)
916 .map_err(|e| HostError::new(FfiErrorKind::Failed, format!("setting '{key}': {e}")))
917 }
918
919 pub fn set_setting<T: Serialize + ?Sized>(&self, key: &str, value: &T) -> HostResult<()> {
921 let value = serde_json::to_value(value)
922 .map_err(|e| HostError::new(FfiErrorKind::InvalidArguments, e.to_string()))?;
923 self.command(
924 methods::SETTINGS_SET,
925 &SettingsSetArgs {
926 key: key.into(),
927 value,
928 },
929 )
930 }
931
932 pub fn remove_setting(&self, key: &str) -> HostResult<()> {
933 self.command(
934 methods::SETTINGS_SET,
935 &SettingsSetArgs {
936 key: key.into(),
937 value: Value::Null,
938 },
939 )
940 }
941
942 pub fn start_job(&self, title: impl Into<String>, cancellable: bool) -> HostResult<Job> {
946 let started: JobStarted = self.call(
947 methods::JOB_START,
948 &JobStartArgs {
949 title: title.into(),
950 cancellable,
951 },
952 )?;
953 Ok(Job {
954 host: self.clone(),
955 job_id: started.job_id,
956 finished: false,
957 })
958 }
959
960 pub fn copy_text(&self, text: impl Into<String>) -> HostResult<()> {
963 self.command(methods::CLIPBOARD_SET_TEXT, &TextArgs { text: text.into() })
964 }
965
966 pub fn post(&self, token: impl Into<String>) -> HostResult<()> {
969 self.command(
970 methods::POST,
971 &PostArgs {
972 token: token.into(),
973 },
974 )
975 }
976
977 pub fn subscribe(&self, events: &[&str]) -> HostResult<()> {
980 self.command(
981 methods::EVENTS_SUBSCRIBE,
982 &SubscribeArgs {
983 events: events.iter().map(|e| e.to_string()).collect(),
984 },
985 )
986 }
987}
988
989#[derive(Clone)]
991pub struct Layer {
992 host: Host,
993 layer_id: String,
994}
995
996impl Layer {
997 pub fn id(&self) -> &str {
998 &self.layer_id
999 }
1000
1001 pub fn upsert(&self, objects: Vec<OverlayObject>) -> HostResult<()> {
1003 self.host.command(
1004 methods::LAYER_UPSERT,
1005 &UpsertObjectsArgs {
1006 layer_id: self.layer_id.clone(),
1007 objects,
1008 replace_all: false,
1009 },
1010 )
1011 }
1012
1013 pub fn replace_all(&self, objects: Vec<OverlayObject>) -> HostResult<()> {
1015 self.host.command(
1016 methods::LAYER_UPSERT,
1017 &UpsertObjectsArgs {
1018 layer_id: self.layer_id.clone(),
1019 objects,
1020 replace_all: true,
1021 },
1022 )
1023 }
1024
1025 pub fn remove(&self, object_ids: Vec<String>) -> HostResult<()> {
1026 self.host.command(
1027 methods::LAYER_REMOVE_OBJECTS,
1028 &RemoveObjectsArgs {
1029 layer_id: self.layer_id.clone(),
1030 object_ids,
1031 },
1032 )
1033 }
1034
1035 pub fn clear(&self) -> HostResult<()> {
1036 self.host.command(
1037 methods::LAYER_CLEAR,
1038 &IdArgs {
1039 id: self.layer_id.clone(),
1040 },
1041 )
1042 }
1043
1044 pub fn update(&self, mut update: LayerUpdate) -> HostResult<()> {
1046 update.layer_id = self.layer_id.clone();
1047 self.host.command(methods::LAYER_UPDATE, &update)
1048 }
1049
1050 pub fn set_visible(&self, visible: bool) -> HostResult<()> {
1051 self.update(LayerUpdate {
1052 visible: Some(visible),
1053 ..Default::default()
1054 })
1055 }
1056
1057 pub fn select(&self, object_ids: Vec<String>) -> HostResult<()> {
1059 self.host.command(
1060 methods::LAYER_SELECT,
1061 &SelectArgs {
1062 layer_id: self.layer_id.clone(),
1063 object_ids,
1064 },
1065 )
1066 }
1067
1068 pub fn put_raster(
1070 &self,
1071 object_id: impl Into<String>,
1072 rect: Rect,
1073 image: Image,
1074 smooth: bool,
1075 ) -> HostResult<()> {
1076 from_ffi(self.host.ffi.put_raster(RasterUpload {
1077 layer_id: RString::from(self.layer_id.as_str()),
1078 object_id: RString::from(object_id.into()),
1079 x: rect.x,
1080 y: rect.y,
1081 width: rect.width,
1082 height: rect.height,
1083 pixels: image.into_pixels(),
1084 smooth,
1085 }))
1086 }
1087
1088 pub fn highlight(&self, object_ids: Vec<String>) -> HostResult<()> {
1091 self.host.command(
1092 methods::LAYER_HIGHLIGHT,
1093 &SelectArgs {
1094 layer_id: self.layer_id.clone(),
1095 object_ids,
1096 },
1097 )
1098 }
1099
1100 pub fn set_min_zoom(&self, min_zoom: Option<f64>) -> HostResult<()> {
1103 self.host.command(
1104 methods::LAYER_SET_MIN_ZOOM,
1105 &MinZoomArgs {
1106 layer_id: self.layer_id.clone(),
1107 min_zoom,
1108 },
1109 )
1110 }
1111
1112 pub fn set_panes(&self, panes: Option<Vec<PaneId>>) -> HostResult<()> {
1116 self.host.command(
1117 methods::LAYER_SET_PANES,
1118 &PaneFilterArgs {
1119 layer_id: self.layer_id.clone(),
1120 panes,
1121 },
1122 )
1123 }
1124
1125 pub fn set_visible_in_pane(&self, pane: PaneId, visible: bool) -> HostResult<()> {
1128 self.host.command(
1129 methods::LAYER_SET_PANE_VISIBILITY,
1130 &PaneVisibilityArgs {
1131 layer_id: self.layer_id.clone(),
1132 pane,
1133 visible,
1134 },
1135 )
1136 }
1137
1138 pub fn remove_layer(self) -> HostResult<()> {
1140 self.host.command(
1141 methods::LAYER_REMOVE,
1142 &IdArgs {
1143 id: self.layer_id.clone(),
1144 },
1145 )
1146 }
1147}
1148
1149#[derive(Clone)]
1151pub struct Surface {
1152 host: Host,
1153 surface_id: String,
1154}
1155
1156impl Surface {
1157 pub fn id(&self) -> &str {
1158 &self.surface_id
1159 }
1160
1161 pub fn set(&self, name: &str, value: impl Serialize) -> HostResult<()> {
1163 let value = serde_json::to_value(value)
1164 .map_err(|e| HostError::new(FfiErrorKind::InvalidArguments, e.to_string()))?;
1165 let mut properties = Map::new();
1166 properties.insert(name.to_string(), value);
1167 self.set_many(properties)
1168 }
1169
1170 pub fn set_many(&self, properties: Map<String, Value>) -> HostResult<()> {
1174 self.host.command(
1175 methods::SURFACE_SET,
1176 &SurfaceProperties {
1177 surface_id: self.surface_id.clone(),
1178 properties,
1179 },
1180 )
1181 }
1182
1183 pub fn is_open(&self) -> bool {
1184 self.host
1185 .call::<_, bool>(
1186 methods::SURFACE_IS_OPEN,
1187 &IdArgs {
1188 id: self.surface_id.clone(),
1189 },
1190 )
1191 .unwrap_or(false)
1192 }
1193
1194 pub fn close(&self) -> HostResult<()> {
1195 self.host.command(
1196 methods::SURFACE_CLOSE,
1197 &IdArgs {
1198 id: self.surface_id.clone(),
1199 },
1200 )
1201 }
1202}
1203
1204pub struct Job {
1207 host: Host,
1208 job_id: String,
1209 finished: bool,
1210}
1211
1212impl Job {
1213 pub fn id(&self) -> &str {
1214 &self.job_id
1215 }
1216
1217 pub fn update(&self, fraction: Option<f32>, message: Option<&str>) {
1219 let _ = self.host.command(
1220 methods::JOB_UPDATE,
1221 &JobUpdateArgs {
1222 job_id: self.job_id.clone(),
1223 fraction: fraction.map(|f| f.clamp(0.0, 1.0)),
1224 message: message.map(str::to_string),
1225 },
1226 );
1227 }
1228
1229 pub fn finish(mut self, error: Option<String>) {
1231 self.finish_inner(error);
1232 }
1233
1234 fn finish_inner(&mut self, error: Option<String>) {
1235 if self.finished {
1236 return;
1237 }
1238 self.finished = true;
1239 let _ = self.host.command(
1240 methods::JOB_FINISH,
1241 &JobFinishArgs {
1242 job_id: self.job_id.clone(),
1243 error,
1244 },
1245 );
1246 }
1247}
1248
1249impl Drop for Job {
1250 fn drop(&mut self) {
1251 self.finish_inner(None);
1252 }
1253}
1254
1255fn panic_message(payload: &(dyn Any + Send)) -> String {
1260 if let Some(text) = payload.downcast_ref::<&str>() {
1261 (*text).to_string()
1262 } else if let Some(text) = payload.downcast_ref::<String>() {
1263 text.clone()
1264 } else {
1265 "unknown panic payload".to_string()
1266 }
1267}
1268
1269fn guarded<T>(f: impl FnOnce() -> Result<T, FfiError>) -> FfiResult<T> {
1271 match catch_unwind(AssertUnwindSafe(f)) {
1272 Ok(Ok(value)) => ROk(value),
1273 Ok(Err(error)) => RErr(error),
1274 Err(payload) => RErr(FfiError::new(
1275 FfiErrorKind::Panicked,
1276 format!("plugin panicked: {}", panic_message(payload.as_ref())),
1277 )),
1278 }
1279}
1280
1281#[doc(hidden)]
1282pub struct Adapter<P: Plugin> {
1283 plugin: Arc<P>,
1285 catalogs: Option<(std::path::PathBuf, String)>,
1287 host: Option<Host>,
1289}
1290
1291fn plugin_catalogs(plugin_root: &str) -> Result<Option<(std::path::PathBuf, String)>, String> {
1294 let root = std::path::Path::new(plugin_root);
1295 let path = root.join(crate::manifest::MANIFEST_FILENAME);
1296 if !path.is_file() {
1297 return Ok(None);
1298 }
1299 let manifest = crate::PluginManifest::from_file(&path).map_err(|e| e.to_string())?;
1300 Ok(manifest.catalogs(root))
1301}
1302
1303fn switch_language(
1308 catalogs: Option<&(std::path::PathBuf, String)>,
1309 tag: Option<&str>,
1310) -> Result<(), String> {
1311 use crate::i18n;
1312 let language = tag.and_then(i18n::by_tag).unwrap_or(i18n::source());
1313 let catalog = match catalogs {
1314 Some((dir, domain)) => Catalog::load(dir, domain, language).map_err(|e| e.message),
1315 None => Ok(None),
1316 };
1317 match catalog {
1318 Ok(catalog) => {
1319 i18n::set_catalog(language, catalog);
1320 match tag {
1321 Some(tag) if i18n::by_tag(tag).is_none() => Err(format!(
1322 "eov's language '{tag}' is unknown to this plugin's SDK; texts are in English"
1323 )),
1324 _ => Ok(()),
1325 }
1326 }
1327 Err(error) => {
1328 i18n::set_catalog(language, None);
1329 Err(format!("translations not loaded: {error}"))
1330 }
1331 }
1332}
1333
1334impl<P: Plugin> Adapter<P> {
1335 fn dispatch(&self, event_json: &str) -> Result<String, FfiError> {
1336 let event: HostEvent = serde_json::from_str(event_json).map_err(|e| {
1337 FfiError::new(FfiErrorKind::InvalidArguments, format!("bad event: {e}"))
1338 })?;
1339 if let HostEvent::LanguageChanged { language } = &event
1340 && let Err(error) = switch_language(self.catalogs.as_ref(), Some(language))
1341 && let Some(host) = &self.host
1342 {
1343 host.info(error);
1347 }
1348 match event {
1349 HostEvent::ContextMenuRequested(context) => {
1350 let items = self.plugin.context_menu(&context);
1351 to_json(&ContextMenuResponse { items })
1352 }
1353 HostEvent::UiCallback {
1354 surface_id,
1355 name,
1356 args,
1357 } => {
1358 let value = self
1359 .plugin
1360 .ui_callback(&surface_id, &name, &args)
1361 .map_err(FfiError::failed)?;
1362 to_json(&value)
1363 }
1364 HostEvent::Unknown => Err(FfiError::new(
1365 FfiErrorKind::Unsupported,
1366 "event not supported by this plugin version",
1367 )),
1368 other => self
1369 .plugin
1370 .on_event(other)
1371 .map(|()| "null".to_string())
1372 .map_err(FfiError::failed),
1373 }
1374 }
1375}
1376
1377fn to_json<T: Serialize>(value: &T) -> Result<String, FfiError> {
1378 serde_json::to_string(value).map_err(|e| FfiError::failed(e.to_string()))
1379}
1380
1381impl<P: Plugin> PluginFfi for Adapter<P> {
1382 fn handle_event(&self, event_json: RStr<'_>) -> FfiResult<RString> {
1383 guarded(|| self.dispatch(event_json.as_str()).map(RString::from))
1384 }
1385
1386 fn apply_filter(&self, filter_id: RStr<'_>, frame: FilterFrame<'_>) -> FfiResult<()> {
1387 guarded(|| {
1388 let FilterFrame {
1389 pixels,
1390 width,
1391 height,
1392 stride,
1393 view,
1394 } = frame;
1395 let mut frame = Frame::new(
1396 pixels.into_mut_slice(),
1397 width,
1398 height,
1399 stride as usize,
1400 view,
1401 )
1402 .ok_or_else(|| {
1403 FfiError::new(
1404 FfiErrorKind::InvalidArguments,
1405 format!("frame buffer too small for {width}x{height} (stride {stride})"),
1406 )
1407 })?;
1408 self.plugin
1409 .apply_filter(filter_id.as_str(), &mut frame)
1410 .map_err(FfiError::failed)
1411 })
1412 }
1413
1414 fn shutdown(&self) {
1415 let _ = catch_unwind(AssertUnwindSafe(|| self.plugin.shutdown()));
1416 }
1417}
1418
1419#[doc(hidden)]
1423pub fn into_plugin_box<P: Plugin>(plugin: P) -> PluginBox {
1424 into_plugin_box_with_catalogs(plugin, None, None)
1425}
1426
1427fn into_plugin_box_with_catalogs<P: Plugin>(
1428 plugin: P,
1429 catalogs: Option<(std::path::PathBuf, String)>,
1430 host: Option<Host>,
1431) -> PluginBox {
1432 PluginFfi_TO::from_value(
1433 Adapter {
1434 plugin: Arc::new(plugin),
1435 catalogs,
1436 host,
1437 },
1438 TD_CanDowncast,
1439 )
1440}
1441
1442extern "C" fn slide_source<P: Plugin>(instance: &PluginBox) -> FfiResult<SlideSourceBox> {
1445 slide_source_of::<P>(instance)
1446}
1447
1448#[doc(hidden)]
1450pub fn slide_source_of<P: Plugin>(instance: &PluginBox) -> FfiResult<SlideSourceBox> {
1451 guarded(|| {
1452 let adapter = instance
1453 .obj
1454 .downcast_as::<Adapter<P>>()
1455 .map_err(|_| FfiError::failed("the instance was not created by this plugin library"))?;
1456 Ok(SlideSourceFfi_TO::from_value(
1457 SourceAdapter {
1458 plugin: Arc::clone(&adapter.plugin),
1459 },
1460 TD_Opaque,
1461 ))
1462 })
1463}
1464
1465struct SourceAdapter<P: Plugin> {
1466 plugin: Arc<P>,
1467}
1468
1469impl<P: Plugin> SlideSourceFfi for SourceAdapter<P> {
1470 fn open(&self, request_json: RStr<'_>) -> FfiResult<SlideBox> {
1471 guarded(|| {
1472 let request: SlideOpenRequest =
1473 serde_json::from_str(request_json.as_str()).map_err(|e| {
1474 FfiError::new(FfiErrorKind::InvalidArguments, format!("bad request: {e}"))
1475 })?;
1476 let reader = self.plugin.open_slide(&request).map_err(FfiError::failed)?;
1477 Ok(SlideFfi_TO::from_value(SlideAdapter { reader }, TD_Opaque))
1478 })
1479 }
1480}
1481
1482struct SlideAdapter {
1483 reader: Box<dyn SlideReader>,
1484}
1485
1486impl SlideFfi for SlideAdapter {
1487 fn info(&self) -> FfiResult<RString> {
1488 guarded(|| to_json(&self.reader.info()).map(RString::from))
1489 }
1490
1491 fn read_region(&self, region: SlideRegion, out: RSliceMut<'_, u8>) -> FfiResult<()> {
1492 guarded(|| {
1493 let out = out.into_mut_slice();
1494 let expected = region.width as usize * region.height as usize * 4;
1495 if out.len() != expected {
1496 return Err(FfiError::new(
1497 FfiErrorKind::InvalidArguments,
1498 format!(
1499 "the buffer holds {} bytes; {}×{} RGBA needs {expected}",
1500 out.len(),
1501 region.width,
1502 region.height
1503 ),
1504 ));
1505 }
1506 self.reader
1507 .read_region(®ion, out)
1508 .map_err(FfiError::failed)
1509 })
1510 }
1511
1512 fn read_associated_image(&self, name: RStr<'_>) -> FfiResult<Pixels> {
1513 guarded(|| {
1514 let image = self
1515 .reader
1516 .read_associated_image(name.as_str())
1517 .map_err(FfiError::failed)?;
1518 Ok(Pixels {
1519 width: image.width,
1520 height: image.height,
1521 data: image.data.into(),
1522 })
1523 })
1524 }
1525
1526 fn call(&self, method: RStr<'_>, _args_json: RStr<'_>) -> FfiResult<RString> {
1527 RErr(FfiError::new(
1528 FfiErrorKind::Unsupported,
1529 format!("the slide has no method '{}'", method.as_str()),
1530 ))
1531 }
1532}
1533
1534#[doc(hidden)]
1536pub fn create_plugin<P: Plugin>(host: HostBox, init_json: &str) -> Result<PluginBox, FfiError> {
1537 guarded(|| {
1538 let init: PluginInit = serde_json::from_str(init_json)
1539 .map_err(|e| FfiError::new(FfiErrorKind::InvalidArguments, format!("bad init: {e}")))?;
1540 let host = Host::from_ffi(host);
1541 let catalogs = plugin_catalogs(&init.plugin_root).unwrap_or_else(|error| {
1545 host.info(format!("translations not loaded: {error}"));
1546 None
1547 });
1548 if let Err(error) = switch_language(catalogs.as_ref(), init.language.as_deref()) {
1549 host.info(error);
1550 }
1551 let plugin = P::create(host.clone(), init).map_err(FfiError::failed)?;
1552 Ok(into_plugin_box_with_catalogs(plugin, catalogs, Some(host)))
1553 })
1554 .into_result()
1555}
1556
1557extern "C" fn create_instance<P: Plugin>(
1558 host: HostBox,
1559 init_json: RStr<'_>,
1560) -> FfiResult<PluginBox> {
1561 create_plugin::<P>(host, init_json.as_str()).into()
1562}
1563
1564#[doc(hidden)]
1566pub fn root_module<P: Plugin>() -> PluginModuleRef {
1567 PluginModule {
1568 abi_version: abi::ABI_VERSION,
1569 api_version: RStr::from_str(abi::API_VERSION),
1570 create: create_instance::<P>,
1571 slide_source: slide_source::<P>,
1572 }
1573 .leak_into_prefix()
1574}
1575
1576#[macro_export]
1580macro_rules! export_plugin {
1581 ($plugin:ty) => {
1582 #[doc(hidden)]
1583 #[unsafe(no_mangle)]
1584 #[allow(non_upper_case_globals)]
1585 pub static _1as_0lib_1header_0root_bmodule_bloader: $crate::__private::LibHeader = {
1586 extern "C" fn __eov_erased_root_module() -> $crate::__private::RootModuleResult {
1587 fn __eov_root_module() -> $crate::abi::PluginModuleRef {
1588 $crate::sdk::root_module::<$plugin>()
1589 }
1590 $crate::__private::call_root_module_loader(__eov_root_module)
1591 }
1592 unsafe {
1593 $crate::__private::LibHeader::from_constructor::<$crate::abi::PluginModuleRef>(
1594 __eov_erased_root_module,
1595 $crate::__private::CheckTypeLayout::Yes,
1596 )
1597 }
1598 };
1599 };
1600}