Skip to main content

kitchen_contract/
catalog.rs

1//! Every op an app offers, by id: its own, the shared ones, its tools', and the script ops and
2//! recipes in its folders ([standard §2.2](../../../standard/spec/02-ops.md)). Another app's ops
3//! are not in it. The Operations menu, the search, the pipeline check and the runtime's `ops` call
4//! read it; it holds descriptions only (the runtime holds what runs).
5
6use std::collections::BTreeMap;
7
8use crate::ops::{OpSource, OpSpec};
9use crate::types::Type;
10
11/// The operations an app offers, and the port types it declares.
12#[derive(Clone, Debug, Default)]
13pub struct Catalog {
14    specs: BTreeMap<String, OpSpec>,
15    types: Vec<Type>,
16}
17
18impl Catalog {
19    /// An empty catalog for an app whose data flows as `types`.
20    pub fn new(types: impl IntoIterator<Item = Type>) -> Self {
21        Self { specs: BTreeMap::new(), types: types.into_iter().collect() }
22    }
23
24    /// The port types the app declares.
25    pub fn types(&self) -> &[Type] {
26        &self.types
27    }
28
29    /// Whether `ty` is one of the app's types (or `any`).
30    pub fn knows(&self, ty: &Type) -> bool {
31        ty.as_str() == Type::ANY || self.types.contains(ty)
32    }
33
34    /// Adds `spec` (replacing one with its id), after checking it is well formed and names only
35    /// the app's types.
36    pub fn add(&mut self, spec: OpSpec) -> Result<(), String> {
37        spec.check()?;
38        if let Some(p) = spec.inputs.iter().chain(&spec.outputs).find(|p| !self.knows(&p.ty)) {
39            let known: Vec<&str> = self.types.iter().map(Type::as_str).collect();
40            return Err(format!("{}: port {} has type {}, not one of {}", spec.id, p.name, p.ty, known.join(", ")));
41        }
42        self.specs.insert(spec.id.clone(), spec);
43        Ok(())
44    }
45
46    /// Takes the operation `id` out; whether it was there.
47    pub fn remove(&mut self, id: &str) -> bool {
48        self.specs.remove(id).is_some()
49    }
50
51    /// The operation `id`.
52    pub fn get(&self, id: &str) -> Option<&OpSpec> {
53        self.specs.get(id)
54    }
55
56    /// Every operation, by id.
57    pub fn all(&self) -> impl Iterator<Item = &OpSpec> {
58        self.specs.values()
59    }
60
61    /// How many operations.
62    pub fn len(&self) -> usize {
63        self.specs.len()
64    }
65
66    /// Whether it has none.
67    pub fn is_empty(&self) -> bool {
68        self.specs.is_empty()
69    }
70
71    /// The operations by family, families and operations by name (the Operations menu). Scripts
72    /// without a family go under "Scripts", tools' under their tool's name.
73    pub fn by_family(&self) -> Vec<(String, Vec<&OpSpec>)> {
74        let mut out: BTreeMap<String, Vec<&OpSpec>> = BTreeMap::new();
75        for s in self.specs.values() {
76            let family = if !s.family.is_empty() {
77                s.family.clone()
78            } else {
79                match &s.source {
80                    OpSource::Builtin => "Other".into(),
81                    OpSource::Script { .. } => "Scripts".into(),
82                    OpSource::Tool { tool, .. } => tool.clone(),
83                    OpSource::Recipe { .. } => "Recipes".into(),
84                }
85            };
86            out.entry(family).or_default().push(s);
87        }
88        let mut out: Vec<(String, Vec<&OpSpec>)> = out.into_iter().collect();
89        for (_, ops) in &mut out {
90            ops.sort_by_key(|o| o.title.to_lowercase());
91        }
92        out
93    }
94
95    /// The operations that take an input of type `ty` (what can follow a node's output).
96    pub fn taking(&self, ty: &Type) -> Vec<&OpSpec> {
97        self.specs.values().filter(|s| s.inputs.iter().any(|p| ty.feeds(&p.ty))).collect()
98    }
99
100    /// The ops a screen's offers can run: every required input filled by one of `offers` (the
101    /// runtime's `ops` with `fillable_by`, [standard §6.1](../../../standard/spec/06-runtime-api.md)).
102    pub fn fillable_by(&self, offers: &[Type]) -> Vec<&OpSpec> {
103        self.specs
104            .values()
105            .filter(|s| s.inputs.iter().filter(|p| !p.optional).all(|p| offers.iter().any(|o| o.feeds(&p.ty))))
106            .collect()
107    }
108
109    /// The operations whose title, id, family or line contains every word of `query` (case
110    /// ignored).
111    pub fn search(&self, query: &str) -> Vec<&OpSpec> {
112        let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
113        self.specs
114            .values()
115            .filter(|s| {
116                let text = format!("{} {} {} {}", s.title, s.id, s.family, s.summary).to_lowercase();
117                words.iter().all(|w| text.contains(w))
118            })
119            .collect()
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use crate::ops::PortSpec;
127    use crate::params::ParamSpec;
128
129    fn catalog() -> Catalog {
130        let mut c = Catalog::new(["image", "mask", "table"].map(Type::new));
131        c.add(
132            OpSpec::new("blur", "Gaussian blur")
133                .family("Filter")
134                .input(PortSpec::new("image", "image"))
135                .output(PortSpec::new("image", "image"))
136                .param(ParamSpec::number("sigma", 2.0)),
137        )
138        .unwrap();
139        c.add(
140            OpSpec::new("otsu", "Otsu threshold")
141                .family("Threshold")
142                .input(PortSpec::new("image", "image"))
143                .output(PortSpec::new("mask", "mask")),
144        )
145        .unwrap();
146        c.add(
147            OpSpec::new("count", "Count objects")
148                .summary("Counts the objects of a mask")
149                .input(PortSpec::new("mask", "mask"))
150                .output(PortSpec::new("counts", "table")),
151        )
152        .unwrap();
153        c
154    }
155
156    #[test]
157    fn refuses_unknown_types() {
158        let mut c = catalog();
159        let err = c
160            .add(
161                OpSpec::new("hp", "High-pass").input(PortSpec::new("x", "signal")).output(PortSpec::new("x", "signal")),
162            )
163            .unwrap_err();
164        assert!(err.contains("signal") && err.contains("image, mask, table"), "{err}");
165        assert_eq!(c.len(), 3);
166    }
167
168    #[test]
169    fn groups_finds_and_follows() {
170        let c = catalog();
171        let grouped = c.by_family();
172        let families: Vec<&str> = grouped.iter().map(|(f, _)| f.as_str()).collect();
173        assert_eq!(families, ["Filter", "Other", "Threshold"]);
174        let after_mask: Vec<&str> = c.taking(&Type::new("mask")).iter().map(|s| s.id.as_str()).collect();
175        assert_eq!(after_mask, ["count"]);
176        assert_eq!(c.search("objects COUNT").len(), 1);
177        assert_eq!(c.search("thresh").first().map(|s| s.id.as_str()), Some("otsu"));
178    }
179
180    #[test]
181    fn a_screen_lists_the_ops_its_offers_can_run() {
182        let c = catalog();
183        let fill = |offers: &[&str]| -> Vec<String> {
184            c.fillable_by(&offers.iter().map(Type::new).collect::<Vec<_>>()).iter().map(|s| s.id.clone()).collect()
185        };
186        assert_eq!(fill(&["image"]), ["blur", "otsu"]);
187        assert_eq!(fill(&["mask"]), ["count"]);
188        assert!(fill(&["table"]).is_empty());
189    }
190}