Skip to main content

ocio_rs/transform/
group.rs

1use std::ffi::c_void;
2use std::ptr::NonNull;
3
4use super::{transform_from_raw_handle, Transform, TransformHandle};
5use crate::{
6    cstr_from_mut, cstr_to_opt_string, cstring, Config, ConstConfig, OcioError, Result,
7    TransformDirection,
8};
9use ocio_sys;
10
11/// An ordered list of transforms evaluated as one transform.
12///
13/// Group transforms are useful for composing generated or user-authored
14/// transform chains before asking a `Config` for a processor.
15/// Adding or replacing a child rejects direct and indirect cycles before
16/// mutation. Acyclic groups may share children; non-group children require no
17/// graph traversal. Group traversal occurs only while editing, not per pixel.
18pub struct GroupTransform {
19    pub(crate) handle: NonNull<c_void>,
20}
21
22impl GroupTransform {
23    /// Create an empty group transform.
24    pub fn create() -> Result<Self> {
25        crate::clear_last_error();
26        let handle = unsafe { ocio_sys::ocio_group_transform_create() };
27        crate::handle_result(handle).map(|handle| Self { handle })
28    }
29
30    /// Return the number of child transforms in the group.
31    pub fn num_transforms(&self) -> i32 {
32        unsafe { ocio_sys::ocio_group_transform_get_num_transforms(self.handle.as_ptr()) }
33    }
34
35    /// Append `child` to the end of the group.
36    pub fn append_transform(&self, child: &impl TransformHandle) -> Result<()> {
37        crate::clear_last_error();
38        unsafe {
39            ocio_sys::ocio_group_transform_append_transform(self.handle.as_ptr(), child.as_ptr());
40        }
41        crate::ocio_call_status()
42    }
43
44    /// Insert `child` at the beginning of the group.
45    pub fn prepend_transform(&self, child: &impl TransformHandle) -> Result<()> {
46        crate::clear_last_error();
47        unsafe {
48            ocio_sys::ocio_group_transform_prepend_transform(self.handle.as_ptr(), child.as_ptr());
49        }
50        crate::ocio_call_status()
51    }
52
53    /// Return the child transform at `index`, if present.
54    ///
55    /// The returned handle shares the native child rather than copying it.
56    /// Mutating it affects every group retaining that child. Replacing the
57    /// group's slot does not retarget an already returned handle.
58    pub fn transform(&self, index: i32) -> Option<Transform> {
59        self.try_transform(index).ok().flatten()
60    }
61
62    /// Return the shared native child while preserving OCIO query failures.
63    ///
64    /// This has the same sharing and mutation semantics as [`Self::transform`];
65    /// it does not copy the child transform.
66    pub fn try_transform(&self, index: i32) -> Result<Option<Transform>> {
67        crate::clear_last_error();
68        let handle =
69            unsafe { ocio_sys::ocio_group_transform_get_transform(self.handle.as_ptr(), index) };
70        crate::ocio_call_status()?;
71        Ok(transform_from_raw_handle(handle))
72    }
73
74    /// Replace a child in place, preserving the group's identity and metadata.
75    ///
76    /// The group retains the same native transform as `child`. Existing handles
77    /// to the previous child remain valid. An invalid index returns an error.
78    pub fn set_transform(&self, index: i32, child: &impl TransformHandle) -> Result<()> {
79        crate::clear_last_error();
80        unsafe {
81            ocio_sys::ocio_group_transform_set_transform(
82                self.handle.as_ptr(),
83                index,
84                child.as_ptr(),
85            );
86        }
87        crate::ocio_call_status()
88    }
89
90    #[deprecated(since = "0.2.0", note = "compat alias; prefer transform()")]
91    pub fn get_transform(&self, index: i32) -> Option<Transform> {
92        self.transform(index)
93    }
94
95    #[deprecated(since = "0.2.0", note = "compat alias; prefer transform()")]
96    pub fn get_transform_v1(&self, index: i32) -> Option<Transform> {
97        self.transform(index)
98    }
99
100    /// Return the transform direction used when this group is evaluated.
101    pub fn direction(&self) -> TransformDirection {
102        let dir = unsafe { ocio_sys::ocio_group_transform_get_direction(self.handle.as_ptr()) };
103        match dir {
104            1 => TransformDirection::Inverse,
105            _ => TransformDirection::Forward,
106        }
107    }
108
109    /// Set the transform direction used when this group is evaluated.
110    pub fn set_direction(&self, direction: TransformDirection) {
111        self.try_set_direction(direction)
112            .expect("failed to set group transform direction");
113    }
114
115    /// Set the transform direction and surface any OCIO validation error.
116    pub fn try_set_direction(&self, direction: TransformDirection) -> crate::Result<()> {
117        crate::clear_last_error();
118        unsafe {
119            ocio_sys::ocio_group_transform_set_direction(self.handle.as_ptr(), direction as i32);
120        }
121        crate::ocio_call_status()
122    }
123
124    /// Copy the group container and metadata using OCIO's native operation.
125    /// Child transforms remain shared with the original. Use
126    /// [`Self::create_deep_copy`] to independently copy the graph.
127    pub fn create_editable_copy(&self) -> Result<Self> {
128        crate::clear_last_error();
129        let handle = unsafe { ocio_sys::ocio_transform_create_editable_copy(self.handle.as_ptr()) };
130        crate::handle_result(handle).map(|handle| Self { handle })
131    }
132
133    /// Deep-copy the built-in transform graph while preserving sharing within
134    /// the copy. Group nodes are reconstructed as native OCIO groups; other
135    /// nodes use their native editable-copy method. Custom native subclasses
136    /// may have additional state or copy semantics not represented by this API.
137    /// Cycles and null children from external native interop are rejected.
138    pub fn create_deep_copy(&self) -> Result<Self> {
139        crate::clear_last_error();
140        let handle =
141            unsafe { ocio_sys::ocio_group_transform_create_deep_copy(self.handle.as_ptr()) };
142        crate::handle_result(handle).map(|handle| Self { handle })
143    }
144
145    /// Remove the child transform at `index` by rebuilding this wrapper's group.
146    ///
147    /// OCIO exposes no in-place removal API. Existing shared references,
148    /// including groups that already contain this group and previously obtained
149    /// metadata, continue to refer to the original native object.
150    pub fn remove_transform(&self, index: usize) -> Result<()> {
151        crate::clear_last_error();
152        unsafe {
153            ocio_sys::ocio_group_transform_remove_transform(self.handle.as_ptr(), index as u64)
154        };
155        crate::ocio_call_status()
156    }
157
158    /// Remove every child by rebuilding this wrapper's group. Existing shared
159    /// native references continue to point to the original group; see
160    /// [`Self::remove_transform`].
161    pub fn clear_transforms(&self) -> Result<()> {
162        crate::clear_last_error();
163        unsafe { ocio_sys::ocio_group_transform_clear_transforms(self.handle.as_ptr()) };
164        crate::ocio_call_status()
165    }
166
167    /// # Safety
168    /// `config`, `format_name`, and `os` must be valid pointers accepted by the OCIO ABI.
169    #[deprecated(
170        since = "0.2.0",
171        note = "raw OCIO ostream entry point; prefer write_to_string(&Config, format_name) for Rust callers"
172    )]
173    pub unsafe fn write(&self, config: *mut c_void, format_name: *const i8, os: *mut c_void) {
174        crate::clear_last_error();
175        unsafe {
176            ocio_sys::ocio_group_transform_write(self.handle.as_ptr(), config, format_name, os);
177        }
178        let _ = crate::ocio_call_status();
179    }
180
181    /// Serialize this group transform using OCIO's writer for `format_name`.
182    ///
183    /// Returns `None` in stub builds where no real OCIO serializer is linked.
184    pub fn write_to_string(
185        &self,
186        config: &Config,
187        format_name: impl AsRef<str>,
188    ) -> Result<Option<String>> {
189        let format_name = cstring(format_name)?;
190        crate::clear_last_error();
191        let result = unsafe {
192            cstr_from_mut(ocio_sys::ocio_group_transform_write_to_string(
193                self.handle.as_ptr(),
194                config.handle.as_ptr(),
195                format_name.as_ptr(),
196            ))
197        };
198        crate::ocio_call_status()?;
199        Ok(result)
200    }
201
202    /// Serialize using a retained read-only native config without copying it.
203    pub fn write_to_string_with_const_config(
204        &self,
205        config: &ConstConfig,
206        format_name: impl AsRef<str>,
207    ) -> Result<Option<String>> {
208        let format_name = cstring(format_name)?;
209        crate::clear_last_error();
210        let result = unsafe {
211            cstr_from_mut(ocio_sys::ocio_group_transform_write_to_string_const(
212                self.handle.as_ptr(),
213                config.handle.as_ptr(),
214                format_name.as_ptr(),
215            ))
216        };
217        crate::ocio_call_status()?;
218        Ok(result)
219    }
220
221    /// Return format metadata attached to the group, when available.
222    pub fn format_metadata(&self) -> Option<crate::FormatMetadata> {
223        let handle = unsafe { ocio_sys::ocio_transform_get_format_metadata(self.handle.as_ptr()) };
224        NonNull::new(handle).map(|h| crate::FormatMetadata { handle: h })
225    }
226
227    #[deprecated(since = "0.2.0", note = "compat alias; prefer format_metadata()")]
228    pub fn format_metadata_v1(&self) -> Option<crate::FormatMetadata> {
229        self.format_metadata()
230    }
231
232    #[deprecated(since = "0.2.0", note = "compat alias; prefer format_metadata()")]
233    pub fn format_metadata_v2(&self) -> Option<crate::FormatMetadata> {
234        self.format_metadata()
235    }
236
237    /// Return the number of serialization formats supported by `write_to_string`.
238    pub fn num_write_formats() -> i32 {
239        unsafe { ocio_sys::ocio_group_transform_get_num_write_formats() }
240    }
241
242    /// Return the writer format name at `index`, or `None` for an invalid index.
243    pub fn format_name_by_index(index: i32) -> Option<String> {
244        if index < 0 || index >= Self::num_write_formats() {
245            return None;
246        }
247        unsafe {
248            cstr_to_opt_string(ocio_sys::ocio_group_transform_get_format_name_by_index(
249                index,
250            ))
251        }
252    }
253
254    /// Return the writer format extension at `index`, without a leading dot.
255    /// Returns `None` for an invalid index.
256    pub fn format_extension_by_index(index: i32) -> Option<String> {
257        if index < 0 || index >= Self::num_write_formats() {
258            return None;
259        }
260        unsafe {
261            cstr_to_opt_string(ocio_sys::ocio_group_transform_get_format_extension_by_index(index))
262        }
263    }
264}
265
266impl Drop for GroupTransform {
267    fn drop(&mut self) {
268        unsafe { ocio_sys::ocio_group_transform_destroy(self.handle.as_ptr()) };
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275    use crate::transform::{CDLTransform, FileTransform};
276
277    #[test]
278    fn create_group() {
279        let gt = GroupTransform::create();
280        assert!(gt.is_ok());
281    }
282
283    #[test]
284    fn num_transforms() {
285        let gt = GroupTransform::create().unwrap();
286        let _ = gt.num_transforms();
287    }
288
289    #[test]
290    fn append_transform_no_crash() {
291        let gt = GroupTransform::create().unwrap();
292        let ft = FileTransform::create().unwrap();
293        gt.append_transform(&ft).unwrap();
294    }
295
296    #[test]
297    fn prepend_transform_no_crash() {
298        let gt = GroupTransform::create().unwrap();
299        let ft = FileTransform::create().unwrap();
300        gt.prepend_transform(&ft).unwrap();
301    }
302
303    #[test]
304    fn get_transform_no_crash() {
305        let gt = GroupTransform::create().unwrap();
306        let ft = FileTransform::create().unwrap();
307        gt.append_transform(&ft).unwrap();
308        let _ = gt.transform(0);
309    }
310
311    #[test]
312    fn get_transform_out_of_range() {
313        let gt = GroupTransform::create().unwrap();
314        assert!(gt.transform(0).is_none());
315    }
316
317    #[test]
318    #[allow(deprecated)]
319    fn get_transform_compat_aliases_no_crash() {
320        let gt = GroupTransform::create().unwrap();
321        let _ = gt.get_transform(0);
322        let _ = gt.get_transform_v1(0);
323    }
324
325    #[test]
326    fn append_multiple_transforms_no_crash() {
327        let gt = GroupTransform::create().unwrap();
328        let ft = FileTransform::create().unwrap();
329        let ct = CDLTransform::create().unwrap();
330        gt.append_transform(&ft).unwrap();
331        gt.append_transform(&ct).unwrap();
332    }
333
334    #[test]
335    fn append_via_enum_no_crash() {
336        let gt = GroupTransform::create().unwrap();
337        let t = Transform::File(FileTransform::create().unwrap());
338        gt.append_transform(&t).unwrap();
339    }
340
341    #[test]
342    fn create_editable_copy_no_crash() {
343        let gt = GroupTransform::create().unwrap();
344        let _ = gt.create_editable_copy();
345    }
346
347    #[test]
348    fn remove_clear_no_crash() {
349        let g = GroupTransform::create().unwrap();
350        let cdl = CDLTransform::create().unwrap();
351        g.append_transform(&cdl).unwrap();
352        g.remove_transform(0).unwrap();
353        g.clear_transforms().unwrap();
354    }
355
356    #[test]
357    fn format_metadata_no_crash() {
358        let g = GroupTransform::create().unwrap();
359        let _ = g.format_metadata();
360    }
361
362    #[test]
363    fn write_to_string_no_crash() {
364        let g = GroupTransform::create().unwrap();
365        let cdl = CDLTransform::create().unwrap();
366        g.append_transform(&cdl).unwrap();
367
368        let config = Config::raw().unwrap();
369        let written = g.write_to_string(&config, "Academy/ASC Common LUT Format");
370        assert!(written.is_ok());
371
372        if crate::is_stub_build() {
373            assert!(written.unwrap().is_none());
374        }
375    }
376
377    #[test]
378    fn static_write_format_queries_no_crash() {
379        let count = GroupTransform::num_write_formats();
380        assert!(count >= 0);
381        let _ = GroupTransform::format_name_by_index(0);
382        let _ = GroupTransform::format_extension_by_index(0);
383    }
384
385    #[test]
386    #[cfg_attr(ocio_stub, ignore = "requires a real OpenColorIO build")]
387    fn static_write_format_queries_real_behavior() {
388        if crate::is_stub_build() {
389            return;
390        }
391
392        let count = GroupTransform::num_write_formats();
393        assert!(count > 0);
394        assert!(GroupTransform::format_name_by_index(0).is_some());
395        assert!(GroupTransform::format_extension_by_index(0).is_some());
396    }
397}