Skip to main content

eov_plugin_api/
testing.rs

1//! Unit-test support for plugins: run a [`Plugin`] against an in-memory
2//! mock host.
3//!
4//! ```
5//! use eov_plugin_api::prelude::*;
6//! use eov_plugin_api::testing::TestHarness;
7//!
8//! struct Counter {
9//!     host: Host,
10//! }
11//!
12//! impl Plugin for Counter {
13//!     fn create(host: Host, _init: PluginInit) -> Result<Self, String> {
14//!         Ok(Self { host })
15//!     }
16//!
17//!     fn on_event(&self, event: HostEvent) -> Result<(), String> {
18//!         if let HostEvent::FileOpened { file } = event {
19//!             self.host.info(format!("opened {}", file.filename));
20//!         }
21//!         Ok(())
22//!     }
23//! }
24//!
25//! let harness = TestHarness::<Counter>::new().unwrap();
26//! harness
27//!     .send(HostEvent::FileOpened {
28//!         file: FileInfo {
29//!             file_id: 1,
30//!             filename: "a.svs".into(),
31//!             ..Default::default()
32//!         },
33//!     })
34//!     .unwrap();
35//! assert_eq!(harness.calls_to("log").len(), 1);
36//! ```
37//!
38//! The mock answers every method the real host knows with a plausible
39//! result, keeps layers, surfaces, settings and contributions in memory so
40//! tests can inspect them, and records every call.
41
42use crate::abi::{
43    FfiError, FfiErrorKind, FfiResult, FilterFrame, FilterView, HostFfi, HostFfi_TO, Pixels,
44    PluginBox, RasterUpload, RegionRequest,
45};
46use crate::protocol::{methods, *};
47use crate::sdk::{Image, Plugin, create_plugin, slide_source_of};
48use abi_stable::{
49    sabi_trait::TD_Opaque,
50    std_types::{RErr, ROk, RSliceMut, RStr, RString},
51};
52use serde::de::DeserializeOwned;
53use serde_json::{Map, Value, json};
54use std::collections::BTreeMap;
55use std::marker::PhantomData;
56use std::sync::atomic::{AtomicU64, Ordering};
57use std::sync::{Arc, Mutex, MutexGuard};
58
59/// One recorded host call.
60#[derive(Debug, Clone, PartialEq)]
61pub struct RecordedCall {
62    pub method: String,
63    pub args: Value,
64}
65
66/// A layer as the mock host stores it.
67#[derive(Debug, Clone, PartialEq)]
68pub struct MockLayer {
69    pub spec: LayerSpec,
70    pub objects: BTreeMap<String, OverlayObject>,
71    pub rasters: BTreeMap<String, RasterUpload>,
72    pub selection: Vec<String>,
73    /// Panes the plugin hid the layer in (`layer.set_pane_visibility`).
74    pub hidden_panes: std::collections::BTreeSet<PaneId>,
75    /// Objects drawn highlighted (`layer.highlight`).
76    pub highlighted: Vec<String>,
77    /// The only panes showing the layer (`layer.set_panes`).
78    pub only_panes: Option<Vec<PaneId>>,
79}
80
81/// A surface as the mock host stores it.
82#[derive(Debug, Clone, PartialEq)]
83pub struct MockSurface {
84    pub spec: SurfaceSpec,
85    pub properties: Map<String, Value>,
86    pub open: bool,
87}
88
89type RegionReader = dyn Fn(&RegionRequest) -> Result<Image, String> + Send + Sync;
90
91/// Everything the mock host knows. Tests may read and modify it freely.
92#[derive(Default)]
93pub struct MockState {
94    pub calls: Vec<RecordedCall>,
95    pub snapshot: HostSnapshot,
96    pub properties: BTreeMap<FileId, PropertyMap>,
97    pub settings: Map<String, Value>,
98    pub layers: BTreeMap<String, MockLayer>,
99    pub surfaces: BTreeMap<String, MockSurface>,
100    pub toolbar_buttons: BTreeMap<String, ToolbarButtonSpec>,
101    pub hud_buttons: BTreeMap<String, HudButtonSpec>,
102    pub tools: BTreeMap<String, ToolSpec>,
103    pub hotkeys: BTreeMap<String, HotkeySpec>,
104    /// Badges by id: (slide, text).
105    pub badges: BTreeMap<String, (Option<FileId>, String)>,
106    /// Batch commands registered, by id.
107    pub batch_commands: BTreeMap<String, BatchCommandSpec>,
108    /// `batch.progress` calls, in order.
109    pub batch_progress: Vec<BatchProgressArgs>,
110    /// `batch.finish` calls, in order.
111    pub batch_finished: Vec<BatchFinishArgs>,
112    pub active_tool: Option<String>,
113    pub filters: BTreeMap<String, FilterSpec>,
114    pub undo: Vec<UndoPushArgs>,
115    pub notifications: Vec<NotifyArgs>,
116    pub status: Option<String>,
117    pub clipboard: Option<String>,
118    pub roi: BTreeMap<FileId, Rect>,
119    pub measurements: Vec<MeasurementInfo>,
120    /// What `view.display` answers.
121    pub display: DisplayAdjustments,
122    pub posted: Vec<String>,
123    /// The model store: what `model.resolve` and `model.list` answer, by
124    /// the SHA-256 of the main file (lower case). See
125    /// [`MockState::add_model`].
126    pub models: BTreeMap<String, ModelRecord>,
127    /// `model.fetch` requests, in order, with the request id each was
128    /// answered with. Answer them with [`TestHarness::finish_model_fetch`]
129    /// or [`TestHarness::cancel_model_fetch`].
130    pub model_fetches: Vec<(String, ModelFetchArgs)>,
131    /// Serves `read_region`; without one a mid-grey opaque image is returned.
132    pub region_reader: Option<Box<RegionReader>>,
133    /// Methods that fail with [`FfiErrorKind::Unsupported`], to emulate an
134    /// older host.
135    pub unsupported: Vec<String>,
136}
137
138impl MockState {
139    /// Puts a model in the mock's model store.
140    pub fn add_model(&mut self, record: ModelRecord) {
141        self.models
142            .insert(record.sha256.to_ascii_lowercase(), record);
143    }
144
145    /// The arguments of every recorded call to `method`.
146    pub fn calls_to(&self, method: &str) -> Vec<Value> {
147        self.calls
148            .iter()
149            .filter(|call| call.method == method)
150            .map(|call| call.args.clone())
151            .collect()
152    }
153
154    /// Objects of a layer, in id order.
155    pub fn objects(&self, layer_id: &str) -> Vec<OverlayObject> {
156        self.layers
157            .get(layer_id)
158            .map(|layer| layer.objects.values().cloned().collect())
159            .unwrap_or_default()
160    }
161}
162
163/// The mock host object handed to the plugin.
164#[derive(Clone)]
165pub struct MockHost {
166    state: Arc<Mutex<MockState>>,
167    next_id: Arc<AtomicU64>,
168}
169
170impl Default for MockHost {
171    fn default() -> Self {
172        Self::new()
173    }
174}
175
176impl MockHost {
177    pub fn new() -> Self {
178        Self {
179            state: Arc::new(Mutex::new(MockState::default())),
180            next_id: Arc::new(AtomicU64::new(1)),
181        }
182    }
183
184    /// The shared state (poison-tolerant).
185    pub fn state(&self) -> MutexGuard<'_, MockState> {
186        self.state.lock().unwrap_or_else(|e| e.into_inner())
187    }
188
189    /// The FFI object to pass to a plugin.
190    pub fn to_ffi(&self) -> crate::abi::HostBox {
191        HostFfi_TO::from_value(self.clone(), TD_Opaque)
192    }
193
194    fn fresh_id(&self, prefix: &str) -> String {
195        format!("{prefix}-{}", self.next_id.fetch_add(1, Ordering::Relaxed))
196    }
197
198    fn handle(&self, method: &str, args: Value) -> Result<Value, FfiError> {
199        let mut state = self.state();
200        state.calls.push(RecordedCall {
201            method: method.to_string(),
202            args: args.clone(),
203        });
204        if state.unsupported.iter().any(|m| m == method) {
205            return Err(FfiError::new(
206                FfiErrorKind::Unsupported,
207                format!("unknown method '{method}'"),
208            ));
209        }
210        fn parse<T: DeserializeOwned>(args: Value) -> Result<T, FfiError> {
211            serde_json::from_value(args)
212                .map_err(|e| FfiError::new(FfiErrorKind::InvalidArguments, e.to_string()))
213        }
214        let null = Value::Null;
215        Ok(match method {
216            methods::LOG | methods::RENDER_REQUEST | methods::EVENTS_SUBSCRIBE => null,
217            methods::NOTIFY => {
218                let args: NotifyArgs = parse(args)?;
219                state.notifications.push(args);
220                null
221            }
222            methods::STATUS => {
223                let args: StatusArgs = parse(args)?;
224                state.status = args.text;
225                null
226            }
227            methods::SNAPSHOT => json!(state.snapshot),
228            methods::FILE_INFO => {
229                let args: FileArgs = parse(args)?;
230                let file =
231                    state.snapshot.file(args.file_id).cloned().ok_or_else(|| {
232                        FfiError::failed(format!("no open file {}", args.file_id))
233                    })?;
234                json!(file)
235            }
236            methods::FILE_PROPERTIES => {
237                let args: FileArgs = parse(args)?;
238                json!(
239                    state
240                        .properties
241                        .get(&args.file_id)
242                        .cloned()
243                        .unwrap_or_default()
244                )
245            }
246            methods::FILE_OPEN => null,
247            methods::TOOLBAR_ADD => {
248                let spec: ToolbarButtonSpec = parse(args)?;
249                state.toolbar_buttons.insert(spec.button_id.clone(), spec);
250                null
251            }
252            methods::TOOLBAR_UPDATE => {
253                let update: ButtonUpdate = parse(args)?;
254                let button = state
255                    .toolbar_buttons
256                    .get_mut(&update.button_id)
257                    .ok_or_else(|| FfiError::failed("unknown toolbar button"))?;
258                if let Some(active) = update.active {
259                    button.active = active;
260                }
261                if let Some(enabled) = update.enabled {
262                    button.enabled = enabled;
263                }
264                if let Some(tooltip) = update.tooltip {
265                    button.tooltip = tooltip;
266                }
267                if let Some(icon) = update.icon_svg {
268                    button.icon_svg = icon;
269                }
270                null
271            }
272            methods::TOOLBAR_REMOVE => {
273                let args: IdArgs = parse(args)?;
274                state.toolbar_buttons.remove(&args.id);
275                null
276            }
277            methods::HUD_ADD => {
278                let spec: HudButtonSpec = parse(args)?;
279                state.hud_buttons.insert(spec.button_id.clone(), spec);
280                null
281            }
282            methods::HUD_UPDATE => {
283                let update: ButtonUpdate = parse(args)?;
284                let button = state
285                    .hud_buttons
286                    .get_mut(&update.button_id)
287                    .ok_or_else(|| FfiError::failed("unknown HUD button"))?;
288                if let Some(active) = update.active {
289                    button.active = active;
290                }
291                if let Some(menu) = update.menu {
292                    button.menu = menu;
293                }
294                null
295            }
296            methods::HUD_REMOVE => {
297                let args: IdArgs = parse(args)?;
298                state.hud_buttons.remove(&args.id);
299                null
300            }
301            methods::BATCH_REGISTER => {
302                let spec: BatchCommandSpec = parse(args)?;
303                state.batch_commands.insert(spec.command_id.clone(), spec);
304                null
305            }
306            methods::BATCH_PROGRESS => {
307                state.batch_progress.push(parse(args)?);
308                null
309            }
310            methods::BATCH_FINISH => {
311                state.batch_finished.push(parse(args)?);
312                null
313            }
314            methods::BADGE_SET => {
315                let args: BadgeArgs = parse(args)?;
316                match args.text {
317                    Some(text) => {
318                        state.badges.insert(args.badge_id, (args.file_id, text));
319                    }
320                    None => {
321                        state.badges.remove(&args.badge_id);
322                    }
323                }
324                null
325            }
326            methods::HOTKEY_REGISTER => {
327                let spec: HotkeySpec = parse(args)?;
328                state.hotkeys.insert(spec.hotkey_id.clone(), spec);
329                null
330            }
331            methods::HOTKEY_UNREGISTER => {
332                let args: IdArgs = parse(args)?;
333                state.hotkeys.remove(&args.id);
334                null
335            }
336            methods::TOOL_REGISTER => {
337                let spec: ToolSpec = parse(args)?;
338                state.tools.insert(spec.tool_id.clone(), spec);
339                null
340            }
341            methods::TOOL_UNREGISTER => {
342                let args: IdArgs = parse(args)?;
343                state.tools.remove(&args.id);
344                if state.active_tool.as_deref() == Some(args.id.as_str()) {
345                    state.active_tool = None;
346                }
347                null
348            }
349            methods::TOOL_ACTIVATE => {
350                let args: IdArgs = parse(args)?;
351                if !state.tools.contains_key(&args.id) {
352                    return Err(FfiError::failed(format!("unknown tool '{}'", args.id)));
353                }
354                state.active_tool = Some(args.id);
355                null
356            }
357            methods::TOOL_DEACTIVATE => {
358                state.active_tool = None;
359                null
360            }
361            methods::LAYER_CREATE => {
362                let spec: LayerSpec = parse(args)?;
363                state.layers.insert(
364                    spec.layer_id.clone(),
365                    MockLayer {
366                        spec,
367                        objects: BTreeMap::new(),
368                        rasters: BTreeMap::new(),
369                        selection: Vec::new(),
370                        hidden_panes: Default::default(),
371                        highlighted: Vec::new(),
372                        only_panes: None,
373                    },
374                );
375                null
376            }
377            methods::LAYER_UPDATE => {
378                let update: LayerUpdate = parse(args)?;
379                let layer = layer_mut(&mut state, &update.layer_id)?;
380                if let Some(visible) = update.visible {
381                    layer.spec.visible = visible;
382                }
383                if let Some(opacity) = update.opacity {
384                    layer.spec.opacity = opacity;
385                }
386                if let Some(name) = update.name {
387                    layer.spec.name = name;
388                }
389                if let Some(z) = update.z {
390                    layer.spec.z = z;
391                }
392                if let Some(style) = update.style {
393                    layer.spec.style = style;
394                }
395                null
396            }
397            methods::LAYER_REMOVE => {
398                let args: IdArgs = parse(args)?;
399                state.layers.remove(&args.id);
400                null
401            }
402            methods::LAYER_HIGHLIGHT => {
403                let args: SelectArgs = parse(args)?;
404                layer_mut(&mut state, &args.layer_id)?.highlighted = args.object_ids;
405                null
406            }
407            methods::LAYER_SET_MIN_ZOOM => {
408                let args: MinZoomArgs = parse(args)?;
409                layer_mut(&mut state, &args.layer_id)?.spec.min_zoom = args.min_zoom;
410                null
411            }
412            methods::LAYER_SET_PANES => {
413                let args: PaneFilterArgs = parse(args)?;
414                layer_mut(&mut state, &args.layer_id)?.only_panes = args.panes;
415                null
416            }
417            methods::LAYER_SET_PANE_VISIBILITY => {
418                let args: PaneVisibilityArgs = parse(args)?;
419                let layer = layer_mut(&mut state, &args.layer_id)?;
420                if args.visible {
421                    layer.hidden_panes.remove(&args.pane);
422                } else {
423                    layer.hidden_panes.insert(args.pane);
424                }
425                null
426            }
427            methods::VIEW_DISPLAY => json!(state.display),
428            methods::LAYER_SELECT => {
429                let args: SelectArgs = parse(args)?;
430                layer_mut(&mut state, &args.layer_id)?.selection = args.object_ids;
431                null
432            }
433            methods::LAYER_UPSERT => {
434                let args: UpsertObjectsArgs = parse(args)?;
435                if let Some(bad) = args.objects.iter().find(|o| !o.shape.is_valid()) {
436                    return Err(FfiError::new(
437                        FfiErrorKind::InvalidArguments,
438                        format!("object '{}' has an invalid shape", bad.object_id),
439                    ));
440                }
441                let layer = layer_mut(&mut state, &args.layer_id)?;
442                if args.replace_all {
443                    layer.objects.clear();
444                    layer.rasters.clear();
445                }
446                for object in args.objects {
447                    layer.objects.insert(object.object_id.clone(), object);
448                }
449                null
450            }
451            methods::LAYER_REMOVE_OBJECTS => {
452                let args: RemoveObjectsArgs = parse(args)?;
453                let layer = layer_mut(&mut state, &args.layer_id)?;
454                for id in &args.object_ids {
455                    layer.objects.remove(id);
456                    layer.rasters.remove(id);
457                }
458                layer.selection.retain(|id| !args.object_ids.contains(id));
459                null
460            }
461            methods::LAYER_CLEAR => {
462                let args: IdArgs = parse(args)?;
463                let layer = layer_mut(&mut state, &args.id)?;
464                layer.objects.clear();
465                layer.rasters.clear();
466                layer.selection.clear();
467                null
468            }
469            methods::SURFACE_OPEN => {
470                let spec: SurfaceSpec = parse(args)?;
471                drop(state);
472                let surface_id = self.fresh_id("surface");
473                let mut state = self.state();
474                if spec.kind == SurfaceKind::Sidebar {
475                    // One sidebar at a time, as in the real host.
476                    for surface in state.surfaces.values_mut() {
477                        if surface.spec.kind == SurfaceKind::Sidebar {
478                            surface.open = false;
479                        }
480                    }
481                }
482                state.surfaces.insert(
483                    surface_id.clone(),
484                    MockSurface {
485                        properties: spec.properties.clone(),
486                        spec,
487                        open: true,
488                    },
489                );
490                json!(SurfaceOpened { surface_id })
491            }
492            methods::SURFACE_SET => {
493                let args: SurfaceProperties = parse(args)?;
494                let surface = state
495                    .surfaces
496                    .get_mut(&args.surface_id)
497                    .filter(|s| s.open)
498                    .ok_or_else(|| FfiError::failed("surface is not open"))?;
499                surface.properties.extend(args.properties);
500                null
501            }
502            methods::SURFACE_CLOSE => {
503                let args: IdArgs = parse(args)?;
504                if let Some(surface) = state.surfaces.get_mut(&args.id) {
505                    surface.open = false;
506                }
507                null
508            }
509            methods::SURFACE_IS_OPEN => {
510                let args: IdArgs = parse(args)?;
511                json!(state.surfaces.get(&args.id).is_some_and(|s| s.open))
512            }
513            methods::DIALOG_CONFIRM | methods::DIALOG_OPEN_FILE | methods::DIALOG_SAVE_FILE => {
514                drop(state);
515                json!(RequestId {
516                    request_id: self.fresh_id("request"),
517                })
518            }
519            methods::VIEW_SET
520            | methods::VIEW_PAN
521            | methods::VIEW_ZOOM
522            | methods::VIEW_FIT
523            | methods::VIEW_FRAME
524            | methods::VIEW_ORIENTATION
525            | methods::APP_CYCLE_PANE
526            | methods::APP_CYCLE_TAB
527            | methods::APP_SERIES => null,
528            methods::UNDO_PUSH => {
529                let args: UndoPushArgs = parse(args)?;
530                state.undo.push(args);
531                null
532            }
533            methods::UNDO_CLEAR => {
534                let args: UndoClearArgs = parse(args)?;
535                match args.file_id {
536                    Some(file_id) => state.undo.retain(|e| e.file_id != Some(file_id)),
537                    None => state.undo.clear(),
538                }
539                null
540            }
541            methods::FILTER_REGISTER => {
542                let spec: FilterSpec = parse(args)?;
543                state.filters.insert(spec.filter_id.clone(), spec);
544                null
545            }
546            methods::FILTER_SET_ENABLED => {
547                let args: FilterEnableArgs = parse(args)?;
548                state
549                    .filters
550                    .get_mut(&args.filter_id)
551                    .ok_or_else(|| FfiError::failed("unknown filter"))?
552                    .enabled = args.enabled;
553                null
554            }
555            methods::FILTER_UNREGISTER => {
556                let args: IdArgs = parse(args)?;
557                state.filters.remove(&args.id);
558                null
559            }
560            methods::SETTINGS_GET => {
561                let args: KeyArgs = parse(args)?;
562                state
563                    .settings
564                    .get(&args.key)
565                    .cloned()
566                    .unwrap_or(Value::Null)
567            }
568            methods::SETTINGS_SET => {
569                let args: SettingsSetArgs = parse(args)?;
570                if args.value.is_null() {
571                    state.settings.remove(&args.key);
572                } else {
573                    state.settings.insert(args.key, args.value);
574                }
575                null
576            }
577            methods::JOB_START => {
578                drop(state);
579                json!(JobStarted {
580                    job_id: self.fresh_id("job"),
581                })
582            }
583            methods::JOB_UPDATE | methods::JOB_FINISH => null,
584            methods::CLIPBOARD_SET_TEXT => {
585                let args: TextArgs = parse(args)?;
586                state.clipboard = Some(args.text);
587                null
588            }
589            methods::ROI_GET => {
590                let args: FileArgs = parse(args)?;
591                json!(state.roi.get(&args.file_id))
592            }
593            methods::MEASUREMENTS_LIST => {
594                let args: FileArgs = parse(args)?;
595                json!(
596                    state
597                        .measurements
598                        .iter()
599                        .filter(|m| m.file_id == args.file_id)
600                        .collect::<Vec<_>>()
601                )
602            }
603            methods::POST => {
604                let args: PostArgs = parse(args)?;
605                state.posted.push(args.token);
606                null
607            }
608            methods::MODEL_FETCH => {
609                let args: ModelFetchArgs = parse(args)?;
610                args.validate()
611                    .map_err(|e| FfiError::new(FfiErrorKind::InvalidArguments, e))?;
612                drop(state);
613                let request_id = self.fresh_id("model");
614                self.state().model_fetches.push((request_id.clone(), args));
615                json!(RequestId { request_id })
616            }
617            methods::MODEL_RESOLVE => {
618                let args: ModelResolveArgs = parse(args)?;
619                if !is_sha256_hex(&args.sha256) {
620                    return Err(FfiError::new(
621                        FfiErrorKind::InvalidArguments,
622                        "sha256 must be 64 hex digits",
623                    ));
624                }
625                json!(state.models.get(&args.sha256.to_ascii_lowercase()))
626            }
627            methods::MODEL_LIST => json!(state.models.values().collect::<Vec<_>>()),
628            other => {
629                return Err(FfiError::new(
630                    FfiErrorKind::Unsupported,
631                    format!("unknown method '{other}'"),
632                ));
633            }
634        })
635    }
636}
637
638fn layer_mut<'a>(state: &'a mut MockState, layer_id: &str) -> Result<&'a mut MockLayer, FfiError> {
639    state
640        .layers
641        .get_mut(layer_id)
642        .ok_or_else(|| FfiError::failed(format!("unknown layer '{layer_id}'")))
643}
644
645impl HostFfi for MockHost {
646    fn call(&self, method: RStr<'_>, args_json: RStr<'_>) -> FfiResult<RString> {
647        let args: Value = match serde_json::from_str(args_json.as_str()) {
648            Ok(args) => args,
649            Err(e) => {
650                return RErr(FfiError::new(FfiErrorKind::InvalidArguments, e.to_string()));
651            }
652        };
653        match self.handle(method.as_str(), args) {
654            Ok(value) => ROk(RString::from(value.to_string())),
655            Err(error) => RErr(error),
656        }
657    }
658
659    fn read_region(&self, request: RegionRequest) -> FfiResult<Pixels> {
660        let pixels = u64::from(request.width) * u64::from(request.height);
661        if pixels > crate::abi::MAX_REGION_PIXELS {
662            return RErr(FfiError::new(
663                FfiErrorKind::InvalidArguments,
664                "region too large",
665            ));
666        }
667        let state = self.state();
668        let image = match &state.region_reader {
669            Some(reader) => match reader(&request) {
670                Ok(image) => image,
671                Err(e) => return RErr(FfiError::failed(e)),
672            },
673            None => Image {
674                width: request.width,
675                height: request.height,
676                data: [128, 128, 128, 255].repeat(pixels as usize),
677            },
678        };
679        ROk(Pixels {
680            width: image.width,
681            height: image.height,
682            data: image.data.into(),
683        })
684    }
685
686    fn read_associated_image(&self, _file_id: i64, name: RStr<'_>) -> FfiResult<Pixels> {
687        RErr(FfiError::failed(format!(
688            "no associated image '{}'",
689            name.as_str()
690        )))
691    }
692
693    fn put_raster(&self, raster: RasterUpload) -> FfiResult<()> {
694        if !raster.pixels.is_well_formed() {
695            return RErr(FfiError::new(
696                FfiErrorKind::InvalidArguments,
697                "raster size does not match its data",
698            ));
699        }
700        let mut state = self.state();
701        let layer_id = raster.layer_id.to_string();
702        match layer_mut(&mut state, &layer_id) {
703            Ok(layer) => {
704                layer.rasters.insert(raster.object_id.to_string(), raster);
705                ROk(())
706            }
707            Err(e) => RErr(e),
708        }
709    }
710}
711
712/// Default init for tests: unique, writable temporary directories.
713pub fn test_init(plugin_id: &str) -> PluginInit {
714    static COUNTER: AtomicU64 = AtomicU64::new(0);
715    let root = std::env::temp_dir().join(format!(
716        "eov-plugin-test-{}-{}",
717        std::process::id(),
718        COUNTER.fetch_add(1, Ordering::Relaxed)
719    ));
720    let data_dir = root.join("data");
721    let cache_dir = root.join("cache");
722    let _ = std::fs::create_dir_all(&data_dir);
723    let _ = std::fs::create_dir_all(&cache_dir);
724    PluginInit {
725        plugin_id: plugin_id.to_string(),
726        plugin_version: "0.0.0".to_string(),
727        host_name: "eov".to_string(),
728        host_version: crate::abi::API_VERSION.to_string(),
729        api_version: crate::abi::API_VERSION.to_string(),
730        plugin_root: root.to_string_lossy().into_owned(),
731        data_dir: data_dir.to_string_lossy().into_owned(),
732        cache_dir: cache_dir.to_string_lossy().into_owned(),
733        settings: Map::new(),
734        legacy_config_dir: None,
735        headless: false,
736    }
737}
738
739/// Drives a plugin through the same FFI adapter the host uses.
740pub struct TestHarness<P: Plugin> {
741    host: MockHost,
742    instance: PluginBox,
743    _plugin: PhantomData<fn() -> P>,
744}
745
746impl<P: Plugin> TestHarness<P> {
747    pub fn new() -> Result<Self, String> {
748        Self::with_init(test_init("test_plugin"))
749    }
750
751    pub fn with_init(init: PluginInit) -> Result<Self, String> {
752        Self::with_host(MockHost::new(), init)
753    }
754
755    /// Uses a prepared mock (e.g. with a snapshot or region reader set).
756    pub fn with_host(host: MockHost, init: PluginInit) -> Result<Self, String> {
757        let init_json = serde_json::to_string(&init).map_err(|e| e.to_string())?;
758        let instance =
759            create_plugin::<P>(host.to_ffi(), &init_json).map_err(|e| e.message.into_string())?;
760        Ok(Self {
761            host,
762            instance,
763            _plugin: PhantomData,
764        })
765    }
766
767    pub fn host(&self) -> &MockHost {
768        &self.host
769    }
770
771    pub fn state(&self) -> MutexGuard<'_, MockState> {
772        self.host.state()
773    }
774
775    /// The arguments of every call to `method` so far.
776    pub fn calls_to(&self, method: &str) -> Vec<Value> {
777        self.state().calls_to(method)
778    }
779
780    /// Delivers an event; returns the plugin's JSON response.
781    pub fn send(&self, event: HostEvent) -> Result<Value, FfiError> {
782        let json = serde_json::to_string(&event).map_err(|e| FfiError::failed(e.to_string()))?;
783        let reply = self
784            .instance
785            .handle_event(RStr::from_str(&json))
786            .into_result()?;
787        serde_json::from_str(reply.as_str()).map_err(|e| FfiError::failed(e.to_string()))
788    }
789
790    /// Requests context-menu items.
791    pub fn context_menu(&self, context: MenuContext) -> Result<Vec<MenuItem>, FfiError> {
792        let reply = self.send(HostEvent::ContextMenuRequested(context))?;
793        let response: ContextMenuResponse =
794            serde_json::from_value(reply).map_err(|e| FfiError::failed(e.to_string()))?;
795        Ok(response.items)
796    }
797
798    /// Invokes a surface callback.
799    /// Opens a slide through the plugin's slide source as eov does, through
800    /// the FFI: what [`TestSlide`] returns is what eov would get.
801    pub fn open_slide(&self, request: &SlideOpenRequest) -> Result<TestSlide, FfiError> {
802        let source = slide_source_of::<P>(&self.instance).into_result()?;
803        let json = serde_json::to_string(request).map_err(|e| FfiError::failed(e.to_string()))?;
804        let slide = source.open(RStr::from_str(&json)).into_result()?;
805        Ok(TestSlide { slide })
806    }
807
808    pub fn ui_callback(
809        &self,
810        surface_id: &str,
811        name: &str,
812        args: Vec<Value>,
813    ) -> Result<Value, FfiError> {
814        self.send(HostEvent::UiCallback {
815            surface_id: surface_id.to_string(),
816            name: name.to_string(),
817            args,
818        })
819    }
820
821    /// The last `model.fetch` request: the request id it was answered with
822    /// and its arguments.
823    pub fn last_model_fetch(&self) -> Option<(String, ModelFetchArgs)> {
824        self.state().model_fetches.last().cloned()
825    }
826
827    /// Answers the `model.fetch` request `request_id` as eov does: with the
828    /// stored model (which then also goes into the mock's model store, so
829    /// `model.resolve` finds it) or with the error eov reported.
830    pub fn finish_model_fetch(
831        &self,
832        request_id: &str,
833        outcome: Result<ModelRecord, String>,
834    ) -> Result<Value, FfiError> {
835        let event = match outcome {
836            Ok(record) => {
837                self.state().add_model(record.clone());
838                HostEvent::ModelFetched {
839                    request_id: request_id.to_string(),
840                    path: Some(record.path.clone()),
841                    model: Some(record),
842                    error: None,
843                    cancelled: false,
844                }
845            }
846            Err(error) => HostEvent::ModelFetched {
847                request_id: request_id.to_string(),
848                path: None,
849                model: None,
850                error: Some(error),
851                cancelled: false,
852            },
853        };
854        self.send(event)
855    }
856
857    /// Answers `request_id` as eov does when the user declines or cancels
858    /// the download.
859    pub fn cancel_model_fetch(&self, request_id: &str) -> Result<Value, FfiError> {
860        self.send(HostEvent::ModelFetched {
861            request_id: request_id.to_string(),
862            path: None,
863            model: None,
864            error: Some("The download was cancelled.".to_string()),
865            cancelled: true,
866        })
867    }
868
869    /// Runs a filter over a tightly packed RGBA buffer.
870    pub fn apply_filter(
871        &self,
872        filter_id: &str,
873        pixels: &mut [u8],
874        width: u32,
875        height: u32,
876        view: FilterView,
877    ) -> Result<(), FfiError> {
878        self.instance
879            .apply_filter(
880                RStr::from_str(filter_id),
881                FilterFrame {
882                    pixels: RSliceMut::from_mut_slice(pixels),
883                    width,
884                    height,
885                    stride: width * 4,
886                    view,
887                },
888            )
889            .into_result()
890    }
891}
892
893impl<P: Plugin> Drop for TestHarness<P> {
894    fn drop(&mut self) {
895        self.instance.shutdown();
896    }
897}
898
899/// A slide opened with [`TestHarness::open_slide`].
900pub struct TestSlide {
901    slide: crate::abi::SlideBox,
902}
903
904impl TestSlide {
905    /// The slide's metadata, checked as eov checks it.
906    pub fn info(&self) -> Result<SlideInfo, String> {
907        let json = self
908            .slide
909            .info()
910            .into_result()
911            .map_err(|e| e.message.into_string())?;
912        let info: SlideInfo = serde_json::from_str(json.as_str()).map_err(|e| e.to_string())?;
913        info.validate()?;
914        Ok(info)
915    }
916
917    /// The RGBA pixels of `region`, read into a zeroed buffer as eov reads
918    /// them.
919    pub fn read_region(&self, region: crate::abi::SlideRegion) -> Result<Vec<u8>, FfiError> {
920        let mut out = vec![0u8; region.width as usize * region.height as usize * 4];
921        self.slide
922            .read_region(
923                region,
924                abi_stable::std_types::RSliceMut::from_mut_slice(&mut out),
925            )
926            .into_result()?;
927        Ok(out)
928    }
929}
930
931#[cfg(test)]
932mod tests {
933    use super::*;
934    use crate::sdk::{Frame, Host};
935
936    struct Probe {
937        host: Host,
938    }
939
940    impl Plugin for Probe {
941        fn create(host: Host, init: PluginInit) -> Result<Self, String> {
942            if init.plugin_id == "refuse" {
943                return Err("refused".into());
944            }
945            host.add_toolbar_button(ToolbarButtonSpec {
946                button_id: "go".into(),
947                tooltip: "Go".into(),
948                icon_svg: "<svg/>".into(),
949                ..Default::default()
950            })
951            .map_err(String::from)?;
952            Ok(Self { host })
953        }
954
955        fn on_event(&self, event: HostEvent) -> Result<(), String> {
956            match event {
957                HostEvent::ToolbarButtonClicked { button_id } if button_id == "panic" => {
958                    panic!("boom")
959                }
960                HostEvent::ToolbarButtonClicked { .. } => {
961                    let layer = self
962                        .host
963                        .create_layer(LayerSpec::new("cells", 1).named("Cells").interactive(true))
964                        .map_err(String::from)?;
965                    layer
966                        .upsert(vec![OverlayObject::new(
967                            "c1",
968                            Shape::Point { x: 1.0, y: 2.0 },
969                        )])
970                        .map_err(String::from)?;
971                    Ok(())
972                }
973                HostEvent::FileClosed { .. } => Err("cannot close".into()),
974                _ => Ok(()),
975            }
976        }
977
978        fn context_menu(&self, context: &MenuContext) -> Vec<MenuItem> {
979            vec![MenuItem {
980                item_id: format!("at-{}", context.image_x),
981                label: "Here".into(),
982                ..Default::default()
983            }]
984        }
985
986        fn ui_callback(&self, _surface: &str, name: &str, args: &[Value]) -> Result<Value, String> {
987            Ok(json!({ "name": name, "argc": args.len() }))
988        }
989
990        fn apply_filter(&self, _filter_id: &str, frame: &mut Frame<'_>) -> Result<(), String> {
991            frame.for_each_pixel(|_, _, px| px[0] = 255 - px[0]);
992            Ok(())
993        }
994    }
995
996    fn view() -> ViewInfo {
997        ViewInfo {
998            pane: 1,
999            file_id: 1,
1000            zoom: 1.0,
1001            ..Default::default()
1002        }
1003    }
1004
1005    #[test]
1006    fn layers_take_min_zoom_and_pane_visibility() {
1007        use crate::sdk::{Host, Image};
1008        let mock = MockHost::new();
1009        let host = Host::from_ffi(mock.to_ffi());
1010        host.create_layer(LayerSpec::new("heat", 1)).unwrap();
1011        let layer = host.layer("heat");
1012        layer.set_min_zoom(Some(0.25)).unwrap();
1013        layer.set_visible_in_pane(3, false).unwrap();
1014        let rect = Rect {
1015            x: 0.0,
1016            y: 0.0,
1017            width: 10.0,
1018            height: 10.0,
1019        };
1020        let blank = Image {
1021            width: 2,
1022            height: 2,
1023            data: vec![0; 16],
1024        };
1025        layer.put_raster("map", rect, blank, false).unwrap();
1026        let state = mock.state();
1027        let mock_layer = &state.layers["heat"];
1028        assert_eq!(mock_layer.spec.min_zoom, Some(0.25));
1029        assert!(mock_layer.hidden_panes.contains(&3));
1030        assert!(mock_layer.rasters.contains_key("map"));
1031        drop(state);
1032        assert_eq!(host.display_adjustments(None).unwrap().gamma, 1.0);
1033    }
1034
1035    #[test]
1036    fn hotkeys_badges_and_highlights_reach_the_host() {
1037        use crate::sdk::Host;
1038        let mock = MockHost::new();
1039        let host = Host::from_ffi(mock.to_ffi());
1040        host.register_hotkey(HotkeySpec {
1041            hotkey_id: "next".into(),
1042            hotkey: Hotkey::key("j"),
1043            description: "Next object".into(),
1044        })
1045        .unwrap();
1046        host.set_badge("predicted", Some(1), Some("Predicted"))
1047            .unwrap();
1048        host.create_layer(LayerSpec::new("cells", 1)).unwrap();
1049        host.layer("cells").highlight(vec!["a".into()]).unwrap();
1050        {
1051            let state = mock.state();
1052            assert!(state.hotkeys.contains_key("next"));
1053            assert_eq!(
1054                state.badges["predicted"],
1055                (Some(1), "Predicted".to_string())
1056            );
1057            assert_eq!(state.layers["cells"].highlighted, ["a"]);
1058        }
1059        host.set_badge("predicted", None, None).unwrap();
1060        host.unregister_hotkey("next").unwrap();
1061        let state = mock.state();
1062        assert!(state.badges.is_empty() && state.hotkeys.is_empty());
1063    }
1064
1065    #[test]
1066    fn create_registers_contributions() {
1067        let harness = TestHarness::<Probe>::new().unwrap();
1068        // Built with `..Default::default()`, it arrives enabled.
1069        assert!(harness.state().toolbar_buttons["go"].enabled);
1070    }
1071
1072    #[test]
1073    fn create_errors_are_reported() {
1074        let error = TestHarness::<Probe>::with_init(test_init("refuse"))
1075            .err()
1076            .unwrap();
1077        assert_eq!(error, "refused");
1078    }
1079
1080    #[test]
1081    fn events_reach_the_plugin_and_overlays_are_stored() {
1082        let harness = TestHarness::<Probe>::new().unwrap();
1083        harness
1084            .send(HostEvent::ToolbarButtonClicked {
1085                button_id: "go".into(),
1086            })
1087            .unwrap();
1088        let objects = harness.state().objects("cells");
1089        assert_eq!(objects.len(), 1);
1090        assert_eq!(objects[0].shape, Shape::Point { x: 1.0, y: 2.0 });
1091    }
1092
1093    #[test]
1094    fn panics_become_errors() {
1095        let harness = TestHarness::<Probe>::new().unwrap();
1096        let error = harness
1097            .send(HostEvent::ToolbarButtonClicked {
1098                button_id: "panic".into(),
1099            })
1100            .unwrap_err();
1101        assert_eq!(error.kind(), FfiErrorKind::Panicked);
1102        assert!(error.message.contains("boom"));
1103        // The instance is still usable afterwards.
1104        harness
1105            .send(HostEvent::Ready {
1106                restore_sidebar: false,
1107            })
1108            .unwrap();
1109    }
1110
1111    #[test]
1112    fn handler_errors_are_failures() {
1113        let harness = TestHarness::<Probe>::new().unwrap();
1114        let error = harness
1115            .send(HostEvent::FileClosed { file_id: 1 })
1116            .unwrap_err();
1117        assert_eq!(error.kind(), FfiErrorKind::Failed);
1118        assert_eq!(error.message.as_str(), "cannot close");
1119    }
1120
1121    #[test]
1122    fn context_menus_and_callbacks_return_values() {
1123        let harness = TestHarness::<Probe>::new().unwrap();
1124        let items = harness
1125            .context_menu(MenuContext {
1126                pane: 1,
1127                view: view(),
1128                image_x: 5.0,
1129                image_y: 6.0,
1130                hit: None,
1131                selection: Vec::new(),
1132            })
1133            .unwrap();
1134        assert_eq!(items[0].item_id, "at-5");
1135        assert!(items[0].enabled, "built with `..Default::default()`");
1136        let reply = harness
1137            .ui_callback("surface-1", "clicked", vec![json!(1), json!("x")])
1138            .unwrap();
1139        assert_eq!(reply, json!({ "name": "clicked", "argc": 2 }));
1140    }
1141
1142    #[test]
1143    fn filters_modify_frames_in_place() {
1144        let harness = TestHarness::<Probe>::new().unwrap();
1145        let mut pixels = vec![10, 20, 30, 255, 40, 50, 60, 255];
1146        harness
1147            .apply_filter("invert", &mut pixels, 2, 1, FilterView::default())
1148            .unwrap();
1149        assert_eq!(pixels, vec![245, 20, 30, 255, 215, 50, 60, 255]);
1150    }
1151
1152    #[test]
1153    fn short_frames_are_rejected() {
1154        let harness = TestHarness::<Probe>::new().unwrap();
1155        let mut pixels = vec![0u8; 7];
1156        let error = harness
1157            .apply_filter("invert", &mut pixels, 2, 1, FilterView::default())
1158            .unwrap_err();
1159        assert_eq!(error.kind(), FfiErrorKind::InvalidArguments);
1160    }
1161
1162    #[test]
1163    fn unknown_methods_are_unsupported() {
1164        let host = MockHost::new();
1165        let sdk_host = Host::from_ffi(host.to_ffi());
1166        let error = sdk_host
1167            .call::<_, Value>("does.not.exist", &json!({}))
1168            .unwrap_err();
1169        assert!(error.is_unsupported());
1170    }
1171
1172    #[test]
1173    fn invalid_shapes_are_rejected() {
1174        let host = MockHost::new();
1175        let sdk_host = Host::from_ffi(host.to_ffi());
1176        let layer = sdk_host.create_layer(LayerSpec::new("l", 1)).unwrap();
1177        let error = layer
1178            .upsert(vec![OverlayObject::new(
1179                "bad",
1180                Shape::Polyline {
1181                    points: vec![[0.0, f64::NAN]],
1182                },
1183            )])
1184            .unwrap_err();
1185        assert_eq!(error.kind, FfiErrorKind::InvalidArguments);
1186    }
1187
1188    #[test]
1189    fn settings_round_trip() {
1190        let host = MockHost::new();
1191        let sdk_host = Host::from_ffi(host.to_ffi());
1192        sdk_host.set_setting("threshold", &0.5).unwrap();
1193        assert_eq!(sdk_host.setting::<f64>("threshold").unwrap(), Some(0.5));
1194        sdk_host.remove_setting("threshold").unwrap();
1195        assert_eq!(sdk_host.setting::<f64>("threshold").unwrap(), None);
1196    }
1197
1198    const MODEL_SHA: &str = "70a8deef1f01716efbc87feb181ea398425d08b5e4984ad9d4ab2b83fd354f92";
1199
1200    /// Uses a stored model, or asks eov for it, on a toolbar click.
1201    struct ModelUser {
1202        host: Host,
1203        request: std::sync::Mutex<Option<String>>,
1204    }
1205
1206    impl Plugin for ModelUser {
1207        fn create(host: Host, _init: PluginInit) -> Result<Self, String> {
1208            Ok(Self {
1209                host,
1210                request: std::sync::Mutex::new(None),
1211            })
1212        }
1213
1214        fn on_event(&self, event: HostEvent) -> Result<(), String> {
1215            match event {
1216                HostEvent::ToolbarButtonClicked { .. } => {
1217                    if let Some(model) = self.host.resolve_model(MODEL_SHA).map_err(String::from)? {
1218                        self.host.info(format!("using {}", model.path));
1219                        return Ok(());
1220                    }
1221                    let request = self
1222                        .host
1223                        .fetch_model(ModelFetchArgs {
1224                            url: Some("https://models.example.org/m.onnx".into()),
1225                            sha256: MODEL_SHA.into(),
1226                            name: Some("Reference".into()),
1227                            companions: vec![ModelFileSpec {
1228                                sha256: "cd2735866bd69648eb17df97f196f266e6e2569f8c21fa1e9779fb7e3a233ef8"
1229                                    .into(),
1230                                file_name: Some("m.onnx.data".into()),
1231                                ..Default::default()
1232                            }],
1233                            ..Default::default()
1234                        })
1235                        .map_err(String::from)?;
1236                    *self.request.lock().unwrap() = Some(request);
1237                }
1238                HostEvent::ModelFetched {
1239                    request_id,
1240                    path,
1241                    error,
1242                    cancelled,
1243                    ..
1244                } if self.request.lock().unwrap().as_deref() == Some(request_id.as_str()) => {
1245                    match (path, error) {
1246                        (Some(path), _) => self.host.info(format!("using {path}")),
1247                        (None, _) if cancelled => self.host.info("not now"),
1248                        (None, error) => self.host.info(format!("failed: {error:?}")),
1249                    }
1250                }
1251                _ => {}
1252            }
1253            Ok(())
1254        }
1255    }
1256
1257    fn logged(harness: &TestHarness<ModelUser>) -> Vec<String> {
1258        harness
1259            .calls_to("log")
1260            .iter()
1261            .map(|args| args["message"].as_str().unwrap_or_default().to_string())
1262            .collect()
1263    }
1264
1265    #[test]
1266    fn models_are_fetched_once_and_then_resolved() {
1267        let harness = TestHarness::<ModelUser>::new().unwrap();
1268        let click = || {
1269            harness
1270                .send(HostEvent::ToolbarButtonClicked {
1271                    button_id: "x".into(),
1272                })
1273                .unwrap()
1274        };
1275        click();
1276        let (request, args) = harness.last_model_fetch().expect("the plugin asked");
1277        assert_eq!(args.sha256, MODEL_SHA);
1278        assert_eq!(args.companions.len(), 1);
1279        harness
1280            .finish_model_fetch(
1281                &request,
1282                Ok(ModelRecord {
1283                    sha256: MODEL_SHA.into(),
1284                    path: "/models/70a8/m.onnx".into(),
1285                    file_name: "m.onnx".into(),
1286                    size: 10,
1287                    ..Default::default()
1288                }),
1289            )
1290            .unwrap();
1291        assert_eq!(logged(&harness), ["using /models/70a8/m.onnx"]);
1292        // Stored now: the next click resolves it without a download.
1293        click();
1294        assert_eq!(harness.state().model_fetches.len(), 1);
1295        assert_eq!(logged(&harness).len(), 2);
1296        let listed = Host::from_ffi(harness.host().to_ffi()).models().unwrap();
1297        assert_eq!(listed.len(), 1);
1298    }
1299
1300    #[test]
1301    fn declined_and_failed_fetches_reach_the_plugin() {
1302        let harness = TestHarness::<ModelUser>::new().unwrap();
1303        let click = || {
1304            harness
1305                .send(HostEvent::ToolbarButtonClicked {
1306                    button_id: "x".into(),
1307                })
1308                .unwrap()
1309        };
1310        click();
1311        let (request, _) = harness.last_model_fetch().unwrap();
1312        harness.cancel_model_fetch(&request).unwrap();
1313        click();
1314        let (request, _) = harness.last_model_fetch().unwrap();
1315        harness
1316            .finish_model_fetch(&request, Err("SHA-256 mismatch".into()))
1317            .unwrap();
1318        assert_eq!(
1319            logged(&harness),
1320            ["not now", "failed: Some(\"SHA-256 mismatch\")"]
1321        );
1322        assert!(harness.state().models.is_empty());
1323    }
1324
1325    #[test]
1326    fn model_requests_are_checked_and_old_hosts_refuse_them() {
1327        let mock = MockHost::new();
1328        let host = Host::from_ffi(mock.to_ffi());
1329        let bad = host
1330            .fetch_model(ModelFetchArgs {
1331                sha256: "abc".into(),
1332                ..Default::default()
1333            })
1334            .unwrap_err();
1335        assert_eq!(bad.kind, FfiErrorKind::InvalidArguments);
1336        let nameless = host
1337            .fetch_model(ModelFetchArgs {
1338                sha256: MODEL_SHA.into(),
1339                companions: vec![ModelFileSpec {
1340                    sha256: MODEL_SHA.into(),
1341                    ..Default::default()
1342                }],
1343                ..Default::default()
1344            })
1345            .unwrap_err();
1346        assert!(nameless.message.contains("file_name"), "{nameless}");
1347        assert_eq!(host.resolve_model(MODEL_SHA).unwrap(), None);
1348        mock.state()
1349            .unsupported
1350            .push(methods::MODEL_FETCH.to_string());
1351        assert!(
1352            host.fetch_model(ModelFetchArgs {
1353                sha256: MODEL_SHA.into(),
1354                ..Default::default()
1355            })
1356            .unwrap_err()
1357            .is_unsupported()
1358        );
1359    }
1360}