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::protocol::{methods, *};
89use abi_stable::{
90 prefix_type::PrefixTypeTrait,
91 sabi_trait::{TD_CanDowncast, TD_Opaque},
92 std_types::{RErr, ROk, RSliceMut, RStr, RString},
93};
94use serde::{Serialize, de::DeserializeOwned};
95use serde_json::{Map, Value};
96use std::any::Any;
97use std::panic::{AssertUnwindSafe, catch_unwind};
98use std::sync::Arc;
99
100pub const ROOT_MODULE_LOADER_SYMBOL: &str = "_1as_0lib_1header_0root_bmodule_bloader";
104
105pub trait Plugin: Send + Sync + Sized + 'static {
118 fn create(host: Host, init: PluginInit) -> Result<Self, String>;
120
121 fn on_event(&self, event: HostEvent) -> Result<(), String> {
123 let _ = event;
124 Ok(())
125 }
126
127 fn context_menu(&self, context: &MenuContext) -> Vec<MenuItem> {
129 let _ = context;
130 Vec::new()
131 }
132
133 fn ui_callback(&self, surface_id: &str, name: &str, args: &[Value]) -> Result<Value, String> {
137 let _ = (surface_id, name, args);
138 Ok(Value::Null)
139 }
140
141 fn apply_filter(&self, filter_id: &str, frame: &mut Frame<'_>) -> Result<(), String> {
144 let _ = (filter_id, frame);
145 Ok(())
146 }
147
148 fn open_slide(&self, request: &SlideOpenRequest) -> Result<Box<dyn SlideReader>, String> {
157 Err(format!(
158 "this plugin reads no slide formats (asked for '{}')",
159 request.format_id
160 ))
161 }
162
163 fn shutdown(&self) {}
167}
168
169pub trait SlideReader: Send + Sync + 'static {
177 fn info(&self) -> SlideInfo;
180
181 fn read_region(&self, region: &SlideRegion, out: &mut [u8]) -> Result<(), String>;
186
187 fn read_associated_image(&self, name: &str) -> Result<Image, String> {
190 Err(format!("no associated image '{name}'"))
191 }
192}
193
194#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct HostError {
201 pub kind: FfiErrorKind,
202 pub message: String,
203}
204
205impl HostError {
206 fn new(kind: FfiErrorKind, message: impl Into<String>) -> Self {
207 Self {
208 kind,
209 message: message.into(),
210 }
211 }
212
213 pub fn is_unsupported(&self) -> bool {
215 self.kind == FfiErrorKind::Unsupported
216 }
217}
218
219impl std::fmt::Display for HostError {
220 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221 f.write_str(&self.message)
222 }
223}
224
225impl std::error::Error for HostError {}
226
227impl From<FfiError> for HostError {
228 fn from(error: FfiError) -> Self {
229 Self::new(error.kind(), error.message.into_string())
230 }
231}
232
233impl From<HostError> for String {
234 fn from(error: HostError) -> Self {
235 error.message
236 }
237}
238
239pub type HostResult<T> = Result<T, HostError>;
240
241fn from_ffi<T>(result: FfiResult<T>) -> HostResult<T> {
242 result.into_result().map_err(HostError::from)
243}
244
245#[derive(Debug, Clone, PartialEq, Eq, Default)]
251pub struct Image {
252 pub width: u32,
253 pub height: u32,
254 pub data: Vec<u8>,
255}
256
257impl Image {
258 pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
260 if x >= self.width || y >= self.height {
261 return None;
262 }
263 let i = (y as usize * self.width as usize + x as usize) * 4;
264 self.data.get(i..i + 4).map(|p| [p[0], p[1], p[2], p[3]])
265 }
266
267 fn into_pixels(self) -> abi::Pixels {
268 abi::Pixels {
269 width: self.width,
270 height: self.height,
271 data: self.data.into(),
272 }
273 }
274}
275
276impl From<abi::Pixels> for Image {
277 fn from(pixels: abi::Pixels) -> Self {
278 Self {
279 width: pixels.width,
280 height: pixels.height,
281 data: pixels.data.into_vec(),
282 }
283 }
284}
285
286pub struct Frame<'a> {
288 pixels: &'a mut [u8],
289 width: u32,
290 height: u32,
291 stride: usize,
292 view: FilterView,
293}
294
295impl<'a> Frame<'a> {
296 pub fn new(
299 pixels: &'a mut [u8],
300 width: u32,
301 height: u32,
302 stride: usize,
303 view: FilterView,
304 ) -> Option<Self> {
305 let row = (width as usize).checked_mul(4)?;
306 if stride < row {
307 return None;
308 }
309 let needed = if height == 0 {
310 0
311 } else {
312 stride.checked_mul(height as usize - 1)?.checked_add(row)?
313 };
314 (pixels.len() >= needed).then_some(Self {
315 pixels,
316 width,
317 height,
318 stride,
319 view,
320 })
321 }
322
323 pub fn width(&self) -> u32 {
324 self.width
325 }
326
327 pub fn height(&self) -> u32 {
328 self.height
329 }
330
331 pub fn stride(&self) -> usize {
333 self.stride
334 }
335
336 pub fn view(&self) -> &FilterView {
338 &self.view
339 }
340
341 pub fn row_mut(&mut self, y: u32) -> &mut [u8] {
343 assert!(y < self.height, "row {y} out of range");
344 let start = y as usize * self.stride;
345 &mut self.pixels[start..start + self.width as usize * 4]
346 }
347
348 pub fn rows_mut(&mut self) -> impl Iterator<Item = &mut [u8]> + '_ {
350 let row = self.width as usize * 4;
351 let height = self.height as usize;
352 self.pixels
353 .chunks_mut(self.stride.max(1))
354 .take(height)
355 .map(move |chunk| &mut chunk[..row])
356 }
357
358 pub fn for_each_pixel(&mut self, mut f: impl FnMut(u32, u32, &mut [u8])) {
360 let width = self.width;
361 for (y, row) in self.rows_mut().enumerate() {
362 let (pixels, _) = row.as_chunks_mut::<4>();
363 for (x, px) in pixels.iter_mut().enumerate().take(width as usize) {
364 f(x as u32, y as u32, px);
365 }
366 }
367 }
368}
369
370#[derive(Clone)]
376pub struct Host {
377 ffi: Arc<HostBox>,
378}
379
380impl Host {
381 pub fn from_ffi(ffi: HostBox) -> Self {
384 Self { ffi: Arc::new(ffi) }
385 }
386
387 pub fn call_raw(&self, method: &str, args_json: &str) -> HostResult<String> {
389 from_ffi(
390 self.ffi
391 .call(RStr::from_str(method), RStr::from_str(args_json)),
392 )
393 .map(RString::into_string)
394 }
395
396 pub fn call<A, R>(&self, method: &str, args: &A) -> HostResult<R>
398 where
399 A: Serialize + ?Sized,
400 R: DeserializeOwned,
401 {
402 let args = serde_json::to_string(args)
403 .map_err(|e| HostError::new(FfiErrorKind::InvalidArguments, e.to_string()))?;
404 let reply = self.call_raw(method, &args)?;
405 serde_json::from_str(&reply).map_err(|e| {
406 HostError::new(
407 FfiErrorKind::Failed,
408 format!("unexpected reply to '{method}': {e}"),
409 )
410 })
411 }
412
413 fn command<A: Serialize + ?Sized>(&self, method: &str, args: &A) -> HostResult<()> {
414 self.call::<A, Value>(method, args).map(|_| ())
415 }
416
417 pub fn log(&self, level: LogLevel, message: impl Into<String>) {
422 let _ = self.command(
423 methods::LOG,
424 &LogArgs {
425 level,
426 message: message.into(),
427 },
428 );
429 }
430
431 pub fn debug(&self, message: impl Into<String>) {
432 self.log(LogLevel::Debug, message);
433 }
434
435 pub fn info(&self, message: impl Into<String>) {
436 self.log(LogLevel::Info, message);
437 }
438
439 pub fn warn(&self, message: impl Into<String>) {
440 self.log(LogLevel::Warn, message);
441 }
442
443 pub fn error(&self, message: impl Into<String>) {
444 self.log(LogLevel::Error, message);
445 }
446
447 pub fn notify(&self, level: NotifyLevel, message: impl Into<String>) {
449 let _ = self.command(
450 methods::NOTIFY,
451 &NotifyArgs {
452 level,
453 message: message.into(),
454 detail: None,
455 },
456 );
457 }
458
459 pub fn notify_error(&self, message: impl Into<String>, detail: impl Into<String>) {
461 let _ = self.command(
462 methods::NOTIFY,
463 &NotifyArgs {
464 level: NotifyLevel::Error,
465 message: message.into(),
466 detail: Some(detail.into()),
467 },
468 );
469 }
470
471 pub fn set_status(&self, text: Option<&str>) {
473 let _ = self.command(
474 methods::STATUS,
475 &StatusArgs {
476 text: text.map(str::to_string),
477 },
478 );
479 }
480
481 pub fn snapshot(&self) -> HostResult<HostSnapshot> {
485 self.call(methods::SNAPSHOT, &Map::new())
486 }
487
488 pub fn file_info(&self, file_id: FileId) -> HostResult<FileInfo> {
489 self.call(methods::FILE_INFO, &FileArgs { file_id })
490 }
491
492 pub fn file_properties(&self, file_id: FileId) -> HostResult<PropertyMap> {
494 self.call(methods::FILE_PROPERTIES, &FileArgs { file_id })
495 }
496
497 pub fn open_file(&self, path: impl Into<String>) -> HostResult<()> {
499 self.command(methods::FILE_OPEN, &OpenFileArgs { path: path.into() })
500 }
501
502 pub fn read_region(&self, request: RegionRequest) -> HostResult<Image> {
511 from_ffi(self.ffi.read_region(request)).map(Image::from)
512 }
513
514 pub fn read_associated_image(&self, file_id: FileId, name: &str) -> HostResult<Image> {
516 from_ffi(
517 self.ffi
518 .read_associated_image(file_id, RStr::from_str(name)),
519 )
520 .map(Image::from)
521 }
522
523 pub fn roi(&self, file_id: FileId) -> HostResult<Option<Rect>> {
525 self.call(methods::ROI_GET, &FileArgs { file_id })
526 }
527
528 pub fn measurements(&self, file_id: FileId) -> HostResult<Vec<MeasurementInfo>> {
530 self.call(methods::MEASUREMENTS_LIST, &FileArgs { file_id })
531 }
532
533 pub fn add_toolbar_button(&self, spec: ToolbarButtonSpec) -> HostResult<()> {
536 self.command(methods::TOOLBAR_ADD, &spec)
537 }
538
539 pub fn update_toolbar_button(&self, update: ButtonUpdate) -> HostResult<()> {
540 self.command(methods::TOOLBAR_UPDATE, &update)
541 }
542
543 pub fn set_toolbar_button_active(&self, button_id: &str, active: bool) -> HostResult<()> {
545 self.update_toolbar_button(ButtonUpdate {
546 button_id: button_id.to_string(),
547 active: Some(active),
548 ..Default::default()
549 })
550 }
551
552 pub fn remove_toolbar_button(&self, button_id: &str) -> HostResult<()> {
553 self.command(
554 methods::TOOLBAR_REMOVE,
555 &IdArgs {
556 id: button_id.into(),
557 },
558 )
559 }
560
561 pub fn add_hud_button(&self, spec: HudButtonSpec) -> HostResult<()> {
562 self.command(methods::HUD_ADD, &spec)
563 }
564
565 pub fn update_hud_button(&self, update: ButtonUpdate) -> HostResult<()> {
566 self.command(methods::HUD_UPDATE, &update)
567 }
568
569 pub fn remove_hud_button(&self, button_id: &str) -> HostResult<()> {
570 self.command(
571 methods::HUD_REMOVE,
572 &IdArgs {
573 id: button_id.into(),
574 },
575 )
576 }
577
578 pub fn set_badge(
582 &self,
583 badge_id: &str,
584 file_id: Option<FileId>,
585 text: Option<&str>,
586 ) -> HostResult<()> {
587 self.command(
588 methods::BADGE_SET,
589 &BadgeArgs {
590 badge_id: badge_id.to_string(),
591 file_id,
592 text: text.map(str::to_string),
593 },
594 )
595 }
596
597 pub fn register_batch_command(&self, spec: BatchCommandSpec) -> HostResult<()> {
601 self.command(methods::BATCH_REGISTER, &spec)
602 }
603
604 pub fn batch_progress(
606 &self,
607 run_id: &str,
608 fraction: Option<f32>,
609 message: Option<&str>,
610 ) -> HostResult<()> {
611 self.command(
612 methods::BATCH_PROGRESS,
613 &BatchProgressArgs {
614 run_id: run_id.to_string(),
615 fraction,
616 message: message.map(str::to_string),
617 },
618 )
619 }
620
621 pub fn finish_batch(&self, result: BatchFinishArgs) -> HostResult<()> {
624 self.command(methods::BATCH_FINISH, &result)
625 }
626
627 pub fn register_hotkey(&self, spec: HotkeySpec) -> HostResult<()> {
634 self.command(methods::HOTKEY_REGISTER, &spec)
635 }
636
637 pub fn unregister_hotkey(&self, hotkey_id: &str) -> HostResult<()> {
638 self.command(
639 methods::HOTKEY_UNREGISTER,
640 &IdArgs {
641 id: hotkey_id.to_string(),
642 },
643 )
644 }
645
646 pub fn register_tool(&self, spec: ToolSpec) -> HostResult<()> {
647 self.command(methods::TOOL_REGISTER, &spec)
648 }
649
650 pub fn unregister_tool(&self, tool_id: &str) -> HostResult<()> {
651 self.command(methods::TOOL_UNREGISTER, &IdArgs { id: tool_id.into() })
652 }
653
654 pub fn activate_tool(&self, tool_id: &str) -> HostResult<()> {
655 self.command(methods::TOOL_ACTIVATE, &IdArgs { id: tool_id.into() })
656 }
657
658 pub fn deactivate_tools(&self) -> HostResult<()> {
660 self.command(methods::TOOL_DEACTIVATE, &Map::new())
661 }
662
663 pub fn create_layer(&self, spec: LayerSpec) -> HostResult<Layer> {
667 let layer_id = spec.layer_id.clone();
668 self.command(methods::LAYER_CREATE, &spec)?;
669 Ok(self.layer(layer_id))
670 }
671
672 pub fn layer(&self, layer_id: impl Into<String>) -> Layer {
674 Layer {
675 host: self.clone(),
676 layer_id: layer_id.into(),
677 }
678 }
679
680 pub fn open_surface(&self, spec: SurfaceSpec) -> HostResult<Surface> {
684 let opened: SurfaceOpened = self.call(methods::SURFACE_OPEN, &spec)?;
685 Ok(self.surface(opened.surface_id))
686 }
687
688 pub fn surface(&self, surface_id: impl Into<String>) -> Surface {
690 Surface {
691 host: self.clone(),
692 surface_id: surface_id.into(),
693 }
694 }
695
696 pub fn confirm(&self, args: ConfirmArgs) -> HostResult<String> {
701 self.call::<_, RequestId>(methods::DIALOG_CONFIRM, &args)
702 .map(|r| r.request_id)
703 }
704
705 pub fn open_file_dialog(&self, args: FileDialogArgs) -> HostResult<String> {
708 self.call::<_, RequestId>(methods::DIALOG_OPEN_FILE, &args)
709 .map(|r| r.request_id)
710 }
711
712 pub fn save_file_dialog(&self, args: FileDialogArgs) -> HostResult<String> {
715 self.call::<_, RequestId>(methods::DIALOG_SAVE_FILE, &args)
716 .map(|r| r.request_id)
717 }
718
719 pub fn fetch_model(&self, args: ModelFetchArgs) -> HostResult<String> {
727 self.call::<_, RequestId>(methods::MODEL_FETCH, &args)
728 .map(|r| r.request_id)
729 }
730
731 pub fn resolve_model(&self, sha256: &str) -> HostResult<Option<ModelRecord>> {
733 self.call(
734 methods::MODEL_RESOLVE,
735 &ModelResolveArgs {
736 sha256: sha256.to_ascii_lowercase(),
737 },
738 )
739 }
740
741 pub fn models(&self) -> HostResult<Vec<ModelRecord>> {
743 self.call(methods::MODEL_LIST, &Map::new())
744 }
745
746 pub fn set_view(&self, args: ViewSetArgs) -> HostResult<()> {
749 self.command(methods::VIEW_SET, &args)
750 }
751
752 pub fn pan(&self, pane: Option<PaneId>, dx: f64, dy: f64) -> HostResult<()> {
754 self.command(methods::VIEW_PAN, &ViewPanArgs { pane, dx, dy })
755 }
756
757 pub fn zoom(&self, pane: Option<PaneId>, factor: f64) -> HostResult<()> {
759 self.command(
760 methods::VIEW_ZOOM,
761 &ViewZoomArgs {
762 pane,
763 factor,
764 anchor_x: None,
765 anchor_y: None,
766 animate: false,
767 },
768 )
769 }
770
771 pub fn fit(&self, pane: Option<PaneId>) -> HostResult<()> {
772 self.command(methods::VIEW_FIT, &PaneArgs { pane })
773 }
774
775 pub fn set_view_orientation(
779 &self,
780 pane: Option<PaneId>,
781 rotation_deg: f64,
782 flipped: bool,
783 ) -> HostResult<()> {
784 self.command(
785 methods::VIEW_ORIENTATION,
786 &ViewOrientationArgs {
787 pane,
788 rotation_deg,
789 flipped,
790 },
791 )
792 }
793
794 pub fn display_adjustments(&self, pane: Option<PaneId>) -> HostResult<DisplayAdjustments> {
797 self.call(methods::VIEW_DISPLAY, &PaneArgs { pane })
798 }
799
800 pub fn frame(&self, pane: Option<PaneId>, rect: Rect) -> HostResult<()> {
802 self.command(
803 methods::VIEW_FRAME,
804 &ViewFrameArgs {
805 pane,
806 rect,
807 padding: None,
808 },
809 )
810 }
811
812 pub fn cycle_pane(&self, offset: i32) -> HostResult<()> {
813 self.command(methods::APP_CYCLE_PANE, &OffsetArgs { offset })
814 }
815
816 pub fn cycle_tab(&self, offset: i32) -> HostResult<()> {
817 self.command(methods::APP_CYCLE_TAB, &OffsetArgs { offset })
818 }
819
820 pub fn series(&self, action: SeriesAction) -> HostResult<()> {
821 self.command(methods::APP_SERIES, &SeriesArgs { action })
822 }
823
824 pub fn request_render(&self) -> HostResult<()> {
827 self.command(methods::RENDER_REQUEST, &Map::new())
828 }
829
830 pub fn push_undo(
835 &self,
836 entry_id: impl Into<String>,
837 file_id: Option<FileId>,
838 label: impl Into<String>,
839 ) -> HostResult<()> {
840 self.command(
841 methods::UNDO_PUSH,
842 &UndoPushArgs {
843 entry_id: entry_id.into(),
844 file_id,
845 label: label.into(),
846 },
847 )
848 }
849
850 pub fn clear_undo(&self, file_id: Option<FileId>) -> HostResult<()> {
852 self.command(methods::UNDO_CLEAR, &UndoClearArgs { file_id })
853 }
854
855 pub fn register_filter(&self, spec: FilterSpec) -> HostResult<()> {
858 self.command(methods::FILTER_REGISTER, &spec)
859 }
860
861 pub fn set_filter_enabled(&self, filter_id: &str, enabled: bool) -> HostResult<()> {
862 self.command(
863 methods::FILTER_SET_ENABLED,
864 &FilterEnableArgs {
865 filter_id: filter_id.into(),
866 enabled,
867 },
868 )
869 }
870
871 pub fn unregister_filter(&self, filter_id: &str) -> HostResult<()> {
872 self.command(
873 methods::FILTER_UNREGISTER,
874 &IdArgs {
875 id: filter_id.into(),
876 },
877 )
878 }
879
880 pub fn setting<T: DeserializeOwned>(&self, key: &str) -> HostResult<Option<T>> {
884 let value: Value = self.call(methods::SETTINGS_GET, &KeyArgs { key: key.into() })?;
885 if value.is_null() {
886 return Ok(None);
887 }
888 serde_json::from_value(value)
889 .map(Some)
890 .map_err(|e| HostError::new(FfiErrorKind::Failed, format!("setting '{key}': {e}")))
891 }
892
893 pub fn set_setting<T: Serialize + ?Sized>(&self, key: &str, value: &T) -> HostResult<()> {
895 let value = serde_json::to_value(value)
896 .map_err(|e| HostError::new(FfiErrorKind::InvalidArguments, e.to_string()))?;
897 self.command(
898 methods::SETTINGS_SET,
899 &SettingsSetArgs {
900 key: key.into(),
901 value,
902 },
903 )
904 }
905
906 pub fn remove_setting(&self, key: &str) -> HostResult<()> {
907 self.command(
908 methods::SETTINGS_SET,
909 &SettingsSetArgs {
910 key: key.into(),
911 value: Value::Null,
912 },
913 )
914 }
915
916 pub fn start_job(&self, title: impl Into<String>, cancellable: bool) -> HostResult<Job> {
920 let started: JobStarted = self.call(
921 methods::JOB_START,
922 &JobStartArgs {
923 title: title.into(),
924 cancellable,
925 },
926 )?;
927 Ok(Job {
928 host: self.clone(),
929 job_id: started.job_id,
930 finished: false,
931 })
932 }
933
934 pub fn copy_text(&self, text: impl Into<String>) -> HostResult<()> {
937 self.command(methods::CLIPBOARD_SET_TEXT, &TextArgs { text: text.into() })
938 }
939
940 pub fn post(&self, token: impl Into<String>) -> HostResult<()> {
943 self.command(
944 methods::POST,
945 &PostArgs {
946 token: token.into(),
947 },
948 )
949 }
950
951 pub fn subscribe(&self, events: &[&str]) -> HostResult<()> {
954 self.command(
955 methods::EVENTS_SUBSCRIBE,
956 &SubscribeArgs {
957 events: events.iter().map(|e| e.to_string()).collect(),
958 },
959 )
960 }
961}
962
963#[derive(Clone)]
965pub struct Layer {
966 host: Host,
967 layer_id: String,
968}
969
970impl Layer {
971 pub fn id(&self) -> &str {
972 &self.layer_id
973 }
974
975 pub fn upsert(&self, objects: Vec<OverlayObject>) -> HostResult<()> {
977 self.host.command(
978 methods::LAYER_UPSERT,
979 &UpsertObjectsArgs {
980 layer_id: self.layer_id.clone(),
981 objects,
982 replace_all: false,
983 },
984 )
985 }
986
987 pub fn replace_all(&self, objects: Vec<OverlayObject>) -> HostResult<()> {
989 self.host.command(
990 methods::LAYER_UPSERT,
991 &UpsertObjectsArgs {
992 layer_id: self.layer_id.clone(),
993 objects,
994 replace_all: true,
995 },
996 )
997 }
998
999 pub fn remove(&self, object_ids: Vec<String>) -> HostResult<()> {
1000 self.host.command(
1001 methods::LAYER_REMOVE_OBJECTS,
1002 &RemoveObjectsArgs {
1003 layer_id: self.layer_id.clone(),
1004 object_ids,
1005 },
1006 )
1007 }
1008
1009 pub fn clear(&self) -> HostResult<()> {
1010 self.host.command(
1011 methods::LAYER_CLEAR,
1012 &IdArgs {
1013 id: self.layer_id.clone(),
1014 },
1015 )
1016 }
1017
1018 pub fn update(&self, mut update: LayerUpdate) -> HostResult<()> {
1020 update.layer_id = self.layer_id.clone();
1021 self.host.command(methods::LAYER_UPDATE, &update)
1022 }
1023
1024 pub fn set_visible(&self, visible: bool) -> HostResult<()> {
1025 self.update(LayerUpdate {
1026 visible: Some(visible),
1027 ..Default::default()
1028 })
1029 }
1030
1031 pub fn select(&self, object_ids: Vec<String>) -> HostResult<()> {
1033 self.host.command(
1034 methods::LAYER_SELECT,
1035 &SelectArgs {
1036 layer_id: self.layer_id.clone(),
1037 object_ids,
1038 },
1039 )
1040 }
1041
1042 pub fn put_raster(
1044 &self,
1045 object_id: impl Into<String>,
1046 rect: Rect,
1047 image: Image,
1048 smooth: bool,
1049 ) -> HostResult<()> {
1050 from_ffi(self.host.ffi.put_raster(RasterUpload {
1051 layer_id: RString::from(self.layer_id.as_str()),
1052 object_id: RString::from(object_id.into()),
1053 x: rect.x,
1054 y: rect.y,
1055 width: rect.width,
1056 height: rect.height,
1057 pixels: image.into_pixels(),
1058 smooth,
1059 }))
1060 }
1061
1062 pub fn highlight(&self, object_ids: Vec<String>) -> HostResult<()> {
1065 self.host.command(
1066 methods::LAYER_HIGHLIGHT,
1067 &SelectArgs {
1068 layer_id: self.layer_id.clone(),
1069 object_ids,
1070 },
1071 )
1072 }
1073
1074 pub fn set_min_zoom(&self, min_zoom: Option<f64>) -> HostResult<()> {
1077 self.host.command(
1078 methods::LAYER_SET_MIN_ZOOM,
1079 &MinZoomArgs {
1080 layer_id: self.layer_id.clone(),
1081 min_zoom,
1082 },
1083 )
1084 }
1085
1086 pub fn set_panes(&self, panes: Option<Vec<PaneId>>) -> HostResult<()> {
1090 self.host.command(
1091 methods::LAYER_SET_PANES,
1092 &PaneFilterArgs {
1093 layer_id: self.layer_id.clone(),
1094 panes,
1095 },
1096 )
1097 }
1098
1099 pub fn set_visible_in_pane(&self, pane: PaneId, visible: bool) -> HostResult<()> {
1102 self.host.command(
1103 methods::LAYER_SET_PANE_VISIBILITY,
1104 &PaneVisibilityArgs {
1105 layer_id: self.layer_id.clone(),
1106 pane,
1107 visible,
1108 },
1109 )
1110 }
1111
1112 pub fn remove_layer(self) -> HostResult<()> {
1114 self.host.command(
1115 methods::LAYER_REMOVE,
1116 &IdArgs {
1117 id: self.layer_id.clone(),
1118 },
1119 )
1120 }
1121}
1122
1123#[derive(Clone)]
1125pub struct Surface {
1126 host: Host,
1127 surface_id: String,
1128}
1129
1130impl Surface {
1131 pub fn id(&self) -> &str {
1132 &self.surface_id
1133 }
1134
1135 pub fn set(&self, name: &str, value: impl Serialize) -> HostResult<()> {
1137 let value = serde_json::to_value(value)
1138 .map_err(|e| HostError::new(FfiErrorKind::InvalidArguments, e.to_string()))?;
1139 let mut properties = Map::new();
1140 properties.insert(name.to_string(), value);
1141 self.set_many(properties)
1142 }
1143
1144 pub fn set_many(&self, properties: Map<String, Value>) -> HostResult<()> {
1148 self.host.command(
1149 methods::SURFACE_SET,
1150 &SurfaceProperties {
1151 surface_id: self.surface_id.clone(),
1152 properties,
1153 },
1154 )
1155 }
1156
1157 pub fn is_open(&self) -> bool {
1158 self.host
1159 .call::<_, bool>(
1160 methods::SURFACE_IS_OPEN,
1161 &IdArgs {
1162 id: self.surface_id.clone(),
1163 },
1164 )
1165 .unwrap_or(false)
1166 }
1167
1168 pub fn close(&self) -> HostResult<()> {
1169 self.host.command(
1170 methods::SURFACE_CLOSE,
1171 &IdArgs {
1172 id: self.surface_id.clone(),
1173 },
1174 )
1175 }
1176}
1177
1178pub struct Job {
1181 host: Host,
1182 job_id: String,
1183 finished: bool,
1184}
1185
1186impl Job {
1187 pub fn id(&self) -> &str {
1188 &self.job_id
1189 }
1190
1191 pub fn update(&self, fraction: Option<f32>, message: Option<&str>) {
1193 let _ = self.host.command(
1194 methods::JOB_UPDATE,
1195 &JobUpdateArgs {
1196 job_id: self.job_id.clone(),
1197 fraction: fraction.map(|f| f.clamp(0.0, 1.0)),
1198 message: message.map(str::to_string),
1199 },
1200 );
1201 }
1202
1203 pub fn finish(mut self, error: Option<String>) {
1205 self.finish_inner(error);
1206 }
1207
1208 fn finish_inner(&mut self, error: Option<String>) {
1209 if self.finished {
1210 return;
1211 }
1212 self.finished = true;
1213 let _ = self.host.command(
1214 methods::JOB_FINISH,
1215 &JobFinishArgs {
1216 job_id: self.job_id.clone(),
1217 error,
1218 },
1219 );
1220 }
1221}
1222
1223impl Drop for Job {
1224 fn drop(&mut self) {
1225 self.finish_inner(None);
1226 }
1227}
1228
1229fn panic_message(payload: &(dyn Any + Send)) -> String {
1234 if let Some(text) = payload.downcast_ref::<&str>() {
1235 (*text).to_string()
1236 } else if let Some(text) = payload.downcast_ref::<String>() {
1237 text.clone()
1238 } else {
1239 "unknown panic payload".to_string()
1240 }
1241}
1242
1243fn guarded<T>(f: impl FnOnce() -> Result<T, FfiError>) -> FfiResult<T> {
1245 match catch_unwind(AssertUnwindSafe(f)) {
1246 Ok(Ok(value)) => ROk(value),
1247 Ok(Err(error)) => RErr(error),
1248 Err(payload) => RErr(FfiError::new(
1249 FfiErrorKind::Panicked,
1250 format!("plugin panicked: {}", panic_message(payload.as_ref())),
1251 )),
1252 }
1253}
1254
1255#[doc(hidden)]
1256pub struct Adapter<P: Plugin> {
1257 plugin: Arc<P>,
1259}
1260
1261impl<P: Plugin> Adapter<P> {
1262 fn dispatch(&self, event_json: &str) -> Result<String, FfiError> {
1263 let event: HostEvent = serde_json::from_str(event_json).map_err(|e| {
1264 FfiError::new(FfiErrorKind::InvalidArguments, format!("bad event: {e}"))
1265 })?;
1266 match event {
1267 HostEvent::ContextMenuRequested(context) => {
1268 let items = self.plugin.context_menu(&context);
1269 to_json(&ContextMenuResponse { items })
1270 }
1271 HostEvent::UiCallback {
1272 surface_id,
1273 name,
1274 args,
1275 } => {
1276 let value = self
1277 .plugin
1278 .ui_callback(&surface_id, &name, &args)
1279 .map_err(FfiError::failed)?;
1280 to_json(&value)
1281 }
1282 HostEvent::Unknown => Err(FfiError::new(
1283 FfiErrorKind::Unsupported,
1284 "event not supported by this plugin version",
1285 )),
1286 other => self
1287 .plugin
1288 .on_event(other)
1289 .map(|()| "null".to_string())
1290 .map_err(FfiError::failed),
1291 }
1292 }
1293}
1294
1295fn to_json<T: Serialize>(value: &T) -> Result<String, FfiError> {
1296 serde_json::to_string(value).map_err(|e| FfiError::failed(e.to_string()))
1297}
1298
1299impl<P: Plugin> PluginFfi for Adapter<P> {
1300 fn handle_event(&self, event_json: RStr<'_>) -> FfiResult<RString> {
1301 guarded(|| self.dispatch(event_json.as_str()).map(RString::from))
1302 }
1303
1304 fn apply_filter(&self, filter_id: RStr<'_>, frame: FilterFrame<'_>) -> FfiResult<()> {
1305 guarded(|| {
1306 let FilterFrame {
1307 pixels,
1308 width,
1309 height,
1310 stride,
1311 view,
1312 } = frame;
1313 let mut frame = Frame::new(
1314 pixels.into_mut_slice(),
1315 width,
1316 height,
1317 stride as usize,
1318 view,
1319 )
1320 .ok_or_else(|| {
1321 FfiError::new(
1322 FfiErrorKind::InvalidArguments,
1323 format!("frame buffer too small for {width}x{height} (stride {stride})"),
1324 )
1325 })?;
1326 self.plugin
1327 .apply_filter(filter_id.as_str(), &mut frame)
1328 .map_err(FfiError::failed)
1329 })
1330 }
1331
1332 fn shutdown(&self) {
1333 let _ = catch_unwind(AssertUnwindSafe(|| self.plugin.shutdown()));
1334 }
1335}
1336
1337#[doc(hidden)]
1341pub fn into_plugin_box<P: Plugin>(plugin: P) -> PluginBox {
1342 PluginFfi_TO::from_value(
1343 Adapter {
1344 plugin: Arc::new(plugin),
1345 },
1346 TD_CanDowncast,
1347 )
1348}
1349
1350extern "C" fn slide_source<P: Plugin>(instance: &PluginBox) -> FfiResult<SlideSourceBox> {
1353 slide_source_of::<P>(instance)
1354}
1355
1356#[doc(hidden)]
1358pub fn slide_source_of<P: Plugin>(instance: &PluginBox) -> FfiResult<SlideSourceBox> {
1359 guarded(|| {
1360 let adapter = instance
1361 .obj
1362 .downcast_as::<Adapter<P>>()
1363 .map_err(|_| FfiError::failed("the instance was not created by this plugin library"))?;
1364 Ok(SlideSourceFfi_TO::from_value(
1365 SourceAdapter {
1366 plugin: Arc::clone(&adapter.plugin),
1367 },
1368 TD_Opaque,
1369 ))
1370 })
1371}
1372
1373struct SourceAdapter<P: Plugin> {
1374 plugin: Arc<P>,
1375}
1376
1377impl<P: Plugin> SlideSourceFfi for SourceAdapter<P> {
1378 fn open(&self, request_json: RStr<'_>) -> FfiResult<SlideBox> {
1379 guarded(|| {
1380 let request: SlideOpenRequest =
1381 serde_json::from_str(request_json.as_str()).map_err(|e| {
1382 FfiError::new(FfiErrorKind::InvalidArguments, format!("bad request: {e}"))
1383 })?;
1384 let reader = self.plugin.open_slide(&request).map_err(FfiError::failed)?;
1385 Ok(SlideFfi_TO::from_value(SlideAdapter { reader }, TD_Opaque))
1386 })
1387 }
1388}
1389
1390struct SlideAdapter {
1391 reader: Box<dyn SlideReader>,
1392}
1393
1394impl SlideFfi for SlideAdapter {
1395 fn info(&self) -> FfiResult<RString> {
1396 guarded(|| to_json(&self.reader.info()).map(RString::from))
1397 }
1398
1399 fn read_region(&self, region: SlideRegion, out: RSliceMut<'_, u8>) -> FfiResult<()> {
1400 guarded(|| {
1401 let out = out.into_mut_slice();
1402 let expected = region.width as usize * region.height as usize * 4;
1403 if out.len() != expected {
1404 return Err(FfiError::new(
1405 FfiErrorKind::InvalidArguments,
1406 format!(
1407 "the buffer holds {} bytes; {}×{} RGBA needs {expected}",
1408 out.len(),
1409 region.width,
1410 region.height
1411 ),
1412 ));
1413 }
1414 self.reader
1415 .read_region(®ion, out)
1416 .map_err(FfiError::failed)
1417 })
1418 }
1419
1420 fn read_associated_image(&self, name: RStr<'_>) -> FfiResult<Pixels> {
1421 guarded(|| {
1422 let image = self
1423 .reader
1424 .read_associated_image(name.as_str())
1425 .map_err(FfiError::failed)?;
1426 Ok(Pixels {
1427 width: image.width,
1428 height: image.height,
1429 data: image.data.into(),
1430 })
1431 })
1432 }
1433
1434 fn call(&self, method: RStr<'_>, _args_json: RStr<'_>) -> FfiResult<RString> {
1435 RErr(FfiError::new(
1436 FfiErrorKind::Unsupported,
1437 format!("the slide has no method '{}'", method.as_str()),
1438 ))
1439 }
1440}
1441
1442#[doc(hidden)]
1444pub fn create_plugin<P: Plugin>(host: HostBox, init_json: &str) -> Result<PluginBox, FfiError> {
1445 guarded(|| {
1446 let init: PluginInit = serde_json::from_str(init_json)
1447 .map_err(|e| FfiError::new(FfiErrorKind::InvalidArguments, format!("bad init: {e}")))?;
1448 let plugin = P::create(Host::from_ffi(host), init).map_err(FfiError::failed)?;
1449 Ok(into_plugin_box(plugin))
1450 })
1451 .into_result()
1452}
1453
1454extern "C" fn create_instance<P: Plugin>(
1455 host: HostBox,
1456 init_json: RStr<'_>,
1457) -> FfiResult<PluginBox> {
1458 create_plugin::<P>(host, init_json.as_str()).into()
1459}
1460
1461#[doc(hidden)]
1463pub fn root_module<P: Plugin>() -> PluginModuleRef {
1464 PluginModule {
1465 abi_version: abi::ABI_VERSION,
1466 api_version: RStr::from_str(abi::API_VERSION),
1467 create: create_instance::<P>,
1468 slide_source: slide_source::<P>,
1469 }
1470 .leak_into_prefix()
1471}
1472
1473#[macro_export]
1477macro_rules! export_plugin {
1478 ($plugin:ty) => {
1479 #[doc(hidden)]
1480 #[unsafe(no_mangle)]
1481 #[allow(non_upper_case_globals)]
1482 pub static _1as_0lib_1header_0root_bmodule_bloader: $crate::__private::LibHeader = {
1483 extern "C" fn __eov_erased_root_module() -> $crate::__private::RootModuleResult {
1484 fn __eov_root_module() -> $crate::abi::PluginModuleRef {
1485 $crate::sdk::root_module::<$plugin>()
1486 }
1487 $crate::__private::call_root_module_loader(__eov_root_module)
1488 }
1489 unsafe {
1490 $crate::__private::LibHeader::from_constructor::<$crate::abi::PluginModuleRef>(
1491 __eov_erased_root_module,
1492 $crate::__private::CheckTypeLayout::Yes,
1493 )
1494 }
1495 };
1496 };
1497}