Skip to main content

ocio_rs/
color_space_set.rs

1use std::ffi::c_void;
2use std::ptr::NonNull;
3
4use crate::{cstr_from_mut, cstr_to_opt_string, cstring, ColorSpace, OcioError, Result};
5use ocio_sys;
6
7/// Mutable collection of [`ColorSpace`] handles used by OCIO set-style APIs.
8pub struct ColorSpaceSet {
9    pub(crate) handle: NonNull<c_void>,
10}
11
12/// Read-only native result of a color-space set operation.
13///
14/// The result owns OCIO's original const set, with no additional editable copy.
15pub struct ConstColorSpaceSet {
16    handle: NonNull<c_void>,
17}
18
19/// A borrowed editable or read-only color-space set.
20#[derive(Clone, Copy)]
21pub enum ColorSpaceSetRef<'a> {
22    Editable(&'a ColorSpaceSet),
23    ReadOnly(&'a ConstColorSpaceSet),
24}
25
26impl<'a> From<&'a ColorSpaceSet> for ColorSpaceSetRef<'a> {
27    fn from(value: &'a ColorSpaceSet) -> Self {
28        Self::Editable(value)
29    }
30}
31impl<'a> From<&'a ConstColorSpaceSet> for ColorSpaceSetRef<'a> {
32    fn from(value: &'a ConstColorSpaceSet) -> Self {
33        Self::ReadOnly(value)
34    }
35}
36impl ColorSpaceSetRef<'_> {
37    fn raw(self) -> (*mut c_void, bool) {
38        match self {
39            Self::Editable(value) => (value.handle.as_ptr(), false),
40            Self::ReadOnly(value) => (value.handle.as_ptr(), true),
41        }
42    }
43
44    fn operation(self, other: Self, operation: i32) -> Result<ConstColorSpaceSet> {
45        let (left, left_const) = self.raw();
46        let (right, right_const) = other.raw();
47        crate::clear_last_error();
48        let handle = unsafe {
49            ocio_sys::ocio_color_space_set_operation(
50                left,
51                left_const,
52                right,
53                right_const,
54                operation,
55            )
56        };
57        crate::handle_result(handle).map(|handle| ConstColorSpaceSet { handle })
58    }
59    fn equals(self, other: Self) -> Result<bool> {
60        let (left, left_const) = self.raw();
61        let (right, right_const) = other.raw();
62        crate::clear_last_error();
63        let equal =
64            unsafe { ocio_sys::ocio_color_space_set_equal(left, left_const, right, right_const) };
65        crate::ocio_call_status()?;
66        Ok(equal)
67    }
68
69    fn const_color_space(self, name: &std::ffi::CStr) -> Result<Option<crate::ConstColorSpace>> {
70        let (handle, is_const) = self.raw();
71        crate::clear_last_error();
72        let space = unsafe {
73            ocio_sys::ocio_color_space_set_ref_get_const_color_space(
74                handle,
75                is_const,
76                name.as_ptr(),
77            )
78        };
79        crate::ocio_call_status()?;
80        Ok(NonNull::new(space).map(|handle| crate::ConstColorSpace { handle }))
81    }
82
83    fn const_color_space_by_index(self, index: i32) -> Result<Option<crate::ConstColorSpace>> {
84        let (handle, is_const) = self.raw();
85        crate::clear_last_error();
86        let space = unsafe {
87            ocio_sys::ocio_color_space_set_ref_get_const_color_space_by_index(
88                handle, is_const, index,
89            )
90        };
91        crate::ocio_call_status()?;
92        Ok(NonNull::new(space).map(|handle| crate::ConstColorSpace { handle }))
93    }
94}
95
96macro_rules! set_lookup {
97    () => {
98        /// Look up a name with OCIO's matching rules; `-1` means absent.
99        pub fn try_color_space_index(&self, name: impl AsRef<str>) -> Result<i32> {
100            let name = cstring(name)?;
101            let (handle, is_const) = ColorSpaceSetRef::from(self).raw();
102            crate::clear_last_error();
103            let index = unsafe {
104                ocio_sys::ocio_color_space_set_ref_get_color_space_index(
105                    handle,
106                    is_const,
107                    name.as_ptr(),
108                )
109            };
110            crate::ocio_call_status()?;
111            Ok(index)
112        }
113        /// Check name or alias membership, preserving native errors.
114        pub fn try_has_color_space(&self, name: impl AsRef<str>) -> Result<bool> {
115            let name = cstring(name)?;
116            let (handle, is_const) = ColorSpaceSetRef::from(self).raw();
117            crate::clear_last_error();
118            let found = unsafe {
119                ocio_sys::ocio_color_space_set_ref_has_color_space(handle, is_const, name.as_ptr())
120            };
121            crate::ocio_call_status()?;
122            Ok(found)
123        }
124    };
125}
126
127macro_rules! set_operations {
128    () => {
129        /// Compare names using OCIO's set equality semantics, not deep color-space equality.
130        pub fn try_equals<'a>(&self, other: impl Into<ColorSpaceSetRef<'a>>) -> Result<bool> {
131            ColorSpaceSetRef::from(self).equals(other.into())
132        }
133        /// Return OCIO's union as an independently owned read-only set.
134        pub fn union<'a>(
135            &self,
136            other: impl Into<ColorSpaceSetRef<'a>>,
137        ) -> Result<ConstColorSpaceSet> {
138            ColorSpaceSetRef::from(self).operation(other.into(), 0)
139        }
140        /// Return OCIO's intersection as an independently owned read-only set.
141        pub fn intersection<'a>(
142            &self,
143            other: impl Into<ColorSpaceSetRef<'a>>,
144        ) -> Result<ConstColorSpaceSet> {
145            ColorSpaceSetRef::from(self).operation(other.into(), 1)
146        }
147        /// Return OCIO's set difference as an independently owned read-only set.
148        pub fn difference<'a>(
149            &self,
150            other: impl Into<ColorSpaceSetRef<'a>>,
151        ) -> Result<ConstColorSpaceSet> {
152            ColorSpaceSetRef::from(self).operation(other.into(), 2)
153        }
154    };
155}
156
157impl ConstColorSpaceSet {
158    set_lookup!();
159    set_operations!();
160
161    /// Share a named native color space without making an editable copy.
162    /// The returned handle retains its own native reference.
163    pub fn try_const_color_space(
164        &self,
165        name: impl AsRef<str>,
166    ) -> Result<Option<crate::ConstColorSpace>> {
167        ColorSpaceSetRef::from(self).const_color_space(&cstring(name)?)
168    }
169
170    /// Share a native color space by index, or return `None` for an invalid index.
171    pub fn try_const_color_space_by_index(
172        &self,
173        index: i32,
174    ) -> Result<Option<crate::ConstColorSpace>> {
175        ColorSpaceSetRef::from(self).const_color_space_by_index(index)
176    }
177
178    /// Return the number of color spaces, preserving native errors.
179    pub fn try_num_color_spaces(&self) -> Result<i32> {
180        crate::clear_last_error();
181        let count = unsafe {
182            ocio_sys::ocio_const_color_space_set_get_num_color_spaces(self.handle.as_ptr())
183        };
184        crate::ocio_call_status()?;
185        Ok(count)
186    }
187    /// Copy the name at `index`, or return `None` for an invalid index.
188    pub fn try_color_space_name_by_index(&self, index: i32) -> Result<Option<String>> {
189        crate::clear_last_error();
190        let name = unsafe {
191            cstr_to_opt_string(
192                ocio_sys::ocio_const_color_space_set_get_color_space_name_by_index(
193                    self.handle.as_ptr(),
194                    index,
195                ),
196            )
197        };
198        crate::ocio_call_status()?;
199        Ok(name)
200    }
201    /// Copy a named color space into an independent editable object.
202    pub fn copy_color_space(&self, name: impl AsRef<str>) -> Result<Option<ColorSpace>> {
203        let name = cstring(name)?;
204        crate::clear_last_error();
205        let handle = unsafe {
206            ocio_sys::ocio_const_color_space_set_copy_color_space(
207                self.handle.as_ptr(),
208                name.as_ptr(),
209            )
210        };
211        crate::ocio_call_status()?;
212        Ok(NonNull::new(handle).map(|handle| ColorSpace { handle }))
213    }
214    /// Copy an indexed color space into an independent editable object.
215    pub fn copy_color_space_by_index(&self, index: i32) -> Result<Option<ColorSpace>> {
216        crate::clear_last_error();
217        let handle = unsafe {
218            ocio_sys::ocio_const_color_space_set_copy_color_space_by_index(
219                self.handle.as_ptr(),
220                index,
221            )
222        };
223        crate::ocio_call_status()?;
224        Ok(NonNull::new(handle).map(|handle| ColorSpace { handle }))
225    }
226    /// Create an editable copy on explicit request.
227    pub fn create_editable_copy(&self) -> Result<ColorSpaceSet> {
228        crate::clear_last_error();
229        let handle = unsafe {
230            ocio_sys::ocio_const_color_space_set_create_editable_copy(self.handle.as_ptr())
231        };
232        crate::handle_result(handle).map(|handle| ColorSpaceSet { handle })
233    }
234}
235impl Drop for ConstColorSpaceSet {
236    fn drop(&mut self) {
237        unsafe { ocio_sys::ocio_const_color_space_set_destroy(self.handle.as_ptr()) }
238    }
239}
240
241impl ColorSpaceSet {
242    /// Look up a name with OCIO's matching rules; `-1` means absent.
243    pub fn try_color_space_index(&self, name: impl AsRef<str>) -> Result<i32> {
244        let name = cstring(name)?;
245        crate::clear_last_error();
246        let index = unsafe {
247            ocio_sys::ocio_color_space_set_ref_get_color_space_index(
248                self.handle.as_ptr(),
249                false,
250                name.as_ptr(),
251            )
252        };
253        crate::ocio_call_status()?;
254        Ok(index)
255    }
256    /// Check name or alias membership, preserving native errors.
257    pub fn try_has_color_space(&self, name: impl AsRef<str>) -> Result<bool> {
258        let name = cstring(name)?;
259        crate::clear_last_error();
260        let found = unsafe {
261            ocio_sys::ocio_color_space_set_ref_has_color_space(
262                self.handle.as_ptr(),
263                false,
264                name.as_ptr(),
265            )
266        };
267        crate::ocio_call_status()?;
268        Ok(found)
269    }
270    /// Compare the sets by color-space names, as OCIO does.
271    pub fn try_equals<'a>(&self, other: impl Into<ColorSpaceSetRef<'a>>) -> Result<bool> {
272        ColorSpaceSetRef::from(self).equals(other.into())
273    }
274    /// Return OCIO's union as an independently owned read-only set.
275    pub fn union<'a>(&self, other: impl Into<ColorSpaceSetRef<'a>>) -> Result<ConstColorSpaceSet> {
276        ColorSpaceSetRef::from(self).operation(other.into(), 0)
277    }
278    /// Return OCIO's intersection as an independently owned read-only set.
279    pub fn intersection<'a>(
280        &self,
281        other: impl Into<ColorSpaceSetRef<'a>>,
282    ) -> Result<ConstColorSpaceSet> {
283        ColorSpaceSetRef::from(self).operation(other.into(), 1)
284    }
285    /// Return OCIO's difference as an independently owned read-only set.
286    pub fn difference<'a>(
287        &self,
288        other: impl Into<ColorSpaceSetRef<'a>>,
289    ) -> Result<ConstColorSpaceSet> {
290        ColorSpaceSetRef::from(self).operation(other.into(), 2)
291    }
292    /// Create an empty color-space set.
293    pub fn create() -> Result<Self> {
294        crate::clear_last_error();
295        let handle = unsafe { ocio_sys::ocio_color_space_set_create() };
296        crate::handle_result(handle).map(|handle| Self { handle })
297    }
298
299    /// Create an editable copy that is independent from the original set.
300    pub fn create_editable_copy(&self) -> Result<Self> {
301        crate::clear_last_error();
302        let handle =
303            unsafe { ocio_sys::ocio_color_space_set_create_editable_copy(self.handle.as_ptr()) };
304        crate::handle_result(handle).map(|handle| Self { handle })
305    }
306
307    /// Return the number of color spaces currently in the set.
308    pub fn num_color_spaces(&self) -> i32 {
309        unsafe { ocio_sys::ocio_color_space_set_get_num_color_spaces(self.handle.as_ptr()) }
310    }
311
312    /// Return one color-space name by index.
313    pub fn color_space_name_by_index(&self, index: i32) -> Option<String> {
314        self.try_color_space_name_by_index(index).ok().flatten()
315    }
316
317    /// Return a color-space name by index while preserving bridge failures.
318    pub fn try_color_space_name_by_index(&self, index: i32) -> Result<Option<String>> {
319        crate::clear_last_error();
320        let name = unsafe {
321            cstr_from_mut(
322                ocio_sys::ocio_color_space_set_get_color_space_name_by_index(
323                    self.handle.as_ptr(),
324                    index,
325                ),
326            )
327        };
328        crate::ocio_call_status()?;
329        Ok(name)
330    }
331
332    /// Return an independent editable copy of a color space by index.
333    pub fn color_space_by_index(&self, index: i32) -> Option<ColorSpace> {
334        self.try_color_space_by_index(index).ok().flatten()
335    }
336
337    /// Copy a color space by index while preserving bridge failures.
338    pub fn try_color_space_by_index(&self, index: i32) -> Result<Option<ColorSpace>> {
339        crate::clear_last_error();
340        let handle = unsafe {
341            ocio_sys::ocio_color_space_set_get_color_space_by_index(self.handle.as_ptr(), index)
342        };
343        crate::ocio_call_status()?;
344        Ok(NonNull::new(handle).map(|h| ColorSpace { handle: h }))
345    }
346
347    /// Look up an independent editable color-space copy by name.
348    pub fn color_space(&self, name: impl AsRef<str>) -> Option<ColorSpace> {
349        self.try_color_space(name).ok().flatten()
350    }
351
352    /// Look up a shared read-only color space without copying the native object.
353    pub fn try_const_color_space(
354        &self,
355        name: impl AsRef<str>,
356    ) -> Result<Option<crate::ConstColorSpace>> {
357        let name = cstring(name)?;
358        crate::clear_last_error();
359        let handle = unsafe {
360            ocio_sys::ocio_color_space_set_get_const_color_space(
361                self.handle.as_ptr(),
362                name.as_ptr(),
363            )
364        };
365        crate::ocio_call_status()?;
366        Ok(NonNull::new(handle).map(|handle| crate::ConstColorSpace { handle }))
367    }
368
369    /// Share a native color space by index, or return `None` for an invalid index.
370    /// The returned handle remains valid if the set is modified or dropped.
371    pub fn try_const_color_space_by_index(
372        &self,
373        index: i32,
374    ) -> Result<Option<crate::ConstColorSpace>> {
375        ColorSpaceSetRef::from(self).const_color_space_by_index(index)
376    }
377
378    /// Copy a color space by name while preserving bridge failures.
379    pub fn try_color_space(&self, name: impl AsRef<str>) -> Result<Option<ColorSpace>> {
380        let n = cstring(name)?;
381        crate::clear_last_error();
382        let handle = unsafe {
383            ocio_sys::ocio_color_space_set_get_color_space(self.handle.as_ptr(), n.as_ptr().cast())
384        };
385        crate::ocio_call_status()?;
386        Ok(NonNull::new(handle).map(|h| ColorSpace { handle: h }))
387    }
388
389    /// Return the index of a color space by name, or `-1` when missing.
390    pub fn color_space_index(&self, name: impl AsRef<str>) -> i32 {
391        let n = match cstring(name) {
392            Ok(n) => n,
393            Err(_) => return -1,
394        };
395        unsafe {
396            ocio_sys::ocio_color_space_set_get_color_space_index(
397                self.handle.as_ptr(),
398                n.as_ptr().cast(),
399            )
400        }
401    }
402
403    /// Return whether a color space named `name` is present in the set.
404    pub fn has_color_space(&self, name: impl AsRef<str>) -> bool {
405        let n = match cstring(name) {
406            Ok(n) => n,
407            Err(_) => return false,
408        };
409        unsafe {
410            ocio_sys::ocio_color_space_set_has_color_space(self.handle.as_ptr(), n.as_ptr().cast())
411        }
412    }
413
414    /// Insert one color space into the set.
415    pub fn add_color_space(&self, color_space: &ColorSpace) {
416        self.try_add_color_space(color_space)
417            .expect("failed to add color space to set");
418    }
419
420    /// Insert one color space into the set and surface any OCIO validation error.
421    pub fn try_add_color_space(&self, color_space: &ColorSpace) -> Result<()> {
422        crate::clear_last_error();
423        unsafe {
424            ocio_sys::ocio_color_space_set_add_color_space(
425                self.handle.as_ptr(),
426                color_space.handle.as_ptr(),
427            );
428        }
429        crate::ocio_call_status()
430    }
431
432    /// Add an editable or read-only color space. OCIO stores an independent copy.
433    pub fn try_add_color_space_ref<'a>(
434        &self,
435        color_space: impl Into<crate::ColorSpaceRef<'a>>,
436    ) -> Result<()> {
437        let (space, is_const) = color_space.into().raw();
438        crate::clear_last_error();
439        unsafe {
440            ocio_sys::ocio_color_space_set_add_color_space_ref(
441                self.handle.as_ptr(),
442                space,
443                is_const,
444            )
445        };
446        crate::ocio_call_status()
447    }
448
449    /// Insert every color space from `other` into the set.
450    pub fn add_color_spaces(&self, other: &ColorSpaceSet) {
451        self.try_add_color_spaces(other)
452            .expect("failed to add color spaces to set");
453    }
454
455    /// Insert every color space from `other` and surface any OCIO validation error.
456    pub fn try_add_color_spaces(&self, other: &ColorSpaceSet) -> Result<()> {
457        crate::clear_last_error();
458        unsafe {
459            ocio_sys::ocio_color_space_set_add_color_spaces(
460                self.handle.as_ptr(),
461                other.handle.as_ptr(),
462            );
463        }
464        crate::ocio_call_status()
465    }
466
467    /// Add copies of the color spaces in an editable or read-only set.
468    /// As in OCIO, a conflict can leave preceding entries already added.
469    pub fn try_add_color_spaces_ref<'a>(
470        &self,
471        other: impl Into<ColorSpaceSetRef<'a>>,
472    ) -> Result<()> {
473        let (set, is_const) = other.into().raw();
474        crate::clear_last_error();
475        unsafe {
476            ocio_sys::ocio_color_space_set_add_color_spaces_ref(self.handle.as_ptr(), set, is_const)
477        };
478        crate::ocio_call_status()
479    }
480
481    /// Remove one color space by canonical name, case-insensitively.
482    ///
483    /// Unlike lookup and membership queries, OCIO does not resolve aliases
484    /// when removing; an alias or other missing name leaves the set unchanged.
485    pub fn remove_color_space(&self, name: impl AsRef<str>) -> Result<()> {
486        let n = cstring(name)?;
487        crate::clear_last_error();
488        unsafe {
489            ocio_sys::ocio_color_space_set_remove_color_space(
490                self.handle.as_ptr(),
491                n.as_ptr().cast(),
492            )
493        };
494        crate::ocio_call_status()
495    }
496
497    /// Remove every color space found in `other` from this set.
498    pub fn remove_color_spaces(&self, other: &ColorSpaceSet) {
499        self.try_remove_color_spaces(other)
500            .expect("failed to remove color spaces from set");
501    }
502
503    /// Remove every color space found in `other` and surface any OCIO validation error.
504    pub fn try_remove_color_spaces(&self, other: &ColorSpaceSet) -> Result<()> {
505        crate::clear_last_error();
506        unsafe {
507            ocio_sys::ocio_color_space_set_remove_color_spaces(
508                self.handle.as_ptr(),
509                other.handle.as_ptr(),
510            );
511        }
512        crate::ocio_call_status()
513    }
514
515    /// Remove entries named by an editable or read-only set.
516    /// Removing this set from itself clears it safely.
517    pub fn try_remove_color_spaces_ref<'a>(
518        &self,
519        other: impl Into<ColorSpaceSetRef<'a>>,
520    ) -> Result<()> {
521        let (set, is_const) = other.into().raw();
522        crate::clear_last_error();
523        unsafe {
524            ocio_sys::ocio_color_space_set_remove_color_spaces_ref(
525                self.handle.as_ptr(),
526                set,
527                is_const,
528            )
529        };
530        crate::ocio_call_status()
531    }
532
533    /// Remove every color space from the set.
534    pub fn clear_color_spaces(&self) {
535        self.try_clear_color_spaces()
536            .expect("failed to clear color spaces from set");
537    }
538
539    /// Remove every color space and surface any OCIO validation error.
540    pub fn try_clear_color_spaces(&self) -> Result<()> {
541        crate::clear_last_error();
542        unsafe { ocio_sys::ocio_color_space_set_clear_color_spaces(self.handle.as_ptr()) };
543        crate::ocio_call_status()
544    }
545}
546
547impl Drop for ColorSpaceSet {
548    fn drop(&mut self) {
549        unsafe { ocio_sys::ocio_color_space_set_destroy(self.handle.as_ptr()) };
550    }
551}
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556
557    #[test]
558    fn create_color_space_set() {
559        let set = ColorSpaceSet::create();
560        assert!(set.is_ok());
561    }
562
563    #[test]
564    fn color_space_set_methods_no_crash() {
565        let set = ColorSpaceSet::create().unwrap();
566        let _ = set.num_color_spaces();
567        let _ = set.color_space_name_by_index(0);
568        let _ = set.color_space_by_index(0);
569        let _ = set.color_space("raw");
570        let _ = set.color_space_index("raw");
571        let _ = set.has_color_space("raw");
572    }
573
574    #[test]
575    fn get_color_space_by_name_no_crash() {
576        let set = ColorSpaceSet::create().unwrap();
577        let cs = set.color_space("raw");
578        if let Some(cs) = cs {
579            let _ = cs.name();
580        }
581    }
582
583    #[test]
584    fn get_color_space_by_index_no_crash() {
585        let set = ColorSpaceSet::create().unwrap();
586        let cs = set.color_space_by_index(0);
587        if let Some(cs) = cs {
588            let _ = cs.name();
589        }
590    }
591
592    #[test]
593    fn create_editable_copy_no_crash() {
594        let set = ColorSpaceSet::create().unwrap();
595        let _ = set.create_editable_copy();
596    }
597
598    #[test]
599    fn color_space_index_negative_on_missing() {
600        let set = ColorSpaceSet::create().unwrap();
601        let idx = set.color_space_index("nonexistent_color_space_xyz");
602        // In non-stub mode this returns -1 for missing
603        // In stub mode it also returns -1
604        assert_eq!(idx, -1);
605    }
606
607    #[test]
608    fn mutate_color_space_set_no_crash() {
609        let set = ColorSpaceSet::create().unwrap();
610        let other = ColorSpaceSet::create().unwrap();
611        let cs = ColorSpace::create().unwrap();
612        cs.set_name("UnitColorSpace").unwrap();
613        set.add_color_space(&cs);
614        set.add_color_spaces(&other);
615        let _ = set.remove_color_space("raw");
616        set.try_remove_color_spaces(&other).unwrap();
617        set.try_clear_color_spaces().unwrap();
618    }
619}